I want your awesome python snippets.

I’m building (and will eventually post someplace) a collection of the cooler Python snippets I dredge up. I’m looking for snippets which are:

  • Short
  • New-to-Python accessible
  • Showcase the best ideas of python – clean, simple, powerful.

The goal is to build up a small pile of code snippets that programming newbies, or programmers from other languages can look at and go “wow, I got to get me some of that”.

Anything is game; feel free to post them in the comments, on pastebin (obviously post the link), etc.

  • Jon
    This will be ridiculous to most people, but I've been programming professionally in Python for a year and a half and only figured this out today...

    instead of (when overriding a method to add kwargs...)

    def foo(self, **kwargs):
    if "foobar" in kwargs:
    self.foobar = kwargs["foobar"]
    del(kwargs["foobar"])
    else:
    self.foobar = None
    super(Foo, self).foo(**kwargs)

    do

    def foo(self, **kwargs):
    self.foobar = kwargs.pop("foobar", None)
    super(Foo, self).foo(**kwargs)
  • Joso S. O. Bueno
    # a bit washed out, but should fulfill the "acessible" part while retaining some wonder
    # with the zip and enumerate calls.

    # (I have some oneliner obfuscated versions of this, but I don't think those are the goal :-) )

    def romans_to_numerals(roman_str):
    __ roman_digits = "IVXLCDM"
    __ numeric_values = (1, 5, 10, 50, 100, 500, 1000)
    __ values = dict(zip(roman_digits, numeric_values))
    __ final_value = 0
    __ for i, digit in enumerate(roman_str):
    ____ final_value += values[digit]
    ____ if i > 0 and roman_digits.index(roman_str[i - 1]) < roman_digits.index(digit):
    ______ final_value -= 2 * values[roman_str[i - 1]]
    __ return final_value
  • Neat python tricks - http://bit.ly/79CND9 on reddit and on Stackoverflow - http://bit.ly/6qmAum
  • Roger Pate
    While there's some controversy around Community Wiki questions on Stack Overflow (I notice you have an account), this seems to be exactly appropriate. One suggestion: state a time limit in the question after which you'll close it, otherwise it will accumulate duplicates and other cruft.
  • Roger Pate
    __all__ = []
    def export(obj):
    __all__.append(obj.__name__)
    return obj

    @export
    class Example: pass

    @export
    def example(): pass
  • pkarl
  • chin
    Recursive generation of binary digits

    def iinc(n):
    if n <= 0: return [0]
    res = iinc(n-1)
    stack = res[:]
    while stack:
    k = stack.pop()
    if k: res[len(stack)] = 0
    else: res[len(stack)] = 1; return res
    return [1] + res
  • Take a look at my blog (pysnippet.com). I have some posts about file-like objects, unit-testing, and language features such as the with-statement and for/while/try-else.
  • Sean
    From the command line on any system that can run Python and has the standard library, you can use python to create a web server to serve up the files on port 8000 with the current directory as www-root.

    python -m SimpleHTTPServer
  • seedifferently
    Rosetta code might have some interesting snippets: http://rosettacode.org/
  • Gokhan
  • # Flash Policy Server in 25 lines
    # http://code.google.com/p/flashpolicytwistd

    from __future__ import with_statement

    from twisted.application import internet, service
    from twisted.internet import protocol, reactor
    from twisted.protocols import basic
    from twisted.python import log

    class FlashPolicyProtocol(basic.LineReceiver):
    delimiter = '\0'
    MAX_LENGTH = 64

    def lineReceived(self, request):
    if request != '<policy-file-request/>':
    self.transport.loseConnection()
    return
    self.transport.write(self.factory.response_body)

    class FlashPolicyFactory(protocol.ServerFactory):
    protocol = FlashPolicyProtocol

    def __init__(self):
    with open('/etc/flashpolicy.xml', 'rb') as f:
    self.response_body = f.read() + '\0'

    application = service.Application('flashpolicy')
    internet.TCPServer(843, FlashPolicyFactory()).setServiceParent(service.IServiceCollection(application))
  • zellyn
    Perhaps too long, Norvig's sudoku solver is beautiful: http://norvig.com/sudoku.html
blog comments powered by Disqus