Python Tips, Tricks, and Hacks
Revision 9 vs. Revision 10
Changelog:
Added resetDefaults decorator.
Legend:
- Unmodified
- Added
- Removed
-
Content
r9 r10 597 597 598 598 ``None`` is immutable (and we're not trying to change it anyways), so we're safe from accidently changing value of the default. 599 599 600 600 On the plus side, a clever programmer could probably turn this into a trick, in effect creating C-style 'static variables'. 601 601 602 If 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 616 Simply 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 602 624 603 625 Arbitrary Numbers of Arguments 604 626 ------------------------------ 605 627 Python 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: 606 628 … … 918 940 A bit outdated (assumes you're used to Python 2.2 or so), but full of more Python tricks and tips. 919 941 920 942 `Dr. Dobb's: Python Decorators <http://www.ddj.com/web-development/184406073>`_ 921 943 Need ideas or examples on using decorator functions? This is a good article. 922 944 945 `Python Cookbook <http://oreilly.com/catalog/9780596007973/>`_ 946 Source of the ``resetDefaults`` decorator and many other useful Python tips. 947 923 948 `Python Docs: Function Definitions <http://docs.python.org/ref/function.html>`_ 924 949 A good briefing on function syntax and the workings of function decorators. 925 950 926 951 `Wikipedia: "?:" <http://en.wikipedia.org/wiki/%3F:>`_ 927 952 Different ternary operators for different languages. Where I found out about Python's new ternary operator.