<?xml version="1.0" encoding="UTF-8"?>
<feed version="0.3" xmlns="http://purl.org/atom/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/"><title type="text/plain">:: cleverdevil ::</title>
<tagline type="text/plain">:: Jonathan LaCour :: clever devil ::</tagline>
<link rel="alternate" type="text/html" href="http://cleverdevil.org/" />
<id>tag:cleverdevil.org,2012:/</id>
<generator url="http://textpattern.com" version="g1.17">Textpattern</generator>
<modified>2009-05-06T17:02:51Z</modified>
<author>
		<name>Jonathan LaCour</name>
		<email>&#106;&#111;&#110;&#97;&#116;&#104;&#97;&#110;&#64;&#99;&#108;&#101;&#118;&#101;&#114;&#100;&#101;&#118;&#105;&#108;&#46;&#111;&#114;&#103;</email>
		<url>http://cleverdevil.org/</url>
</author>
<entry>
		<issued>2009-01-29T15:01:00Z</issued>
		<modified>2009-01-29T15:29:23Z</modified>
		<title>Buy My Expertise and Save Lives!</title>
		<link rel="alternate" type="text/html" href="http://cleverdevil.org/computing/79/" />
		<id>tag:cleverdevil.org,2009-01-29:79</id>
		<dc:subject>programming</dc:subject>
		<content type="text/html" mode="escaped" xml:lang="en">
	&lt;p&gt;&lt;center&gt;&lt;div style=&quot;background: #003A7C; border: 3px solid #002D60; padding: 0 10px 10px 10px; width: 396px;&quot;&gt;&lt;/p&gt;
 &lt;img src=&quot;http://thirstrelief.shootq.com/img/shootq_thirstrelief_logo.png&quot; /&gt;&lt;br /&gt;
&lt;/div&gt;&lt;/center&gt;

	&lt;p&gt;I&amp;#8217;m proud to report that my employer, &lt;a href=&quot;http://web.shootq.com&quot;&gt;ShootQ&lt;/a&gt; is sponsoring the &lt;a href=&quot;http://thirstrelief.shootq.com&quot;&gt;ThirstRelief Mentor Auction&lt;/a&gt; to benefit &lt;a href=&quot;http://thirstrelief.org&quot;&gt;ThirstRelief International&lt;/a&gt;. Bidding starts tonight, Thursday, January 29 at 10 p.m. EST. If you have any interest in photography, I&amp;#8217;d encourage you to participate in the auction, as there are some great opportunities available to interact with some of the best in the world.&lt;/p&gt;

	&lt;p&gt;One of the auctions available to bid on is a 90-minute mentor session with the ShootQ development team, including yours truly. While we may not be as glitzy as some of the other folks up for auction, I&amp;#8217;d like to think that we could still fetch a nice sum. So &lt;a href=&quot;http://thirstrelief.shootq.com&quot;&gt;join in the cause, and start bidding&lt;/a&gt; tonight!&lt;/p&gt;

	&lt;p&gt;Its a joy to be a part of a business that puts such an emphasis on making a difference in the world, and I am excited to be able to chip in a bit myself.&lt;/p&gt;


 
</content>
</entry>
<entry>
		<issued>2009-01-10T17:46:00Z</issued>
		<modified>2009-01-10T18:31:36Z</modified>
		<title>Metaclasses Demystified [5]</title>
		<link rel="alternate" type="text/html" href="http://cleverdevil.org/computing/78/" />
		<id>tag:cleverdevil.org,2009-01-10:78</id>
		<dc:subject>turbogears</dc:subject>
		<content type="text/html" mode="escaped" xml:lang="en">
&lt;p&gt;&lt;i&gt;This article originally appeared in the July 2008 issue of &lt;a href=&quot;http://pymag.phparch.com/&quot;&gt;Python
Magazine&lt;/a&gt; and was adapted from Jonathan LaCour&amp;#8217;s
&lt;a href=&quot;http://cleverdevil.org/train&quot;&gt;CLEVERtrain&lt;/a&gt; professional Python training services.&lt;/i&gt;&lt;/p&gt;


	&lt;p&gt;The word &amp;#8220;metaclass&amp;#8221; often strikes fear into the hearts of Python
programmers. This article explores metaclasses in an approachable way, in
order to take the mystery out of metaclasses, and enable you to leverage
metaprogramming techniques to solve real problems.&lt;/p&gt;


	&lt;p&gt;There are few things in the Python world that are so misunderstood and
feared as metaclasses. In fact, when I recently was training a group of
seasoned programmers about metaclasses, I asked the room what sprung to mind
when they heard the word &amp;#8220;metaclass.&amp;#8221; The students shouted out their feelings
in chorus â &amp;#8220;confusing,&amp;#8221; &amp;#8220;magical,&amp;#8221; and worst of all, &amp;#8220;difficult.&amp;#8221;&lt;/p&gt;


	&lt;p&gt;Well, as I told my students that day, when it comes to metaclasses, I&amp;#8217;d
