Import as an expression that works differently for different modules?
I am learning Python and now I am learning about import statements in Python. I was testing some code and I came across something out of the ordinary. Here is the code I tested.
from math import pow as power
import random as x
print(pow(2, 3))
print(power(2, 3))
print(x.randint(0, 5))
print(random.randint(0, 5))
I found out that in Python you can reassign module names with as
, so I reassigned pow for power. I expected both pow(2, 3)
to and power(2, 3)
output the same, because all I did was change the name. However it pow(2, 3)
outputs 8
which is an integer and power(2, 3)
outputs 8.0
which is a float. Why is this?
Also, I also imported the module random
and set its name x
. In the case of power and capacity, both the old name pow
and the new name worked power
. But with this random module only the new name does not work x
, but the old name random
. print(x.randint(0, 5))
works but random.randint(0, 5)
doesn't work. Why is this so?
Can someone explain to Python newbies like me why my code is not working as I expect? I am using Python version 3.62 if that helps.
source to share
This is because when you import pow
from math as power
, and then you call pow
, the called pow
is inline , not pow
from the math module .
There random
is no built-in function for in python, so you only import x
.
Pow built-in function documentation
source to share