NameError: name 'word' is not defined - python

I'm trying to make a mixWord function and I'm getting an error saying
NameError: name 'word' is not defined
What am I missing from here?
def mixWord(word):
characterList = list(word);
print characterList
import random;
random.shuffle(characterList);
print characterList;
shuffledWord = ''.join(characterList);
print shuffledWord;
Traceback (most recent call last):
File "", line 1, in
mixWord (word)
NameError: name 'word' is not defined

The problem is PEBKAC - exactly what form, is for you to find out.
That is, the code executed is not the same as the code posted; the posted code works as expected:
def mixWord(word):
characterList = list(word);
print characterList
import random;
random.shuffle(characterList);
print characterList;
shuffledWord = ''.join(characterList);
print shuffledWord;
mixWord("PEBKAC")
So, find out why:
Has the file been saved?
Has the file been saved to the correct location?
Is the file from the correct location being run?
Is the error from different code entirely?
Also try running the code directly from an IDLE buffer as that should be immune to the previous potential issue(s).
After resolving the issue, consider updating the code to not using semicolons as they are not required here and it is un-Pythonic.

I think the problem is that you are calling mixWord(word) without defining any word variable.

Related

'str' object has no attribute 'from_directory_url' in python

I am trying to make the call
from azure.storage.fileshare import ShareDirectoryClient
shrdDirClient = ShareDirectoryClient.from_directory_url
(detailedFileURI,snapshot=None, credential=None)
but resulted in the error above.
I tried
if hasattr(ShareDirectoryClient, 'from_directory_url'):
print("Present")
But it did not go into the loop.
My full code is too long. This is another approach I tried resulting in 'str' object is not callable error
from azure.storage.fileshare import ShareDirectoryClient
from datetime import timedelta,datetime
now = datetime.now(timezone('UTC'))
sasToken = generate_share_sas(accountName, shareName, accountKey,\
permission=AccountSasPermissions(read=True, \
write=False, \
delete=False, \
list=True, create=True), expiry=now + timedelta(days=3650)\
)
accountURL = "https://nsclusterhdistorage.file.core.windows.net"
shareName = "dev-archived-data"
detailedFileURI = accountURL+'/'+shareName
sh = ShareDirectoryClient()
sh.from_directory_url(detailedFileURI,snapshot=None, credential=sasToken)
I am relatively new to python azure storage file share.
can someone help
Sorry, I can't reproduce this.
I ran the following code:
from azure.storage.fileshare import ShareDirectoryClient
detailedFileURI = "Something"
shrdDirClient = ShareDirectoryClient.from_directory_url(detailedFileURI,snapshot=None, credential=None)
and it generated the following error:
Traceback (most recent call last):
File "D:\StackOverflow\azure_storage_test.py", line 4, in <module>
shrdDirClient = ShareDirectoryClient.from_directory_url(detailedFileURI,snapshot=None, credential=None)
File "C:\Python37\lib\site-packages\azure\storage\fileshare\_directory_client.py", line 164, in from_directory_url
credential=credential, **kwargs)
File "C:\Python37\lib\site-packages\azure\storage\fileshare\_directory_client.py", line 96, in __init__
raise ValueError("Please specify a share name.")
ValueError: Please specify a share name.
Now clearly this isn't successful execution. If I'm honest, I don't know what to set detailedFileURI to. But that's not the point. The point is that the code sample above is enough to prove that I can get in to the from_directory_url method, and this is clear from the traceback.
However, if I run the following code:
from azure.storage.fileshare import ShareDirectoryClient
ShareDirectoryClient = "some string"
detailedFileURI = "Something"
shrdDirClient = ShareDirectoryClient.from_directory_url(detailedFileURI,snapshot=None, credential=None)
then I do encounter the same error:
Traceback (most recent call last):
File "D:\StackOverflow\azure_storage_test.py", line 5, in <module>
shrdDirClient = ShareDirectoryClient.from_directory_url(detailedFileURI,snapshot=None, credential=None)
AttributeError: 'str' object has no attribute 'from_directory_url'
Of course, there's not a lot of point in importing ShareDirectoryClient if you're then going to assign a string to it. You may as well remove the import statement. However, doing this reproduces your error message. In the absence of any further code in your question I can only conclude that your code does the same as this, although perhaps more subtly.
The only other suggestion I have is that your installation of the azure-storage-file-share package has somehow got broken. If you run a Python script containing the following two lines only, you should get either <class 'type'> or <class 'str'> as output. I get <class 'type'>, and I would expect that anyone else using this package would get the same. However, if you get <class 'str'>, then it is likely that the package has got corrupted and you may want to try reinstalling it.
from azure.storage.fileshare import ShareDirectoryClient
print(type(ShareDirectoryClient))
For some reason ‘ ShareDirectoryClient’ is of type {string}. You either import it as a string, i.e. ‘ azure.storage.fileshare’ simply has this defined as a string, or, you assign it to a string later in your code (not visible in the part that has been shared). Please try this:
X = ‘some_string’
X()
… and you will get the string-is-not-callable error which means a string cannot be invoked (i.e. it is not a function one can call)
Then another experiment:
Y = ‘another_string’
Y.bla()
… and you get the other error that a string object has no attribute named ‘bla’.
In Python everything is an object. If you define
class MyClass()
pass
And then try ‘MyClass.bla()’ you will get MyClass does does not have attribute ‘bla’.
Can you try to import ShareDirectoryClient and then type(ShareDirectoryClient) and we’ll see what type of object gets imported.

