473,804 Members | 2,164 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamically defined functions via exec in imported module

Hello all,
I'm trying to write a function that will dynamically generate other
functions via exec. I then want to be able to import the file (module)
containing this function and use it in other modules, but for some
reason it only works using the "import <mod>" syntax, and not "from
<modimport *" syntax... i.e. in the latter case, the function is
dynamically generated, but not accessible from the importing module.
Any ideas on what I can do to be able to retain the second form of
import and still have the exec'd functions visible?

Here's the code... I have three files:

############### ############### #####
# modA.py

def dynamicdef(name , amt):
'''Dynamically defines a new function with the given name that
adds
the given amt to its argument and returns the result.'''
stm = "def %s(x):\n\tretur n x + %d" % (name, amt)
print stm
# exec stm # --- with this, 'name' is only accessible within
this fn
exec stm in globals() # --- this makes it global within this
module...

print eval(name)
dynamicdef('plu s5', 5)

print plus5(7)
############### ############### #####
# modB.py
# This uses the dynamicdef to dynamically define a new function, and
it
# works fine, with the newly defined function being accessible thru
the modA
# module...

import modA

modA.dynamicdef ('plus10', 10)

print help(modA.plus5 )
print help(modA.plus1 0)

print modA.plus5(20)
print modA.plus10(20)

############### ############### #####
# modC.py
# This uses the dynamicdef to dynamically define a new function, but
it
# doesn't work; seems like knowledge of the newly defined function in
the
# modA module is not propagated back to this context or something...?

from modA import *

dynamicdef('plu s10', 10)

print help(plus5)
#print help(plus10) # !!! Fails: NameError: name 'plus10' is not
defined

print plus5(20)
print plus10(20)
############### ############### #####
Thanks for any help/suggestions,
---nadeem

Aug 15 '08
11 2584
On Aug 16, 3:25*pm, George Sakkis <george.sak...@ gmail.comwrote:
On Aug 16, 12:50*am, Michele Simionato <michele.simion ...@gmail.com>
wrote:
The namedtuple recipe by Raymond Hetting does
exactly that and, guess what, it uses exec!

I might be wrong, but the reason namedtuple uses exec is performance.
IIRC earlier versions of the recipe used a metaclass instead, so it's
not that it *has* to use exec, it's just an optimization, totally
justified in this case since namedtuples should be almost as fast as
plain tuples.
I always thought the reason for "exec" was having a good signature in
the namedtuple constructor. I have not
measure performance, though.
Aug 16 '08 #11
On Aug 16, 4:02*pm, Maric Michaud <ma...@aristote .infowrote:
I'd say that everywhere exec/eval are used in a application/function/lib that
doesn't mean to interpret arbitrary and user provided python code, it is a
bad usage
Problem is, there are things you cannot do without
exec/eval: for instance look at the implementation of
my own decorator module, which uses eval to
guarantee a good signature for the decorated function.
Probably it could be done without exec, with
bytecode hacks, but I regard fiddling with bytecodes
as something worse than exec itself. I am not
sure if in Python 3.0 the signature object is
powerful enough to do the job, I never had to
time to check how it works.

Michele Simionato
Aug 16 '08 #12

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

Similar topics

3
19341
by: Fernando Rodriguez | last post by:
Hi, How can I get the list of all the functions defined in the current module?
4
1573
by: Joerg Schuster | last post by:
Hello, I want to refer to all functions of a module, say test2.py, without having to manually enumerate them. The following code comes closest to what I am trying to do. It does not work, because dir() does not return functions, but function names as strings. ##### test2.py #####
6
2036
by: Kamilche | last post by:
I can't figure out how to list all functions from an imported module. I searched Google, but all the answers I found didn't work. Did something change in Python 2.2, perhaps there's a new method of doing it?
5
1575
by: James Tauber | last post by:
Had a question from a colleague that I embarrassingly couldn't answer. He has a script, foo.py with a global. He wants to import bar.py and needs that global available in bar.py The following obviously doesn't work: # foo.py my_global = "hello" print globals().keys()
5
15711
by: Ed Havelaar | last post by:
I have a cool function that I want to use as a default value for a column in my table. But I can't because apparently Access doesn't allow user defined functions in expressions for default values. It's very annoying. Is there any way around it? What I need is something like AutoNumber, *except* I want the values to be unique across six different tables. Any ideas? Unknown function <name> in validation expression or default value...
2
5488
by: David Emme | last post by:
Access 97 I have a number of SELECT statements which contain references to user-defined VBA functions. These typically work as expected, but occasionally, on one user's machine or another, produce a "function not defined" message when the SELECT statement is executed, even having previously worked on that machine. What can I do to correct this difficulty when it occurs? What do I need to know about user-defined functions in SELECT...
4
1303
by: Paul McGuire | last post by:
I have a new enhancement to pyparsing that doubles the parse speed (using a technique called "packrat parsing"), but which is not suitable for all parsers, specifically those that have complex parse actions. I don't want to just enable this feature by default - I think there is too much risk of it breaking existing code. Actually, I think the chance is <10%, but I think I'm better off leaving the feature dormant unless explicitly enabled,...
0
1068
by: Mike | last post by:
Hi. I have a vb.net/asp.net application, originally created in VS2003. I'm upgrading it to VS2005, and have found that Public Functions in a module are no longer accessable in my application. My code looks like this - and in this example I cannot call Function 123 within my application. --- Public Module ABC Public Function 123() as Boolean ...
1
1138
by: anil.pundoor | last post by:
hi all, i have following code if <condition> from SIPT.xml_param_mapping import MESSAGE_PARAMETER_MAPPING else: from SIPT.msg_param_mapping import MESSAGE_PARAMETER_MAPPING
0
9714
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, 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...
0
10600
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
10350
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...
0
10096
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
9174
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
6866
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
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4311
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
2
3834
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.