Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid writing the name of the module all the time when importing a module in python?

I use the math module a lot lately. I don't want to write math.sqrt(x) and math.sin(x) all the time. I would like to shorten it and write sqrt(x) and sin(x). How?

like image 755
snakile Avatar asked Aug 13 '10 11:08

snakile


1 Answers

For longer module names it is common to shorten them, e.g.

import numpy as np

Then you can use the short name. Or you can import the specific stuff that you need, as shown in the other anwsers:

from math import sin, sqrt

This is often used inside packages, for code that is more closely coupled. For libraries the first option with the name shortening is often the prefered way.

What you should never do is use the from math import * form. It will pollute the name space, potentially leading to name collisions and making debugging harder. Most importantly it makes the code hard to read, because it is not clear where a particular function came from.

An exception can be made in the interactive interpreter. But once you are in the habit of using the shortened names it might not be worth to go with another convention there.

like image 186
nikow Avatar answered Nov 14 '22 22:11

nikow