Skip to content

Instantly share code, notes, and snippets.

@ptmcg
Last active August 19, 2021 07:43
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 ptmcg/668b5ea354cfca6d234d1fac1a2d4b14 to your computer and use it in GitHub Desktop.
Save ptmcg/668b5ea354cfca6d234d1fac1a2d4b14 to your computer and use it in GitHub Desktop.
DRY namedtuple
#
# auto_namedtuple.py
#
# I like my martinis and my Python DRY
#
# Copyright 2020, Paul McGuire
#
import traceback
from collections import namedtuple
def autonamedtuple(field_names, **kwargs):
# read the calling source line to get the name of the variable
# being assigned to - use that as that namedtuple's class name
# (assumes that the calling source line is of the form:
# ClassName = autonamedtuple(... etc. ...)
stack = traceback.extract_stack(limit=2)
caller_line = stack[0][-1]
class_name = caller_line.partition('=')[0].strip()
return namedtuple(class_name, field_names, **kwargs)
# instead of this
Point = namedtuple("Point", "x y", defaults=(0, 0))
# write this
Point = autonamedtuple("x y", defaults=(0, 0))
# try it out!
print(Point, Point())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment