By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,907 Members | 2,039 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,907 IT Pros & Developers. It's quick & easy.

__init__.py file

P: n/a
Hi,

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).

Many thanks
Francesco
Apr 8 '08 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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

Apr 9 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.