Python custom module name not defined
This is a surprisingly common issue and this question was still without an proper answer, so here we go.
Let's suppose we have a module only with functions inside, say:
file app/foo.py:
def a(): print('Hello from foo.a') def b(): print('Hello from foo.b')
I would genuinely expect this to work (but it DOESN'T):
file app/bar.py:
import app.foo # These will not work! foo.a() foo.b()
It turns out that you have to import each element explicitly or give app.foo
a name:
Import everything (usually considered a bad practice):
from app.foo import * # Both will work fine a() b()
Import only what you want:
from app.foo import b # This will work b() # But this will not a()
Give
app.foo
a (nice) name:import app.foo as baz # Both will work as expected baz.a() baz.b()
Even if the examples above use only functions, it works exactly the same for everything declared at the top most scope of the module, like classes or variables.
Hope it helps!
BSmith156
Updated on July 04, 2022Comments
-
BSmith156 almost 2 years
I have a custom package called 'package' and a custom module in that package called 'module' which has a function returning 'test' when called. When I import my package if I do:
from package import module
Everything works fine but if I do:
from package import *
Or
import package
Then when trying to use the 'module' module it comes up with an error name 'module' is not defined. Why is it not importing the module when I use import * or when I import the package?
The code in the module I am trying to call is this:
def printTest(): return("Test")
The code in the file calling the module is this:
import package print(module.printTest())
-
Maurice over 7 yearsCan you please show us the code the code in the
module
module andpackage
package and the way you are calling it? -
chickity china chinese chicken over 7 yearsprobably want to call it like
package.module.printTest()
-
BSmith156 over 7 years@Maurice just edited my post to include it
-
BSmith156 over 7 years@downshift This gives me an error module 'package' has no attribute 'module'.
-
Marvo over 7 yearsIf you want to import a function of a module in a package you can either write
from package.module import function
and usefunction()
or you can writeimport package.module as pm
and usepm.function()
. You cannot import all modules of a package with a single statement likeimport package
, this imports only the functions/methods of the file__init__.py
in the package directory. -
chickity china chinese chicken over 7 years@BSmith156 my apologies, closest thing to the syntax you're looking for I can think of is
from package.module import *
then you'd only useprint(printTest())
-
-
varagrawal almost 3 yearsYou could also do
from app import foo
, then thefoo.a()
will work as expected.