nustack
ReferenceNu STDmem

refs.std

Dict-substrate refs for standard-library value types.

Module nustd.mem.refs.std.

Dict-substrate refs for standard-library value types.

Each ref is a typed slot in the nested-dict substrate whose stored form differs from its domain type, so it overrides store (domain -> storage) and coerce (storage -> domain). The value interface comes from mixing in the matching nustd Form, exactly as IntRef mixes in Int.

  • Decimal / Fraction / complex / Path / UUID: str
  • date / datetime / time / timezone: str (ISO / offset)
  • BasisPoint: int (raw basis points)
  • Percentage: float (raw percentage)
  • timedelta: float (total seconds)
NameSortCallMeaning
BasisPointRefrefBasisPointRef(address, parent_ref=None, owner_shape=None)A BasisPoint slot in the dict substrate, stored as a raw int of bps.
ComplexRefrefComplexRef(address, parent_ref=None, owner_shape=None)A complex slot in the dict substrate, stored as str(complex).
DateRefrefDateRef(address, parent_ref=None, owner_shape=None)A date slot in the dict substrate, stored as an ISO string.
DatetimeRefrefDatetimeRef(address, parent_ref=None, owner_shape=None)A datetime slot in the dict substrate, stored as an ISO string.
DecimalRefrefDecimalRef(address, parent_ref=None, owner_shape=None)A Decimal slot in the dict substrate, stored as its exact string form.
FractionRefrefFractionRef(address, parent_ref=None, owner_shape=None)A Fraction slot in the dict substrate, stored as "numerator/denom".
PathRefrefPathRef(address, parent_ref=None, owner_shape=None)A filesystem path slot in the dict substrate, stored as a plain str.
PercentageRefrefPercentageRef(address, parent_ref=None, owner_shape=None)A Percentage slot in the dict substrate, stored as a raw float.
TimeRefrefTimeRef(address, parent_ref=None, owner_shape=None)A time-of-day slot in the dict substrate, stored as an ISO string.
TimedeltaRefrefTimedeltaRef(address, parent_ref=None, owner_shape=None)A timedelta slot in the dict substrate, stored as total seconds.
TimezoneRefrefTimezoneRef(address, parent_ref=None, owner_shape=None)A fixed-offset timezone slot, stored as its UTC±HH:MM string.
UUIDRefrefUUIDRef(address, parent_ref=None, owner_shape=None)A UUID slot in the dict substrate, stored as its hyphenated string.

BasisPointRef

A BasisPoint slot in the dict substrate, stored as a raw int of bps.

BasisPointRef(address, parent_ref=None, owner_shape=None)

Path nustd.mem.BasisPointRef. Kind Ref, sort ref, cardinality scalar.

Notes

  • Stored as the bps count itself (250 for 2.5%), an int, so no rounding creeps in the way a stored float would.

Example

from nustd.fin import PyBasisPoint
class Fees(nu.Shape):
    taker = nustd.mem.BasisPointRef.slot()
data = {}
ctx = nu.Context().bind(dict, data, Fees)
_ = nu.run(Fees.taker.set(PyBasisPoint(250)), ctx)
data
nu.run(Fees.taker.apply(1000), ctx)[0]
{'taker': 250}
25.0

Methods

.set(value)

Write a BasisPoint into the slot as a raw int of bps.

Builds SetCmd.

Arguments

NameTypeDefaultMeaning
valueArg[PyBasisPoint | int]

Notes

  • A plain Python value is converted at tree-build time; a Nu operand gets a ToInt node instead.

Undocumented: example.

Inherited methods

From nu.domains.shape.forms.item.MutableItemForm:

CallBuildsMeaning
.erase()EraseBuild an Erase.
.init(value)IfDoSet value iff the leaf is currently missing.

From nu.domains.shape.forms.item.ItemForm:

CallBuildsMeaning
.exists()ExistsBuild an Exists query.
.missing()MissingBuild a Missing query.

From nustd.fin.forms.BasisPoint:

CallBuildsMeaning
BasisPointRef.of(value)BasisPointA basis-point count from a raw int: BasisPoint(500).
BasisPointRef.from_pct(pct)BasisPointFrom a percentage: BasisPoint.from_pct(5.0) -> 500 bps.
BasisPointRef.from_dec(dec)BasisPointFrom a decimal ratio: BasisPoint.from_dec(0.05) -> 500 bps.
.to_pct()FloatThe percentage (500 bps -> 5.0).
.to_dec()FloatThe decimal ratio (500 bps -> 0.05).
.to_int()IntThe raw basis-point count.
.apply(amount)FloatThis many basis points of amount.
.add_to(amount)Floatamount grown by these basis points.
.sub_from(amount)Floatamount reduced by these basis points.
a + bBasisPoint
a - bBasisPoint
a * bBasisPoint
a / bBasisPoint
a // bBasisPoint
a > bBool
a < bBool
a >= bBool
a <= bBool
.eq(other)BoolWhether two basis-point counts are equal.
.ne(other)BoolWhether two basis-point counts differ.

