Forum: Poser Python Scripting


Subject: Useful Code Snippets

structure opened this issue on Jun 27, 2019 ยท 94 posts


structure posted Thu, 04 November 2021 at 4:38 AM Forum Coordinator

adp001 posted at 2:49 AM Wed, 3 November 2021 - #4429830


class ignore_error(object):
    def __init__(self, *args):
        self.tolerable = args

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        return exc_type in self.tolerable if len(self.tolerable) else True


with ignore_error(NameError, poser.error):
    actor = poser.Scene().Actor("not existing actor")




Made a mistake in:

    def __exit__(self, exc_type, exc_val, exc_tb):
        return exc_type in self.tolerable if len(self.tolerable) else True

the default result must be False, not True:

    def __exit__(self, exc_type, exc_val, exc_tb):
        return exc_type in self.tolerable if len(self.tolerable) else False



nice addition,  this could be used in conjunction with contextlib.suppress
which captures all kinds of errors and ignores them.

in this simple example, I am trying to print a non-digit string as an integer,
and the output is suppressed. 


import contextlib

with contextlib.suppress(NameError, TypeError, WindowsError):
    def do_something(*args, **kwargs):
        try:
            print(int(message))
        except ValueError:
            raise TypeError("%s is invalid" %(message))

    message = "nothing to see here, move along"
    do_something()


without the contextlib.suppress in place the output is 
TypeError: nothing to see here, move along is invalid

In the following amended example the output is printed as
nothing to see here, move along

import contextlib

with contextlib.suppress(NameError, TypeError, WindowsError):
    def do_something(*args, **kwargs):
        try:
            print(message)
        except ValueError:
            raise TypeError("%s is invalid" %(message))

    message = "nothing to see here, move along"
    do_something()

            

I am unsure that I have found every type of python error, but here is an
almost comprehensive list of errors that contextlib.suppress can capture. 

errorlist = [ArithmeticError, AssertionError, BrokenPipeError, BufferError,
ChildProcessError, ConnectionAbortedError,  ConnectionError,
ConnectionRefusedError, ConnectionResetError, EOFError, FileExistsError,
FileNotFoundError, FloatingPointError, ImportError, IndentationError,
IndexError, InterruptedError, IsADirectoryError, KeyError, LookupError,
MemoryError, ModuleNotFoundError, NameError, NotADirectoryError,
NotImplementedError, OverflowError, ProcessLookupError, ReferenceError,
RuntimeError, SyntaxError, SystemError, TabError, TimeoutError, TypeError,
UnboundLocalError, UnicodeEncodeError, UnicodeError, UnicodeTranslateError,
ValueError, WindowsError, ZeroDivisionError, ]

Locked Out