Python Forum
initialisation and metaclass
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
initialisation and metaclass
#1
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.
Reply
#2
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!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  singleton using metaclass bb8 12 8,679 Feb-13-2018, 01:27 PM
Last Post: bb8

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020