recommend that we called upon the wise words of Douglas Adams in his famed
book &amp;#8220;The Hitchhiker&amp;#8217;s Guide to the Galaxy.&amp;#8221;&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;&amp;#8220;Don&amp;#8217;t panic!&amp;#8221;&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;Once you take a closer look at how object-oriented programming works in
Python, you&amp;#8217;ll quickly discover that not only are metaclasses easy, they&amp;#8217;re
also extremely useful. Here, we&amp;#8217;ll do our best to take all of the mystery out
of metaclasses, and show you that there&amp;#8217;s nothing to be afraid of!&lt;/p&gt;


	&lt;h2&gt;Revisiting Classes&lt;/h2&gt;


	&lt;p&gt;Most Python programmers are familiar with creating classes, and might even
create or modify their own classes several times a week in the course of their
work. Many of us were even taught about classes and object-oriented
programming in the course of our education. But, when was the last time any of
us really thought about classes in depth since we were first introduced to the
concept? I&amp;#8217;d wager that most of us take classes for granted, and don&amp;#8217;t really
think about what they are providing for us, and more importantly, &lt;em&gt;how&lt;/em&gt; they
provide it to us.&lt;/p&gt;


	&lt;p&gt;Understanding metaclasses can be greatly simplified by taking another look
at Python classes, from a slightly different perspective. In order to do this,
lets pose a simple question. What exactly does a class &lt;em&gt;do&lt;/em&gt;?&lt;/p&gt;


	&lt;p&gt;My first instinct when attempting to answer this question is to rely on my
education, which unearths big, fancy, computer-sciency words like
&amp;#8220;encapsulation&amp;#8221; and &amp;#8220;abstraction.&amp;#8221; Its tempting to allow this to cloud our
thinking, so lets do our best to think at a much simpler level when
considering this question. So, I ask again â what does a class do?&lt;/p&gt;


	&lt;p&gt;Fundamentally, a class is used to construct objects called &lt;em&gt;instances&lt;/em&gt;.
This is essentially all a class does â creates instances. The process of
creating instances using a class is called &lt;em&gt;instantiation&lt;/em&gt;. For example, given
a class &lt;code&gt;Person&lt;/code&gt;, we can instantiate it to create an &amp;#8220;instance&amp;#8221; of that
&lt;code&gt;Person&lt;/code&gt; class.&lt;/p&gt;


&lt;code&gt;&lt;pre&gt;
    class Person(object):
        pass

    jonathan = Person()
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;This instance is related back to its class in that the class is what
&lt;em&gt;constructs&lt;/em&gt; the instance. What do we mean by &amp;#8220;construct&amp;#8221;? Well, when a class
is instantiated, it constructs an instance by providing it with its
&amp;#8220;namespace.&amp;#8221; We all know from Tim Peters&amp;#8217; &amp;#8220;The Zen of Python&amp;#8221; that namespaces
are a &amp;#8220;honking great idea,&amp;#8221; and classes are a great example of why! The
attributes in the namespace of a class are used to define the namespace of its
instances, thus providing those instances with behavior and state. Lets
enhance our &lt;code&gt;Person&lt;/code&gt; class, to see how this works.&lt;/p&gt;


&lt;code&gt;&lt;pre&gt;
    &amp;gt;&amp;gt;&amp;gt; class Person(object):
    ...    greeting = 'Hello'
    ...    
    ...    def greet(self, who):
    ...        print self.greeting, who

    &amp;gt;&amp;gt;&amp;gt; jonathan = Person()
    &amp;gt;&amp;gt;&amp;gt; jonathan.greet('Readers')
    'Hello Readers'
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;The &lt;code&gt;Person&lt;/code&gt; class now has two attributes in its namespace â &lt;code&gt;greeting&lt;/code&gt; and
&lt;code&gt;greet&lt;/code&gt;. When we instantiate our &lt;code&gt;Person&lt;/code&gt; class, our instance is given both
state, in the form of the &lt;code&gt;greeting&lt;/code&gt; attribute, and behavior, in the form of
the &lt;code&gt;greet&lt;/code&gt; method. In this way, a class is of critical and primary importance
in defining how its instances will behave.&lt;/p&gt;


	&lt;p&gt;So, what does a class do? Lets summarize. In a nutshell, a class is an
object with constructs instances through a process called instantiation,
therefore defining the namespace, behavior, and state of that instance.&lt;/p&gt;


	&lt;h2&gt;Defining Metaclasses&lt;/h2&gt;


	&lt;p&gt;Now that we&amp;#8217;ve established clearly what a class is, we can confidently pose
the question â what exactly is a metaclass? When sifting through
documentation, the most common answer you&amp;#8217;ll find to that question is short,
but often difficult to unpack:&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;A metaclass is the class of a class.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;While this answer is certainly correct and concise, and tells us what a
metaclass &lt;em&gt;is&lt;/em&gt;, it still doesn&amp;#8217;t tell us what a metaclass &lt;em&gt;does&lt;/em&gt;. Lets look
at an alternate answer to the question:&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;A metaclass is a class whose instances are classes.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;I will concede that this answer is just as much of a mouthful as its
counterpart, but it has the benefit of giving us a clue as to what a metaclass
&lt;em&gt;does&lt;/em&gt;! In short, a metaclass constructs classes. We also know that a
metaclass is just another class, and we&amp;#8217;ve just spent some time outlining what
a class does. As a result, we should be able to build upon what we&amp;#8217;ve learned
about classes earlier to determine a bit more about metaclasses.&lt;/p&gt;


	&lt;p&gt;Recall that a class helps define the behavior and state of its instances.
