Good evening. There is a class (mongoengine):

class BaseMetaDocument(Document): unit = StringField(..., readonly = True) name = StringField(..., readonly = False) active = BooleanField(...) 

Not all attributes have a readonly property defined, so when outputting to a form I use the code:

  ... try: readonly = v.readonly except: readonly = False info = dict(..., readonly = readonly) return info 

Question: can you somehow write "in one line"?

    2 answers 2

    Yes, you can use the getattr () function:

     readonly = getattr(v, 'readonly', False) 

      There is a built-in function to check for the presence of a field / method: hasattr .

        if hasattr(a, 'property'): a.property` 

      https://stackoverflow.com/questions/610883/how-to-know-if-an-object-has-an-attribute-in-python