Python:循环与字典场景下,导入函数传参与同模块全局变量对比
Hey there! Let's break down how to handle this scenario where you've split your code into modules, and now need to traverse that big decision tree dict while pulling variables from multiple input dicts (without relying on global variables). Here are a few practical, maintainable approaches:
1. Wrap Input Dicts in a Context Object
Instead of passing each input dict separately every time, bundle them into a single container class or dataclass. This keeps your function parameters clean and avoids having to update every function call if you add a new input dict later.
# Main module setup class InputContext: def __init__(self, user_data, system_config, runtime_state): self.user_data = user_data self.system_config = system_config self.runtime_state = runtime_state # Initialize the context and pass it to your module function from tree_traversal import traverse_tree input_ctx = InputContext(user_data_dict, system_config_dict, runtime_state_dict) final_result = traverse_tree(decision_tree_root, input_ctx) # In your split module (tree_traversal.py) def traverse_tree(node, input_ctx): if node["type"] == "variable": # Map node source to the corresponding dict in the context source_map = { "user": input_ctx.user_data, "system": input_ctx.system_config, "runtime": input_ctx.runtime_state } return source_map[node["source"]][node["key"]] elif node["type"] == "branch": # Recursively traverse child nodes with the same context condition_val = traverse_tree(node["condition"], input_ctx) return traverse_tree(node["true_branch"], input_ctx) if condition_val else traverse_tree(node["false_branch"], input_ctx)
2. Use Keyword Argument Unpacking
If you prefer not to create a custom class, pack all input dicts into a single dictionary and unpack them when calling your module function. This keeps calls concise while making dependencies explicit.
# Main module call from tree_traversal import traverse_tree input_dicts = { "user_data": user_data_dict, "system_config": system_config_dict, "runtime_state": runtime_state_dict } final_result = traverse_tree(decision_tree_root, **input_dicts) # In tree_traversal.py def traverse_tree(node, user_data, system_config, runtime_state): if node["type"] == "variable": source_map = { "user": user_data, "system": system_config, "runtime": runtime_state } return source_map[node["source"]][node["key"]] # ... rest of your traversal logic
3. Encapsulate Traversal in a Class
For a more OOP approach, create a traverser class that initializes with your input dicts. Then, the traversal method can access these dicts directly without needing to pass them around recursively.
# In tree_traversal.py class DecisionTreeTraverser: def __init__(self, user_data, system_config, runtime_state): self.source_map = { "user": user_data, "system": system_config, "runtime": runtime_state } def traverse(self, node): if node["type"] == "variable": return self.source_map[node["source"]][node["key"]] elif node["type"] == "condition": left_val = self.traverse(node["left"]) right_val = self.traverse(node["right"]) return left_val >= right_val # Example condition check # ... handle other node types # Main module usage from tree_traversal import DecisionTreeTraverser traverser = DecisionTreeTraverser(user_data_dict, system_config_dict, runtime_state_dict) final_result = traverser.traverse(decision_tree_root)
Quick Tips:
- Keep your
source_mapconsistent across all traversal logic to avoid duplicate code. - If your input dicts share a common interface (e.g., all use a
getmethod with default values), you can simplify variable retrieval even further. - Avoid cross-module global variables—it makes your code harder to test, debug, and reuse.
内容的提问来源于stack exchange,提问作者user3112131

