469,293 Members | 1,335 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,293 developers. It's quick & easy.

__init__.py file

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
1 4554
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.

Similar topics

3 posts views Thread by Gary Wilson Jr | last post: by
3 posts views Thread by Daniel Schüle | last post: by
3 posts views Thread by Sandro Dentella | last post: by
6 posts views Thread by Rob Cowie | last post: by
3 posts views Thread by Luis P. Mendes | last post: by
25 posts views Thread by Erik Lind | last post: by
1 post views Thread by Ryan Krauss | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
1 post views Thread by Geralt96 | last post: by
reply views Thread by harlem98 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.