Reputation: 278
I have two files:
file1:
import file2
file2.func1(file2.variable1)
def func2(arg):
print('this is func2')
print('it takes this:', arg)
file2:
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. Pycharm IDE does not pick up any errors but when I run it I get:
AttributeError: module 'file1' has no attribute 'func2'
What's the best practice to spread functions?
Upvotes: 0
Views: 46
Reputation: 101
it is a good practice to use packaging in 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. It should be uni directional.
Below is an example:
Upvotes: 1
Reputation: 5359
I wouldn't use circular imports. Try a setup like this:
package
with modules
, is an empty file)statics
and your function call)statics
and your function call)file1.py:
import statics
statics.func1(statics.variable1)
file2.py:
import statics
statics.func2(statics.variable1)
statics.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 :)
Upvotes: 1