ruskin
ruskin

Reputation: 479

Does this code follow Python coding standards\style and idioms?

I have written this code in log.py.

import logging
import os


# make directory
directory = 'logs'
if not os.path.exists(directory):
  os.makedirs(directory)

# create logger
logger = logging.getLogger('testfile')
logger.setLevel(logging.DEBUG)


loghandler = logging.FileHandler(directory + '\log.txt')

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to loghandler
loghandler.setFormatter(formatter)

# add loghandler to logger
logger.addHandler(loghandler)

Now, user can use this in any module like

import log
log.logger.warn("gjh")

Upvotes: 0

Views: 170

Answers (3)

6502
6502

Reputation: 114461

I see a couple of problems

  1. Apparently you are indenting using two spaces and this is a crime in Python
  2. You are using '\log.txt' that works just because a lowercase L has no special meaning as a control character. Better to use the os-specific path construction function instead (see os.path.join)

Upvotes: 2

dubbaluga
dubbaluga

Reputation: 2343

regarding the coding style I would recommend to use dedicated tools. There have been some posts before, for example this one: PyLint, PyChecker or PyFlakes?

Personally I prefer to use pylint with a configuration file adapted to some things that I want to be followed in my projects (e. g. special variable names). If you want to have a quick look, try pep8.

Best regards, Rainer

Upvotes: 1

Eli Bendersky
Eli Bendersky

Reputation: 273366

You're creating a whole module for a single global object. If you want to save code, just have a function that creates it:

def make_logger():
  logger = logging.getLogger('testfile')
  # initializations...
  # ...
  return logger

logger = make_logger()
logger.warn('ghj')

With keyword arguments and default values, you can also easily customize its creation if such a need arises (and it probably will arise as your program gets more complex).

Upvotes: 3

Related Questions