public
Created

Random Exception Generation

  • Download Gist
Random Assignment
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
import random
import string
 
 
class RandomAssignment(object):
__max_attr_length__ = 10
__alphabet__ = string.letters + string.digits
 
def __setattr__(self, key, value):
newkey = ''.join(random.sample(self.__alphabet__,
int(self.__max_attr_length__ * random.random())))
self.__dict__[newkey] = value
 
r = RandomAssignment()
r.elem = "hello"
r.elem = "world"
r.fun = "goodbye"
# I'm filtering out all the __stuff__
 
print dir(r)
>>> ['mqgBIZ', 'vZtKXn9Tq', 'JQ6Eb']
 
print r.mqgBIZ
>>> "hello"
 
print r.vZtKXn9Tq
>>> "goodbye"
 
print r.JQ6Eb
>>> "world"
Random Exceptions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
import exceptions
import random
 
def RandomException(*args, **kwargs):
exc = vars(exceptions)
classes = [exc[k] for k in exc if
not k.startswith("__") and
not k.startswith("Unicode")]
return random.choice(classes)(*args, **kwargs)
raise RandomException("What's going on here?")
 
"""
$ python randomexception.py
AssertionError: What's going on here?
 
$ python randomexception.py
IndentationError: What's going on here?
 
$ python randomexception.py
IOError: What's going on here?
 
$ python randomexception.py
MemoryError: What's going on here?
 
"""

For more variety, you could find all defined exceptions from BaseException__subclasses__:

import random


def get_exceptions(thing = BaseException):
    subs = thing.__subclasses__()

    found = []
    for s in subs:
        found.extend(get_exceptions(s))
    return subs + found


def RandomException(*args, **kwargs):
    for x in range(1000):
        exc = random.choice(get_exceptions())
        try:
            return exc(*args, **kwargs)
        except Exception:
            # Keep trying until an exception doesn't error for the
            pass
    else:
        return BaseException()


if __name__ == "__main__":
    raise RandomException("OHNO")

(Edit: moved random.choice() inside for loop to make it less useless)

I'm not entirely sure what your for loop accomplishes, since nothing changes between iterations.

I could see this working:

def RandomException(*args, **kwargs):
  exc = get_exceptions()
  random.shuffle(exc)
  for x in exc:
    try:
      return exc(*args, **kwargs)
    except Exception: pass
  else:
    return BaseException()

Oops, the random.choice() was supposed to be in the for loop, although shuffling the exceptions and looping through them is a much nicer way of doing it

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.