Is there a conflict of libraries here?

Peter J. Holzer hjp-python at hjp.at
Sat Nov 7 14:32:35 EST 2020


On 2020-11-07 13:26:30 -0500, Steve wrote:
> Ok, I think I see a light in the fog.
> 
> It looks as if I can identify a variable to contain a library.
> 
> Import datetime as dt1
> 
> I guess that I can have a second variable containing that same library:
> 
> Import datetime as dt2
> 
> Should I presume that not doing this is what caused the interference in my
> code?

Not quite. The problem isn't that you imported the library twice, but
that you have a library (package/module) and a class of the same name.

When you try to import both with that name, only one of them will be
visible, since you can't have one name refer to two different things at
the same time.

>>> import datetime

The name datetime now refers to the module datetime:

>>> datetime
<module 'datetime' from '/usr/lib/python3.8/datetime.py'>
>>> id(datetime)
140407076788160


>>> from datetime import datetime

Now the name datetime now refers to the class datetime:

>>> datetime
<class 'datetime.datetime'>
>>> id(datetime)
9612160


You can import one or both of them with different names:

>>> import datetime as dt_module
>>> dt_module
<module 'datetime' from '/usr/lib/python3.8/datetime.py'>
>>> id(dt_module)
140407076788160

>>> from datetime import datetime as dt_class
>>> dt_class
<class 'datetime.datetime'>
>>> id(dt_class)
9612160

        hp

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20201107/33e222e5/attachment.sig>


More information about the Python-list mailing list