首页 > 解决方案 > 从 Python 3.7.x 中的本地文件导入函数后的问题

问题描述

我正在尝试将一组函数从外部文件导入到我的主文件中。主要原因是为了保持整洁。

我有一个命令输入屏幕,用户在其中输入命令,然后根据他们输入的内容执行命令。我想将命令存储在函数中,这些函数存储在单独的文件中。示例伪代码:

import other_file_example as other

clear = lambda: system.os('clear') or None

def foo_func():
   Do stuff
   other.do_stuff_in_main()

外部文件:

import main_file

def do_stuff_in_main():
   clear()
   execute_some_func_from main()

我遇到的问题是,默认情况下,如果不执行“From main import *”或其他某种形式的导入,我将无法访问 main 中定义的函数、对象和模块。然而,这让我的 linter 发疯了。我将所有内容导入到我的 Commands.py 文件中,然后将其导入到我的 Main.py 文件中。所以我双重导入它。它按预期工作。但是我的 linter 给了我一堆问题,抱怨 Function *****() 已经存在或一些类似的错误。我的问题是,我应该忽略 linter 吗?或者有没有更好的方法来做到这一点而不会抛出任何错误,同时保持程序的预期功能。

一个后续问题是:像这样进口会有什么后果?是否有任何性能、内存或任何其他由此产生的问题?

标签: python-3.x

解决方案


我解决了这个问题。我会把这个留给任何有类似问题的人。我通过向我的函数添加源模块参数解决了这个问题。每当我从另一个文件调用函数时,我都会传入对当前命名空间的引用。这允许函数执行和访问主文件中的对象和函数,而无需执行任何循环导入。

# file that contains my functions commands.py

def game_exit(source_module):
     confirm = input(source_module.term.red('Are you sure you want to exit?\nType y/n : '))
     if str(confirm) == 'y':
          source_module.cls()
          exit
     else:
          source_module.command_prompt()

MainCLI 文件:

# this is the mainCLI module

import commands
import sys
import os
from blessings import Terminal

term = Terminal()    
cls = lambda: os.system('clear') or None
current_module = sys.modules[__name__]

commands.game_exit(current_module)

def command_prompt():
    input('Type a command and press enter...')
    if input:
        do stuff......

最后是 main.py 文件:

import mainCLI

if __name__ == "__main__":
      mainCLI.cls()
      mainCLI.main_loop()

到目前为止,这非常有效。上面的代码大大压缩了实际使用的代码。但希望这能解释我是如何解决这个问题的。祝人民好运。


推荐阅读