1

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.

Community
  • 1
  • 1
Rodrigo
  • 11,909
  • 23
  • 68
  • 101

1 Answers1

1

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.

jez
  • 14,867
  • 5
  • 37
  • 64
  • Soo... The problem is the working directory. I CAN'T import the class in the working directory? And yes, all the files are in the working directory! – Rodrigo Sep 27 '16 at 17:18
  • You can `import my_class` on its own from there, for sure, but if you want to wrap multiple files up in a package, stay out of the package directory itself. (see edit) – jez Sep 27 '16 at 17:32