Rodrigo
Rodrigo

Reputation: 12693

How to import a simple class in working directory with python?

I read various answer (relative import), but none work to import a simple class. I have this structure:

__init__.py   (empty)
my_script.py
other_script.py
my_class.py

I want to use my_class.py in both script (my_script.py and other_script.py). Like all answer suggest, I just use:

from .my_class import My_class

but I always get

SystemError: Parent module '' not loaded, cannot perform relative import

I am using Python 3.5 and PyCharm 2016.1.2. Does I need to configure the __init__.py? How can I import a simple class?

Edit

All the files are in the working directory. I just use the Pycharm to run and I wasn't having problem until try to import the class.

Upvotes: 1

Views: 605

Answers (1)

jez
jez

Reputation: 15359

Ensure that your current working directory is not the one that contains these files. For example, if the path to __init__.py is spam/eggs/__init__.py, make sure you are working in directory spam—or alternatively, that /path/to/spam is in sys.path and you are working in some third place. Either way, do not attempt to work in directory eggs. To test your code, you say import eggs.

The reasoning is as follows. Since you're using __init__.py you clearly want to treat this collection of files as a package. To work as a package, a directory must fulfill both the following criteria:

  1. it contains a file called __init__.py
  2. its parent directory is part of the search path (or the parent directory is your current working directory); in effect, a package directory must masquerade as a file, i.e. be findable in exactly the same way that a single-file module might be found.

If you're working inside the package directory you may not be fulfilling criterion 2. You can do a straightforward import my_class from there, certainly, but the "relative import" thing you're trying is a feature that only a fully-working package will support.

Upvotes: 1

Related Questions