Lexical scope: converting Perl to Python

jenifer adam jenigirly at gmail.com
Sat Jun 13 04:42:38 EDT 2009


On Jun 13, 10:44 am, Mike Kazantsev <mk.frag... at gmail.com> wrote:
> On Fri, 12 Jun 2009 22:02:53 -0700 (PDT)
>
>
>
>
>
> Andrew Savige <ajsav... 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
>
>   @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
>
>  signature.asc
> < 1KViewDownload

Check http://www.voipsipsdk.com its a good one.



More information about the Python-list mailing list