How do I import all functions from a package in python?

11,353

Pretty easy

__init__.py:

from simupy.blk import *
from simupy.info import *

Btw, just my two cents but it looks like you want to import your package's functions in __init__.py but perform actions in __main__.py.

Like

__init__.py:

from simupy.blk import *
from simupy.info import *

__main__.py:

from simupy import *

# your code
dir_path = ....

It's the most pythonic way to do. After that you will be able to:

  • Run your script as a proper Python module: python -m simupy
  • Use your module as library: import simupy; print(simupy.bar())
  • Import only a specific package / function: from simupy.info import bar.

For me it's part of the beauty of Python..

Share:
11,353

Related videos on Youtube

Tian
Author by

Tian

Reminded of humility, appreciating the community

Updated on September 16, 2022

Comments

  • Tian
    Tian over 1 year

    I have a directory as such:

    python_scripts/
         test.py
         simupy/
              __init__.py
              info.py
              blk.py
    

    'blk.py' and 'info.py are modules that contains several functions, one of which is the function 'blk_func(para)'.

    Within '__init__.py' I have included the following code:

    import os
    dir_path = os.path.dirname(os.path.realpath(__file__))
    
    file_lst = os.listdir(dir_path)
    filename_lst = list(filter(lambda x: x[-3:]=='.py', file_lst))
    filename_lst = list(map(lambda x: x[:-3], filename_lst))
    filename_lst.remove('__init__')
    
    __all__ = filename_lst.copy()
    

    I would like to access the function 'blk_func(para)', as well as all other functions inside the package, within 'test.py'. Thus I import the package by putting the following line of code in 'test.py':

    from simupy import*
    

    However, inorder to use the function, I still have to do the following:

    value = blk.blk_func(val_param)
    

    How do I import the package simupy, such that I can directly access the function in 'test.py' by just calling the function name? i.e.

    value = blk_func(val_para)
    
  • Tian
    Tian almost 6 years
    Is there a way to import the modules in __init__.py in a non-explicit fashion? Say I have many modules in the simupy package, and that it would be too troublesome to type "from simupy.module import *" for every module
  • Arount
    Arount almost 6 years
    There are, but I cannot tell you it's a good practice, lot of well designed libraries import all modules by hand, it's ok