0

When doing oop in python where should I add the logger.

Should I add it:

  • before the class Rocket(): and give it a file global scope or
  • after the class Rocket():  and give it a class scope.

Syntax allows for both. But which would be consider more correct in the python culture.

Assume I have a class

class Rocket():
# Rocket simulates a rocket ship for a game,
#  or a physics simulation.

def __init__(self):
    # Each rocket has an (x,y) position.
    self.x = 0
    self.y = 0


def move_up(self):
    # Increment the y-position of the rocket.
    self.y += 1
  • 1
    Logging is an area that bends the rules quite a bit. – whatsisname Jul 11 '18 at 0:54
0

This doesn't matter very much. Logging is largely orthogonal to the design of your code, so it doesn't always clearly belong to a particular class or module.

However, many logging frameworks allow you to filter by the logger name, where this logger name is typically the fully qualified name of a class or module. In that case, think about whether you would only filter for that module or also for that particular class. Per-class loggers might also be more appropriate if you want inherited classes to use the same logger, but I would find that unusual.

In Python, it is typically more convenient to use module-level global variables instead of class-variables because of the scoping rules. E.g. in your methods you would have to access a class member as Rocket.LOGGER, whereas LOGGER would refer to a module-level variable. Also, class level variables are visible as instance variables. E.g. we could then access some_rocket.LOGGER. It is of course possible to make the logger pseudo-private by giving it a double-underscore name, but where possible the better approach is to avoid objects/classes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.