[Python-ideas] Prevent importing yourself?

Andrew Barnert abarnert at yahoo.com
Fri Jan 29 19:16:46 EST 2016


On Jan 29, 2016, at 15:42, Sjoerd Job Postmus <sjoerdjob at sjec.nl> wrote:
> 
> What I experienced was having collisions on the python-path, and modules
> from my codebase colliding with libraries in the stdlib (or outside it).
> For example, a library might import one of its dependencies which
> coincidentally had the same name as one of the libraries I have.

Yes. The version of this I've seen most from novices is that they write a program named "json.py" that imports and uses requests, which tries to use the stdlib module json, which gives them an AttributeError on json.loads.

(One of my favorite questions on StackOverflow came from a really smart novice who'd written a program called "time.py", and he got an error about time.time on one machine, but not another. He figured out that obviously, requests wants him to define his own time function, which he was able to do by using the stuff in datetime. And he figured out the probable difference between the two machines--the working one had an older version of requests. He just wanted to know why requests didn't document this new requirement that they'd added. :))

> Maybe a suggestion would be to add the path of the module to the error
> message?

That would probably help, but think about what it entails:

Most AttributeErrors aren't on module objects, they're on instances of user-defined classes with a typo, or on None because the user forgot a "return" somewhere, or on str because the user didn't realize the difference between the string representation of an object and the objects, etc.

To make matters worse, AttributeError objects don't even carry the name of the object being attributed, so even if you wanted to make tracebacks do some magic if isinstance(obj, types.ModuleType), there's no way to do it.

So, that means you'd have to make ModuleType.__getattr__ do the special error message formatting. 

> (Of course, another option would be to look for other modules of the
> same name when you get an attribute-error on a module to aid debugging,
> but I think that's too heavy-weight.)

If that could be done only when the exception escapes to top level and dumps s traceback, that might be reasonable. And it would _definitely_ be helpful. But I don't think it's possible without major changes.


More information about the Python-ideas mailing list