Access to the caller's globals, not your own

Rob Gaddi rgaddi at highlandtechnology.invalid
Wed Nov 16 12:52:56 EST 2016


Steven D'Aprano wrote:

> On Tuesday 15 November 2016 15:55, Dan Sommers wrote:
>
>> On Mon, 14 Nov 2016 16:20:49 +1100, Steven D'Aprano wrote:
>> 
>>> import library
>>> SPAMIFY = False  # only affects this module, no other modules
>>> result = library.make_spam(99)
>> 
>> I must be missing something, because it seems too obvious:
> [snip]
>
> I wouldn't say "obvious" so much as "complex".
>
> A factory function or a class that holds state for a local make_spam() callable 
> would be a possible solution, but it significantly increases the complexity, 
> especially for the simple case:
>
> import library
> result = library.make_spam(arg)
>
>
> versus:
>
> import library
> make_spam = library.make_library()
> result = make_spam(arg)
>
> What a drag.
>
>

And there you have it; an entire extra line at import time.

It's the answer that's explicit.  It's versatile (you can create
multiple library instances with different defaults if that sort of thing
is really your jam), and it uses no tricky mechanisms that unskilled
programmers won't understand.

You can even create a default object in the main library with some
sensible defaults and bind out the methods as functions just to provide
a quick and easy answer for people who don't care.

  class Library:
    ...

  _defaultlib = Library()
  _defaultlib.rounding = NEAREST_EVEN
  make_spam = _defaultlib.make_spam

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.



More information about the Python-list mailing list