ipstruct

Module: ipstruct

Inheritance diagram for IPython.ipstruct:

Mimic C structs with lots of extra functionality.

Struct

class IPython.ipstruct.Struct(dict=None, **kw)

Class to mimic C structs but also provide convenient dictionary-like functionality.

Instances can be initialized with a dictionary, a list of key=value pairs or both. If both are present, the dictionary must come first.

Because Python classes provide direct assignment to their members, it’s easy to overwrite normal methods (S.copy = 1 would destroy access to S.copy()). For this reason, all builtin method names are protected and can’t be assigned to. An attempt to do s.copy=1 or s[‘copy’]=1 will raise a KeyError exception. If you really want to, you can bypass this protection by directly assigning to __dict__: s.__dict__[‘copy’]=1 will still work. Doing this will break functionality, though. As in most of Python, namespace protection is weakly enforced, so feel free to shoot yourself if you really want to.

Note that this class uses more memory and is much slower than a regular dictionary, so be careful in situations where memory or performance are critical. But for day to day use it should behave fine. It is particularly convenient for storing configuration data in programs.

+,+=,- and -= are implemented. +/+= do merges (non-destructive updates), -/-= remove keys from the original. See the method descripitions.

This class allows a quick access syntax: both s.key and s[‘key’] are valid. This syntax has a limitation: each ‘key’ has to be explicitly accessed by its original name. The normal s.key syntax doesn’t provide access to the keys via variables whose values evaluate to the desired keys. An example should clarify this:

Define a dictionary and initialize both with dict and k=v pairs: >>> d={‘a’:1,’b’:2} >>> s=Struct(d,hi=10,ho=20)

The return of __repr__ can be used to create a new instance: >>> s Struct({‘__allownew’: True, ‘a’: 1, ‘b’: 2, ‘hi’: 10, ‘ho’: 20})

Note: the special ‘__allownew’ key is used for internal purposes.

__str__ (called by print) shows it’s not quite a regular dictionary: >>> print s Struct({‘__allownew’: True, ‘a’: 1, ‘b’: 2, ‘hi’: 10, ‘ho’: 20})

Access by explicitly named key with dot notation: >>> s.a 1

Or like a dictionary: >>> s[‘a’] 1

If you want a variable to hold the key value, only dictionary access works: >>> key=’hi’ >>> s.key Traceback (most recent call last):

File “<stdin>”, line 1, in ?

AttributeError: Struct instance has no attribute ‘key’

>>> s[key]
10

Another limitation of the s.key syntax (and Struct(key=val) initialization): keys can’t be numbers. But numeric keys can be used and accessed using the dictionary syntax. Again, an example:

This doesn’t work (prompt changed to avoid confusing the test system): ->> s=Struct(4=’hi’) Traceback (most recent call last):

...

SyntaxError: keyword can’t be an expression

But this does: >>> s=Struct() >>> s[4]=’hi’ >>> s Struct({4: ‘hi’, ‘__allownew’: True}) >>> s[4] ‘hi’

__init__()

Initialize with a dictionary, another Struct, or by giving explicitly the list of attributes.

Both can be used, but the dictionary must come first: Struct(dict), Struct(k1=v1,k2=v2) or Struct(dict,k1=v1,k2=v2).

allow_new_attr()

Set whether new attributes can be created inside struct

This can be used to catch typos by verifying that the attribute user tries to change already exists in this Struct.

clear()

Clear all attributes.

copy()

Return a (shallow) copy of a Struct.

dict()

Return the Struct’s dictionary.

dictcopy()

Return a (shallow) copy of the Struct’s dictionary.

get()
has_key()

Like has_key() dictionary method.

hasattr()

hasattr function available as a method.

Implemented like has_key, to make sure that all available keys in the internal dictionary of the Struct appear also as attributes (even numeric keys).

items()

Return the items in the Struct’s dictionary, in the same format as a call to {}.items().

keys()

Return the keys in the Struct’s dictionary, in the same format as a call to {}.keys().

merge()

This is similar to update(), but much more flexible. First, a dict is made from data+key=value pairs. When merging this dict with the Struct S, the optional dictionary ‘conflict’ is used to decide what to do.

If conflict is not given, the default behavior is to preserve any keys with their current value (the opposite of the update method’s behavior).

conflict is a dictionary of binary functions which will be used to solve key conflicts. It must have the following structure:

conflict == { fn1 : [Skey1,Skey2,...], fn2 : [Skey3], etc }

Values must be lists or whitespace separated strings which are automatically converted to lists of strings by calling string.split().

Each key of conflict is a function which defines a policy for resolving conflicts when merging with the input data. Each fn must be a binary function which returns the desired outcome for a key conflict. These functions will be called as fn(old,new).

An example is probably in order. Suppose you are merging the struct S with a dict D and the following conflict policy dict:

S.merge(D,{fn1:[‘a’,’b’,4], fn2:’key_c key_d’})

If the key ‘a’ is found in both S and D, the merge method will call:

S[‘a’] = fn1(S[‘a’],D[‘a’])

As a convenience, merge() provides five (the most commonly needed) pre-defined policies: preserve, update, add, add_flip and add_s. The easiest explanation is their implementation:

preserve = lambda old,new: old update = lambda old,new: new add = lambda old,new: old + new add_flip = lambda old,new: new + old # note change of order! add_s = lambda old,new: old + ‘ ‘ + new # only works for strings!

You can use those four words (as strings) as keys in conflict instead of defining them as functions, and the merge method will substitute the appropriate functions for you. That is, the call

S.merge(D,{‘preserve’:’a b c’,’add’:[4,5,’d’],my_function:[6]})

will automatically substitute the functions preserve and add for the names ‘preserve’ and ‘add’ before making any function calls.

For more complicated conflict resolution policies, you still need to construct your own functions.

popitem()

a 2-tuple; but raise KeyError if S is empty.

setdefault()
update()

Update (merge) with data from another Struct or from a dictionary. Optionally, one or more key=value pairs can be given at the end for direct update.

values()

Return the values in the Struct’s dictionary, in the same format as a call to {}.values().

Can be called with an optional argument keys, which must be a list or tuple of keys. In this case it returns only the values corresponding to those keys (allowing a form of ‘slicing’ for Structs).

Table Of Contents

Previous topic

ipmaker

Next topic

irunner

This Page