Try every line without exception prematurely breaking code - python-3.x

I would like to write a single try-except statement that is able to run multiple try statements without the code breaking.
s = "hello, this is a string."
Using the above string as an example:
ls = []
try:
ls.append(s.split())
ls.append(s.str.split()) # expected error
ls.append(s.split(","))
ls.append(s.split("i"))
except:
pass
Above is what I tried originally but the code stops by the second try-statement.
ls = []
try:
ls.append(s.split())
except:
pass
try:
ls.append(s.str.split()) # expected error
except:
pass
try:
ls.append(s.split(","))
except:
pass
try:
ls.append(s.split("i"))
except:
pass
Eventually, I was able to get all my strings appended to the list with the above code. Is there a better way of doing this than writing individual try-except statements?

From my understanding, when an error occurs in a try statement, it will immediately go to the except statement which is why your code doesn't execute after the second try statement.
Though there are probably better solutions to your question, here is my attempt for your problem:
ls = []
char=[' ',',','i']
for i in char:
try:
ls.append(s.split(i))
ls.append(s.str.split(i))
except:
pass
print(ls)

You can use the fuckit module.
Wrap your code in a function with #fuckit decorator:
import fuckit
#fuckit
def func():
code a
code b #if b fails, it should ignore, and go to c.
code c #if c fails, go to d
code d
Or you can try this :
def a():
try: # a code
except: pass # or raise
else: return True
def b():
try: # b code
except: pass # or raise
else: return True
def c():
try: # c code
except: pass # or raise
else: return True
def d():
try: # d code
except: pass # or raise
else: return True
def main():
try:
a() and b() or c() or d()
except:
pass

Related

My code is showing error during Exception handling

