Skip to content

Instantly share code, notes, and snippets.

@jennielees
Created March 16, 2015 18:45
Show Gist options
  • Save jennielees/e3cdb3353fa725703ede to your computer and use it in GitHub Desktop.
Save jennielees/e3cdb3353fa725703ede to your computer and use it in GitHub Desktop.
inspecting python classes
def get_property_or_default(obj, prefix):
# If any of the properties defined on this object match the prefix, return
# the value of that property.
for key, value in obj.__dict__.iteritems():
if key.startswith(prefix):
return value
# Otherwise, we check that there is exactly one property, and return that
assert len(obj.__dict__) == 1
return value
def get_property_or_default(obj, prefix):
# a more functional/obtuse way of doing it
match = filter(lambda k: k.startswith(prefix), obj.__dict__)
if len(match) > 0:
return obj.__dict__.get(start[0])
else:
return obj.__dict__.values()[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment