Getting different values for Decimal LocalContext Type

Viewed 55

I have written following code to determine type of decimal localcontext:

print('decimal.localcontext() type: ', type(decimal.localcontext()))

Output:

decimal.localcontext() type:  <class 'decimal.ContextManager'> #ContextManager

However, the following code is returning a different output for type:

with decimal.localcontext() as ctx1:
    print(type(ctx1))

Output:

<class 'decimal.Context'>

My question is why the second code snippet is returning decimal.Context instead of decimal.ContextManager

1 Answers

It is because of the 'with statement' functionality. This is part of the decimal.localcontext() function source-code:

def localcontext(ctx=None):
    """Return a context manager for a copy of the supplied..."""
    if ctx is None: ctx = getcontext()
    return _ContextManager(ctx)

As you can see, it returns a decimal.ContextManager object with type:

<class 'decimal.ContextManager'>

As mentioned above, decimal.localcontext() will return a context manager. A context manager is an object that defines the runtime context to be established when executing a with statement. The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code. Context managers are normally invoked using the with statement (described in section The with statement), but can also be used by directly invoking their methods..

Context managers have a __enter__() method that is called when invoking them using 'with statement'. The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any. So in the second case, the type of 'ctx1' is the same as __enter__() method's retrun value.

Related