Created
March 16, 2015 18:45
-
-
Save jennielees/e3cdb3353fa725703ede to your computer and use it in GitHub Desktop.
inspecting python classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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