简体   繁体   English

在多个文件中传播 Python 项目 (MWE)

[英]Spreading Python Project throughout multiple files (MWE)

I have two files:我有两个文件:

file1:文件1:

import file2

file2.func1(file2.variable1)


def func2(arg):
    print('this is func2')
    print('it takes this:', arg)

file2:文件2:

import file1

variable1 = 'this is variable 1'


def func1(var):
    print('this is function1')
    print('and', var)


file1.func2(variable1)

The main reason I want such a split is that my project is getting quite big and I'd like to start moving some functions into separate.py files for better readability and more comfortable maintenance.我想要这样一个拆分的主要原因是我的项目变得相当大,我想开始将一些功能移动到单独的.py 文件中,以获得更好的可读性和更舒适的维护。 Pycharm IDE does not pick up any errors but when I run it I get: Pycharm IDE 没有发现任何错误,但是当我运行它时,我得到:

AttributeError: module 'file1' has no attribute 'func2'

What's the best practice to spread functions?传播函数的最佳实践是什么?

I wouldn't use circular imports.我不会使用循环导入。 Try a setup like this:尝试这样的设置:

  • __init__.py (making sure your folder is being seen as a package with modules , is an empty file) __init__ .py(确保您的文件夹被视为带有modulespackage是一个空文件)
  • file1.py (will only contain import of statics and your function call) file1.py (将仅包含statics导入和您的 function 调用)
  • file2.py (will only contain import of statics and your function call) file2.py (将只包含statics导入和您的 function 调用)
  • statics.py (will hold the functions itself and the declared variables. statics.py (将保存函数本身和声明的变量。

file1.py:文件1.py:

import statics

statics.func1(statics.variable1)

file2.py:文件2.py:

import statics

statics.func2(statics.variable1)

statics.py:静态.py:

variable1 = 'this is variable 1'

def func2(arg):
    print('this is func2')
    print('it takes this:', arg)

def func1(var):
    print('this is function1')
    print('and', var)

This solves circular imports and will save you a ton of headache:)这解决了循环导入问题,将为您省去很多麻烦:)

it is a good practice to use packaging in python.在 python 中使用封装是一个很好的做法。 You are trying to import the files into each other.您正在尝试将文件相互导入。 This is called circular dependency.这称为循环依赖。 Try to create all the utilities in one package and import into another.尝试在一个 package 中创建所有实用程序并导入另一个。 It should be uni directional.它应该是单向的。


Below is an example:下面是一个例子:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM