Shared Variable between Parent and Child in Python

I have a global configuration pp that changes at runtime and needs it to be shared across all parent/child objects.

class Config:
    pp = 'Init'
    def __init__(self):
        pass
    
class Child(Config):
    def __init__(self, name):
        self.cc = name

par = Config()
print(f"Parent: {par.pp}")
par.pp = "123"
print(f"Parent: {par.pp}")
child = Child('XYZ')
print(f"Child-1: {child.pp} - {child.cc}")

This prints:

Parent: Init 
Parent: 123 
Child-1: Init - XYZ

The third line is expected to be Child-1: 123 - XYZ

How can I implement that in a clean way?

UPDATE*
Currently it works with a method like:

class Config:
    pp = 'Init'
    def __init__(self):
        pass
    def set_pp(self, val):
        type(self).pp = val

>Solution :

In your example, the parent of Child is not par (which is an instance of Config, but it is the class Config. So you could change the value directly on the class, like that:

class Config:
    pp = 'Init'
    def __init__(self):
        pass
    
class Child(Config):
    def __init__(self, name):
        self.cc = name

print(f"Parent: {Config.pp}")
Config.pp = "123"
print(f"Parent: {Config.pp}")
child = Child('XYZ')
print(f"Child-1: {child.pp} - {child.cc}")

Note that if you want to keep the same syntax, you could write

class Config:
    _pp = "Init"

    @property
    def pp(self):
        return self._pp
    
    @pp.setter
    def pp(self, value):
        self.__class__._pp = value

    def __init__(self):
        pass
    
class Child(Config):
    def __init__(self, name):
        self.cc = name

par = Config()
print(f"Parent: {par.pp}")
par.pp = "123"
print(f"Parent: {par.pp}")
child = Child('XYZ')
print(f"Child-1: {child.pp} - {child.cc}")

In this version, the pp is set from the parent object, to the class Config.

Leave a Reply