简体   繁体   中英

python variable assignment with “:”

在此处输入图像描述

def unexpected_exceptions(exctype, value, tb):
    exception = ''.join(traceback.format_exception(exctype, value, tb))
    _logger = logging.getLogger('unexpected_exceptions')
    _logger.setLevel(logging.DEBUG)

    f_handler: FileHandler = logging.FileHandler(os.path.join(BASE_PATH, 'log ' + CURRENT_VERSION + '.log'))

    f_handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s'))
    _logger.addHandler(f_handler)
    _logger.exception(exception, exc_info=True)
    f_handler.close()
    _logger.removeHandler(f_handler)
    print(value)

sry i cound't find any article about this

what is this variable assignment?

f_handler: FileHandler = logging.FileHandler(os.path.join(BASE_PATH, 'log ' + CURRENT_VERSION + '.log'))

The syntax is for type hint/annotation introduced in python 3.5

This is used by tools to provide better hints, static checks etc. Note, this does not alter behaviour of python at all and is only a feature to help tools to provide additional support.

In the case you provided:

t:str=1

t is hinted to be a variable of type str . This shall allow your IDE to provide str methods on t when you press . !

This is the standard example from pydocs for type hints -

The function below takes and returns a string and is annotated as follows:

def greeting(name: str) -> str:
    return 'Hello ' + name

In the function greeting, the argument name is expected to be of type str and the return type str. Subtypes are accepted as arguments.

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