0

I'm working on a GUI app. Let's say that I have a file main.py which is in the root directory and I want to import widgets like this:

from widgets import FancyWindow, ColorPicker
# ...

And my app is structured like so:

| main.py
+ widgets/
    | __init__.py
    | fancy_window.py
    | color_picker.py
...

IIRC, I would have to import classes from the other modules like so:

from widgets.color_picker import ColorPicker
from widgets.fancy_window import FancyWindow

So my question is if there is something I can do in widgets/__init__.py to make it so that I can do imports in the way I want to?

1
  • In widgets/__init__.py import the things you want to be available in the widget package's namespace. i.e. from fancy_window import FancyWindow. Commented Aug 6, 2014 at 19:13

4 Answers 4

1

You actually have it there already, just make your __init__.py have those two lines:

from widgets.color_picker import ColorPicker
from widgets.fancy_window import FancyWindow

Anything that you import (and any other symbols you define) in __init__.py will then be available.

E.g. if you put:

apple = 5

in __init__.py you could also do: from widgets import apple. No magic :)

Sign up to request clarification or add additional context in comments.

2 Comments

This is the one that worked for me. But there is still a little odd issue. If I try to do a from widgets import * in main.py, I'll get an error from importlib telling me TypeError: hasattr(): attribute name must be string. But if I don't do the star and give the actual name of the widget I want, there is no error.
@Benjamin you'd need to post more code/context for that one - maybe open a different question?
1

In __init__.py you can import the modules, then export them:

from fancy_window import FancyWindow
from color_picker import ColorPicker

__all__ = [FancyWindow, ColorPicker]

Now, you can do the following:

from widgets import * # Only imports FancyWindow and ColorPicker
from widgets import FancyWindow
from widgets import ColorPicker
import widgets
color_picker = widgets.ColorPicker()

Comments

1

The best way would be to use __init__.py to perform setups needed for the package.

# __init__.py
from fancy_window import FancyWindow
from color_picker import ColorPicker

Then in main.py you can perform imports directly.

# main.py
from widgets import FancyWindow, ColorPicker

A more convenient way to package everything in __init__.py

# __init__.py
from fancy_window import *
from color_picker import *

Comments

0

yes, by adding the public variables of the other modules to __all__ in __init__.py
see https://docs.python.org/3/reference/simple_stmts.html#import

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.