-1

Taking this question as a pointer, let's say there exists a class like the following:

class Container(object):
    def __init__(self, **kwargs):
      self._meta = defaultdict(lambda: None)
      for attr, value in kwargs.iteritems():
          self._meta[attr] = value

    def __getattr__(self, key):
      try:
          return self._meta[key]
      except KeyError:
          raise AttributeError(key)

    def __setattr__(self, key, value):
      if key in ('_meta', '_hasattr'):
          super(Container, self).__setattr__(key, value)
      else:
          self._meta[key] = value

This allows the following behavior:

c = Container()
c.a = 1
print(c.a) # 1
print(c.b) # None

Question: What is the best way to implement an operator such that the following works:

# Should delete the value of a from Container._meta
del c.a 

Of course, one could obviously implement a method like,

def _delete(self, key):
  ...

But is there way to re-use a python operator to do this?

Community
  • 1
  • 1
viksit
  • 7,542
  • 9
  • 42
  • 54

1 Answers1

1

Just define the __delattr__ method:

def __delattr__(self, key):
    del self._meta[key]
zondo
  • 19,901
  • 8
  • 44
  • 83
  • Thanks. I'd tried this before, and for some reason it wasn't working. I think the reason was that I was doing a "if key in self._meta", which screwed it up in some way I haven't been able to figure out yet. – viksit Mar 23 '16 at 20:11