Python Forum
import libraries from another script
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
import libraries from another script
#1
I have made a script names libraries.py in which i have written
import datetime as dt
import numpy as np
from netCDF4 import Dataset
import matplotlib as plt
import matplotlib.pyplot as plt
I want to call this script from another script, just to get rid of typing these everytime.
In my second script names script.py, I have written

import libraries
xvals = np.arange(-2, 1, 0.01)
While compiling the second script using python script.py, it is showing error.
The commands in the libraries is compiling well but why can not I use those imported libraries in another function.
Reply
#2
The import in libraries.py are importing those packages into the libraries module's name space. To access them after importing libraries, you need to access them from that name space:

xvals = libraries.np.arange(-2, 1, 0.01)
Alternatively, you could star import them, which dumps everything from the libraries name space into the current name space:

from libraries import *
xvals = np.arange(-2, 1, 0.01)
However, this is not recommended. Star imports are opaque as to what they are importing into the current name space, which can cause name conflicts.

Frankly, the correct way to deal with this issue is to just copy and paste those imports to the top of new files. It's actually probably easier than typing "from libraries import *".
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
(Jun-29-2018, 11:29 AM)ichabod801 Wrote: Frankly, the correct way to deal with this issue is to just copy and paste those imports to the top of new files. It's actually probably easier than typing "from libraries import *".
changes out of your control

Not just easier - transient imports should not be relied upon. Someone may change the imports in the module you are importing from - and you, all of a sudden, get an error.

The interpreter does not import objects already in memory, so that there's no impact on memory/performance if you re-import APIs - but your code have better chance of surviving
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020