Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

python - Printing message when class variable is called

I'm using a 2 python class as configuration file. One of them contain old parameters (deprecated) and I would like to display a message if a deprecated param is used.

Here is how I used the different class:

config_backup.py

class _ConfigBackup:
    PARAM1 = 'a'
    PARAM2 = 'b'

config_new.py

class Config(_ConfigBackup):
    PARAM3 = 'c'
    PARAM4 = 'd'

cfg = Config

Then I can call cfg and have result like this:

>>> cfg.PARAM3
'c'
>>> cfg.PARAM1
Parameter PARAM1 is deprecated.
'a'

The function or method would look like this I think:

def warning(param):
    print(f"Parameter {param.__name__} is deprecated.")
    return param

I am not exactly sure if this is possible, maybe by using decorator or with statement, any idea ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a proof-of-concept solution that meets the objection of having too many properties to be workable.

class Config:
    def __init__(self):
        self.deprecated = {'PARAM1': 'a', 'PARAM2': 'b'}
        self.nondeprecated = {'PARAM3': 'c', 'PARAM4': 'd'}
    def __getattr__(self, parmname):
        if parmname in self.__dict__["deprecated"]:
            print(f"{parmname} is deprecated")
            return self.__dict__["deprecated"][parmname]
        return self.__dict__["nondeprecated"][parmname]

>>> c = Config()
>>> c.PARAM1
PARAM1 is deprecated
'a'
>>> c.PARAM2
PARAM2 is deprecated
'b'
>>> c.PARAM3
'c'

I didn't put the deprecated parameters in a separate class because that would complicate the example unnecessarily. And real-world code would need to be able to cope with attempts to name a nonexistent parameter, and not do this:

>>> c.PARAM5
Traceback (most recent call last):
  File "<pyshell#105>", line 1, in <module>
    c.PARAM5
  File "<pyshell#100>", line 9, in __getattr__
    return self.__dict__["nondeprecated"][parmname]
KeyError: 'PARAM5'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...