dimanche 18 avril 2021

How to define a global function inside a specific context via contextmanager and decorators

I am trying to create global functions that would only be accessible inside a specific context using both context managers and decorators. So far i have been able to implement something that looks like This (i have removed bits of code that are irelevant to the question):

Mod.py

def canUseFooBar(func):
    def wrapper():

       global Foo
       if "Foo" in globals():
          raise ValueError("Error: The user already defined the function Foo")
       else:
          def Foo():
             print("Global function Foo has been called")
       # The rest of the functions would be protected in the same way in order to protect accidental  overrides
       global Section
       @contextmanager
       def Section():

          global Bar
          def Bar():
             print("Global function Bar has been called")
          
          yield None
          del Bar

       func()
       del Foo
       del Section

    return wrapper

UserCode.py

import ModPackage.Mod as MOD

@canUseFooBar
def userFunction_01():
    # The function can use Foo
    # And Bar only inside a "Section"
    MOD.Foo()
    with MOD.Section():
       MOD.Bar()


def userFunction_02():
    # This function cannot use neither, Foo, Section() nor Bar()
    # It would raise a ValueError
    MOD.Foo()
    with MOD.Section():
       MOD.Bar()

This kinda looks like what i am trying to achive, however, what i would really like to do is something that would looke like this to the user:

UserCode.py

#Some import 

@canUseFooBar
def userFunction_01():
    Foo()
    with Section():
       Bar()

I am ok with having some functions in the global namespace because this feature is not designed to be used in a huge project but rather a very small scripting api where the user would only write one function.

Also, ultimately, the user would not even have to bother with decorators and imports as it will be requested from him to give the path to their scripts and the api will automaticaly decorate the functions and create the imports.





Aucun commentaire:

Enregistrer un commentaire