'How to import other Python files
I have this file, abc.py
:
def asb():
print("Hello, ")
def xyz():
print("World!")
In my main.py
file,
from abc import asb
from abc import xyz
I want to import both asb
and abc
from abc.py
without using separate lines.
I assume it's going to be something like this:
from abc import asb and xyz
Solution 1:[1]
Taken from Python documentation:
There is a variant of the import statement that imports names from a module directly into the importing module’s symbol table. For example:
>>> from fibo import fib, fib2
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
In your case, this would be
>>> from abc import asb, xyz
If you need to import many functions, I would suggest using:
>>> import abc
>>> abc.asb()
>>> abc.xyz()
or, if your abc is too long, use an alias:
>>> import abc as m
>>> m.asb()
>>> m.xyz()
instead of:
>>> from abc import *
as this will pollute your namespace.
Solution 2:[2]
Use:
from abc import asb, xyz
Or to import all functions:
from abc import *
Do refer to websites. They give lots of examples. For example, Python – Call function from another file
Solution 3:[3]
You can separate your function names using comma—',
':
from datetime import datetime, date
So in your case, you will have:
from abc import asb, xyz
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | hwhap |
Solution 2 | Peter Mortensen |
Solution 3 | Peter Mortensen |