On Mon, Feb 16, 2015 at 6:15 PM, Steven D'Aprano <st...@pearwood.info> wrote: > Here is a fork of that recipe. It uses an inner class for the new > namedtuple class. The only thing which needs exec is the __new__ method. > > http://code.activestate.com/recipes/578918-yet-another-namedtuple/ > > This demonstrates a powerful truth about Python: *most of the time* you > don't need to use exec or eval because the standard language features > are powerful enough to solve the problem for you. Using a dynamically > created inner class is *almost* enough to solve this problem, only the > __new__ method defeats it. If our requirements where just a little less > demanding, we could avoid exec completely.
No, exec is not necessary at all. If they had to the author could have reimplemented the argument assignment logic by hand. They chose not to because it is "too hard". (And it is.) Fortunately, they don't have to go that far: signature = inspect.Signature([ inspect.Parameter(field_name, inspect.Parameter.POSITIONAL_OR_KEYWORD) for field_name in field_names]) def __new__(cls, *args, **kwargs): return tuple.__new__(cls, signature.bind(*args, **kwargs).arguments.values()) -- Devin _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor