Измените значение переменной параметра декоратора в python - PullRequest
1 голос
/ 21 марта 2020

У меня есть следующий код, в котором значение «User» по умолчанию равно None, и оно принимается декоратором «need_authentication», дело в том, что я изменяю значение User, но когда я вызываю декоратор, оно всегда получает None. Теперь у меня переменная User не "None", потому что я печатаю ее перед вызовом show_content. Это мой код:

import user

User = None

def login():
    #In this function, I change User value


@user.need_authentication(actual_user=User)
def show_content():
    print('contenido')

login()
show_content():
    print("content")

Это мой декоратор:

def need_authentication(actual_user = None):
    def decorator(func):
        def check_authentication(*args, **kwargs):
            print(app.User)
            print(user)
            if user == None:
                print("lo siento, necesita registrarse para acceder al contenido")
            else:
                func(*args, **kwargs)

        return check_authentication

    return decorator

1 Ответ

0 голосов
/ 21 марта 2020

вы можете использовать диктовку:

actual_user = {'user': None}

def need_authentication(actual_user = actual_user):
    def decorator(func):
        def check_authentication(*args, **kwargs):
            print(app.User)
            user = actual_user[user]
            print(user)
            if user == None:
                print("lo siento, necesita registrarse para acceder al contenido")
            else:
                func(*args, **kwargs)

        return check_authentication

    return decorator
...