Import functions from one python file to another
24,231
You can import a file and then use the functions on that file using the import name before the function name.
import example #this import the entire file named example.py
example.myfunction() #this call a function from example file
Author by
shayms8
Updated on July 09, 2022Comments
-
shayms8 almost 2 years
Say i have a python file called
a.py
with the functions x,y,z.I want to import them to a new file called
b.py
I tried:
from a import *
ANDfrom a import all
with no luck.I can just do it separately:
from a import x
,from a import y
....How can i import them ALL at once?
-
Sohaib Farooqi over 6 yearsyou can do
import a
and then call functiona.x()
-
donkopotamus over 6 years
from a import *
should work fine, unless you have, for example, defined__all__
ina
somehow. If that is not the case then we'll need more information.
-
-
roganjosh over 6 yearsHow does this relate to the question? Why does
from a import x
work and notfrom a import *
?. -
Saelyth over 6 yearsit imports all functions of a file to be used from a different file. And as bonus I added the proper way to call those imported functions. That covers the entire question O,o
-
roganjosh over 6 yearsActually, you're right.
import *
is not a good idea but I'm curious as to why it doesn't work in this case. -
Saelyth over 6 yearsI am not sure. Is hard to tell without checking the real code. It might be that * is for modules or packages, while the OP may not have a
__init__
in there and just a simple .py file with a method or two in no particular order. I need to research this also as I never seen that behaviour before (never tried to be honest). Edit: found this stackoverflow.com/questions/2360724/…