Hugh_Kelley
Hugh_Kelley

Reputation: 1040

Permanently add Libraries in Python

I have this simple piece of code in a file:

frame = DataFrame(np.random.randn(2, 4),
    index=pd.date_range('1/1/2000', periods=2, freq='W-WED'),
    columns=['Colorado', 'Texas', 'New York', 'Ohio'])

When I try to run the file I get error messages telling me that it doesn't know what to do with DataFrame, np, or pd. I can fix this easily by adding in "

from pandas import DataFrame
import numpy as np
import pandas as pd

My question: is there a way that I can avoid having to import these libraries within every file that I want to use those tools?

I had imported them in the command line before running this file but this didn't seem to make a difference.

New to Python. Thanks in advance for the help.

Using Python 2 in the Canopy editor.

Upvotes: 0

Views: 151

Answers (1)

mgilson
mgilson

Reputation: 310079

Generally, if you are going to use a package/module, then you should* import it in every module that needs it. While it might be a little annoying writing the same imports over and over, it's better in the long run because it makes your code a lot more clear. e.g. you know what np or DataFrame is and where it comes from.

I suppose that it's worth noting that you probably can get around this requirement by writing your own import hook, but . . .That's way too complicated a thing to do just to enable you to write code that will likely confuse your co-workers :-)


*There are some conveniences that you can use to get around this in the interactive interpretter, but not in anything that gets imported via the normal mechanisms.

Upvotes: 3

Related Questions