Jadzia Jadzia - 1 year ago 80
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:


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

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.

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

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

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":
elif value == "high":
level = VERB_HIGH
elif value == "debug":
level = VERB_DEBUG
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 Source

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:


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

enter image description here

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