Skip to content

Instantly share code, notes, and snippets.

@juhasch
Last active December 11, 2015 11:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juhasch/4597994 to your computer and use it in GitHub Desktop.
Save juhasch/4597994 to your computer and use it in GitHub Desktop.
Allow to use units with numbers in iPython, e.g. "1n"=1e-9 or "1G"=1e9
# -*- coding: utf-8 -*-
"""
IPython extension for engineering units
See README.txt for usage examples.
Author: Juergen Hasch <python@elbonia.de>
Parts taken from the physics.py extension by Georg Brandl <georg@python.org>
This file has been placed in the public domain.
Allows units to be specified like
1n
or
1 n
or
1e3p
"""
import re
import sys
from math import pi
number = r'(-?[\d0-9.-]+)'
unit = r'([a-df-zA-Z1°µ][a-df-zA-Z0-9°µ/^-]*)'
match = number + r'\s*' + unit
_prefixes = {
'Y': 1.e24 , 'Z': 1.e21, 'E': 1.e18, 'P': 1.e15, 'T': 1.e12,
'G': 1.e9, 'M': 1.e6, 'k': 1.e3, 'h': 1.e2, 'da': 1.e1,
'd': 1.e-1, 'c': 1.e-2, 'm': 1.e-3, 'mu': 1.e-6, 'u': 1.e-6, 'n': 1.e-9,
'p': 1.e-12, 'f': 1.e-15, 'a': 1.e-18, 'z': 1.e-2,
'y': 1.e-24,
}
def replace_inline(mo):
"""Replace unit by quantity
"""
try:
return mo.group(1) + "*" + str(_prefixes[mo.group(2)])
except KeyError:
return mo.group(2)
class QTransformer(object):
"""IPython command line transformer that recognizes and replaces unit
expressions.
"""
# XXX: inheriting from PrefilterTransformer as documented gives TypeErrors,
# but apparently is not needed after all
priority = 99
enabled = True
def transform(self, line, continue_prompt):
line = re.sub(match,replace_inline, line)
return line
q_transformer = QTransformer()
def load_ipython_extension(ip):
ip.prefilter_manager.register_transformer(q_transformer)
print 'Engineering Units extension activated.'
def unload_ipython_extension(ip):
ip.prefilter_manager.unregister_transformer(q_transformer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment