bencarter78
bencarter78

Reputation: 3895

Importing classes in python returns cannot import name error

I'm starting out with my very first python project but I'm running into a problem right from the start. I'm trying to figure out how to import a class into my main.py file.

My directory structure is...

game
- __init__.py
- main.py
- player.py

So far I have in main.py...

from player import Player

player1 = Player("Ben")
print player1.name

I get the following error...

Traceback (most recent call last): File "main.py", line 1, in from player import Player ImportError: cannot import name Player

I've had a google but can't find anything that works. Can someone help please?

I'm using Python 2.7.10

Update

So my player.py contains

class Player:
    def __init__(self, name):
        self.name = name

    def name(self):
        return self.name

and my init.py file is empty

Upvotes: 0

Views: 14474

Answers (1)

Waylan
Waylan

Reputation: 42497

When you do from player Python looks for a module named player at the root of the PYTHONPATH. As no such module exists, an error is raised.

By using a relative import (prefixing the module name with a dot) you tell Python to look for the module in the same directory as the current file. Like this:

from .player import Player

Or, if that gets confusing, you can just use the absolute path (game.player) which should be at the root of the PYTHONPATH if installed correctly.

from game.player import Player

However, you can't always guarantee that a library will always be installed at the PYTHONPATH root by your users, so relative paths are generally preferred when importing modules within the same library. See the docs for more info.

Upvotes: 2

Related Questions