selfboot / AnnotatedShadowSocks

Annotated shadowsocks(python version)
Other
3 stars 1 forks source link

Modules contained in collections #19

Open selfboot opened 7 years ago

selfboot commented 7 years ago

defaultdict

Usually, a Python dictionary throws a KeyError if you try to get an item with a key that is not currently in the dictionary. The defaultdict in contrast will simply create any items that you try to access (provided of course they do not exist yet). To create such a "default" item, it calls the function object that you pass in the constructor (more precisely, it's an arbitrary "callable" object, which includes function and type objects).

Doc says:

class collections.defaultdict([default_factory[, ...]])

Returns a new dictionary-like object. defaultdict is a subclass of the built-in dict class. It overrides one method(__missing__(key)) and adds one writable instance variable(default_factory). The remaining functionality is the same as for the dict class.

The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

For example:

from collections import defaultdict

somedict = {}
print somedict[3]       # KeyError
someddict = defaultdict(int)
print someddict[3]      # print int(), thus 0

POLL_NULL = 0x00
results = defaultdict(lambda: POLL_NULL)
print results[1]        # print POLL_NULL, thus 0

Ref
How does collections.defaultdict work?