douglib.utils

Hello!

douglib.utils

Created on Thu 2014-07-10 at 09:51:32 PDT

Contains non-math-related utilities used by douglib such as decorators, colored terminal printing, code timing and progress bars.

class douglib.utils.Borg

Inheritable class.

Having a class that inherits from Borg will allow the class to be instances an arbitrary number of times, with each instance always having the same data.

Any change to a single instance will also change the data in other instances.

Examples

>>> a = Borg()
>>> b = Borg()
>>> repr(a)             
'<utils.Borg object at 0x...>'
>>> repr(b)             
'<utils.Borg object at 0x...>'
>>> a.value = 5
>>> a.value
5
>>> b.value
5

Resistance is futile.

class douglib.utils.CodeTimer(label=None)

A Simple code execution timer.

My attempt at making a simple code timer. The idea is that a user can just call this simple thing, once to start and once again to stop. Upon stopping, it prints out the time delta.

Stop times are printed in Red, while lap times are printed in Cyan. Time differences, as provided by the delta() method, are printed in Yellow.

Parameters:label (string) – An optional label for the timer. Will be displayed upon stopping or lapping the timer.
label

string – The label for the timer instance.

running

bool – Returns True if the timer is currently running.

start_t

datetime.datetime object – The time, in seconds, that the timer was last started, as reported by the built-in time.clock() function. Returns None if the timer has never been started.

stop_t

datetime.datetime object – The time, in seconds, that the timer was last stopped, as reported by the built-in time.clock() function. Returns None if the timer has never been stopped.

diff

float – The time between the the last lap or stop event and the start event. Returns None if the timer has never been lapped or stopped.

prev_t

datetime.datetime object – The timestamp of the previous lap, start, or delta event. Returns None if the timer has never been started.

start(self)

Start the timer.

stop(self, override_label=None)

Stops the timer and prints out the elapsed time, optionally overriding the label temporarily. Returns the elapsed time as a datetime.timedelta object.

reset(self)

Resets the timer and clears the last start_t, stop_t, and diff values.

lap(self, override_label=None)

Prints out the current elapsed time, optionally overrideing the label temporarily. Returns the elapsed time as a datetime.timedelta object.

delta(self, override_label=None)

Prints out the time delta between this call and the previous call of delta, lap, or start. Returns the value as a datetime.timedelta object.

Examples

Basic Usage:

>>> ct = CodeTimer("my_label")
>>> ct.start()
>>> # code to time
>>> ct.stop()           
my_label: 13.2725267063 seconds.

Printing out lap times:

>>> ct = CodeTimer()
>>> ct.start()
>>> for _i in range(3):
...     ct.lap()        
Current Exec: 6.99158129829 seconds.
Current Exec: 6.9916975028 seconds.
Current Exec: 6.99176305405 seconds.
>>> ct.stop()           
Exec time: 18.8153060201 seconds.
delta(override_label=None)

Prints out the time delta between this call and the previous call of delta, lap or start. Returns the value as a datetime.timedelta object.

lap(override_label=None)

Returns and prints out the current timer value.

reset()

Reset the timer.

start()

Start the timer

stop(override_label=None)

Stop the timer and return and print the delta with label.

exception douglib.utils.DougLibError

Generic Exception Class for douglib

exception douglib.utils.ObsoleteError(value=None)

Custom error for reporting obsolete functions

exception douglib.utils.RangeError(value)

A custom exception for reporting out-of-range errors

class douglib.utils.Singleton

Inheritable class.

Having a class that inherits from Singleton will allow the class to be instanced only once. Any subsequent instancing will actually return the originally instanced memory location.

This is slighly different from Borg in that only a single memory location (identity) will be used. With Borg, multiple identities are allowed, but each identity has the same state.

Examples

>>> a = Singleton()
>>> b = Singleton()
>>> repr(a)             
'<utils.Singleton object at 0x...>'
>>> repr(b)             
'<utils.Singleton object at 0x...>'
>>> repr(a) == repr(b)
True

