Yarin
Yarin

Reputation: 183499

Child class doesn't recognize module imports of parent class?

I've got two classes in two different modules:

animal.py:

import json

class Animal(object):
    pass

monkey:

import animal

class Monkey(animal.Animal):

    def __init__(self):
        super(Monkey, self).__init__()

        # Do some json stuff...

When I try to instantiate a Monkey, I get a

NameError: global name 'json' is not defined

But I'm importing json in the defining module of the super class, so why wouldn't it be loaded?

Upvotes: 5

Views: 6365

Answers (2)

smichak
smichak

Reputation: 4958

Well, python imports do not function as C #include pre-processor directive. They import the module to the namespace of the importing module only and not to the global namespace. So, you're gonna have to import json in each and every module you intend to use it.

Upvotes: 2

Thomas
Thomas

Reputation: 181745

It is loaded, but its name is not available in the scope of monkey.py.

You could type animal.json to get at it (but why would you), or just type

import json

in monkey.py as well. Python will ensure that the module is not loaded twice.

Upvotes: 11

Related Questions