I have written this code by defining instSet() class (This code inserts element to list using insert() method and then performs various functions such as removing an element using remove() method by checking if the element is present, if not, raises an expetion:
class instSet(object):
def __init__(self):
self.vals = []
def insert(self, e):
if not e in self.vals:
self.vals.append(e)
def remove(self, e):
try:
self.vals.remove(e)
except:
raise ValueError(str(e) + ' not found')
def member(self, e):
return e in self.vals
def __str__(self):
self.vals.sort()
result = ''
for e in self.vals:
result = result + str(e) + ','
return '{' + result[:-1] + '}'
Some expression performed are:
a = instSet()
a.insert(1)
a.remove(3)
print(a)
Main problem is when I am trying to remove an element which is not present in the list it is throwing error like this:
ValueError: list.remove(x): x not in list
Insted it should return:
ValueError: 3 not found
What is wrong in the above code?
There is issue with valueError that you used in except. Try using below code
except:
raise Exception(str(e) + ' not found') from None

python: generic function call from one instance to another

I am trying to write a method which calls another method in another instance. I do not know which combination of args and kwargs i get.
So i wrote the following method. But that looks not very elegant and not very pythonic to me.
Is there a better way to implement this?
def __call_generic_remote_function(self, rfunc_name, rargs=None, rkwargs=None):
try:
lfunc_name = getattr(self.inst_to_wrap, rfunc_name)
except AttributeError:
return f"Method {rfunc_name} is not existing!"
if rargs is None and rkwargs is None:
result = lfunc_name()
elif rargs is not None and rkwargs is not None:
result = lfunc_name(*rargs, **rkwargs)
elif rargs is None:
result = lfunc_name(**rkwargs)
else:
result = lfunc_name(*rargs)
return result
This question is probably off topic as it is more opinion based but I would write it something like the following. Can also be a standalone function.
def call_generic_remote_function(object_instance, func_name, *args, **kwargs):
try:
func_to_call = getattr(object_instance, func_name)
except AttributeError:
return f"Method {func_name} does not exist!"
return func_to_call(*args, **kwargs)
Tested Via:
class Foo:
def bar(self, a, b, k):
print(a, b, k)
def bar2(self):
print("Called")
f = Foo()
call_generic_remote_function(f, 'bar', 1, 2, k=3)
call_generic_remote_function(f, 'bar2')
print(call_generic_remote_function(f, 'bar3'))
Output:
1 2 3
Called
Method bar3 does not exist!

The trouble with a calculation of the set len

I can't resolve this problem:/ My code returned a bound method, not a len of the set. Help me with your advise, please!)
class PowerSet():
def __init__(self):
self.powerset = set()
def size(self):
return len(self.powerset)
def put(self, value):
if value in self.powerset:
raise KeyError
else:
return self.powerset.add(value)
a = PowerSet()
for i in range(10):
a.put(i)
print(a.size)
# <bound method PowerSet.size of <__main__.PowerSet object at 0x7f7291042940>>
but
print(len(a.powerset))
# 10
I think you just have to write len(a.size()) with brackets. Now you are asking to print the method, you are not callng it.

How to run a function in 'background'

I'm parsing the last line of a continuously updating log file. If it matches, I want to return the match to a list and start another function using that data. I need to keep watching for new entries and parse them even while the new function continues.
I've been working this from a few different angles for about a week with varying success. I tried threading, but ran into issues getting the return value, I tried using a global var but couldn't get it working. I'm now trying asyncio, but having even more issues getting that to work.
def tail():
global match_list
f.seek(0, os.SEEK_END)
while True:
line = f.readline()
if not line:
time.sleep(0.1)
continue
yield line
def thread():
while True:
tail()
def somefun(list):
global match_list
#do things here
pass
def main():
match_list = []
f = open(r'file.txt')
thread=threading.Thread(target=thread, args=(f,))
thread.start()
while True:
if len(match_list) >= 1:
somefun(match_list)
if __name__ == '__main__':
main()
Wrote the above from memory..
I want tail() to return the line to a list that somefun() can use.
I'm having issues getting it to work, I will use threading or asyncio.. anything to get it running at this point.
In asyncio you might use two coroutines, one that reads from file, and the other that processes the file. Since they communicate using queue, they don't need the global variable. For example:
import os, asyncio
async def tail(f, queue):
f.seek(0, os.SEEK_END)
while True:
line = f.readline()
if not line:
await asyncio.sleep(0.1)
continue
await queue.put(line)
async def consume(queue):
lines = []
while True:
next_line = await queue.get()
lines.append(next_line)
# it is not clear if you want somefun to receive the next
# line or *all* lines, but it's easy to do either
somefun(next_line)
def somefun(line):
# do something with line
print(f'line: {line!r}')
async def main():
queue = asyncio.Queue()
with open('file.txt') as f:
await asyncio.gather(tail(f, queue), consume(queue))
if __name__ == '__main__':
asyncio.run(main())
# or, on Python older than 3.7:
#asyncio.get_event_loop().run_until_complete(main())
The beauty of an asyncio-based solution is that you can easily start an arbitrary number of such coroutines in parallel (e.g. you could start gather(main1(), main2()) in an outer coroutine, and run that), and have them all share the same thread.
with a few small fixes you almost run this :) (comments inside)
match_list # should be at the module scope
def tail():
# f = open(...) ???
f.seek(0, os.SEEK_END)
while True:
line = f.readline()
if not line:
time.sleep(0.1)
continue
yield line
def thread():
for line in tail():
match_list.append(line) # append line
print("thread DONE!")
def somefun(list):
#do things here
while match_list:
line = match_list.pop(0)
print(line)
def main():
match_list = []
f = open(r'file.txt')
thread=threading.Thread(target=thread, args=(f,))
thread.start()
while True:
if match_list:
somefun(match_list)
time.sleep(0.1) # <-- don't burn the CPU :)

How to fix "None" answer and Take inputs as arguments?

I'm giving mettl exam and the question was for solving the parenthesis are matching or not.But all I'm getting as result is NONE.
I'm not sure how to take the input as argument, please help out:
I've tried changing, it is taking the input if I provide a hard coded one.
'''
# these are the metll instructions
class UserMainCode(object):
#classmethod
def areParenthesisBalanced(cls, input1):
'''
input1 : string
Expected return type : string
'''
# Read only region end
# Write code here
pass
'''
# this is the code I tried
class Stack():
def __init__(self):
self.items=[]
def push(self,item):
self.items.append(item)
def is_empty(self):
return self.items == []
def pop(self):
return self.items.pop()
def show_me(self):
return self.items
def peek(self):
if not self.is_empty():
return self.items[-1]
input1=[]
def areParenthesisBalanced(input1):
s=Stack()
is_balanced=True
index=0
def is_match(p1,p2):
if p1=="(" and p2==")":
return True
elif p1=="[" and p2=="]":
return True
elif p1=="{" and p2=="}":
return True
else:
return False
while index< len(input1) and is_balanced:
paren=input1[index]
if paren in"({[":
s.push(paren)
else:
if s.is_empty():
is_balanced=False
else:
top = s.pop()
if not is_match(top,paren):
is_balanced=False
index+=1
if s.is_empty() and is_balanced:
return True
else:
return False
print (areParenthesisBalanced(input1))
I was hoping to atleast get a normal True. I'm not sure how to proceed

Resources