Access to the caller's globals, not your own
Dan Sommers
dan at tombstonezero.net
Mon Nov 14 23:55:22 EST 2016
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:
import library
# only affects this module, no other modules
library = library.make_library(spamify=False)
# ...
result = library.make_spam(99)
And then in library.py:
class Library:
def__init__(self, spamify=False):
self.spamify = spamify
def make_spam(self, p):
return ((p, "spammified")
if self.spamify else
(p, "hammified"))
def make_library(spamify=False):
return Library(spamify)
How do you want the following code to work:
import library
SPAMIFY=False
def make_false_spam():
return library.make_spam(99)
def make_true_spam():
global SPAMIFY
SPAMIFY=True
return library.make_spam(99)
I don't have to tell you how many things can go wrong with code like
that. ;-)
Yes, it's a straw man. No, I don't think we have all the details of
your use case. Yes, I'm willing to have missed something subtle (or not
so subtle).
Dan
More information about the Python-list
mailing list