Adding static typing to Python

Michal Wallace sabren at manifestation.com
Tue Feb 19 19:06:18 CET 2002


On Tue, 19 Feb 2002, Jason Orendorff wrote:

> class Frob(object):
>     def get_name(self):
>         return self.__name
> 
>     def set_name(self, name):
>         if re.match('^\w+$', name) is None:
>             raise ValueError("Frob.name may only contain name characters")
>         self.__name = name
> 
>     name = property(get_name, set_name, None,
>                     """ The Frob's canonical given name """)
> 
> Guido hints there may be some syntactic sugar for this
> in an upcoming version.


He created a metaclass called autoprop that does the
name=property(...)  assignment automatically..

   http://www.python.org/2.2/descrintro.html#metaclasses


I incorporated this into my strongbox package... It also
lets you define something like "slots" automatically:


   class Person(Strongbox):
       # static typing of slots:
       name = attr(str)
       
       # default values, lambda typing:
       age = attr(int, default=18, okay=lambda v: v > 0)

       # regexp typing:
       tel = attr(str, okay="[0123456890()-]+") 

       # enumerations:
       favorite_color = attr(str, okay=["red","green","blue"])
       
       # autoprop style access:
       def get_canDrink(self):
           return self.age > 21


Then:

>>> person = Person(name="fred")
>>> person.name
fred
>>> person.age = 5
>>> person.canDrink
0
>>> person.age = "55"  # automatic type casting!
>>> person.age
55
>>> person.age = "apple"
# (raises TypeError)
>>> person.age = -5
# (raises ValueError)
>>> person.newAttribute = 5  
# (raises attribute error)
>>> person.private.newAttribute = 5 # works fine.


The point of doing all this isn't to speed up the compiler
or anything. It's just to save me from having to write the
same kinds of validation code over and over again when
dealing with records that have to be saved to MySQL. The
automatic type casting is great when you're pulling data
from an HTML form...

I don't have the code online anywhere, but I can post it if
anyone's interested.

Cheers,

- Michal   http://www.sabren.net/   sabren at manifestation.com 
------------------------------------------------------------
Give your ideas the perfect home: http://www.cornerhost.com/
 cvs - weblogs - php - linux shell - perl/python/cgi - java
------------------------------------------------------------





More information about the Python-list mailing list