From nu.lang.forms.Form:

CallBuildsMeaning
.is_empty()BoolTrue if this Form yields the EMPTY sentinel.
.is_invalid()BoolTrue if this Form yields the INVALID sentinel.
.is_sentinel()BoolTrue if this Form yields either sentinel (EMPTY or INVALID).
.not_empty()BoolTrue if this Form does not yield EMPTY.
.not_invalid()BoolTrue if this Form does not yield INVALID.

ComplexRef

A complex slot in the dict substrate, stored as str(complex).

ComplexRef(address, parent_ref=None, owner_shape=None)

Path nustd.mem.ComplexRef. Kind Ref, sort ref, cardinality scalar.

Notes

  • str(complex) is what complex(str) reads back, so the value round-trips exactly, parentheses and all.

Example

class Signal(nu.Shape):
    amp = nustd.mem.ComplexRef.slot()
data = {}
ctx = nu.Context().bind(dict, data, Signal)
_ = nu.run(Signal.amp.set(complex(1, 2)), ctx)
data
nu.run(Signal.amp.real(), ctx)[0]
{'amp': '(1+2j)'}
1.0

Methods

.set(value)

Write a complex into the slot as its string form.

Builds SetCmd.

Arguments

NameTypeDefaultMeaning
valueArg[complex | str]

Notes

  • A plain Python value is serialised at tree-build time; a Nu operand gets a ToStr node instead.

Undocumented: example.

Inherited methods

From nu.domains.shape.forms.item.MutableItemForm:

CallBuildsMeaning
.erase()EraseBuild an Erase.
.init(value)IfDoSet value iff the leaf is currently missing.

From nu.domains.shape.forms.item.ItemForm:

CallBuildsMeaning
.exists()ExistsBuild an Exists query.
.missing()MissingBuild a Missing query.

From nustd.cmath.forms.complex:

CallBuildsMeaning
ComplexRef.of(real=0, imag=0)complexBuild a complex number: complex(real, imag).
.real()FloatThe real part.
.imag()FloatThe imaginary part.
.conjugate()complexThe complex conjugate (negates the imaginary part).
a + bcomplex
a - bcomplex
a * bcomplex
a / bcomplex
a ** bcomplex
-acomplex
+acomplex
abs(a)Float
.eq(other)BoolWhether two complex numbers are equal.
.ne(other)BoolWhether two complex numbers differ.

From nu.lang.forms.Form:

CallBuildsMeaning
.is_empty()BoolTrue if this Form yields the EMPTY sentinel.
.is_invalid()BoolTrue if this Form yields the INVALID sentinel.
.is_sentinel()BoolTrue if this Form yields either sentinel (EMPTY or INVALID).
.not_empty()BoolTrue if this Form does not yield EMPTY.
.not_invalid()BoolTrue if this Form does not yield INVALID.

DateRef

A date slot in the dict substrate, stored as an ISO string.

DateRef(address, parent_ref=None, owner_shape=None)

Path nustd.mem.DateRef. Kind Ref, sort ref, cardinality scalar.

Notes

  • Stored as YYYY-MM-DD, so the data dict stays readable and sorts by date lexicographically.
  • A datetime written here is stringified whole, and reading it back as a date then fails on the time part; write d.date().

Example

from datetime import date
class Trade(nu.Shape):
    day = nustd.mem.DateRef.slot()
data = {}
ctx = nu.Context().bind(dict, data, Trade)
_ = nu.run(Trade.day.set(date(2024, 1, 2)), ctx)
data
nu.run(Trade.day.year(), ctx)[0]
{'day': '2024-01-02'}
2024

Methods

.set(value)

Write a date into the slot as an ISO string.

Builds SetCmd.

Arguments

NameTypeDefaultMeaning
valueArg[date | str]

Notes

  • A date is formatted at tree-build time and anything else is passed through str; a Nu operand gets a ToStr node, so what it yields has to be something date.fromisoformat accepts.

Undocumented: example.

Inherited methods

From nu.domains.shape.forms.item.MutableItemForm:

CallBuildsMeaning
.erase()EraseBuild an Erase.
.init(value)IfDoSet value iff the leaf is currently missing.

From nu.domains.shape.forms.item.ItemForm:

CallBuildsMeaning
.exists()ExistsBuild an Exists query.
.missing()MissingBuild a Missing query.

From nustd.datetime.forms.date:

