The runtime keeps telling me:
expected an indented block
But I don't want write nothing inside my except block, I just want it to catch and swallow the exception.
Just write
pass
as in
try:
# Do something illegal.
...
except:
# Pretend nothing happened.
pass
EDIT: #swillden brings up a good point, viz., this is a terrible idea in general. You should, at the least, say
except TypeError, DivideByZeroError:
or whatever kinds of errors you want to handle. Otherwise you can mask bigger problems.
For those who are very unclear as to why you would want to do this. Here is an example where I initially thought that an empty block would be a good idea:
def set_debug_dir(self, debug_dir=None):
if debug_dir is None:
debug_dir = self.__debug_dir
elif isinstance(debug_dir, (Path, str)):
debug_dir = debug_dir # this is my null operation
elif isinstance(debug_dir, list):
debug_dir = functools.reduce(os.path.join, debug_dir)
else:
raise TypeError('Unexpected type for debug_dir: {}'.format(type(debug_dir).__name__))
But it would be more clear to reorganize the statement:
def set_debug_dir(self, debug_dir=None):
if debug_dir is None:
debug_dir = self.__debug_dir
elif isinstance(debug_dir, list):
debug_dir = functools.reduce(os.path.join, debug_dir)
elif not isinstance(debug_dir, (Path, str)):
raise TypeError('Unexpected type for debug_dir: {}'.format(type(debug_dir).__name__))
I've never done this in more permanent code, but I frequently do it as a placeholder
if some_expression:
True
else:
do_something(blah)
Just sticking a True in there will stop the error. Not sure if there's anything bad about this.
Related
Thats my first question on Stackoverflow and im a totally Python beginner.
I want to write, to get firm with python, a small Backup-Programm, the main part is done, but now i want to make it a bit "portable" and use a Config file, which i want to Validate.
My class "getBackupOptions" should be give Back a validate dict which should be enriched with "GlobalOptions" and "BackupOption" so that i finally get an fully "BackupOption" dict when i call "getBackupOptions.BackupOptions".
My Question now is, (in this Example is it easy, because its only the Function which check if the Path should be Recursive searched or not) how to simplify my Code?
For each (possible) Error i must write a new "TryExcept" Block - Can i Simplify it?
Maybe is there another way to Validate Config Files/Arrays?
class getBackupOptions:
def __init__(self,BackupOption,GlobalOptions):
self.BackupOption = BackupOption
self.GlobalOptions = GlobalOptions
self.getRecusive()
def getRecusive(self):
try:
if self.BackupOption['recursive'] != None:
pass
else:
raise KeyError
except KeyError:
try:
if self.GlobalOptions['recursive'] != None:
self.BackupOption['recursive'] = self.GlobalOptions['recursive']
else:
raise KeyError
except KeyError:
print('Recusive in: ' + str(self.BackupOption) + ' and Global is not set!')
exit()
Actually i only catch an KeyError, but what if the the Key is there but there is something else than "True" or "False"?
Thanks a lot for you help!
You may try this
class getBackupOptions:
def __init__(self,BackupOption,GlobalOptions):
self.BackupOption = BackupOption
self.GlobalOptions = GlobalOptions
self.getRecusive()
def getRecusive(self):
if self.BackupOption.get('recursive') == 'True' and self.GlobalOptions.get('recursive') == 'True':
self.BackupOption['recursive'] = self.GlobalOptions['recursive']
else:
print('Recusive in: ' + str(self.BackupOption) + ' and Global is not set!')
exit()
Here get method is used, therefore KeyError will not be faced.
If any text other than True comes in the field it will be considered as False.
I have a function written here:
def addItem(aBookcase, name, mediaType):
"""
Returns False if aBookcase is full, otherwise returns True and
adds item of given name and mediaType to aBookcase.
"""
pass
emptySpacesBefore = aBookcase.getEmptySpaces()
if aBookcase.getEmptySpaces() == 0:
added = False
return added
else:
position = findSpace(aBookcase)
aBookcase.setName(*position, name=name)
aBookcase.setType(*position, mediaType=mediaType)
added = True
emptySpacesAfter = aBookcase.getEmptySpaces()
assert added is True, "No free positions"
assert emptySpacesAfter < emptySpacesBefore, "Same amount of empty spaces"
assert aBookcase.getName(*position) is name, "Error with name"
assert aBookcase.getType(*position) is mediaType, "Error with media type"
Yet when I go to test the function with this line of code:
assert addItem(small, "Algorhythms, date structures and compatibility", BOOK)
I get an 'AssertionError' as shown here:
So if I'm right, it means I'm not handling it but I'm not sure how or why? Is it something wrong with my code? Something missing? etc.
when it works properly, your addItem function returns nothing, so it returns None, which is seen as a failure by the last assert statement that you inserted. You should return added for both cases (True or False)
BTW since you reached that line, it means that all previous assertions are OK so good news: your code is OK.
i have to check if the content of some variable are of some specific type (it is a sanity check i want to implement). If each one of these is not of the specified type then the program has to abort.
I'm not experienced in python, i've a glance to the official guide on the web where it is stated that it is possible to define own exceptions by class implementation. I don't know if that would be hard or not, but since i don't have to do something particularly complicated is it possible to do that in a simple way?
Update
I've implemented the exception int exception in the following way:
class TypeCheckingException(Exception):
def __init__(self,type_in,type_exp):
self.type_in = type_in
self.type_exp = type_exp
The specific line of the implementation its use are:
try:
if isinstance(var1,str) == 0:
raise TypeCheckingException(type(var1),str)
if isinstance(var2,str) == 0:
raise TypeCheckingException(type(var2),str)
if isinstance(var3,int) == 0:
raise TypeCheckingException(type(var3),int)
if isinstance(var4,int) == 0:
raise TypeCheckingException(type(var4),int)
if isinstance(var5,str) == 0:
raise TypeCheckingException(type(var5),str)
if isinstance(var6,float) == 0:
raise TypeCheckingException(type(var6),float)
except TypeCheckingException, tce:
print "Type expected input " + str(tce.type_in) + " while type expected is " + str(tce.type_exp) + "."
In this case works, but the error output is quite verbose... i'd like to make it shorter...
Any clue?
You want to use isinstance(variable, type).
>>> a = 'str'
>>> isinstance(a, str)
True
You won't need to use exception handling with this route. You can check for instance type, then exit, if necessary.
New to Python, so I'm sure this is a noob question, but Googling isn't availing me of a clear answer.
Given the following function which is intended to ensure that the user input is a string, why can't I (or how can I) add a print statement when the exception is triggered? The print statement I've inserted there doesn't work.
def string_checker(action):
try:
check = isinstance(action, basestring)
if check == True:
return True
except ValueError:
print "We need a string here!"
return None
action = "words"
string_checker(action)
This may do what you want:
def string_checker(action):
try:
assert isinstance(action, basestring)
return True
except AssertionError:
print "We need a string here!"
return None
action = "words"
string_checker(action)
string_checker(21)
But you could also return "We need a string here!" instead of printing it, or return False, for consistency.
The problem is that you're never raising a value error if action isn't a string. Try this:
def string_checker(action):
try:
check = isinstance(action, basestring)
if check:
return True
else:
raise ValueError
except ValueError:
print "We need a string here!"
return None
But really, I don't think you need an exception. This should work fine:
def string_checker(action):
try:
check = isinstance(action, basestring)
if check:
return True
else:
print "We need a string here!"
return None
I'm not sure I understand. This appears to print "We need a string here!":
def string_checker(action):
try:
raise ValueError()
check = isinstance(action, basestring)
if check == True:
return True
except ValueError:
print "We need a string here!"
return None
action = "words"
string_checker(action)
raw_input('#')
Note the raise ValueError() in the try. Are you sure an exception is being thrown?
For example I have a line of code like this
if checked:
checked_string = "check"
else:
checked_string = "uncheck"
print "You can {} that step!".format(checked_string)
Is there a shortcut to this? I was just curious.
print "You can {} that step!".format('check' if checked else 'uncheck')
checkmap = {True: 'check', False: 'uncheck'}
print "You can {} that step!".format(checkmap[bool(checked)]))
This can be handled with python 3.6+ using f-strings
print(f"You can {'check' if checked else 'uncheck'} that step!")
I know, I'm very late. But people do search.
I'm using this in a situation, where the format strings must be as simple as possible, because they are part of the user supplied configuration, i.e. written by people knowing nothing about Python.
In this basic form is the usage limited to just one condition.
class FormatMap:
def __init__(self, value):
self._value = bool(value)
def __getitem__(self, key):
skey = str(key)
if '/' not in skey:
raise KeyError(key)
return skey.split('/', 1)[self._value]
def format2(fmt, value):
return fmt.format_map(FormatMap(value))
STR1="A valve is {open/closed}."
STR2="Light is {off/on}."
STR3="A motor {is not/is} running."
print(format2(STR1, True))
print(format2(STR2, True))
print(format2(STR3, True))
print(format2(STR3, False))
# A valve is closed.
# Light is on.
# A motor is running.
# A motor is not running.