From Script to Reusable Package: Modules, Testing, and Numeric Pitfalls
A runnable script is only the first step toward software that others can install, call, test, and trace. This article explains how to turn a small script into a reusable package by organizing modules around responsibilities, separating public interfaces from implementation details, diagnosing circular and relative-import problems, preserving metadata in decorators, and using tests as repeatable evidence. It also covers type annotations versus runtime validation, numeric modeling for money, approximate comparison and tolerances, special values, dependency and environment reproducibility, and a delivery checklist that links build artifacts to source versions.
1. From “It Runs” to “It Can Be Delivered”
When learning to program, the easiest result to achieve is a script that runs. But when the code must be handed to a colleague, deployed to another machine, or extended continuously, problems tend to appear in clusters:
- It runs locally but fails elsewhere because dependencies are missing.
- Multiple files import one another, and the program starts only after the import order is adjusted.
- A function is changed, but there is no way to tell whether other logic has been affected.
- A calculation looks reasonable on the surface but contains precision or boundary errors.
- A released version has a problem, but the corresponding code state cannot be found.
These symptoms are not merely syntax problems. They indicate that engineering boundaries have not been established. A reliable small package should answer at least four questions: How is the code organized? How is behavior verified? How is the runtime environment reproduced? How is the change history traced?
A useful delivery goal can be defined as follows: install the package in a clean environment, call the public interfaces according to the agreed contract, execute all tests successfully, and be able to trace a build artifact back to its source-code version.
2. Module Decomposition: Organize Around Responsibilities, Not Line Counts
2.1 Every module should have a clear reason to change
Splitting one long file into several short files does not automatically improve maintainability. An effective split should allow different responsibilities to change independently.
For example, a small program that calculates order amounts can be organized as follows:
project-root/├── project-metadata-file├── src/│ └── amount_package/│ ├── __init__.py│ ├── calculation.py│ ├── validation.py│ └── entry.py└── tests/├── test_amount_calculation└── test_input_validation
The calculation module owns calculation rules, the validation module owns input constraints, and the entry module coordinates the execution flow. A calculation function should not also read configuration, emit logs, or connect to external services as a side effect; otherwise, testing a simple rule would involve the entire runtime environment.
A practical rule is this: if two features often change for different reasons, consider separating them. If they jointly maintain the same business constraint, do not force them apart merely to shorten a file.
2.2 Public interfaces and internal implementation should be distinguishable
Users of a package need to know which functions they may call, but they do not need to understand every internal detail. Public interfaces should be as small and stable as possible, while internal helper functions can evolve with the implementation.
For example, expose only “calculate the amount due” as a capability, and complete input checks, discount handling, and rounding internally. In this way, callers do not need to update large amounts of code when the internal algorithm changes.
Interface stability does not mean that an interface can never change. It means that changes must be clearly documented and supported by tests and compatibility decisions.
3. Import Mechanics: Understand Loading to Eliminate Hidden Failures
3.1 Why circular imports can produce “object does not exist”
Suppose module A imports module B at the top level, and module B imports module A at the top level. If A has not yet executed a certain function definition when B tries to access that function, B may receive a module that has not finished initialization.
The core of a circular import problem is therefore not the names of the two files, but a mutual dependency during module loading.
When addressing the problem, first adjust the dependency relationships:
- Extract data structures or rules shared by both sides into a third module.
- Move flow coordination to a higher-level entry point, and let lower-level modules provide only independent capabilities.
- Pass required behavior in as parameters instead of making a lower layer depend on a higher layer.
Delaying an import inside a local function can sometimes avoid an initialization conflict, but it does not necessarily solve the architectural problem. If the dependency direction remains confused, similar failures may occur again during maintenance.
3.2 Relative imports depend on package context
Files inside a package can use relative imports:
from .validation import validate_amount
The dot represents the current package context. If the file is executed directly as an isolated script, the runtime may not be able to determine which package it belongs to and therefore cannot resolve the relative location.
The correct approach is to start the entry point as a module within the package, rather than making an internal implementation file also act as an independent script.
For projects that need multiple invocation methods, design a thin entry point that only reads input, calls the package interface, and returns an exit status. Do not permanently hide package-structure problems by temporarily modifying the search path; that practice tends to produce environment-dependent import results.
3.3 Importing a module should not automatically execute the entire business flow
When a module is imported, its top-level statements usually execute. Top-level code should therefore consist mainly of definitions and necessary lightweight initialization, not immediate data processing.
def main():print("Start processing")if __name__ == "__main__":main()
This structure distinguishes how the module is used: when executed directly as an entry point, it calls the main function; when imported as a dependency, it retains its definitions.
However, this only protects logic inside the conditional block. If statements that read files, make requests, or bulk-write data remain outside the conditional block, importing the module will still cause side effects.
4. Decorators: Preserve Interface Information When Changing Behavior
Decorators are often used to add logging, permission checks, or metrics in a uniform way. The basic approach is to replace the original function with a wrapper function.
The problem is that, after replacement, the exposed function name, documentation, and other information may become that of the wrapper itself. This can affect debug output, API documentation, and mechanisms that rely on function metadata.
When designing decorators, use the standard metadata-preservation mechanism provided by the language, and verify that argument passing, return values, and exception propagation match the original interface contract.
The following schematic structure illustrates the idea:
def decorate(function):def wrapper(*args, **kwargs):return function(*args, **kwargs)# Use the standard metadata-preservation mechanism here.return wrapper
Manually copying the function name is not equivalent to fully preserving the wrapper relationship. In particular, when function signatures need to be analyzed, verify whether the relevant tools can follow the wrapper relationship to the original function.
In addition, exception handling inside decorators must be careful. If a decorator catches every exception, emits a message, and does not propagate the exception, callers may incorrectly believe that the operation succeeded. That behavior breaks the interface semantics.
5. Testing: Turn Requirements into Repeatable Evidence
5.1 Tests should verify contracts, not restate the implementation
If a test simply copies the formula inside a function, both the implementation and the test can be wrong and still pass.
A better approach is to start from business rules and provide inputs and expected outputs that can be judged independently. For amount calculations, tests should cover at least:
- Normal amounts and normal quantities.
- Boundary cases such as zero amount and zero quantity.
- Negative amounts or invalid quantities.
- Whether very large inputs exceed the permitted business range.
- Rounding thresholds.
- Data types that do not conform to the contract.
Assume the interface contract states that amounts are represented in the smallest currency unit and that quantities must be nonnegative integers. The checks can then use explicit integer results:
def total_amount(unit_amount: int, quantity: int) -> int:if type(unit_amount) is not int or type(quantity) is not int:raise TypeError("Amount and quantity must be integers")if unit_amount < 0 or quantity < 0:raise ValueError("Amount and quantity cannot be negative")return unit_amount * quantityassert total_amount(199, 3) == 597assert total_amount(0, 3) == 0assert total_amount(199, 0) == 0
This example uses exact type checks because it explicitly requires excluding inputs such as booleans that do not match the business meaning. A real project should decide, according to its interface contract, whether other integer-compatible types are acceptable.
5.2 Distinguish test assertions from production validation
Assertions are suitable for expressing expectations in tests, but they should not be used as input validation that must always execute in production. Under some optimized execution modes, assertions may be disabled.
Therefore, when external input is invalid, the code should explicitly raise an exception or return an agreed error result, and tests should verify that these behaviors actually occur.
In addition to verifying exception categories, verify whether any side effects that should not have occurred took place before the failure. For example, an invalid order must not be written to a record before the amount format error is reported.
5.3 Passing tests does not prove the absence of defects
Tests can only show that covered scenarios behave as expected. Integration behavior involving file handling, network calls, and external storage also requires corresponding integration verification.
A testing strategy can unfold from the inside out: first verify pure calculation functions, then verify module composition, and finally verify the complete invocation path after installation. This helps identify local errors quickly while also checking whether packaging and the runtime environment have omitted required content.
6. Type Constraints: Catch Interface Misuse Early, but Do Not Replace Runtime Checks
Type annotations make interfaces clearer and help static checks find some errors, such as passing a string to a parameter that requires an integer or calling a method on a result that may be empty.
However, type annotations usually do not automatically perform runtime validation. External files, user input, and network responses may still provide data that does not conform to the annotations.
A layered strategy is therefore necessary:
- Validate and convert external data at input boundaries.
- Use explicit type contracts in internal interfaces.
- Run static checks in the delivery pipeline.
- Use tests to verify business rules that go beyond types.
“Amount is an integer” is a type constraint. “Amount must not be negative” is a value-range constraint. “Discount must not exceed the order amount” is a business constraint. These three must be handled separately; one mechanism cannot be expected to solve all of them.
7. Numeric Pitfalls: Define the Numeric Model Before Implementing Calculations
7.1 Binary floating point is unsuitable for monetary calculations without a deliberate design
Many decimal fractions cannot be represented exactly in a finite number of binary bits. After floating-point calculations, results may therefore differ slightly from the decimal values people expect.
For money, a common approach is to use integers in the smallest currency unit or to use a numeric representation that explicitly supports decimal precision and rounding rules.
Integer representations are not a universal solution. If proportional discounts, tax rates, or exchange rates are involved, it is still necessary to define how intermediate results are handled, when rounding takes place, and whether rounded values participate in later calculations.
7.2 Approximate comparison must match the business scale
For scientific computing or measurement values, directly testing two floating-point numbers for exact equality is usually inappropriate. A common approximate comparison has the following form, for two numbers a and b:
difference <= max(absolute_tolerance,relative_tolerance * max(abs(a), abs(b)))
Absolute tolerance is useful for controlling error near zero, while relative tolerance adapts to different magnitudes. Tolerances must not be chosen arbitrarily; they should come from measurement precision, algorithm error, or an accepted business range.
For monetary settlement, however, “almost equal” should not replace explicit rounding rules.
7.3 Special values and operation order also need testing
Numeric inputs may include non-finite values, zero denominators, or data outside the business range. Some special floating-point values do not follow ordinary numeric comparison intuition, so validity cannot be determined solely by checking whether a value is greater than zero or below a certain upper limit.
In addition, floating-point addition is not strictly associative in the mathematical sense. When aggregating many numbers, different calculation orders may produce different final digits. If the business requires stable output, explicitly define the precision model, the aggregation method, and the rounding stages rather than arbitrarily truncating decimal places at the end.
8. Environment Reproduction and Version History: Close the Reliability Loop
A project should declare runtime dependencies, development dependencies, and supported runtime environments. Runtime dependencies determine whether installed functionality is complete, while development dependencies are used for tasks such as testing, type checking, and building.
Dependency declarations and environment lock files also have different responsibilities: the former describes compatibility ranges, while the latter records a specific dependency combination used for a particular verification. Recording only which components happened to be installed on a local machine does not fully describe what the project actually needs.
Version history should be organized around explainable changes. Each commit should focus on one modification when possible and explain why the modification was made. A code rollback does not mean that business state rolls back automatically; if a change involves external data structures or data migration, compatibility and recovery plans must be designed separately.
Final acceptance should not consist of running tests once in a development directory. It should complete a repeatable delivery chain:
- Build the installable artifact from a specified code version.
- Install the artifact in an isolated environment.
- Validate the public interfaces and startup entry points.
- Run tests and type checks.
- Check for unexpected import side effects.
- Record the version and dependency state corresponding to the artifact.
Moving from a script to a software package adds more than directories, configuration, and commands. It adds a way of working that is explainable, verifiable, and traceable. Module boundaries control dependencies, tests constrain behavior, types describe interfaces, numeric rules preserve calculation semantics, and environment and history records make delivery reproducible. Only when these parts work together does the code truly meet the condition of being safe for others to use.