CallBuildsMeaning
DateRef.of(year, month, day)dateBuild a date: date(year, month, day).
DateRef.today()dateToday's date: date.today().
DateRef.from_iso(value)dateParse an ISO date string: date.fromisoformat(s).
DateRef.from_ordinal(value)dateFrom a proleptic Gregorian ordinal: date.fromordinal(n).
DateRef.from_timestamp(value)dateFrom a POSIX timestamp: date.fromtimestamp(t).
.year()IntThe year.
.month()IntThe month (1..12).
.day()IntThe day of the month (1..31).
.weekday()IntThe day of week, Monday=0.
.isoweekday()IntThe day of week, Monday=1.
.toordinal()IntThe proleptic Gregorian ordinal.
.isoformat()StrThe date as an ISO string (YYYY-MM-DD).
.ctime()StrThe date as a C-style string.
.strftime(fmt)StrFormat the date with a strftime pattern.
.replace(year=None, month=None, day=None)dateA copy with the given components replaced.
a + bdate
a - bdate | timedelta
a > bBool
a < bBool
a >= bBool
a <= bBool
.eq(other)BoolWhether two dates are equal.
.ne(other)BoolWhether two dates differ.

From nu.lang.forms.Form:

CallBuildsMeaning
.is_empty()BoolTrue if this Form yields the EMPTY sentinel.
.is_invalid()BoolTrue if this Form yields the INVALID sentinel.
.is_sentinel()BoolTrue if this Form yields either sentinel (EMPTY or INVALID).
.not_empty()BoolTrue if this Form does not yield EMPTY.
.not_invalid()BoolTrue if this Form does not yield INVALID.

DatetimeRef

A datetime slot in the dict substrate, stored as an ISO string.

DatetimeRef(address, parent_ref=None, owner_shape=None)

Path nustd.mem.DatetimeRef. Kind Ref, sort ref, cardinality scalar.

Notes

  • Whatever tzinfo the value carries rides along in the ISO string and comes back with it; a naive datetime stays naive.
  • A number found in the slot is read as a UTC epoch timestamp, so a dict filled from a feed that stores epochs still lifts.

Example

from datetime import datetime
class Event(nu.Shape):
    at = nustd.mem.DatetimeRef.slot()
data = {}
ctx = nu.Context().bind(dict, data, Event)
_ = nu.run(Event.at.set(datetime(2024, 1, 2, 3, 4)), ctx)
data
nu.run(Event.at.hour(), ctx)[0]
{'at': '2024-01-02T03:04:00'}
3

Methods

.set(value)

Write a datetime into the slot as an ISO string.

Builds SetCmd.

Arguments

NameTypeDefaultMeaning
valueArg[datetime | str]

Notes

  • A datetime is formatted at tree-build time and anything else is passed through str; a Nu operand gets a ToStr node.

Undocumented: example.

Inherited methods

From nu.domains.shape.forms.item.MutableItemForm:

CallBuildsMeaning
.erase()EraseBuild an Erase.
.init(value)IfDoSet value iff the leaf is currently missing.

From nu.domains.shape.forms.item.ItemForm:

CallBuildsMeaning
.exists()ExistsBuild an Exists query.
.missing()MissingBuild a Missing query.

From nustd.datetime.forms.datetime:

CallBuildsMeaning
DatetimeRef.of(year, month, day, hour=0, minute=0, second=0, microsecond=0)datetimeBuild a datetime: datetime(year, month, day, hour, ...).
DatetimeRef.now(tz=None)datetimeThe current local (or tz) datetime: datetime.now(tz).
DatetimeRef.from_iso(value)datetimeParse an ISO datetime string: datetime.fromisoformat(s).
DatetimeRef.from_timestamp(value, tz=None)datetimeFrom a POSIX timestamp: datetime.fromtimestamp(ts, tz).
DatetimeRef.combine(date_value, time_value)datetimeCombine a date and a time: datetime.combine(date, time).
.year()IntThe year.
.month()IntThe month (1..12).
.day()IntThe day of the month (1..31).
.hour()IntThe hour (0..23).
.minute()IntThe minute (0..59).
.second()IntThe second (0..59).
.microsecond()IntThe microsecond (0..999999).
.weekday()IntThe day of week, Monday=0.
.isoweekday()IntThe day of week, Monday=1.
.timestamp()FloatThe POSIX timestamp.
.isoformat()StrThe datetime as an ISO string.
.strftime(fmt)StrFormat the datetime with a strftime pattern.
.date()dateThe date part.
.time()timeThe time part.
.replace(year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None)datetimeA copy with the given components replaced.
a + bdatetime
a - bdatetime | timedelta
a > bBool
a < bBool
a >= bBool
a <= bBool
.eq(other)BoolWhether two datetimes are equal.
.ne(other)BoolWhether two datetimes differ.

From nu.lang.forms.Form:

CallBuildsMeaning
.is_empty()BoolTrue if this Form yields the EMPTY sentinel.
.is_invalid()BoolTrue if this Form yields the INVALID sentinel.
.is_sentinel()BoolTrue if this Form yields either sentinel (EMPTY or INVALID).
.not_empty()BoolTrue if this Form does not yield EMPTY.
.not_invalid()BoolTrue if this Form does not yield INVALID.

DecimalRef

A Decimal slot in the dict substrate, stored as its exact string form.

