Falken
Falken

Reputation: 1059

Splitting a Python script in multiple files sharing the same namespace

Similar questions have been asked for other languages (C++, Clojure, TypeScript, maybe others) but I am still looking for an answer for Python.

There are a lot of similar questions related to the use of import and global in Python but the associated answers don't fit my needs. I just want to split a big file into smaller ones to easily modify/reuse parts of the code in different versions of the same program, without having to deal with different namespaces or managing global variables.

A simple hack to do what I want would be to merge selected Python files at runtime with a script but I hope there is a pythonic way of doing that.

With an illustration, what I am trying to do is going from several big files which are almost identical:

big_file_v1.py

## First part
# Hundreds of code lines to define things, make computations...

## Second part
# More code to do a few additional things

big_file_v2.py

## First part
# Exactly the same first part as in big_file_v1.py

## Second part
# A lot of small differences compared to big_file_v1.py

...to several smaller files with most of them not needing any modification or only needing modifications that I want to share across all of the different versions:

myprog_v1.py

include first_part_common_to_both_versions.py

include second_part_v1.py

myprog_v2.py

include first_part_common_to_both_versions.py

include second_part_v2.py

In this second case, using include-like commands, I can instantly share the modifications made in first_part_common_to_both_versions.py across version 1 and 2 of my program and I just need to modify/copy the smaller files second_part_v2.py if I want to make new modifications/create another new version.

The question is: how to do this include in Python?

Just to avoid debates on good software development practices, I use Python as a tool to solve scientific questions and as such, I care more about editing comfort than coding practice.

Upvotes: 1

Views: 1209

Answers (1)

John Richardson
John Richardson

Reputation: 696

Have a look at exec or execfile:

"Python's exec statement is similar to the import statement, with an important difference: The exec statement executes a file in the current namespace. The exec statement doesn't create a new namespace. We'll look at this in the section called “The exec Statement”

Upvotes: 1

Related Questions