cf.Constant


class cf.Constant(value, _func=None)[source]

Bases: cfdm.functions.Constant

A container for a constant with context manager support.

The constant value is accessed via the value attribute:

>>> c = cf.Constant(1.2)
>>> c.value
1.2

Conversion to int, float, str and bool is with the usual built-in functions:

>>> c = cf.Constant(1.2)
>>> int(c)
1
>>> float(c)
1.2
>>> str(c)
'1.2'
>>> bool(c)
True

Augmented arithmetic assignments (+=, -=, *=, /=, //=) update Constant objects in-place:

>>> c = cf.Constant(20)
>>> c.value
20
>>> c /= 2
>>> c
<CF Constant: 10.0>
>>> c += c
<CF Constant: 20.0>
>>> c = cf.Constant('New_')
>>> c *= 2
<CF Constant: 'New_New_'>

Binary arithmetic operations (+, -, *, /, //) are equivalent to the operation acting on the Constant object’s value attribute:

>>> c = cf.Constant(20)
>>> c.value
20
>>> c * c
400
>>> c * 3
60
>>> 2 - c
-18
>>> c = cf.Constant('New_')
>>> c * 2
'New_New_'

Care is required when the right hand side operand is a numpy array

>>> c * numpy.array([1, 2, 3])
array([20, 40, 60])
>>> d = numpy.array([1, 2, 3]) * c
>>> d
array([10, 20, 30], dtype=object)
>>> type(d[0])
int

Unary arithmetic operations (+, -, abs) are equivalent to the operation acting on the Constant object’s value attribute:

>>> c = cf.Constant(-20)
>>> c.value
-20
>>> -c
20
>>> abs(c)
20
>>> +c
-20

Rich comparison operations are equivalent to the operation acting on the Constant object’s value attribute:

>>> c = cf.Constant(20)
>>> d = cf.Constant(1)
>>> c.value
20
>>> d.value
1
>>> d < c
True
>>> c != 20
False
>>> 20 == c
True
>>> c = cf.Constant('new')
>>> d = cf.Constant('old')
>>> c == d
False
>>> c == 'new'
True
>>> c != 3
True
>>> 3 == c
False
>>> c = cf.Constant()
>>> c < numpy.array([10, 20, 30])
array([False, False,  True])
>>> numpy.array([10, 20, 30]) >= c
array([False,  True,  True])

Constant instances are hashable.

Context manager

The Constant instance can be used as a context manager that upon exit executes the function defined by the _func attribute, with the value attribute as an argument. For example, the Constant instance c would execute c._func(c.value) upon exit.

New in version (cfdm): 1.8.8.0

Initialisation

Parameters
value:

A value for the constant.

_func: function, optional

A function that that is executed upon exit from a context manager, that takes the value parameter as its argument.

Inspection

Attributes

value

Miscellaneous

Methods

copy

Return a deep copy.

Attributes

_func

Special

Methods

__deepcopy__

Called by the copy.deepcopy function.

__enter__

Enter the runtime context.

__exit__

Exit the runtime context.

__repr__

Called by the repr built-in function.

__str__

Called by the str built-in function.