Natalie Perret
Natalie Perret

Reputation: 8997

How to avoid repeating "from . import class_name" when "." is actually referring to an invalid identifier?

Say I have the very simple folder architecture below when working with a PyCharm project:

- 1 - Something
   - scripta.py
   - scriptb.py
   - dummyclass.py

Since 1 - Something is an invalid identifier I have to use something like below in scripta.py and scriptb.py in order to be able to import DummyClass defined in dummyclass.py:

from .dummyclass import DummyClass

Is there any way to avoid that since both scripts and the class definition are within the same package without changing this invalid identifier?

I thought creating an __init__.py and putting the import there would help but it actually does not...

Any thoughts?

Upvotes: 0

Views: 48

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599630

I'm not sure why the directory can't be renamed - if it's someone else's codebase it's just as invalid for them as it is for you. But assuming you can't, one solution is to put that directory directly on the Python path; either from outside Python by adding it to the PYTHONPATH environment variable, or from inside by adding it to sys.path. After that you can just import the module directly.

Upvotes: 1

Related Questions