eval() and global variables

  • Thread starter Juan Pablo Romero Méndez
  • Start date
J

Juan Pablo Romero Méndez

Hello,

Suppose this function is given:

def f(x,y):
return x+y+k


Is it possible to somehow assign a value to k without resorting to
making k global?

I'm thinking something like this:

eval("f(1,1)", {"f":f, "k":1})

Or even better, something like:

def g(k):
return f

g(1)(1,1) ==> 3


Regards,

Juan Pablo
 
P

Peter Otten

Juan said:
Suppose this function is given:

def f(x,y):
return x+y+k


Is it possible to somehow assign a value to k without resorting to
making k global?

You can replace the function's global dictionary:
.... return x+y+k
....Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'k' is not defined

This is a hack, of course.

Peter
 
J

Juan Pablo Romero Méndez

The hack given by Peter works fine, except in this case:
.... f2 = lambda x,y:(x,y,fn(x,y))
.... function = type(f2)
.... f3 = function(f2.func_code,dict())
.... print f3
....Traceback (most recent call last):
File "<stdin>", line 1, in <module>


Strange...
 
P

Peter Otten

Juan said:
The hack given by Peter works fine, except in this case:

... f2 = lambda x,y:(x,y,fn(x,y))
... function = type(f2)
... f3 = function(f2.func_code,dict())
... print f3
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>



Strange...

The variable fn must be passed to the lambda somehow. You could return f2()
from aaaa(), and f2() would still have to "know" about it. This is called
a "closure".
function(code, globals[, name[, argdefs[, closure]]])

Create a function object from a code object and a dictionary.
The optional name string overrides the name from the code object.
The optional argdefs tuple specifies the default argument values.
The optional closure tuple supplies the bindings for free variables.

In your case we can reuse the closure just like the code:
.... def inner(x, y): return x + fn(x, y)
.... return function(inner.func_code, {}, closure=inner.func_closure)
....8

While we're at it, let's explore the remaining arguments:
210

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,085
Messages
2,570,597
Members
47,218
Latest member
GracieDebo

Latest Threads

Top