[Python-ideas] Decorators for variables

Steven D'Aprano steve at pearwood.info
Sun Apr 3 06:47:53 EDT 2016

On Sun, Apr 03, 2016 at 10:02:55AM +0200, Matthias welp wrote:
> > So is there anything left of the assignment-decorator proposal, or is
> > it completely withdrawn?
> I think this sums the current open ends up:
> - Namespace variables decoration was dismissed by one of Steven's posts,
> but is actually something that might be wanted (via being able to put
> descriptors into namespaces that have a __dict__ accessor (e.g. modules))

It's not that I dismissed the idea, but that such a thing is not 
possible today.

Maybe you could hack up something tricky by replacing the module 
__dict__ with a subclass, or replacing the entire module object with 
some custom class instance, but that's messy and fragile, and I'm not 
sure that it would work for (say) globals inside functions.

I think the idea of "namespace descriptors" is promising. But it 
probably needs a PEP and a significant amount of work to determine what 
actually is possible now and what needs support from the compiler.

> - Variable decoration can be more clear about descriptor/value difference
> at assignment

I'm not sure what you mean by that.

> - Giving property objects access to their variable's name (e.g. via
> __name__) like functions have would open up quite a bit of possibilities,

Such as what?

> and would mean decorators would get quite a bit more power than what they
> have.

What extra power are you thinking of?

> Something that I had said earlier, but what went on a sidepath
> - Decorators may directly *deep* set the behaviour of the variable, and
> with it set the further behaviour of the variable (in the same scope). Such
> that
>     @decorator
>     var = 20
>     var = 40
>     will not reset var to 40, but the var = 40 goes through the descriptor
> (if applied).

This functionality has nothing to do with decorators. If it were 
possible, if namespaces (other than classes) supported descriptors, then 
the decorator syntax doesn't add anything to this. You could write:

var = magic(20)

I'm not calling it "decorator" because the whole @ decorator syntax is 
irrelevant to this.

With respect Matthias, I think you are conflating and mixing up the 
power of descriptors as applied to classes, and the separate and 
distinct powers of decorators. You don't need one to have the other.


More information about the Python-ideas mailing list