1

I create a class in a file. declare some class variable A = 5 and another class variable B = A+1. When importing that class from another file, I get a NameError: name 'A' is not defined. Is there a way around this or can/should class variables not depend on other class variables the way I am trying to do that?

Note that this NameError only happens when I import form another file. If i were to define the classe and create an instance of that class in the same file, everything runs smoothly.

file: file1.py

class foo:
    A = 5
    B = A+7

file: file2.py

from file1 import foo

I then run:

python file2.py

and get

NameError: name 'A' is not defined.

EDIT : The example above was too simplistic to reflect my actual problem. I was actually trying to define a class as such:

class foo:
    A = 5
    B = [i*A for A in range(3)]

The reasons why it doesn't work in Python 3 are to be found in the link in my answer.

Mazata
  • 73
  • 6

2 Answers2

2

Use the qualified name of the class variable:

In this_module.py:

class C:
    a = 0
    b = C.a + 1

...in some other file:

from this_module import C
gmds
  • 19,325
  • 4
  • 32
  • 58
  • @Mazata Shouldn't you accept your own answer in this circumstance and edit your question to reflect what you actually meant? – gmds Apr 09 '19 at 13:21
  • On second thought, yes you are right. I'll do that as soon as Stack Overflow lets me. – Mazata Apr 09 '19 at 13:27
0

I have found the problem. My code snippet was too simplified to accurately reflect my real situation. I was actually doing something like this:

class C:
    foo = 2
    bar = [i*foo for i in range(3)]

and then import that class from another file. While this apparently works in python 2, according to this answer, in Python 3:

class scope and list comprehension do not mix.

So there you have it. This can actually be marked as a duplicate.

Mazata
  • 73
  • 6