Jadzia Jadzia - 14 days ago 5
Python Question

Python property with getters and setters

I am new to Python.

I want to have a class called "Verbosity". It is intended for controlling the amount of printed output of my new Python program.

The verbosity should be constant while my program is running, thus I was intending to initialize the Verbosity object with the level of the desired verbosity. Lets call an instance of this object "verb".

While my program is running, I frequently want to check the verbosity so that the program knows when to print output or not. Thus I want to call verb.high, verb.low, and so on and get back true or false.

Here is some sample code (based on some code in some package I found), but it doesn't work yet in my program:

VERB_QUIET = 0
VERB_LOW = 1
VERB_MEDIUM = 2
VERB_HIGH = 3
VERB_DEBUG = 4

class Verbosity(object):
"""Class used to determine what to print to standard output.

Attributes:
level: Determines what level of output to print.
"""
value = "low"

def __init__(self, new_value="low"):

self.level = new_value

def __getattr__(self, name):
"""Determines whether a certain verbosity level is
less than or greater than the stored value.

Args:
name: The verbosity level at which the info/warning string
will be output.
"""

if name is "quiet":
return self.level >= VERB_QUIET
elif name is "low":
return self.level >= VERB_LOW
elif name is "medium":
return self.level >= VERB_MEDIUM
elif name is "high":
return self.level >= VERB_HIGH
elif name is "debug":
return self.level >= VERB_DEBUG

def __setattr__(self, name, value):
"""Sets the verbosity level

Args:
name: The name of what to set. Should always be 'level'.
value: The value to set the verbosity to.

Raises:
ValueError: Raised if either the name or the level is not
a valid option.
"""

if name == "level":
if value == "quiet":
level = VERB_QUIET
elif value == "low":
level = VERB_LOW
elif value == "medium":
level = VERB_MEDIUM
elif value == "high":
level = VERB_HIGH
elif value == "debug":
level = VERB_DEBUG
else:
raise ValueError("Invalid verbosity level " + str(value) + " specified.")
super(Verbosity, self).__setattr__("level", level)


If you have a better approach, I would be glad to hear that. Still I would also be interested on how to get the above approach working.

Answer

Please see the Python in-built logging module. There's no need to re-invent the wheel.

Here's a sample from the docs:

import logging
logging.warning('Watch out!')  # will print a message to the console
logging.info('I told you so')  # will not print anything

If you want to set the logging level so that INFO + higher priority messages are printed:

logging.getLogger().setLevel(logging.INFO)

I also recommend sticking with the default logging levels listed here:

enter image description here

Comments