Adding if or try except blok in python function - python-2.7

I got this question i'm a little unsure how to solve:
"There are a NoneType error when reproducing the code. The getaddressdata() returns a None value. This can be fixed by adding an if-statement in the getpricelist() to see if the data is None. Use a try except block to handle invalid data."
Have to fix this before my code can run.
my function / code you see here:
def getpricelist( ):
l1=[]
for line in file('addresslist.txt'):
data=getaddressdata(line.strip( ),'Cambridge,MA')
if data != 'None':
l1.append(data)
return l1
Where do i make the try / except blok??

You should use pythonic idiom is None to check if the variable is of a NoneType or not:
data = getaddressdata(line.strip( ),'Cambridge,MA')
if data is not None:
l1.append(data)
Also see:
not None test in Python
What is the difference between " is None " and " ==None "
Hope that helps.

Related

Saving a file without closing it in Python

Suppose I have a dictionary of files that I am iterating through. I am doing some with each file and then writing it to report (Note: not using the csv mod).
file_list = ['f1', 'f2', 'f3', 'f4']
report = "C:/reports/report_%s"%(timestamp)
r = open(report, "w')
What happens if something happens in f3 that crashes the script before it finishes. I can use try-catch to handle for an error but I don't want to just close the report. Perhaps I want the script to continue. Perhaps there is a power failure while the script is running. Perhaps there are multiple try-catch statements and I don't want to close for each error. Essentially, I just want to save the file without closing it on each iteration of the list, so that if a crash occurs, I can still retrieve the data written to the report up until that point. How can I do this? I cannot simply do report.save(), right? I thought about using flush() with os.fsync() as explained in another question, but I am not 100% sure that's applicable to my scenario. Any suggestion on how to achieve my goal here?
try:
....do stuff...
report.write(<stuff_output> + "\n")
try:
....do more stuff....
report.write(<stuff_output> + "\n")
except:
continue
report.close()
except Exception as e:
pass
It appears I was able resolve this issue by simply using flush() and os.fsync() within the correct scope and placing the r.close() outside of the try. So even if it tries and fails it passes or continues and at the end it closes:
try:
for item in file_list:
try:
r.write("This is item: " + item + "\n")
except:
r.flush()
os.fsync(r)
continue
except Exception as e:
pass
r.close()
This would always print "This is item: f1", "This is item: f2", "This is item: f3" to the report.

unexpected syntax error on 'else' while the code seems correct

def restudy():
print "OK, since you decided to restudy at MIANYANG high school, you must work hard!"
print '''
Now, it's time to determine your destiny.
Please answer the questions below:
what's the result of 1+1?
if you give the right answer, you can go to Shanghai; but if you can't
you'll be caught in here forever.
'''
test = raw_input("> ")
if test == "2":
print "you succeed!"
shanghai()
else: # that's the error line
restudy()
And that's the result terminal shows to me:
else:
^
SyntaxError: invalid syntax
what's the problem about my code? cuz I think it seems right.
hope someone could help me out.
thanks!

Unexpected results when checking all values in a Python dictionary are None

Let's consider the following three dictionaries:
topByClass = {'Real Estate': 'VNO', 'Construction': 'TOL', 'Utilities': 'EXC'}
shouldPass = {'Real Estate': None, 'Construction': None, 'Utilities': 'EXC'}
shouldFail = {'Real Estate': None, 'Construction': None, 'Utilities': None}
I am looking to separate instances where all values in the dictionary are None, from everything else. (i.e. the first two should pass, while the last should fail)
I looked around online, particularly at posts such as this one. I tested various solutions out in the python console (running Python 2.7 in a virtualenv on my Mac), and the following worked:
not all(value == None for value in topByClass.values())
Both with and without "not" I can separate dictionaries like 'topByClass' from 'shouldFail'.
>>> not all(value == None for value in shouldFail.values())
>>> False
>>> not all(value == None for value in topByClass.values())
>>> True
(and vice versa for without not)
The thing is, when I go to run the python file, the if statement always evaluates as if every value is None. I have checked if possibly I am mistaking the dictionary, however I print off the dict "topByClass" in the console, and have directly pasted it above. Any ideas what this could be?
Edit:
def _getTopByClass(self, assetClass):
# Find the instrument with the highest rank.
ret = None
highestRank = None
for instrument in self.__instrumentsByClass[assetClass]:
rank = self._getRank(instrument)
if rank is not None and (highestRank is None or rank > highestRank):
highestRank = rank
ret = instrument
return ret
def _getTop(self):
ret = {}
for assetClass in self.__instrumentsByClass:
ret[assetClass] = self._getTopByClass(assetClass)
return ret
def _rebalance(self):
topByClass = self.getTop()
self.info(topByClass) # where I get the output I presented above
if any(value is not None for value in topByClass.values()):
self.info("Not All Empty")
else:
self.info("All None")
Now with the above "if" all are printing ("Not All Empty")
If you would like to see getRank() or more, I would reccommend this example from PyAlgoTrade, as the core mechanics affecting the problem are similar.
Edit 2:
Thought I might mention this incase someone tried to replicate the file linked above... PyAlgoTrade's modules for downloading feeds doesn't work. So you have to use this package to download the data, as well as adding bars from csv:
feed = yahoofeed.Feed()
feed.addBarsFromCSV("SPY", "data/SPY.csv")
for industry, stocks in instrumentsByClass.items():
for stock in stocks:
feed.addBarsFromCSV(stock, "data/"+stock+".csv")
Edit 3: Added some debug info:
self.info(isinstance(topByClass, dict))
self.info(isinstance(topByClass.values(), list))
self.info(isinstance(topByClass.values()[0], str))
returns:
>>> True
>>> True
>>> True (False when the first value is None)
Also, per a comment I thought I'd throw this in
self.info(list(topByClass.values()))
>>> [None, None, None, None]
FINAL EDIT:
Many thanks to all the people who responded, thought I would go ahead and post what I figured out incase anyone runs into a similar problem...
First of all the code/output that identified the problem:
self.info(list(shouldFail.values())
>>> [None, None, None]
self.info(list(topByClass.values())
>>>['VNO', 'TOL', 'EXC']
self.info(list(value is not None for value in topByClass.values()))
>>> [True, True, True]
self.info(any(value is not None for value in topByClass.values()))
>>> <generator object <genexpr> at 0x116094dc0>
I wasn't sure why it returned a generator, then I realized that it was probably using numpy's any() function, as I decalred:
import numpy as *
After changing this to:
import numpy as np
it behaved as expected.
Since you haven't shown us the actual code that is tickling the fail (I understand that might not be possible in a production environment), here is some philosophy about how to debug in a class hierarchy, and one theory about what might be causing this:
do add a print or logging statement to print/log your instance's values before you test it. Then you can see if it really held the value you believe it did ("When reality collides with a theory, reality wins"). Logging should become your new trusty friend in bug-hunting. Distrust all your assumptions (rubber-duck them). But logging is faster and more reliable than poring over a large class hierarchy.
beware there might be an accidental string conversion somewhere up your class hierarchy (possibly from some class someone else wrote, or accidental use of str or repr e.g in a constructor, setter or property, or a init or method with an arg default = 'None' instead of None): 'None' != None . This sort of bug is subtle and insidious. If you find it, you will laugh as you cry.
Anyway, happy logging, and please post us the logger output when you pinpoint the failing comparison. It's important to track down these sort of 'existential' bugs, since they reveal something broken or blind spot in your chain of assumptions, or debugging methodology. That's how you learn.

User defined exception - python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am learning how to create userdefined exception in python
import sqlite3
class MyError(Exception):
def __init__(self, value):
self.value = value
try:
conn= sqlite34.connect('database56.sqlite')
print conn
print 'connection established'
except MyError as e:
print 'Error message:', e.value
When I run the above program ,I get the name error
NameError: name 'sqlite13' is not defined
how do I call the user defined exception if there is a failure to connect to the database ? When [except MyError as e:] is replaced by [except:],still the exception block is not called.
Thanks for your help.
Defining an exception doesn't change what exceptions are raised by other modules. If you want your code to use your exception, you have to catch what the other module rasies and then re-raise your own.
import sqlite3
class MyError(Exception):
def __init__(self, value):
self.value = value
try:
conn= sqlite3.connect('database56.sqlite')
print conn
print 'connection established'
except sqlite3.Error as e:
print 'Error message:', e.value
raise MyError('Could not connect to db: ' + e.value)
I've caught the generic sqlite3 error here but you may need to add other exceptions if they are also raised by the module. Exactly what those exceptions are isn't easy to figure out in python. You can read the source, experiment or look around at examples on the net.
I think this is a XY Problem.
In this case, you want to catch a NameError, so you should directly use that in the except statement. If you want to perform actions after catching the error, you should put that actions in the except statement. Some documentation can be found here.
Example:
except NameError as e:
print 'Error message:', e.value
print 'Splite module not loaded'
User-defined errors are for example useful with wrong/unexpected parameters or output. So user-defined errors are useful because you determine the situations when they are raised, which is not necessarily a situation where "python would crash".
Here some documentation about it.
Maybe an example can help clarifying.
Say you have a function when one of the variables is the price of something.
Then you might do:
class NegativePriceException(Exception):
def __init__(self):
print "Price can't be negative!"
raise AttributeError
def calc_price(...):
price = ... #some calculation
if price < 0:
raise NegativePriceException
return price

Django - Passing a filtered result to a template

Inside of my Django view I am trying to retrieve results from my database and then pass them on to my template with the following code:
f = request.GET.get('f')
try:
fb_friends_found= UserProfile.objects.filter(facebookid__in=f).values('facebookid')
i = fb_friends_found[0] #To get the dictionary inside of the list
results = i['facebookid'] #To retrieve the value for the 'facebookid' key
variables = RequestContext (request, {'results': results })
return render_to_response('findfriends.html', variables)
I carried out the first three lines within the 'try' block using manage.py shell and this worked fine, printing the correct 'facebookid'.
Unfortunately I can't get it to work in my browser. Any suggestions?
Do you have a specific problem you're running into, such as an exception?
I feel like you should get some kind of exception if you have a try block without an except statement.
try:
# something
except Exception: # but be more specific
print "exception occurred"
Otherwise, the code looks good, and if nothing is rendering in your browser, I'd look into the template. Unless... you're hiding errors in your try block, in which case you should remove the try block and let the error occur to understand what's wrong.