Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
import vs inserting code
#7
(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 module
do_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 »
Reply


Messages In This Thread
import vs inserting code - by Skaperen - Jun-14-2024, 01:18 AM
RE: import vs inserting code - by rodiongork - Jun-19-2024, 07:55 PM
RE: import vs inserting code - by Gribouillis - Jun-19-2024, 09:42 PM
RE: import vs inserting code - by Skaperen - Jun-20-2024, 10:38 PM
RE: import vs inserting code - by rodiongork - Jun-21-2024, 05:47 AM
RE: import vs inserting code - by Skaperen - Jun-22-2024, 01:21 AM
RE: import vs inserting code - by Gribouillis - Jun-22-2024, 08:14 AM
RE: import vs inserting code - by Skaperen - Jun-23-2024, 01:54 AM
RE: import vs inserting code - by Gribouillis - Jun-23-2024, 06:52 AM
RE: import vs inserting code - by AdamHensley - Jun-23-2024, 12:02 PM
RE: import vs inserting code - by Skaperen - Jun-26-2024, 09:58 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  visual studio code python how to get source code of import module definitian umen 2 4,200 Jun-13-2020, 06:20 PM
Last Post: umen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020