Python : NameError: global name 'GetText' is not defined

I have been stuck with this error for a couple of hours now. Not sure what is wrong. Below is the piece of code
NameError: global name 'GetText' is not defined
class BaseScreen(object):
def GetTextFromScreen(self, x, y, a, b, noofrows = 0):
count = 0
message = ""
while (count < noofrows):
line = Region(self.screen.x + x, self.screen.y + y + (count * 20), a, b)
message = message + "\n" + line.text()
count += 1
return message
class HomeScreen(BaseScreen):
def GetSearchResults(self):
if self.screen.exists("Noitemsfound.png"):
return 'No Items Found'
else:
return self.GetTextFromScreen(36, 274, 680, 20, 16)
class HomeTests(unittest.TestCase):
def test_001S(self):
Home = HomeScreen()
Home.ResetSearchCriteria()
Home.Search("0009", "Key")
self.assertTrue("0009" in Home.GetSearchResults(), "Key was not returned")
Basescreen class has all the reusable methods applicable across different screens.
Homescreen inherits Basescreen.
In HomeTests test case class, the last step is to Home.GetSearchResults() which in turn calls a base class method and the error.
Note:
I have another screenclass and testcaseclass doing the same which works without issues.
I have checked all the importing statements and is ok
'GetText' in the error message is the name of method initially after which i changed it to GetTextFromScreen
Error message is still pointing to a line 88 in code which is not there any more. Module import/reloading issue?
Try clearing out your *.pyc files (or __pycache__ if using 3+).
You asked:
Error message is still pointing to a line 88 in code which is not there any more. Module import/reloading issue?
Yes. The traceback (error messages) will show the current (newest saved) file, even if you haven't run it yet. You must reload/reimport to get the new file.
The discrepancy comes from the fact that traceback printouts read from the script file (scriptname.py) saved on your drive. However, the program is run either from the module saved in memory, or sometimes from the .pyc file. If you fix an error by changing your script, and save it to your drive, then the same error will still occur if you don't reload it.
If you're running interactively for testing, you can use the reload function:
>>> import mymodule
>>> mymodule.somefunction()
Traceback (most recent call last):
File "mymodule.py", line 3, in somefunction
Here is a broken line
OhNoError: Problem with your file
Now, you fix the error and save mymodule.py, return to your interactive session, but you still get the error, but the traceback shows the fixed line
>>> mymodule.somefunction()
Traceback (most recent call last):
File "mymodule.py", line 3, in somefunction
Here is the fixed line
OhNoError: Problem with your file
So you have to reload the module:
>>> reload(mymodule)
<module 'mymodule' from '/path/to/mymodule.py'>
>>> mymodule.somefunction()
Success!

