Next / Previous / Contents / TCC Help System / NM Tech homepage

14.11. ElementMaker.__getattr__(): Handle arbitrary method calls

This method is called whenever the caller invokes an undefined method of a factory instance. It implements the feature that you can use an element name as a method name so that “E.tag(...)” is the equivalent of “E(tag, ...)”.

The method is a one-liner, but it's a rather abstruse one-liner for anyone that has never studied functional programming. See the functools.partial documentation. The method returns a callable object that acts the same as a call to the factory instance, except with tag inserted before its other positional arguments.

The Wikipedia article on currying explains this technique in depth.

etbuilder.py
# - - -   E l e m e n t M a k e r . _ _ g e t a t t r _ _

    def __getattr__(self, tag):
        '''Handle arbitrary method calls.

          [ tag is a string ->
              return a new et.Element instance whose name
              is (tag), and elements of p and kw have
              the same effects as E(*(p[1:]), **kw) ]
        '''
        return partial(self, tag)