Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing modules twice in python with different names

I did import the module with a name, and import it again without a name and both seems to be working fine and gives the same class type.

>>> from collections import Counter as c
>>> c
<class 'collections.Counter'>

>>> from collections import Counter
>>> Counter
<class 'collections.Counter'>

How does that works in python, is that a single object points to the same reference? Also why not that the previous name import got overwritten or removed.

I'm not sure about the terminology as well

like image 846
bhansa Avatar asked Oct 25 '25 14:10

bhansa


1 Answers

Using python 2.7.13:

>>> from collections import Counter as c
>>> c
<class 'collections.Counter'>
>>> from collections import Counter
>>> Counter
<class 'collections.Counter'>
>>> id(c), id(Counter)
(140244739511392, 140244739511392)
>>> id(c) == id(Counter)
True

Yes, c and Counter are the same. Two variables (names) that reference the same object.

like image 70
Rafael Barros Avatar answered Oct 27 '25 05:10

Rafael Barros



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!