Search code examples
pythonmaya

In my Python script for Maya, I need to check if a Logger argument is being passed in before I instantiate my own. How do I do that?


I am creating a tool for Maya using Python and I need to check if logger is being passed in before I instantiate my own. How would I do that, and do I make a function to deal with the logging specifically? I guess there might be a higher tier one, like the Shotgun Maya one.

# this is a global variable
LOGGER = logging.logger(etc etc)
 
def function(logger=LOGGER):

Solution

  • If I understand correctly what you want to do, the idiom is to assign a falsey value to a keyword argument and proceed to assign either the default (here, the global variable) or what you explicitly passed to the function:

    LOGGER = ... # global instance
    ...
    def f(..., logger=None):
        ...
        logger = logger if logger else LOGGER
        ...
    ...  
    f(...)                              # uses LOGGER
    f(..., logger=logging.logger(...))  # uses new instance
    

    It's important to note that when you say def f(..., var=something) the assignment to var happens at compile time, so if you omit the assignment to the falsey value and directly say def f(..., logger=LOGGER) you have two problems ① if LOGGER is not bound at compile time you will have an error and ② if at runtime you change the global LOGGER your function will continue to use the LOGGER that was defined at compile time.