Metaclasses provide the same basic capability to classes, giving you the
ability to change the way a class will behave at runtime. This technique is
commonly referred to as &amp;#8220;metaprogramming.&amp;#8221;&lt;/p&gt;


	&lt;p&gt;Having a definition of metaclasses and metaprogramming is useful, but lets
take a deeper look by investigating an existing metaclass.&lt;/p&gt;


	&lt;h2&gt;The &lt;code&gt;type&lt;/code&gt; Metaclass&lt;/h2&gt;


	&lt;p&gt;In Python, classes which inherit from &lt;code&gt;object&lt;/code&gt; are called &amp;#8220;new-style
classes.&amp;#8221; All such new-style classes have a default metaclass called &lt;code&gt;type&lt;/code&gt;.
We can prove that &lt;code&gt;type&lt;/code&gt; is the metaclass of &lt;code&gt;object&lt;/code&gt; through simple
introspection in the Python interpreter. Recall, a metaclass is the class of a
class, so what is the class of &lt;code&gt;object&lt;/code&gt;:&lt;/p&gt;


&lt;code&gt;&lt;pre&gt;
    &amp;gt;&amp;gt;&amp;gt; print object.__class__
    &amp;lt;type 'type'&amp;gt;
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;Just as we expected! The metaclass of &lt;code&gt;object&lt;/code&gt; is &lt;code&gt;type&lt;/code&gt;, and thus all
classes which inherit from &lt;code&gt;object&lt;/code&gt; will be provided with this metaclass by
default. Classes that do not inherit from &lt;code&gt;object&lt;/code&gt; are called &amp;#8220;old-style
classes&amp;#8221; and will disappear in Python 3.0. While old-style classes also
support metaclasses and metaprogramming, we&amp;#8217;ll focus on new-style classes in
this article for the sake of simplicity.&lt;/p&gt;


	&lt;p&gt;Typically, classes are defined using the &lt;code&gt;class&lt;/code&gt; statement in Python, as
we saw in our earlier &lt;code&gt;Person&lt;/code&gt; example. However, we have just learned that
metaclasses create classes when they are instantiated. This means that we
should be able to define a class by instantiating the &lt;code&gt;type&lt;/code&gt; metaclass
manually.&lt;/p&gt;


	&lt;p&gt;Lets define our original &lt;code&gt;Person&lt;/code&gt; class again, but this time, lets do it
without using the &lt;code&gt;class&lt;/code&gt; statement by instantiating the &lt;code&gt;type&lt;/code&gt; metaclass:&lt;/p&gt;


&lt;code&gt;&lt;pre&gt;
    &amp;gt;&amp;gt;&amp;gt; def greet(self, who):
    ...    print self.greeting, who

    &amp;gt;&amp;gt;&amp;gt; Person = type(
    ...    'Person', 
    ...    (object,),
    ...    {'greet': greet, 'greeting': 'Hello'}
    ... )
    &amp;gt;&amp;gt;&amp;gt;
    &amp;gt;&amp;gt;&amp;gt; jonathan = Person()
    &amp;gt;&amp;gt;&amp;gt; jonathan.greet('Readers')
    'Hello Readers'
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;This method of creating classes is equivalent to using the &lt;code&gt;class&lt;/code&gt;
statement, and reveals quite a bit about how metaclasses work. The constructor
for a metaclass expects very specific arguments:&lt;/p&gt;


	&lt;ol&gt;
	&lt;li&gt;The first argument is the name of the class.&lt;/li&gt;
		&lt;li&gt;The second argument is a tuple of the base classes for the class.&lt;/li&gt;
		&lt;li&gt;The last argument is a dictionary representing the namespace of the class.
  This dictionary contains all of the attributes that would typically appear
  within the body of a class statement.&lt;/li&gt;
	&lt;/ol&gt;


	&lt;p&gt;Now, we&amp;#8217;ve seen a metaclass in action, and we know how to instantiate them
to create classes. Armed with this knowledge of the default &lt;code&gt;type&lt;/code&gt; metaclass,
we can now tackle the much more interesting problem of creating our own
metaclasses.&lt;/p&gt;


	&lt;h2&gt;Defining Metaclasses&lt;/h2&gt;


	&lt;p&gt;Defining metaclasses in Python is as simple as creating a class that
inherits from the built-in &lt;code&gt;type&lt;/code&gt; metaclass. The constructor for our metaclass
will take the same arguments as the constructor for the &lt;code&gt;type&lt;/code&gt; metaclass:&lt;/p&gt;


	&lt;ol&gt;
	&lt;li&gt;The class name.&lt;/li&gt;
		&lt;li&gt;A tuple of the class bases.&lt;/li&gt;
		&lt;li&gt;A dictionary representing the namespace of the class.&lt;/li&gt;
	&lt;/ol&gt;


	&lt;p&gt;Constructors typically perform some action on their instances, so lets make
