0

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

13
  • 1
    Show us the full contents of player.py. Commented Oct 14, 2015 at 18:41
  • 1
    show us what's in __init__.py and player.py for that matter. Commented Oct 14, 2015 at 18:42
  • 2
    Where are you invoking your script when you get the error? I would suspect player.py is not on the PYTHONPATH Commented Oct 14, 2015 at 18:43
  • what happens if you open ipython and try to import player? Commented Oct 14, 2015 at 18:50
  • Is that the only player.py file on your computer? It's possible that you're actually importing an older version of player that doesn't have a Player class. Commented Oct 14, 2015 at 18:50

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.