What's the best way to minimize the need of run time checks?
Chris Angelico
rosuav at gmail.com
Sun Aug 14 09:18:40 EDT 2016
On Sun, Aug 14, 2016 at 8:49 PM, BartC <bc at freeuk.com> wrote:
> Well, it's using exec(). So it is generating new program code at runtime.
> That is possible in quite a few languages, even C.
It doesn't have to; that's only so it doesn't have to manually
construct a Function object. Or you could make a simpler __init__ that
requires keyword arguments. Here's an exec-free version:
def record(name, fieldnames):
if isinstance(fieldnames, str):
fieldnames = fieldnames.split()
class Inner(object):
__slots__ = fieldnames
def __init__(self, **kwargs):
for n in fieldnames:
if n in kwargs: setattr(self, n, kwargs[n])
def __repr__(self):
fields = ', '.join("%s=%r" % (n, getattr(self, n)) for n
in fieldnames)
return "record %s(%s)" % (type(self).__name__, fields)
Inner.__name__ = Inner.__qualname__ = name
return Inner
You lose the ability to construct a record with positional args, and
you lose the argument name info from help() and other forms of
introspection, but it works, and it doesn't use exec.
How do you do that in C? Do you have an 'exec' function in C?
Certainly not in any of my compilers. The nearest equivalent would be
a compile-time directive, eg a preprocessor macro, and that most
definitely isn't this flexible. Types just aren't first-class objects
in C.
ChrisA
More information about the Python-list
mailing list