473,698 Members | 2,051 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting a function name from string

If I have a string that contains the name of a function, can I call it?
As in:

def someFunction():
print "Hello"

s = "someFuncti on"
s() # I know this is wrong, but you get the idea...

/David
Nov 2 '05 #1
5 14798
"David Rasmussen" <da************ *@gmx.net> wrote in message
news:43******** **************@ dtext02.news.te le.dk...
If I have a string that contains the name of a function, can I call it?
As in:

def someFunction():
print "Hello"

s = "someFuncti on"
s() # I know this is wrong, but you get the idea...

/David


Lookup the function in the vars() dictionary.
def fn(x): .... return x*x
.... vars()['fn'] <function fn at 0x009D67B0> vars()['fn'](100)

10000

-- Paul
Nov 2 '05 #2
"Paul McGuire" <pt***@austin.r r._bogus_.com> writes:
"David Rasmussen" <da************ *@gmx.net> wrote in message
news:43******** **************@ dtext02.news.te le.dk...
If I have a string that contains the name of a function, can I call it?
As in:

def someFunction():
print "Hello"

s = "someFuncti on"
s() # I know this is wrong, but you get the idea...

/David


Lookup the function in the vars() dictionary.
def fn(x): ... return x*x
... vars()['fn'] <function fn at 0x009D67B0> vars()['fn'](100) 10000


vars() sans arguments is just locals, meaning it won't find functions
in the global name space if you use it inside a function:
def fn(x): .... print x
.... def fn2(): .... vars()['fn']('Hello')
.... fn2() Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in fn2
KeyError: 'fn'


Using globals() in this case will work, but then won't find functions
defined in the local name space.

For a lot of uses, it'd be better to build the dictionary by hand
rather than relying on one of the tools that turns a namespace into a
dictionary.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Nov 3 '05 #3
David Rasmussen wrote:
If I have a string that contains the name of a function, can I call it?
As in:

def someFunction():
print "Hello"

s = "someFuncti on"
s() # I know this is wrong, but you get the idea...


py> eval("someFunct ion()")
'Hello'
py> eval(s)() # note the second pair of brackets
'Hello'

See also exec -- but before you use either eval or
exec, make sure you are fully aware of the security
implications. Whatever a user could do to your system
by sitting down in front of it with a Python
interactive session open and typing commands at the
keyboard, they can also do remotely if you call exec on
input they provide.

So you probably don't want to be calling exec on
strings that you get from random users via a website.

It has been my experience that, more often than not,
any time you think you want to evaluate strings, you
don't need to.

For instance, instead of passing around the name of the
function as a string:

s = "someFuncti on"
eval(s)()

you can pass around the function as an object:

s = someFunction # note the lack of brackets
s()

--
Steven.

Nov 3 '05 #4
On Wed, 02 Nov 2005 19:01:46 -0500, Mike Meyer <mw*@mired.or g> wrote:
"Paul McGuire" <pt***@austin.r r._bogus_.com> writes:
"David Rasmussen" <da************ *@gmx.net> wrote in message
news:43******** **************@ dtext02.news.te le.dk...
If I have a string that contains the name of a function, can I call it?
As in:

def someFunction():
print "Hello"

s = "someFuncti on"
s() # I know this is wrong, but you get the idea...

/David


Lookup the function in the vars() dictionary.
> def fn(x):

... return x*x
...
> vars()['fn']

<function fn at 0x009D67B0>
> vars()['fn'](100)

10000


vars() sans arguments is just locals, meaning it won't find functions
in the global name space if you use it inside a function:
def fn(x):... print x
... def fn2():... vars()['fn']('Hello')
... fn2()Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in fn2
KeyError: 'fn'


Using globals() in this case will work, but then won't find functions
defined in the local name space.

For a lot of uses, it'd be better to build the dictionary by hand
rather than relying on one of the tools that turns a namespace into a
dictionary.

IMO it would be nice if name lookup were as cleanly
controllable and defined as attribute/method lookup.
Is it a topic for py3k?

Regards,
Bengt Richter
Nov 3 '05 #5
bo**@oz.net (Bengt Richter) writes:
For a lot of uses, it'd be better to build the dictionary by hand
rather than relying on one of the tools that turns a namespace into a
dictionary.

IMO it would be nice if name lookup were as cleanly
controllable and defined as attribute/method lookup.
Is it a topic for py3k?


I'm not sure what you mean by "cleanly controllable and defined". I'd
say name lookup is well defined and clean, as it's the same as it is
in pretty much any language that supports nested scopes, modulo
assignment creating things in the local scope. If you're talking about
letting users control that mechanism, that's definitely py3k material,
if not "python-like-language-that's-not-python" material. On the other
hand, if you just want to provide tools that let users do name lookups
the way they can do attribute lookups, that's easy, and we could add
that now:

getname(name) - returns the object name is bound to.
setname(name, value) - binds the variable name.

And maybe you want an optional third argument of a callable, which
causes the functions to work on names starting in the callables name
space.

