1

Question at the end. In myClasses.py, I have class A with class variables. dist is hard coded. distPerc is calculated. I won't need instances of this class. Hence the usage of class variables.

#version1
import utils
class A:
    dist = [10, 90, 0, 0, 0, 0]
    distPerc = [utils.convert_to_percent(x, dist) for x in dist]

myTest.py contains:

import myClasses
a = myClasses.A
print(a.distPerc)

When I run it, I get

NameError: name 'dist' is not defined

If I change the class to

#version2
class A:
    dist = [10, 90, 0, 0, 0, 0]
    distPerc = []
    for x in dist:
        distPerc.append(utils.convert_to_percent(x, dist))

and run it, it works:

[0.1, 0.9, 0.0, 0.0, 0.0, 0.0]

utils.py contains:

def convert_to_percent(x: int, lv: list = None):
    oo = 0
    if lv is None:
        oo = 10 ** (int(math.log10(x)) + 1)
    if type(lv) == list:
        oo = sum(lv)
    return x / 10 ** int(math.log10(oo))

If I use any function in list comprehension in version1, even builtin, it throws a NameError.

Question: even though an alternative works; I'd like to learn, why would list comprehension fail in #version1?

kal
  • 41
  • 2
  • 5

0 Answers0