__init__.py file

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • cesco

    __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
  • Jeffrey Barish

    #2
    Re: __init__.py file

    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_ob ject or from dirA.dirB import
    my_object. I use the technique only with objects that are legitimately
    global.
    --
    Jeffrey Barish

    Comment

    Working...