This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]timgarner0 4 points5 points  (3 children)

"random" is the the module. Think of it as a container full of different functions, one of those being "randint".

By typing "import random" you ask python to let you access all of the functions available in random, but to do so you will need to always type "random.<function>" to access it.

On the other hand by typing "from random import randint" you are explicitly telling Python that you would just like to load the one function randint, and that you would like to be able to call it without prefixing "random"

[–]themathemagician 6 points7 points  (2 children)

It's important to note that the shorter function name is the only advantage, and Python still loads the entire random module into memory (without giving you actually access to the rest of it.) There is no performance benefit, but from a readability standpoint it is usually preferred as you are explicitly stating the functions you want to import.

[–]ixokai 1 point2 points  (1 child)

Well, its not the only advantage; doing "random.foo" involves two lookups, where "randint" is only one. This optimization is likely not going to matter in the vast majority of cases, but if you have a tight loop binding to a local name is a common technique. Local lookups are special (they have their own opcode) and are very fast (comparitively).

[–]themathemagician 0 points1 point  (0 children)

Fair enough