[Python-ideas] Mitigating 'self.' Method Pollution
Chris Angelico
rosuav at gmail.com
Sat Jul 11 03:38:04 CEST 2015
On Sat, Jul 11, 2015 at 11:34 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> That would, of course, mean that it's impossible to have a local
> variable with the same name as the declared attribute. I often write
> micro-optimized code like this:
>
> spam = self.spam = {}
> for x in big_loop:
> # avoid the repeated look-ups of ".spam"
> spam[x] = something
>
> If I declared "self spam", this wouldn't work (or rather, it would work,
> but it wouldn't have the effect I am looking for). The solution is
> simple: don't declare "self spam" in this case.
That's not a killer; you'd just have to do something like "_spam =
self.spam = {}", which would have the exact same effect. You
abbreviate "self." to "_" and cache the lookup.
ChrisA
More information about the Python-ideas
mailing list