[reportlab-users] python data types for tables

Robin Becker robin at reportlab.com
Fri Apr 28 07:19:19 EDT 2006

will at phototropia.org wrote:
> Friends:
>       I am storing the data and attributes for tables in dictionaries with
> one dictionary for each table.  I have two routes for storing these
> dictionaries:
> 1)Make a dictionary of dictionaries called say tables with the name of
> each table as dictionary name in tables.
> 2)Make a list of the table dictionaries witht the name of the table as an
> attribute in the dictionary.
>       I will have few enough tables per project that it probably doesn't
> matter, but others will likely use this for potentially many tables,
> if that effects the decision.
>       If I go with the list of dictionaries, I have to iterate through the
> list to find a table everytime something is changed.  With a
> dictionary of dictionaries, I would have to copy a table's
> dictionary to change the name of the dictionary.
>      Any thougts on which data model is better, or criteria for this
> decision?
> thanks,
> Will

Why exactly do you need to copy in the dictionary case? For renaming that's not true

ie to rename table 'A' to be called 'B'

Tables['B'] = Tables['A']	#this is not a copy
del Tables['A']

Tables['B'] = Tables['A'].copy()	#this is a copy

in the other case presumably you have something like

T=[t for t in Tables if t.name=='A']
if T and len(T)==1:
     T[0].name = 'B'
     #handle no table or duplicate table errors

for copying you presumably have to do something like

T=[t for t in Tables if t.name=='A']
if T and len(T)==1:
     t = T[0].copy()
     t.name = 'B'
     #handle no table or duplicate table errors

here we assume that the table instances have a copy method to clone themselves. 
You'll need to subclass dict in the list case as you get an error doing this

 >>> a=dict()
 >>> a.name='A'
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
AttributeError: 'dict' object has no attribute 'name'

I think the dictionary case is easier. Note that in the dict copy only the top 
level of the dict is copied. The dictionaries can evolve separately, but if they 
contain mutable elements they are shared. EG

 >>> A = dict(a=[0,1,2],b=3)
 >>> B = A.copy()
 >>> A['a'].append(4)
 >>> B['a']
[0, 1, 2, 4]

to fully disambiguate you need to use copy.deepcopy
Robin Becker

More information about the reportlab-users mailing list