DecimalRef(address, parent_ref=None, owner_shape=None)

Path nustd.mem.DecimalRef. Kind Ref, sort ref, cardinality scalar.

Notes

  • The stored string is str(Decimal), so precision and trailing zeros survive the round trip where a float would lose them.
  • A Decimal already sitting in the data dict is read as it is, so a dict populated by hand works either way.

Example

from decimal import Decimal
class Quote(nu.Shape):
    price = nustd.mem.DecimalRef.slot()
data = {}
ctx = nu.Context().bind(dict, data, Quote)
_ = nu.run(Quote.price.set(Decimal("1.250")), ctx)
data
nu.run(Quote.price, ctx)[0]
{'price': '1.250'}
Decimal('1.250')

Methods

.set(value)

Write a Decimal into the slot as its string form.

Builds SetCmd.

Arguments

NameTypeDefaultMeaning
valueArg[Decimal | str]

Notes

  • A plain Python value is serialised now, at tree-build time; a Nu operand gets a ToStr node instead, serialised when the tree runs.

Undocumented: example.

Inherited methods

From nu.domains.shape.forms.item.MutableItemForm:

CallBuildsMeaning
.erase()EraseBuild an Erase.
.init(value)IfDoSet value iff the leaf is currently missing.

From nu.domains.shape.forms.item.ItemForm:

CallBuildsMeaning
.exists()ExistsBuild an Exists query.
.missing()MissingBuild a Missing query.

From nustd.decimal.forms.Decimal:

CallBuildsMeaning
DecimalRef.of(value)DecimalBuild a decimal from a string or int, exactly: Decimal(str(value)).
DecimalRef.from_float(value)DecimalFrom a binary float: Decimal.from_float(f) (carries float error).
a + bDecimal
a - bDecimal
a * bDecimal
a / bDecimal
a // bDecimal
a % bDecimal
a ** bDecimal
-aDecimal
abs(a)Decimal
+aDecimal
.quantize(exp)DecimalRound to the exponent of exp (e.g. Decimal.of("0.01")).
.normalize()DecimalA canonical form with trailing zeros removed.
.to_integral_value()DecimalThe value rounded to the nearest integer, kept as a Decimal.
.sqrt()DecimalThe square root.
.exp()DecimalThe exponential, e ** self.
.ln()DecimalThe natural logarithm.
.log10()DecimalThe base-10 logarithm.
.compare(other)DecimalDecimal('-1') / '0' / '1' for self <, ==, > other.
.copy_abs()DecimalThe absolute value (context-free, no rounding).
.copy_negate()DecimalThe negation (context-free, no rounding).
.adjusted()IntThe adjusted exponent after shifting out the coefficient's digits.
.as_integer_ratio()TupleThe exact value as a (numerator, denominator) pair of ints.
.is_finite()BoolWhether the value is finite (not infinite, not NaN).
.is_infinite()BoolWhether the value is positive or negative infinity.
.is_nan()BoolWhether the value is a NaN (quiet or signaling).
.is_zero()BoolWhether the value is zero (positive or negative).
.is_signed()BoolWhether the sign bit is set (negative, including -0).
a > bBool
a < bBool
a >= bBool
a <= bBool
.eq(other)BoolWhether two decimals are equal in value.
.ne(other)BoolWhether two decimals differ in value.

From nu.lang.forms.Form:

CallBuildsMeaning
.is_empty()BoolTrue if this Form yields the EMPTY sentinel.
.is_invalid()BoolTrue if this Form yields the INVALID sentinel.
.is_sentinel()BoolTrue if this Form yields either sentinel (EMPTY or INVALID).
.not_empty()BoolTrue if this Form does not yield EMPTY.
.not_invalid()BoolTrue if this Form does not yield INVALID.

FractionRef

A Fraction slot in the dict substrate, stored as "numerator/denom".

FractionRef(address, parent_ref=None, owner_shape=None)

Path nustd.mem.FractionRef. Kind Ref, sort ref, cardinality scalar.

Notes

  • The stored string is str(Fraction), already in lowest terms, so the exact ratio round-trips.

Example

from fractions import Fraction
class Split(nu.Shape):
    share = nustd.mem.FractionRef.slot()
data = {}
ctx = nu.Context().bind(dict, data, Split)
_ = nu.run(Split.share.set(Fraction(3, 4)), ctx)
data
nu.run(Split.share, ctx)[0]
{'share': '3/4'}
Fraction(3, 4)

Methods

.set(value)

Write a Fraction into the slot as its string form.

Builds SetCmd.

Arguments

NameTypeDefaultMeaning
valueArg[Fraction | str]

Notes

  • A plain Python value is serialised at tree-build time; a Nu operand gets a ToStr node instead.

Undocumented: example.

Inherited methods

From nu.domains.shape.forms.item.MutableItemForm:

CallBuildsMeaning
.erase()EraseBuild an Erase.
.init(value)IfDoSet value iff the leaf is currently missing.

