简体   繁体   中英

Python imported module dependency

Let's say I have file main.py :

import math
import mymodule.py
print(math.ceil(5/3))

and then mymodule.py :

print(math.ceil(10/3))

mymodule.py gives an error that math is not defined, even though its parent module has it imported.

Considering both main.py and mymodule.py need to use the math lib, do I need to import it twice? It just seems non-optimal. What's the most pythonic way to solve this issue?

I know it's a dumb example, but I'm trying to fragment a code I made into several modules for organization, and this issue appeared multiple times in several levels

mymodule.py is parent for main.py since you are importing mymodule within main .
You need to import math within mymodule so that it gets inherited in main .
Then there won't be a need to import within main .

mymodule.py

import math

main.py

import  mymodule
print mymodule.math.pow(10,2)

Result:

>>> 
100.0
>>> 

This is really very basic. If you have something in a separate file, like mymodule.py, then you can import that function in any python file easily in the same directory.

two files:

mymodule.py:

import math

def aFunc():
    return math.ceil(10/3)


# We could also just use this file as a standalone
if __name__ == "__main__":
    print(aFunc())

main.py:

import mymodule

print(mymodule.aFunc())

You could also specifically call out the function you want to import.

main.py (alternative):

from mymodule import aFunc

print(aFunc())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM