Python import class in __init__.py from file in the same package

I feel like I should know this by programming in Python as much as I have, but I am constantly learning new things about the beautiful lanuaguge. The question I have (which may very well be a duplicate, however I haven't been able to find the same case) is this. I have a file layout like this:

websocket/
    __init__.py
    client.py
    server.py

      

How can I import the classes that are in the file __init__.py

from client.py

or server.py

? Nice and simple: P Thanks in advance! My question is not a duplicate of this , because I am importing from within the package, and anyway, doing what the people in the answer were doing didn't help at all.

+3


source to share


1 answer


The names defined in the package file __init__.py

are available as names in the package namespace itself.

So if you have a class Connection

in your package __init__

, from that package you import it just as if you were using your package: refer to it by package name, as in

from websocket import Connection

      



If for some reason your package is not configured in your pythonpath, or your directory name might change, you can use relative imports - in that case refer to the current package in the same way .

that in yours client.py

you can simply do:

from . import Connection

      

+1


source







All Articles