<p>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":</p>

<pre><code>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

&gt;&gt;&gt; f = Foo()
&gt;&gt;&gt; f.foobar()
bar
&gt;&gt;&gt; f.foobar.func_name
'bar'
</code></pre>

<p>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:</p>

<pre><code>dict["foobar"] = types.FunctionType(bar.func_code, {}, "foobar")
</code></pre>

<p>There is also types.MethodType, but I need an instance that does'nt exist yet to use that. Am I missing someting here?</p>

[{'answer_id': 65682, 'author': 'Nathan Shively-Sanders', 'author_id': 7851, 'author_profile': 'https://Stackoverflow.com/users/7851', 'pm_score': 2, 'selected': False, 'text': "<p>I think what you want to do is this:</p>\n\n<pre><code>&gt;&gt;&gt; class Foo():\n...   def __init__(self, x):\n...     self.x = x\n... \n&gt;&gt;&gt; def bar(self):\n...   print 'bar:', self.x\n... \n&gt;&gt;&gt; bar.func_name = 'foobar'\n&gt;&gt;&gt; Foo.foobar = bar\n&gt;&gt;&gt; f = Foo(12)\n&gt;&gt;&gt; f.foobar()\nbar: 12\n&gt;&gt;&gt; f.foobar.func_name\n'foobar'\n</code></pre>\n\n<p>Now you are free to pass <code>Foo</code>s to a library that expects <code>Foo</code> instances to have a method named <code>foobar</code>.</p>\n\n<p>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. </p>\n\n<p>Note that <code>func_name</code> is only assignable in Python 2.4 and higher.</p>\n"}, {'answer_id': 65716, 'author': 'Aaron Maenpaa', 'author_id': 2603, 'author_profile': 'https://Stackoverflow.com/users/2603', 'pm_score': 5, 'selected': True, 'text': '<p>Try dynamically extending the bases that way you can take advantage of the mro and the methods are actual methods:</p>\n\n<pre><code>class Parent(object):\n    def bar(self):\n        print "bar"\n\nclass MetaFoo(type):\n    def __new__(cls, name, bases, dict):\n        return type(name, (Parent,) + bases, dict)\n\nclass Foo(object):\n    __metaclass__ = MetaFoo\n\nif __name__ == "__main__":\n    f = Foo()\n    f.bar()\n    print f.bar.func_name\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/65400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5179/']