our constructor set a flag on the instance that we can inspect to make sure
that our metaclass is being used.&lt;/p&gt;


&lt;code&gt;&lt;pre&gt;
    class MyFirstMeta(type):
        def __init__(cls, name, bases, ns):
            cls.uses_my_metaclass = True
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;One important thing to note here is that the first argument to the
constructor of a class is typically called &lt;code&gt;self&lt;/code&gt;, as it refers to the
instance being constructed. It is conventional to name the first argument of a
metaclass constructor &lt;code&gt;cls&lt;/code&gt; as the metaclass instance is actually a &lt;em&gt;class&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;Now that we&amp;#8217;ve defined our metaclass, we know that we can construct a new
class called &lt;code&gt;MyClass&lt;/code&gt; simply by instantiating the metaclass:&lt;/p&gt;


&lt;code&gt;&lt;pre&gt;
    &amp;gt;&amp;gt;&amp;gt; MyClass = MyFirstMeta('MyClass', (object,), {})
    &amp;gt;&amp;gt;&amp;gt; print MyClass.uses_my_metaclass
    True
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;This very simple metaclass has given us our first glimpse into the power of
metaclasses. Within our metaclass constructor, we gave our class some state in
the form of a boolean attribute &lt;code&gt;uses_my_metaclass&lt;/code&gt;. Metaclasses have the
power to add, remove, or modify any attribute of the class being constructed.
Metaclasses will frequently add or replace methods on their instances, based
upon the data in the namespace of the class. Many Python object-relational
mappers use metaclasses to transform the attributes of a class into database
table definitions, for example.&lt;/p&gt;


	&lt;p&gt;While you can certainly construct classes by manually instantiating custom
metaclasses, it is much more convenient to use the &lt;code&gt;class&lt;/code&gt; statment to create
your classes. Python allows you to define the metaclass for a class by using
the special &lt;code&gt;__metaclass__&lt;/code&gt; attribute in your class statement:&lt;/p&gt;


&lt;code&gt;&lt;pre&gt;
    class MyClass(object):
        __metaclass__ = MyFirstMeta
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;This is the preferred method of attaching metaclasses to your classes. An
important thing to note about this syntax is that while you are not manually
instantiating the metaclass when defining your classes this way, the Python
interpeter &lt;em&gt;will&lt;/em&gt; instantiate the metaclass. The metaclass instantiation
will occur immediately after the class statement has been fully executed. As a
result, bugs in metaclasses often are triggered during imports. In a way, the
class statement is simply syntactic sugar for instantiating metaclasses!&lt;/p&gt;


	&lt;h2&gt;Mystery Metaclass Methods&lt;/h2&gt;


	&lt;p&gt;Before we move onto some practical examples of metaclasses, lets
investigate metaclass definition a bit further. Our &lt;code&gt;Person&lt;/code&gt; class defines a
method called &lt;code&gt;greet&lt;/code&gt; within its namespace. Instances of &lt;code&gt;Person&lt;/code&gt; will thus
have an &amp;#8220;instance method&amp;#8221; called &lt;code&gt;greet&lt;/code&gt;. We know what happens when we define
methods on a class, but what happens if we define a method on a &lt;em&gt;metaclass&lt;/em&gt;?&lt;/p&gt;


	&lt;p&gt;Methods defined on a class become &lt;em&gt;instance methods&lt;/em&gt;. Since instances of
metaclasses are &lt;em&gt;classes&lt;/em&gt;, methods defined on metaclasses become _class
methods_. Lets take a look at this in practice:&lt;/p&gt;


&lt;code&gt;&lt;pre&gt;
    &amp;gt;&amp;gt;&amp;gt; class MysteryMeta(type):
    &amp;gt;&amp;gt;&amp;gt; ... def mystery_method(cls):
    &amp;gt;&amp;gt;&amp;gt; ...     return 'I am a class method!'
    &amp;gt;&amp;gt;&amp;gt; 
    &amp;gt;&amp;gt;&amp;gt; class Mystery(object):
            __metaclass__ = MysteryMeta
    &amp;gt;&amp;gt;&amp;gt; 
    &amp;gt;&amp;gt;&amp;gt; print Mystery.mystery_method()
    I am a class method!
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;This revelation often surprises people, but is a logical outcome of the
fact that metaclasses are simply classes which produce classes. Many
metaclasses utilize this capability of defining class methods, but it is often
preferable to define such class methods on a base class, which is easier to
document and understand.&lt;/p&gt;


	&lt;p&gt;We&amp;#8217;ve now established what metaclasses are, how they work, and how we can
define our own by inheriting from &lt;code&gt;type&lt;/code&gt;. But, what about practical use
cases for metaclasses? Lets take a look at several examples of how we might
come to use metaprogramming in practice.&lt;/p&gt;


	&lt;h2&gt;Example: The Enforcer&lt;/h2&gt;


	&lt;p&gt;When I am teaching Python to programmers with strong backgrounds in
