How can I run a script after importing it? - python

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

Related

How to import a python function from a sibling folder

This question has been asked before. Even though I couldn't get an answer that solves this issue.
I have the following directory and subdirectories:
I have a function hello() in test1.py that I want to import in test2.py.
test1.py:
def hello():
print("hello")
test2.py:
import demoA.test1 as test1
test1.hello()
Output:
Traceback (most recent call last):
File "c:/Users/hasli/Documents/Projects/test/demoB/test2.py", line 1, in <module>
import demoA.test1 as test1
ModuleNotFoundError: No module named 'demoA'
This is exactly as explained in https://www.freecodecamp.org/news/module-not-found-error-in-python-solved/ but I can't access hello()
I am using python 3: Python 3.8.9
You need to add demoA to the list of paths used for import.
import sys
sys.path.append('..')
import demoA.test1 as test1
test1.hello()

Python: Function: not recognizing dependencies

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!

Importing Classes & Variables in Python 2.7

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.

Ipython notebook : Name error for Imported script function

I have two scripts sources.py and nest.py. They are something like this
sources.py
import numpy as np
from nest import *
def make_source():
#rest of the code
def detect():
Nest = nest()
Nest.fit()
if __name__=='main':
detect()
nest.py
import numpy as np
from sources import *
class nest(object):
def _init_(self):
self.source = make_source()
def fit(self):
#rest of the code
When I run the script like python sources.py It works fine.
But in the Ipython notebook environment if I do the following
In [1]: from sources import *
In [2]: detect()
I am getting the following error
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-5-e9c378341590> in <module>()
----> detect()
C:\sources.pyc in detect()
--> 7 Nest = nest()
C:\nest.pyc in _init_()
--> 7 self.source = make_source()
NameError: global name 'make_source' is not defined
I am confused about why this is occurring. Can you give me an insight on how it is different in both cases and how to solve this ?
The thing is that there is a difference between
import something
and
from something import *
concerning namespaces.
If you have recursive imports its better to never do "from something import *" or "import something as someotherthing"
You get a full explanation here:
Circular (or cyclic) imports in Python

Multiple modules , single instance of a class - Python

I have two modules misc.py and main.py and would like to define all classes present in misc.py in main.py.
Below is the code
#misc.py
class dummy:
def __init__(self):
pass
def dummyPrint(self):
print "Welcome to python"
#main.py
import misc
dummyObj = dummy()
dummyObj.dummyPrint()
Is this the right way to go ? I do not see any output i.e., Welcome to python
$python misc_main.py misc.py
EDIT: I added the statement from misc import dummy and i am getting the following error
$python misc_main.py main.py
Traceback (most recent call last):
File "misc_main.py", line 5, in <module>
dummyObj = dummmy()
NameError: name 'dummmy' is not defined
When you do the following command, you are calling misc_main.py from the interpreter with misc.py as an argument.
python misc_main.py misc.py
Since misc_main is not reading command line arguments, this is equivalent to
python misc_main.py
I am surprised that you do not get errors, in either case. You need to import the actual class if you want to get output.
from misc import dummy
dummyObj = dummy()
dummyObj.dummyPrint()
Note, I am assuming your main file is actually in called misc_main.py rather than main.py as you have stated in your question. Otherwise you are not invoking the correct file.

Categories

Resources