Python interpreter doesn't work in some directories - can it give a warning?

The interpreter is often not fully usable when the current directory happens to contain some python code unrelated to the command to be executed. This can be surprising and annoying. For example when the REPL starts seemingly normally, but the help appears broken. It happened to me several times and there were times when some explanation message would be really appreciated.

$ cd /usr/lib64/python3.13/asyncio ; python -c "help(int)"
attempted relative import with no known parent package

$ cd /usr/lib64/python3.9 ; python -c "print(99)"
AttributeError: module 'linecache' has no attribute '_register_code' (consider renaming '/usr/lib64/python3.11/linecache.py' since it has the same name as the standard library module named 'linecache' and prevents importing that standard library module)

There are several ways to avoid this problem (e.g. with the -P option) provided that the user understands how the sys.path works. However if a user is already aware of the problem, he will probably simply chdir away.

My first idea was that there is nothing we can do, because the interpreter cannot know if the current directory was entered deliberately or by chance or mistake. However, very often the current directory is a subdirectory of some existing sys.path item. Would it be possible to emit a warning about a possible conflict of cwd with the sys.path?

I’m sorry if this is a duplicate, but could not find specific enough search keywords.

1 Like

The “relative import with no known parent package” exception would be a reasonable candidate for a hint based on checking whether the offending module is reachable as both a top level module and a submodule.

1 Like