Playing with Python Globals

Playing with globals in Klayout with Python.
open Macro Editor and add each of the
below to separate files.
Save each change the sys.path.append to your path
Running main.py will print what's in subfile
The first iteration stays in memory in Klayout,
if you change settings.myList.append('hey there now') in subfile
to something new it still uses the above.

This works in Anaconda Spyder Flawlessly
You should have 3 files
main.py
subfile.py
settings.py
Save all then run main.py

######################################################
# Save this as main.py 
from pya import *
import sys 
import re
#change the below to your path
sys.path.append("C:/Users/Tracy/KLayout/pymacros")
import settings
import subfile

#supposed to print whats in subfile
#but first iteration stays in memory in Klayout
#works in Spyder Flawlessly
settings.init()          # Call only once
subfile.stuff()         # Do stuff with global var
print(settings.myList[0])
######################################################
#Global vars settings
#Save this as settings.py
def init():
    global myList
    myList = []
######################################################
#Save this as  subfile.py
import sys
#change the below to your path
sys.path.append("C:/Users/Tracy/KLayout/pymacros")
import settings

def stuff():
    list.settings.myList()
    settings.myList.append('hey there now')
######################################################

Comments

  • Hi @tagger5896,

    I think the difference is that inside KLayout the interpreter stays alive. It lives inside the application and isn't just started with a script and shut down afterwards again. So if you add something to the path, it stays there until you close KLayout.

    Matthias

  • That's exactly the behavior as you described, how to fix it
    I have ideas . and this is limiting the idea.

  • Would it not be possible to read back, manipulate
    and write (not append) the path to "wherever" just
    as if it was the first time?

    There has to be some "de-cruft" facility?

  • edited March 2021

    Matthias, Jim

    The "de-cruft" sorcery is to remove the module from memory
    del Subfile
    del sys.modules["Subfile"]

    Matthias made an important point that I overlooked Klayout Python is an interpreter,
    so it stays alive . Remove the module from memory frees this up.

    I learn something new everyday.

    Thanks guys

  • More testing reveals you can reset the global variable
    Settings.myList = []

Sign In or Register to comment.