Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Below is the hard way. Here's the easy way. Don't know why it didn't occur to me sooner.</p> <pre><code>import inspect def get_user_attributes(cls): boring = dir(type('dummy', (object,), {})) return [item for item in inspect.getmembers(cls) if item[0] not in boring] </code></pre> <hr> <p>Here's a start</p> <pre><code>def get_user_attributes(cls): boring = dir(type('dummy', (object,), {})) attrs = {} bases = reversed(inspect.getmro(cls)) for base in bases: if hasattr(base, '__dict__'): attrs.update(base.__dict__) elif hasattr(base, '__slots__'): if hasattr(base, base.__slots__[0]): # We're dealing with a non-string sequence or one char string for item in base.__slots__: attrs[item] = getattr(base, item) else: # We're dealing with a single identifier as a string attrs[base.__slots__] = getattr(base, base.__slots__) for key in boring: del attrs['key'] # we can be sure it will be present so no need to guard this return attrs </code></pre> <p>This should be fairly robust. Essentially, it works by getting the attributes that are on a default subclass of <code>object</code> to ignore. It then gets the mro of the class that's passed to it and traverses it in reverse order so that subclass keys can overwrite superclass keys. It returns a dictionary of key-value pairs. If you want a list of key, value tuples like in <code>inspect.getmembers</code> then just return either <code>attrs.items()</code> or <code>list(attrs.items())</code> in Python 3.</p> <p>If you don't actually want to traverse the mro and just want attributes defined directly on the subclass then it's easier:</p> <pre><code>def get_user_attributes(cls): boring = dir(type('dummy', (object,), {})) if hasattr(cls, '__dict__'): attrs = cls.__dict__.copy() elif hasattr(cls, '__slots__'): if hasattr(base, base.__slots__[0]): # We're dealing with a non-string sequence or one char string for item in base.__slots__: attrs[item] = getattr(base, item) else: # We're dealing with a single identifier as a string attrs[base.__slots__] = getattr(base, base.__slots__) for key in boring: del attrs['key'] # we can be sure it will be present so no need to guard this return attrs </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload