I am quite new to writing modules in Python.
I use Python 3.5
I have a script called describeToolbox.py that contain functions that I would like to be able to call, like this one:
#describeToolbox.py
import shelve
def getRawData(prefix):
shelfFile = shelve.open('data'+prefix)
df = shelfFile['data'+prefix]
shelfFile.close()
return df
This is meant to retrieve a dataFrame from a shelve file
In my console now, I write the following statements:
In [7]:import shelve
import describeToolbox as TB
In [8]:TB.getRawData('Myprefix')
Out [8]:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-9-67160af666cc> in <module>()
----> 1 TB.getRawData('Myprefix')
C:\Users\Math\Documents\Docs\Commos\Notebooks\describeToolbox.py in getRawData(prefix)
1 def getRawData(prefix):
----> 2 shelfFile = shelve.open('data'+prefix)
3 df = shelfFile['data'+prefix]
4 shelfFile.close()
5 return df
NameError: name 'shelve' is not defined
It gives me an error message saying that the module 'shelve', the dependency, is not defined.
Basically I dont know where is the correct place to import all the dependencies so that my function can load them when I want to import it.
I would like to write a depository of functions I use often in one module and call them when needed.
Thank you for your help!
Related
Problem
I would like to import a script containing many functions and then run them, so that I can use the function. I may have misunderstood the purpose of import. I am working in Jupyter.
Reprex
#Create the script in a local folder
%%writefile test.py
c = 500
def addup(a,b,c):
return a*b + (c)
#import the file and use it
import test
addup(1,5,c)
#Error message
---------------------------------------------------------------------------
# NameError Traceback (most recent call last)
# <ipython-input-1-71cb0c70c39d> in <module>
# 1 import test
# ----> 2 addup(1,5,c)
# NameError: name 'addup' is not defined
Any help appreciated.
You have not called the function! You need a dot . to call a function from a module.
This is the correct syntax:
import test
result = test.addup(1,5,c)
Import a specific function:
from test import addup
addup(1,5,c)
Importing all of the module's functions:
from test import *
addup(1,5,c) # this way you can use any function from test.py without the need to put a dot
I'm using Python since few days and I'm trying to learn as much as possible from it. I'm using Jupyter notebook as well. I made a python file fibo.py where I code a function fib and I saved it. In the same folder I try to import that module and use the function fib
import pandas as pd
import numpy as np
import fibo
result = fibo.fib(10)
but I get the following error message :
AttributeError: module 'fibo' has no attribute 'fib'
Could you please give me some suggestions where the problem should be? Thank you in advance.
This is the code for fibo.py
# Fibonacci numbers module\n",
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
The error I get is here:
AttributeError Traceback (most recent call last)
<ipython-input-1-73202afd3146> in <module>
3
4 import fibo
----> 5 result = fibo.fib(10)
AttributeError: module 'fibo' has no attribute 'fib'
I tried also
from fibo import fib
And I get the following:
ImportError Traceback (most recent call last)
<ipython-input-2-b2d78eaf1dcb> in <module>
4 import fibo
5 #result = fibo.fib(10)
----> 6 from fibo import fib
ImportError: cannot import name 'fib' from 'fibo' (C:\Users\my_folder\Documents\JupyterWork\fibo.py)
Save the file as .py using any text editor other than jupyter notebook.
Because jupyter notebook file are stored in JSON format.
I have files with functions saved locally that I want to load. However, when I do this, its not picking up already loaded loaded packages such as pandas.
import pandas as pd
import numpy as np
x=pd.DataFrame({"a":[1,2,3]})
This function is saved locally to a test_function.py file...it isn't run in my jupter notebook directly.
# saved on file locally...
def multiply_values(data):
if data.__class__ == pd.DataFrame():
return(x.iloc[:,0]*2)
Load the function...
from test_function import *
multiply_values(x)
I then get
NameError: name 'pd' is not defined
Can someone explain to me how I should be handling this? How am I not importing this correctly?
I also updated the test_function.py file to have
import pandas as pd as the very first line & within the function itself.
I get this response:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-75-00666e9e2407> in <module>
1 xx = pd.DataFrame({'a':[0,23,234,3]})
2
----> 3 multiply_values(xx)
~/Downloads/testfunc.py in multiply_values(data)
1 import pandas as pd
2
----> 3
4 def multiply_values(data):
5 import pandas as pd
NameError: name 'pd' is not defined
I successfully downloaded tweets into a json file. Now I try to import it in a database with this function:
def import_json(fi):
logging.warning("Loading tweets from json file {0}".format(fi))
for line in open(fi, "rb"):
data = json.loads(line.decode('utf-8'))
database.create_tweet_from_dict(data)
the json-file "keywords_BVBS04.json" lays in a folder called data which is in the current directory. The function is in a file called BVBS04.py
to start the import I type BVBS04.import_json(keywords_BVBS04.json) in ipython in the console. this is what I get back:
NameError Traceback (most recent call
last) in ()
----> 1 BVBS04.import_json(keywords_BVBS04.json)
NameError: name 'keywords_BVBS04' is not defined
Now here comes the is a beginner's question: Where/how do I have to define "keywords_BVBS04"? I tried a lot :(
Thanks!
This is what you want,
1) you need to import the function from the script, not use dot-notation on the script.
2) Quote the filename.
>>> from BVBS04 import import_json
>>> import_json("keywords_BVBS04.json")
Good luck with the rest of things
Hi I'm having trouble importing classes and variables into python files from other python files. Functions work fine.
As a test, I set up file1 with a function, a class, an assigned instance of the class, and a random variable. I then used various methods in file2:
1.
import file1
2.
from file1 import *
error: 'name not defined'
3.
from file1 import variable,class,instance,etc
error: cannot import name Class
4+. And then doing some other things...
creating a init.py file
or then trying to set directory:
import os
os.chdir("/Users/mardersteina/Documents")
Not sure what I'm doing wrong. Function imports fine, but can't figure this one out with the classes and variables no matter what I'm looking up.
Untitled7:
def happy():
print "yo!"
class Tap(object):
def __init__(self,level):
self.level = level
level4 = Tap(4)
x = 14
Untitled9:
%run "/Users/mardersteina/Documents/Untitled9.py"
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/Users/mardersteina/Documents/Untitled9.py in <module>()
1 import Untitled7
2
----> 3 print Untitled7.x
4 """
5 from Untitled7 import Tap
AttributeError: 'module' object has no attribute 'x'
%run "/Users/mardersteina/Documents/Untitled9.py"
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
/Users/mardersteina/Documents/Untitled9.py in <module>()
4 print Untitled7.x
5 """
----> 6 from Untitled7 import Tap
7
8 print Tap(4).level
ImportError: cannot import name Tap
%run "/Users/mardersteina/Documents/Untitled9.py"
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
/Users/mardersteina/Documents/Untitled9.py in <module>()
11 from Untitled7 import *
12
---> 13 print level4.level
NameError: name 'level4' is not defined
I can see that you are running the file from an open console .
Most probably the issue is that you had imported the Untitled7.py previously when it only had one function . When you do that Python caches the module in sys.modules .
So if you try to import it in same session again, you would get the cached version from sys.modules , and that would be the reason any changes to the Untitled7 you did after importing it once are not visible.
To fix this issue, you can reload the module -
In Python 3.x , use importlib.reload() to reload the module (to take in new changes) , Example -
import importlib
importlib.reload(Untitled7)
In Python 2.x , use reload() method -
reload(Untitled7)
Or you can also close the python terminal and reopen it, and it should fix the issue.