hopeless-programmer
hopeless-programmer

Reputation: 990

Path class alternative to __file__ in python

Each python script has its own __file__ property, which is str with the path to this script.

Since there is a pathlib.Path class, is there any corresponding alternative to __file__? Like __file_path__ such that type(__file_path__) == Path?

Is it true that the closest we can have to this is to just use Path(__file__) instead of __file__?

Upvotes: 1

Views: 526

Answers (1)

MisterMiyagi
MisterMiyagi

Reputation: 51979

The __file__ and similar attributes are set by the import machinery. All these attribute use the str type to describe paths.

In order to treat these paths as Path instances, the simplest option is to convert them explicitly, for example as pathlib.Path(__file__), when needed.

Upvotes: 2

Related Questions