Enforce precision in decimal python
<p>In some environments, exact decimals (numerics, numbers...) are defined with <code>scale</code> and <code>precision</code>, with scale being all significant numbers, and precision being those right of the decimal point. I want to use python's decimal implementation to raise an error, if the precision of the casted string is higher than the one defined by the implementation.</p>

<p>So for example, I have an environment, where <code>scale = 4</code> and <code>precision = 2</code>.
How can I achieve these commands to raise an error, because their precision exceeds that of the implementation?</p>

<pre><code>decimals.Decimal('1234.1')
decimals.Decimal('0.123')
</code></pre>

<p>The closest I could find in the <code>decimal</code> <a href="https://docs.python.org/2/library/decimal.html" rel="nofollow">module</a> is in the <code>context.create_decimal_from_float</code> example, using the <code>Inexact</code> <a href="https://docs.python.org/2/library/decimal.html#decimal.Inexact" rel="nofollow">context trap</a>  :</p>

<pre><code>&gt;&gt;&gt; context = Context(prec=5, rounding=ROUND_DOWN)
&gt;&gt;&gt; context.create_decimal_from_float(math.pi)
Decimal('3.1415')
&gt;&gt;&gt; context = Context(prec=5, traps=[Inexact])
&gt;&gt;&gt; context.create_decimal_from_float(math.pi)
Traceback (most recent call last):
    ...
Inexact: None
</code></pre>

<p>The decimal module doesn't seem to have the concept of scale. It's precision is basically your scale + your precision. </p>

python decimal precision