From nu.domains.shape.forms.item.ItemForm:

CallBuildsMeaning
.exists()ExistsBuild an Exists query.
.missing()MissingBuild a Missing query.

From nustd.fractions.forms.Fraction:

CallBuildsMeaning
FractionRef.of(numerator, denominator=1)FractionBuild a fraction from numerator and denominator: Fraction(n, d).
FractionRef.from_float(value)FractionThe exact fraction equal to a float: Fraction.from_float(f).
FractionRef.from_decimal(value)FractionThe exact fraction equal to a Decimal: Fraction.from_decimal(d).
FractionRef.from_str(value)FractionParse a fraction string: Fraction(s) (e.g. "3/4", "1.5").
.numerator()IntThe numerator (in lowest terms).
.denominator()IntThe denominator (in lowest terms, always positive).
.limit_denominator(max_denominator=1000000)FractionThe closest fraction with denominator at most max_denominator.
.as_integer_ratio()TupleThe (numerator, denominator) pair as a tuple.
a + bFraction
a - bFraction
a * bFraction
a / bFraction
a // bFraction
a % bFraction
a ** bFraction
-aFraction
abs(a)Fraction
+aFraction
a > bBool
a < bBool
a >= bBool
a <= bBool
.eq(other)BoolWhether two fractions are equal.
.ne(other)BoolWhether two fractions differ.

From nu.lang.forms.Form:

CallBuildsMeaning
.is_empty()BoolTrue if this Form yields the EMPTY sentinel.
.is_invalid()BoolTrue if this Form yields the INVALID sentinel.
.is_sentinel()BoolTrue if this Form yields either sentinel (EMPTY or INVALID).
.not_empty()BoolTrue if this Form does not yield EMPTY.
.not_invalid()BoolTrue if this Form does not yield INVALID.

PathRef

A filesystem path slot in the dict substrate, stored as a plain str.

PathRef(address, parent_ref=None, owner_shape=None)

Path nustd.mem.PathRef. Kind Ref, sort ref, cardinality scalar.

Notes

  • Lifted to a PurePath, so the flavour follows the machine reading it: the same stored string is a PurePosixPath on Linux and a PureWindowsPath on Windows.
  • Pure means no filesystem: the calls take the path apart and put it back together, they never touch disk.

Example

from pathlib import PurePath
class Cfg(nu.Shape):
    root = nustd.mem.PathRef.slot()
data = {}
ctx = nu.Context().bind(dict, data, Cfg)
_ = nu.run(Cfg.root.set(PurePath("/srv/app.toml")), ctx)
data
nu.run(Cfg.root.name(), ctx)[0]
{'root': '/srv/app.toml'}
'app.toml'

Methods

.set(value)

Write a path into the slot as a plain string.

Builds SetCmd.

Arguments

NameTypeDefaultMeaning
valueArg[PurePath | str]

Notes

  • A plain Python value goes through str at tree-build time; a Nu operand gets a ToStr node.

Undocumented: example.

Inherited methods

From nu.domains.shape.forms.item.MutableItemForm:

CallBuildsMeaning
.erase()EraseBuild an Erase.
.init(value)IfDoSet value iff the leaf is currently missing.

From nu.domains.shape.forms.item.ItemForm:

CallBuildsMeaning
.exists()ExistsBuild an Exists query.
.missing()MissingBuild a Missing query.

From nustd.pathlib.forms.Path:

CallBuildsMeaning
PathRef.of()PathBuild a path from segments: PurePath(*segments).
PathRef.cwd()PathThe current working directory: Path.cwd().
PathRef.home()PathThe user's home directory: Path.home().
.name()StrThe final component (filename).
.stem()StrThe final component without its suffix.
.suffix()StrThe file extension of the final component (including the dot).
.suffixes()ListAll file extensions of the final component.
.parts()TupleThe path's components as a tuple.
.parent()PathThe logical parent of the path.
.root()StrThe root (e.g. / on POSIX).
.anchor()StrThe concatenation of drive and root.
.drive()StrThe drive (empty on POSIX).
.with_name(name)PathA copy with the final component's name replaced.
.with_stem(stem)PathA copy with the final component's stem replaced.
.with_suffix(suffix)PathA copy with the final component's suffix replaced.
.joinpath()PathJoin one or more components onto the path.
.relative_to(other)PathThe path relative to other.
a / bPathJoin with /: Path.of("a") / "b".
.as_posix()StrThe path as a string with forward slashes.
.as_uri()StrThe path as a file:// URI (requires an absolute path).
.match(pattern)BoolWhether the path matches a glob pattern.
.is_absolute()BoolWhether the path is absolute.
.is_relative_to(other)BoolWhether the path is relative to other.
a > bBool
a < bBool
a >= bBool
a <= bBool
.eq(other)BoolWhether two paths are equal.
.ne(other)BoolWhether two paths differ.

