Minimal example
class foo:
loadings = dict(hi=1)
if 'hi' in loadings:
print(loadings['hi'])
# works
print({e : loadings[e] for e in loadings})
# NameError global name 'loadings' not defined
I tried referencing the class namespace as well but that isn't working either
class foo:
loadings = dict(hi=1)
if 'hi' in loadings:
print(loadings['hi'])
#works
print({e : foo.loadings[e] for e in foo.loadings})
#NameError: name 'foo' is not defined
And of course, this works as expected
class foo:
loadings = dict(hi=1)
if 'hi' in loadings:
print(loadings['hi'])
print({e : foo.loadings[e] for e in foo.loadings})
I want to understand why this scope issue is happening then, if I am trying to do something insane understand the best way to do it otherwise. My feeling was that the first code snip should have worked as is, but of course it does not.
The goal
I am creating a DataManager class/module for some csv/json files along with canned database queries, a one stop shop for my program and obtaining data. There is some static data and some dynamic data so it seemed like a great use of static and non-static data members in the same class. While I understand that these could be module level variables, I like the concept of having static class data members (possibly because of a bias from Java). Any help is much appreciated
My solution (for now)
I ended up unfurling the list comprehension to stay in class scope, in the above it would become something like this
class foo:
loadings = dict(hi=1)
temp = dict()
for e in loadings:
temp[e] = loadings[e] # keep in mind this is a minimal example, I probably wouldn't do (just) this
print(temp) # works
del temp
It is not pretty but it works for now
print({k: v for k, v in loadings.items()})
does work. Soloadings
is at least kinda visible in the dict comprehension – Femmerunonce
or something but it seemed that class level code is there for a reason. – Resent