Access to the caller's globals, not your own

Dan Sommers dan at tombstonezero.net
Thu Nov 17 00:40:04 EST 2016


On Thu, 17 Nov 2016 16:17:51 +1100, Steven D'Aprano wrote:

> ... factory functions are great. But I'm saying that as the writer of
> the library, not the user of the library. Can you imagine expecting
> users to do this?

> from math import trig
> sin = trig.build('sine')
> result = sin(0.1)

No, but I could expect users to do this:

    import math # trig functions take radians by default
    math = math.degree_math # but I like degrees

Or to choose from one of these:

    import math # trig functions take radians by default
    import math.degree_math as math # but I like degrees

Or to choose from one of these:

    import math.radian_math as math # use the radians version
    import math.degree_math as math # use the degrees version

The complexity is taken on once, by the library author, who (presumably)
understands the complexity better than the users do.

> It might only be one extra line of code, but conceptually it is an
> order of magnitude more complex. The user has to comprehend factory
> functions and first-class functions as values before they can even
> begin to understand this.

It is only one line of code, but only the library author has to deal
with the rest of that.

> The internal details of how the implementation works is not important
> to the user ...

On that we all agree.  :-)

> ... They only need to understand that the "scheme" parameter takes its
> value from the first found of:
> 
> - an explicit argument
> - a global variable called "WHATEVER"
> - the library default
> 
> which is pretty simple to understand and use.

Hey, wait a minute:  you've slipped another option into the mix because
you originally wanted a separate "global" setting for each module that
imports your library.  With a global global rather than a module global,
you might get something like this:

    import library # default is HAMMIFY
    library.default = library.SPAMMIFY # but I like SPAMMIFY instead

(At which point, I see your point about wanting the library to reach
"out" to some sort of global space rather than the user reaching "in" to
the library space after the fact.)



More information about the Python-list mailing list