Python Forum

Full Version: initialisation and metaclass
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I try to write classes tied to a database.
I want to build properties with each fields of the database without writing all them by hand.
I'd think to do this with a metaclass that catches the fields in the database and create the associated properties by a descriptor.
But my metaclass need to access to the database. How can I pass the database connexion to the meta class before it is used to construct my class ?

Thank you.
You could perhaps return a parametrized metaclass with a function
from functools import lru_cache

@lru_cache(None)
def get_metaclass(arg):
    class MyMeta(type):
        
        def __new__(meta, name, bases, members):
            cls = type.__new__(meta, name, bases, members)
            cls.foo = lambda self, val: '{} {}!'.format(arg, val)
            return cls
        
    return MyMeta

class A(metaclass=get_metaclass('Hello')):
    pass

class B(metaclass=get_metaclass('Hello')):
    pass

assert type(A) is type(B) # <-- A and B have the same metaclass.

a = A()
print(a.foo('World')) # <--- prints Hello World!