Created
July 3, 2013 05:15
-
-
Save thomasballinger/5915611 to your computer and use it in GitHub Desktop.
An object which appears to respect the semantics described at http://akaptur.github.io/blog/2013/06/28/side-effecting-assignment/
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
import gc | |
class Foo(object): | |
"""Object which appears to take the name of the first reference name | |
>>> Foo().name | |
>>> f = Foo() | |
>>> f.name | |
'f' | |
>>> g = f | |
>>> g.name | |
'f' | |
""" | |
def __init__(self): | |
self._name = None | |
def __repr__(self): | |
return '<Foo %s>' % self.name | |
def set_name(self): | |
if self._name is None: | |
namespaces = [ref for ref in gc.get_referrers(self) if isinstance(ref, dict)] | |
keys = [name for ns in namespaces for name, v in ns.iteritems() if v is self] | |
if len(keys) > 1: | |
print 'you caught me, I can\'t actually tell which was first' | |
self._name = ' aka '.join(keys) | |
elif len(keys) == 1: | |
self._name = keys[0] | |
@property | |
def name(self): | |
self.set_name() | |
return self._name | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment