I want your awesome python snippets.

December 19th, 2009 § 16 comments

I’m build­ing (and will even­tu­ally post some­place) a col­lec­tion of the cooler Python snip­pets I dredge up. I’m look­ing for snip­pets which are:

  • Short
  • New-to-Python accessible
  • Show­case the best ideas of python — clean, sim­ple, powerful.

The goal is to build up a small pile of code snip­pets that pro­gram­ming new­bies, or pro­gram­mers from other lan­guages can look at and go “wow, I got to get me some of that”.

Any­thing is game; feel free to post them in the com­ments, on paste­bin (obvi­ously post the link), etc.

  • zel­lyn

    Per­haps too long, Norvig’s sudoku solver is beau­ti­ful: http://norvig.com/sudoku.html

  • http://kpoxit.blogspot.com/ Anton

    # Flash Pol­icy Server in 25 lines
    # http://code.google.com/p/flashpolicytwistd

    from __future__ import with_statement

    from twisted.application import inter­net, ser­vice
    from twisted.internet import pro­to­col, reac­tor
    from twisted.protocols import basic
    from twisted.python import log

    class FlashPolicyProtocol(basic.LineReceiver):
    delim­iter = ‘’
    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):
    pro­to­col = FlashPolicyProtocol

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

    appli­ca­tion = service.Application(‘flashpolicy’)
    internet.TCPServer(843, FlashPolicyFactory()).setServiceParent(service.IServiceCollection(application))

  • Gokhan
  • seed­if­fer­ently

    Rosetta code might have some inter­est­ing snip­pets: http://rosettacode.org/

  • http://www.goldb.org/ Corey
  • Sean

    From the com­mand line on any sys­tem that can run Python and has the stan­dard library, you can use python to cre­ate a web server to serve up the files on port 8000 with the cur­rent direc­tory as www-root.

    python –m SimpleHTTPServer

  • http://pysnippet.com/ Mario

    Take a look at my blog (pysnippet.com). I have some posts about file-like objects, unit-testing, and lan­guage fea­tures such as the with-statement and for/while/try-else.

  • http://kennethreitz.com Ken­neth Reitz
  • chin

    Recur­sive gen­er­a­tion 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

  • pkarl
  • Roger Pate

    __all__ = []
    def export(obj):
    __all__.append(obj.__name__)
    return obj

    @export
    class Exam­ple: pass

    @export
    def exam­ple(): pass

  • Roger Pate

    While there’s some con­tro­versy around Com­mu­nity Wiki ques­tions on Stack Over­flow (I notice you have an account), this seems to be exactly appro­pri­ate. One sug­ges­tion: state a time limit in the ques­tion after which you’ll close it, oth­er­wise it will accu­mu­late dupli­cates and other cruft.

  • http://www.sidmitra.com/ Sid­dharth Mitra

    Neat python tricks — http://bit.ly/79CND9 on red­dit and on Stack­over­flow — http://bit.ly/6qmAum

  • Joso S. O. Bueno

    # a bit washed out, but should ful­fill the “aces­si­ble” part while retain­ing some won­der
    # with the zip and enu­mer­ate calls.

    # (I have some one­liner obfus­cated ver­sions 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)
    __ val­ues = 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

  • Jon

    This will be ridicu­lous to most peo­ple, but I’ve been pro­gram­ming pro­fes­sion­ally in Python for a year and a half and only fig­ured this out today…

    instead of (when over­rid­ing a method to add kwargs…)

    def foo(self, **kwargs):
    if “foo­bar” 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)

  • Jon

    This will be ridicu­lous to most peo­ple, but I’ve been pro­gram­ming pro­fes­sion­ally in Python for a year and a half and only fig­ured this out today…

    instead of (when over­rid­ing a method to add kwargs…)

    def foo(self, **kwargs):
    if “foo­bar” 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)

What's this?

You are currently reading I want your awesome python snippets. at jessenoller.com.

meta