-1

Basically I have a Python With function that does a site login. Everything else I do needs to fall under a With function, so I can continue having the site connection.

As you guessed, I have multiple functions that needing to start with a With function. It gets really redundant. But if I just do a normal function wrap, I would lose the site connection.

I need to figure out a way to proper wrap a With function.

toadead
  • 1,038
  • 16
  • 29

1 Answers1

1

I figured out the answer. It's the Python decorator I'm looking for.

def authenticate(f):
    @wraps(f)
    def wrapper(self, *args, **kwargs):
        self.site_url = kwargs.get('site_url', '')
        with self.sign_in(MY_TOKEN):
            # initiate server details here
            f(self, *args, **kwargs)
    return wrapper

Then in my actual function that need the With first, I do:

@authenticate
def my_func(site_url=''):
    # details of my_func

Be aware site_url is my keyword argument.

toadead
  • 1,038
  • 16
  • 29