[Python-Dev] arguments policy: **kwargs.pop()
Tres Seaver
tseaver at palladion.com
Fri Apr 11 05:48:44 CEST 2014
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On 04/10/2014 10:12 PM, Christian Tismer wrote:
> I always used the policy that arguments are never changed by a
> function, unless explicitly stated. But since I see this pattern quite
> frequently, I wanted to ask if I am right by thinking this way, or if
> the general policy is more like "arguments may be destroyed by
> default".
>
> What do you think? Is this bad style and should be noticed somewhere,
> or is the caller supposed to protect the arguments, or are my worries
> useless?
The caller can't know or care that the function / method pops arguments::
$ python
Python 2.7.3 (default, Feb 27 2014, 19:58:35)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo(**kw):
... bar = kw.pop('bar', 'BAR')
... print 'bar: %s' % bar
... print 'kw: %s' % kw
...
>>> foo()
bar: BAR
kw: {}
>>> foo(bar='baz')
bar: baz
kw: {}
>>> foo(bar='baz', bam='qux')
bar: baz
kw: {'bam': 'qux'}
>>> mykw = {'bar': 'baz', 'bam': 'qux'}
>>> foo(**mykw)
bar: baz
kw: {'bam': 'qux'}
>>> mykw
{'bam': 'qux', 'bar': 'baz'}
because the caller gets its own copy of 'kw', even when called with an
existing dict.
Tres.
- --
===================================================================
Tres Seaver +1 540-429-0999 tseaver at palladion.com
Palladion Software "Excellence by Design" http://palladion.com
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/
iEYEARECAAYFAlNHZhwACgkQ+gerLs4ltQ5RLQCeMaFvMDNexmCw9ggbg34w+AjP
DKMAn1U1WRGW9PV8R/xqJs1HPWUBVEse
=A8nP
-----END PGP SIGNATURE-----
More information about the Python-Dev
mailing list