Home > Back-end >  How to import other Python files
How to import other Python files

Time:12-21

file abc.py
def asb():
  print("hellow")

def xyz():
  print("World")

in file main.py

from abc import asb

from abc import xyz

asb()

xys()

can i import both function only one line e.g. something like his...

from abc import asb and xyz

thanks :)

CodePudding user response:

from abc import asb, xyz

Or to import all functions:
from abc import *

Do refer to websites. They give lots of examples.
For e.g. https://www.geeksforgeeks.org/python-call-function-from-another-file/

CodePudding user response:

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

CodePudding user response:

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.

  • Related