Volume of imported modules / functions in Python

I am new here and not 100% sure how to ask this question, so I’ll just dive right in. Should I use import statements at the beginning of every function that I write, import all the various modules / functions that I need for this function? i.e.

def func1()
    import os.path
    print func(2)
    do something with os.path

def func2()
    import os.path
    do something with os.path

Will this increase memory overhead or other overhead, or will the import statement simply match the local name with the already loaded object? Is there a better way to do this? (Links to tutorials, etc. are welcome. I have been looking for some time, but cannot find a good answer to this question.)

+3
source share
2 answers

; . - , ; . PEP 8.

+6

. import :

def f():
    import sys
    print 'f', sys.version_info

def g():
    print 'g', sys.version_info

if __name__ == '__main__':
    f() # will work
    g() # won't work, since sys hasn't been imported into this modules namespace
+10

Source: https://habr.com/ru/post/1787610/


All Articles