type_bridge.attribute¶
attribute
¶
TypeDB attribute types - base classes and concrete implementations.
This package provides the attribute type system for TypeBridge, including: - Base Attribute ABC - Concrete attribute types (String, Integer, Double, Boolean, Date, DateTime, DateTimeTZ, Decimal, Duration) - Flag system for annotations (Key, Unique, Card)
Attribute
¶
Bases: ABC
Base class for TypeDB attributes.
Attributes in TypeDB are value types that can be owned by entities and relations.
Attribute instances can store values, allowing type-safe construction: Name("Alice") # Creates Name instance with value "Alice" Age(30) # Creates Age instance with value 30
Type name formatting
You can control how the class name is converted to TypeDB attribute name using the 'case' class variable or 'attr_name' for explicit control.
Example
class Name(String): pass # TypeDB attribute: "Name" (default CLASS_NAME)
class PersonName(String): case = TypeNameCase.SNAKE_CASE # TypeDB attribute: "person_name"
class PersonName(String): attr_name = "full_name" # Explicit override
class Age(Integer): pass
class Person(Entity): name: Name age: Age
Direct instantiation with wrapped types (best practice):¶
person = Person(name=Name("Alice"), age=Age(30))
Initialize attribute with a value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
The value to store in this attribute instance |
None
|
Source code in type_bridge/attribute/base.py
__init_subclass__
¶
Called when a subclass is created.
Source code in type_bridge/attribute/base.py
__str__
¶
__repr__
¶
__eq__
¶
Compare attribute with another attribute instance.
For strict type safety, Attribute instances do NOT compare equal to raw values.
To access the raw value, use the .value property.
Examples:
Age(20) == Age(20) # True (same type, same value) Age(20) == Id(20) # False (different types!) Age(20) == 20 # False (not equal to raw value!) Age(20).value == 20 # True (access raw value explicitly)
Source code in type_bridge/attribute/base.py
__hash__
¶
get_attribute_name
classmethod
¶
Get the TypeDB attribute name.
If attr_name is explicitly set, it is used as-is. Otherwise, the class name is formatted according to the case parameter. Default case is CLASS_NAME (preserves class name as-is).
Source code in type_bridge/attribute/base.py
get_value_type
classmethod
¶
is_key
classmethod
¶
is_abstract
classmethod
¶
is_independent
classmethod
¶
get_owners
classmethod
¶
Get all Entity/Relation classes that own this attribute.
Returns:
| Type | Description |
|---|---|
set[type[TypeDBType]]
|
Set of model classes that define this attribute as a field. |
set[type[TypeDBType]]
|
Does not require a database connection (static discovery). |
Source code in type_bridge/attribute/base.py
get_supertype
classmethod
¶
to_schema_definition
classmethod
¶
Generate TypeQL schema definition for this attribute.
Includes support for TypeDB annotations: - @abstract (comes right after attribute name) - @independent (comes right after attribute name, allows standalone existence) - @range(min..max) from range_constraint ClassVar (after value type) - @regex("pattern") from regex ClassVar (after value type) - @values("a", "b", ...) from allowed_values ClassVar (after value type)
Returns:
| Type | Description |
|---|---|
str
|
TypeQL schema definition string |
Source code in type_bridge/attribute/base.py
gt
classmethod
¶
Create greater-than comparison expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Attribute
|
Value to compare against |
required |
Returns:
| Type | Description |
|---|---|
ComparisonExpr
|
ComparisonExpr for attr > value |
Example
Age.gt(Age(30)) # age > 30
Source code in type_bridge/attribute/base.py
lt
classmethod
¶
Create less-than comparison expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Attribute
|
Value to compare against |
required |
Returns:
| Type | Description |
|---|---|
ComparisonExpr
|
ComparisonExpr for attr < value |
Example
Age.lt(Age(30)) # age < 30
Source code in type_bridge/attribute/base.py
gte
classmethod
¶
Create greater-than-or-equal comparison expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Attribute
|
Value to compare against |
required |
Returns:
| Type | Description |
|---|---|
ComparisonExpr
|
ComparisonExpr for attr >= value |
Example
Salary.gte(Salary(80000.0)) # salary >= 80000
Source code in type_bridge/attribute/base.py
lte
classmethod
¶
Create less-than-or-equal comparison expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Attribute
|
Value to compare against |
required |
Returns:
| Type | Description |
|---|---|
ComparisonExpr
|
ComparisonExpr for attr <= value |
Example
Age.lte(Age(65)) # age <= 65
Source code in type_bridge/attribute/base.py
eq
classmethod
¶
Create equality comparison expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Attribute
|
Value to compare against |
required |
Returns:
| Type | Description |
|---|---|
ComparisonExpr
|
ComparisonExpr for attr == value |
Example
Status.eq(Status("active")) # status == "active"
Source code in type_bridge/attribute/base.py
neq
classmethod
¶
Create not-equal comparison expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Attribute
|
Value to compare against |
required |
Returns:
| Type | Description |
|---|---|
ComparisonExpr
|
ComparisonExpr for attr != value |
Example
Status.neq(Status("deleted")) # status != "deleted"
Source code in type_bridge/attribute/base.py
sum
classmethod
¶
Create sum aggregation expression.
Returns:
| Type | Description |
|---|---|
AggregateExpr
|
AggregateExpr for sum(attr) |
Example
Salary.sum() # sum of all salaries
Source code in type_bridge/attribute/base.py
avg
classmethod
¶
Create average (mean) aggregation expression.
Note
Automatically converts to TypeQL 'mean' function. TypeDB 3.x uses 'mean' instead of 'avg'.
Returns:
| Type | Description |
|---|---|
AggregateExpr
|
AggregateExpr for mean(attr) |
Example
Age.avg() # Generates TypeQL: mean($age)
Source code in type_bridge/attribute/base.py
max
classmethod
¶
Create maximum aggregation expression.
Returns:
| Type | Description |
|---|---|
AggregateExpr
|
AggregateExpr for max(attr) |
Example
Score.max() # maximum score
Source code in type_bridge/attribute/base.py
min
classmethod
¶
Create minimum aggregation expression.
Returns:
| Type | Description |
|---|---|
AggregateExpr
|
AggregateExpr for min(attr) |
Example
Price.min() # minimum price
Source code in type_bridge/attribute/base.py
median
classmethod
¶
Create median aggregation expression.
Returns:
| Type | Description |
|---|---|
AggregateExpr
|
AggregateExpr for median(attr) |
Example
Salary.median() # median salary
Source code in type_bridge/attribute/base.py
std
classmethod
¶
Create standard deviation aggregation expression.
Returns:
| Type | Description |
|---|---|
AggregateExpr
|
AggregateExpr for std(attr) |
Example
Score.std() # standard deviation of scores
Source code in type_bridge/attribute/base.py
__get_pydantic_core_schema__
classmethod
¶
Unified Pydantic schema generation for all attribute types.
This base implementation handles the common patterns: - Serialization: extract _value from attribute instances - Validation: wrap raw values in attribute instances - Literal type support (for types that enable it)
Subclasses can override for completely custom behavior, or override the helper methods (_pydantic_serialize, _pydantic_validate, etc.) for targeted customization.
Source code in type_bridge/attribute/base.py
__class_getitem__
classmethod
¶
build_lookup
classmethod
¶
Build an expression for a lookup operator.
This method centralizes the logic for converting lookup names (e.g., 'gt', 'in') into TypeQL expressions. Subclasses (like String) should override this to handle type-specific lookups.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lookup
|
str
|
The lookup operator name (e.g., 'exact', 'gt', 'contains') |
required |
value
|
Any
|
The value to filter by |
required |
Returns:
| Type | Description |
|---|---|
Expression
|
Expression object representing the filter |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the lookup operator is not supported by this attribute type |
Source code in type_bridge/attribute/base.py
Boolean
¶
Bases: Attribute
Boolean attribute type that accepts bool values.
Example
class IsActive(Boolean): pass
class IsVerified(Boolean): pass
Initialize Boolean attribute with a bool value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
bool
|
The boolean value to store |
required |
Source code in type_bridge/attribute/boolean.py
Date
¶
Bases: Attribute
Date attribute type that accepts date values (date only, no time).
This maps to TypeDB's 'date' type, which is an ISO 8601 compliant date without time information.
Range: January 1, 262144 BCE to December 31, 262142 CE
Example
from datetime import date
class PublishDate(Date): pass
class BirthDate(Date): pass
Usage with date values¶
published = PublishDate(date(2024, 3, 30)) birthday = BirthDate(date(1990, 5, 15))
Initialize Date attribute with a date value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
date | str
|
The date value to store. Can be: - datetime.date instance - str in ISO 8601 format (YYYY-MM-DD) |
required |
Example
from datetime import date
From date instance¶
publish_date = PublishDate(date(2024, 3, 30))
From ISO string¶
publish_date = PublishDate("2024-03-30")
Source code in type_bridge/attribute/date.py
__add__
¶
Add a Duration to this Date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Any
|
A Duration to add to this date |
required |
Returns:
| Type | Description |
|---|---|
Date
|
New Date with the duration added |
Example
from type_bridge import Duration d = Date(date(2024, 1, 31)) duration = Duration("P1M") result = d + duration # Date(2024-02-29)
Source code in type_bridge/attribute/date.py
__radd__
¶
__sub__
¶
Subtract a Duration from this Date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Any
|
A Duration to subtract from this date |
required |
Returns:
| Type | Description |
|---|---|
Date
|
New Date with the duration subtracted |
Example
from type_bridge import Duration d = Date(date(2024, 3, 31)) duration = Duration("P1M") result = d - duration # Date(2024-02-29)
Source code in type_bridge/attribute/date.py
DateTime
¶
Bases: Attribute
DateTime attribute type that accepts naive datetime values.
This maps to TypeDB's 'datetime' type, which does not include timezone information.
Example
class CreatedAt(DateTime): pass
Usage with naive datetime¶
event = Event(created_at=CreatedAt(datetime(2024, 1, 15, 10, 30, 45)))
Convert to DateTimeTZ¶
aware_dt = created_at.add_timezone() # Implicit: add system timezone aware_dt_utc = created_at.add_timezone(timezone.utc) # Explicit: add UTC
Initialize DateTime attribute with a datetime value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
datetime
|
The datetime value to store |
required |
Source code in type_bridge/attribute/datetime.py
add_timezone
¶
Convert DateTime to DateTimeTZ by adding timezone information.
Implicit conversion (tz=None): Add system/local timezone Explicit conversion (tz provided): Add specified timezone
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tz
|
timezone | None
|
Optional timezone to add to the naive datetime. If None, uses system local timezone (astimezone()). If provided, uses that specific timezone. |
None
|
Returns:
| Type | Description |
|---|---|
DateTimeTZ
|
DateTimeTZ instance with timezone-aware datetime |
Example
Implicit: add system timezone¶
aware = naive_dt.add_timezone()
Explicit: add UTC timezone¶
from datetime import timezone aware_utc = naive_dt.add_timezone(timezone.utc)
Explicit: add JST (+9) timezone¶
from datetime import timezone, timedelta jst = timezone(timedelta(hours=9)) aware_jst = naive_dt.add_timezone(jst)
Source code in type_bridge/attribute/datetime.py
__add__
¶
Add a Duration to this DateTime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Any
|
A Duration to add to this datetime |
required |
Returns:
| Type | Description |
|---|---|
DateTime
|
New DateTime with the duration added |
Example
from type_bridge import Duration dt = DateTime(datetime(2024, 1, 31, 14, 0, 0)) duration = Duration("P1M") result = dt + duration # DateTime(2024-02-28 14:00:00)
Source code in type_bridge/attribute/datetime.py
DateTimeTZ
¶
Bases: Attribute
DateTimeTZ attribute type that accepts timezone-aware datetime values.
This maps to TypeDB's 'datetime-tz' type, which requires timezone information. The datetime must have tzinfo set (e.g., using datetime.timezone.utc or zoneinfo).
Example
from datetime import datetime, timezone
class CreatedAt(DateTimeTZ): pass
Usage with timezone¶
event = Event(created_at=CreatedAt(datetime(2024, 1, 15, 10, 30, 45, tzinfo=timezone.utc)))
Convert to DateTime¶
naive_dt = created_at.strip_timezone() # Implicit: just strip tz naive_dt_jst = created_at.strip_timezone(timezone(timedelta(hours=9))) # Explicit: convert to JST, then strip
Initialize DateTimeTZ attribute with a timezone-aware datetime value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
datetime
|
The timezone-aware datetime value to store |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the datetime does not have timezone information |
Source code in type_bridge/attribute/datetimetz.py
strip_timezone
¶
Convert DateTimeTZ to DateTime by stripping timezone information.
Implicit conversion (tz=None): Just strip timezone as-is Explicit conversion (tz provided): Convert to specified timezone first, then strip
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tz
|
timezone | None
|
Optional timezone to convert to before stripping. If None, strips timezone without conversion. If provided, converts to that timezone first. |
None
|
Returns:
| Type | Description |
|---|---|
DateTime
|
DateTime instance with naive datetime |
Example
Implicit: strip timezone as-is¶
naive = dt_tz.strip_timezone()
Explicit: convert to JST (+9), then strip¶
from datetime import timezone, timedelta jst = timezone(timedelta(hours=9)) naive_jst = dt_tz.strip_timezone(jst)
Source code in type_bridge/attribute/datetimetz.py
__add__
¶
Add a Duration to this DateTimeTZ.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Any
|
A Duration to add to this timezone-aware datetime |
required |
Returns:
| Type | Description |
|---|---|
DateTimeTZ
|
New DateTimeTZ with the duration added |
Note
Duration addition respects timezone changes (DST, etc.)
Example
from type_bridge import Duration from datetime import datetime, timezone dt = DateTimeTZ(datetime(2024, 1, 31, 14, 0, 0, tzinfo=timezone.utc)) duration = Duration("P1M") result = dt + duration # DateTimeTZ(2024-02-28 14:00:00+00:00)
Source code in type_bridge/attribute/datetimetz.py
Decimal
¶
Bases: NumericAttribute
Decimal attribute type that accepts fixed-point decimal values.
This maps to TypeDB's 'decimal' type, which is a fixed-point signed decimal number with 64 bits to the left of the decimal point and 19 decimal digits of precision after the point.
Range: −2^63 to 2^63 − 10^−19 (inclusive)
Example
from decimal import Decimal as DecimalType
class AccountBalance(Decimal): pass
class Price(Decimal): pass
Usage with decimal values¶
balance = AccountBalance(DecimalType("1234.567890")) price = Price(DecimalType("0.02"))
Initialize Decimal attribute with a decimal value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Decimal | str | int | float
|
The decimal value to store. Can be: - decimal.Decimal instance - str that can be parsed as decimal - int or float (will be converted to Decimal) |
required |
Example
from decimal import Decimal as DecimalType
From Decimal¶
balance = AccountBalance(DecimalType("123.45"))
From string (recommended for precision)¶
balance = AccountBalance("123.45")
From int or float (may lose precision)¶
balance = AccountBalance(123.45)
Source code in type_bridge/attribute/decimal.py
Double
¶
Bases: NumericAttribute
Double precision float attribute type that accepts float values.
Example
class Price(Double): pass
class Score(Double): pass
Initialize Double attribute with a float value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
float
|
The float value to store |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If value violates range_constraint |
Source code in type_bridge/attribute/double.py
Duration
¶
Bases: Attribute
Duration attribute type that accepts ISO 8601 duration values.
This maps to TypeDB's 'duration' type, which represents calendar-aware time spans using months, days, and nanoseconds.
TypeDB duration format: ISO 8601 duration (e.g., P1Y2M3DT4H5M6.789S) Storage: 32-bit months, 32-bit days, 64-bit nanoseconds
Important notes: - Durations are partially ordered (P1M and P30D cannot be compared) - P1D ≠ PT24H (calendar day vs 24 hours) - P1M ≠ P30D (months vary in length) - Addition is not commutative with calendar components
Example
from datetime import timedelta
class SessionDuration(Duration): pass
class EventCadence(Duration): pass
From ISO 8601 string¶
cadence = EventCadence("P1M") # 1 month interval = SessionDuration("PT1H30M") # 1 hour 30 minutes
From timedelta (converted to Duration internally)¶
session = SessionDuration(timedelta(hours=2))
Complex duration¶
complex = EventCadence("P1Y2M3DT4H5M6.789S")
Initialize Duration attribute with a duration value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str | timedelta | Duration
|
The duration value to store. Can be: - str: ISO 8601 duration string (e.g., "P1Y2M3DT4H5M6S") - timedelta: Python timedelta (converted to Duration) - isodate.Duration: Direct Duration object |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If duration components exceed storage limits |
Example
From ISO string¶
duration1 = Duration("P1M") # 1 month duration2 = Duration("PT1H30M") # 1 hour 30 minutes
From timedelta¶
from datetime import timedelta duration3 = Duration(timedelta(hours=2, minutes=30))
Complex duration¶
duration4 = Duration("P1Y2M3DT4H5M6.789S")
Source code in type_bridge/attribute/duration.py
value
property
¶
Get the stored duration value.
Returns:
| Type | Description |
|---|---|
Duration
|
isodate.Duration instance (zero duration if None) |
to_iso8601
¶
Convert duration to ISO 8601 string format.
Returns:
| Type | Description |
|---|---|
str
|
ISO 8601 duration string (e.g., "P1Y2M3DT4H5M6S") |
Example
duration = Duration("P1M") assert duration.to_iso8601() == "P1M"
Source code in type_bridge/attribute/duration.py
__add__
¶
Add two durations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Any
|
Another Duration to add |
required |
Returns:
| Type | Description |
|---|---|
Duration
|
New Duration with sum |
Example
d1 = Duration("P1M") d2 = Duration("P15D") result = d1 + d2 # P1M15D
Source code in type_bridge/attribute/duration.py
__radd__
¶
__sub__
¶
Subtract two durations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Any
|
Another Duration to subtract |
required |
Returns:
| Type | Description |
|---|---|
Duration
|
New Duration with difference |
Example
d1 = Duration("P1M") d2 = Duration("P15D") result = d1 - d2 # P1M-15D
Source code in type_bridge/attribute/duration.py
AttributeFlags
dataclass
¶
AttributeFlags(is_key=False, is_unique=False, card_min=None, card_max=None, has_explicit_card=False, name=None, case=None)
Metadata for attribute ownership and type configuration.
Represents TypeDB ownership annotations like @key, @card(min..max), @unique, and allows overriding the attribute type name with explicit name or case formatting.
Example
class Person(Entity): name: Name = Flag(Key) # @key (implies @card(1..1)) email: Email = Flag(Unique) # @unique @card(1..1) age: Optional[Age] # @card(0..1) - no Flag needed tags: list[Tag] = Flag(Card(min=2)) # @card(2..) jobs: list[Job] = Flag(Card(1, 5)) # @card(1..5)
Override attribute type name explicitly¶
class Name(String): flags = AttributeFlags(name="name")
Or use case formatting¶
class PersonName(String): flags = AttributeFlags(case=TypeNameCase.SNAKE_CASE) # -> person_name
to_typeql_annotations
¶
Convert to TypeQL annotations like @key, @card(0..5).
Rules: - @key implies @card(1..1), so never output @card with @key - @unique with @card(1..1) is redundant, so omit @card in that case - Otherwise, always output @card if cardinality is specified
Returns:
| Type | Description |
|---|---|
list[str]
|
List of TypeQL annotation strings |
Source code in type_bridge/attribute/flags.py
Card
¶
Cardinality marker for multi-value attribute ownership.
IMPORTANT: Card() should only be used with list[Type] annotations. For optional single values, use Optional[Type] instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min
|
int | None
|
Minimum cardinality (default: None, which means unspecified) |
None
|
max
|
int | None
|
Maximum cardinality (default: None, which means unbounded) |
None
|
Examples:
tags: list[Tag] = Flag(Card(min=2)) # @card(2..) - at least two jobs: list[Job] = Flag(Card(1, 5)) # @card(1..5) - one to five ids: list[ID] = Flag(Key, Card(min=1)) # @key @card(1..)
INCORRECT - use Optional[Type] instead:¶
age: Age = Flag(Card(min=0, max=1)) # ❌ Wrong!¶
age: Optional[Age] # ✓ Correct
Initialize cardinality marker.
Supports both positional and keyword arguments: - Card(1, 5) → min=1, max=5 - Card(min=2) → min=2, max=None (unbounded) - Card(max=5) → min=0, max=5 (defaults min to 0) - Card(min=0, max=10) → min=0, max=10
Source code in type_bridge/attribute/flags.py
TypeFlags
dataclass
¶
Metadata flags for Entity and Relation classes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
TypeDB type name (if None, uses class name with case formatting) |
None
|
abstract
|
bool
|
Whether this is an abstract type |
False
|
base
|
bool
|
Whether this is a Python base class that should not appear in TypeDB schema |
False
|
case
|
TypeNameCase
|
Case formatting for auto-generated type names (default: CLASS_NAME) |
CLASS_NAME
|
Example
class Person(Entity): flags = TypeFlags(name="person") name: Name
class PersonName(Entity): flags = TypeFlags() # → PersonName (default CLASS_NAME) name: Name
class PersonName(Entity): flags = TypeFlags(case=TypeNameCase.SNAKE_CASE) # → person_name name: Name
class AbstractPerson(Entity): flags = TypeFlags(abstract=True) name: Name
class BaseEntity(Entity): flags = TypeFlags(base=True) # Python base class only # Children skip this in TypeDB hierarchy
Initialize TypeFlags.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
TypeDB type name (if None, uses class name with case formatting) |
None
|
abstract
|
bool
|
Whether this is an abstract type |
False
|
base
|
bool
|
Whether this is a Python base class that should not appear in TypeDB schema |
False
|
case
|
TypeNameCase
|
Case formatting for auto-generated type names (default: CLASS_NAME) |
CLASS_NAME
|
Source code in type_bridge/attribute/flags.py
TypeNameCase
¶
Bases: Enum
Type name case formatting options for Entity and Relation types.
Integer
¶
Bases: NumericAttribute
Integer attribute type that accepts int values.
Example
class Age(Integer): pass
class Count(Integer): pass
With Literal for type safety¶
class Priority(Integer): pass
priority: Literal[1, 2, 3] | Priority
Initialize Integer attribute with an integer value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
int
|
The integer value to store |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If value violates range_constraint |
Source code in type_bridge/attribute/integer.py
String
¶
Bases: Attribute
String attribute type that accepts str values.
Example
class Name(String): pass
class Email(String): pass
With Literal for type safety¶
class Status(String): pass
status: Literal["active", "inactive"] | Status
Initialize String attribute with a string value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The string value to store |
required |
Source code in type_bridge/attribute/string.py
__str__
¶
__add__
¶
Concatenate strings.
Source code in type_bridge/attribute/string.py
__radd__
¶
contains
classmethod
¶
Create contains string expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
String
|
String value to search for |
required |
Returns:
| Type | Description |
|---|---|
StringExpr
|
StringExpr for attr contains value |
Example
Email.contains(Email("@company.com")) # email contains "@company.com"
Source code in type_bridge/attribute/string.py
like
classmethod
¶
Create regex pattern matching expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
String
|
Regex pattern to match |
required |
Returns:
| Type | Description |
|---|---|
StringExpr
|
StringExpr for attr like pattern |
Example
Name.like(Name("^A.*")) # name starts with 'A'
Source code in type_bridge/attribute/string.py
regex
classmethod
¶
Create regex pattern matching expression (alias for like).
Note
Automatically converts to TypeQL 'like' operator. Both 'like' and 'regex' perform regex pattern matching in TypeDB.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
String
|
Regex pattern to match |
required |
Returns:
| Type | Description |
|---|---|
StringExpr
|
StringExpr for attr like pattern |
Example
Email.regex(Email(".@gmail.com")) # Generates TypeQL: $email like ".@gmail.com"
Source code in type_bridge/attribute/string.py
startswith
classmethod
¶
Create startswith string expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
String
|
Prefix string to check for |
required |
Returns:
| Type | Description |
|---|---|
StringExpr
|
StringExpr for attr like "^prefix.*" |
Source code in type_bridge/attribute/string.py
endswith
classmethod
¶
Create endswith string expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
suffix
|
String
|
Suffix string to check for |
required |
Returns:
| Type | Description |
|---|---|
StringExpr
|
StringExpr for attr like ".*suffix$" |
Source code in type_bridge/attribute/string.py
build_lookup
classmethod
¶
Build an expression for string-specific lookups.
Overrides base method to handle contains, regex, startswith, endswith.
Source code in type_bridge/attribute/string.py
Flag
¶
Create attribute flags for Key, Unique, and Card markers.
Usage
field: Type = Flag(Key) # @key (implies @card(1..1)) field: Type = Flag(Unique) # @unique @card(1..1) field: list[Type] = Flag(Card(min=2)) # @card(2..) field: list[Type] = Flag(Card(1, 5)) # @card(1..5) field: Type = Flag(Key, Unique) # @key @unique field: list[Type] = Flag(Key, Card(min=1)) # @key @card(1..)
For optional single values, use Optional[Type] instead: field: Optional[Type] # @card(0..1) - no Flag needed
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*annotations
|
Any
|
Variable number of Key, Unique, or Card marker instances |
()
|
Returns:
| Type | Description |
|---|---|
Annotated[Any, AttributeFlags]
|
AttributeFlags instance with the specified flags |
Example
class Person(Entity): flags = TypeFlags(name="person") name: Name = Flag(Key) # @key (implies @card(1..1)) email: Email = Flag(Key, Unique) # @key @unique age: Optional[Age] # @card(0..1) tags: list[Tag] = Flag(Card(min=2)) # @card(2..) jobs: list[Job] = Flag(Card(1, 5)) # @card(1..5)