Python wont define function - python

I am getting back into python and I'm having a really basic issue....
My source has the following...
def calrounds(rounds):
print rounds
When I run this through the shell and try to call calrounds(3) I get..
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
calrounds(3)
NameError: name 'calrounds' is not defined
Its been awhile since I've used python, humor me.

Did you import your source first?

It says that the first line of your program is calling calrounds with a parameter 3. Move that below your function definition. The definition needs to be before you call the function. If you are using python 3.0+ you need parenthesis for the print statement.
>>> def calrounds(rounds):
print(rounds)
>>> calrounds(3)
3

The first thing to do is to look at how you're calling the function. Assuming it's in myModule.py, did you import myModule or did you from myModule import calrounds? If you used the first one, you need to call it as myModule.calrounds().
Next thing I would do is to make sure that you're restarting your interpreter. If you have imported a module, importing it again will not reload the source, but use what is already in memory.
The next posibility is that you're importing a file other than the one you think you are. You might be in a different directory or loading something from the standard library. After you import myModule you should print myModule.__file__ and see if it is the file you think you're working on. After 20 years of programming, I still find myself doing this about once a year and it's incredibly frustrating.
Finally, there's the chance that Python is just acting up. Next to your myModule.py there will be a myModule.pyc - this is where Python puts the compiled code so it can load modules faster. Normally it's smart enough to tell if your source has been modified but, occassionally, it fails. Delete your .pyc file and restart the interpreter.

Related

Python - ImportError: cannot import name - another question

I've seen dozens of questions like this with different problems / solutions. After going through the first dozen or so on StackOverflow, I haven't found a solution to my problem which is:
I have a class like this:
class Flight:
pass
in a file called airtravel.py and then on my REPL (in that directory) I use:
from airtravel import Flight
which immediately fails with:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name Flight
>>>
Any suggestions?
There is no such library in Python and PyPi - https://pypi.org/search/?q=airtravel
Make sure they are both on the same directory. Your main.py And airtravel.py
There's several reasons this can happen. Since it's not a ModuleNotFoundError I can think of two things you can try:
Make sure you've spelled Flight correctly in both places. If that doesn't solve your problem then
Change the name of the module from airtravel to something else like airtravel2. The reason for this is that there's a possibility that there's another module named airtravel somewhere else, and is being imported because of higher precedence.
You can try below suggestion and see if it helps.
Probably latest content of your file airtravel.py is not Saved.
Try renaming your file airtravel.py to some other name say airtraveltest.py

Imported module cannot let me use the function it contains

I'm using a 2010 Head First Book for Python, chapter 2. I've created a module called nester, which contains the function print_lol, then made another program which should import nester, create a little list, and then call the function print_lol contained in nester. It doesn't work, tho.
import nester
cast = ["Palin", "Cleese", "Idle", "Jones", "Gilliam", "and Chapman."]
nester.print_lol(cast)
This is the program, and this is the output:
> Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
nester.print_lol(cast)
AttributeError: module 'nester' has no attribute 'print_lol'
What's wrong with that? Why this happens? The code is exactly as in the book, same path, environment paths are ok. What's wrong?
Here is the 'nester' code, and it works properly.
def print_lol(the_list):
for each_item in the_list:
if isinstance(each_item, list):
print_lol(each_item)
else:
print(each_item)
Also, the nester it's in C:\nester. It contains setup.py, nester.py, and the installation folders and files: MANIFEST, Lib, dist, build.
Try this on your python console
dir("nester")
It should show all the available functions. You might need to make sure print_lol is in the list. Most likely, it is under some other sub-tribute. So the way you call it should be nester.some_tribute.print_lol()
Since import nester didn't throw in error, that means your script can import nester. Try (explicit function import)
from nester import print_lol
If this fails, make sure print_lol exist in nester, as in there are no spelling mistakes.
I guess I found out the answer, and it was pretty easy, but I didn't notice that until deeper research on the website with two friends here.
The module where the 'nester' class is put it's called 'nester'. So when I tried to import 'nester', I imported the module, not the class. I changed the code from the question one to:
from nester import nester
cast = ["Palin", "Cleese", "Idle", "Jones", "Gilliam", "and Chapman."]
nester.print_lol(cast)
So I import from 'nester' Module the 'nester' Class.
Pro-tip: NEVER use the same name for Module and Class.
Credits:

Python name 'os' is not defined even though it is explicitly imported

