Call variable as a function

  • Thread starter Chmouel Boudjnah
  • Start date
C

Chmouel Boudjnah

Hey,

It's look simple for most of the people here but i can't figure out to that.

If i have :

def test():
print "foo"

and:

var = "test"

how do i call function test from var, kind of ${$var} in some others
languages (or eval())

Cheers, Chmouel.
 
S

Steve Holden

Chmouel said:
Hey,

It's look simple for most of the people here but i can't figure out to
that.

If i have :

def test():
print "foo"

and:

var = "test"

how do i call function test from var, kind of ${$var} in some others
languages (or eval())
There's always a way:
.... print "hello"
....hello

But it depends how you are creating the reference to the function. The
above is required if all you have is a string, but it would also be
possible to set the variable to the function rather than the function's
name:

Hope this helps.

regards
Steve
 
S

Steve Holden

Chmouel said:
Thanks man it does help.
Then it might help even more to realize that you can use lists and
dictionaries of functions as well:
.... return x*2
........ return "This is an %s" % x
........ return "%s:%s" % (x, x)
....
>>> fl = [f1, f2, f3]
>>> for s in ("bigstring", "tiny"):
.... for i in range(len(fl)):
.... print fl(s)
....
bigstringbigstring
This is an bigstring
bigstring:bigstring
tinytiny
This is an tiny
tiny:tiny
regards
Steve
 
N

Nick Coghlan

Steve said:
There's always a way:

... print "hello"
...
hello

I'd go with locals() for the simple case of a name lookup:

Py> def test():
.... print "Hi there!"
....
Py> var = "test"
Py> locals()[var]()
Hi there!

Cheers,
Nick.
 

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top