Skip to main content

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
19 views

Checking subclass against metaclass type

I have a set of plugins that inherit from a metaclass. the metaclasss is defined like so: from abc import ABC, abstractmethod class MetaReader(ABC): def __init__(self, arg1, arg2, **kwargs): ...
KBriggs's user avatar
  • 1,338
-1 votes
0 answers
24 views

attempting to apply Descriptor to attributes of nested classes using metaclass [closed]

Attempting to apply Descriptor to all attributes, including those of nested classes. Here is my attempt: from typing import Any import os import json import logging logger = logging.getLogger("...
Vasigaran's user avatar
1 vote
1 answer
47 views

Can't delete attribute added by metaclass

I've been playing around with Python metaclasses, and I have encountered a rather strange instance where I cannot delete an attribute added to a class object by a metaclass. Consider the following two ...
MrAzzaman's user avatar
  • 4,746
2 votes
1 answer
95 views

Why does int.__class__ give type in Python?

From what I've read, the built-in types such as int, float, dict, etc have been implemented in C, and they used to be different from user-defined classes before Python 2.2 However, the built-in types ...
Rajdeep Sindhu's user avatar
0 votes
1 answer
32 views

Python Object and Metaclass [closed]

i am new in python and having some confusions. As Java, in python also it is showing that Object is the top-most class but then what is the use of Metaclass as it is showing that all classes are ...
subhrajit1891's user avatar
1 vote
1 answer
40 views

If Python builtins derive from ABCs, then why is their metaclass type instead of ABCMeta?

I was reading PEP-3119, and I discovered that builtins derive from ABCs. From PEP-3119: The built-in type set derives from MutableSet. The built-in type frozenset derives from Set and Hashable. In ...
Jordan's user avatar
  • 306
0 votes
1 answer
33 views

`TypeError: metaclass conflict` for a Subclass of `type`

I made an abstract base class MyABC, whose metaclass is, of coarse, abc.ABCMeta. Then, I wanted to make a class SubType, whose instances are a subclass of MyABC. Since the instance of it is a class, I ...
Prown's user avatar
  • 15
1 vote
1 answer
53 views

Python: Heaptypes with metaclasses

In Python c-api: how can I create a heap type that has a metaclass? I'm well aware of PyType_FromSpec and derivatives and they can do this (from documentation): Changed in version 3.12: The function ...
oBrstisf8o's user avatar
3 votes
0 answers
20 views

What are the allowed values / source spec for umlRole in a metaconstraint?

In a UML definition of a metamodel it is possible to define metaconstraints e.g. <<metaconstraint>> umlRole="classifier" <<metaconstraint>> umlRole = "class"...
wikitect's user avatar
  • 467
1 vote
1 answer
49 views

How to override the internal read query of class or method in django

I wan't to override the internal read query present inside my class or method. I wan't to write generalised solution so that it should work on the class or method where I wan't to modify the read ...
Ayush Kumar's user avatar
1 vote
1 answer
63 views

How can I get IDEs to recognize a desired type name for a statically declared, dynamically created class in Python?

Problem: I am working on a library with, e.g., support for a UInt5 type, an Int33 type, etc. The library is a little more complicated than this, but for the sake of example creating a UInt12 type ...
D. Estes McKnight's user avatar
1 vote
2 answers
27 views

Why is meta class giving an error for abstract?

When I added abstract = True to this code: customUser(AbstractBaseUser,PermissionsMixin): id = models.autofield(primary_key = True) class Meta: verbose_name = 'User' ...
NAIMUR RAHMAN's user avatar
0 votes
1 answer
67 views

How can I refer to this metaclass inside a metaclass without specifying its name in the code?

I have some python code: class Meta(type): def __new__(cls, name, base, attrs): attrs.update({'name': '', 'email': ''}) return super().__new__(cls, name, base, attrs) def ...
Pablo Red's user avatar
0 votes
1 answer
57 views

TclOO metaclass classes objects and objdefine

I'm trying to implement classes implementing interfaces and serialisation of the resulting objects and I encountered an objdefine error message (using Tcl 8.5 + TclOO 1.0.x). I think I have some ...
Christopher Horler's user avatar
1 vote
1 answer
47 views

Can I avoid the ```metaclass=``` when I define an inherited class?

I would like to have a custom metaclass that looks like the definition of a TypedDict. When one declares a new TypedDict we write something like this: from typing import TypedDict class MyClass(...
Nuno's user avatar
  • 225
0 votes
2 answers
50 views

Delegate class construction leads to recursion error

I'm building a framework and want to allow users to easily influence the construction of an object (e.g. singletons) However no matter what I've tried I always get recursion. I wonder if there's a way ...
Pithikos's user avatar
  • 19.9k
2 votes
1 answer
171 views

Modify Enum to return value by default

I am trying to modify Enum to return value by default: class EnumDirectValueMeta(EnumMeta): def __getattribute__(cls, name): try: return object.__getattribute__(cls, name)....
mxsx's user avatar
  • 21
1 vote
3 answers
117 views

How to “template” a registry class that uses __new__ as a factory?

I wrote a class BaseRegistry that uses a classmethod as a decorator to register other classes with a string name in a class attribute dictionary registered. This dictionary is used to return the class ...
PhML's user avatar
  • 1,230
1 vote
2 answers
99 views

How to prevent attribute re-access until all attributes have been accessed once (Python metaclass)?

I have a list of attributes, say ["foo", "bar", "baz"], and I want to write a metaclass which ensures the following properties: They can all be accessed once, in any ...
ijustlovemath's user avatar
0 votes
1 answer
87 views

Dynamically adding abstract methods in an abstract class

from abc import ABCMeta, abstractmethod class DynamicAbstractMeta(ABCMeta): def __new__(cls, name, bases, namespace): item_attributes = ["person", "animal"] # ...
Yang Liang's user avatar
0 votes
2 answers
47 views

How can I retain a reference to the parent object when creating an instance of a nested class through the outer object in Python?

Is it possible to retain a reference to the parent object when creating an instance of a nested class through the outer object, without explicitly passing the parent object as an argument? class ...
Japan Manul's user avatar
3 votes
2 answers
65 views

Class / type of class, that was created with metaclass [duplicate]

class Meta(type): def __new__(cls, name, bases, dct): new_class = type(name, bases, dct) new_class.attr = 100 # add some to class return new_class class WithAttr(...
mikeziminio's user avatar
1 vote
1 answer
148 views

Python - extend enum fields during creation

Is it possible extend enum during creation? Example: class MyEnum(enum.StrEnum): ID = "id" NAME = "NAME And I need that after creating this enum contains the next fields: ID = &...
Sergey's user avatar
  • 135
0 votes
2 answers
74 views

Optimizing Input Verification in Nested Class Methods

I have the following example class: class MyClass: @classmethod def method1(cls, value): print(f'method1 called with value: {value}') cls.method2(value) cls.method3(...
Silverwilly's user avatar
0 votes
1 answer
83 views

Python use metaclass, cause Vscode can't give type hint

I create a metaclass and use it in class "Pool", then Vscode will not provide any type hintabout Pool In python i create a metaclass like this: class SignSingleton(type): def __init__(...
AtomOrigin's user avatar
0 votes
2 answers
74 views

Python decorators for classes to include class identity

Basically I have a Base class and a metaclass and a ton of classes that use both I want to avoid doing class Name(Base, metaclass=Meta) over and over again and instead do this @deco class Name: I ...
user22212491's user avatar
0 votes
1 answer
22 views

Override a keyvalue that is passed to a metaclass of a Baseclass by its childClass

When I derive the BaseClass by the ChildClass, the BaseMetaClass.__new__(...) is run twice. First with the keywordarg "foo" and second time with "bar". Is it possible to override &...
Moritz Hartmann's user avatar
0 votes
0 answers
33 views

How can I access a class name identically before and after instantiation? [duplicate]

I'm building an application where I have events defined as python classes. Each event has an explicit type, which I am setting as the name of the class. I have a property defined at .type that allows ...
Alex Cannan's user avatar
0 votes
0 answers
69 views

Are metaclasses objects? [duplicate]

I always hear or read that 'everything in Python is an object'. This sentence is really helpful for beginner programmers as myself, and I was quickly able to understand that classes, methods are ...
Nuraly's user avatar
  • 5
0 votes
1 answer
214 views

How to make generic class inheriting from TypeVar in Python?

How can I create a Generic class in Python, that has the TypeVar as a base class? The minimum example is this: from typing import TypeVar, Generic T = TypeVar("T") class A(T, Generic[T]): ...
Petr's user avatar
  • 498
0 votes
1 answer
115 views

Metaclass isinstance not working as expected

I've got the following class hiearchy: class Acting: pass class Observing: pass class AgentMeta(type): def __instancecheck__(self, instance: Any) -> bool: return isinstance(instance, ...
KindaTechy's user avatar
  • 1,153
0 votes
1 answer
120 views

How create a metaclass for a SQLAlchemy model?

For example: I want the metaclass to find all fields that start with "any_" and create new fields with different prefixes. I try like this: class MyModelMeta(type): def __new__(mcs, name,...
Boris Mirzakhanyan's user avatar
3 votes
2 answers
206 views

Printing class names of all loaded classes using JVMTI

I am using JNI and JVMTI with C++ with the goal of printing all class names of a target java application. The problem I am experiencing is that it crashes when trying to call the getName() method from ...
UnSure's user avatar
  • 128
0 votes
0 answers
74 views

Designing an Optional Dependency Abstract Class

Or how to design an abstract class A such that A() or A.anything throws 'dependency missing' error but when inheriting like B(A), A behaves like a usual abc.ABC class? In one of my software projects ...
Tim's user avatar
  • 111
1 vote
0 answers
151 views

Python 3.10+ deconstructing an over engineered solution to better understand how metaclasses work with properties, static methods, and classmethods

TL;DR This question examines an over-engineered example of python metaclasses and dataclasses to create a LiteralEnum (for validating a stringly-typed keyword argument) like LinkageMethod and a ...
SumNeuron's user avatar
  • 5,068
0 votes
1 answer
133 views

Python Hierarchical data structure with inheritance

I would to like to create a metaclass for a hierarchical data structure and write a framework for others to use. I found this answer very helpful: https://codereview.stackexchange.com/a/162702/275475 ...
machinev5's user avatar
1 vote
1 answer
151 views

What's the correct type hint for a metaclass method in Python that returns a class instance?

In the example below, __getitem__ indicates the class type as a hint, rather than return of a SpecialClass object. from typing import Self class SpecialMeta(type): def __getitem__(cls, key) -> ...
jheddings's user avatar
  • 27.4k
0 votes
3 answers
63 views

Forcing overriden method to call base method implementation

class Base: def method(self): print("Base method called") class Derived(Base): def method(self): print("Derived method called") I would like to find a way ...
Tommy's user avatar
  • 11
0 votes
2 answers
95 views

How to inherit from a module specified by an argument

Say I have several version of APIs, each have same interface (attributes and function names), they are designed to be inherited in my custom class and rewrite the OnCallback function. # api1.py class ...
aEgoist's user avatar
  • 31
1 vote
1 answer
43 views

Grails how to change a metaclass Method

I'm trying to remove the square brackets that appear in toString off all collections in Grails. These square brackets are added in the toString of the java.util.AbstractCollection class. So the goal ...
Victor Soares's user avatar
4 votes
1 answer
170 views

How can I create a FractionEnum in Python without a metaclass conflict?

I am trying to create a FractionEnum similar to StrEnum or IntEnum. My first attempt resulted in a metaclass conflict: class FractionEnum(fractions.Fraction, Enum): VALUE_1 = 1, 1 VALUE_2 = 8,...
Paul's user avatar
  • 301
0 votes
3 answers
31 views

Primitives class variables of metaclass not shared between subclasses in python, but objects are, why?

consider these two pieces of code: class M(type): hey = [] class S(metaclass=M): pass class N(metaclass=M): pass print(S.hey) # output [] print(N.hey) # output [] S.hey.append(6) ...
Amir Kooshky's user avatar
5 votes
1 answer
445 views

Why does object.__new__ accept parameters?

Besides the obvious asking "again" about __new__ and __init__ in Python - I can ensure, I know what it does. I'll demonstrate some strange and to my opinion undocumented behavior, for which ...
Paebbels's user avatar
  • 16k
2 votes
2 answers
870 views

why keyword argument are not passed into __init_subclass__(..)

Code: class ExternalMeta(type): def __new__(cls, name, base, dct, **kwargs): dct['district'] = 'Jiading' x = super().__new__(cls, name, base, dct) x.city = 'Shanghai' ...
shan's user avatar
  • 265
1 vote
1 answer
122 views

Unsubscriptable "cls" and missing "bases" and "classdict" warning from Pylint

I have create a metaclass based on the EnumMeta, in order to add "contains" functionality to my derived Enum class. Here is my code: class MetaEnum(EnumMeta): def __contains__(cls, ...
Nikolaos Paximadakis's user avatar
0 votes
1 answer
154 views

Metaclass "TypeError: Config_setup.__init__() takes from 1 to 2 positional arguments but 4 were given"

I faced the following error: in <module> class Config(metaclass=Config_setup): TypeError: Config_setup.__init__() takes from 1 to 2 positional arguments but 4 were given I don't know how ...
samira's user avatar
  • 1
0 votes
1 answer
339 views

Dynamically define class with inheritance and static attributes (sqlmodel / sqlalchemy metaclasses)

I have the following class definition that I would like to make dynamic: class SQLModel_custom(SQLModel, registry=self.mapper_registry): metadata = MetaData(schema=self.schema) I've tried ...
ibi0tux's user avatar
  • 2,559
-1 votes
1 answer
93 views

How to recreate the same "base and instance of" relationship that `object` and `type` hold in Python?

I'm learning knowledge about metaclass recently. I learnt that isinstance(object, type) and issubclass(type, object). I want to write self-defined class act like object and type, but how to declare ...
wangjianyu's user avatar
0 votes
1 answer
218 views

How to add attributes in predefined metaclasses in magicDraw?

I want to create metamodel based on uml so i need to add attributes at predefined metaclass level like Operation and Parameter but i don't know how, although in a specific article he can add ...
Amani LEUCHEHEB's user avatar
2 votes
2 answers
681 views

PyCharm gives me a type warning about my metaclass; mypy disagrees

I was trying to write a metaclass named Singleton, that, of course, implement the singleton design pattern: class Singleton(type): def __new__(cls, name, bases = None, attrs = None): if ...
InSync's user avatar
  • 8,554

1
2 3 4 5
25