473,657 Members | 2,758 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 2942
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
1494
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
4826
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
2316
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
1540
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
1305
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
2123
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
1554
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
3270
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
8385
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
8723
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8602
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...
0
7316
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6162
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
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4150
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
4300
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1601
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.