473,602 Members | 2,751 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to dynamicly define function and call the function?

FAN
I want to define some function in python script dynamicly and call
them later, but I get some problem. I have tried the following:

############### ############### ####
# code
############### ############### ####
class test:
def __init__(self):
exec("def dfunc(msg):\n\t print msg\nprint 'exec def function'")
dfunc('Msg in init ...') # it work

def show(self, msg):
dfunc(msg) # doesn't work !
exec('dfunc(msg )') # doesn't work too!

d = test()
d.show('hello')
############### ############### #####
#output
############### ############### ####
exec def function
Msg in init ...
Traceback (most recent call last):
File "test.py", line 10, in ?
d.show('hello')
File "test.py", line 7, in show
dfunc(msg)
NameError: global name 'dfunc' is not defined
############### ############### ####

I think this maybe cause by the scope of function definition, for the
first call of 'dfunc' in __init__ work. So I tried to define the
function as a member function of class 'test', but this time even the
first call doesn't work:

############### ############### ####
# code
############### ############### ####
class test:
def __init__(self):
exec("def dfunc(self,msg) :\n\tprint msg\nprint 'exec def function'")
self.dfunc('Msg in init ...')

def show(self, msg):
exec("self.dfun c(msg)")

d = test()
d.show('hello')
############### ############### #####
#output
############### ############### ####
exec def function
Traceback (most recent call last):
File "test.py", line 9, in ?
d = test()
File "test.py", line 4, in __init__
self.dfunc('Msg in init ...')
AttributeError: test instance has no attribute 'dfunc'
############### ############### ####

Is there any way I can solve this problem?

Regards

- FAN
Sep 9 '05 #1
2 2993
FAN wrote:
class test:
def __init__(self):
exec("def dfunc(msg):\n\t print msg\nprint 'exec def function'")
dfunc('Msg in init ...') # it work

def show(self, msg):
dfunc(msg) # doesn't work !
exec('dfunc(msg )') # doesn't work too!


class Test(object):
def __init__(self):
exec "def dfunc(msg):\n print msg"
dfunc('Hello from __init__.')
self.dfunc = dfunc

def show(self, msg):
self.dfunc(msg)
(Of course, this is assuming your real function is more complicated than
the one you've posted; if it isn't, you don't need to use exec to define
it.)
Sep 9 '05 #2
FAN wrote:
I want to define some function in python script dynamicly and call
them later, but I get some problem. I have tried the following:

############### ############### ####
# code
############### ############### ####
class test:
def __init__(self):
exec("def dfunc(msg):\n\t print msg\nprint 'exec def function'")
dfunc('Msg in init ...') # it work

def show(self, msg):
dfunc(msg) # doesn't work !
I think this maybe cause by the scope of function definition, for the
first call of 'dfunc' in __init__ work.
The exec statement syntax is:
"exec" expression ["in" expression ["," expression]]

http://www.python.org/doc/2.4.1/ref/exec.html

Without the optional part, the default is to execute the statement in
the current scope. As Python allows defining nested functions, the
dfunc() function is local to the the __init__() function and doesn't
exists in the class scope or the global scope.

class Test2(object):
def __init__(self):
exec "def dfunc(msg):\n\t print msg\nprint 'exec def function'" \
in globals()
dfunc('Msg in init ...') # it work

def show(self, msg):
dfunc(msg)

d2 = Test2()
d2.show('hello' )

But I would not advise you to use exec this way...
So I tried to define the
function as a member function of class 'test', but this time even the
first call doesn't work:

############### ############### ####
# code
############### ############### ####
class test:
def __init__(self):
exec("def dfunc(self,msg) :\n\tprint msg\nprint 'exec def function'") self.dfunc('Msg in init ...')
Here again, for the function to become a method of the class, it has to
be defined in the scope of the class - not in the scope of the
__init__() function:

class Test(object):
exec "def dfunc(self,msg) :\n\tprint msg\nprint 'exec def function'"

def __init__(self):
self.dfunc('Msg in init ...')
def show(self, msg):
self.dfunc(msg)

d = Test()
d.show('hello')
Is there any way I can solve this problem?


The first question that comes to mind is "aren't you trying to solve the
wrong problem ?". If you tell us more about your real use case, we may
point you to others - possibly better - ways of solving it. I don't mean
that it's wrong to use the exec statement, but my experience is that
I've never had a use case for it in 5+ years of Python programming.
Everytime I thought I needed exec, it turned out that there was a much
better solution, usually involving callables, closures, properties,
descriptors, metaclasses, or any combination of...

