Do I have to write import on the top line of the code?

Asked 1 years ago, Updated 1 years ago, 110 views

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()

coding-style python optimization

2022-09-21 22:55

1 Answers

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


2022-09-21 22:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.