Skip to content

Instantly share code, notes, and snippets.

@santiagobasulto
Last active December 3, 2019 15:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save santiagobasulto/c04052e07d243b2561d66e5dbc83f4f7 to your computer and use it in GitHub Desktop.
Save santiagobasulto/c04052e07d243b2561d66e5dbc83f4f7 to your computer and use it in GitHub Desktop.
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'
t = Tuple(['z', 3, 'Python', -1])
assert t._1 == 'z'
assert t._2 == 3
assert t._3 == 'Python'
assert t._4 == -1
@Madhurmm
Copy link

Madhurmm commented Dec 3, 2019

if not name.startswith('_') or not _int(name[1:]) statement can be changed to if 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment