pyrevit.coreutils.pyutils

Helper functions for python.

Example

>>> from pyrevit.coreutils import pyutils
>>> pyutils.safe_cast('string', int, 0)
class pyrevit.coreutils.pyutils.DefaultOrderedDict(default_factory=None, *a, **kw)

Bases: collections.OrderedDict

Ordered dictionary with default type.

This is similar to defaultdict and maintains the order of items added to it so in that regards it functions similar to OrderedDict.

Example

>>> from pyrevit.coreutils import pyutils
>>> od = pyutils.DefaultOrderedDict(list)
>>> od['A'] = [1, 2, 3]
>>> od['B'] = [4, 5, 6]
>>> od['C'].extend([7, 8, 9])
>>> for k, v in od.items():
...     print(k, v)
('A', [1, 2, 3])
('B', [4, 5, 6])
('C', [7, 8, 9])
copy()

Copy the dictionary.

pyrevit.coreutils.pyutils.almost_equal(a, b, rnd=5)

Check if two numerical values almost equal

Parameters:
  • a (float) – value a
  • b (float) – value b
  • rnd (int, optional) – n digits after comma. Defaults to 5.
Returns:

True if almost equal

Return type:

bool

pyrevit.coreutils.pyutils.compare_lists(x, y)

Compare two lists.

See: https://stackoverflow.com/a/10872313/2350244

Parameters:
  • x (list) – first list
  • y (list) – second list
pyrevit.coreutils.pyutils.isnumber(token)

Verify if given string token is int or float.

Parameters:token (str) – string value
Returns:True of token is int or float
Return type:bool

Example

>>> isnumber('12.3')
True
pyrevit.coreutils.pyutils.merge(d1, d2)

Merge d2 into d1.

d2 dict values are recursively merged into d1 dict values other d2 values are added to d1 dict values with the same key new d2 values are added to d1 d2 values override other d1 values

Parameters:
  • d1 (dict) – dict to be updated
  • d2 (dict) – dict to be merge into d1
Returns:

updated d1

Return type:

dict

Example

>>> d1 = {1: 1, 2: "B"    , 3: {1:"A", 2:"B"}, 4: "b"  , 5: ["a", "b"]}
>>> d2 = {1: 1, 2: {1:"A"}, 3: {1:"S", 3:"C"}, 4: ["a"], 5: ["c"]}
>>> merge(d1, d2)
... { 1:1,
...   2:{1:'A', 2:'B'},
...   3:{1:'S', 2:'B', 3:'C'},
...   4:['a','b'],
...   5: ['c', 'a', 'b']
... }
pyrevit.coreutils.pyutils.pairwise(iterable, step=2)

Iterate through items in pairs.

Parameters:
  • iterable (iterable) – any iterable object
  • step (int) – number of steps to move when making pairs
Returns:

list of pairs

Return type:

iterable

Example

>>> pairwise([1, 2, 3, 4, 5])
[(1, 2), (3, 4)]    # 5 can not be paired
>>> pairwise([1, 2, 3, 4, 5, 6])
[(1, 2), (3, 4), (5, 6)]
>>> pairwise([1, 2, 3, 4, 5, 6], step=1)
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
pyrevit.coreutils.pyutils.safe_cast(val, to_type, default=None)

Convert value to type gracefully.

This method basically calls to_type(value) and returns the default if exception occurs.

Parameters:
  • val (any) – value to be converted
  • to_type (type) – target type
  • default (any) – value to rerun on conversion exception

Example

>>> safe_cast('name', int, default=0)
0