I have an API that uses abstract class attributes, essentially attributes that exist for all instances of a class & are defined in the class body.
I would like to programmatically generate some of these attributes. They aren't dynamic in the sense that they don't change at runtime.
For example, a class Foo that builds bax
as a dictionary from a list of keys.
this works! but doesn't solve my case, which is a little more complicated.
class Foo:
bax_values = [0,1,2,3]
bax = {f"{x}":x+1 for x in bax_values}
My case is more complicated - there's a template and a set of keys.
class Foo:
bax_values = [0,1,2,3]
bax_template = "bar{s}"
bax = {f"{x}":bax_template.format(s=x) for x in bax_values}
This doesn't work - intriguingly, it says bax_template
is undefined. This seems to contradict the working case, which allowed iteration over the class-defined bax_values
.
What's the difference between these two cases in the eyes of python?
Edit: This question is not a duplicate of "UnboundLocalError: local variable referenced before assignment" Why LEGB rule not applied in this case?
That answer suggests that "You may also access it [bax_template] directly at the class level, during the class definition, but since you are still inside the temporary scope that is just another example of a local access (LEGB)." This is not working in my test case. I am able to access bax_values, but not bax_template. My question is asking what is the difference between these two variables that makes one accessible and the other not. It seems to be something related to the scope of the comprehension variables.
Edit 2: As proof that this seems to be something to do with the scope of the comprehension variables, the following workaround does the job.
from itertools import product
class Foo(object):
bax_values = [0,1,2,3]
bax_template = ['bar{s}']
bax = {f"{key}":template.format(s=key) for key,template in product(bax_values, bax_template)}
which implies that we can reference the class attributes in the iterable portion of a comprehension, but not the value/definition portion of a comprehension