Search code examples
python-3.xpycharmanacondapathlib

how do I correctly use Path (PyCharm)


I'm using PyCharm 2018.1.4

If I write

from pathlib import Path
p = Path('.')

this runs fine.

On the other hand, if I write

import pathlib
p = Path('.')

I get

NameError: name 'Path' is not defined

I thought by using import pathlib I'm importing the complete library, including Path.

Compared to a terminal session:

$ bpython
bpython version 0.17.1 on top of Python 3.6.4 /Users/fanta4/anaconda3/bin/python
>>> import pathlib
>>> p = Path('.')
>>>

no problem.

And just python:

Nick-iMac:~ fanta4$ which python
/Users/fanta4/anaconda3/bin/python

Nick-iMac:~ fanta4$ python
Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 12:04:33)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
>>> import pathlib
>>> p = Path('.')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Path' is not defined

Where is the problem in PyCharm?
In PyCharm I see python 3.6 (File > Default Settings > Project Interpreter)

Thanks!


Solution

  • If you do a naked import (i.e. import pathlib), the Path class is not in the local namespace of your script. It is an attribute of the module object pathlib. To successfully access Path in this case, you must explicitly refer to it via its parent object. I.e.: pathlib.Path.

    Also, I'm not familiar with bpython, but what you've described in your terminal session does not occur in IPython. In fact, I consider it extremely poor design that importing a library in any interactive environment implicitly imports all of its children objects. Number one, it risks polluting the namespace. Number two, it causes confusion in both new and old users of a language.