2

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
Billal BEGUERADJ
1,3855 gold badges17 silver badges34 bronze badges
asked Jul 11, 2018 at 0:39
1
  • 1
    Logging is an area that bends the rules quite a bit. Commented Jul 11, 2018 at 0:54

1 Answer 1

2

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.

answered Jul 14, 2018 at 11:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.