Questions tagged [metaclass]

In object-oriented programming, a metaclass is a class whose instances are classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain classes and their instances. Not all object-oriented programming languages support metaclasses.

metaclass
Filter by
Sorted by
Tagged with
0 votes
1 answer
70 views

Why metaclass works for a class propery but a @classmethod @property doesn't?

It's a simplified reimplementation of Django deb models. This works (similar to what Django does, although there it's an attribute, not a property): class ClassPropertyType(type): @property ...
Velkan's user avatar
  • 7,385
1 vote
1 answer
235 views

When is the __prepare__ method of a metaclass excuted and what uses its return value?

PEP 3115 has the following example of using the __prepare__ method of a metaclass (print statements are mine): # The custom dictionary class member_table(dict): def __init__(self): self....
joseville's user avatar
  • 823
1 vote
1 answer
215 views

Pickle a Dynamically Created Mixin-Class

I am dynamically creating classes using mixins, following the pattern in this SO answer, but it's giving me pickling errors: https://stackoverflow.com/a/28205308/2056246 (In case anyone is curious why ...
Alex Spangher's user avatar
1 vote
1 answer
67 views

Don't know meaning and reason of 'return type.__new__(metacls, name, bases, namespace)' in python metaclass example code

I'm trying to understand about Python Metaclass. I almost understand what Metaclass do in python, but I can't understand meaning of example code class MakeCalc(type): def __new__(metacls, name, ...
J-Hoplin's user avatar
1 vote
1 answer
117 views

How is model Meta class different from model form Meta class?

I wanted to understand the metaclasses we use in the model. I found about it in docs. I remember adding metaclass in model forms as well. It seems like model metaclass and model form metaclass is ...
Ayush Paudel's user avatar
1 vote
1 answer
90 views

How to access variables made in __init_subclass__ from __init__?

Here is sample code: from abc import * class weightlayer(metaclass=ABCMeta): def __init_subclass__(cls): cls.count = 0 def __init__(self): self.order = cls.count cls....
string's user avatar
  • 39
6 votes
3 answers
145 views

Why do keyword arguments to a class definition reappear after they were removed?

I created a metaclass that defines the __prepare__ method, which is supposed to consume a specific keyword in the class definition, like this: class M(type): @classmethod def __prepare__(...
sagittarian's user avatar
  • 1,051
2 votes
1 answer
14k views

What does super().__init__(*args, **kwargs) do? [duplicate]

I don't know what does super().__init__(*args, **kwargs) do here. class B(type): def __init__(self, *args, **kwargs): self.a = 'a' super().__init__(*args, **kwargs) class A(...
showkey's user avatar
  • 520
-1 votes
1 answer
140 views

Python add methods of objects to containing list [duplicate]

I have a list containing objects of same class. now I want to make that list a container class that relates to all methods of the objects it contains as you can see in my example below. But since I ...
erg erg's user avatar
0 votes
1 answer
413 views

Read-only class properties in python ≥3.9 with `help()` support

Since python 3.9, it is supported to stack the @property and @classmethod decorators. However, I struggle to create a class-property that shows up in help under the Readonly properties section. The ...
Hyperplane's user avatar
  • 1,604
4 votes
1 answer
2k views

How to typecheck class with method inserted by metaclass in Python?

In the following code some_method has been added by metaclass: from abc import ABC from abc import ABCMeta from typing import Type def some_method(cls, x: str) -> str: return f"result {x}&...
Roman Susi's user avatar
  • 4,165
0 votes
0 answers
142 views

Is there a way in python to use a subclass attribute generated by __init_subclass__ as a type hint

How can I type hint in a base class to a type which is an attribute of the subclass. For example the type hint (obviously wrong) on IFoo.foo below: class IFoo(ABC): def __init_subclass__(cls, ...
rnorthcott's user avatar
1 vote
1 answer
1k views

how to pass arguments into a nested class in python

I have the following model: def get_my_model(name1, name2): class MyModel(Model): class Meta: table1 = name1 table2 = name2 return MyModel I am ...
Tom's user avatar
  • 2,625
0 votes
0 answers
92 views

WTForms/Flask-WTF class attributes vs instance attributes

I'm now trying to use Flask-WTF (powered by WTForms) to render my frontend forms submission. However, there is a limitation that all the fields in a Form object are class-level attributes, namely all ...
ffyuanda's user avatar
2 votes
1 answer
3k views

How to create dynamic models using pydantic and a dict data type

I am trying to load a yml file into a dict, with pyyaml, theloading process automatically loads proper types for me, e.g., yml file with content below: key1: test key2: 100 will be loaded into a dict ...
shelper's user avatar
  • 10.3k
1 vote
1 answer
171 views

Sphinx autoclass with metaclass not working

Metaclass: class RequestMeta(type): def __new__(mcs, what, bases, attrs): _attrs = {name: decimal_to_string(attr) if callable(attr) else attr for name, attr in attrs.items()} ...
Timofii Sorokin's user avatar
10 votes
1 answer
2k views

Multiple inheritance metaclass conflict involving Enum

I need a double inheritance for a class that is an Enum but also support my own methods. Here's the context: import abc from enum import Enum class MyFirstClass(abc.ABC): @abc.abstractmethod ...
Adam Boinet's user avatar
4 votes
1 answer
766 views

specify metaclass for dynamic type

In Python, you can create types dynamically using the function my_type = type(name, bases, dict). How would you specify a metaclass for this type my_type? (Ideally other than defining a throwaway ...
Michael Green's user avatar
1 vote
1 answer
47 views

Python abstractclass Inheritance

I have two class structured as below from abc import ABCMeta, abstractmethod class C(metaclass=ABCMeta): """""" def __init__(self, x, y): self._x = x ...
Yehui He's user avatar
  • 191
7 votes
2 answers
371 views

How can I document methods inherited from a metaclass?

Consider the following metaclass/class definitions: class Meta(type): """A python metaclass.""" def greet_user(cls): """Print a friendly ...
Alex Waygood's user avatar
  • 7,033
4 votes
1 answer
526 views

What is the corret way to call super in dynamically added methods?

I defined a metaclass which add a method named "test" to the created classes: class FooMeta(type): def __new__(mcls, name, bases, attrs): def test(self): return ...
Woody Huang's user avatar
1 vote
1 answer
321 views

How can a metaclass access attributes defined on a child class?

I'm working on a class generator of sorts. I want to be able to create many children of BasePermission that are customizable using a required_scopes attribute. This is what I have so far. from ...
Brady Dean's user avatar
  • 3,504
0 votes
0 answers
51 views

Python dynamic class with different class variables

I have a class definition roughly like: Class X(metaclass=XMetaClass): fields = [] def __init__(self, attr): self.attr = attr # Use fields here Now I want to create instances ...
Amin Alaee's user avatar
  • 1,895
0 votes
2 answers
76 views

LinkedList of Python Classes

Very simple Overview of Problem Statement: Given Object Name, object attribute information 'A',{"a":1} 'B',{"b":2} 'C',{"c":3} Trying to create a single object which ...
Dibyendu Dey's user avatar
0 votes
2 answers
4k views

Create a pydantic.BaseModel definition with external class or dictionary

I have a (dynamic) definition of a simple class, like so: class Simple: val: int = 1 I intend to use this definition to build a pydantic.BaseModel, so it can be defined from the Simple class; ...
Sazzy's user avatar
  • 1,964
2 votes
2 answers
89 views

What is the nomenclature for the relationship of a class to its associated metaclass?

What do we call the relationship of a class towards its associated metaclass? I'd like to fill the blank in the following two lines: Class A is the metaclass of class B. Class B is the ________ of ...
mutableVoid's user avatar
  • 1,396
0 votes
0 answers
251 views

customize django model meta ordering option

This is how my code looks like class User(AbstractUser,TimeStampModel,Address,TrashBin): FirstFormat = "First name Last name" SecondFormat = "Last name First name" ...
Rahul Narang's user avatar
0 votes
1 answer
158 views

Python Generic typehint going from type to instanciated object

I currently am having some issues with my IDE autocomplete as it can't tell what return types are etc. I have a singleton metaclass, overriding the __call__ method similar to this: SingletonTypes = ...
George Wright's user avatar
3 votes
1 answer
314 views

Why doesn't __qualname__ work the same way in @classmethod than in metaclass

I have implemented a minimalistic enum by writing class SymbolClass(type): def __repr__(cls): return cls.__qualname__ class Symbol(metaclass=SymbolClass): pass class Animal: class Dog(Symbol):...
Camion's user avatar
  • 1,334
1 vote
2 answers
153 views

__getattr__ for class atributes?

For a class Foo, class Foo: ... is there a way to call a specific method whenever Foo.XXX (an arbitrary class attribute XXX, such as bar, bar2, etc.) is being resolved, but NOT whenever Foo().XXX ...
Captain Trojan's user avatar
0 votes
2 answers
538 views

How to wrap all python superclass methods with subclass internal state?

I am aware of this question but I don't think it covers my case. I have an external Dummy class with many methods, all using an instance attribute. Instead of using this instance attribute, I want to ...
Borbag's user avatar
  • 607
1 vote
2 answers
69 views

How can I silently make a nested class aware of it's outer class (by putting all the required code in parent or metaclass)?

I have made a symbol class that helps me to make symbolic constants by using metaclasses >>> class SymbolClass(type): def __repr__(self): return self.__name__ >>> class Symbol(...
Camion's user avatar
  • 1,334
2 votes
1 answer
214 views

Stop Sphinx from Executing a cached classmethod property

I am writing a package for interacting with dataset and have code that looks something like from abc import ABC, ABCMeta, abstractmethod from functools import cache from pathlib import Path from ...
Hyperplane's user avatar
  • 1,604
0 votes
1 answer
373 views

Python 3.9 MetaClass Property vs Classmethod Property

Consider the following code from abc import ABC, ABCMeta class MyMetaClass(ABCMeta): @property def metaclass_property(cls): return "result" # def __dir__(cls): # ...
Hyperplane's user avatar
  • 1,604
1 vote
1 answer
203 views

Metaclass Resolver

Context I started exploring the concept of Metaclass with python. Rapidly, I found myself facing a common problem. TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict)...
dage023's user avatar
  • 11
1 vote
1 answer
1k views

Abstract class inheriting from ABC and QMainWindow [duplicate]

from abc import ABC, abstractmethod from PyQt5.QtWidgets import QMainWindow class _ControlGUI(QMainWindow, ABC): pass The very simple code above is raising an error that is not very clear to me. ...
Mathieu's user avatar
  • 5,536
0 votes
1 answer
363 views

refering to instance of a class from its metaclass python

Is there any way to refer to instance of a class from its metaclass every time an instance is created? I suppose I should use dunder _call_ method inside metaclass for that purpose. I have the ...
KiNest's user avatar
  • 55
5 votes
1 answer
2k views

How to define an abstract metaclass in python

When defining an abstract metaclass in python and instantiating it like this: from abc import ABC, abstractmethod class AbstractMetaClass(type, ABC): @abstractmethod def func(self): ...
stefs's user avatar
  • 53
0 votes
1 answer
1k views

Why am I getting the error: __init__() missing 1 required positional argument?

Fedora 34, Python 3.9.5 I wrote code with a class that inherits from the other two (one of which inherits the QWidget functionality). As a result, this simple class doesn't initialized. from PyQt5 ...
Aleksey.Stack's user avatar
1 vote
1 answer
368 views

Django DRF unit tests added with dynamic mixins via metaclass not being executed

I am trying to test DRF endpoints, and trying to add mixings dynamically to a test in order to execute tests again each method allowed in the endpoint (get, post, put, patch, delete) So, my idea is to ...
Gonzalo's user avatar
  • 812
3 votes
2 answers
655 views

Use of ABCMeta.register

What is the use of ABCMeta's register method? https://docs.python.org/3/library/abc.html It seems that if I have an abstract base class ABC, say, Animal, I can register a subclass of it using register:...
Michele Piccolini's user avatar
1 vote
2 answers
73 views

pd.DataFrame(...) resulting in TypeError when a metaclass is defined before it

I've been playing around with metaclasses to try and get a good feel of them. A really simple (and pointless) one I came up with is the following: class MappingMeta(type, collections.abc.Mapping): ...
user3645016's user avatar
1 vote
1 answer
223 views

Python metaclass for Enum members with variable number of attributes

I am new to Python's metaclasses and I am currently trying to achieve the following: from enum import Enum, EnumMeta class FlexEnumMeta(EnumMeta): # see the attempt for the implementation below ...
Fabien Tribel's user avatar
0 votes
1 answer
4k views

pickle.PicklingError: Can't pickle: it's not the same object as

We're trying to use metaclasses for a custom backend selection (multiprocessing.Process or threading.Thread). The rationale behind this implementation is to extend Process/Thread's functionalities for ...
deepankarm's user avatar
0 votes
1 answer
206 views

How can I use abstract class properties with metaclasses?

I've created an abstract class property for class Parent using metaclasses: from abc import abstractmethod, ABCMeta class ParentMeta(ABCMeta): @property @abstractmethod def CONSTANT(cls): ...
vandenheuvel's user avatar
0 votes
2 answers
150 views

How do i augment or override a method that was added to a class , using a Metaclass in python

Am trying to use a custom Metaclass to add methods to a class, at the same time i want to be able to override or augment the method added to the class that was created from the custom Metaclass(just ...
Christopher_Okoro's user avatar
3 votes
2 answers
2k views

How can I make it a requirement to call super() from within an abstract method of a metaclass?

I have a central metaclass with abstract methods, some of which I would like to not only force them to be present in the child classes, but also want to force the child classes to explicitly call ...
CaffeinatedMike's user avatar
2 votes
1 answer
750 views

MyPy error from using subclass variables in metaclass

I have to use a metaclass and need to access a subclass variable inside the new function (so it's essentially an abstract property). This gives MyPy errors of course, because 'type' has no attributes ...
18Sheimanr's user avatar
1 vote
1 answer
2k views

how to use a singleton instance in multiple django apps

I'm creating a website using django framework. I am using a singleton in one django application and I use it to store some variables . Now that I have created another app in my project, how can I ...
Soumaya's user avatar
  • 11
4 votes
1 answer
426 views

Do we need metaclasses to do this, or is reflection enough?

So I have been quite looking forward to metaclasses. I then heard that it won't be in c++23, as they think we first need reflection and reification in the language before we should add metaclasses. ...
Yakk - Adam Nevraumont's user avatar

1 2 3
4
5
24