【发布时间】:2018-08-23 13:47:35
【问题描述】:
我想识别用户在其交互式 shell 中定义的所有字符串列表。
def lists_of_strings():
d = dict(globals(), **locals())
d = {k:v for (k, v) in d.items() if not k.startswith("_") and k != 'In'}
res = {}
for k, v in d.items():
if isinstance(v, list):
if all(map(lambda x: isinstance(x, str), v)):
res[k] = v
return res
当我在当前的 shell 中定义这个函数时,它可以工作:
>>> lists_of_strings()
{}
>>> mylist = ["a", "b"]
>>> lists_of_strings()
{"mylist": ["a", "b"]}
现在,如果我将这个函数移动到模块 mymodule 中并导入它:
>>> from mymodule import lists_of_strings
>>> lists_of_strings()
{}
>>> mylist = ["a", "b"]
>>> lists_of_strings()
{}
该函数总是返回一个空字典。为什么会这样,更重要的是,我可以解决它吗?
一些上下文:我正在尝试在我的模块中编写一个帮助程序来识别用户在当前 jupyter notebook 中定义的合适变量。我的目标是询问用户是否想将这些变量用作某些预定义函数的参数。
【问题讨论】:
标签: python module jupyter-notebook ipywidgets