__init__.py file

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Apr 9 06:55:43 CEST 2008

En Tue, 08 Apr 2008 17:51:21 -0300, cesco <fd.calabrese at gmail.com>  

> I need to instantiate an object (my_object) whose methods I have to
> use in two files (file1.py and file2.py) which are in the same
> directory. Is it possible to instantiate such object in the
> __init__.py file and then directly use it in file1.py and file2.py?
> If not, as I seem to experience, what is the best practice to follow
> in this case? (I thought __init__.py was somehow useful for that).

Yes, you can, but consider passing the object as an argument. Global  
objects aren't necesarily evil, anyway I don't have enough information to  
make an opinion.

If you insist on use the global object, there is another question.  
__init__.py defines the package namespace, and is the public interfase to  
it, I would not put an object there that is not supposed to be part of the  
package public interfase. You can instantiate the object in any other  
module, and import such module from both file1 and file2.

Gabriel Genellina

More information about the Python-list mailing list