简体   繁体   中英

Check if object path exists in tree of objects

I have a tree of objects and I need to check that particular object contains specific branch of objects. For example:

def specificNodeHasTitle(specificNode):
    # something like this
    return specificNode.parent.parent.parent.header.title != None

Is there an elegant way to do this without throwing exception if needed attribute is missing?

Use try..except :

def specificNodeHasTitle(specificNode):
    try:
        return specificNode.parent.parent.parent.header.title is not None
    except AttributeError:
        # handle exception, for example
        return False

There is nothing wrong with raising exceptions, by the way. It is a normal part of Python programming. Using try..except is the way to handle them.

This works as long as you don't need indexes of arrays in your path to the item.

def getIn(d, arraypath, default=None):
    if not d:
        return d 
    if not arraypath:
        return d
    else:
        return getIn(d.get(arraypath[0]), arraypath[1:], default) \
            if d.get(arraypath[0]) else default

getIn(specificNode,["parent", "parent", "parent", "header", "title"]) is not None

For your specific case, the solution provided by unutbu is the best and the most pythonic, but I can't help trying to show the great capabilities of python and its getattr method:

#!/usr/bin/env python
# https://stackoverflow.com/questions/22864932/python-check-if-object-path-exists-in-tree-of-objects

class A(object):
  pass

class Header(object):
  def __init__(self):
    self.title = "Hello"

specificNode=A()
specificNode.parent = A()
specificNode.parent.parent = A()
specificNode.parent.parent.parent = A()
specificNode.parent.parent.parent.header = Header()

hierarchy1="parent.parent.parent.header.title"
hierarchy2="parent.parent.parent.parent.header.title"

tmp = specificNode
for attr in hierarchy1.split('.'):
  try:
    tmp = getattr(tmp, attr)
  except AttributeError:
    print "Ouch... nopes"
    break
else:
  print "Yeeeps. %s" % tmp


tmp = specificNode
for attr in hierarchy2.split('.'):
  try:
    tmp = getattr(tmp, attr)
  except AttributeError:
    print "Ouch... nopes"
    break
else:
  print "Yeeeps. %s" % tmp

That outputs:

Yeeeps. Hello
Ouch... nopes

Python's great :)

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