On 6 Feb 2003, Thomas Heller wrote: > Guido van Rossum <guido@python.org> writes: > > Can you suggest a concrete syntax to do this? Maybe setting __slots__ > > to a dictionary mapping names to type specifiers would do it -- and it > > would even be backwards compatible: currently, if __slots__ is a dict, > > its keys are used as slot names and its values are ignored, by virtue > > of the way the type constructor iterates over __slots__. > > May I suggest to use an ordered sequence (of pairs) instead of a dict > for __slots__. Then you also can completely control the layout that > C code sees and construct C compatible structures or other data types > from pure Python code. I'm happy with this approach, so long as the tuples can also be keys in a dictionary. ;) Here is an example of what my metaclass does: > <plug> > Here's how ctypes does it: It's named _fields_ instead of __slots__, > and typically you write something like this > > class Point(Structure): > _fields_ = [("x", "i"), > ("y", "i")] > > which defines a Python objects having x and y instance vars, which > must be integers. My metaclass does something similar, though it does not affect the storage, only the validity constraints: def enforce_int(x): if not isinstance(x, (int,long)): raise TypeError def enforce_str(x): if not isinstance(x, basestring): raise TypeError class Foo(object): __metaclass__ = ConstraintObject __slots__ = { 'a' : enforce_int, 'b' : enforce_str, 'c' : str } foo = Foo() foo.a = 1 foo.a = 1.0 > TypeError foo.b = '1' foo.b = 1 > TypeError foo.c = 1 type(foo.c) == '1' -Kevin -- -- Kevin Jacobs The OPAL Group - Enterprise Systems Architect Voice: (216) 986-0710 x 19 E-mail: jacobs@theopalgroup.com Fax: (216) 986-0714 WWW: http://www.theopalgroup.com
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4