473,396 Members | 2,092 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,396 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 2897
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...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...
0
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...
0
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,...

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.