chrisyeh96 / chrisyeh96.github.io

Personal website
https://chrisyeh96.github.io
MIT License
21 stars 22 forks source link

module import precedence mistake in the Python imports article #2

Closed etene closed 6 years ago

etene commented 6 years ago

Hello,

First of all excuse me if this isn't the right place to post this, i didn't really know how to get in touch so I figured a Github issue would be the best way to do it.

I was reading your post regarding imports (https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html), which I found instructive & well written, but there's a small point I think is wrong.

Here's the excerpt:

The Python documentation goes on to mention the following:

The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory.

This seems to be a mistake. For example, calling import math in start.py will import the standard math module, NOT my own math.py file in the same directory.

The documentation is correct: the described behavior applies to modules in the standard library directory. The math module is a builtin module (like the sys module), guaranteed to be always available, and thus not implemented as a separate Python file in the standard library.

If you name your own module argparse for example, it will indeed have precedence over the argparse module in the standard library.

Hope I was clear, and thanks again for your excellent post. Cheers !

chrisyeh96 commented 6 years ago

Thanks for pointing this out! I was unaware of the difference between built-in modules and other modules in Python's standard library until now. I have updated the post.

memocong commented 4 years ago

@chrisyeh96 ,thanks a lot for your well-organized and instructive post regarding python import. For module import precedence on built-in modules , similar to this question, it's proved on my computer (MacOS Mojave, python 3.6/3.7) that math is not in _sys.builtin_modulenames and the math.py file in my working directory will be imported before builtin module math. So, I think only those "builtin modules" in _sys.builtin_modulenames have precedence over the directory containing the script.

ps: here, builtin modules refer to those

Some modules are written in C and built in to the Python interpreter

. reference python doc.

Below is the output information of math module. ` >>> import math

>>> math

<module 'math' from '/Users/xxxx/.pyenv/versions/3.6.5/lib/python3.6/lib-dynload/math.cpython-36m-darwin.so'> `