Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Subclass error KeyError: "'__name__' not in globals"

in video Python -> Object-Oriented Python -> Inheritance -> Subclasses

I run code below in Treehouse workspaces and it work same as video, but when copy whole code to run in Pycham it got error

    "C:\Program Files (x86)\Python 3.5\python.exe" "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.1\helpers\pydev\pydevconsole.py" 60730 60731
    PyDev console: starting.

    import sys; print('Python %s on %s' % (sys.version, sys.platform))
    sys.path.extend(['C:\\Users\\Suvijug\\PycharmProjects\\PythonBasic'])

    Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:16:59) [MSC v.1900 32 bit (Intel)] on win32
    >>> from .monster import Monster
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
      File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.1\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
        module = self._system_import(name, *args, **kwargs)
    KeyError: "'__name__' not in globals"

File: monster.py

    import random

    from .combat import Combat

    COLORS = ['yellow', 'red', 'blue', 'green']


    class Monster(Combat):
        min_hit_points = 1
        max_hit_points = 1
        min_experience = 1
        max_experience = 1
        weapon = 'sword'
        sound = 'roar'

        def __init__(self, **kwargs):
            self.hit_points = random.randint(self.min_hit_points, self.max_hit_points)
            self.experience = random.randint(self.min_experience, self.max_experience)
            self.color = random.choice(COLORS)

            for key, value in kwargs.items():
                setattr(self, key, value)

        # def __str__(self):
        #     return '{} {}, HP: {}, XP: {}'.format(self.color.title(),
        #                                           self.__class__.__name__,
        #                                           self.hit_points,
        #                                           self.experience)

File: combat.py

    import random


    class Combat():
        dodge_limit = 6
        attack_limit = 6

        def dodge(self):
            roll = random.randint(1, self.dodge_limit)
            return roll > 4

        def attack(self):
            roll = random.randint(1, self.attack_limit)
            return roll > 4

another question.... in Pycham why when i import file in console need dot before file name

    # in console, i import file like this
    from .[filename] import [Classname]

but when import in code editor, it show no file until i remove dot

    # in editor i import like this, it show "Unresolved reference" but it work
    from [filename] import [Classname]

1 Answer

Hi Suvijug,

The KeyError in your first code snippet is most likely caused by the relative import statement failing to resolve the name of the package to import from. Try using absolute import like this (substitute your package name below):

from <package>.monster import Monster

See the official Django page for details on module importing.