Lexical scope: converting Perl to Python

Mike Kazantsev mk.fraggod at gmail.com
Sat Jun 13 01:44:31 EDT 2009

On Fri, 12 Jun 2009 22:02:53 -0700 (PDT)
Andrew Savige <ajsavige at yahoo.com.au> wrote:

> I'd like to convert the following Perl code to Python:
>  use strict;
>  {
>    my %private_hash = ( A=>42, B=>69 );
>    sub public_fn {
>      my $param = shift;
>      return $private_hash{$param};
>    }
>  }
>  print public_fn("A");        # good:  prints 42
>  my $x = $private_hash{"A"};  # error: good, hash not in scope
> What is the Pythonic equivalent of Perl's lexical scope, as
> illustrated by the code snippet above?

If you're using scope for garbage-collecting purposes, there's "with"
statement and contextlib:

  from contextlib import contextmanager

  def get_hash():
    complex_hash = dict(A=42, B-69)
    try: yield complex_hash
    except Exception as ex:
      del complex_hash # complex destructor ;)
      raise ex

  with get_hash() as hash:
    # do stuff with hash

Note that this only makes sense if you need to implement some complex
operation on hash destruction, and do that whatever-happens-inside-with
to close the object, obviously not the case with simple dict above.

And if you want to obfuscate one part of your code from another, you'll
probably have better luck with languages like java, since no one seem
to care about such stuff with python, so it'd be a hack against the
language, at best.
Why would you want to hide the code from itself, anyway? It's not like
you'd be able to accomplish it - code can easily grep it's process body
in memory and harvest all the "private" values, so I'd suggest getting
some fresh air when you start to feel like doing that.

Mike Kazantsev // fraggod.net
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 205 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20090613/2ea216fc/attachment-0001.sig>

More information about the Python-list mailing list