Wednesday, December 4, 2013

fun with raise

>>> raise ValueError("wrong value")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: wrong value
>>> try:
...    raise ValueError("wrong value")
... except:
...    raise sys.exc_info()
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ValueError

If you want to really re-raise the exact same message, replace sys.exc_info()[0] with the exception instance.

>>> try:
...    raise ValueError("wrong value")
... except Exception as e:
...    raise (e,) + sys.exc_info()[1:]
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ValueError: wrong value

Alas, replacing the traceback object (sys.exc_info()[2]) does not seem to work:

>>> try:
...     json.loads('NOT JSON')
... except:
...     _, _, tb = sys.exc_info()
...
>>> try:
...    1 / 0
... except Exception as e:
...    raise sys.exc_info()[:2], tb
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ZeroDivisionError: <traceback object at 0x02B752B0>

Thursday, October 31, 2013

exit() is so pedestrian

C:\Users\kurose\workspace>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> raise SystemExit("bye")
bye

C:\Users\kurose\workspace>

Wednesday, October 30, 2013

gEvent friendly REPL

I was surprised how little code this was.  The fileobject module added in gEvent 1.0 and the standard library code module make this trivial.

import sys
import code
from gevent import fileobject

_green_stdin = fileobject.FileObject(sys.stdin)
_green_stdout = fileobject.FileObject(sys.stdout)

def _green_raw_input(prompt):
    _green_stdout.write(prompt)
    return _green_stdin.readline()[:-1]

def run_console(local=None, prompt=">>>"):
    code.interact(prompt, _green_raw_input, local=local or {})

if __name__ == "__main__":
    run_console()

Tuesday, October 29, 2013

missing the __line__ macro from C?

Frame objects to the rescue!

import sys

def __line__():
    f = sys._getframe().f_back
    return f.f_lineno + f.f_code.co_firstlineno

Wednesday, October 16, 2013

sigfigs

def _sigfigs(n, sigfigs=3):
    'helper function to round a number to significant figures'
    if n == 0 or math.isnan(n):  # avoid math domain errors
        return n
    return round(float(n), -int(math.floor(math.log10(abs(n))) - sigfigs + 1))

Wednesday, October 9, 2013

Attribution

>>> class Attribution(object):
...    def __init__(self):
...       self.instance = "instance"
...    type = "type"
...    def __getattr__(self, key):
...       return "__getattr__"
...
>>> a = Attribution()
>>> a.instance
'instance'
>>> a.type
'type'
>>> a.b
'__getattr__'

Thursday, October 3, 2013

time THIS

>>> timeit.timeit("s.recv(1, socket.MSG_PEEK", '''
... import socket
... s = socket.create_connection( ("google.com", 80) )
... s.send("blah blah\\n\\r\\n\\r\\n\\r\\n\\r\\n\\rblahblah blah"
... ''')
Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
  File "C:\Python27\lib\timeit.py", line 230, in timeit
    return Timer(stmt, setup, timer).timeit(number)
  File "C:\Python27\lib\timeit.py", line 136, in __init__
    code = compile(src, dummy_src_name, "exec")
  File "<timeit-src>", line 11
    _t1 = _timer()

SyntaxError: invalid syntax

Thursday, September 26, 2013

variable dis-assignment

>>> def foo():
...    a = 1
...    del a
...    return a
...
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in foo
UnboundLocalError: local variable 'a' referenced before assignment


Friday, September 6, 2013

unicodebreakers

Just when you thought it was safe to unicode....
>>> unicode(3)
u'3'
>>> unicode(3, errors='replace')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, int found

If you prefer Python3:
>>> str(3)
'3'
>>> str(3, errors='replace')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: coercing to str: need bytes, bytearray or buffer-like object, int found

Thursday, September 5, 2013

random failure

>>> random.choice({0:1, 2:3})
1
>>> random.choice({0:1, 2:3})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\random.py", line 274, in choice
    return seq[int(self.random() * len(seq))]  # raises IndexError if seq is empty 
KeyError: 1

Alright pythonauts, why does this fail sometimes and succeed others? :-)

Friday, April 12, 2013

string argument expansion


>>> def variadac(*a): print a
...
>>> variadac(*"abc")
('a', 'b', 'c')

Just a specific example of strings being useful in all the same ways as lists/tuples.