【问题标题】:Deprecate import from a.py when Class changed from a.py to b.py当 Class 从 a.py 更改为 b.py 时,不推荐从 a.py 导入
【发布时间】:2021-06-04 12:25:40
【问题描述】:

我在 a.py 中有一个“模型”类,现在该类已移至 b.py。因此,每当最终用户从导入模型中使用时,我都想通过弃用或一些警告消息。知道该怎么做吗?

【问题讨论】:

    标签: python deprecated deprecation-warning


    【解决方案1】:

    您应该使用警告 (https://docs.python.org/3/library/warnings.html),更特别的是 DeprecationWarning (https://docs.python.org/3/library/exceptions.html#DeprecationWarning)

    这里已经有一个很好的答案:How to warn about class (name) deprecation

    【讨论】:

    • 感谢您的回答。如果我移动了一组课程怎么办?我需要创建所有方法吗?
    【解决方案2】:

    我想出了这个简单的解决方案:

    class Model:
        def __init__(self):
            # prints a warning message in the console
            print('The "Model" class has been moved to b.py, please consider modifying your code !')
    
    m = Model() # instantiate the model class to throw the message
    

    这应该像你预期的那样工作 编辑:这是 a.py 的代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-18
      • 2022-12-06
      • 2020-10-01
      • 2018-05-31
      • 1970-01-01
      • 2016-03-01
      • 1970-01-01
      • 2021-05-28
      相关资源
      最近更新 更多