[Python-3000] sets in P3K?

Nick Coghlan ncoghlan at gmail.com
Wed Apr 26 12:51:57 CEST 2006


Edward Loper wrote:
> One way around this conflict might be to define a new factory function, 
> that generates a set from an iterable. I.e., something like:
>> s = set.from_iter(my_list)
> s = set.from_iter(enumerate(my_list))
> s = set.from_iter(x for x in collection if x>10)
>> (But with a better name than 'from_iter' :) )

Some might object to this as being too magical, but one option is a metaclass 
that overrides __getitem__ as an alternative constructor to the usual 
__call__. Numpy uses this trick to good effect for building matrices.
A single metaclass could cover most builtin and standard library containers:
 def __getitem__(self, args):
 # This just defines the semantics. A real implementation would
 # avoid the temporary objects wherever possible.
 if not isinstance(args, tuple):
 args = (args,)
 arglist = []
 for item in args:
 if isinstance(item, slice):
 if item.step is None:
 item = (item.start, item.stop)
 else:
 item = (item.start, item.stop, item.step)
 arglist.append(item)
 return self(*arglist)
Then you could have:
 s = set[1, 2, 3] # == set((1, 2, 3))
 f = frozenset[1, 2, 3] # == frozenset((1, 2, 3))
 d = dict[1:'x', 2:'y'] # == {1:'x', 2:'y'} == dict(((1,'x'), (2,'y')))
 l = list[1, 2, 3] # == [1, 2, 3] == list((1, 2, 3))
 t = tuple[1, 2, 3] # == (1, 2, 3) == tuple((1, 2, 3))
This can also be spelt more explicitly, but doing so pretty much misses the 
point of this discussion (we're only talking about avoiding a couple of 
parentheses, after all).
Cheers,
Nick.
-- 
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
 http://www.boredomandlaziness.org


More information about the Python-3000 mailing list

AltStyle によって変換されたページ (->オリジナル) /