[Tutor] Anti-Patterns in Python Programming

Audrey M Roy audreyr at gmail.com
Mon Jul 14 02:01:03 CEST 2014


On Fri, Jul 11, 2014 at 10:43 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Fri, Jul 11, 2014 at 01:04:59PM -0700, Audrey M Roy wrote:
>> Steven, any chance you could clarify how to interpret that section? I'm
>> assuming it refers to not importing objects that share state across modules?
>
> Importing objects that share state across modules was not the problem
> I was talking about. Let's have two imaginary modules, spam and eggs:
>
> # spam.py
> x = 23
>
>
> # eggs.py
> from spam import x
>
>
> This is perfectly clean: the eggs module reaches into the spam module,
> grabs the current value of x (23), and sticks that value into itself.
> What it's doing may be more clear if we re-write eggs.py in a slightly
> longer way:
>
> import spam
> x = spam.x
> del spam

This was the piece of information that was missing in my head. Thank you. At
first I was surprised to learn that x was rebound in the local namespace. I had
always assumed it worked differently, as some sort of special reference to
the original object rather than a copy.

I tried out several examples locally and played around with "from...import" in
various scenarios. I understand it better now.

If anyone else reading this is struggling to understand "from...import" and
wants my code examples to try out, let me know and I can share them
somewhere. It's just too much code to paste here.

> The common pattern, where you import a function or a class or a
> constant, and it never gets mutated or rebound, is perfectly fine. But
> there are odd gotchas to "from ... import" that may be surprising.
> That's why I think one needs to be cautious about doing "from ...
> import". You need to think about it: are you sharing an object, where
> modifications to the object will be seen across multiple modules? Is it
> intended as a variable or a constant? If you don't think about it, one
> day you'll be bitten.

With this in mind, is the uncommon pattern of using "from...import" to create
a reference to a mutable object in the current namespace okay to use in
some cases?
Or is it bad practice?
I'm not sure whether to think of it as an occasionally-useful feature or as an
avoid-at-all-costs hack.

Steven, thanks so much, this really helped.

Audrey


More information about the Tutor mailing list