__init__.py file

Jeffrey Barish jeff_barish at earthlink.net
Wed Apr 9 09:33:22 EDT 2008


cesco wrote:
> 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).

I do this and find the technique fantastically convenient.  You don't
explain what problems you encountered -- or perhaps I don't understand what
you mean by using the instances "directly" -- but here's what I do: In
dirA/dirB/__init__.py, I import my_object to import the my_object.py
module.  I then instantiate an object in __init__.py.  (Note that it is a
singleton because Python imports modules only once.)  Import the object in
file{1,2}.py with import dirA.dirB.my_object or from dirA.dirB import
my_object.  I use the technique only with objects that are legitimately
global.
-- 
Jeffrey Barish




More information about the Python-list mailing list