473,289 Members | 2,091 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,289 software developers and data experts.

calling a function from string

hi,

i have a function that I could like to call, but to make it more
dynamic I am constructing a string first that could equivalent to the
name of the function I wish to call. how could I do that? the string
could might include name of the module.

for example

a_string = 'datetime.' + 'today()'

how could I call a_string as function?

Thanks
james

Oct 22 '07 #1
10 2890
On 10/22/07, james_027 <ca********@gmail.comwrote:
hi,

i have a function that I could like to call, but to make it more
dynamic I am constructing a string first that could equivalent to the
name of the function I wish to call. how could I do that? the string
could might include name of the module.

for example

a_string = 'datetime.' + 'today()'

how could I call a_string as function?
you could use getattr:

function_name = 'time' # this is a string
module_name = 'time' # this is a string, too

my_function = getattr(module_name, function_name) # this is the
function object,
# equivalent to my_function = time.time
my_function() # This is the function call, equivalent to time.time()

bye
francesco
Oct 22 '07 #2
i have a function that I could like to call, but to make it more
dynamic I am constructing a string first that could equivalent to the
name of the function I wish to call. how could I do that? the string
could might include name of the module.

for example

a_string = 'datetime.' + 'today()'

how could I call a_string as function?
Use 'eval' in one of the following fashions:

a_string_1 = 'datetime.' + 'today'
a_string_2 = 'datetime.' + 'today()'

eval(a_string_1)()
eval(a_string_2)
Trent.
Oct 22 '07 #3
Trent Nelson napisa³(a):
>i have a function that I could like to call, but to make it more
dynamic I am constructing a string first that could equivalent to the
name of the function I wish to call. how could I do that? the string
could might include name of the module.

for example

a_string = 'datetime.' + 'today()'

how could I call a_string as function?

Use 'eval' in one of the following fashions:

a_string_1 = 'datetime.' + 'today'
a_string_2 = 'datetime.' + 'today()'

eval(a_string_1)()
eval(a_string_2)
Do not use eval(). Not only it's deprecated, it's also unsafe.

--
Jarek Zgoda
Skype: jzgoda | GTalk: zg***@jabber.aster.pl | voice: +48228430101

"We read Knuth so you don't have to." (Tim Peters)
Oct 22 '07 #4
On Oct 22, 4:41 am, "Francesco Guerrieri" <f.guerri...@gmail.com>
wrote:
On 10/22/07, james_027 <cai.hai...@gmail.comwrote:
hi,
i have a function that I could like to call, but to make it more
dynamic I am constructing a string first that could equivalent to the
name of the function I wish to call. how could I do that? the string
could might include name of the module.
for example
a_string = 'datetime.' + 'today()'
how could I call a_string as function?

you could use getattr:

function_name = 'time' # this is a string
module_name = 'time' # this is a string, too

my_function = getattr(module_name, function_name) # this is the
function object,
# equivalent to my_function = time.time

Not quite.

============================================
>>function_name = 'time' # this is a string
module_name = 'time' # this is a string, too
my_function = getattr(module_name, function_name)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
my_function = getattr(module_name, function_name)
AttributeError: 'str' object has no attribute 'time'
============================================

It's actually equivalent to:

============================================
>>"time".time
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
"time".time
AttributeError: 'str' object has no attribute 'time'
============================================

Oct 22 '07 #5
On Oct 22, 5:46 am, Jarek Zgoda <jzg...@o2.usun.plwrote:
Do not use eval(). Not only it's deprecated, it's also unsafe.
I don't think it's deprecated; it doesn't say so:
http://docs.python.org/lib/built-in-funcs.html#l2h-25

Oct 22 '07 #6
james_027 a écrit :
hi,

i have a function that I could like to call, but to make it more
dynamic I am constructing a string first that could equivalent to the
name of the function I wish to call. how could I do that? the string
could might include name of the module.

for example

a_string = 'datetime.' + 'today()'

how could I call a_string as function?
The obvious answer is to use eval or exec, but it's 99.99 times out of
100 the wrong solution.

Better solutions usually rely on Python's introspection features -
mostly globals(), locals(), sys.modules, and of course getattr().
Oct 22 '07 #7
Jarek Zgoda a écrit :
Trent Nelson napisa³(a):
>>i have a function that I could like to call, but to make it more
dynamic I am constructing a string first that could equivalent to the
name of the function I wish to call. how could I do that? the string
could might include name of the module.

for example

a_string = 'datetime.' + 'today()'

how could I call a_string as function?
Use 'eval' in one of the following fashions:

a_string_1 = 'datetime.' + 'today'
a_string_2 = 'datetime.' + 'today()'

eval(a_string_1)()
eval(a_string_2)

Do not use eval(). Not only it's deprecated,
Chapter and verse ???
it's also unsafe.
it's *potentially* unsafe. As long as the eval'd code comes from a
trusted source, there should be no security problem.

