def <dynamic function name> () syntax ?
Steve Holden
sholden at holdenweb.com
Wed Apr 4 13:14:04 EDT 2001
"Bruce Edge" <bedge at troikanetworks.com> wrote in message
news:20010404.095211.716334471.21458 at mead.troikanetworks.com...
> Can the follwoing be accomplished in Python?
>
> I want to create a func named "abc":
>
> >>> name="abc"
>
> >>> eval ("name")
> 'abc'
>
> >>> def eval ("name") ():
> File "<stdin>", line 1
> def eval ("name") ():
> ^
> SyntaxError: invalid syntax
>
It can, but not the way you are trying to do it. You should build a complete
string containing the whole function definition, and then use the exec
statement to execute the definition.
For example:
>>> name = "abc"
>>> func = """def %s(p):
... print "p is", p
... """
>>> exec func % (name, ) # using string substitution
>>> abc("have a banana")
p is have a banana
>>>
Hopet his helps.
regards
Steve
More information about the Python-list
mailing list