I have a module called imtools.py that contains the following function:
import os
def get_imlist(path):
return[os.path.join(path,f) for f in os.listdir(path) if f.endswith('.jpg')]
When I attempt to call the function get_imlist from the console using import imtools and imtools.get_imlist(path), I receive the following error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\...\PycharmProjects\first\imtools.py", line 5, in get_imlist
NameError: name 'os' is not defined
I'm new at Python and I must be missing something simple here, but cannot figure this out. If I define the function at the console it works fine. The specific history of this module script is as follows: initially it was written without the import os statement, then after seeing the error above the import os statement was added to the script and it was re-saved. The same console session was used to run the script before and after saving.
Based on small hints, I'm going to guess that your code didn't originally have the import os line in it but you corrected this in the source and re-imported the file.
The problem is that Python caches modules. If you import more than once, each time you get back the same module - it isn't re-read. The mistake you had when you did the first import will persist.
To re-import the imtools.py file after editing, you must use reload(imtools).
Same problem is with me I am also trying to follow the book of Programming Computer Vision with Python by Jan Erik Solem" [http://programmingcomputervision.com/]. I tried to explore on internet to see the problem but I did not find any valuable solution but I have solved this problem by my own effort.
First you just need to place the 'imtools.py' into the parent folder of where your Python is installed like C:\Python so place the file into that destination and type the following command:
from PIL import Image
from numpy import *
from imtools import *
Instead of typing the code with imtools.get_imlist() you just to remove the imtools from the code like:
get_imlist()
This may solve your problem as I had found my solution by the same technique I used.

Receiving AttributeError from os.path.isfile() function

Receiving the below error when running my script:
Traceback (most recent call last):
File "HC_Main.py", line 54, in <module>
setup_exists = os.path.isfile(config_file)
AttributeError: 'function' object has no attribute 'isfile'
Sample code is:
import os
setup_exists = os.path.isfile(setup_exists)
if setup_exists is False:
print "Setup file exists"
When I checked the IDLE console with dir(os.path), isfile is listed. Additionaly, I can use the function without issues in IDLE as well.
Could it be my IDE causing issues here? I've also tried running the script apart from the IDE, but it still receives the error.
Somehow, os.path is no longer the builtin module, but it has been replaced with a function. Check your code to make sure you didn't accidentally monkey-patch it somewhere.
For clues, you could start by putting:
print os.path
right before the line where you actually use os.path.isfile. This should give you the function's name which will hopefully give you a good place to start looking.
Try
import os.path
instead
see this thread for more info: How do I check whether a file exists using Python?
Found the issue. I had an if/else statement earlier in the code, which was being used to gather the OS version the script was running on. Turns out I used OS (caps) for the variable name, which I think caused this. I changed it around, and it's fixed.

How to run a large amount of python code from a string?

I need to be able to run a large amount of python code from a string. Simply using exec doesn't seem to work, as, while the code runs perfectly in a normal setting, doing it this way seems to throw an error. I also don't think I can just import it as it it hosted on the internet. Here is the code:
import urllib.request
URL = "https://dl.dropboxusercontent.com/u/127476718/instructions.txt"
def main():
instructions = urllib.request.urlopen(URL)
exec(instructions.read().decode())
if __name__ == "__main__":
main()
This is the error I've been getting:
Traceback (most recent call last):
File "C:\Python33\rc.py", line 12, in <module>
main()
File "C:\Python33\rc.py", line 9, in main
exec(instructions.read().decode())
File "<string>", line 144, in <module>
File "<string>", line 120, in main
NameError: global name 'Player' is not defined
The code I'm trying to run is available in the link in the first code snippet.
If you have any questions I'll answer them. Thank you.
Without specifying globals, the exec function (Python/bltinmodule.c) uses PyEval_GetGlobals() and PyEval_GetLocals(). For the execution frame of a function, the latter creates a new f_locals dict, which will be the target for the IMPORT_NAME, STORE_NAME, LOAD_NAME ops in the compiled code.
At the module level in Python the normal state of affairs is globals() == locals(). In that case STORE_NAME is using the module's globals, which is what a function defined within the module will use as its global namespace. However, using separate dicts for globals and locals obviously breaks that assumption.
The solution is to to manually supply globals, which exec will also use as locals:
def main():
instructions = urllib.request.urlopen(URL)
exec(instructions.read().decode(), globals())
You could also use a new dict that has __name__ defined:
def main():
instructions = urllib.request.urlopen(URL)
g = {'__name__': '__main__'}
exec(instructions.read().decode(), g)
I see in the source that the current directory will need a sound file named "pickup.wav", else you'll just get another error.
Of course, the comments about the security problems with using exec like this still apply. I'm only addressing the namespace technicality.
First I thought you might try __import__ with a StringIO object. Might look something like StackOverflow: Local Import Statements in Python.
... but that's not right.
Then I thought of using the imp module but that doesn't seen to work either.
Then I looked at: Alex Martelli's answer to Use of Eval in Python --- and tried to use it on a silly piece of code myself.
I can get the ast object, and the results of the compile() from that (though it also seems that one can simply call compile(some_string_containing_python_source, 'SomeName', 'exec') without going through the ast.parse() intermediary step if you like. From what I gather you'd use ast if you wanted to then traverse the resulting syntax tree, inspecting and possibly modifying nodes, before you compiled it.
At the end it seems that you'll need to exec() the results of your compile() before you have resulting functions, classes or variables defined in your execution namespace.
You can use pipe to put all strings into a child process of python and get output result from it.
Google os.popen or subprocess.Popen

Categories