I agree that eval is usually not the solution, but mainly because Python
has far better (wrt/ readability and maintainance) options for this kind
of things.

Oct 22 '07 #8
>>exec("import datetime") ; exec("x = datetime." + "date." + "today()")
>>print x
2007-10-22


james_027 wrote:
hi,

i have a function that I could like to call, but to make it more
dynamic I am constructing a string first that could equivalent to the
name of the function I wish to call. how could I do that? the string
could might include name of the module.

for example

a_string = 'datetime.' + 'today()'

how could I call a_string as function?

Thanks
james


--
Shane Geiger
IT Director
National Council on Economic Education
sg*****@ncee.net | 402-438-8958 | http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy
Oct 22 '07 #9
On Mon, 22 Oct 2007 08:54:02 +0000, james_027 wrote:
hi,

i have a function that I could like to call, but to make it more dynamic
I am constructing a string first that could equivalent to the name of
the function I wish to call.
That is not the right solution to dynamic functions. There is a much
better way.

how could I do that? the string could might
include name of the module.

for example

a_string = 'datetime.' + 'today()'

how could I call a_string as function?
Others have suggested eval() and exec. Both will work, but have MAJOR
security implications.

The right way to work with "dynamic functions" is to remember that Python
treats functions as first-class objects just like strings and ints and
lists. Here's a simple example:

Suppose I have a function that takes a string and converts it to another
object type.

def converter(x, convert_to):
if convert_to == 'int':
return int(x)
elif convert_to == 'float':
return float(x)
elif convert_to == 'list':
return list(x)
else:
raise ValueError("don't know that type")

and then use the function like this:

my_float = converter('12.345', 'float')
That's the wrong way to do it. This is the right way:

def converter(x, convert_to):
return convert_to(x)

my_float = converter('12.345', float)

See the subtle difference?

'float' is a string, and it has no special meaning.

float() with brackets says "call the function float".

float without brackets *is* the function float. You can pass it around
like any other object (strings, lists, ints, etc.) and call it later.

Try this example:

import datetime, time
functions = [int, float, datetime.time, time.time]
for f in functions:
print f()

--
Steven
Oct 22 '07 #10
On Mon, 22 Oct 2007 23:16:38 +0000, Steven D'Aprano wrote:
>how could I call a_string as function?

Others have suggested eval() and exec. Both will work, but have MAJOR
security implications.
Oh, and they are seriously slower too.
>>import timeit
timeit.Timer('f("2.3")',
.... 'f = float').repeat() # time using 1st class function
[1.7266130447387695, 0.97645401954650879, 0.97271394729614258]
>>timeit.Timer('eval("float")("2.3")'
.... ).repeat() # time using eval and a string
[20.628923177719116, 19.70452094078064, 19.783280849456787]
--
Steven.
Oct 22 '07 #11

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

Similar topics

10
by: headware | last post by:
I know that you can call the method of one from from inside another form by doing something like this Forms("MyForm").MyFunction(12, 34) However, you have to know that MyForm has a function...
1
by: seash | last post by:
class xyz{ public void somefunction{ if(this.folderBrowserDialog1.ShowDialog() == DialogResult.OK) { m_varFolderPath = this.folderBrowserDialog1.SelectedPath; m_varFolderPath += ...
3
by: Jerome Cohen | last post by:
AI am trying to call a third-party web service. this service expects an XML fragment that contains the request plus other parameter. adding the web reference created the syntax below(reference.vb)....
0
by: Przemys³aw Bana¶ | last post by:
Hello! Can anyone help me with calling Novell function from dll? I think my main problem is in translating C variable types to C# types. Here is the code: using System; using...
4
by: Henning M | last post by:
Hej All Im relativ new to VB.net and im trying to collect som device information using cfgmgr32.dll I use - Declare Function GetListLength Lib "cfgmgr32.dll" Alias...
6
by: RB Smissaert | last post by:
Made a C++ dll with MS VC6 and trying to call the dll from Excel VBA. This is the code in the .cpp file: #include "stdafx.h" #include <string> #include <math.h> using namespace std;
0
by: nickyeng | last post by:
#include <iostream> #include <fstream> #include <string> #include <map> #include <iterator> using namespace std; void f(string str){ transform(str.begin(), str.end(), str.begin(),...
5
by: kelvin.koogan | last post by:
How can I call a function in a Delphi DLL from C++/CLI? The Delphi function is declared as follows: function Func1(IsDsb: Boolean; FirstStr, SecondStr : String): String; I've tried ...
4
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...
0
by: BornTOCode | last post by:
Hello, I am attempting to call a (Delphi) win32 DLL from a Delphi.Net webservice. I am using a slightly modified version of the hello world webservice that comes with Delphi 2006. The DLL...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

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.