0

I've noted that in some languages, clojure for example, you can assign meta-data to objects.

In Python, you can also do something like this.

class meta_dict(dict):pass
a={'name': "Bill", 'age':35}
meta_a = meta_dict(a)
meta_a.secret_meta_data='42'
meta_a==a
True
secret_meta_data_dict=meta_a.__dict__
original_dict=dict(meta_a)

I was wondering if this a reasonable pattern to follow when you need to have data in a particular form but want some other data to follow along gracefully.

Alex Miller
  • 69,183
  • 25
  • 122
  • 167
Dave31415
  • 2,846
  • 4
  • 26
  • 34

1 Answers1

0

No comment on ...reasonable pattern to follow... but here is another way to do that using __metaclass__

>>> class MetaFoo(type):
    def __new__(mcs, name, bases, dict):
        dict['foo'] = 'super secret foo'
        return type.__new__(mcs, name, bases, dict)


>>> class Wye(list):
    __metaclass__ = MetaFoo


>>> class Zee(dict):
    __metaclass__ = MetaFoo


>>> y = Wye()
>>> y.append(1)
>>> y.append(2)
>>> y
[1, 2]
>>> y.foo
'super secret foo'
>>> z = Zee({1:2, 3:4})
>>> z[1]
2
>>> z.items()
[(1, 2), (3, 4)]
>>> z.foo
'super secret foo'
>>> 
wwii
  • 23,232
  • 7
  • 37
  • 77