[Python-ideas] anonymous object support

Carl Matthew Johnson cmjohnson.mailinglist at gmail.com
Sat Aug 6 08:37:47 CEST 2011


On Aug 5, 2011, at 10:49 AM, Mike Graham wrote:

> 2011/8/5 dag.odenhall at gmail.com <dag.odenhall at gmail.com>
>> 2011/8/4 Matej Lieskovský <lieskovsky.matej at googlemail.com>:
>>> ...
>>> perhaps a "namespace" statement would do, behaving somewhat like this:
>>> namespace MyObject:
>>>     statements
>>> is equivalent to:
>>> class MyClass(object):
>>>     statements
>>> MyObject = MyClass()
>>> MyClass = None
>>> ...
> 
> As a somewhat off-topic remark, this could already be accomplished
> with metaclasses. 

I think a new keyword (possibly but not necessarily namespace) might good as a way of differentiating "real" classes from metaclass hacks. For example, some ORMs work using a "declarational" syntax with the class statement. That's fine… except that it looks like you can use the resulting objects like classes, when really there's a lot of meta-glue behind the scenes that means things will break if you try to use inheritance or other features of "real" classes.

As another example, using metaclasses you can change namedtuple's syntax from the somewhat clunky

Point = namedtuple('Point', 'x y')

to the more elegant but confusing since it uses "class"

class Point(NamedTuple):
	x
	y

I sort of like this syntax, but I think it would crazy to use in production, because who besides the original creator of the hack would guess that class NamedTuple has a metaclass which uses the __prepare__ method to record the fields accessed during class creation? But with a namespace keyword you signal to the reader of the code: "Here be meta-dragons! Proceed with caution." The counterargument can be made, do we really want to encourage people to fiddle around with metaclasses any more than they already do? But my response to that is that people are already making ORMs and whatnot using the class keyword, so why not pave the cowpath? Also we could throw in some built in tools to make the metaclasses less confusing to work with.





Also, hey free switch statement ;-) :

key = random.choice(["case1", "case2"])
namespace dispatch(dict):
	def case1(): print("One")
	def case2(): print("Two")

dispatch[key]()

-- Carl


More information about the Python-ideas mailing list