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
Share:
24,231
shayms8
Author by

shayms8

Updated on July 09, 2022

Comments

  • shayms8
    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 * AND from 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
      Sohaib Farooqi over 6 years
      you can do import a and then call function a.x()
    • donkopotamus
      donkopotamus over 6 years
      from a import * should work fine, unless you have, for example, defined __all__ in a somehow. If that is not the case then we'll need more information.
  • roganjosh
    roganjosh over 6 years
    How does this relate to the question? Why does from a import x work and not from a import *?.
  • Saelyth
    Saelyth over 6 years
    it 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
    roganjosh over 6 years
    Actually, you're right. import * is not a good idea but I'm curious as to why it doesn't work in this case.
  • Saelyth
    Saelyth over 6 years
    I 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/…