Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #10282 > unrolled thread

Trying to learn about metaclasses

Started by"Steven W. Orr" <steveo@syslang.net>
First post2011-07-25 11:36 -0400
Last post2011-07-31 10:48 +1000
Articles 5 — 5 participants

Back to article view | Back to comp.lang.python


Contents

  Trying to learn about metaclasses "Steven W. Orr" <steveo@syslang.net> - 2011-07-25 11:36 -0400
    Re: Trying to learn about metaclasses jfine <jonathan.fine1@googlemail.com> - 2011-07-25 08:46 -0700
      Re: Trying to learn about metaclasses Karim <karim.liateni@free.fr> - 2011-07-25 19:26 +0200
    Re: Trying to learn about metaclasses "bruno.desthuilliers@gmail.com" <bruno.desthuilliers@gmail.com> - 2011-07-30 10:02 -0700
      Re: Trying to learn about metaclasses Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-07-31 10:48 +1000

#10282 — Trying to learn about metaclasses

From"Steven W. Orr" <steveo@syslang.net>
Date2011-07-25 11:36 -0400
SubjectTrying to learn about metaclasses
Message-ID<mailman.1460.1311608302.1164.python-list@python.org>
I have been doing a lot of reading. I'm starting to get it. I think it's 
really cool as well as dangerous, but I plan on being respectful of the 
construct. I found a web page that I found quite readable.

http://cleverdevil.org/computing/78/

So, I tried to run the example code (below), and I get AttributeError. If 
someone can get me over this hump, I'd be grateful. It complains that Person 
has no _fields attribute, but the print hello I have in EnforcerMeta doesn't 
happen either. Am I doing something wrong?

I'm running python 2.6.2

Here's the error:

585 > ./meta1.py
Traceback (most recent call last):
   File "./meta1.py", line 38, in <module>
     swo.name = 'swo'
   File "./meta1.py", line 27, in __setattr__
     if key in self._fields:
AttributeError: 'Person' object has no attribute '_fields'


And here's the code:

#! /usr/bin/python
# http://cleverdevil.org/computing/78/
class Field(object):
     def __init__(self, ftype):
         self.ftype = ftype

     def is_valid(self, value):
         return isinstance(value, self.ftype)

class EnforcerMeta(type):
     def __init(cls, name, bases, ns):
         # Store the field definitions on the class as a dictionary
         # mapping the field name to the Field instance.
         print 'Hello'
         cls._fields = {}

         # loop through the namespace looking for Field instances.
         for key, value in ns.items():
             if isinstance(value, Field):
                 cls._fields[key] = value

class Enforcer(object):
     # attach the metaclass
     __metaclass__ = EnforcerMeta

     def __setattr__(self, key, value):
         if key in self._fields:
             if not self._fields[key].is_valid(value):
                 raise TypeError('Invalid type for field.')
         super(Enforcer, self).__setattr__(key, value)

class Person(Enforcer):
     name = Field(str)
     age = Field(int)

if __name__ == '__main__':
     swo = Person()
     swo.name = 'swo'
     print 'swo:', swo


-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net

[toc] | [next] | [standalone]


#10283

Fromjfine <jonathan.fine1@googlemail.com>
Date2011-07-25 08:46 -0700
Message-ID<9b81f0d8-3cbd-4020-a1db-edcfba625fcd@g2g2000vbl.googlegroups.com>
In reply to#10282
Hi

I gave a tutorial at this year's EuroPython that covered metaclasses.
You can get the tutorial materials from a link on:
http://ep2011.europython.eu/conference/talks/objects-and-classes-in-python-and-javascript


Jonathan

[toc] | [prev] | [next] | [standalone]


#10295

FromKarim <karim.liateni@free.fr>
Date2011-07-25 19:26 +0200
Message-ID<mailman.1466.1311614797.1164.python-list@python.org>
In reply to#10283
Very good.

Karim

On 07/25/2011 05:46 PM, jfine wrote:
> Hi
>
> I gave a tutorial at this year's EuroPython that covered metaclasses.
> You can get the tutorial materials from a link on:
> http://ep2011.europython.eu/conference/talks/objects-and-classes-in-python-and-javascript
>
>
> Jonathan

[toc] | [prev] | [next] | [standalone]


#10590

From"bruno.desthuilliers@gmail.com" <bruno.desthuilliers@gmail.com>
Date2011-07-30 10:02 -0700
Message-ID<40772fd8-dcda-411f-99d1-7539418e07d0@y13g2000yqy.googlegroups.com>
In reply to#10282
On 25 juil, 17:36, "Steven W. Orr" <ste...@syslang.net> wrote:
> I have been doing a lot of reading. I'm starting to get it. I think it's
> really cool as well as dangerous,

Dangerous ??? Why so ? Is there anything "dangerous" in a constructor
or an initialiser ??? A metaclass is just a class, and a class is just
an object.

[toc] | [prev] | [next] | [standalone]


#10609

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2011-07-31 10:48 +1000
Message-ID<4e34a653$0$29996$c3e8da3$5496439d@news.astraweb.com>
In reply to#10590
bruno.desthuilliers@gmail.com wrote:

> On 25 juil, 17:36, "Steven W. Orr" <ste...@syslang.net> wrote:
>> I have been doing a lot of reading. I'm starting to get it. I think it's
>> really cool as well as dangerous,
> 
> Dangerous ??? Why so ? Is there anything "dangerous" in a constructor
> or an initialiser ??? A metaclass is just a class, and a class is just
> an object.


Obviously not dangerous in the sense of "Arghh, I just lost a finger!!!" :)

I think it is fair to talk about language features' power on a continuum,
where something like 1+1 has very little power (it just adds two numbers),
classes have more power, metaclasses more again, and exec even more still.
Power can be used for good things, but it can also be used for bad. I
consider metaclasses to be about equal in power to decorators, but more
obscure and less straightforward. Consider a decorator example:

@decorate
def func(x):
    return x+1


func(42)
=> returns "the result is 43"

Surprise! What the function does is barely related to the code you can see.
That's surprising and therefore dangerous. Metaclasses give you the same
ability to surprise the reader, hence, dangerous. That's not necessarily a
bad thing: an oxy-acetylene torch is dangerous, and you shouldn't use one
for lighting a cigarette, but if you need to cut through iron bars in a
hurry, it gets the job done.



-- 
Steven

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web