Gayan Jeewantha
Gayan Jeewantha

Reputation: 335

python variable assignment with ":"

enter image description here

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'))

Upvotes: 2

Views: 74

Answers (1)

mahoriR
mahoriR

Reputation: 4597

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.

Upvotes: 3

Related Questions