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)
The import statement You can use the functions inside a module by using a dot(.) operator along with the module name. First, let's see how to use the standard library modules. In the example below, math module is imported into the program so that you can use sqrt() function defined in it.
You can import multiple functions, variables, etc. from the same module at once by writing them separated by commas.
importlib allows you to import any Python module from a string name. You can automate it with going through the list of files in the path. It's more pythonic to use __all__ . Check here for more details.
You can import all the code from a module by specifying the import keyword followed by the module you want to import. import statements appear at the top of a Python file, beneath any comments that may exist. This is because importing modules or packages at the top of a file makes the structure of your code clearer.
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:
python -m simupy
import simupy; print(simupy.bar())
from simupy.info import bar
.For me it's part of the beauty of Python..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With