Andrew
Andrew

Reputation: 151

python 3.4: Cannot import class from another file

A question like this has appeared multiple times here, but none of the answers have worked for me. I'm using Python 3.4 with PyCharm as my IDE. In file make_layers.py, I have the following little placeholder of a class (np is my imported numpy):

class Finder:
    def __init__(self):
        pass
    def get_next_shape(self, uses_left):
        mask = np.zeros(uses_left.shape, dtype=np.int16)
        return mask

In another file in the same directory, box_finder.py, I try to import the class and make a subclass:

import make_layers as ml

class BoxFinder(ml.Finder):
    def __init__(self):
        pass

When I try to run this, it fails at the import statement, saying

AttributeError: module 'make_layers' has no attribute 'Finder'

I've tried endless variations on the syntax (including things like from make_layers import Finder), but nothing works. It must be something obvious, but I can't see the problem. Any help would be appreciated!


EDIT: Antti, you nailed it. There was a sneaky circular import in there. I moved Finder to its own file, and success! Thank you everyone!

Upvotes: 0

Views: 1693

Answers (2)

Gábor Erdős
Gábor Erdős

Reputation: 3689

If you are on Linux, to import your own classes you need to put them into your $PYTHONPATH environment variable.

export PYTHONPATH=$PYTHONPATH:/where/the/file/is

If this is the case i would suggest to put this line in your .bashrc to avoid doing the export in after every restart

Second, to make PyCharm recognise the importable classes from your script you have to mark the directory as sources root. After this PyCharm should see that you have a Finder class inml

Upvotes: 0

holdenweb
holdenweb

Reputation: 37013

Your modules look correct, and should work. The most likely source of error is that another file called make_layers.py is being imported. To check this, print ml.__file__ to see where the make_layers module is being imported from.

Upvotes: 1

Related Questions