Note how the memory location is the same.

douglib.utils.cprint(text, color, end='\n')

Prints text as the specified color. Accepts RGB, CMYK, and White.

douglib.utils.hexvers_to_str(hexvers=None)

Converts a sys.hexversion output to a standard version string.

The sys.hexversion output is of the form 0x030401a5 03 is the major 04 is the minor 01 is the fix a is the release level 5 is the release serial

If hexvers is not defined, then it imports sys.hexversion and runs that.

Parameters:hexvers (int, optional) – The integer representation of a hex-encoded version number. Defaults to None, which pulls the current python version.
Returns:
Return type:The version number representated as a string

Examples

>>> hexvers_to_str()            
a
>>> hexvers_to_str(34014960)
'2.7.6.f0'
douglib.utils.print_and_exec(code)

Prints out a formatted code line and executes it. WARNING: UNSAFE

douglib.utils.print_input(text)

Prints text formatted as a python input by putting “>>> ” in front and making sure that a newline is at the end. Also colors red.

douglib.utils.print_red(text)

Prints text as bright red

douglib.utils.print_section(text, style=3)

Prints out a line in varoius section header styles. Automatically prepends newline char(s) to text for sections and major sections

Notes

0:
subsubsection, denoted by --- subsubsection --- in magenta.
1:
subsection, denoted by ----- subsection ----- in cyan.
2:
section, denoted by ---------- section ---------- in yellow
3:
major section, denoted by ========== MAJOR SECTION ========== in green. Text is forced to uppercase.
douglib.utils.progress_bar(count, size, bar_size=10)

A simple terminal progress bar.

Insert into the loop that you want to monitor progrss on and once after the loop is completed (with count = size)

Parameters:
  • count (int) – ieration that you want to display.
  • size (int) – maximum number of iterations that the loop will go through
  • barLen (int) – Length of the progress bar.

Notes

  1. If count = length, then the bar display will be persistant
  2. I’d like for it to only update if percent_complete changes, but I’m not quite sure how to do that yet.
  3. Does not like to work properly in Spyder. This is because the Spyder terminal doesn’t recognize the \r special character.

Example

size = 1000
n = 0
bar_size = 17
for item in range(size):
    time.sleep(0.02)
    progress_bar(n, size, bar_size)
    n += 1
progress_bar(n, size, bar_size)
douglib.utils.try_again(funcs, args, kwargs, errors, raise_error=None)

Trys multiple functions, arguements, or exceptions until one succeeds. Returns the value of the succeeding function.

Parameters:
  • funcs (list of functions) – List of functions to try, in order.
  • args (list of arguments) – List of arguments for each function.
  • kwargs (list of dicts) – Dictionary of keyword arguments for each function.
  • errors (list of exceptions) – List of errors to catch in the Except clause. If a list of tuples, then the tuple of errors will be caught for a given iteration.
  • raise_error (exception, optional) – The exception to raise if no attempt passes. If None, then raises the most recent exception as RuntimeError
Returns:

The result of whichever function succeeded.

Return type:

retval

Notes

funcs, args, kwargs, and errors must all have the same length.

Examples

>>> def my_func(a):
...     if a == 3:
...         return a
...     else:
...         raise ValueError
>>> errors = [ValueError, ValueError, ValueError]
>>> funcs = [my_func] * 3
>>> args = [1, 2, 3]
>>> kwargs = [None] * 3
>>> try_again(funcs, args, kwargs, errors, OSError("something"))
3
douglib.utils.unjoin_path(path)

Returns a list of all folders that make up PATH. This is the inverse of os.path.join().

os.path.join(*unjoin_path(path)) == path

Note the “splat” (list unpacking) operator (asterisk)

Examples

>>> path = "C:\path1\path2\hello.txt"
>>> my_split_path = unjoin_path(path)
>>> my_split_path
['C:\\', 'path1', 'path2', 'hello.txt']
>>> path == os.path.join(*my_split_path)
True