John John - 1 year ago 110
Python Question

Importing modules in Python - best practice

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.


I found this excellent guide. It explains everything.

Answer Source

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download