Hide
Writing an article is easy - try our reStructured Text demo Join Siafoo Now or Learn More

Python Tips, Tricks, and Hacks

Revision 9 vs. Revision 10

Changelog: Added resetDefaults decorator.

Legend:

Unmodified
Added
Removed
  • Content

    r9 r10  
    597597  
    598598``None`` is immutable (and we're not trying to change it anyways), so we're safe from accidently changing value of the default.  
    599599  
    600600On the plus side, a clever programmer could probably turn this into a trick, in effect creating C-style 'static variables'.  
    601601  
     602If you prefer less cluttered functions at the cost of some clarity, a decorator can be used.  The decorator that follows stores the original values of the default arguments can be used to wrap a function and reset the default arguments before each call.  
     603  
     604.. code:: Python  
     605  
     606 from copy import deepcopy  
     607  
     608 def resetDefaults(f):  
     609     defaults = f.func_defaults  
     610     def resetter(*args, **kwds):  
     611         f.func_defaults = deepcopy(defaults)  
     612         return f(*args, **kwds)  
     613     resetter.__name__ = f.__name__  
     614     return resetter  
     615  
     616Simply prefix a function using decorator syntax to get the expected results.  
     617  
     618.. code:: Python  
     619  
     620    @resetDefaults  
     621    def function(item, stuff = []):  
     622        stuff.append(item)  
     623        print stuff  
    602624  
    603625Arbitrary Numbers of Arguments  
    604626------------------------------  
    605627Python lets you have arbitrary numbers of arguments in your functions.  First define any required arguments (if any), then use a variable with a '*' prepended to it.  Python will take the rest of the non-keyword arguments, put them in a list or tuple, and assign them to this variable:  
    606628  
     
    918940    A bit outdated (assumes you're used to Python 2.2 or so), but full of more Python tricks and tips.  
    919941  
    920942`Dr. Dobb's: Python Decorators <http://www.ddj.com/web-development/184406073>`_  
    921943    Need ideas or examples on using decorator functions?  This is a good article.  
    922944  
     945`Python Cookbook <http://oreilly.com/catalog/9780596007973/>`_  
     946    Source of the ``resetDefaults`` decorator and many other useful Python tips.  
     947  
    923948`Python Docs: Function Definitions <http://docs.python.org/ref/function.html>`_  
    924949    A good briefing on function syntax and the workings of function decorators.  
    925950  
    926951`Wikipedia: "?:" <http://en.wikipedia.org/wiki/%3F:>`_  
    927952    Different ternary operators for different languages.  Where I found out about Python's new ternary operator.