noumenal noumenal - 1 year ago 81
Python Question

Debug and Release Build Strategy for Python Projects

I have a piece of software (2100 SLOC) that I consider to run in two different versions: one version provides verbose debug information to the console and the other version is an optimized release version.

My goal is to have a single

branch to maintain. Is there a way to mark the debug parts of the code and signal the Python interpreter to ignore these parts of the code?

Possible applications include: print statements, Python's logging facility, profiling, and assertions [Edit: These are apparently ignored by setting the

Answer Source

I think you are overcomplicating this. You should ideally not have different code paths for development and production environments, just different configuration, otherwise it becomes harder to be sure whether your tests actually reflect how the code will behave when deployed. Things like profiling and debugging the code should be external to that process, things you run on your codebase rather than part of your codebase.

If all you're concerned with is the logging, just set different output levels in different environments. Assuming you have a standard library logging setup, you could do something like:

import logging
import os

    level=getattr(logging, os.getenv('LOG_LEVEL', 'DEBUG')),

in your entry point, this way you could set an explicit LOG_LEVEL environment variable (one of the allowed values) in your production environment, and default to DEBUG for development. Alternatively make the default the production level (e.g. ERROR) and set it explicitly in your development environments. You should then only output messages via logging, and not use print at all.

You should also let the loggers handle any string interpolation, i.e. using:'hello %s', 'world')

rather than:'hello %s' % 'world')  # or'hello {}'.format('world'))

So that if that logging level isn't active it can optimise out the interpolation for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download