Usually, when importing modules, they seem to put them in the top row like Source Code 2 rather than Source Code 1.
I don't think you need to import it to the top row if it's a module that's only used in this class, but do you import it from the top row? Is it because it's faster?
class SomeClass(object):
def not_often_called(self)
from datetime import datetime
self.datetime = datetime.now()
from datetime import datetime
class SomeClass(object):
def not_often_called(self)
self.datetime = datetime.now()
If you run the function to import modules from within multiple times, the modules are imported only once.
There is no difference in the number of times imported from the top of the module or from within the function.
And in fact, when importing from the top of the module, the compiler LOAD_GLOBAL
while LOAD_FAST
within the function, so importing from within the function is faster. (I compared the execution speed below)
Nevertheless, the reason for importing modules at the top is that the Python Style Guide PEP 08 - Imports recommends that you write so.
Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
import random
def f():
L = []
for i in xrange(1000):
L.append(random.random())
for i in xrange(1000):
f()
$ $ time python import.py
real 0m0.721s
user 0m0.412s
sys 0m0.020s
def f():
import random
L = []
for i in xrange(1000):
L.append(random.random())
for i in xrange(1000):
f()
$ $ time python import2.py
real 0m0.661s
user 0m0.404s
sys 0m0.008s
© 2024 OneMinuteCode. All rights reserved.