Python 我试图通过py文件传递一个全局变量。这是正确的吗?

Python 我试图通过py文件传递一个全局变量。这是正确的吗?,python,function,Python,Function,但现在我想在它自己的文件中定义这个方便的dandy函数,这样我每次处理新代码时都可以调用它,而不必每次都复制粘贴它。这适用于使用完整模块名调用函数。但不是通过整数。你自己运行我的两个代码,因为我不是最擅长解释的! 因此: 问题在于我的全球mlist。现在我无法将枚举映射到变量,然后使用相同的映射进行删除。因为变量刚刚消失。将函数的返回值分配给模块级变量 # Now in its own file --- "pyfile1.py" def mods(*arg): gl

但现在我想在它自己的文件中定义这个方便的dandy函数,这样我每次处理新代码时都可以调用它,而不必每次都复制粘贴它。这适用于使用完整模块名调用函数。但不是通过整数。你自己运行我的两个代码,因为我不是最擅长解释的! 因此:


问题在于我的全球mlist。现在我无法将枚举映射到变量,然后使用相同的映射进行删除。因为变量刚刚消失。

将函数的返回值分配给模块级变量

# Now in its own file --- "pyfile1.py"

def mods(*arg):
    global mlist
    from inspect import currentframe
    if not arg:
        mlist = [module for module in sorted(currentframe().f_back.f_globals)
                 ]
        
        return(mlist)
    
    else:
        for i in arg:
            del currentframe().f_back.f_globals[i]
            
        return([module for module in sorted(currentframe().f_back.f_globals)],
               "-----------------------------------------------",
               "Deleted: "+
               str(arg[:]))

# Open new file: "pyfile2.py"

  from pyfile1 import *
  mods() # works
  mods("tensorflow") works
  mods(1,2,18,20) # having hard time coding this part

谢谢我的模块是否有办法以某种方式返回全局mlist变量?我想不出有什么。您必须在该框架本身中运行模块…只有这样,它才能创建该变量。。。。。我想以某种方式调用模块mods(1,2,3)
[模块对模块排序(currentframe().f_back.f_globals)]
是一种列表理解,它创建了一个新的列表,您的函数永远不会对另一个作用域中的列表进行操作。
# Now in its own file --- "pyfile1.py"

def mods(*arg):
    global mlist
    from inspect import currentframe
    if not arg:
        mlist = [module for module in sorted(currentframe().f_back.f_globals)
                 ]
        
        return(mlist)
    
    else:
        for i in arg:
            del currentframe().f_back.f_globals[i]
            
        return([module for module in sorted(currentframe().f_back.f_globals)],
               "-----------------------------------------------",
               "Deleted: "+
               str(arg[:]))

# Open new file: "pyfile2.py"

  from pyfile1 import *
  mods() # works
  mods("tensorflow") works
  mods(1,2,18,20) # having hard time coding this part
#pyfile2.py
from pyfile1 import *
mlist = mods() # works
mlist , *stuff= mods("tensorflow") works
mlist, *stuff = mods(1,2,18,20) # having hard time coding this part