All Articles

Tips of Python Import

python-import

The import statement is a statement used to load modules in python. It can load system modules or user-defined modules. When a module with the same name exists, generally, the user module would be taken first.

I wrote a small program to sample a batch of random numbers yesterday.

But when I accidentally named the file “random.py”, and I used an “import random” statement to load the system library inside it, the python executor showed that no related functions could be found.

$ python random.py
Traceback (most recent call last):
  File "random.py", line 1, in <module>
    import random
  File "./random.py", line 3, in <module>
    random.seed()
AttributeError: 'module' object has no attribute 'seed'

Later, I recalled the problem of the same name. I listed the files under the same path and found that there was a “random.pyc” file listed, indicating that the python executor was loading the “python.py” file itself when executing “import random”, instead of loading the system library.

After deleting “random.pyc” and renaming the script, the problem has been resolved :)

$ python rand.py
0.57140259469

Published Nov 21, 2011

Flying code monkey