Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

python - I simply want to know why is the code printing the the string even though i am only importing the function inside the module

my_module.py

    
print('Module Imported...')

test = 'Test String'


def find_index(to_search, target):
    '''Find the index of a value in a sequence'''
    for i, value in enumerate(to_search):
        if value == target:
            return i
    return 'none'

intro.py

from my_module import find_index

courses = ['Math', 'Arts', 'History', 'English']

index = find_index(courses, "History")
print(index)

When running this the result is:

Module Imported...
2

I want to know why is my program printing the 'Module Imported...' string even though I am only importing the find_index function.

question from:https://stackoverflow.com/questions/65852381/i-simply-want-to-know-why-is-the-code-printing-the-the-string-even-though-i-am-o

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you import from a module, only the names that you specify are bound in the importing scope, but all of the top level code in that module is executed.

This is important because some of the names that you import might depend on code that you didn't explicitly import -- for example, that module's own imports, the definitions of private functions/classes/objects that the exported functions depend on, etc! It would be extremely unwieldy if you had to understand all of the dependencies of the module you're importing and explicitly import each dependency to make sure that the things you're actually trying to use will work correctly.

Needless to say, you should not have top-level module code that you don't want to get executed on every import. This is why you'll often see blocks in scripts like:

if __name__ == '__main__':
    # actually do stuff

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...