I'm going to incorporate many of the comments already posted.
To have access to function
without having to refer to the module my_file
, you can do one of the following:
from my_file import function
or
from my_file import *
For a more in-depth description of how modules work, I would refer to the documentation on python modules.
The first is the preferred solution, and the second is not recommended for many reasons:
- It pollutes your namespace
- It is not a good practice for maintainability (it becomes more difficult to find where specific names reside.
- You typically don't know exactly what is imported
- You can't use tools such as pyflakes to statically detect errors in your code
Python imports work differently than the #includes/imports in a static language like C or Java, in that python executes the statements in a module. Thus if two modules need to import a specific name (or *) out of each other, you can run into circular referencing problems, such as an ImportError
when importing a specific name, or simply not getting the expected names defined (in the case you from ... import *
). When you don't request specific names, you don't run into the, risk of having circular references, as long as the name is defined by the time you actually want to use it.
The from ... import *
also doesn't guarantee you get everything. As stated in the documentation on python modules, a module can defined the __all__
name, and cause from ... import *
statements to miss importing all of the subpackages, except those listed by __all__
.