Why do I get "NameError: name '...' is not defined" in python module?

filename:recom.py
# Returns a distance-based similarity score for person1 and person2
def sim_distance(prefs,person1,person2):
# Get the list of shared_items
si={}
for item in prefs[person1]:
if item in prefs[person2]:
si[item]=1
# if they have no ratings in common, return 0
if len(si)==0: return 0
# Add up the squares of all the differences
sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2)
for item in prefs[person1] if item in prefs[person2]])
return 1/(1+sum_of_squares)
Am getting the error ,when i try to do reload(recom)
Traceback (most recent call last):
File "", line 1, in
NameError: name 'recom' is not defined
I use python 3.4.3, and I just encountered the same problem. The below solution solved it for me.
When you use reload() you should also use from imp import reload before you use it.
As to getting the Euclidean Distance Score, you can get your answer like:
from recom import critics
from recom import sim_distance
sim_distance(critics,'Lisa Rose','Gene Seymour')
The result is: 0.29429805508554946
You need to have imported the module using "import recom" before it can be reloaded. Also, make sure the code is executing where it can resolve the path to recom.

name 'self' is not defined when doing an unittest?

Edit
So I did try again, with a new file called test2.py and it works. I packaged repoman , and test.py is in the src folder. I modified test.py after I created and installed my repoman egg. I think that's the problem. But thanks for the help. Do you guys think that's the exact reason?
import unittest
import requests
from repoman.core import ultraman, supported
from repoman.ext import writefile,locate_repo
class TestWriteFile(unittest.TestCase):
def setUp(self):
self.username = 'dummy'
self.password = 'dummy'
self.remote = 'http://192.168.1.138:6666/scm/hg/NCL'
def test_scm_permission(self):
"""
Test SCM login.
"""
r = requests.get("http://192.168.1.138:6666/scm/", auth=(self.username, self.password))
self.assertTrue(r.ok)
if __name__ == '__main__':
unittest.main()
Running python test.py I get this error:
Traceback (most recent call last):
File "test.py", line 7, in <module>
class TestWriteFile(unittest.TestCase):
File "test.py", line 19, in TestWriteFile
self.assertTrue(r.ok)
NameError: name 'self' is not defined
I don't think I need to overwrite __init__ function, do I? What's causing this? Why is self not defined? I already declared my superclass unittest.TestCase
Thanks.
I basically learned it from the official sample: Unittest - Basic Example
I'm not sure where the problem is coming from -- whether it's a copying error or the wrong test.py is being executed [update: or some mixed tabs-and-spaces issue, I can never figure out when those get flagged and when they don't] -- but the root cause is almost certainly an indentation error.
Note that the error message is
NameError: name 'self' is not defined
and not
NameError: global name 'self' is not defined
which #Rik Poggi got. This is exactly what happens if you move the self.assertTrue one level in/up:
~/coding$ cat test_good_indentation.py
import unittest
class TestWriteFile(unittest.TestCase):
def test(self):
"""
Doc goes here.
"""
self.assertTrue(1)
if __name__ == '__main__':
unittest.main()
~/coding$ python test_good_indentation.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
versus
~/coding$ cat test_bad_indentation.py
import unittest
class TestWriteFile(unittest.TestCase):
def test(self):
"""
Doc goes here.
"""
self.assertTrue(1)
if __name__ == '__main__':
unittest.main()
~/coding$ python test_bad_indentation.py
Traceback (most recent call last):
File "test_bad_indentation.py", line 3, in <module>
class TestWriteFile(unittest.TestCase):
File "test_bad_indentation.py", line 8, in TestWriteFile
self.assertTrue(1)
NameError: name 'self' is not defined
I don't think that what you showed is the actual code that get executed.
I and others belive that, for a couple of reasons:
If self.assertTrue(r.ok) fails then the line before will too. Therefore self.assertTrue(r.ok) won't execute. (as David Heffernan said)
And because your code looks fine.
I'd say that you probably made a typo of this kind:
def test_scm_permission(self):
^
|
and wrote something here that's not self
In some file that get executed instead of the one you're showing.
Take a look at this example:
# test.py
class MyClass:
def func(sel): # typo error here
self.name = 10
obj = MyClass()
obj.func()
And when I tried to run:
$ python3 test.py
Traceback (most recent call last):
File "test.py", line 8, in <module>
obj.func()
File "test.py", line 4, in func
self.name = 10
NameError: global name 'self' is not defined
Having a traceback similar to yours.
Note: Also if I'm not counting wrong self.assertTrue(r.ok) is on line 18, instead of line 19 (which is the number showed in your traceback).
This is a rewording of David Heffernan's comment.
The code you posted cannot be the cause of that traceback.
Consider these two lines from your code:
r = requests.get("http://192.168.1.138:6666/scm/", auth=(self.username, self.password))
self.assertTrue(r.ok)
The traceback says the error (NameError: name 'self' is not defined)
occurs on the second line (self.assertTrue(r.ok)). However, this cannot have been the case because the first line refers to self. If self were not defined, we would not get past the first line.
Therefore, the code you posted is not the code you ran.
This is an old question, but thought I'd add my two cents as it was not mentioned here. I agree with others that there is some type of spelling error in the original code. Look at this code carefully:
import unittest
import requests
class TestWriteFile(unittest.TestCase):
def setup(self):
self.username = 'dummy'
def test_scm_permission(self):
r = requests.get("http://192.168.1.138:6666/scm/", auth=(self.username, self.password))
self.assertTrue(r.ok)
The code appears okay at first glance (and lint tools will not complain); however, I wrote setup, instead of setUp (note the capital U). This causes self.username not to be defined in the test_scm_permission context, because python did not automatically call my mispelled function name. This is something else to check if you're running into this type of error, but are certain you've defined the class members correctly.
I had the same problem, but not with self. It was a regular variable, defined the line before the error occured.
It was apparently due to ... mixin tabs and spaces.
I replaced all tabs by 4 spaces, and the problem disappeared.
For some unspecified reason, instead of the traditional indentation error, I had this one.

Error when using astWCS trying to create WCS object

I'm running python2.5 and trying to use the astLib library to analyse WCS information in astronomical images. I try and get the object instanciated with the following skeleton code:
from astLib import astWCS
w = astWCS.WCS('file.fits') # error here
where file.fits is a string pointing to a valid fits file.
I have tried using the alternate method of passing a pyfits header object and this fails also:
import pyfits
from astLib import astWCS
f = pyfits.open('file.fits')
header = f[0].header
f.close()
w = astWCS.WCS(header, mode='pyfits') # error here also
The error is this:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/astro/phrfbf/build/lib/python2.6/site-packages/astLib/astWCS.py", line 79, in __init__
self.updateFromHeader()
File "/home/astro/phrfbf/build/lib/python2.6/site-packages/astLib/astWCS.py", line 119, in updateFromHeader
self.WCSStructure=wcs.wcsinit(cardstring)
File "/home/astro/phrfbf/build/lib/python2.6/site-packages/PyWCSTools/wcs.py", line 70, in wcsinit
return _wcs.wcsinit(*args)
TypeError: in method 'wcsinit', argument 1 of type 'char *'
When I run in ipython, I get the full error here on the pastebin
I know the astWCS module is a wrapped version of WCStools but i'd prefer to use the Python module as the rest of my code is in Python
Can anyone help with this problem?
Just found out the updated version of this library has fixed the problem, thanks for everyone's help
Oh sorry, I should have seen. Looking at the pastebin in more detail, the only error I can think of is that, for some reason the header has unicode in it. It can't be converted to char *, and you get the error. I tried searching for something in the header, but everything looks okay. Can you do this and post the output in another pastebin?
import pyfits
f = pyfits.open('file.fits')
header = f[0].header
f.close()
for x, i in enumerate(header.iteritems()):
if len(str(i[1])) >= 70:
print x, str(i[1])
cardlist = header.ascardlist()
cardstring = ""
for card in cardlist:
cardstring = cardstring + str(card)
print repr(cardstring)
Or, if you can check the header of your fits file for "funny" characters, getting rid of them should solve the issue.

Categories

Resources