eval2

Module Contents

eval2.eval2(obj, t=None, ps=False, useDecimal=True)

This function will convert a string into the appropriate data type.

This function is similar in concept to eval(), although it does not inherit from it. It produces different types than eval() to suit the needs of inpRW.

If ps is True, eval2() will return an inpString, inpInt, or inpDecimal as appropriate. If ps is False, eval2() will return str, int, and float (if useDecimal = False) or Decimal (if useDecimal = True).

If t is not set, eval2() will first try to convert obj to an integer type, and then a decimal type, and then finally a string type. If the underlying type of obj is known ahead of time, t can be set to this type to for better performance. However, if t is specified incorrectly, obj will be treated as a string. You should specify t when you are confident of the underlying type, as the function will run much faster.

Here are some example scenarios, first using ps = True:

>>> from eval2 import eval2
>>> eval2(' "Nodeset (1)"', t=str, ps=True)
inpString(' "Nodeset (1)"', False)
>>> eval2(' 100 ', t=int, ps=True)
inpInt(' 100 ')
>>> eval2(' 1.234E1 ', t=float, ps=True)
inpDecimal(' 1.234E1 ')

If we set ps and useDecimal to False, we get the built-in types:

>>> eval2(' "Nodeset (1)"', t=str, useDecimal=False)
' "Nodeset (1)"'
>>> eval2(' 100 ', t=int, useDecimal=False)
100
>>> eval2(' 1.234E1 ', t=float, useDecimal=False)
12.34

useDecimal = True only applies to floating point numbers, which will instead be evaluated to Decimal:

>>> eval2(' 1.234E1 ', t=float)
Decimal('12.34')

Not specifying t is slower, but eval2() will find the best type:

>>> eval2(' 1.23', ps=True)
inpDecimal(' 1.23')

If we specify t incorrectly, we will get a string type as the output:

>>> eval2(' 1.23', t=int, ps=True)
inpString(' 1.23', False)
Parameters:
  • obj (str) – A string representation of the object to evaluate.

  • t (str or float or int) – The expected type of obj. Pass in the type, not an object of the type.

  • ps (bool) – Preserve Spacing. If True, inpInt, inpDecimal, and inpString objects will be created. Defaults to False.

  • useDecimal (bool) – If True, float-like objects will instead be evaluated to Decimal objects. Defaults to True.

Returns:

str, inpString, int, inpInt, Decimal, or inpDecimal