Importing modules in Python - best practice

John picture John · Mar 29, 2012 · Viewed 43k times · Source

I am new to Python as I want to expand skills that I learned using R. In R I tend to load a bunch of libraries, sometimes resulting in function name conflicts.

What is best practice in Python. I have seen some specific variations that I do not see a difference between

import pandas, from pandas import *, and from pandas import DataFrame

What are the differences between the first two and should I just import what I need. Also, what would be the worst consequences for someone making small programs to process data and compute simple statistics.

UPDATE

I found this excellent guide. It explains everything.

Answer

Paul picture Paul · Mar 29, 2012

import pandas imports the pandas module under the pandas namespace, so you would need to call objects within pandas using pandas.foo.

from pandas import * imports all objects from the pandas module into your current namespace, so you would call objects within pandas using only foo. Keep in mind this could have unexepcted consequences if there are any naming conflicts between your current namespace and the pandas namespace.

from pandas import DataFrame is the same as above, but only imports DataFrame (instead of everything) into your current namespace.

In my opinion the first is generally best practice, as it keeps the different modules nicely compartmentalized in your code.