"from module import data; print(data)" vs "import module; print(module.data)"

Dan Stromberg drsalists at gmail.com
Thu Feb 25 11:20:59 EST 2016


On Thu, Feb 25, 2016 at 8:15 AM, Dan Stromberg <drsalists at gmail.com> wrote:
> On Wed, Feb 24, 2016 at 7:39 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> On Thursday 25 February 2016 12:07, Dan Stromberg wrote:
>>
>>> Could people please compare and contrast the two ways of doing imports
>>> in the Subject line?
>>
>> from module import data; print(data)
>>
>> import module; print(module.data)
>
>>> Is it fair to say that the former increases the surface area of your
>>> shared (sometimes mutable) state?
>>
>> No, I can't say that it is. If anything, the opposite is the case: it
>> decreases the surface area, because `data` now is local to the importing
>> (not imported) module. Rebinding data will not affect anything else.
>
>> There are two scenarios (`from module import...` versus `import ...`), each
>> with two cases: mutation, and rebinding:
>>
>> (1) from module import data
>>
>> (a) Mutation (only applies to mutable data like lists, dicts etc)
>>
>> In place mutation affects everything relying on module.data regardless of
>> how or where it is accessed.
>
> We have some scenarios where "data" is an instance of a class, and we
> need to monkey patch it for unit testing.
>
> Please ignore: My intuition is telling me that "module.data; data.mutate()" would be
> easier to monkey patch in a way that all modules will see.  Is that
> fair to say?
>
> Thanks.

Correction!
My intuition is telling me that "module.data; module.data.mutate()"
would be easier to monkey patch in a way that all modules will see.
Is that fair to say?



More information about the Python-list mailing list