I am currently doing manual python code refactoring.
In order to be sure that I break nothing in the original code by forgetting to correct the instructions I enclose within functions, I want to be sure that the function can have no access to the global variables when I am testing them. What would be the right way to do this, except copying them in a separate module?
Edit:
Just to be clear: I am trying to convert my initial code into something like this:
def big_function(args):
def one_small_transformation(args):
# No one else needs to see this transformation outside the function1
def second_small_transformation(args):
...
# Block of instructions chaining small transformations
# Other big functions and code making them work together
Sometimes I forget to correct the variable names in my small transforms and code inside small transformations call variables from the large block of instructions.
Unittests: The unittests for big_function are passed; errors pop in when I start editing the code after refactoring. On the current stage of the project, writing unittests for the small transformations looks like an overkill, because they will be completely re-written once the internal logic of the big_function is clear.
You may find it advantages to first place all global variables into a singleton (global) object. This makes any use of the globals extremely obvious, aiding you down the road as you aim to reduce/eliminate them.
So, take global declarations in a module like
dir_root = "/example/rootdir"
debug_level = 3
and wrap them in a class with a single declared instance:
class GLOBALS:
dir_root = ...
debug_level = ...
Globals = GLOBALS()
Of course, existing references to the variables will have to be updated to use e.g. Globals.dir_root
instead of dir_root
directly.
The benefit of doing this is that it allows you to highlight the usage of globals while keeping application logic intact. This lets you do the refactoring in a more incremental manner that is less apt to introduce new logic errors. And as per your original question, you can be sure that any function that doesn't reference the Globals
object explicitly is not using any global variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With