YJZ
YJZ

Reputation: 4214

python import module for code in another py file

Hi I store user defined functions in a separte file my_functions.py. E.g.,

#my_functions.py
def some_func():
    sleep(1)
    print(1)

And the main code in another file main.py:

#main.py
from time import sleep
from my_functions import *

some_func()

When I run main.py, I have error that sleep is not define. It seems things imported from my_functions.py doesn't know about from time import sleep

Should I import time module in my_funcions.py?

I feel confused, cause I thought only some_func is imported, and if I write from time import sleep in my_functions.py, this sentence won't get executed...

And more general advice about how to store user defined functions is appreciated. Thanks

Upvotes: 4

Views: 142

Answers (2)

Guoliang
Guoliang

Reputation: 895

Yes, you should import the time module in my_functions.py. hope this helps you understanding how import works:

Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs). The first form (without from) repeats these steps for each identifier in the list. The form with from performs step (1) once, and then performs step (2) repeatedly. https://docs.python.org/2.0/ref/import.html

Here is a style guide from PEP008 about import

Upvotes: 1

python必须死
python必须死

Reputation: 1089

from time import sleep
#my_functions.py
def some_func():
    sleep(1)
    print(1)

You need to import the function in the file/module where you use it.

Upvotes: 1

Related Questions