473,786 Members | 2,611 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

What's the best way to iniatilize a function

I have a set of functions to wrap a library. For example,

mylib_init()
mylib_func()
mylib_exit()

or

handle = mylib_init()
mylib_func(hand le)
mylib_exit(hand le)

In order to call mylib_func(), mylib_init() has to be called once.
When it's done, or when program exits, mylib_exit() should
be called once to free resources.

I can list all three functions in a module and let the
application manage the init call and exit call. Or, better,
to have the wrapper function manage these calls. I'm currently
using a singleton class (see below.) It seems to work fine.

My questions here are:

1. every time I call the function:

MyLib().func()

part of the object creation code is called, at least to check if
there is an existing instance of the class, then return it. So it
may not be very efficient. Is there a better way?

2. what's the right way to call mylib_exit()? I put it in __del__(self)
but it is not being called in my simple test.
STATUS_UNINITIA LIZED = 0
STATUS_INITIALI ZED = 1
STATUS_ERROR = 2

class MyLib (object):
instance = None
status = STATUS_UNINITIA LIZED

def __new__(cls, *args, **kargs):
if cls.instance is None:
cls.instance = object.__new__( cls, *args, **kargs)
return cls.instance

def __init__(self):
if self.status == STATUS_UNINITIA LIZED:
mylib_init()
self.status = STATUS_INITIALI ZED

def func(self):
return mylib_func()

def __del__(self):
mylib_exit()
May 27 '07 #1
6 1426
On Sun, 27 May 2007 10:51:46 -0700, Jack wrote:
I have a set of functions to wrap a library. For example,

mylib_init()
mylib_func()
mylib_exit()

or

handle = mylib_init()
mylib_func(hand le)
mylib_exit(hand le)

In order to call mylib_func(), mylib_init() has to be called once.
When it's done, or when program exits, mylib_exit() should
be called once to free resources.

Sounds like a module to me.

Write it as a module. Python will call your initialization code, once, the
first time you import it. Python will handle the garbage collection of
your resources when your module goes away. Modules are automatically
singletons.
# mylib wrapper(?) module
# Initialize a bunch of data
DATA = range(1000000)

def func():
return DATA[0] # or something useful...
Note that mylib.func() doesn't need to check that it is initialized,
because if it isn't, it can't be called! That is to say, if some of your
initialization code fails, an exception will be raised and the module will
not be imported.

Note two gotchas:

(1) Python can automatically free most data structures and close open
files, but if your needs are more sophisticated, this approach may not be
suitable.

(2) Module imports are cached. Calling "import mylib" imports the module,
but calling "del mylib" doesn't free it because of the cache.

Calling "del mylib; del sys.modules['mylib']" should remove the cache,
allowing Python's normal garbage collection to free your resources, but
note the above caveats regarding the types of resources that Python can
automatically free.
I can list all three functions in a module and let the
application manage the init call and exit call. Or, better,
to have the wrapper function manage these calls. I'm currently
using a singleton class (see below.) It seems to work fine.

Why do you care that it is a singleton? Surely the important thing is that
all the instances share the same state, not that there is only one
instance?

The easiest way to ensure all instances share the same state is to put all
the data you care about into class attributes instead of instance
attributes:
class MyLib(object):
DATA = range(100000) # initialized when the class is defined
def func(self):
return self.DATA[0]

Note that there are no __init__ or __new__ methods needed.

If you don't want the (trivial) expense of creating new instances just to
call the func method, use a class method that doesn't need an instance:

class MyLib(object):
DATA = range(100000) # initialized when the class is defined
@classmethod
def func(cls):
return cls.DATA[0]
See also the source to the random module for another way to expose a
class-based interface as if it were a set of functions.
My questions here are:

1. every time I call the function:

MyLib().func()

part of the object creation code is called, at least to check if
there is an existing instance of the class, then return it. So it
may not be very efficient. Is there a better way?
Yes. The caller should save the instance and reuse it, the same as any
other expensive instance:

obj = MyLib()
obj.func()
obj.func()

2. what's the right way to call mylib_exit()? I put it in __del__(self)
but it is not being called in my simple test.
instance.__del_ _ is only called when there are no references to the
instance.

instance = MyLib()
another = instance
data = [None, 1, instance]
something = {"key": instance}
del another # __del__ will not be called, but name "another" is gone
del instance # __del__ still not called, but name "instance" is gone
data = [] # __del__ still not called
something.clear () # now __del__ will be called!
It isn't easy to keep track of all the places you might have a reference
to something, but Python can do it much better than you can.
--
Steven.

May 27 '07 #2
Thanks Steven, for the reply. Very helpful. I've got a lot to learn in
Python :)

Some questions:
(1) Python can automatically free most data structures and close open
files, but if your needs are more sophisticated, this approach may not be
suitable.
Since it's a wrapper of a DLL or .so file, I actually need to call
mylib_exit()
to do whatever cleanup the library needs to do.
>2. what's the right way to call mylib_exit()? I put it in __del__(self)
but it is not being called in my simple test.

instance.__del_ _ is only called when there are no references to the
instance.
I didn't call del explicitly. I'm expecting Python to call it when
the program exits. I put a logging line in __del__() but I never
see that line printed. It seems that __del__() is not being called
even when the program exits. Any idea why?
May 28 '07 #3
Jack schrieb:
I didn't call del explicitly. I'm expecting Python to call it when
the program exits. I put a logging line in __del__() but I never
see that line printed. It seems that __del__() is not being called
even when the program exits. Any idea why?

http://effbot.org/pyfaq/my-class-def...the-object.htm

better solutions:

http://docs.python.org/ref/try.html
http://docs.python.org/whatsnew/pep-343.html

Gregor
May 28 '07 #4
On Mon, 28 May 2007 11:01:26 +0200, Gregor Horvath wrote:
Jack schrieb:
>I didn't call del explicitly. I'm expecting Python to call it when
the program exits. I put a logging line in __del__() but I never
see that line printed. It seems that __del__() is not being called
even when the program exits. Any idea why?


http://effbot.org/pyfaq/my-class-def...the-object.htm

better solutions:

http://docs.python.org/ref/try.html
http://docs.python.org/whatsnew/pep-343.html

They might be better solutions, but not for the Original Poster's problem.

The O.P. has a library that has to hang around for long time, not just a
call or two, and then needs to be closed.

try...except and with define *blocks of code*, not long-lasting libraries
with data, functions, etc. Maybe you could shoe-horn the O.P.'s problem
into a with block, but the result would surely be ugly and fragile.

--
Steven.

May 28 '07 #5
On Sun, 27 May 2007 23:20:49 -0700, Jack wrote:
Thanks Steven, for the reply. Very helpful. I've got a lot to learn in
Python :)

Some questions:
>(1) Python can automatically free most data structures and close open
files, but if your needs are more sophisticated, this approach may not be
suitable.

Since it's a wrapper of a DLL or .so file, I actually need to call
mylib_exit()
to do whatever cleanup the library needs to do.
Well, there may be better ways, but I'd do something like this:
# === mylib module ===

# Exception raised if library is not initiated
class Uninitiated(Exc eption):
pass
def _init():
"""Private set-up code."""
global DATA, _INITIALIZED
DATA = range(100000) # or something more useful
_INITIALIZED = True

def _close():
"""Private tear-down code."""
global DATA, _INITIALIZED
del DATA, _INITIALIZED

def isinited():
"""Return True if the library is initialized, otherwise False."""
try:
_INITIALIZED; return True
except NameError:
return False

def init():
"""Public set-up code."""
if not isinited(): _init()

def close():
"""Public tear-down code."""
if isinited(): _close()

exit = close # alias for exit/close.
def func():
if isinited():
return DATA[0]
else:
raise Uninitiated("Li brary is not initialized")
All of the above can be modified to be in a class instead of a module.
That's especially useful if you can have multiple instances, perhaps with
different state.
>>2. what's the right way to call mylib_exit()? I put it in __del__(self)
but it is not being called in my simple test.

instance.__del __ is only called when there are no references to the
instance.