From nu.lang.forms.Form:

CallBuildsMeaning
.is_empty()BoolTrue if this Form yields the EMPTY sentinel.
.is_invalid()BoolTrue if this Form yields the INVALID sentinel.
.is_sentinel()BoolTrue if this Form yields either sentinel (EMPTY or INVALID).
.not_empty()BoolTrue if this Form does not yield EMPTY.
.not_invalid()BoolTrue if this Form does not yield INVALID.

PercentageRef

A Percentage slot in the dict substrate, stored as a raw float.

PercentageRef(address, parent_ref=None, owner_shape=None)

Path nustd.mem.PercentageRef. Kind Ref, sort ref, cardinality scalar.

Notes

  • Stored as the percentage number itself (2.5 for 2.5%), not the 0.025 decimal fraction.

Example

from nustd.fin import PyPercentage
class Fees(nu.Shape):
    rate = nustd.mem.PercentageRef.slot()
data = {}
ctx = nu.Context().bind(dict, data, Fees)
_ = nu.run(Fees.rate.set(PyPercentage(2.5)), ctx)
data
nu.run(Fees.rate.to_bps(), ctx)[0]
{'rate': 2.5}
250

Methods

.set(value)

Write a Percentage into the slot as a raw float.

Builds SetCmd.

Arguments

NameTypeDefaultMeaning
valueArg[PyPercentage | float]

Notes

  • A plain Python value is converted at tree-build time; a Nu operand gets a ToFloat node instead.

Undocumented: example.

Inherited methods

From nu.domains.shape.forms.item.MutableItemForm:

CallBuildsMeaning
.erase()EraseBuild an Erase.
.init(value)IfDoSet value iff the leaf is currently missing.

From nu.domains.shape.forms.item.ItemForm:

CallBuildsMeaning
.exists()ExistsBuild an Exists query.
.missing()MissingBuild a Missing query.

From nustd.fin.forms.Percentage:

CallBuildsMeaning
PercentageRef.of(value)PercentageA percentage from a raw value: Percentage(75.5).
PercentageRef.from_dec(dec)PercentageFrom a decimal ratio: Percentage.from_dec(0.755) -> 75.5%.
PercentageRef.from_bps(bps)PercentageFrom basis points: Percentage.from_bps(7550) -> 75.5%.
PercentageRef.from_ratio(numerator, denominator)PercentageFrom a ratio: Percentage.from_ratio(3, 4) -> 75%.
.to_dec()FloatThe decimal ratio (75.5% -> 0.755).
.to_bps()IntThe basis points (75.5% -> 7550).
.to_float()FloatThe raw percentage value.
.apply(amount)FloatThis percentage of amount.
.add_to(amount)Floatamount grown by this percentage.
.sub_from(amount)Floatamount reduced by this percentage.
.is_valid(min_val=0.0, max_val=100.0)BoolWhether the value falls within [min_val, max_val].
.clamp(min_val=0.0, max_val=100.0)PercentageThis percentage clamped to [min_val, max_val].
a + bPercentage
a - bPercentage
a * bPercentage
a / bPercentage
-aPercentage
a > bBool
a < bBool
a >= bBool
a <= bBool
.eq(other)BoolWhether two percentages are equal.
.ne(other)BoolWhether two percentages differ.

From nu.lang.forms.Form:

CallBuildsMeaning
.is_empty()BoolTrue if this Form yields the EMPTY sentinel.
.is_invalid()BoolTrue if this Form yields the INVALID sentinel.
.is_sentinel()BoolTrue if this Form yields either sentinel (EMPTY or INVALID).
.not_empty()BoolTrue if this Form does not yield EMPTY.
.not_invalid()BoolTrue if this Form does not yield INVALID.

TimeRef

A time-of-day slot in the dict substrate, stored as an ISO string.

TimeRef(address, parent_ref=None, owner_shape=None)

Path nustd.mem.TimeRef. Kind Ref, sort ref, cardinality scalar.

Notes

  • Stored as HH:MM:SS, with microseconds and a tz offset appended only when the value carries them.

Example

from datetime import time
class Session(nu.Shape):
    opens = nustd.mem.TimeRef.slot()
data = {}
ctx = nu.Context().bind(dict, data, Session)
_ = nu.run(Session.opens.set(time(9, 30)), ctx)
data
nu.run(Session.opens.minute(), ctx)[0]
{'opens': '09:30:00'}
30

Methods

.set(value)

Write a time into the slot as an ISO string.

Builds SetCmd.

Arguments

NameTypeDefaultMeaning
valueArg[time | str]

Notes

  • A time is formatted at tree-build time and anything else is passed through str; a Nu operand gets a ToStr node.

Undocumented: example.

Inherited methods

From nu.domains.shape.forms.item.MutableItemForm:

CallBuildsMeaning
.erase()EraseBuild an Erase.
.init(value)IfDoSet value iff the leaf is currently missing.

