Access to the caller's globals, not your own

Ethan Furman ethan at stoneleaf.us
Wed Nov 16 04:30:22 EST 2016


On 11/16/2016 12:36 AM, Steven D'Aprano wrote:

> But, for what its worth...
>
> I have a function, let's call it quartile(data, n). Unfortunately there's about
> a dozen different ways to calculate quartiles, and they all give ever-so-
> slightly different results. So I end up with:
>
> def quartile(data, n, scheme="Method 7"):
>      ...
>
>
> which lets the caller choose the specific calculation method they want to use,
> or just use the default. *My* default, chosen by me, which may or may not be
> convenient.
>
> And then there's a bunch of other functions which depend on quartile(). I don't
> have to list them, but there's at least two and may be more. They too will have
> an optional parameter to choose a calculation method. And *that* almost rules
> out your factory function idea: having to call a factory to create multiple
> functions is too confusing for a library API.
>
>      quartile, iqr, blah blah blah = library.make_functions()
>
>
> So while I'd consider that under some circumstances, I don't like it here.
>
> I'd like the caller to be able to set their own default, if they don't like
> mine, in the easiest way possible. That means a global.
>
> DEFAULT_SCHEME = "Method 7"
>
> # Late binding of the default, instead of early binding.
> def quartile(data, n, scheme=None):
>      if scheme is None:
>          scheme = DEFAULT_SCHEME
>      ...
>
>
> Say they want to match the same calculation method that Excel uses, they can
> just modify the library.DEFAULT_SCHEME and forget all about it.
>
> But that's globally global, and I actually want it to only be global to their
> own module. Hence my question.

I think you stuck with the same solution Decimal uses: a context that you can either set globally global, or one that can be used as a context manager.

--
~Ethan~



More information about the Python-list mailing list