473,746 Members | 2,513 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dynamic construction of variables / function names

python provides a great way of dynamically creating fuctions calls and
class names from string

a function/class name can be stored as string and called/initilzed

e.g

def foo(a,b):
return a+b

def blah(c,d):
return c*d
list = ["foo", "blah"]

for func in list:
print func(2,4)

or similar items
what is the way if the names of functions are some modification e.g

def Newfoo(a,b):
return a+b

def Newblah(c,d):
return c*d

list = ["foo", "blah"]

for func in list:
print "New"+func( 2,4)

or define a variable

"New"+list[0] = "First Funciton"
I think , print "New"+func( 2,4) and "New"+list[0] = "First
Funciton"

will not work, either eval or exec should be used
is it correct way, is there a simple way, is this techniqe has a name?

thanks

Mar 30 '06 #1
5 2945
On 29 Mar 2006 22:44:24 -0800, Sakcee <sa****@gmail.c om> wrote:
python provides a great way of dynamically creating fuctions calls and
class names from string

a function/class name can be stored as string and called/initilzed

e.g

def foo(a,b):
return a+b

def blah(c,d):
return c*d
list = ["foo", "blah"]

for func in list:
print func(2,4)

or similar items
what is the way if the names of functions are some modification e.g

def Newfoo(a,b):
return a+b

def Newblah(c,d):
return c*d

list = ["foo", "blah"]

for func in list:
print "New"+func( 2,4)

or define a variable

"New"+list[0] = "First Funciton"
I think , print "New"+func( 2,4) and "New"+list[0] = "First
Funciton"

will not work, either eval or exec should be used
is it correct way, is there a simple way, is this techniqe has a name?

thanks


You could get the function object from globals(), for example:

for func in list:
f = globals().get(" New"+func, None)
if f and callable(f):
print f(2, 4)

--
I like python!
My Blog: http://www.donews.net/limodou
My Site: http://www.djangocn.org
NewEdit Maillist: http://groups.google.com/group/NewEdit
Mar 30 '06 #2
Em Qua, 2006-03-29 √*s 22:44 -0800, Sakcee escreveu:
either eval or exec should be used
is it correct way, is there a simple way, is this techniqe has a name?


eval and exec are insecure. Try looking at globals():