From nu.domains.shape.forms.item.ItemForm:

CallBuildsMeaning
.exists()ExistsBuild an Exists query.
.missing()MissingBuild a Missing query.

From nustd.datetime.forms.time:

CallBuildsMeaning
TimeRef.of(hour=0, minute=0, second=0, microsecond=0)timeBuild a time: time(hour, minute, second, microsecond).
TimeRef.from_iso(value)timeParse an ISO time string: time.fromisoformat(s).
.hour()IntThe hour (0..23).
.minute()IntThe minute (0..59).
.second()IntThe second (0..59).
.microsecond()IntThe microsecond (0..999999).
.isoformat()StrThe time as an ISO string.
.strftime(fmt)StrFormat the time with a strftime pattern.
.replace(hour=None, minute=None, second=None, microsecond=None)timeA copy with the given components replaced.
a > bBool
a < bBool
a >= bBool
a <= bBool
.eq(other)BoolWhether two times are equal.
.ne(other)BoolWhether two times differ.

From nu.lang.forms.Form:

CallBuildsMeaning
.is_empty()BoolTrue if this Form yields the EMPTY sentinel.
.is_invalid()BoolTrue if this Form yields the INVALID sentinel.
.is_sentinel()BoolTrue if this Form yields either sentinel (EMPTY or INVALID).
.not_empty()BoolTrue if this Form does not yield EMPTY.
.not_invalid()BoolTrue if this Form does not yield INVALID.

TimedeltaRef

A timedelta slot in the dict substrate, stored as total seconds.

TimedeltaRef(address, parent_ref=None, owner_shape=None)

Path nustd.mem.TimedeltaRef. Kind Ref, sort ref, cardinality scalar.

Notes

  • One float of seconds, so the stored number compares and sums directly without going through the ref.
  • Sub-microsecond precision is lost, the same as timedelta.total_seconds() loses it.

Example

from datetime import timedelta
class Job(nu.Shape):
    took = nustd.mem.TimedeltaRef.slot()
data = {}
ctx = nu.Context().bind(dict, data, Job)
_ = nu.run(Job.took.set(timedelta(minutes=90)), ctx)
data
nu.run(Job.took.seconds(), ctx)[0]
{'took': 5400.0}
5400

Methods

.set(value)

Write a timedelta into the slot as a float of total seconds.

Builds SetCmd.

Arguments

NameTypeDefaultMeaning
valueArg[timedelta | float]

Notes

  • A timedelta is converted at tree-build time and a plain number is taken as seconds already; a Nu operand gets a TimedeltaTotalSeconds node, so it must yield a timedelta.

Undocumented: example.

Inherited methods

From nu.domains.shape.forms.item.MutableItemForm:

CallBuildsMeaning
.erase()EraseBuild an Erase.
.init(value)IfDoSet value iff the leaf is currently missing.

From nu.domains.shape.forms.item.ItemForm:

CallBuildsMeaning
.exists()ExistsBuild an Exists query.
.missing()MissingBuild a Missing query.

From nustd.datetime.forms.timedelta:

CallBuildsMeaning
TimedeltaRef.of(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)timedeltaBuild a timedelta from its components: timedelta(...).
.days()IntThe whole-days component.
.seconds()IntThe seconds component (0..86399).
.microseconds()IntThe microseconds component (0..999999).
.total_seconds()FloatThe total duration in seconds.
a + btimedelta
a - btimedelta
a * btimedelta
a / btimedelta | Float
a // btimedelta
a % btimedelta
-atimedelta
abs(a)timedelta
+atimedelta
a > bBool
a < bBool
a >= bBool
a <= bBool
.eq(other)BoolWhether two spans are equal.
.ne(other)BoolWhether two spans differ.

From nu.lang.forms.Form:

CallBuildsMeaning
.is_empty()BoolTrue if this Form yields the EMPTY sentinel.
.is_invalid()BoolTrue if this Form yields the INVALID sentinel.
.is_sentinel()BoolTrue if this Form yields either sentinel (EMPTY or INVALID).
.not_empty()BoolTrue if this Form does not yield EMPTY.
.not_invalid()BoolTrue if this Form does not yield INVALID.

TimezoneRef

A fixed-offset timezone slot, stored as its UTC±HH:MM string.

TimezoneRef(address, parent_ref=None, owner_shape=None)

Path nustd.mem.TimezoneRef. Kind Ref, sort ref, cardinality scalar.

Notes

  • Only fixed offsets survive: the stored text is what str gives a datetime.timezone, and a named zone (ZoneInfo) written here does not come back as one.
  • Reading parses the offset by hand, hours and optional minutes, so "UTC" alone lifts to UTC.

Example

from datetime import timedelta, timezone
class Site(nu.Shape):
    tz = nustd.mem.TimezoneRef.slot()
