bhansa
bhansa

Reputation: 7504

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

Upvotes: 4

Views: 1976

Answers (3)

Iceandele
Iceandele

Reputation: 660

If you take a look at the disassembled code, you can see that it does load the same object. (line 2 and line 14)

>>> import dis
>>> codeObj = compile("from collections import Counter as c; from collections import Counter", "foo", "exec")
>>> dis.dis(codeObj)
  1           0 LOAD_CONST               0 (0)
              2 LOAD_CONST               1 (('Counter',))
              4 IMPORT_NAME              0 (collections)
              6 IMPORT_FROM              1 (Counter)
              8 STORE_NAME               2 (c)
             10 POP_TOP
             12 LOAD_CONST               0 (0)
             14 LOAD_CONST               1 (('Counter',))
             16 IMPORT_NAME              0 (collections)
             18 IMPORT_FROM              1 (Counter)
             20 STORE_NAME               1 (Counter)
             22 POP_TOP
             24 LOAD_CONST               2 (None)
             26 RETURN_VALUE

And as others have mentioned, you can use id(c) == id(Counter) or c is Counter to test if they have the same reference.

Upvotes: 1

Raja G
Raja G

Reputation: 6633

As I remember , everything you define in python is an object belongs to a class. And yes if a variable object has assigned some value and if you create another variable with same value then python wont create a new reference for the second variable but it will use first variables reference for second variable as well.

For example:

>>> a=10
>>> id(a)
2001255152
>>> b=20
>>> id(b)
2001255472
>>> c=10
>>> id(c)
2001255152
>>>

I may not explain in much better way but my example does I hope.

Upvotes: 1

Rafael Barros
Rafael Barros

Reputation: 2881

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.

Upvotes: 4

Related Questions