Jun-22-2024, 08:14 AM
(This post was last modified: Jun-22-2024, 08:14 AM by Gribouillis.)
(Jun-22-2024, 01:21 AM)Skaperen Wrote: a function certainly should not access caller local namespace. but, in some cases, you need to work with local namespace in some common way in many places.This is not recommended, but I have a use case of this in my scripts, when I put notes to a class of students, I use a program that defines some global variables and then calls a function that uses the variables defined in this namespace. My solution is to pass the whole namespace to the function, so the script looks like this
SPAM = 'some spammish data' EGGS = 'some eggish data' HAM = 'some hammish data' from library import do_the_work result = do_the_work(globals()) # pass the global namespace to the function result.print_stats()Then
def do_the_work(dic): print(dic['SPAM']) ...This works with a
globals()
namespace, and do_the_work()
could even modify the global namespace. I could use it also with a locals()
namespace if the function only needs to read the data from this namespace, but one cannot write data in a locals()
namespace.For the global namespace, I could alternately pass the name of the current module because
do_the_work()
could then access the global namespace through the moduledo_the_work(__name__)then
def do_the_work(name): import sys module = sys.modules[name] print(module.SPAM) module.EGGS = 'some new value'The idea of using global variables like this came from the documentation of a very old and famous module, the PEAK module by Philip J Eby. He speaks about « executable configuration files » and it is the kind of concept I need to put notes to my students. In only need to set a few constants and then call an engine that processes that data.
« We can solve any problem by introducing an extra level of indirection »