Skip to content

Instantly share code, notes, and snippets.

@val314159
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save val314159/ef6232cc5c623cff6642 to your computer and use it in GitHub Desktop.
Save val314159/ef6232cc5c623cff6642 to your computer and use it in GitHub Desktop.
Just use this function to grab all your parents' private variables in a list.
def _append_private_attr(cls,inst,propname,ret):
attrname = '_%s__%s' %(cls.__name__, propname)
if hasattr(inst,attrname):
ret.append( getattr(inst,attrname) )
pass
def get_private_inherited_attrs(cls,inst,propname,ret=None):
"""
Just use this function to grab all your parents private variables in a list.
Motivation:
In python, using private class variables (vars that start with __)
don't work at all when using super. (the descriptor doesn't get private
class varialbes for whatever reason)
this makes it extrmely hard to use with super(), hence this routine.
Usage:
class B:
__my_prop_name = ['B-val',0,1,2,3]
pass
class B2:
__my_prop_name = ['B2-val',10,11,12,13]
pass
class A(B,B2):
__my_prop_name = ['A-val',4,5,6,7]
pass
a = A()
results = get_private_inherited_attrs(a.__class__,a,'my_prop_name')
"""
if ret is None:
ret = []
pass
_append_private_attr(cls,inst,propname,ret)
if hasattr(cls,'__mro__'):
for base in cls.__mro__:
_append_private_attr(base,inst,propname,ret)
pass
return ret
else:
# ok old style class, hope there's no dreaded diamond...
for base in cls.__bases__:
_append_private_attr(base,inst,propname,ret)
get_private_inherited_attrs(base,inst,propname,ret)
pass
return ret
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment