0

For better code readability, let's suppose that I've got my code logically splitted in different python files, my main main.py file and an included.py file. I'd like to embed included.py inside of the main file.

I know it's possible to import it on main.py (e.g. from included import *), but, in some cases, objects/classes/variables on the main.py file may be imported on the included.py file too (e.g. from main import *).

What I'd like to do is to import the included.py file "as is" (like PHP does, with the include statement) on a specific position of my main.py file, by forcing the interpreter to read the content of the file and to place it on the specified position.

Is it possible?

auino
  • 1,644
  • 5
  • 23
  • 43
  • 2
    I think its better to design in a way that you include only one file in another and not the cyclic way. – Teja Feb 07 '18 at 09:05

1 Answers1

1

In Python 2, try the execfile() command:

execfile('included.py')

In Python 3, try

exec(compile(open('included.py', "rb").read(), 'included.py', 'exec'))    

I performed a simple test and this seems to work. Does it help in your case?

For more 'traditional' import ways: https://stackoverflow.com/a/20749411/5172579

For the relation of Python2's execfile() and Python3's exec(): https://stackoverflow.com/a/6357418/5172579

p.s. as noted in the comment: Cyclic imports should be avoided in general and can lead easily to infinite import recursions.

Floyd4K
  • 96
  • 4