&amp;#8220;bondage and discipline&amp;#8221; languages like Java, I frequently hear the same
complaints about Python. One such complaint is that class definitions are
&amp;#8220;loose&amp;#8221; and you cannot enforce the type of variables by declaring them
up-front. In order to illustrate how to use metaclasses, lets define a little
library that will address this particular complaint.&lt;/p&gt;


	&lt;p&gt;Our goal is to create a base class called &lt;code&gt;Enforcer&lt;/code&gt; that will enforce the
types of attributes on its subclasses. Lets say we wanted to enforce that the
&lt;code&gt;name&lt;/code&gt; attribte of our &lt;code&gt;Person&lt;/code&gt; class was a string, and that the &lt;code&gt;age&lt;/code&gt;
attribute was an integer. Attempting to set attribtues with the wrong type
should trigger a &lt;code&gt;TypeError&lt;/code&gt; to be raised, just like the Java compiler would
catch such errors.&lt;/p&gt;


&lt;code&gt;&lt;pre&gt;
    class Person(Enforcer):
        name = Field(str)
        age = Field(int)
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;The first thing we need to do is define the &lt;code&gt;Field&lt;/code&gt; class, which we will
use to hold onto the type of the variable we&amp;#8217;re attempting to restrict. Lets
also give it the ability to validate whether or not a value is of the right
type for that particular attribute:&lt;/p&gt;


&lt;code&gt;&lt;pre&gt;
    class Field(object):
        def __init__(self, ftype):
            self.ftype = ftype

        def is_valid(self, value):
            return isinstance(value, self.ftype)
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;Now that we have our &lt;code&gt;Field&lt;/code&gt; class, we need to create a metaclass that will
look at the namespace of our class, searching for &lt;code&gt;Field&lt;/code&gt; definitions, and
then storing them in a dictionary for later use. Recall that the last argument
to the constructor of a metaclass is a dictionary containing the namespace of
the class. We can loop through this namespace to find &lt;code&gt;Field&lt;/code&gt; definitions:&lt;/p&gt;


&lt;code&gt;&lt;pre&gt;
    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.
            cls._fields = {}

            # loop through the namespace looking for Field instances
            for key, value in ns.items():
                if isinstance(value, Field):
                    cls._fields[key] = value
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;Our metaclass first attaches a &lt;code&gt;_fields&lt;/code&gt; dictionary to the class itself.
This data structure is where we will store &lt;code&gt;Field&lt;/code&gt; definitions for later
use. We then loop through the items in the namespace looking for &lt;code&gt;Field&lt;/code&gt;
instances, and finally we store them in our &lt;code&gt;_fields&lt;/code&gt; dictionary.&lt;/p&gt;


	&lt;p&gt;Next up is the &lt;code&gt;Enforcer&lt;/code&gt; base class itself. The &lt;code&gt;Enforcer&lt;/code&gt; base class
first needs to attach the &lt;code&gt;EnforcerMeta&lt;/code&gt; metaclass we&amp;#8217;ve just defined. This is
a very common way for libraries to distribute their metaclasses, by defining a
base class to inherit from, rather than requiring users to even know that a
metaclass is being used, or how to attach the metaclass to their classes.&lt;/p&gt;


	&lt;p&gt;The second thing the &lt;code&gt;Enforcer&lt;/code&gt; base class needs to do is to override the
&lt;code&gt;__setattr__&lt;/code&gt; method. This is a special method on Python classes that allows
you to override the default attribute setting behavior on your Python objects.
The &lt;code&gt;__setattr__&lt;/code&gt; method takes in the name of the attribute being set, and the
value being set.&lt;/p&gt;


&lt;code&gt;&lt;pre&gt;
    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)
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;Our &lt;code&gt;Enforcer&lt;/code&gt; class first attaches the metaclass. Then, it overrides the
&lt;code&gt;__setattr__&lt;/code&gt; method so that it can watch for field assignments. First, we
check to see if the attribute being set is one of our defined fields. Then, we
ask the field definition if the value that is being passed is valid for the
field definition. If it is not a valid type for the field, we raise a
&lt;code&gt;TypeError&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;The last line of the &lt;code&gt;Enforcer&lt;/code&gt; class is extremely important. This line is
instructing the Python interpreter to call the &lt;code&gt;__setattr__&lt;/code&gt; implementation
on the appropriate superclass definition, in this case &lt;code&gt;object&lt;/code&gt;. Without
this line, attribute setting would fail on all &lt;code&gt;Enforcer&lt;/code&gt; subclasses.&lt;/p&gt;


	&lt;p&gt;Lets try out our new creation from the Python interactive prompt:&lt;/p&gt;


