473,836 Members | 1,602 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

howto get function from module, known by string names?

hi all,
can anyone explain howto get function from module, known by string
names?
I.e. something like

def myfunc(module_s tring1, func_string2, *args):
eval('from ' + module_string1 + 'import ' + func_string2')
return func_string2(*a rgs)

or, if it's impossible, suppose I have some modules
module1 module2 module3 ... etc
each module has it own funcs 'alfa', 'beta' and class module1,
module2,... with same string name as module name.
can I somehow pass module as function param and then import function
'alfa' from (for example) module8? and/or import class moduleN from
moduleN?

something like
def myfunc(moduleK, *args):
return moduleK.moduleK (*args)
or return moduleK.alfa(*a rgs)

Thx, D

May 15 '07 #1
7 5101
On 15 May 2007 04:29:56 -0700, dmitrey wrote
hi all,
can anyone explain howto get function from module, known by string
names?
I.e. something like

def myfunc(module_s tring1, func_string2, *args):
eval('from ' + module_string1 + 'import ' + func_string2')
return func_string2(*a rgs)
To find a module by its name in a string, use __import__. To find an object's
attribute by its name in a string, use getattr.

Together, that becomes something like this:
>>def myfunc(module_s tring1, func_string2, *args):
.... func = getattr(__impor t__(module_stri ng1), func_string2)
.... return func(*args)
....
>>myfunc("math" , "sin", 0)
0.0
>>myfunc("opera tor", "add", 2, 3)
5

Hope this helps,

--
Carsten Haese
http://informixdb.sourceforge.net

May 15 '07 #2
And howto check does module 'asdf' exist (is available for import) or
no? (without try/cache of course)
Thx, D.

Carsten Haese wrote:
On 15 May 2007 04:29:56 -0700, dmitrey wrote
hi all,
can anyone explain howto get function from module, known by string
names?
I.e. something like

def myfunc(module_s tring1, func_string2, *args):
eval('from ' + module_string1 + 'import ' + func_string2')
return func_string2(*a rgs)

To find a module by its name in a string, use __import__. To find an object's
attribute by its name in a string, use getattr.

Together, that becomes something like this:
>def myfunc(module_s tring1, func_string2, *args):
... func = getattr(__impor t__(module_stri ng1), func_string2)
... return func(*args)
...
>myfunc("math ", "sin", 0)
0.0
>myfunc("operat or", "add", 2, 3)
5

Hope this helps,

--
Carsten Haese
http://informixdb.sourceforge.net
May 21 '07 #3
And howto check does module 'asdf' exist (is available for import) or
no? (without try/cache of course)
Thx, D.

Carsten Haese wrote:
On 15 May 2007 04:29:56 -0700, dmitrey wrote
hi all,
can anyone explain howto get function from module, known by string
names?
I.e. something like

def myfunc(module_s tring1, func_string2, *args):
eval('from ' + module_string1 + 'import ' + func_string2')
return func_string2(*a rgs)

To find a module by its name in a string, use __import__. To find an object's
attribute by its name in a string, use getattr.

Together, that becomes something like this:
>def myfunc(module_s tring1, func_string2, *args):
... func = getattr(__impor t__(module_stri ng1), func_string2)
... return func(*args)
...
>myfunc("math ", "sin", 0)
0.0
>myfunc("operat or", "add", 2, 3)
5

Hope this helps,

--
Carsten Haese
http://informixdb.sourceforge.net
May 21 '07 #4
And howto check does module 'asdf' exist (is available for import) or
no? (without try/cache of course)
Thx, D.

Carsten Haese wrote:
On 15 May 2007 04:29:56 -0700, dmitrey wrote
hi all,
can anyone explain howto get function from module, known by string
names?
I.e. something like

def myfunc(module_s tring1, func_string2, *args):
eval('from ' + module_string1 + 'import ' + func_string2')
return func_string2(*a rgs)

To find a module by its name in a string, use __import__. To find an object's
attribute by its name in a string, use getattr.

Together, that becomes something like this:
>def myfunc(module_s tring1, func_string2, *args):
... func = getattr(__impor t__(module_stri ng1), func_string2)
... return func(*args)
...
>myfunc("math ", "sin", 0)
0.0
>myfunc("operat or", "add", 2, 3)
5

Hope this helps,

--
Carsten Haese
http://informixdb.sourceforge.net
May 21 '07 #5
Sorry, some problems with internet connection yield these messages

May 21 '07 #6
En Mon, 21 May 2007 10:13:02 -0300, dmitrey <op*****@ukr.ne tescribió:
And howto check does module 'asdf' exist (is available for import) or
no? (without try/cache of course)
What's wrong with this:

try: import asdf
except ImportError: asdf = None

....later...

if asdf:
asdf.zxcv(1)
...

--
Gabriel Genellina

May 21 '07 #7
On Mon, 2007-05-21 at 06:13 -0700, dmitrey wrote:
And howto check does module 'asdf' exist (is available for import) or
no? (without try/cache of course)
Why would you need to do that? What are you planning to do when you have
determined that the module doesn't exist? Surely you're not planning on
swallowing the error silently, because that would make your program very
hard to debug. The Pythonic response is to raise an exception, but then
you might as well just propagate the exception that __import__ already
raises:
>>def myfunc(module_s tring1, func_string2, *args):
.... func = getattr(__impor t__(module_stri ng1), func_string2)
.... return func(*args)
....
>>myfunc("asdf" , "spam")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in myfunc
ImportError: No module named asdf

Hope this helps,

--
Carsten Haese
http://informixdb.sourceforge.net
May 21 '07 #8

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

Similar topics

9
4969
by: Penn Markham | last post by:
Hello all, I am writing a script where I need to use the system() function to call htpasswd. I can do this just fine on the command line...works great (see attached file, test.php). When my webserver runs that part of the script (see attached file, snippet.php), though, it doesn't go through. I don't get an error message or anything...it just returns a "1" (whereas it should return a "0") as far as I can tell. I have read the PHP...
2
4461
by: Marc Shapiro | last post by:
I am relatively new to python (I have used it on and off for a few small projects over the last few years) so I imagine that what I am trying to do has already been done, but practical experience, even if it is reinventing the wheel, is still useful, so... I am trying to write a module to handle drop down menus using curses (on linux). Curses seems to have a wrapper for the panels library, but not forms, or menus. I am not even sure...
8
2539
by: Mark English | last post by:
I'd like to write a Tkinter app which, given a class, pops up a window(s) with fields for each "attribute" of that class. The user could enter values for the attributes and on closing the window would be returned an instance of the class. The actual application I'm interested in writing would either have simple type attributes (int, string, etc.), or attributes using types already defined in a c-extension, although I'd prefer not to...
4
2222
by: Andy | last post by:
What do people think of this? 'prefixed string'.lchop('prefix') == 'ed string' 'string with suffix'.rchop('suffix') == 'string with ' 'prefix and suffix.chop('prefix', 'suffix') == ' and ' The names are analogous to strip, rstrip, and lstrip. But the functionality is basically this: def lchop(self, prefix):
7
14393
by: Guy Robinson | last post by:
Hello, I have a directory of python scripts that all (should) contain a number of attributes and methods of the same name. I need to import each module, test for these items and unload the module. I have 2 questions. 1.. How do unload an imported module? 2.. how do I test for the existance of a method in a module without running it?
5
1805
by: Bruce Lawrence | last post by:
I'm running Access 97 and my modules are looping if someone puts an invalid value in. The setup: 3 macros - get_clock_num, verify_clocknum, append_to_history 3 functions. each in their own module - get_clocks(), verify_clocks(), append() Each macro runs a function from in its corresponding module. Here is my code.
3
6512
by: ATS | last post by:
HOWTO Implement LoadLibrary, GetProcAdress, and FreeLibrary. Below is code that I want to be able to use simple LoadLibrary\GetProcAddress\FreeLibrary technqiues on. I've used the code that was initially placed on the .NET 247 forum as such: http://dotnet247.com/247reference//msgs/28/140461.aspx I have expanded it here to let one call any/all kinds of functions. The idea is that a "MASTER" Invoke function takes arrays that explain...
4
2862
by: Ray Dukes | last post by:
What I am looking to do is map the implementation of interface properties and functions to an inherited method of the base class. Please see below. '**************************************************************************** ' Issues '****************************************************************************
8
1936
by: Gillard | last post by:
hello, anyone have a snippet to get the name of the season for a date???? something like GetSeason(today) and it return summer
0
9673
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
10859
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
10560
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
10602
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
10260
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
9388
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
6984
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
5653
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...
2
4023
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.