metaclass

Mypy error on __init_subclass__ example from python documentation

Mypy error on __init_subclass__ example from python documentation Question: From the official Python 3 documentation for __init__subclass__: class Philosopher: def __init_subclass__(cls, /, default_name: str, **kwargs): super().__init_subclass__(**kwargs) cls.default_name = default_name class AustralianPhilosopher(Philosopher, default_name="Bruce"): pass The problem is, mypy raises "Type[Philosopher]" has no attribute "default_name". What is the solution for this? How can I make mypy take …

Total answers: 1

Python typing for a metaclass Singleton

Python typing for a metaclass Singleton Question: I have a Python (3.8) metaclass for a singleton as seen here I’ve tried to add typings like so: from typing import Dict, Any, TypeVar, Type _T = TypeVar("_T", bound="Singleton") class Singleton(type): _instances: Dict[Any, _T] = {} def __call__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: if cls …

Total answers: 1

Why does defining new class sometimes call the __init__() function of objects that the class inherits from?

Why does defining new class sometimes call the __init__() function of objects that the class inherits from? Question: I’m trying to understand what actually happens when you declare a new class which inherits from a parent class in python. Here’s a very simple code snippet: # inheritance.py class Foo(): def __init__(self, *args, **kwargs): print("Inside foo.__init__") …

Total answers: 1

`__set_name__` hook manually added to `functools.wraps()` descriptor instance never called

`__set_name__` hook manually added to `functools.wraps()` descriptor instance never called Question: I’m trying to add a __set_name__ hook to the descriptor produced by functools.wraps inside a decorator, but it is never called and I don’t see any error messages: import functools def wrap(fn): """Decorator.""" @functools.wraps(fn) def w(*args, **kwargs): return fn(*args, **kwargs) # This never gets …

Total answers: 1

Separating __call__ into __new__ and __init__

Separating __call__ into __new__ and __init__ Question: I am trying to write some metaclass for a special case of a SingletonMeta. This is not a question about Singletons. It is about using metaclasses in Python. I need to control __new__ and __init__ of the Singleton classes (the instances of SingletonMeta) separately, but I was not …

Total answers: 1

How to get default arguments from concrete __init__ into a metaclass' __call__?

How to get default arguments from concrete __init__ into a metaclass' __call__? Question: Please consider class Meta(type): def __call__(cls, *args, **kwargs): print(cls) print(f"args = {args}") print(f"kwargs = {kwargs}") super().__call__(*args, **kwargs) class Actual(metaclass=Meta): def __init__(self, value=1): print(f"value=P{value}") a1 = Actual() a2 = Actual(value=2) outputs <class ‘__main__.Actual’> args = () kwargs = {} value=P1 <class ‘__main__.Actual’> args …

Total answers: 1

How to add type hint to python factory_boy Factory classes?

How to add type hint to python factory_boy Factory classes? Question: So we are working with some existing code where there is an implementation of factories classes from the factory_boy project which create instances of other classes for example class TableFactory(Factory): class Meta: model = Table id = LazyAttribute(lambda x: uuid4()) color = SubFactory(ColorFactory) reference …

Total answers: 1

Can I implement a class method dynamically in Python?

Can I implement a class method dynamically in Python? Question: In Python, it’s no secret that you can implement attributes of an instance of a class dynamically. Here’s what that looks like: class MyClass(object): def __getattribute__(self, name): if name == ‘dynamic_attribute’: return "dynamic attribute value" return super().__getattribute__(name) # Create an instance of my class obj …

Total answers: 1

Making classfactory that derive from dataclass objects informed by types in python

Making classfactory that derive from dataclass objects informed by types in python Question: When using dataclasses.dataclass the type information informs how parameters are parsed. I would like to take a defined dataclass and produce a class that changes all the attribute type declarations from X to Optional[List[X]]. from dataclasses import dataclass from dataclasses_json import DataClassJsonMixin …

Total answers: 3

Are there any unique features provided only by metaclasses in Python?

Are there any unique features provided only by metaclasses in Python? Question: I have read answers for this question: What are metaclasses in Python? and this question: In Python, when should I use a meta class? and skimmed through documentation: Data model. It is very possible I missed something, and I would like to clarify: …

Total answers: 1