Last active
December 3, 2019 15:02
-
-
Save santiagobasulto/c04052e07d243b2561d66e5dbc83f4f7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Tuple(tuple): | |
def __getattr__(self, name): | |
def _int(val): | |
try: | |
return int(val) | |
except ValueError: | |
return False | |
if not name.startswith('_') or not _int(name[1:]): | |
raise AttributeError("'tuple' object has no attribute '%s'" % name) | |
index = _int(name[1:]) - 1 | |
return self[index] | |
t = Tuple(['z', 3, 'Python', -1]) | |
print(t._1) # 'z' | |
print(t._2) # 3 | |
print(t._3) # 'Python' |
This file contains hidden or 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
t = Tuple(['z', 3, 'Python', -1]) | |
assert t._1 == 'z' | |
assert t._2 == 3 | |
assert t._3 == 'Python' | |
assert t._4 == -1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if not name.startswith('_') or not _int(name[1:])
statement can be changed toif not name.startswith('_') or not _int(name[1:]) or len(self) < _int(name[1:])
to make it more robust. Will help in avoiding IndexError: tuple index out of range