473,738 Members | 5,084 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question on metaclasses

Hello,

I've been experimenting with metaclasses a bit (even though I am quite
a newbie to python) and stumpled over the following problem in my code:

class Meta(type):
def __init__(cls, name, bases, dct):
for attr, value in dct.items():
if callable(value) :
dct[attr] = wrapper(value)

wrapper adds debugging-information to methods of the class (at least
that is my plan).

Using dct[attr] = wrapper(value) does not result in wrapped methods,
though. Using setattr(cls, attr, wrapper(value)) creates the desired
effect, though.

Why are the changes to dct not visible in the instantiated class? Is
dct not the namespace of the class currently instantiated?
best regards
Steffen

Jul 19 '05 #1
9 1195
Steffen Glückselig wrote:
Hello,

I've been experimenting with metaclasses a bit (even though I am quite
a newbie to python) and stumpled over the following problem in my code:

class Meta(type):
def __init__(cls, name, bases, dct):
for attr, value in dct.items():
if callable(value) :
dct[attr] = wrapper(value)

wrapper adds debugging-information to methods of the class (at least
that is my plan).

Using dct[attr] = wrapper(value) does not result in wrapped methods,
though. Using setattr(cls, attr, wrapper(value)) creates the desired
effect, though.

Why are the changes to dct not visible in the instantiated class? Is
dct not the namespace of the class currently instantiated?


You don't use metaclasses correctly I believe. Usage should look like this:

class Foo(type):
def __new__(cls, name, bases, dict):

for k,v in [(k, v) for k,v in dict.items() if callable(v)]:
cls.wrap(k,v,cl s.get_directive s(v), dict)

return super(Foo, self).__new__(s elf, name, bases, dict)

Notice the __new__ instead of __init__, and the call to (actually, through
super) type.__new__

--
Regards,

Diez B. Roggisch
Jul 19 '05 #2
> class Foo(type):
def __new__(cls, name, bases, dict):

for k,v in [(k, v) for k,v in dict.items() if callable(v)]:
cls.wrap(k,v,cl s.get_directive s(v), dict)

return super(Foo, self).__new__(s elf, name, bases, dict)


There is a confusion of self and cls above - rename self with cls.
--
Regards,

Diez B. Roggisch
Jul 19 '05 #3
Diez B. Roggisch wrote:
Steffen Glückselig wrote:
Hello,

I've been experimenting with metaclasses a bit (even though I am quite
a newbie to python) and stumpled over the following problem in my code:

class Meta(type):
def __init__(cls, name, bases, dct):
for attr, value in dct.items():
if callable(value) :
dct[attr] = wrapper(value)

wrapper adds debugging-information to methods of the class (at least
that is my plan).

Using dct[attr] = wrapper(value) does not result in wrapped methods,
though. Using setattr(cls, attr, wrapper(value)) creates the desired
effect, though.

Why are the changes to dct not visible in the instantiated class? Is
dct not the namespace of the class currently instantiated?


You don't use metaclasses correctly I believe. Usage should look like this:

class Foo(type):
def __new__(cls, name, bases, dict):

for k,v in [(k, v) for k,v in dict.items() if callable(v)]:
cls.wrap(k,v,cl s.get_directive s(v), dict)

return super(Foo, self).__new__(s elf, name, bases, dict)

^^^^ ^^^^
self is not bound in your method; use

return super(Foo, cls).__new__(na me, bases, dict)

Reinhold
Jul 19 '05 #4
Diez B. Roggisch wrote:
class Foo(type):
def __new__(cls, name, bases, dict):

for k,v in [(k, v) for k,v in dict.items() if callable(v)]:
cls.wrap(k,v,cl s.get_directive s(v), dict)

return super(Foo, self).__new__(s elf, name, bases, dict)


There is a confusion of self and cls above - rename self with cls.


And remove the first argument to __new__.

Reinhold
Jul 19 '05 #5
Are wrap and get_directives somehow built-in? I couldn't find
references to them.

I've noticed, too, that using __new__ I can manipulate the dictionary
resulting in the behavior I intented.

I'd rather like to know: Why does it work in __new__ but not in
__init__?

And, stimulated by your response: Why is using __new__ superior to
__init__?
best regards
Steffen

Jul 19 '05 #6
Steffen Glückselig wrote:
Are wrap and get_directives somehow built-in? I couldn't find
references to them.

I've noticed, too, that using __new__ I can manipulate the dictionary
resulting in the behavior I intented.

I'd rather like to know: Why does it work in __new__ but not in
__init__?

And, stimulated by your response: Why is using __new__ superior to
__init__?


At short, __new__ is called on the class and must return the instance; that
means that the instance isn't created yet.

