2

I have created a Python package, let's call it 'mypackage'. There is a function in that package that does a check depending on a environment variable, and returns a boolean. That function is used in another function. Here is an example :

def check():
    if env_var == "value":
       return True
    return False

# check is used in foo
def foo():
    if check():
        raise PermissionError()
    else:
        return "foo"

My problem here is that the check function can be overwritten just by doing this

import mypackage

def other_func():
    return False

mypackage.check = other_func

How can I prevent a user from doing so, or make the "check" function unmodifiable ?

elj96
  • 53
  • 3
  • Even if you prevent that change, what does block somebody from modifying the `env_var` itself? I think you should use something completely external like an API call to a remote server...than you have control over what's happening, otherwise it sounds like python might not be the best tool for the job. Take a look at this: https://stackoverflow.com/questions/261638/how-do-i-protect-python-code-from-being-read-by-users – Gameplay Feb 02 '23 at 16:05
  • If you are concerned about security, just exposing your package code for import defeats any security measures against overwriting the variable. If someone can read the code, he can change it. Whether directly or by copying and modifying. – matszwecja Feb 02 '23 at 16:06
  • Yes, in Python, your check function can be quite easily modified, unlike other languages that have the `final` keyword (well Python now has the `final` decorator, but that's not going to prevent what you're worried about). You _could_ do some such nonsense with metaclassing to prevent this, but honestly, it'll be more ideal to come to terms with the fact that overriding is a possibility in Python and that it's better to focus your efforts on making sure users of this module don't deliberately override this function. – Jamie.Sgro Feb 02 '23 at 16:11
  • 1
    Two resources to help in your investigation: https://stackoverflow.com/questions/2425656/how-to-prevent-a-function-from-being-overridden-in-python and https://stackoverflow.com/questions/321024/making-functions-non-override-able – Jamie.Sgro Feb 02 '23 at 16:11

0 Answers0