Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to handle & return both properties AND functions missing in a Python class using the __getattr__ function?
    primarykey
    data
    text
    <p>It is fairly easy to use the <code>__getattr__</code> special method on Python classes to handle either missing properties or functions, but seemingly not both at the same time.</p> <p>Consider this example which handles any property requested which is not defined explicitly elsewhere in the class...</p> <pre><code>class Props: def __getattr__(self, attr): return 'some_new_value' &gt;&gt;&gt; p = Props() &gt;&gt;&gt; p.prop # Property get handled 'some_new_value' &gt;&gt;&gt; p.func('an_arg', kw='keyword') # Function call NOT handled Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; TypeError: 'str' object is not callable </code></pre> <p>Next, consider this example which handles any function call not defined explicitly elsewhere in the class...</p> <pre><code>class Funcs: def __getattr__(self, attr): def fn(*args, **kwargs): # Do something with the function name and any passed arguments or keywords print attr print args print kwargs return return fn &gt;&gt;&gt; f = Funcs() &gt;&gt;&gt; f.prop # Property get NOT handled &lt;function fn at 0x10df23b90&gt; &gt;&gt;&gt; f.func('an_arg', kw='keyword') # Function call handled func ('an_arg',) {'kw': 'keyword'} </code></pre> <p>The question is how to handle both types of missing attributes in the same <code>__getattr__</code>? How to detect if the attribute requested was in property notation or in method notation with parentheses and return either a value or a function respectively? Essentially I want to handle SOME missing property attributes AND SOME missing function attributes and then resort to default behavior for all the other cases.</p> <p>Advice?</p>
    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.
 

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