Back to index

python3.2  3.2.2
Classes | Functions | Variables
collections Namespace Reference

Classes

class  _Link
 OrderedDict. More...
class  OrderedDict
class  Counter
class  _ChainMap
class  UserDict
class  UserList
class  UserString
class  Point

Functions

def namedtuple
def _count_elements
 Counter.

Variables

list __all__
string _class_template
string _repr_template = '{name}=%r'
string _field_template
tuple Point = namedtuple('Point', 'x, y', True)
tuple p = Point(x=10, y=20)
tuple Point3D = namedtuple('Point3D', Point._fields + ('z',))
tuple TestResults = namedtuple('TestResults', 'failed attempted')

Function Documentation

def collections._count_elements (   mapping,
  iterable 
) [private]

Counter.

Definition at line 386 of file collections.py.

00386 
00387 def _count_elements(mapping, iterable):
00388     'Tally elements from the iterable.'
00389     mapping_get = mapping.get
00390     for elem in iterable:
00391         mapping[elem] = mapping_get(elem, 0) + 1
00392 
00393 try:                                    # Load C helper function if available
    from _collections import _count_elements

Here is the caller graph for this function:

def collections.namedtuple (   typename,
  field_names,
  verbose = False,
  rename = False 
)
Returns a new subclass of tuple with named fields.

>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__                   # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22)             # instantiate with positional args or keywords
>>> p[0] + p[1]                     # indexable like a plain tuple
33
>>> x, y = p                        # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y                       # fields also accessable by name
33
>>> d = p._asdict()                 # convert to a dictionary
>>> d['x']
11
>>> Point(**d)                      # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100)               # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)

Definition at line 293 of file collections.py.

00293 
00294 def namedtuple(typename, field_names, verbose=False, rename=False):
00295     """Returns a new subclass of tuple with named fields.
00296 
00297     >>> Point = namedtuple('Point', ['x', 'y'])
00298     >>> Point.__doc__                   # docstring for the new class
00299     'Point(x, y)'
00300     >>> p = Point(11, y=22)             # instantiate with positional args or keywords
00301     >>> p[0] + p[1]                     # indexable like a plain tuple
00302     33
00303     >>> x, y = p                        # unpack like a regular tuple
00304     >>> x, y
00305     (11, 22)
00306     >>> p.x + p.y                       # fields also accessable by name
00307     33
00308     >>> d = p._asdict()                 # convert to a dictionary
00309     >>> d['x']
00310     11
00311     >>> Point(**d)                      # convert from a dictionary
00312     Point(x=11, y=22)
00313     >>> p._replace(x=100)               # _replace() is like str.replace() but targets named fields
00314     Point(x=100, y=22)
00315 
00316     """
00317 
00318     # Parse and validate the field names.  Validation serves two purposes,
00319     # generating informative error messages and preventing template injection attacks.
00320     if isinstance(field_names, str):
00321         field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
00322     field_names = list(map(str, field_names))
00323     if rename:
00324         seen = set()
00325         for index, name in enumerate(field_names):
00326             if (not all(c.isalnum() or c=='_' for c in name)
00327                 or _iskeyword(name)
00328                 or not name
00329                 or name[0].isdigit()
00330                 or name.startswith('_')
00331                 or name in seen):
00332                 field_names[index] = '_%d' % index
00333             seen.add(name)
00334     for name in [typename] + field_names:
00335         if not all(c.isalnum() or c=='_' for c in name):
00336             raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
00337         if _iskeyword(name):
00338             raise ValueError('Type names and field names cannot be a keyword: %r' % name)
00339         if name[0].isdigit():
00340             raise ValueError('Type names and field names cannot start with a number: %r' % name)
00341     seen = set()
00342     for name in field_names:
00343         if name.startswith('_') and not rename:
00344             raise ValueError('Field names cannot start with an underscore: %r' % name)
00345         if name in seen:
00346             raise ValueError('Encountered duplicate field name: %r' % name)
00347         seen.add(name)
00348 
00349     # Fill-in the class template
00350     class_definition = _class_template.format(
00351         typename = typename,
00352         field_names = tuple(field_names),
00353         num_fields = len(field_names),
00354         arg_list = repr(tuple(field_names)).replace("'", "")[1:-1],
00355         repr_fmt = ', '.join(_repr_template.format(name=name) for name in field_names),
00356         field_defs = '\n'.join(_field_template.format(index=index, name=name)
00357                                for index, name in enumerate(field_names))
00358     )
00359 
00360     # Execute the template string in a temporary namespace and
00361     # support tracing utilities by setting a value for frame.f_globals['__name__']
00362     namespace = dict(__name__='namedtuple_%s' % typename)
00363     try:
00364         exec(class_definition, namespace)
00365     except SyntaxError as e:
00366         raise SyntaxError(e.msg + ':\n\n' + class_definition)
00367     result = namespace[typename]
00368     if verbose:
00369         print(class_definition)
00370 
00371     # For pickling to work, the __module__ variable needs to be set to the frame
00372     # where the named tuple is created.  Bypass this step in enviroments where
00373     # sys._getframe is not defined (Jython for example) or sys._getframe is not
00374     # defined for arguments greater than 0 (IronPython).
00375     try:
00376         result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
00377     except (AttributeError, ValueError):
00378         pass
00379 
00380     return result
00381 

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

Initial value:
00001 ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList',
00002             'UserString', 'Counter', 'OrderedDict']

Definition at line 1 of file collections.py.

Definition at line 239 of file collections.py.

Initial value:
00001 '''\
00002     {name} = _property(_itemgetter({index:d}), doc='Alias for field number {index:d}')
00003 '''

Definition at line 289 of file collections.py.

Definition at line 287 of file collections.py.

tuple collections.p = Point(x=10, y=20)

Definition at line 1054 of file collections.py.

tuple collections.Point = namedtuple('Point', 'x, y', True)

Definition at line 1053 of file collections.py.

tuple collections.Point3D = namedtuple('Point3D', Point._fields + ('z',))

Definition at line 1078 of file collections.py.

tuple collections.TestResults = namedtuple('TestResults', 'failed attempted')

Definition at line 1082 of file collections.py.