It’s easy to import only parts of a package in Python. You can import a particular module (file) from a package, or particular classes, functions or constants (variables) from a module.
The syntax looks the same or similar in all of these cases.
Consider this module:
mystuff/mymodule.py
def greet():
print("Hello")
def another_function():
print("Zzzzzzz")
def main():
greet()
if __name__ == "__main__":
main()
If we want to import only the greet function, we can do this:
from mystuff.mymodule import greet
greet()
output:
Hello
Import Examples
The following are all valid import statements, given the above code.
from mystuff.mymodule import greet as g
from mystuff import mymodule as mm
from mystuff.mymodule import greet as g, another_function as func
g()
mm.greet()
func()
output:
Hello
Hello
Zzzzzzz
Leave a Reply