&lt;code&gt;&lt;pre&gt;
    &amp;gt;&amp;gt;&amp;gt; class Person(Enforcer):
    ...    name = Field(str)
    ...    age = Field(int)
    ... 
    &amp;gt;&amp;gt;&amp;gt; jonathan = Person()
    &amp;gt;&amp;gt;&amp;gt; jonathan.name = 3
    TypeError: Invalid type
    &amp;gt;&amp;gt;&amp;gt; jonathan.age = 'Old'
    TypeError: Invalid type
    &amp;gt;&amp;gt;&amp;gt; jonathan.name = 'Jonathan'
    &amp;gt;&amp;gt;&amp;gt; jonathan.age = 28
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;Our metaclass has completely changed the way that our class behaves,
transforming it into a more rigid class definition that keeps our Java-loving
friends happy. While such restrictive enforcement is atypical in Python, it
certainly shows how powerful metaclasses can be.&lt;/p&gt;


	&lt;p&gt;This example also illustrates a common pattern for metaclasses, in which a
class describes how it wants to behave in a &amp;#8220;declarative&amp;#8221; way without actually
writing any code to implement that behavior. The metaclass subsequently takes
that metadata, and uses it to &amp;#8220;reprogram&amp;#8221; the class. This is the essence of
what metaprogramming brings to the table, and is the most popular use-case for
metaclasses.&lt;/p&gt;


	&lt;h2&gt;Example: Auto Decorator&lt;/h2&gt;


	&lt;p&gt;Since being given a special syntax in Python 2.4, decorators have become a
very commonly used feature. A decorator is essentially a wrapper around a
function or method. In versions of Python prior to 2.4, decorators were
applied by manually replacing the method definition with a &amp;#8220;decorated&amp;#8221; version
of the method. Starting in Python 2.4, decorators could be applied using the
now popular &lt;code&gt;@decorator&lt;/code&gt; syntax.&lt;/p&gt;


	&lt;p&gt;Sometimes, I find myself in the situation where I need to decorate all of
the methods of a class with the same decorator. Lets create a metaclass that
will simplify this process by automatically applying a decorator that is
declared in the namespace of the class:&lt;/p&gt;


&lt;code&gt;&lt;pre&gt;
    import inspect

    class AutoDecorateMeta(type):
        def __init__(cls, name, bases, ns):
            deco = ns.get('decorator', lambda f: f)
            for key, value in ns.items():
                # skip the decorator and constructor
                if key in ('decorator', '__init__'): continue

                # skip objects in the namespace that aren't methods
                if not inspect.isfunction(value): continue

                # apply the decorator
                setattr(cls, key, deco(value))
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;Our metaclass first looks up an attribute named &lt;code&gt;decorator&lt;/code&gt; in the
namespace of the class. This is the decorator that we will apply to every
method of the class. Note that if such a decorator cannot be found in the
namespace of the class, we define a fake decorator that will simply return the
existing method definition.&lt;/p&gt;


	&lt;p&gt;Next, we loop through the namespace of the class looking for methods. If we
encounter the decorator or the constructor, we skip them, as we don&amp;#8217;t want to
decorate our constructor or the decorator itself. We then make use of the
&lt;code&gt;inspect&lt;/code&gt; module to determine if the value is a method, and if it is, we
replace the method definition with a decorated version of that method.&lt;/p&gt;


	&lt;p&gt;Lets put our metaclass to the test by creating a class that defines several
properties. Typically, we&amp;#8217;d have to decorate every method with the
&lt;code&gt;@property&lt;/code&gt; decorator, which could add a lot of verbosity to our class,
depending on the number of methods we&amp;#8217;d have to decorate.&lt;/p&gt;


&lt;code&gt;&lt;pre&gt;
    class Person(object):
        __metaclass__ = AutoDecorateMeta
        decorator = property

        def __init__(self, first, middle, last):
            self.first = first
            self.middle = middle
            self.last = last

        def name(self):
            return '%s %s' % (self.first, self.last)

        def full_name(self):
            return '%s %s %s' % (self.first, self.middle, self.last)

        def initials(self):
            return '%s%s%s' % (self.first[0], self.middle[0], self.last[0])
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;Now that we&amp;#8217;ve created our class, we should be able to try it out from our
Python interactive prompt to see if all of our methods were transformed into
properties:&lt;/p&gt;


&lt;code&gt;&lt;pre&gt;    
    &amp;gt;&amp;gt;&amp;gt; mlk = Person('Martin', 'Luther', 'King')
    &amp;gt;&amp;gt;&amp;gt; print mlk.name
    Martin King
    &amp;gt;&amp;gt;&amp;gt; print mlk.full_name
    Martin Luther King
    &amp;gt;&amp;gt;&amp;gt; print mlk.initials
    MLK
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;Not only is this example useful in practice, it also illustrates another
use case for metaclasses and metaprogramming â automating repetitive tasks
that occur in class definition. This metaclass could be used to wrap every
method of a class in a transaction, to add debugging hooks, or even to
synchronize all of the methods using a thread lock.&lt;/p&gt;


	&lt;h2&gt;Cautionary Notes&lt;/h2&gt;


	&lt;p&gt;Metaclasses are fantastically cool, and as we&amp;#8217;ve seen, they can be pretty
useful. The rise of object-relational mappers and web frameworks have put
metaclasses into use by an increasing number of Python users, and has
increased the visibility of metaclasses substantially. That being said,
metaclasses are a feature of Python that must be used carefully. Because
metaclasses do their work at class definition time, bugs in your metaclasses
can result in errors that are triggered at import time. In addition,
metaclasses are often hidden from the programmer behind a base class, which
can cause confusion.&lt;/p&gt;


	&lt;p&gt;Applied judiciously, metaclasses can be a great tool for solving problems,
