Last active
August 19, 2021 07:43
-
-
Save ptmcg/668b5ea354cfca6d234d1fac1a2d4b14 to your computer and use it in GitHub Desktop.
DRY namedtuple
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
# | |
# 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