cfdm.Constant¶

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

Bases: object

A container for a constant with context manager support.

The constant value is accessed via the value attribute:

>>> c = cfdm.Constant(1.9)
>>> c.value
1.9

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

>>> c = cfdm.Constant(1.9)
>>> int(c)
1
>>> float(c)
1.9
>>> str(c)
'1.9'
>>> bool(c)
True

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

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

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

>>> c = cfdm.Constant(20)
>>> c.value
20
>>> c * c
400
>>> c * 3
60
>>> 2 - c
-18
>>> c = cfdm.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)
int

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

>>> c = cfdm.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 = cfdm.Constant(20)
>>> d = cfdm.Constant(1)
>>> c.value
20
>>> d.value
1
>>> d < c
True
>>> c != 20
False
>>> 20 == c
True
>>> c = cfdm.Constant('new')
>>> d = cfdm.Constant('old')
>>> c == d
False
>>> c == 'new'
True
>>> c != 3
True
>>> 3 == c
False
>>> c = cfdm.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.

Attributes

Copying¶

Methods

 copy Return a deep copy.

Attributes

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.