data = {}
ctx = nu.Context().bind(dict, data, Site)
_ = nu.run(Site.tz.set(timezone(timedelta(hours=5, minutes=30))), ctx)
data
nu.run(Site.tz, ctx)[0]
{'tz': 'UTC+05:30'}
datetime.timezone(datetime.timedelta(seconds=19800))

Methods

.set(value)

Write a timezone into the slot as its offset string.

Builds SetCmd.

Arguments

NameTypeDefaultMeaning
valueArg[timezone | str]

Notes

  • A plain Python value goes through str at tree-build time; a Nu operand gets a ToStr node.

Undocumented: example.

Inherited methods

From nu.domains.shape.forms.item.MutableItemForm:

CallBuildsMeaning
.erase()EraseBuild an Erase.
.init(value)IfDoSet value iff the leaf is currently missing.

From nu.domains.shape.forms.item.ItemForm:

CallBuildsMeaning
.exists()ExistsBuild an Exists query.
.missing()MissingBuild a Missing query.

From nustd.datetime.forms.timezone:

CallBuildsMeaning
TimezoneRef.of(offset, name=None)timezoneBuild a fixed-offset zone: timezone(offset, name).
TimezoneRef.utc()timezoneThe UTC zone: timezone.utc.
.utcoffset(dt=None)timedeltaThe offset from UTC as a timedelta.
.tzname(dt=None)StrThe zone's name.
.dst(dt=None)None_Daylight-saving adjustment (always None for a fixed offset).
.eq(other)BoolWhether two zones are equal.
.ne(other)BoolWhether two zones differ.

From nu.lang.forms.Form:

CallBuildsMeaning
.is_empty()BoolTrue if this Form yields the EMPTY sentinel.
.is_invalid()BoolTrue if this Form yields the INVALID sentinel.
.is_sentinel()BoolTrue if this Form yields either sentinel (EMPTY or INVALID).
.not_empty()BoolTrue if this Form does not yield EMPTY.
.not_invalid()BoolTrue if this Form does not yield INVALID.

UUIDRef

A UUID slot in the dict substrate, stored as its hyphenated string.

UUIDRef(address, parent_ref=None, owner_shape=None)

Path nustd.mem.UUIDRef. Kind Ref, sort ref, cardinality scalar.

Notes

  • Parsing on read is uuid.UUID(str), which takes the hyphenated form, a bare hex run, or a URN, so a hand-filled dict is forgiving.

Example

import uuid
class Row(nu.Shape):
    rid = nustd.mem.UUIDRef.slot()
data = {}
ctx = nu.Context().bind(dict, data, Row)
_ = nu.run(Row.rid.set(uuid.UUID(int=1)), ctx)
data
nu.run(Row.rid.int_(), ctx)[0]
{'rid': '00000000-0000-0000-0000-000000000001'}
1

Methods

.set(value)

Write a UUID into the slot as its hyphenated string.

Builds SetCmd.

Arguments

NameTypeDefaultMeaning
valueArg[UUID | str]

Notes

  • A plain Python value goes through str at tree-build time; a Nu operand gets a ToStr node.

Undocumented: example.

Inherited methods

From nu.domains.shape.forms.item.MutableItemForm:

CallBuildsMeaning
.erase()EraseBuild an Erase.
.init(value)IfDoSet value iff the leaf is currently missing.

From nu.domains.shape.forms.item.ItemForm:

CallBuildsMeaning
.exists()ExistsBuild an Exists query.
.missing()MissingBuild a Missing query.

From nustd.uuid.forms.UUID:

CallBuildsMeaning
UUIDRef.from_str(value)UUIDParse a hex string (with or without hyphens) into a UUID.
UUIDRef.from_bytes(value)UUIDBuild a UUID from 16 bytes.
UUIDRef.from_int(value)UUIDBuild a UUID from a 128-bit integer.
.version()IntThe version number (1, 3, 4, or 5).
.variant()StrThe variant.
.time()IntThe 60-bit timestamp (version 1).
.clock_seq()IntThe 14-bit clock sequence (version 1).
.node()IntThe 48-bit node (version 1).
.hex()StrThe UUID as a 32-character hex string.
.urn()StrThe UUID as a URN (urn:uuid:...).
.bytes()BytesThe UUID as 16 bytes.
.bytes_le()BytesThe UUID as 16 bytes, little-endian.
.int_()IntThe UUID as a 128-bit integer.
a > bBool
a < bBool
a >= bBool
a <= bBool
.eq(other)BoolWhether two UUIDs are equal.
.ne(other)BoolWhether two UUIDs differ.

From nu.lang.forms.Form:

CallBuildsMeaning
.is_empty()BoolTrue if this Form yields the EMPTY sentinel.
.is_invalid()BoolTrue if this Form yields the INVALID sentinel.
.is_sentinel()BoolTrue if this Form yields either sentinel (EMPTY or INVALID).
.not_empty()BoolTrue if this Form does not yield EMPTY.
.not_invalid()BoolTrue if this Form does not yield INVALID.

On this page