Вопрос

I'm writing an API and I have used some managed attributes because they are retrieved from network, therefore it may generate errors.

Inside the getter-setter I want to check if API user have used a try clause around the attribute get/set.

def getter_or_setter():
    try:
        network_operations()
    except:
        if called_inside_try():
            raise
        else:
            log.error('error string')
Это было полезно?

Решение

First thing: I don't have an answer to your question, and have no idea if it's actually possible to determine if your function is called from a try block :)

That being said, what I'm sure of however, is that it is a weird thing to do. You should leave the decision to raise an exception or fail silently to the caller based either on an explicit parameter or an alternative way of calling your function.

As an example, I believe you should consider how dict handles missing keys:

  • When using d['missing'], the dict raises a KeyError
  • The caller can choose to use d.get('missing') to avoid an exception.
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top