Last active
August 29, 2018 16:00
-
-
Save warm200/0358d8a4b991beab435827e609f3e298 to your computer and use it in GitHub Desktop.
Return all key, value as a dictionary under a subclass
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
class A(object): | |
class Argument: | |
a = "testme" | |
b = list("this is a list") | |
class _OldClass: | |
pass | |
class _NewClass(object): | |
pass | |
_all_vars = set(dir(_OldClass) + dir(_NewClass)) | |
def props(x): | |
return { | |
key: vars(x).get(key, getattr(x, key)) for key in dir(x) if key not in _all_vars | |
} | |
# Note: | |
# vars(x).get(key, gettattr(x, key)) is used instead of the | |
# simpler gettatrr(x, key) for python2.7 compat. | |
# Indeed python2 and python3 lead to different results for | |
# class Foo(object): | |
# def bar(self): | |
# pass | |
# getattr(Foo, 'bar') | |
# python 2.7 : > unbound method bar | |
# python 3.x : > function Foo.bar | |
# print(props(getattr(a, "Argument", None))) | |
# >> {'a': 'testme', 'b': ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 'l', 'i', 's', 't']} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment