How to add method using metaclass
How do I add an instance method to a class using a metaclass (yes I do need to use a metaclass)? The following kind of works, but the func_name will still be "foo":
def bar(self):
print "bar"
class MetaFoo(type):
def __new__(cls, name, bases, dict):
dict["foobar"] = bar
return type(name, bases, dict)
class Foo(object):
__metaclass__ = MetaFoo
>>> f = Foo()
>>> f.foobar()
bar
>>> f.foobar.func_name
'bar'
My problem is that some library code actually uses the func_name and later fails to find the 'bar' method of the Foo instance. I could do:
dict["foobar"] = types.FunctionType(bar.func_code, {}, "foobar")
There is also types.MethodType, but I need an instance that does'nt exist yet to use that. Am I missing someting here?
Asked by: Lenny452 | Posted: 27-01-2022
Answer 1
Try dynamically extending the bases that way you can take advantage of the mro and the methods are actual methods:
class Parent(object):
def bar(self):
print "bar"
class MetaFoo(type):
def __new__(cls, name, bases, dict):
return type(name, (Parent,) + bases, dict)
class Foo(object):
__metaclass__ = MetaFoo
if __name__ == "__main__":
f = Foo()
f.bar()
print f.bar.func_name
Answered by: Thomas346 | Posted: 28-02-2022
Answer 2
I think what you want to do is this:
>>> class Foo():
... def __init__(self, x):
... self.x = x
...
>>> def bar(self):
... print 'bar:', self.x
...
>>> bar.func_name = 'foobar'
>>> Foo.foobar = bar
>>> f = Foo(12)
>>> f.foobar()
bar: 12
>>> f.foobar.func_name
'foobar'
Now you are free to pass Foo
s to a library that expects Foo
instances to have a method named foobar
.
Unfortunately, (1) I don't know how to use metaclasses and (2) I'm not sure I read your question correctly, but I hope this helps.
Note that func_name
is only assignable in Python 2.4 and higher.
Similar questions
Python How to call child class method from Parent metaclass
I am trying to write my own implementation of test runner, what I struggle with is some kind of setUp and TearDown methods and how to override/invoke them.
class MetaTestCase(type):
def __call__(self, *args, **kwds):
return super().__call__(*args, **kwds)
def __new__(self, name, bases, attrs):
def replaced_fnc(fn):
def new_test(*args, **kwargs):
self.befo...
Python metaclass and the object base class
After reading the excellent SO post, I tried crafting a module level metaclass:
def metaclass(future_class_name, future_class_parents, future_class_attrs):
print "module.__metaclass__"
future_class_attrs["bar"]="bar"
return type(future_class_name, future_class_parents, future_class_attrs)
__me...
Python Metaclass did not change the class when used
I found this question while i searched the usage of metaclass in python.It's a good question with a wonderful answer,See Here.But while i followed the example like this:
class UpperAttrMetaclass(type):
def __new__(cls, name, bases, dct):
attrs = ((name, value) for name, value in dct.items() if not name.star...
python - How do I create a proper metaclass for my task?
I have task creating an iterable class which on iter returns an iterator on the list of instance already created from this class, for example:
x = SomeClass()
y = SomeClass()
for obj in SomeClass:
print obj
>><__main__.SomeClass object at .......> and etc
I made it through the metaclass and globals(). It looks terrible, but it works. And I want to find a mo...
python - How do I create a simple metaclass?
I've been doing Python for some time now, and I've always somewhat understood the meaning of metaclasses, but I've never needed one.
Now I think the best solution for my problem is a metaclass (correct me if there's a better way).
What I'm trying to create is a system which automatically adds a class variable n and a list instances to each class of mine. Here's a simplified example of one ...
python - Why is the metaclass not being used in this case?
My question is two-fold: First, I don't understand why the__new__() method of theMetaBoundedInt metaclass is not being called by the definition of the classBoundedIntand secondly would like to know how to get it work. At this point, I don't know if it works properly since it's not even being executed -- so my question is not really about that at this point (but if you spot something, ...
Python metaClass and import *
Main Goal: Automatically register classes (by a string) in a factory to be created dynamically at run time using that string, classes can be in their own file and not grouped in one file.
I have couple of classes which all inherit from the same base class and they define a string as their type.
A user wants to get an instance of one of these classes but only knows the type at run time.
Therefore I...
python - How does one create a metaclass?
This question already has answers here:
metaclass - Python 3 type is both an object and class?
I am reading Learning python. Regarding metaclass, the book said type is an object and also is itself class. I am trying to search python doc online but don't see any similar description. Can someone point me any official doc?
Thinking a bit more on this statement that type is both object and class, I think it makes sense.
The reasons are as following.
type is callable, seeing...
oop - Python class design with metaclass
I have a class design where the Children classes inheriting from a certain Parent class just differ in some parameters, but the Parent class contains all methods, which are using the parameters provided as class variables on the Children. So, in other words, each of my Child classes is fully described by the list of parameters
python - Want a class that will behave like an ABC but also a metaclass
One of the answers to a previous question I asked suggests the use of a metaclass.
class DogType(type):
def __init__(cls, name, bases, attrs):
""" this is called at the Dog-class creation time. """
if not bases:
return
#pick the habits of direct ancestor and...
python - How to draw a class's metaclass in UML?
If class A is created by its __metaclass M, how does the arrow look in UML?
The stereotype syntax seems to be related.
I didn't look in
metaclass - Modifying a Python class
I'd like to modify all classes in Python. For example str and int and others like Person(object).
I'd like to add an attribute to them and to change the way its methods works.
Which is the best approach for this? Metaclasses?
python - "Error when calling the metaclass bases" when declaring class inside a module
Let me start by saying, I also get the same error whey defining __init__ and running super()'s __init__. I only simplified it down to this custom method to see if the error still happened.
import HTMLParser
class Spider(HTMLParser):
"""
Just a subclass.
"""
This alone in a module raises the following error:
Traceback (most...
python - Should I use a metaclass, class decorator, or override the __new__ method?
Here is my problem. I want the following class to have a bunch of property attributes. I could either write them all out like foo and bar, or based on some other examples I've seen, it looks like I could use a class decorator, a metaclass, or override the __new__ method to set the properties automagically. I'm just not sure what the "right" way to do it would be.
cl...
python: subclass a metaclass
For putting methods of various classes into a global registry I'm using a decorator with a metaclass. The decorator tags, the metaclass puts the function in the registry:
class ExposedMethod (object):
def __init__(self, decoratedFunction):
self._decoratedFunction = decoratedFunction
def __call__(__self,*__args,**__kw):
return __self._decoratedFunction(*__args,**__kw)
class ExposedM...
metaclass - Calling a method with getattr in Python
How to call a method using getattr?
I want to create a metaclass, which can call non-existing methods of some other class that start with the word 'oposite_'. The method should have the same number of arguments, but to return the opposite result.
def oposite(func):
return lambda s, *args, **kw: not oposite(s, *args, **kw)
class Negate(type):
def __getattr__(self, name):
if name.startswit...
python - Metaclass Mixin or Chaining?
Is it possible to chain metaclasses?
I have class Model which uses __metaclass__=ModelBase to process its namespace dict. I'm going to inherit from it and "bind" another metaclass so it won't shade the original one.
First approach is to subclass class MyModelBase(ModelBase):
MyModel(Model):
__metaclass__ = MyModelBase # inherits from `ModelBase`
Create instance method in metaclass using partial in Python 3
Using metaclasses, I am trying to create an instance method by simplifying an existing instance method. The problem is that partial does not work with instance method. This is a simple example of what I try to achieve:
from functools import partial
class Aclass(object):
def __init__(self, value):
self._value = value
def complex(self, a, b):
...
python - metaclass conflict with ctypes Structure
I'm trying to create a metaclass for the class I created here: ctypes variable length structures
I want to simplify the Points class so it looks like this (Python 3.2):
class Points(c.Structure, metaclass=VariableMeta):
_fields_ = [
('num_points', c.c_uint32),
('points', 'P...
Python 2.x metaclass generated wrappers break inspect
I'm having an issue where I have wrapped some class methods using a metaclass, but now if I use the help() built-in the methods are displayed as the wrapper instead of the original method.
# Example:
class MetaBuilderModule(type):
@staticmethod
def time_method(method):
@functools.wraps(method)
def __wrapper(self, *args, **kwargs):
if self.__timingstatus__[method.__name_...
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python