Return dict {attribute_name: attribute_value}, objects filtered. i.e {'a': 1, 'b': (2, 2), 'c': [3, 3]}
{k: val for k, val in self.__dict__.items() if not str(hex(id(val))) in str(val)}
Return list [attribute_names], objects filtered. i.e ['a', 'b', 'c', 'd']
[k for k, val in self.__dict__.items() if not str(hex(id(val))) in str(val)]
Return list [attribute_values], objects filtered. i.e [1, (2, 2), [3, 3], {4: 4}]
[val for k, val in self.__dict__.items() if not str(hex(id(val))) in str(val)]
Removing the if
condition. Return {'a': 1, 'c': [3, 3], 'b': (2, 2), 'e': <function <lambda> at 0x7fc8a870fd70>, 'd': {4: 4}, 'f': <object object at 0x7fc8abe130e0>}
{k: val for k, val in self.__dict__.items()}
As long as the default implementation of __repr__
is not overridden the if
statement will return True
if the hexadecimal representation of the location in memory of val
is in the __repr__
return string.
Regarding the default implementation of __repr__
you could find useful this answer. In short:
def __repr__(self):
return '<{0}.{1} object at {2}>'.format(
self.__module__, type(self).__name__, hex(id(self)))
Wich returns a string like:
<__main__.Bar object at 0x7f3373be5998>
The location in memory of each element is got via the id()
method.
Python Docs says about id():
Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
CPython implementation detail: This is the address of the object in memory.
class Bar:
def __init__(self):
self.a = 1
self.b = (2, 2)
self.c = [3, 3]
self.d = {4: 4}
self.e = lambda: "5"
self.f = object()
#__str__ or __repr__ as you prefer
def __str__(self):
return "{}".format(
# Solution in Short Number 1
{k: val for k, val in self.__dict__.items() if not str(hex(id(val))) in str(val)}
)
# Main
print(Bar())
Output:
{'a': 1, 'c': [3, 3], 'b': (2, 2), 'd': {4: 4}}
Note:
Tested with Python 2.7.13
and Python 3.5.3
In Python 2.x .iteritems()
is preferred over .items()