and give Python programmers the ability to take advantage of metaprogramming
techniques in their own code. I hope that this article has shed some light on
what metaclasses are, and has taken some of the mystery out of metaclasses.&lt;/p&gt;
</content>
</entry>
<entry>
		<issued>2008-07-30T02:53:00Z</issued>
		<modified>2008-07-30T02:55:45Z</modified>
		<title>Metaclasses in July Python Magazine [1]</title>
		<link rel="alternate" type="text/html" href="http://cleverdevil.org/computing/77/" />
		<id>tag:cleverdevil.org,2008-07-30:77</id>
		<dc:subject>programming</dc:subject>
		<content type="text/html" mode="escaped" xml:lang="en">
	&lt;p&gt;&lt;img src=&quot;http://pymag.phparch.com/img/pymag/issues/thumbnails/77.jpg&quot; style=&quot;float: right; margin: 0 0 10px 10px; border: 1px solid black;&quot; /&gt;&lt;/p&gt;

	&lt;p&gt;While I do not advertise it directly on this site, in addition to my &amp;#8220;day job&amp;#8221; I also provide Python training services for companies and individuals that want a comprehensive introduction to the Python programming language on a compressed schedule. One of the most difficult topics to condense and explain to a group of new Python programmers is metaclasses. Over the last year or so I&amp;#8217;ve spent a lot of time refining my teaching methods to make this complex topic approachable.&lt;/p&gt;

	&lt;p&gt;A few months ago, I presented a version of my slides on metaclasses at a &lt;a href=&quot;http://pyatl.org&quot;&gt;PyATL&lt;/a&gt; meeting.  Following the meeting, I was approached by &lt;a href=&quot;http://blog.doughellmann.com&quot;&gt;Doug Hellmann&lt;/a&gt; about the possibility of writing an article on metaclasses for &lt;a href=&quot;http://pymag.phparch.com/&quot;&gt;Python Magazine&lt;/a&gt;.  Well, I am pleased to say that my article, entitled &lt;em&gt;Metaclasses Demystified&lt;/em&gt; appears in the &lt;a href=&quot;http://pymag.phparch.com/c/issue/view/77&quot;&gt;July 2008 issue&lt;/a&gt; of Python Magazine.&lt;/p&gt;

	&lt;p&gt;This is my first professionally published technical article, and I am really excited that my work will be read by many Python programmers. Depending on feedback from readers, expect to see more contributions to Python Magazine from me in the future. It was a lot of fun crafting the article!&lt;/p&gt;



 
</content>
</entry>
<entry>
		<issued>2008-07-13T20:02:00Z</issued>
		<modified>2008-07-13T21:03:20Z</modified>
		<title>MobileMe Disappointment [1]</title>
		<link rel="alternate" type="text/html" href="http://cleverdevil.org/computing/76/" />
		<id>tag:cleverdevil.org,2008-07-13:76</id>
		<dc:subject>apple</dc:subject>
		<content type="text/html" mode="escaped" xml:lang="en">
	&lt;p&gt;When I first heard about Apple&amp;#8217;s &lt;a href=&quot;http://apple.com/mobileme&quot;&gt;new MobileMe service&lt;/a&gt;, I was excited by the prospect of being able to keep all of my devices in sync instantly, with no waiting. I was so excited, that I purchased a boxed version of .Mac so that I&amp;#8217;d be one of the first to get my hands on the service when it debuted.&lt;/p&gt;

	&lt;p&gt;One of the main reasons I purchased MobileMe was because of Apple&amp;#8217;s &lt;a href=&quot;http://www.apple.com/mobileme/features/&quot;&gt;beautiful marketing site&lt;/a&gt; describing the features of MobileMe.  The site states:&lt;/p&gt;

	&lt;blockquote&gt;
		&lt;p&gt;MobileMe stores all your email, contacts, and calendars in the cloud and pushes them down to your iPhone, iPod touch, Mac, and PC. When you make a change on one device, the cloud updates the others. &lt;strong&gt;Push happens automatically, instantly, and continuously. You don&amp;#8217;t have to wait for it&lt;/strong&gt; or remember to do anything &amp;#8212; such as docking your iPhone and syncing manually &amp;#8212; to stay up to date.&lt;/p&gt;
	&lt;/blockquote&gt;

	&lt;p&gt;As it turns out, this is not only misleading, but is essentially a bold-faced lie. While the &amp;#8220;push&amp;#8221; &lt;em&gt;does&lt;/em&gt; occur from your iPhone to the cloud and vice-versa, your Mac only receives and sends updates once &lt;a href=&quot;http://support.apple.com/kb/TS1155&quot;&gt;every 15 minutes&lt;/a&gt;, even if you instruct it to sync &amp;#8220;Automatically&amp;#8221; in the MobileMe preferences pane on your Mac.  Honestly, I expected better from Apple.&lt;/p&gt;

	&lt;p&gt;In addition to this very irritating issue, I have several other problems with the service, which is billed as &amp;#8220;Exchange for the rest of us,&amp;#8221; that greatly diminish its usefulness.&lt;/p&gt;

	&lt;p&gt;I would love to utilize the push email service to manage my personal email. However, I have a personal domain where all of my email is delivered. In addition, I subscribe to many mailing lists, and receive several hundred emails a day. All of my email is neatly organized into folders automatically, using server-side mail filters through the excellent &lt;a href=&quot;http://www.procmail.org/&quot;&gt;procmail&lt;/a&gt; utility.&lt;/p&gt;

	&lt;p&gt;MobileMe email has two massive shortcomings that make it useless for my situation:&lt;/p&gt;

	&lt;ol&gt;
	&lt;li&gt;You cannot set up MobileMe to handle email for a personal domain, unless you set up your existing mail server to forward email onto MobileMe. I could live without this one, if it were not for the second problem.&lt;/li&gt;
		&lt;li&gt;While rules that you set up in Apple mail &amp;#8220;sync&amp;#8221; to MobileMe, they are not applied server side. In order for your rules to be applied, you must have a version of Apple Mail running on some computer connected to the internet to apply those rules client-side.&lt;/li&gt;
	&lt;/ol&gt;

	&lt;p&gt;MobileMe is a very compelling service if you just read the marketing, but in the end, in falls extremely short of my expectations from a company like Apple. I have sent my complaints onto MobileMe customer support, and am awaiting a response. Hopefully, they&amp;#8217;ll at least acknowledge the misleading marketing.&lt;/p&gt;


 
</content>
</entry>
<entry>
		<issued>2008-06-11T13:49:11Z</issued>
		<modified>2008-06-11T13:49:11Z</modified>
		<title>iPhone 3G is Cheaper* [11]</title>
		<link rel="alternate" type="text/html" href="http://cleverdevil.org/computing/75/" />
		<id>tag:cleverdevil.org,2008-06-11:75</id>
		<dc:subject>technology</dc:subject>
		<content type="text/html" mode="escaped" xml:lang="en">
	&lt;p&gt;I purchased a first-generation iPhone the day that it came out. Its been a wonderful purchase from the start, in spite of the fact that it cost me $599. Sure, thats a lot of money, but I always felt like I was getting my money&amp;#8217;s worth out of the hardware. The first iPhone was the best iPod, best mobile browsing device, and best phone. When Apple reduced the price to $399, I thought that this was an absolute steal.&lt;/p&gt;

	&lt;p&gt;When I first heard rumors that the iPhone 3G was going to cost less than the current iPhone, I had guessed that this was pure rumor and speculation. There is no way that Apple would sell the iPhone for less than $399, as it would force them to restructure the pricing for their iPod line. By the same token, I couldn&amp;#8217;t fathom Apple allowing ATT to subsidize the phone, because this would mean that ATT would be making this subsidy back up by somehow gouging the customer in service fees. Apple did an excellent job of standing up for the consumer with the first iPhone, by negotiating a low-price data plan and allowing for at-home activation through iTunes.&lt;/p&gt;

	&lt;p&gt;Needless to say, I was shocked at the price point that was announced during the keynote. Only $199? And no mention of contracts, subsidies, or rate increases? Was this too good to be true? &lt;/p&gt;

	&lt;p&gt;As it turns out, yes.&lt;/p&gt;

	&lt;p&gt;Currently, I pay ATT $20/month for 200 text messages and unlimited data over their EDGE network. ATT has announced that the new iPhone 3G data plan will cost $30/month, and will include no text messages. ATT charges $5/month for 200 text messages, which means that the iPhone data plan is effectively being increased by $15/month, representing a 75% increase over the existing data plan.&lt;/p&gt;

	&lt;p&gt;Over the course of the two year contract, an iPhone 3G will cost you a full $360 more than a first-generation iPhone would. This means that with the same ATT service plans, the $199 8GB iPhone 3G will actually end up costing you $559, where an 8 GB iPhone 1.0 will cost you only $399, representing a savings of $160!  The iPhone 3G isn&amp;#8217;t cheaper at all, it is in fact far more expensive.&lt;/p&gt;

	&lt;p&gt;Compounding this is the fact that if I upgraded, I&amp;#8217;d likely give my current iPhone to my wife, and have to pay an additional $20/month for her data plan. By my math, getting a new iPhone 3G would cost me a minimum of $1039 over two years. Yikes!&lt;/p&gt;

	&lt;p&gt;So, I&amp;#8217;ll be passing on the new &amp;#8220;cheaper&amp;#8221; iPhone, and keeping my iPhone 1.0. I&amp;#8217;ll be able to run all the great new third-party applications, and will have every feature that my iPhone 3G toting friends will have, apart from 3G speed and GPS. As much as I hate the EDGE network, and would like to have GPS, those features simply aren&amp;#8217;t worth over a thousand dollars to me. Here&amp;#8217;s hoping that Apple and ATT come up with something more compelling and consumer-friendly, rather than misleading consumers.&lt;/p&gt;


 
</content>
</entry></feed>
