简体   繁体   中英

Is it possible to catch empty nested attributes in python?

I'm trying to create a custom object that supports nested attributes.

I need to implement a specific kind of search.

If an attribute doesn't exist at the lowest level, I want to recurse and see if the attribute exists at a higher level.

I've spent all day trying to do this. The closest I've come is being able to print the attribute search path.

class MyDict(dict):
  def __init__(self):
    super(MyDict, self).__init__()

  def __getattr__(self, name):
    return self.__getitem__(name)

  def __getitem__(self, name):
    if name not in self:
      print name
      self[name] = MyDict()
    return super(MyDict, self).__getitem__(name)

config = MyDict()
config.important_key = 'important_value'
print 'important key is: ', config.important_key
print config.random.path.to.important_key

Output:

important key is:  important_value
random
path
to
important_key
{}

What I need to happen is instead to see if important_key exists at the lowest level ( config.random.path.to ), then go up a level ( config.random.path ) and only return None if it doesn't exist at the top level.

Do you think this is possible?

Thank you so much!

Yes, it's possible. In your search routine, recur to the end of the path, checking for the desired attribute. At the bottom level, return the attribute if found, None otherwise. At each non-terminal level, recur to the next level down.

if end of path   # base case
    if attribute exists here
        return attribute
    else
        return None
else  # some upper level
    exists_lower = search(next level down)
    if exists_lower
        return exists_lower
    else
        if attribute exists here
            return attribute
        else
            return None

Does this pseudo code get you moving toward a solution?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM