Check if inline function / class / type / module was overloaded during script?

Question

We get a strange error ** and we suspect that this is because our script.py *** assigned a variable that already has a built in mind. For instance.

str = 2 

Is there any way to check if this happened?


Until

We think this will include:

  • Assign a list at the beginning of the script containing all the built-in object names as strings:

     builtin_names = get_builtin_var_names() # hypothetical function 
  • Assign a list at the end of the script containing all user-assigned object names as strings:

     user_names = get_user_var_names() # hypothetical function 
  • Find the intersection and check if it is empty:

     overwritten_names = list(set(user_names) & set(builtin_names)) if overwritten_names: print("Whoops") 

Similar


** A silent error , for those who are interested in it, it is silent, that is, it ends without an error code, but the value it splashes out differs from the two implementations of the same code, call them A and B ... both versions require execution of two modules (separate files) that we made (changes.py and dnds.py), but while:

  • Version A: includes running changes.py -> intermediate pickle data (in a .p file) -> dnds.py,
  • Version B: includes running changes.py -> returns data (a dict) as arguments dnds.py -> dnds.py.

And for some reason, only version A is the one that has the correct final value (compared to the MATLAB dnds function ).

*** script.py , actually dnds.py (who imported changes.py ). You can find all the code , but to check out the two alternative versions that I talked about ** you need to specifically look at dnds.py , line with: CTRL + F: "#@TODO:Urgent:debug:2016-11-28:" After you find this line, you can read the rest of this line of comments for instructions on how to replicate version B, and its resulting silent error ** . For some reason, I have to sort the data to make it work ... when I just return dicts directly, I get the wrong dN / dS values.

+5
source share
1 answer

You can get the names (and values) of built-in functions through dict __builtins__ . You can get the names (and values) of global variables with globals() and locals with locals() . So you can do something like:

 import __builtin__ name, val = None, None for name, val in locals().iteritems(): if hasattr(__builtin__, name) and getattr(__builtin__, name) != val: print("{} was overwritten!".format(name)) 

and then the same for globals() . This will check if there is any object in the local namespace that has a different value in the builtins namespace. (Setting name and val to None is necessary so that the variables exist before calling locals , otherwise you will get the error "resized word during iteration", because the names are added partially through the loop.)

You can also use a tool like pylint , which checks for such errors among many others.

+3
source

Source: https://habr.com/ru/post/1260420/


All Articles