exec behaviour; Functions as instance members.

Mikael Olofsson mikael at isy.liu.se
Mon Oct 18 08:12:03 EDT 1999


On 18-Oct-99 Michel NIZETTE wrote:
 >  1) Inside a function definition why doesn't
 >  
 >  exec "global i"
 >  exec "i = 1"
 >  
 >  set the global variable i to 1, although
 >  
 >  exec "global i\ni = 1"
 >  
 >  does ?

These things bugged me once, too.

>From Python Reference Manual, 6.12 The global statement

  Programmer's note: the global is a directive to the parser. It 
  applies only to code parsed at the same time as the global 
  statement. In particular, a global statement contained in an 
  exec statement does not affect the code block containing the 
  exec statement, and code contained in an exec statement is 
  unaffected by global statements in the code containing the exec 
  statement. 

In both your examples the global statement will not affect the 
code block containing your exec command(s). 

In the first example the two exec commands will be parsed
separately, and the first exec command will be useless as 
noted in the quotation above. The second command will set 
the local variable i.

In your second example the global declaration and the assignment
will be parsed together, and you will set the global variable i.
However, as I understand things, if you do 

  exec "global i\ni = 1"
  i = 2

you will have one global variable i with the value 1, and one 
local variable with the value 2.

 >  2) To define a function as a member of a class instance, is there a
 >  shorter way than introducing a temporary function name as in the
 >  following ?
 >  
 >  def Temp():
 >      # Code...
 >  ClassInst.Func = Temp
 >  del Temp

This one I will have to leave to the wizards.

/Mikael

-----------------------------------------------------------------------
E-Mail:  Mikael Olofsson <mikael at isy.liu.se>
WWW:     http://www.dtr.isy.liu.se/dtr/staff/mikael
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
Date:    18-Oct-99
Time:    13:54:58

This message was sent by XF-Mail.
-----------------------------------------------------------------------




More information about the Python-list mailing list