如何在中心工具包实现基于类名字符串的对象创建功能?
The issue with your current make_class function is that globals() in the utils module only returns the global namespace of the utils module itself—not the namespace of the main module where you defined my_class. Here are two practical fixes:
Option 1: Explicitly Pass the Caller's Global Namespace
This is the most straightforward and transparent approach. Modify your utils function to accept the caller's globals() as an argument:
# utils.py def make_class(class_name, caller_globals): try: cls = caller_globals[class_name] if not isinstance(cls, type): raise TypeError(f"{class_name} is not a class") return cls() except KeyError: raise ValueError(f"Class {class_name} not found in the provided namespace")
Then call it from your main module by passing your own globals():
# main.py import utils class my_class: def __init__(self): print("Instance of my_class created!") obj = utils.make_class('my_class', globals())
Option 2: Auto-Detect the Caller's Namespace with inspect
If you want to avoid forcing the caller to pass globals(), you can use Python's inspect module to automatically grab the caller's namespace from the call stack:
# utils.py import inspect def make_class(class_name): # Get the caller's frame (skip the current function's frame) caller_frame = inspect.stack()[1] caller_globals = caller_frame.frame.f_globals try: cls = caller_globals.get(class_name) if cls is None: raise ValueError(f"Class '{class_name}' not found in caller's namespace") if not isinstance(cls, type): raise TypeError(f"'{class_name}' refers to an object that's not a class") return cls() finally: # Clean up the frame to prevent memory leaks del caller_frame
Now you can use it exactly as you originally wanted:
# main.py import utils class my_class: def __init__(self): print("Instance of my_class created!") obj = utils.make_class('my_class')
Notes
- The
inspectapproach is convenient but has minor performance overhead, so it's best suited for small-scale use cases. - Both methods include basic error handling to avoid crashes if the class name is invalid or not found.
内容的提问来源于stack exchange,提问作者Ray Salemi