$ python2.4
Python 2.4.3c1 (#2, Mar 29 2006, 08:34:35)
[GCC 4.0.3 (Debian 4.0.3-1)] on linux2
Type "help", "copyright" , "credits" or "license" for more information.
def Newfoo(a, b): .... return a+b
.... def Newblah(c, d): .... return c*d
.... list = ["foo", "blah"]
for func in list: .... print globals()["New"+func](2, 4)
....
6
8 # That was a bit confusing, let see in parts .... print globals()
{'Newblah': <function Newblah at 0xb7d3df44>,
'__builtins__': <module '__builtin__' (built-in)>,
'Newfoo': <function Newfoo at 0xb7d3df0c>,
'list': ['foo', 'blah'],
'func': 'blah',
'__name__': '__main__',
'__doc__': None} print globals()["New"+func] <function Newblah at 0xb7d3df44> print globals()["New"+func](2, 4) 8 # HTH,

....

--
Felipe.

Mar 30 '06 #3
Sakcee wrote:
python provides a great way of dynamically creating fuctions calls and
class names from string

a function/class name can be stored as string and called/initilzed

e.g

def foo(a,b):
return a+b

def blah(c,d):
return c*d
list = ["foo", "blah"]

for func in list:
print func(2,4)

or similar items
No, that doesn't work. To convert a string to a function name you have to
look it up in a suitable namespace, or store a list of functions instead of
a list of strings. So something like this would work:

lst = [foo, blah]

for func in lst:
print func(2,4)



what is the way if the names of functions are some modification e.g

def Newfoo(a,b):
return a+b

def Newblah(c,d):
return c*d

list = ["foo", "blah"]

for func in list:
print "New"+func( 2,4)

or define a variable

"New"+list[0] = "First Funciton"
I think , print "New"+func( 2,4) and "New"+list[0] = "First
Funciton"

will not work, either eval or exec should be used
is it correct way, is there a simple way, is this techniqe has a name?

One common way is to group the functions you want callable together in a
class and then use getattr to access them.

class Commands:
def Newfoo(self, a,b):
return a+b

def Newblah(self, c,d):
return c*d

def call(self, fname, *args. **kw):
fn = getattr(self, "New"+fname )
return fn(*args, **kw)

cmds = Commands()
lst = ["foo", "blah"]
for func in lst:
print cmds.call(func, 2, 4)
Mar 30 '06 #4
Sakcee wrote:
python provides a great way of dynamically creating fuctions calls and
class names from string

a function/class name can be stored as string and called/initilzed

e.g

def foo(a,b):
return a+b

def blah(c,d):
return c*d
list = ["foo", "blah"]

for func in list:
print func(2,4)

or similar items
Have you actually tried to do this? It doesn't work:

Traceback (most recent call last):
File "<stdin>", line 2, in ?
TypeError: object of type 'string' is not callable

(Also, it is poor practice to shadow the built-in list
as you have.)

You are attempting to call "foo"(2, 4). Strings are not
callable.

Two ways to actually do what you are trying to do is
with eval and exec:
eval("foo(2, 3)") 5 exec("print foo(2, 3)") 5

but be aware of the possible security implications of
eval and exec.

If you are calling instance methods, you can use getattr:
class Foo: .... def foo(self, x,y):
.... return x+y
.... getattr(Foo(), "foo")(2, 3) 5

But the best way is, if possible, avoid this altogether
and remember that functions are first-class objects in
Python. Instead of doing this:

L = ["foo", "bar"]
for func in L:
print eval(func + "(2, 3)")

do this:

L = [foo, bar] # list containing function objects
for func in L:
print func(2, 3)

what is the way if the names of functions are some modification e.g
As far as I know, the only ways are: use eval or exec,
or look in locals and/or globals:
func = locals().get("f " + "oo", None)
if callable(func):

.... func(2, 3)
....
5

You can use globals() instead of locals(), but there
may be issues with scoping rules that I can't think of.

Personally, I think the best way is: find another way
to solve your problem.

is it correct way, is there a simple way, is this techniqe has a name?


I'm told that some people call this "dynamic
programming", but personally I call it "difficult to
maintain, difficult to debug programming".

(Before people get all cranky at me, I'm aware that it
isn't *always* the Wrong Way to solve problems, but it
is a technique which is subject to abuse and can often
be avoided by using function objects instead of
function names.)
--
Steven.

Mar 30 '06 #5
Steven D'Aprano wrote:
Sakcee wrote:
python provides a great way of dynamically creating fuctions calls and
class names from string
(snip)
Personally, I think the best way is: find another way to solve your
problem.

See Duncan's post for a pretty clean and pythonic solution. Another one
that may be more explicit and avoid messing with locals() or globals() is:
is it correct way, is there a simple way, is this techniqe has a name?

I'm told that some people call this "dynamic programming",


In some other languages, it could be called 'metaprogrammin g', but this
is such a common idiom in Python that I'd just call this "programmin g" !-)
but
personally I call it "difficult to maintain, difficult to debug
programming".
Oh yes ? Why so ? I've used such patterns hundreds of time, and it has
never been a problem so far.

Dynamically selecting the function to call given a name (as string) is
is a well-known programming pattern. I learned this in C, using a
hashtable to store names/function pointer pairs. And that's mostly what
the proposed solutions (the one based on globals() or locals() as well
as Duncan's class-based one) do - the main difference being that Python
offers the hashtable for free !-)

nb : I agree that the use of the global or local namespaces may not be
the best thing to do - better to use (any variant of) Duncan's solution
IMHO.
(Before people get all cranky at me, I'm aware that it isn't *always*
the Wrong Way to solve problems, but it is a technique which is subject
to abuse and can often be avoided by using function objects instead of
function names.)


When you get the function name as user input, you cannot directly access
the function object.

And anyway, what do you think Python do when you call a function ?
Python namespaces *are* hash tables mapping symbols names (as string) to
objects (as pointers). I don't see much difference here.

(nb 2 : I agree that it is of course better to avoid 'manual' namespace
lookup whenever possible)

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Mar 30 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
1498
by: Leif K-Brooks | last post by:
I try to make my code comply to the Python style guide (http://www.python.org/peps/pep-0008.html). Last time I read it, I swear that it said to use CamelCase for often-used functions and lower_case_with_underscores for rarely-used utility functions. Now it says to use low_case_with_underscores for everything, but it claims to be last updated in 2001. Am I crazy?
8
4833
by: Falc2199 | last post by:
Hi, Does anyone know how to make this work? var sectionId = 5; repeat_section_sectionId(); function repeat_section_5(){ alert("firing"); }
12
404
by: Eric | last post by:
I've got a pretty large C program with global variables and function names strewn about (i.e. no "static" declarations in front of them). Now I want to expose the ability for user's to supply their own shared object / dll code which will link with my large ugly program. Problem: naming collisions. If my program has: void common_function_name (void) {
3
2323
by: joseluismarchetti | last post by:
Hello everybody, Although I am sure this is an important question for this group, I am not sure this question belongs to this group and I will be happy to move it to the correct one after you point it to me. Direct question: How can I know if a function is defined in more than one static library that I am using to link ?
2
1549
by: newhand | last post by:
If somehow a bunch of function names in string can be passed into an executible, is it possible that for each name call, it will trigger the corresponding function of that name? Of course, this can be done by mapping string function names with functions themselves? Is there a better and direct way? Thanks in advance!
3
1309
by: Xiaoshen Li | last post by:
Dear All, A tutorial told me that there are more than 700 functions available. To see all the function names, man 3 intro. But on my machine, it only gives one page text. For example, if I hope to see the function names in 3C chapter, how should I do it? I know "man sqrt" will give me the information about the function sqrt. But there are many functions that I don't even know their names or I am not even aware of them.
7
2128
by: Petr Jakes | last post by:
I have got names of functions stored in the file. For the simplicity expect one row only with two function names: printFoo, printFOO In my code I would like to define functions and then to read function names from the file, so the functions can be executed in the order the function names are stored in a file. While trying to read the names from the file I am getting always "strings" and I am not able to execute them. I would like to...
2
1558
by: hemant.singh | last post by:
I am stuck with strange JS issue My product gives user to show some images(which track mouseover) on page by embedding script like <script src=http://domain.com/GetDynamicJS?domagic=1> </script> Now user is embedding more than of the above and when user mouse over's the image output of first1 than function getting called is script loaded in last ... thus error, as that script don't have the relevant
16
3279
by: Xiaoxiao | last post by:
Hi, I got a C library, is there a way to view the public function names in this library so that I can use in my C program? Thanks.
0
8975
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
9516
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9286
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9219
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6774
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Duprť who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4587
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4840
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3294
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2768
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.