Also, the fact that you seems to be at lost with Python's inner
mechanisms makes me think you probably don't know other - possibly
better - ways to solve your problem.

If what you need is to "parameteri ze" a function, closures and nested
functions may be a better solution. A silly exemple:

def makeadder(step) :
def adder(num):
return step + num
return adder

add1 = makeadder(1)
add3 = makeadder(3)

add1(1)
=> 2
add1(2)
=> 3
add2(1)
=> 3
add2(2)
=> 4

Functions being first-class citizen in Python, it's easy to parameterize
a function with another:

import sys
def buildfun(funtes t, funiftrue, funiffalse):
def built(arg):
if funtest(arg):
print "%s is true for %s" % (funtest, arg)
funiftrue("%s\n " % str(arg))
else:
print "%s is false for %s" % (funtest, arg)
funiffalse("%s\ n" % str(arg))
return built

b = buildfun(lambda arg: arg == 42, sys.stdout.writ e, sys.stderr.writ e)
b(42)
b("toto")

Another possibility is to work with callable objects. A function in
Python is just an object (an instance of the function class), and any
object having a __call__() method is callable:

class Greeter(object) :
def __init__(self,
name,
greeting="hello %(who)s, my name is %(name)s"):

""" greeting is supposed to be a format string
with %(name)s and %(who)s in it
"""
self.name = name
self.greeting = greeting

def __call__(self, who):
return self.greeting % {'name': self.name, 'who': who}

Yet another possibility is to go with metaclasses, but I won't give an
exemple here !-)
HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Sep 9 '05 #3

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

Similar topics

7
1644
by: David. E. Goble | last post by:
Hi all; I need to build a list of strings in one function and use the list in another function. ie buildlist(char list, FILE **infile); { int i;
4
4328
by: Bill Sun | last post by:
Hi, All I have a conventional question, How to create a 3 dimension array by C language. I see some declare like this: int *** array; int value; array = create3Darray(m,n,l);
2
2006
by: DaWoE | last post by:
Hi all, I'm fairly new to ASP.NET. What i want to do is creat a online registration form. On the first step is getting the users details and the number of people he wants to register. Based on the number of people i want to create a form where he can enter the persons details. For example he wants to register 3 people. Then the second step of the registration would have to be like this :
7
2153
by: Nobody | last post by:
Anyone have a clean way of solving this define issue? In Windows, there are sometimes unicode functions and multibyte functions... the naming convention used is FunctionA for multibyte and FunctionW for unicode... So basically what happens is: void FunctionA(); void FunctionW();
19
2410
by: Sensei | last post by:
Hi! I'm concerned about the legality of such a definition: #define funcX funcY where funcX belongs to the *standard* C functions. Is it legal to do this? The standard says "any function declared in a header may be additionally implemented as a macro defined in the header, so a library function should not be declared explicitly if its header is included". Is this applicable to standard functions? And, what if the definition
1
6454
by: saiyen | last post by:
Hey all, ive been banging my head agains the wall for a few days now, and finally decided to ask for help. i have a document that writes the header with all the javascript in it, then modifyes a <div> tag with a button. the button has an onClick event that is supposed to call a javascript function in the header. The whole application works wonderfully in Firefox, however it seems as if IE cannot/willnot call the function. if i put an alert in...
2
1315
by: barabenka | last post by:
I want to program general class for function nodes of factor graph…. Functions (I define them separately) can have different number of variables, for example f_A(x1,x2), f_B(x1, x2, x3)… Each variable may take different number of values, let say N1 for x1, N2 for x2…. In the program I need to build a table of all possible values of a function. If I knew the number of variables taken by function I would write something like this: //for...
0
883
by: JoppeG | last post by:
Hi. I have a slight problem with my database software. The thing is I have written code for a function to add a new "Tab" with a "plane" and a "DataGrid" grid for viewing database info. This is how some of the function code looks, public void AddNewDefaultDataGridTab( DataSet dynamicDataSet, string dynamicTable, string TabTitle, string columnFileToLoad) { //<code for making all look as it should.> }
28
6025
by: ravi | last post by:
Hello everybody, I am writing a small application which does some work before the user main function starts execution. I am trying to #define the main function. But the problem is that,
0
7920
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
8401
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
8404
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
8054
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
8268
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
3900
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...
1
2418
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
1
1510
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1254
bsmnconsultancy
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...

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.