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 10 2936
On 10/22/07, james_027 <ca********@gma il.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
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.
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.as ter.pl | voice: +48228430101
"We read Knuth so you don't have to." (Tim Peters)
On Oct 22, 4:41 am, "Francesco Guerrieri" <f.guerri...@gm ail.com>
wrote:
On 10/22/07, james_027 <cai.hai...@gma il.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_na me = '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'
=============== =============== ==============
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().
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.
>>exec("impor t 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.ne t | 402-438-8958 | http://www.ncee.net
Leading the Campaign for Economic and Financial Literacy
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.3 45', '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.3 45', 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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 called
MyFunction. Can you specify a string for the function name like you
can with the form name? That is can I do something like
Forms("MyForm")."MyFunction"
|
by: seash |
last post by:
class xyz{
public void somefunction{
if(this.folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
m_varFolderPath = this.folderBrowserDialog1.SelectedPath;
m_varFolderPath += "\\Iamlucky.txt";
|
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).
I changed the data type for the structure that contains the XML data from
the default "String" to "xml.xmldocument" to enable easy filling of the
data.
my client code creates an XML document class, fills the data using standard
xml dom...
|
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 System.Collections.Generic;
using System.ComponentModel;
|
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
"CM_Get_Device_ID_List_SizeA" (ByRef pulLen As Integer, ByVal pszFilter As
Integer, ByVal UlFlags As Integer) As Integer -
To get the length of the device list. This seems to work as I get a
CR_SUCCESS (I get a number around 8500. But as I'm not sure what is in the
| |
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;
|
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(), ptr_fun(::tolower));
|
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
extern "C" char *Func1(int isDsb, char *firstString, char
|
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 the...
|
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 works fine when called from a win32 app. The problem I am encountering is that the string being returned to the caller is in Chinese (No, I'm not kidding). (I need it to be in English).
Background: The DLL uses 3 pchar parms, 2 in and one out. In...
|
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...
| |
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,...
|
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...
|
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,...
|
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...
|
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...
|
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();...
| |
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
|
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...
| |