Lexical scope: converting Perl to Python
Stephen Hansen
apt.shansen at gmail.com
Sat Jun 13 01:35:57 EDT 2009
>
> private_hash = dict( A=42, B=69 )
> def public_fn(param):
> return private_hash[param]
> print public_fn("A") # good: prints 42
> x = private_hash["A"] # works: oops, hash is in scope
>
> I'm not happy with that because I'd like to limit the scope of the
> private_hash variable so that it is known only inside public_fn.
>
A common idiom to do that would be this:
def public_fn(param, __private_hash=dict(A=42, B=69)):
return __private_hash[param]
People often squint when they see that but it is useful in several ways.
Python initializes the default arguments -once-, at definition. If they are
mutable-- a dictionary, list or such-- that same dict is used everytime the
function is called.
HTH,
--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090612/2986bac0/attachment-0001.html>
More information about the Python-list
mailing list