[Python-ideas] [Python-Dev] If you shadow a module in the standard library that IDLE depends on, bad things happen

Chris Angelico rosuav at gmail.com
Sun Nov 1 10:24:37 EST 2015


On Mon, Nov 2, 2015 at 2:06 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Mon, Nov 02, 2015 at 12:44:27AM +1100, Chris Angelico wrote:
>> On Mon, Nov 2, 2015 at 12:25 AM, Alexander Walters
>> <tritium-list at sdamon.com> wrote:
>> >   If you are worrying about shadowing ONLY the standard library - guess
>> > what?  those names don't change often, and are well known.  Don't use those
>> > names.
>>
>> Well known? Okay. No cheating now! Which of these names will shadow
>> something from the standard library, and which don't?
>>
>> code.py
>> cgi.py
>> chunk.py
> [...]
>
> Does it matter? It really only matters if you shadow something that gets
> imported.
>
> It's not exactly great practice to name your script "code.py", but if
> you do, and it doesn't directly or indirectly try to import the code
> library, it's harmless. That's why it is harmful to present users with
> an alert (which they won't read) warning them that they're shadowing a
> stdlib module.

It matters under two circumstances:

1) Currently, if the stdlib module ends up getting imported *even
indirectly* by something you use. The indirect import is the subtle
one here.

2) Under the proposal to reorder sys.path, if you want to import
*your* module, you wouldn't be able to.

I'm responding to the suggestion that the standard library names are
"well known" to the point where people can be told not to use them. I
say they are not; sure, everyone knows that 'sys.py' would be a bad
name, and you wouldn't call your module "pprint.py" unless you
deliberately want to shadow the normal standard library module, but
there are a lot that are more obscure. Suppose you start learning
about Python's data types, and you create a "types.py" that lets you
play with strings, integers, floats, and so on. Then, in the next
lesson, you meet enumerations, and enum.py.

$ touch types.py; python3 -c "import enum"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/local/lib/python3.6/enum.py", line 2, in <module>
    from types import MappingProxyType, DynamicClassAttribute
ImportError: cannot import name 'MappingProxyType'

Tell me, is this an implausible scenario? Should a person just
learning about Python's type system have to also learn not to use the
name "types.py"?

ChrisA


More information about the Python-ideas mailing list