Module csvutils :: Class MappingTransformer
[hide private]
[frames] | no frames]

Class MappingTransformer

source code

    object --+    
             |    
RowTransformer --+
                 |
                MappingTransformer

A RowTransformer that expects and returns rows as mappings.

Examples:
>>> import csv
>>> rows = list(csv.DictReader(["1,3.34,4-3.2j,John",
...                             "4,4,4,4",
...                             "0,-1.1,3.4,None" ],
...                            fieldnames="IFCS"))
>>> # by default, MappingTransformer returns each row as is
>>> list(MappingTransformer()(rows)) == rows
True
>>> # transform and return the first two columns only
>>> for row in MappingTransformer({'I':int,'F':float})(rows):
...    print row
{'I': 1, 'F': 3.3399999999999999}
{'I': 4, 'F': 4.0}
{'I': 0, 'F': -1.1000000000000001}
>>> # as before, but keep the rest columns too
>>> for row in MappingTransformer({'I':int, 'F':float}, default=None)(rows):
...    print row
{'I': 1, 'C': '4-3.2j', 'S': 'John', 'F': 3.3399999999999999}
{'I': 4, 'C': '4', 'S': '4', 'F': 4.0}
{'I': 0, 'C': '3.4', 'S': 'None', 'F': -1.1000000000000001}
>>> # transform the 'F' column and leave the rest as is
>>> for row in MappingTransformer({'F':float}, default=None)(rows):
...    print row
{'I': '1', 'C': '4-3.2j', 'S': 'John', 'F': 3.3399999999999999}
{'I': '4', 'C': '4', 'S': '4', 'F': 4.0}
{'I': '0', 'C': '3.4', 'S': 'None', 'F': -1.1000000000000001}
>>> # transform and return the 'F' and 'S' columns
>>> for row in MappingTransformer({'S':str,'F':float})(rows):
...    print row
{'S': 'John', 'F': 3.3399999999999999}
{'S': '4', 'F': 4.0}
{'S': 'None', 'F': -1.1000000000000001}
>>> # exclude the 'S' column and eval() the rest (XXX: Use eval for trusted data only)
>>> for row in MappingTransformer(default=eval, exclude=['S'])(rows):
...    print row
{'I': 1, 'C': (4-3.2000000000000002j), 'F': 3.3399999999999999}
{'I': 4, 'C': 4, 'F': 4}
{'I': 0, 'C': 3.3999999999999999, 'F': -1.1000000000000001}


Instance Methods [hide private]
 
__init__(self, adaptors={}, **kwds)
Specifies what transformations to apply to each row.
source code
 
__call__(self, rows)
Transform the given rows by this transformer.
source code

Inherited from object: __delattr__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __str__

Properties [hide private]

Inherited from object: __class__

Method Details [hide private]

__init__(self, adaptors={}, **kwds)
(Constructor)

source code 
Specifies what transformations to apply to each row.
Parameters:
Overrides: RowTransformer.__init__

__call__(self, rows)
(Call operator)

source code 
Transform the given rows by this transformer.
Parameters:
  • rows - An iterable of mappings.
Returns:
An iterator over the transformed rows as dicts.
Overrides: RowTransformer.__call__