I have a file called "Notebook.ipynb". I want to import my own module into it patterns.py. Let's say in patterns.py I have a variable a=1. If I print it in Jupyter after importing it, I expect to get 1. But if I change the value of the variable to patterns.py Jupyter will continue to think that the variable a is equal to one. At the same time, of course, I restart the cell in which the variable is imported from patterns.py
What do I need to do to make Jupyter understand that the value of the variable has changed?
Suppose we have a file at folder_name/filename.py and call it in some .ipynb
def some_func():
print("test")
which was modified like this
def some_func():
print("test2")
In this case, second call of the following code in .ipynb
import folder_name.filename as module_name
module_name.some_func()
returns test
To update the function, you need to reload the module:
importlib.reload(module_name)
# you can reload "folder_name.filename" if you do not use molude name alias
module_name.some_func()
This code will return test2
Don't forget to import importlib before you run reload
This has happened to me.
You need to restart the python kernel so jupyter can read the new state of the python scripts located in the working directory.
Then the variable a should print the new assigned value.
There's actually a nifty IPython extension for this called autoreload. This answer shows how to use it in an IPython shell, but you can do the same in a Jupyter notebook. Just add:
%load_ext autoreload
%autoreload 2
before you import the module whose changes you want to have tracked, and it'll be re-imported before every cell you execute.
Just in addition to #ilia post:
Let's say the module's name is main.py
That's the code I put in the Jupiter's notebook cell, just before calling functions from the main module
import importlib
imported_module = importlib.import_module("main")
importlib.reload(imported_module)
from main import *
Related
I'm currently building an user friendly program in Python. Currently, the user is able to modify the input values provided in an init script that we can call init.py. At this moment the user can open in Spyder, the main.py and run/execute the whole process or just typing the classical command:
python3 main.py
The main.py file import all the variables needed from the init.py and run normally. What I would like to do now is to add a feature which allows the user to change the name of the init.py file. For example to be able to build initcustom.py.
And use the following command :
python3 main.py initcustom.py
How can I be able to import variables in main.py from a script which can change name (that should be provided by the user in the command line)?
And in the case where nothing is specified we keep the classical init.py
What such feature will induce as changes in the case where someone just want to do F5 using Spyder without precising input names?
Thank you in advance for your help
You can probably do something with exec
import sys
exec(‘import’+’sys.argv[2]’)
Why log10() is failing to be recognized when called within a function definition in another script? I'm running Python3 in Anaconda (Jupyter and Spyder).
I've had success with log10() in Jupyter (oddly without even calling "import math"). I've had success with defining functions in a .py file and calling those functions within a separate script. I should be able to perform a simple log10.
I created a new function (in Spyder) and saved it in a file "test_log10.py":
def test_log10(input):
import math
return math.log10(input)
In a separate script (Jupyter notebook) I run :
import test_log10
test_log10.test_log10(10)
I get the following error:
"NameError: name 'log10' is not defined"
What am I missing?
Since I'm not using the environment of Jupyther and alike, I don't know how to correct it in these system, perhaps there is some configuration file over there,check the documentation.
But exactly on the issue, when this happens its because python has not "linked" well something at the import, so I suggest a workaround with the libs in the next way:
import numpy as np
import math
and when you are using functions from math, simply add the np. before, i.e.:
return math.log10(input)
to
return np.math.log10(input)
Exactly I don't know why the mismatch, but this worked for me.
I have a very simple .py file, displayD3caller.py:
def caller():
print("Here is a print statement from displayD3caller.py")
I can import and use the function defined in other files, and from the python shell. However, when I try to import the function in a Jupyter Notebook, it can't find the module:
ImportError: No module named 'displayD3caller'
What can I do to fix this?
Before Jupyter Notebook uses any change to the source code of related files, the kernal needs to be restarted. This includes creating a new file.
If you make a new module after Jupyter is already running, you need to restart the kernal before it will find it. From the top menu, select Kernal > Restart. You will need to re-execute any cells whose outputs you depend on.
Im writing a GUI and I say:
from tkinter import *
Further in the program theres a function wich is:
def nameFunc():
messagebox.showinfo(........)
The problem is that by running the code in the latest Pycharm, it tells me that messagebox is not defined even if I already imported everything from tkinter, it only works if I explicitly say:
from tkinter import messagebox
This only occurs when I run the code on Pycharm, in the standard python IDLE its fine.
Why?
PyCharm is behaving exactly as it should, if you take a look at the documentation on packages:
what happens when the user writes from sound.effects import *? Ideally, one would hope that this somehow goes out to the filesystem, finds which submodules are present in the package, and imports them all. This could take a long time and importing sub-modules might have unwanted side-effects that should only happen when the sub-module is explicitly imported.
The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered.
tkinter does not define a __all__ to automatically import submodules and you should be glad it doesn't import them all automatically:
import tkinter.__main__
print("this will only print after you close the test window")
the program only continues to run after a window pops up with the current tcl/Tk version and some other content is closed, to import submodules of the package you must explicitly import them with:
from tkinter import messagebox
however as I describe in my other answer here, because of how IDLE is built it has already loaded some of the submodules when your code is being executed in the idle Shell.
I am confused about some behavior of Python. I always thought importing a module basically meant executing it. (Like they say here: Does python execute imports on importation) So I created three simple scripts to test something:
main.py
import config
print(config.a)
config.a += 1
print(config.a)
import test
print(config.a)
config.py
def get_a():
print("get_a is called")
return 1
a = get_a()
test.py
import config
print(config.a)
config.a += 1
The output when running main.py is:
get_a is called
1
2
2
3
Now I am confused because I expected get_a() to be called twice, once from main.py and once from test.py. Can someone please explain why it is not? What if I really wanted to import config a second time, like it was in the beginning with a=1?
(Fortunately, for my project this behavior is exactly what I wanted, because get_a() corresponds to a function, which reads lots of data from a database and of course I only want to read it once, but it should be accessible from multiple modules.)
Because the config module is already loaded so there's no need to 'run' it anymore, just return the loaded instance.
Some standard library modules make use of this, from example random. It creates an object of class Random on first import and reuses it when it gets imported again. A comment on the module reads:
# Create one instance, seeded from current time, and export its methods
# as module-level functions. The functions share state across all uses
#(both in the user's code and in the Python libraries), but that's fine
# for most programs and is easier for the casual user than making them
# instantiate their own Random() instance.