简体   繁体   中英

How to annotate nested dictionary in python 3.6?

I have a dictionary like the following:

OAUTH2_PROVIDER = {
    'SCOPES': {
        'read': 'Read scope',
        'write': 'Write scope',
        'userinfo': 'Access to user info',
        'full-userinfo': 'Access to full user info',
    },
    'DEFAULT_SCOPES': {
        'userinfo'
    },
    'ALLOWED_REDIRECT_URI_SCHEMES': ['http', 'https', 'rutube'],
    'PKCE_REQUIRED': import_string('tools.oauth2.is_pkce_required'),
    'OAUTH2_VALIDATOR_CLASS': 'oauth2.validator.OAuth2WithJwtValidator',
    'REFRESH_TOKEN_EXPIRE_SECONDS': 30 * 24 * 60 * 60,
    "ACCESS_TOKEN_EXPIRE_SECONDS": 3600,
}

And I want to annotate the following key with integer type to check that it's always integer:

'REFRESH_TOKEN_EXPIRE_SECONDS': 30 * 24 * 60 * 60,

as Integer. In python 3.6 we don't have TypedDict. What may I replace it with?

Inside of dictionaries object types are preserved. You can set the type of the value inside of the dictionary (as this value is actually its own object with its own type).

In your example, you can set the type of the value as an int with:

OAUTH2_PROVIDER['REFRESH_TOKEN_EXPIRE_SECONDS']=int(
    OAUTH2_PROVIDER['REFRESH_TOKEN_EXPIRE_SECONDS']
)

print(type(OAUTH2_PROVIDER['REFRESH_TOKEN_EXPIRE_SECONDS'])) #=> <class 'int'>

EDIT: Getting to OP's core issue of removing nested if statements here :

You can simply add a single if statement that forces a int class or raises an error:

REFRESH_TOKEN_EXPIRE_SECONDS = oauth2_settings.REFRESH_TOKEN_EXPIRE_SECONDS
if not isinstance(REFRESH_TOKEN_EXPIRE_SECONDS, int):
    REFRESH_TOKEN_EXPIRE_SECONDS = timedelta(seconds=REFRESH_TOKEN_EXPIRE_SECONDS)
else:
    e = "REFRESH_TOKEN_EXPIRE_SECONDS must be an int"
    raise ImproperlyConfigured(e)
refresh_expire_at = now - REFRESH_TOKEN_EXPIRE_SECONDS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM