1

I created a custom py file that returns your globals() values and lets you delete any imported modules. However since it runs globals() within that function, when I import the module in another py file, it just returns the globals() directory files for the function namespace where it was defined. I hope this makes sense.

Example:

   # custom py file: "mod1.py"

   def mods():
   return( globals() )
   

   # different py file, kernel reset

    from mod1 import mods
    mods()

So what is happening is that it is running globals() - which returns all the names in the local namespace but that namespace is where the function was define aka: "mod1.py". How can I run it in the 2nd py file?

Py_Student
  • 163
  • 1
  • 12
  • Is this any help? https://stackoverflow.com/questions/6618795/get-locals-from-calling-namespace-in-python – alani Jul 25 '20 at 18:01

1 Answers1

1

Based on this answer to a somewhat related question -- if I've correctly understood what you are trying to achieve -- you could have:

mod1.py

import inspect
from types import ModuleType

def delete_modules():
    "deletes modules from namespace of the caller"
    frame = inspect.currentframe()
    try:
        globals = (frame.f_back.f_globals)
        to_delete = []
        for name, obj in globals.items():
            if type(obj) == ModuleType and name != '__builtins__':
                to_delete.append(name)
        for name in to_delete:
            print(f"Deleting module {name}")
            del globals[name]            
    finally:
        del frame

And then do:

>>> import os
>>> import sys
>>> from mod1 import delete_modules
>>> a = "hello"
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'delete_modules', 'os', 'sys']
>>> delete_modules()
Deleting module os
Deleting module sys
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'delete_modules']
alani
  • 12,573
  • 2
  • 13
  • 23
  • This is good, but I dont want to manage just modules. I want to return all the functions defined, namespace variables, modules imported. Basically what globals().keys() returns – Py_Student Jul 25 '20 at 19:23
  • 1
    @Py_Student The `globals` variable here inside `delete_modules` is the globals as seen in the caller. You could make a function that simply returns this instead of doing anything with it. In that case, it is essentially just the code that I borrowed from the page which I quoted, but with `f_globals` instead of `f_locals`. – alani Jul 25 '20 at 19:36