Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's possible in a sense; it depends on what exactly you mean. Decorator syntax like this...</p> <pre><code>@dec def foo(): pass </code></pre> <p>is really just sugar for this:</p> <pre><code>def foo(): pass foo = dec(foo) </code></pre> <p>So there's nothing to stop you from using a decorator on a predefined function in the global namespace. </p> <pre><code>func = dec(func) </code></pre> <p>But the methods of built-in classes live in the namespace of that class, and that namespace can't be modified directly, as <a href="https://stackoverflow.com/a/12476484/577088">chepner</a> has already pointed out. That's a good thing, because it ensures that objects of type <code>str</code> will behave as expected! However, you could <em>subclass</em> str and decorate the method that way. (The below works in Python 2; in Python 3, pass the output of <code>filter</code> to a list. <code>super</code> also may work a little differently; I'll post a Python 3 update in the future.)</p> <pre><code>&gt;&gt;&gt; def remove_empty(fn): ... def filtered(*args, **kwargs): ... return filter(lambda x: x != '', fn(*args, **kwargs)) ... return filtered ... &gt;&gt;&gt; class WeirdString(str): ... @remove_empty ... def split(self, *args, **kwargs): ... return super(WeirdString, self).split(*args, **kwargs) ... &gt;&gt;&gt; 'This decorator is unnecessary\n\n\n'.split('\n') ['This decorator is unnecessary', '', '', ''] &gt;&gt;&gt; WeirdString('This decorator is unnecessary\n\n\n').split('\n') ['This decorator is unnecessary'] </code></pre> <p>Or more directly (and so more in the spirit of decorator use):</p> <pre><code>&gt;&gt;&gt; class WeirdString2(str): ... split = remove_empty(str.split) ... &gt;&gt;&gt; WeirdString2('This decorator is unnecessary\n\n\n').split('\n') ['This decorator is unnecessary'] </code></pre> <p>In the case of this <em>particular</em> example, I'd prefer an explicit filter. But I can imagine, for example, a subclass of a built-in class that does some <a href="http://docs.python.org/dev/library/functools.html#functools.lru_cache" rel="nofollow noreferrer">memoization</a> or something like that.</p>
 

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