I'm using python 3.2.2. When I write a simple program, I meet the problem.
>>> reload(recommendations)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
reload(recommendations)
NameError: name 'reload' is not defined
How should I do it?
You probably wanted importlib.reload().
from importlib import reload
In Python 2.x, this was a builtin, but in 3.x, it's in the importlib module.
Note that using reload() outside of the interpreter is generally unnecessary, what were you trying to do here?
An update to #Gareth Latty's answer. imp was depreciated in Python 3.4. Now you want importlib.reload().
from importlib import reload
Try importlib.reload.
Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter.
from importlib import reload
reload(module_name)
As others have said, you need either importlib.reload(module) or at some earlier point you need to from importlib import reload. But you can hide the from importlib import reload in an initialization file. Make sure that PYTHONSTARTUP is defined in your shell. For example,
export PYTHONSTARTUP=$HOME/python/startup.py
might a reasonable line to add to your ~/.bash_profile, if your shell is bash, and depending on where you store your python files. (If you’re following these instructions, start a new terminal window at this point so that the line is executed.) Then you can put the line
from importlib import reload
in ~/python/startup.py and it will happen automatically. (Again, if you’re following along, start a new python session at this point.) This might look a bit complex just to solve this one problem, but it’s a thing you only have to do once, and then for every similar problem along the lines of “I wish python would always do this”, once you find the solution you can put it in ~/python/startup.py and forget about it.
Related
Using pycharm with python 3.7. I am using queue.SimpleQueue. The code runs fine, and PyCharm is pointed at the correct interpreter and all that. But with this code:
import queue
Q = queue.SimpleQueue()
I get a warning "Cannot find reference 'SimpleQueue' in 'queue.pyi'".
I do some searching. I hit ctrl-B on the "import queue" statement and it takes me to a file called queue.pyi in the folder helpers/typeshed/stdlib/3/ under the pycharm installation. So apparently instead of the queue.py file in lib/python3.7/ under the python venv, it thinks I'm trying to import this queue.pyi file instead, which I didn't even know existed.
Like I said, the code runs fine, and I can simply add # noinspection PyUnresolvedReferences and the warning goes away, but then the type inferencing and code hints on the variable Q don't work.
Another fix is to instead import _queue and use _queue.SimpleQueue, because apparently in python 3.7 queue.SimpleQueue is implemented in cython and is imported from a cython package _queue. But importing _queue seems hackish and implementation-dependent.
Is there a way to tell PyCharm that import queue means the actual lib/python3.7/queue.py as opposed to whatever helpers/typeshed/stdlib/3/queue.pyi is?
It was fixed in PyCharm 2019.3 https://youtrack.jetbrains.com/issue/PY-31437, could you please try to update?
I am using PyScripter to implement a lesson from the Python Tutorial: https://docs.python.org/3.7/tutorial/modules.html#more-on-modules
However, when I attempt to import my own module quadform.py in a separate code by calling
import quadform
quadform.quad_form(1,1,-6)
I get the error:
Traceback (most recent call last):
File "<module1>", line 1, in <module>
ModuleNotFoundError: No module named 'quadform'
Even more confusing is that when I copy + paste the exact code into a separate module saved in the same location, the import on the second module does works. Since then, I have tried various permutations of syntax, using different IDEs, calling from different modules, calling from the shell, and fiddling with the Path in Environment Variables with only a few successes and seemingly at random.
Can someone explain what might be the issue? At the moment, I cannot reliably call any of my modules without getting the same error. I am a beginner trying to pick up Python (and programming in general) on my own so any help would be greatly appreciated.
Read further down:
https://docs.python.org/3.7/tutorial/modules.html#the-module-search-path
https://docs.python.org/3.7/tutorial/modules.html#packages
https://docs.python.org/3.7/tutorial/modules.html#intra-package-references
If you structure your modules like it says, you should be able to import the right things. sys.path is a list of the folders Python looks in to find packages.
I'm trying to run a Python program, which uses the pygame modules, from MATLAB. I know I can use either
system('python program.py')
or just
! python program.py
However, I keep getting the error:
Traceback (most recent call last):
File "program.py", line 1, in <module>
import pygame
ImportError: No module named pygame
What is strange is that if I run the program from the command line, it works just fine. Does anyone know why if run from within MATLAB, Python can't find pygame?
The problem may be that MATLAB is not seeing your PYTHONPATH, which normally stores Python libraries and modules. For custom modules, PYTHONPATH should also include the path to your custom folders.
You can try setting the value of PYTHONPATH from within a MATLAB running session:
PATH_PYTHON = '<python_lib_folder>'
setenv('PYTHONPATH', PATH_PYTHON); % set env path (PYTHONPATH) for this session
system('python program.py');
See also the possibly relevant SO answer here: How can I call a Qtproject from matlab?
As I haven't used matlab too often and don't have the program available now I cannot say for sure, but matlab may be creating a custom environment with custom paths (this happens a lot, so the user has a very consistent experience in their software). When matlab installs it may not export paths to its own modules to your default environment. So when calling for pygame.py outside of matlab, python cannot find pygame.py under its usual lookup paths.
Solutions could be:
find the pygame.py, and map the path to it directly in your code, though this could cause you headaches later on during deployment
Try just copying the pygame.py file to your working directory, could have dependences that need to addressed.
Install pygame directly from its developer at http://www.pygame.org. Version differences could be a problem but pygame gets put under the usual lookup paths for python. (This would be my preferred solution personally.)
Or just export the location of path to pygame in matlab's library to your default enivronment. This could be a problem during deployment too.
For posterity, first try everything that Stewie noted here ("Undefined variable "py" or class" when trying to load Python from MATLAB R2014b?). If it doesnt work then it's possible that you have multiple pythons. You can try and check which python works (with all the related installed modules) on your bash/terminal. And then use
pyversion PYTHONPATH
to let matlab know the right path.
Also use py.importlib.import_module('yourmodule') to import the module after that.
That should get you started.
I have a simple module and a basic def. Module name is example315.py and the def is
def right_justify(s)
print(s)
This works fine when I import example315 and then call example315.right_justify("hello world")
If I change my def to not return anything (in fact I can change it in any way) and then run the function again (AFTER saving my module of course) iit still does the print.
Short of exiting IDLE and starting over I can't seem to get it to work.
Any help appreciated
The module is loaded once per session, you have to re-load it when you change it.
From the Python tutorial on modules:
For efficiency reasons, each module is only imported once per
interpreter session. Therefore, if you change your modules, you must
restart the interpreter – or, if it’s just one module you want to test
interactively, use reload(), e.g. reload(modulename).
The problem you're facing is the fact that IDLE has already imported and built its internal representation of your module. Editing the file on disk won't reflect on the now imported memory-resident version in IDLE. You should be able to get the behavior you're looking for with:
example315 = reload(example315)
And here's some source: Python Docs Source
I wrote a very simple python program.
#!/usr/bin/env python
import random
x = random.uniform(-1, 1)
print str(x)
I run this from command prompt.
python random.py
It returned with error:
Traceback (most recent call last):
File "random.py", line 2, in <module>
import random
File "D:\python practise\random.py", line 3, in <module>
x = random.uniform(-1, 1)
AttributeError: 'module' object has no attribute 'uniform'
It is a very simple program, I can't understand what mistake I did in this.
(operating system: Windows 7; python version: 2.7)
Don't name your file random.py, it is importing itself and looking for uniform in it.
It's a bit of a quirk with how Python imports things, it looks in the local directory first and then starts searching the PYTHONPATH. Basically, be careful naming any of your .py files the same as one of the standard library modules.
Don't name your program as an Library.
And just as a Tip: You don't need an String storing something and printing it out just after generating it.
#!/usr/bin/env python
import random
print(random.uniform(-1, 1))
This will work fine too ;)
Your problem is that you named your test program "random.py". The current working directory is on the module search path before anything else, so when you say "import random", it imports your own test program rather than the standard library random.
Rename your test program -- or just take the .py suffix off -- and it should work.
The solution to your problem is renaming your file (random.py) to something other than Python built-ins, standard libraries, reserved keywords etc.
However I strongly recommend you take Python Tutorial, before trying any other tutorial or book. You especially need to learn more about Python scopes and namespaces.