__init__, on the other hand, is called on the instance which is already created
at that point. So changing dct in __init__ is pointless, because the instance
(which is a class actually) is already created.

Reinhold
Jul 19 '05 #7
Reinhold Birkenfeld wrote:
Diez B. Roggisch wrote:
class Foo(type):
def __new__(cls, name, bases, dict):

for k,v in [(k, v) for k,v in dict.items() if callable(v)]:
cls.wrap(k,v,cl s.get_directive s(v), dict)

return super(Foo, self).__new__(s elf, name, bases, dict)


There is a confusion of self and cls above - rename self with cls.


And remove the first argument to __new__.


Ehm, no, I don't think so. The code was copied and pasted from a working
metaclass (at least I hope so...), and in the original code a underscore
was used for the first argument. I've been following that bad habit for a
while but recently started to be more following to the established
conventions. So I rewrote that code on the fly.

This is the full metaclass:

class TransactionAwar e(type):
TAS_REX = re.compile("tas ::([^, ]+(, *[^, ]+)*)")
WRAPPERS = {
"create" : w_create,
"active" : w_active,
"bind" : w_bind,
"sync" : w_sync,
"autocommit " : w_autocommit,
}
def __new__(_, name, bases, dict):

for k,v in [(k, v) for k,v in dict.items() if callable(v)]:
_.wrap(k,v,_.ge t_directives(v) , dict)

return super(Transacti onAware, _).__new__(_, name, bases, dict)

def wrap(_, name, fun, ds, dict, level=0):
if ds:
d, rest = ds[0], ds[1:]
key = "_taw_%s_%i " % (name, level)
try:
w_fun = _.WRAPPERS[d](key)
dict[key] = fun
_.wrap(name, w_fun, rest, dict, level+1)
except KeyError, e:
print "No transaction aware property named %s" % d
raise e
else:

dict[name] = fun

wrap = classmethod(wra p)

def get_directives( _, v):
try:
doc = v.__doc__
res = []
if doc:
for l in doc.split("\n") :
m = _.TAS_REX.match (l.strip())
if m:
res += [s.strip() for s in m.group(1 ).split(",")]
res.reverse()
return res
except KeyError:
return []
get_directives = classmethod(get _directives)

--
Regards,

Diez B. Roggisch
Jul 19 '05 #8
So dct is something like a template rather than the __dict__ of the
actual class?

I'd assume that changing the content of a dict would be possible even
after it has been assigned to some object (here, a class).
thanks and best regards
Steffen

Jul 19 '05 #9
Diez B. Roggisch wrote:
Reinhold Birkenfeld wrote:
Diez B. Roggisch wrote:
class Foo(type):
def __new__(cls, name, bases, dict):

for k,v in [(k, v) for k,v in dict.items() if callable(v)]:
cls.wrap(k,v,cl s.get_directive s(v), dict)

return super(Foo, self).__new__(s elf, name, bases, dict)

There is a confusion of self and cls above - rename self with cls.


And remove the first argument to __new__.


Ehm, no, I don't think so. The code was copied and pasted from a working
metaclass (at least I hope so...), and in the original code a underscore
was used for the first argument. I've been following that bad habit for a
while but recently started to be more following to the established
conventions. So I rewrote that code on the fly.


Oh yes. I forgot that __new__ is a staticmethod anyhow.

Reinhold
Jul 19 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1910
by: Stephan Diehl | last post by:
I have a question about metaclasses: How would be the best way to "merge" different metaclasses? Or, more precisely, what is the best way to merge metaclass functionality? The idea is basicly the following: One has several (metaclass) modules that implements an interesting feature. Lets say, I have a metaclass L, that adds logging capabilities to all method calls and another one, called P, that creates properties on the fly.
3
2095
by: Mike C. Fletcher | last post by:
Slides from my PyGTA presentation on Tuesday, focusing mostly on why/where you would want to use meta-classes, are available in PDF format: http://members.rogers.com/mcfletch/programming/metaclasses.pdf BTW, for those not on Python-list, be sure to check out David & Michele's newest developerworks article on the topic: http://www.ibm.com/developerworks/library/l-pymeta.html...
27
2010
by: Michele Simionato | last post by:
> Hello, my name is Skip and I am metaclass-unaware. I've been programming in > Python for about ten years and I have yet to write a metaclass. At first I > thought it was just that metaclasses were new to the language, but now as > more and more people use them and proclaim their widespread benefits, I have > come to realize that through years of abuse my brain has become addicted to > classic classes. I began using Python since...
1
2508
by: Alan Isaac | last post by:
Forman's book is out of print. Is there a good substitute? Thanks, Alan Isaac
0
8968
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8787
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9334
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9259
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9208
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6750
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4569
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4824
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3279
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.