The real question is (as always) - what's the use case? In particular,
what's the use case that we really want to encourage? As I said,
you're usually better off separating dynamically built names into
their own dictionary rather than trying to plug them into - or pull
them out of - one of the language namespaces. If you plug them in,
there's no way to get them back out except by mechanisms similar to
how you got them in, so you might as well let those mechanisms include
a dictionary. If you pull it out, you might as well have referenced
the bare name rather than the string. If you constructed the name in
some way, then changing the constructor to do a dictionary lookup
should be straightforward . All of these technics avoid problems that
come from overloading a language namespace.

Of course, I'm not omniscient, so you may have something that doesn't
fit those cases in mind - in which case, let's hear about it.

You can even arrange to run python code with your dictionary as a
namespace. Following are excerpts from a tool I'm currently not
working on.

class P:
def __init__(self):
self.variables = dict(In = self.set_input, Out = self.set_output ,
Labels = self.set_labels , Float = DoubleVar,
String = StringVar, Int = IntVar)

def calculate(self) :
for name, var in self.inputs.ite ms():
self.variables[name] = var.get()
self.variables['calculate']()
for name, var in self.outputs.it ems():
var.set(self.va riables[name])

def run(self):
self.app.mainlo op(self.calcula te)
def main(args):
app = P()
execfile(argv[1], app.variables)
app.run()

Here I create a dictionnary - P().variables - and populate it with
names and their values. I then run the code of interest with that
dictionary as the global namespace. The code will add things to the
namespace - in particular, "calculate" . I then run a loop which will,
at unspecified times, set names in the P().variables dictionary, run
the "calculate" callable created by the code of interest, then copy
values out of the dictionary. This works ilke a charm. If you don't
want to deal with entire files, you can use exec, or even eval if you
just want to get a value back.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Nov 3 '05 #6

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

Similar topics

2
6916
by: Eyal | last post by:
Hey, I would appriciate if anyone can help on this one: I have a java object/inteface having a method with a boolean parameter. As I'm trying to call this method from a javascript it fails on a type mismatch. It is positively because of the boolean(java primitive)parameter. It goes fine if I change this parameter to int or String. This inteface has a lot more methods which works fine, it is just the
11
4857
by: Derek Martin | last post by:
Using VB.Net, I would like to retrieve the currently logged in user's DN from Active Directory. Alternatively, if, using WindowsIdentity, or something similar, I would like to get the user's full name that is found on the Workstation Locked screen between the ( )'s. Does anyone know how to do that? The only constraint: no use of ActiveDS.dll permitted by the design. Many thanks! Derek
1
4267
by: Lyle Fairfield | last post by:
Option Explicit ' requires VBScript to be installed ' (maybe don't give this to your sugnificant other as ' it gets deleted addresses as well as current) ' obvious fixups needed '1. how get wab file location ' further development '1. get names too? ' maybe some WABs are encrypted
1
1867
by: pukya78 | last post by:
Hi, I am trying to get the current file and the line number which is getting executed. I used: MessageBox.Show(New StackTrace(New StackFrame(True)).GetFrame(0).GetFileLineNumber) which gives me the line number. Later on, I was trying to write a generalized routine, so that I can log the file name and the method.
1
9482
by: kamleshsharmadts | last post by:
I am using Ajax with struts in web application. from jsp i am calling a function of ajax.js onclick of a button. code of that call function which calling from jsp given as below:- onclick="retrieveURL('/application/home_page.do?processAction=ItinerarySearch','AfoHomeForm')" after clicking on button i am getting following error:- object does not support this property or method at statement (Which i have made it bold in js file)
4
6217
by: AshishMishra16 | last post by:
HI friends, I am using the Flex to upload files to server. I m getting all the details about the file, but I m not able to upload it to Server. Here is the code i m using for both flex & for Struts: import java.io.File; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator;
3
1931
by: TC | last post by:
Hey All, I have some classes that I recently built for a website which uses the HttpWebRequest & HttpWebResponse objects from the System.Net namespace. Basically, the classes rap submitted data up, connect to external websites on external servers and post / remove the data from these other sites. It works fine locally but when uploaded to the BCentral production server, the outgoing requests get shutdown.
0
1552
by: TG | last post by:
Hi! Once again I have hit a brick wall here. I have a combobox in which the user types the server name and then clicks on button 'CONNECT' to populate the next combobox which contains all the databases in that server. Then after the user selects a database, I have another button that he/she click and I want to retrieve file groups from a specific table. At this point when he/she clicks on that button I get an error:
1
4922
by: raghuvendra | last post by:
Hi I have a jsp page with 4 columns: namely Category name , Category order, Input field and a submit button. All these are aligned in a row. And Each Category Name has its corresponding Category order, Input field and a submit button. The Category name is being fetched from the oracle db along with the corresponding Category order. In the corresponding input field (text box) the user enters a new category order which gets stored in...
5
1632
by: tshad | last post by:
I have the following class in my VS 2008 project that has a namespace of MyFunctions. ********************************* Imports System Imports System.Text.RegularExpressions Namespace MyFunctions Public Class BitHandling
0
8598
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9152
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...
0
9016
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...
1
8887
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
8856
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
7709
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...
0
5858
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
4613
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
1997
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.