Reputation: 659
Say I have a package "colorExtentions" and in my __init__.py
I have __all__=["red", "blue"]
. This package should be able to be extended automatically by adding modules to the directory and to the __all__
list. Is the following acceptable or is there another "best practice" for such kind of things?
import colorExtentions
from colorExtentions import *
for moduleName in colorExtentions.__all__:
colors.append(moduleName)
promptUserToChoose(colors)
Upvotes: 0
Views: 247
Reputation: 88997
Presuming that each colour is a class, I would argue the nicer solution would be to ensure all of your colours subclass from a single class (which is good design anyway):
class Color:
...
Then, when you want a list of all colours, you can simply import any modules that will contain the classes, and do:
from colorExtentions import *
colors = Color.__subclasses__()
This way you end up with a list of each Color
subclass.
Note in 2.x, you will need new-style classes (inheriting from object
) to have the __subclasses__()
method available.
Upvotes: 3
Reputation: 4062
Importing all names from modules are discouraged in the official Python documentation. See:
http://docs.python.org/2/howto/doanddont.html#from-module-import
Quote:
When It Is Just Fine
There are situations in which from module import * is just fine:
- The interactive prompt. For example, from math import * makes Python an amazing scientific calculator.
- When extending a module in C with a > module in Python.
- When the module advertises itself as from import * safe.
If you insist of using __all__
- use some other name, like color_list
, and extend that variable dynamically. Then import that variable:
import colorExtentions
from colorExtentions import color_list
colors.extends(color_list)
Upvotes: 0