Sebastian Meckovski
Sebastian Meckovski

Reputation: 278

Spreading Python Project throughout multiple files (MWE)

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

Answers (2)

H R
H R

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:

enter image description here

Upvotes: 1

JarroVGIT
JarroVGIT

Reputation: 5359

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)
  • file1.py (will only contain import of statics and your function call)
  • file2.py (will only contain import of statics and your function call)
  • statics.py (will hold the functions itself and the declared variables.

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

Related Questions