How to get all named args in a dict?

John Machin sjmachin at lexicon.net
Thu May 14 19:48:08 EDT 2009


On May 15, 6:24 am, Jason Tackaberry <t... at urandom.ca> wrote:
> On Thu, 2009-05-14 at 20:15 +0000, kj wrote:
> > That problem is easily solved: just make "x = locals()" the first
> > statement in the definition of foo.
>
> That doesn't solve the problem.  You'd need locals().copy()

Dave's solution doesn't formally solve the problem because x is the
first arg of foo and re-binding x to locals() is not a good idea if
you need to use the passed-in args before calling bar().

Adding .copy() is necessary only if for some weird reason you want to
call locals() *again* before calling bar().

| >>> def foo(x=None, y=None, z=None):
| ...     d = locals()
| ...     print d
| ...     p = 100
| ...     print d
| ...     print locals()
| ...     print d
| ...
| >>> foo(1,2,3)
| {'y': 2, 'x': 1, 'z': 3}
| {'y': 2, 'x': 1, 'z': 3}
| {'y': 2, 'x': 1, 'z': 3, 'd': {...}, 'p': 100}
| {'y': 2, 'x': 1, 'z': 3, 'd': {...}, 'p': 100}
| >>>

Bonus: not only a side-effect, but a recursive one.

Like the manual says, _*UPDATE*_ and return a dictionary ...

HTH,
John



More information about the Python-list mailing list