Lexical scope: converting Perl to Python

Terry Reedy tjreedy at udel.edu
Sat Jun 13 07:43:29 CEST 2009


Andrew Savige 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
> 
> The real code is more complex; the above is a simplified example.
> 
> Notice that this code uses Perl's lexical scope to hide the
> %private_hash variable, but not the public_fn() function.
> 
> While I could convert this code to the following Python code:
> 
>  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

Why would you do that if you do not want to do that?

> 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.

def public_fn():
   private_hash = dict( A=42, B=69 )
   def public_fn(param):
     return private_hash[param]
   return public_fn
public_fn = public_fn()
print (public_fn("A"))
x = private_hash["A"]

# outputs
42
Traceback (most recent call last):
   File "C:\Programs\Python31\misc\t1", line 8, in <module>
     x = private_hash["A"]
NameError: name 'private_hash' is not defined

Terry Jan Reedy




More information about the Python-list mailing list