Last page update: November 23, 2011
Note
It is better to have 100 functions operate on one data structure than 10 functions on 10 data structures. – Alan J. Perlis, Epigrams on Programming
Main classes:
Other classes:
Complete reference:
The Genro Bag has a consistent number of methods. They are listed here in alphabetical order.
The Genro BagNode has a relevant number of methods. They are listed here in alphabetical order.
addValidator() getValue() setStaticValue() delAttr() hasAttr() setValue() getAttr() resolver() staticvalue() getLabel() setAttr() subscribe() getStaticValue() setLabel() value()
The gnrbag module contains a single class intended to be used: Bag.
A Bag is a generic container object, similar to a dictionary, with some useful properties:
- it is ordered
- accessibility by key
- iterability
- it is hierarchic
A Bag can store any kind of python object with a label in an ordered list. It can also store attributes about any value stored: Bag attributes are metadata that are an addition to the stored object without distrurbing the stored data.
A Bag can be loaded and saved in some ways:
- saved to and loaded from pikle files or strings: the object stored in the bag must be picklable of course
- saved to and loaded from xml files or strings with a specific syntax: the object stored in the Bag must be strings, numbers or dates
- loaded from a generic xml file preserving the whole hierarchical structure and the attributes: all values will be of type string of course
- loaded from a generic html file: requires tidy.
Another class you could have to deal with is BagNode (a Bag is a list of BagNode-s).
BagNode is not intended to be instanced directly, it is used internally by Bag, however in some cases is useful to interact with BagNode instances inside a Bag.
Note
The square brackets around some parameters in the following method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Genro Library Reference
Note
Some methods have the “square-brackets notation”: it is a shorter notation for the method
| synopsis: | the foundamental data structure in GenroPy |
|---|
A container object like a dictionary, but ordered.
Nested elements can be accessed with a path of keys joined with dots
Add an item to the current Bag using a path in the form “label1.label2. ... .labelN”, returning the current Bag. If the path already exists, this method replicates the path keeping both the old values and the new value
| Parameters: |
|
|---|
Example:
>>> beatles = Bag()
>>> beatles.setItem('member','John') # alternatively, you could write beatles.addItem('member','John')
>>> beatles.addItem('member','Paul')
>>> beatles.addItem('member','George')
>>> beatles.addItem('member','Ringo')
>>> print beatles
0 - (str) member: John
1 - (str) member: Paul
2 - (str) member: George
3 - (str) member: Ringo
Obviously, you can’t use the square-brackets notations within this method, because if you try to insert different values with the same label you would lose all the values except for the last one
Add a validator into the node at the given path
| Parameters: |
|
|---|
Convert a Bag in a Dictionary and return it.
| Parameters: |
|
|---|
Note
If you attempt to transform a hierarchical bag to a dictionary, the resulting dictionary will contain nested bags as values. In other words only the first level of the Bag is transformed to a dictionary, and the transformation is not recursive
TODO
| Parameters: |
|
|---|
Call the __str__ method, and return an ascii encoded formatted representation of the Bag
| Parameters: |
|
|---|
TODO
| Parameters: |
|
|---|
Set a new item of a tag type into the current structure or return the parent
| Parameters: |
|
|---|
Clear the Bag
Clear all the setBackRef() assumption
TODO
| Parameters: |
|
|---|
Return a Bag copy
Return a deep Bag copy
Define a formula that uses defined symbols
| Parameters: | kwargs – a key-value couple which represents the formula and the string that describes it |
|---|
Define a variable and link it to a BagFormula Resolver at the specified path.
| Parameters: | kwargs – a dict of symbol to make a formula. |
|---|
>>> mybag=Bag({'rect': Bag()})
>>> mybag['rect.params.base'] = 20
>>> mybag['rect.params.height'] = 10
>>> mybag.defineFormula(calculate_perimeter='2*($base + $height)' )
>>> mybag.defineSymbol(base ='params.base', height='params.height')
>>> mybag['rect.perimeter']= mybag.formula('calculate_perimeter')
>>> print mybag['rect.perimeter']
60
TODO
| Parameters: |
|
|---|
This method is analog to dictionary’s pop() method. It pops the given item from a Bag at the relative path and returns it
| Parameters: |
|
|---|
>>> b = Bag()
>>> b.setItem('a',1)
>>> b.addItem('a',2)
>>> b.addItem('a',3)
>>> b.pop('a')
1
>>> print b
0 - (int) a: 2
1 - (int) a: 3
Set False in the ParentBag reference of the relative Bag
It returns a list of n tuples including keys and/or values and/or attributes of all the Bag’s elements, where n is the number of special keys called in the method
| Parameters: | what – the parameter who includes a string of one or more special keys separated by a comma |
|---|
Here follows a list of the special keys:
Special keys Description '#k' Show the label of each item '#v' Show the value of each item '#v.path' Show inner values of each item '#__v' Show the values of each node in ‘static’ mode ??? '#a' Show attributes of each item '#a.attributeName' Show the attribute called ‘attrname’ for each item
| Parameters: |
|
|---|
Square-brackets notations:
You have to use the special char ? followed by d: followed by one or more expressions:
>>> print b['documents.letters.?d:#k,#a.createdOn,#a.createdBy']
[('letter_to_sheila','12-4-2003','Walter'),('letter_to_mark','10-7-2003','Jack'),('letter_to_john','11-5-2003','Mark')]
>>> print b['documents.letters.?d:#v,#a.createdOn']
[('file0', '10-7-2003'), ('file1', '11-5-2003'), ('file2', '12-4-2003')]
Fill a void Bag from a source (basestring, Bag or list)
| Parameters: | source – the source for the Bag |
|---|
TODO
| Parameters: | cb – TODO |
|---|
TODO
| Parameters: |
|
|---|
Set a BagFormula resolver
| Parameters: |
|
|---|
Fill a Bag with values read from an XML string or file or URL
| Parameters: |
|
|---|
TODO
| Parameters: |
|
|---|
Get the node’s attribute at the given path and return it. If it doesn’t exist, it returns None, so that this method never raises a KeyError
| Parameters: |
|
|---|
>>> b = Bag()
>>> b.setItem('documents.letters.letter_to_mark','file0',createdOn='10-7-2003',createdBy= 'Jack')
>>> print b
0 - (Bag) documents:
0 - (Bag) letters:
0 - (str) letter_to_mark: file0 <createdOn='10-7-2003' createdBy='Jack'>
>>> print b.getAttr('documents.letters.letter_to_mark', 'createdBy')
Jack
>>> print b.getAttr('documents.letters.letter_to_mark', 'fileOwner')
None
>>> print b.getAttr('documents.letters.letter_to_mark', 'fileOwner', default='wrong')
wrong
Square-brackets notations:
You have to use the special char ? followed by the attribute’s name:
>>> print b['documents.letters.letter_to_sheila?fileOwner']
Steve
Return the deepest matching node in the bag and the remaining path of the path. bag.getDeepestNode(‘foo.bar.baz’) returns:
>>> if 'foo.bar.baz' in bag:
>>> return (bag.getNode(foo.bar.baz), [])
>>> elif 'foo.bar' in bag:
>>> return (bag.getNode('foo.bar'), ['baz'])
>>> elif 'bar' in bag:
>>> return (bag.getNode(foo),['bar','baz'])
>>> else:
>>> return (None,['foo','bar','baz'])
This method returns the deepest matching node in the bag and the remaining path of the path. bag.getDeepestNode(‘foo.bar.baz’) returns:
>>> if 'foo.bar.baz' in bag:
>>> return (bag.getNode(foo.bar.baz), [])
>>> elif 'foo.bar' in bag:
>>> return (bag.getNode('foo.bar'), ['baz'])
>>> elif 'bar' in bag:
>>> return (bag.getNode(foo),['bar','baz'])
>>> else:
>>> return (None,['foo','bar','baz'])
This method get the resolver of the node at the given path
| Parameters: | path – the path of the node |
|---|
Return the Bag index with all the internal address
Return the Bag index as a plan list of the Nodes paths
| Parameters: | asText – TODO |
|---|
TODO
Return the value of the given item if it is in the Bag, else it returns None, so that this method never raises a KeyError
This method reimplements the list’s __getitem__() method. Usually a path is a string formed by the labels of the nested items, joined by the char ‘.’, but several different path notations have been implemented to offer some useful features:
A path can also be a list of keys
| Parameters: |
|
|---|
>>> mybag = Bag()
>>> mybag.setItem('a',1)
>>> first= mybag.getItem('a')
>>> second = mybag.getItem('b')
>>> print(first,second)
(1, None)
>>> b = Bag()
>>> b['aa.bb.cc'] = 1234
>>> b['aa.bb.cc']
1234
Square-brackets notations:
>>> mybag = Bag({'a':1,'b':2})
>>> second = mybag['b']
>>> print second
2
Return the BagNode stored at the relative path
| Parameters: |
|
|---|
Return a BagNode with the requested attribute (e.g. searching a node with a given ‘id’ in a Bag build from html)
| Parameters: |
|
|---|
Get the actual list of nodes contained in the Bag. The getNodes method works as the filter of a list
This method get the resolver of the node at the given path
| Parameters: | path – the path of the node |
|---|
This method is analog to dictionary’s has_key() method. Seek for the presence of the key in the Bag, and return True if the given item has the key, False otherwise
| Parameters: | path – the path of the given item |
|---|
>>> b = Bag({'a':1,'b':2,'c':3})
>>> b.has_key('a')
True
>>> b.has_key('abc')
False
Return a copy of the Bag as a list of tuples containing all key,value pairs
>>> b = Bag({'a':1,'b':2,'c':3})
>>> b.items()
[('a', 1), ('c', 3), ('b', 2)]
TODO
TODO
TODO
Return a copy of the Bag as a list of keys
>>> b = Bag({'a':1,'a':2,'a':3})
>>> b.keys()
['a', 'c', 'b']
Allow a Bag to be picklable
Warning
deprecated since version 0.7
Allow to merge two bags into one
>>> john_doe=Bag()
>>> john_doe['telephones']=Bag()
>>> john_doe['telephones.house']=55523412
>>> other_numbers=Bag({'mobile':444334523, 'office':3320924, 'house':2929387})
>>> other_numbers.setAttr('office',{'from': 9, 'to':17})
>>> john_doe['telephones']=john_doe['telephones'].merge(other_numbers)
>>> print john_doe
0 - (Bag) telephones:
0 - (int) house: 2929387
1 - (int) mobile: 444334523
2 - (int) office: 3320924 <to='17' from='9'>
>>> john_doe['credit_cards']=Bag()
Get the actual list of nodes contained in the Bag. The getNodes method works as the filter of a list
Return a pickled Bag
| Parameters: |
|
|---|
This method is analog to dictionary’s pop() method. It pops the given item from a Bag at the relative path and returns it
| Parameters: |
|
|---|
>>> b = Bag()
>>> b.setItem('a',1)
>>> b.addItem('a',2)
>>> b.addItem('a',3)
>>> b.pop('a')
1
>>> print b
0 - (int) a: 2
1 - (int) a: 3
This method is analog to dictionary’s pop() method. It pops the given node from a Bag at the relative path and returns it
| Parameters: | path – path of the given node |
|---|
Remove a node’s validator at the given path
| Parameters: |
|
|---|
Restore a Bag from its picklable form to its original form
TODO
| Parameters: | childname – the childname including the row name |
|---|
Allow to set, modify or delete attributes into a node at the given path
You can set the attributes into a Bag with the _attributes parameter if you have a dict of attributes; alternatively, you can pass all the attributes as **kwargs.
>>> b = Bag()
>>> b.setAttr('documents.letters.letter_to_sheila', createdOn='12-4-2003', createdBy='Walter', lastModify= '12-9-2003')
>>> b.setAttr('documents.letters.letter_to_sheila', fileOwner='Steve')
>>> b.setAttr('documents',{'type':'secret','createdOn':'2010-11-15'})
>>> print b
0 - (Bag) documents: <createdOn='2010-11-15' type='secret'>
0 - (Bag) letters:
0 - (str) letter_to_mark: file0 <createdOn='10-7-2003' createdBy='Jack'>
1 - (str) letter_to_john: file1 <lastModify='11-9-2003' createdOn='11-5-2003' createdBy='Mark'>
2 - (str) letter_to_sheila: file2 <lastModify='12-9-2003' createdOn='12-4-2003' fileOwner='Steve' createdBy='Walter'>
You may delete an attribute assigning None to an existing value:
>>> b.setAttr('documents.letters.letter_to_sheila', fileOwner=None, createdOn=None, createdBy=None)
>>> print b
0 - (Bag) documents: <createdOn='2010-11-15' type='secret'>
0 - (Bag) letters:
0 - (str) letter_to_sheila: file2 <lastModify='12-9-2003'>
Force a Bag to a more strict structure. It makes the Bag similar to a tree-leaf model: a Bag can have only one Parent and it knows this reference
| Parameters: |
|
|---|
An alternative syntax for a BagCbResolver call
| Parameters: |
|
|---|
TODO
| Parameters: |
|
|---|
Set an item (values and eventually attributes) to your Bag using a path in the form label1.label2...labelN. If path already exists, it overwrites the value at the given path. Return the Bag.
The default behaviour of setItem() is to add the new value as the last element. You can change this trend with the _position argument, who provides a compact syntax to insert the element in the desired place
| Parameters: |
|
|---|
Example:
>>> mybag = Bag()
>>> mybag.setItem('a',1)
>>> mybag.setItem('b',2)
>>> mybag.setItem('c',3)
>>> mybag.setItem('d',4)
>>> mybag.setItem('e',5, _position= '<')
>>> mybag.setItem('f',6, _position= '<c')
>>> mybag.setItem('g',7, _position= '<#3')
>>> print mybag
0 - (int) e: 5
1 - (int) a: 1
2 - (int) b: 2
3 - (int) g: 7
4 - (int) f: 6
5 - (int) c: 3
6 - (int) d: 4
Square-brackets notations:
Bag[path] = value
Example:
>>> mybag = Bag()
>>> mybag['a'] = 1
>>> mybag['b.c.d'] = 2
>>> print mybag
0 - (int) a: 1
1 - (Bag) b:
0 - (Bag) c:
0 - (int) d: 2
Note
if you have to use the _position attribute you can’t use the square-brackets notation
Set a resolver into the node at the given path
| Parameters: |
|
|---|
If path is in the Bag, return its value. If not, insert in the path the default value and return it. Default defaults to None
TODO
| Parameters: | pars – TODO None: label ascending |
|---|
Provide a subscribing of a function to an event. Subscribing an event on a Bag means that every time that it happens, it is propagated along the bag hierarchy and is triggered by its eventhandler. A subscription can be seen as a event-function couple, so you can define many eventhandlers for the same event
| Parameters: |
|
|---|
TODO
| Parameters: | what – TODO |
|---|
It transforms a flat Bag into a hierarchical Bag and returns it.
| Parameters: |
|
|---|
Return a complete standard XML version of the Bag, including the encoding tag <?xml version=‘1.0’ encoding=’UTF-8’?> (the docHeader default value)
The content of the Bag is hierarchically represented as an XML block sub-element of the node <GenRoBag> (see the toXmlBlock() documentation for more details about type representation). Is also possible to write the result on a file, passing the path of the file as the ‘filename’ parameter.
| Parameters: |
|
|---|
>>> mybag=Bag()
>>> mybag['aa.bb']=4567
>>> mybag.toXml()
'<?xml version='1.0' encoding='iso-8859-15'?>
<GenRoBag>
<aa><bb T="L">
4567</bb></aa></GenRoBag>'
TODO
Unpickle a pickled Bag
| Parameters: | source – the source path |
|---|
Delete a subscription of an event of a given subscriberId
| Parameters: |
|
|---|
Update the Bag with the key/value pairs from otherbag, overwriting all the existing keys. Return None
| Parameters: |
|
|---|
Return a copy of the Bag values as a list
Calls a function for each node of the Bag
| Parameters: | callback – the function which is called |
|---|
A standard resolver. Call a callback method, passing its kwargs parameters
TODO
Calculate the value of an algebric espression
TODO
TODO
BagNode is the element type which a Bag is composed of. That’s why it’s possible to say that a Bag is a collection of BagNodes. A BagNode is an object that gather within itself, three main things:
Set a new validator into the BagValidationList of the node. If there are no validators into the node then addValidator instantiate a new BagValidationList and append the validator to it
| Parameters: |
|
|---|
TODO
Receive one or more attributes’ labels and remove them from the node’s attributes
It returns the value of an attribute. You have to specify the attribute’s label. If it doesn’t exist then it returns a default value
| Parameters: |
|
|---|
TODO
Return the node’s label
Get node’s value in static mode
TODO
Return the value of the BagNode. It is called by the property .value
| Parameters: |
|
|---|
Check if a node has the given pair label-value in its attributes’ dictionary
TODO
TODO
Get node’s resolver
It receives one or more key-value couple, passed as a dict or as named parameters, and sets them as attributes of the node.
| Parameters: |
|
|---|
Set node’s label
Set node’s value in static mode
TODO
Set the node’s value, unless the node is locked. This method is called by the property .value
| Parameters: |
|
|---|
Get node’s value in static mode
TODO
| Parameters: |
|
|---|
TODO
Return the value of the BagNode. It is called by the property .value
| Parameters: |
|
|---|
BagResolver is an abstract class, that defines the interface for a new kind of dynamic objects. By “Dynamic” property we mean a property that is calculated in real-time but looks like a static one
TODO
TODO
TODO
TODO
TODO
TODO
Warning
deprecated since version 0.7
TODO
TODO
TODO
TODO
TODO
This class provides the validation system for a BagNode. This is a list of validators related to a BagNode. This class is used only from the addValidator and removeValidator methods of the Bag and BagNode’ classes. All the methods of this class must be considered private.
Add a new validator to the BagValidationList.
| Parameters: |
|
|---|
TODO
| Parameters: | value – TODO |
|---|
TODO
| Parameters: |
|
|---|
This method get the validatorsdata of a validator
Remove a validator
| Parameters: | validator – the validator to remove |
|---|
Set a validation for the case of a string value
| Parameters: |
|
|---|
TODO
| Parameters: |
|
|---|
Provide a validaton for Host address value
| Parameters: |
|
|---|
TODO
| Parameters: |
|
|---|
Provides a validation for the length of a string value
| Parameters: |
|
|---|
TODO
TODO
TODO
| Parameters: |
|
|---|
TODO
| Parameters: | path – TODO |
|---|
TODO
| Parameters: | path – TODO |
|---|
TODO
| Parameters: | path – TODO |
|---|
TODO
| Parameters: | path – TODO |
|---|
TODO
| Parameters: | path – TODO |
|---|