Search code examples
pythonloggingpython-typing

Type Annotation For a Python Logger


I'm quite new to incorporating type hints in my Python code and often feel that I am on shaky ground while doing so. I have a function that creates and returns a custom logger and I'm wondering if I have hinted at the return type correctly.

import logging

def get_logger(param1: str, ...) -> logging.getLogger:
    logger = logging.getLogger(__name__)
    
    # define format
    # add handlers
   
    return logger 

Is logging.getLogger the correct return type in this case? If not, what is the correct type?


Solution

  • Type hints are supposed to use types. In the case of getLogger() it's logging.Logger:

    import logging
    
    def get_logger(param1: str, ...) -> logging.Logger:
        logger = logging.getLogger(__name__)
        
        # define format
        # add handlers
       
        return logger