Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to forbid a python function to use any variable except local ones?

Tags:

python

scope

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.

like image 464
chiffa Avatar asked Nov 02 '22 08:11

chiffa


1 Answers

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.

like image 85
Myk Willis Avatar answered Nov 09 '22 11:11

Myk Willis