Erysol
Erysol

Reputation: 594

Clean importing of python submodules

I have an directory like this

test.py
foo/__init__.py
foo/bar.py

and in the bar.py a simple function:

def say_stuff()
    print("Stuff")

And want to call it from the Test.py like this:

import foo
foo.bar.say_stuff()

Then i get the following error:

AttributeError: module 'foo' has no attribute 'bar'

I know to at least fix that error by editing the __init __.py

from .bar import *

But then both of those approaches work:

foo.bar.say_stuff()
foo.say_stuff()

Now my question, how do i get only the foo.bar.say_stuff() to work. I dont want to load every thing into foo, already beacuse i want clean auto_complete suggestions from my IDE.

Is there any source you can recommend to properly learn pythons import system. All the tutaorals seem too basic and always run into unexpected behavior.

Upvotes: 1

Views: 70

Answers (1)

Felipe Calliari Ribas
Felipe Calliari Ribas

Reputation: 36

You just need to change from:

from .bar import *

to:

import foo.bar

This behavior is described here: https://docs.python.org/3/reference/import.html#submodules

Upvotes: 1

Related Questions