I didn't call del explicitly. I'm expecting Python to call it when
the program exits. I put a logging line in __del__() but I never
see that line printed. It seems that __del__() is not being called
even when the program exits. Any idea why?
Python tries really really hard to call instance.__del_ _() but there are
pathological cases where it just can't. Maybe you've found one of them.

But I'm guessing that you may have defined a __del__ method, but not
actually created an instance. If so, __del__ will never be called.

This should work:

class Foo(object):
def __del__(self):
print "All gone now"

instance = Foo()
When you exit, instance will be garbage collected and instance.__del_ _()
will be called. But without the instance, __del__ is not called on the
class directly.
Hope this was some help,
--
Steven.

May 28 '07 #6
Jack wrote:
>>2. what's the right way to call mylib_exit()? I put it in __del__(self)
but it is not being called in my simple test.

instance.__del __ is only called when there are no references to the
instance.

I didn't call del explicitly. I'm expecting Python to call it when
the program exits. I put a logging line in __del__() but I never
see that line printed. It seems that __del__() is not being called
even when the program exits. Any idea why?
If you make your extension available as a module (Python or C), you can use
atexit: http://docs.python.org/lib/module-atexit.html

Note: your exit handler will only be called at normal termination.

May 28 '07 #7

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

Similar topics

699
34241
by: mike420 | last post by:
I think everyone who used Python will agree that its syntax is the best thing going for it. It is very readable and easy for everyone to learn. But, Python does not a have very good macro capabilities, unfortunately. I'd like to know if it may be possible to add a powerful macro system to Python, while keeping its amazing syntax, and if it could be possible to add Pythonistic syntax to Lisp or Scheme, while keeping all of the...
226
12709
by: Stephen C. Waterbury | last post by:
This seems like it ought to work, according to the description of reduce(), but it doesn't. Is this a bug, or am I missing something? Python 2.3.2 (#1, Oct 20 2003, 01:04:35) on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> d1 = {'a':1} >>> d2 = {'b':2} >>> d3 = {'c':3}
125
14855
by: Sarah Tanembaum | last post by:
Beside its an opensource and supported by community, what's the fundamental differences between PostgreSQL and those high-price commercial database (and some are bloated such as Oracle) from software giant such as Microsoft SQL Server, Oracle, and Sybase? Is PostgreSQL reliable enough to be used for high-end commercial application? Thanks
11
2572
by: modemer | last post by:
If I define the following codes: void f(const MyClass & in) {cout << "f(const)\n";} void f(MyClass in) {cout<<"f()\n";} MyClass myclass; f(myclass); Compiler complain that it can't find the best match. Anyone could give a detail explanation in theory? Which one is good?
4
2474
by: atv | last post by:
Whatis the proper way to handle errors from function calls? For example, i normally have a main function, with calls to mine or c functions. Should i check for errors in the functions called themselves, or should i return a code to main and handle the error there? If i don't return them to main, except for the structure, what use is the main function except for calling functions?
51
4567
by: jacob navia | last post by:
I would like to add at the beginning of the C tutorial I am writing a short blurb about what "types" are. I came up with the following text. Please can you comment? Did I miss something? Is there something wrong in there? -------------------------------------------------------------------- Types A type is a definition for a sequence of storage bits. It gives the meaning of the data stored in memory. If we say that the object a is an
22
5650
by: vietor.liu | last post by:
is this? int hashpjw(char* str,int size) { unsigned long h=0,g; for(unsigned char *p=(unsigned char*)str;*p;++p) { h=(h<<4)+*p; if(g=(h&0xf0000000)) {
8
2495
by: johnsonholding | last post by:
Here is the code for a pop-up window that works in Firefox and not in IE - I get a java error or something, Here is the code : </script> <SCRIPT language="JavaScript" type="text/javascript"> <!-- ; var newwindow = ''
8
13062
by: werner | last post by:
Hi! I don't want to use eval() in order to parse a user-supplied formula. What alternatives do I have? PHP has no standard functionality for tokenizing or parsing expressions in this regard. Here is a simple example: The user supplies the following formula in string format, "a = (6+10)/4", and the script needs to find out what the value of 'a' is.
0
9650
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
10363
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
10164
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
9962
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...
1
7515
isladogs
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...
0
6748
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
5398
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
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
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.