From 0c176593ef8205ff07ac639aeb49a6678a0ea505 Mon Sep 17 00:00:00 2001 From: Austin Noto-Moniz Date: Fri, 13 Feb 2026 13:39:23 -0500 Subject: [PATCH 1/6] Replace typing List, Dict, Set, Tuple, Type. As of python 3.9, the builtin classes can be used as type annotations, so there's no need to use the separate "typing" versions (which are also deprecated). Note that data_objects and predictor_evaluation retain List for now, as it conflicts with their definition of a method called "list". --- src/citrine/_rest/ai_resource_metadata.py | 2 +- src/citrine/_rest/collection.py | 2 +- src/citrine/_rest/engine_resource.py | 2 +- src/citrine/_rest/pageable.py | 6 +- src/citrine/_rest/paginator.py | 4 +- .../polymorphic_serializable.py | 2 +- src/citrine/_serialization/properties.py | 34 ++++---- src/citrine/_utils/batcher.py | 6 +- src/citrine/_utils/functions.py | 4 +- src/citrine/_utils/template_util.py | 6 +- src/citrine/exceptions.py | 2 +- src/citrine/gemd_queries/criteria.py | 14 ++-- src/citrine/gemd_queries/filter.py | 6 +- src/citrine/gemtables/columns.py | 4 +- src/citrine/gemtables/rows.py | 10 +-- src/citrine/gemtables/variables.py | 84 +++++++++---------- src/citrine/informatics/catalyst/assistant.py | 2 +- .../constraints/categorical_constraint.py | 2 +- .../ingredient_ratio_constraint.py | 20 ++--- src/citrine/informatics/data_sources.py | 4 +- src/citrine/informatics/descriptors.py | 10 +-- src/citrine/informatics/design_candidate.py | 18 ++-- .../design_spaces/formulation_design_space.py | 18 ++-- .../hierarchical_design_space.py | 16 ++-- .../design_spaces/product_design_space.py | 10 +-- .../informatics/design_spaces/subspace.py | 2 +- .../design_spaces/top_level_design_space.py | 2 +- src/citrine/informatics/dimensions.py | 6 +- .../executions/design_execution.py | 2 +- .../informatics/executions/execution.py | 2 +- .../executions/predictor_evaluation.py | 8 +- src/citrine/informatics/experiment_values.py | 6 +- src/citrine/informatics/feature_effects.py | 6 +- src/citrine/informatics/generative_design.py | 18 ++-- src/citrine/informatics/predict_request.py | 2 +- .../predictor_evaluation_metrics.py | 2 +- .../predictor_evaluation_result.py | 36 ++++---- .../informatics/predictor_evaluator.py | 44 +++++----- .../attribute_accumulation_predictor.py | 2 +- .../predictors/auto_ml_predictor.py | 12 +-- .../predictors/chemical_formula_featurizer.py | 14 ++-- .../predictors/expression_predictor.py | 6 +- .../informatics/predictors/graph_predictor.py | 12 +-- .../ingredient_fractions_predictor.py | 6 +- .../ingredients_to_formulation_predictor.py | 12 +-- .../predictors/label_fractions_predictor.py | 6 +- .../predictors/mean_property_predictor.py | 12 +-- .../molecular_structure_featurizer.py | 8 +- src/citrine/informatics/predictors/node.py | 2 +- .../predictors/single_predict_request.py | 2 +- .../predictors/single_prediction.py | 2 +- src/citrine/informatics/reports.py | 18 ++-- src/citrine/informatics/scores.py | 32 +++---- .../workflows/analysis_workflow.py | 2 +- src/citrine/jobs/job.py | 4 +- src/citrine/resources/_default_labels.py | 4 +- src/citrine/resources/condition_template.py | 8 +- src/citrine/resources/data_concepts.py | 10 +-- src/citrine/resources/data_objects.py | 8 +- src/citrine/resources/data_version_update.py | 8 +- src/citrine/resources/dataset.py | 14 ++-- src/citrine/resources/delete.py | 12 +-- src/citrine/resources/descriptors.py | 10 +-- src/citrine/resources/design_workflow.py | 2 +- .../resources/experiment_datasource.py | 2 +- src/citrine/resources/file_link.py | 6 +- src/citrine/resources/gemd_resource.py | 14 ++-- src/citrine/resources/gemtables.py | 4 +- src/citrine/resources/ingestion.py | 4 +- src/citrine/resources/ingredient_run.py | 12 +-- src/citrine/resources/ingredient_spec.py | 16 ++-- src/citrine/resources/material_run.py | 16 ++-- src/citrine/resources/material_spec.py | 20 ++--- src/citrine/resources/material_template.py | 10 +-- src/citrine/resources/measurement_run.py | 24 +++--- src/citrine/resources/measurement_spec.py | 20 ++--- src/citrine/resources/measurement_template.py | 14 ++-- src/citrine/resources/parameter_template.py | 8 +- src/citrine/resources/predictor.py | 6 +- src/citrine/resources/predictor_evaluation.py | 2 +- src/citrine/resources/process_run.py | 20 ++--- src/citrine/resources/process_spec.py | 20 ++--- src/citrine/resources/process_template.py | 16 ++-- src/citrine/resources/project.py | 4 +- src/citrine/resources/property_template.py | 8 +- src/citrine/resources/table_config.py | 26 +++--- src/citrine/resources/team.py | 32 +++---- 87 files changed, 478 insertions(+), 478 deletions(-) diff --git a/src/citrine/_rest/ai_resource_metadata.py b/src/citrine/_rest/ai_resource_metadata.py index 4b3175ed7..62e02fb08 100644 --- a/src/citrine/_rest/ai_resource_metadata.py +++ b/src/citrine/_rest/ai_resource_metadata.py @@ -29,4 +29,4 @@ class AIResourceMetadata(): """:Optional[str]: short description of the resource's status""" status_detail = properties.List(properties.Object(StatusDetail), 'status_detail', default=[], serializable=False) - """:List[StatusDetail]: a list of structured status info, containing the message and level""" + """:list[StatusDetail]: a list of structured status info, containing the message and level""" diff --git a/src/citrine/_rest/collection.py b/src/citrine/_rest/collection.py index a5a9869a5..35295a4aa 100644 --- a/src/citrine/_rest/collection.py +++ b/src/citrine/_rest/collection.py @@ -33,7 +33,7 @@ def _get_path(self, *, ignore_dataset: bool = False, action: Union[str, Sequence[str]] = [], - query_terms: Dict[str, str] = {}, + query_terms: dict[str, str] = {}, ) -> str: """Construct a url from __base_path__ and, optionally, id and/or action.""" base = self._dataset_agnostic_path_template if ignore_dataset else self._path_template diff --git a/src/citrine/_rest/engine_resource.py b/src/citrine/_rest/engine_resource.py index 9abd9f568..8957ffd57 100644 --- a/src/citrine/_rest/engine_resource.py +++ b/src/citrine/_rest/engine_resource.py @@ -63,7 +63,7 @@ class EngineResource(EngineResourceWithoutStatus[Self], IncludeParentProperties[ """:Optional[str]: short description of the resource's status""" status_detail = properties.List(properties.Object(StatusDetail), 'metadata.status.detail', default=[], serializable=False) - """:List[StatusDetail]: a list of structured status info, containing the message and level""" + """:list[StatusDetail]: a list of structured status info, containing the message and level""" @classmethod def build(cls, data: dict): diff --git a/src/citrine/_rest/pageable.py b/src/citrine/_rest/pageable.py index 129155cf7..5e8b38fcd 100644 --- a/src/citrine/_rest/pageable.py +++ b/src/citrine/_rest/pageable.py @@ -13,7 +13,7 @@ def _get_path(self, *, ignore_dataset: bool = False, action: Union[str, Sequence[str]] = [], - query_terms: Dict[str, str] = {}, + query_terms: dict[str, str] = {}, ) -> str: """Construct a url from __base_path__ and, optionally, id.""" raise NotImplementedError # pragma: no cover @@ -27,7 +27,7 @@ def _fetch_page(self, additional_params: Optional[dict] = None, *, version: Optional[str] = None - ) -> Tuple[Iterable[dict], str]: + ) -> tuple[Iterable[dict], str]: """ Fetch visible elements. This does not handle pagination. @@ -102,7 +102,7 @@ def _fetch_page(self, def _page_params(self, page: Optional[int], per_page: Optional[int], - module_type: Optional[str] = None) -> Dict[str, int]: + module_type: Optional[str] = None) -> dict[str, int]: params = {} if page is not None: params["page"] = page diff --git a/src/citrine/_rest/paginator.py b/src/citrine/_rest/paginator.py index 60dd6cac7..ac2c54eb5 100644 --- a/src/citrine/_rest/paginator.py +++ b/src/citrine/_rest/paginator.py @@ -13,7 +13,7 @@ class Paginator(Generic[ResourceType]): """ def paginate(self, - page_fetcher: Callable[[Optional[int], int], Tuple[Iterable[dict], str]], + page_fetcher: Callable[[Optional[int], int], tuple[Iterable[dict], str]], collection_builder: Callable[[Iterable[dict]], Iterable[ResourceType]], per_page: int = 100, search_params: Optional[dict] = None, @@ -29,7 +29,7 @@ def paginate(self, Parameters --------- - page_fetcher: Callable[[Optional[int], int], Tuple[Iterable[dict], str]] + page_fetcher: Callable[[Optional[int], int], tuple[Iterable[dict], str]] Fetches the next page of elements collection_builder: Callable[[Iterable[dict]], Iterable[ResourceType]] Builds each element in the collection into the appropriate resource diff --git a/src/citrine/_serialization/polymorphic_serializable.py b/src/citrine/_serialization/polymorphic_serializable.py index bd7028266..01218606f 100644 --- a/src/citrine/_serialization/polymorphic_serializable.py +++ b/src/citrine/_serialization/polymorphic_serializable.py @@ -12,7 +12,7 @@ class PolymorphicSerializable(Generic[SelfType]): @classmethod @abstractmethod - def get_type(cls, data) -> Type[Serializable]: + def get_type(cls, data) -> type[Serializable]: """Get the underlying type based on given data.""" @classmethod diff --git a/src/citrine/_serialization/properties.py b/src/citrine/_serialization/properties.py index 95cceef28..f3f947176 100644 --- a/src/citrine/_serialization/properties.py +++ b/src/citrine/_serialization/properties.py @@ -74,12 +74,12 @@ def __init__(self, @property @abstractmethod - def underlying_types(self) -> typing.Union[DeserializedType, typing.Tuple[DeserializedType]]: + def underlying_types(self) -> typing.Union[DeserializedType, tuple[DeserializedType]]: """Return the python types handled by this property.""" @property @abstractmethod - def serialized_types(self) -> typing.Union[SerializedType, typing.Tuple[SerializedType]]: + def serialized_types(self) -> typing.Union[SerializedType, tuple[SerializedType]]: """Return the types used to serialize this property.""" def _error_source(self, base_class: type) -> str: @@ -241,7 +241,7 @@ def _set_elements(self, value: typing.Union[SerializedType, DeserializedType]): @lru_cache(maxsize=1024) def _get_key_and_base_class(prop: Property, klass: typing.Any) -> \ - typing.Tuple[typing.Optional[str], typing.Optional[str]]: + tuple[typing.Optional[str], typing.Optional[str]]: """ Return the base class and class attribute name for the object and property. @@ -415,7 +415,7 @@ def _serialize(self, value: datetime) -> int: class List(PropertyCollection[list, list]): def __init__(self, - element_type: typing.Union[Property, typing.Type[Property]], + element_type: typing.Union[Property, type[Property]], serialization_path: typing.Optional[str] = None, *, serializable: bool = True, @@ -469,7 +469,7 @@ def _set_elements(self, value): class Set(PropertyCollection[set, typing.Iterable]): def __init__(self, - element_type: typing.Union[Property, typing.Type[Property]], + element_type: typing.Union[Property, type[Property]], serialization_path: typing.Optional[str] = None, *, serializable: bool = True, @@ -530,7 +530,7 @@ class Union(Property[typing.Any, typing.Any]): """ def __init__(self, - element_types: typing.Sequence[typing.Union[Property, typing.Type[Property]]], + element_types: typing.Sequence[typing.Union[Property, type[Property]]], serialization_path: typing.Optional[str] = None, *, serializable: bool = True, @@ -547,7 +547,7 @@ def __init__(self, use_init=use_init) if not isinstance(element_types, typing.Iterable): raise ValueError("element types must be iterable: {}".format(element_types)) - self.element_types: typing.List[Property, ...] = \ + self.element_types: list[Property, ...] = \ [el if isinstance(el, Property) else el() for el in element_types] @property @@ -585,7 +585,7 @@ class SpecifiedMixedList(PropertyCollection[list, list]): """A finite list in which the type of each entry is specified.""" def __init__(self, - element_types: typing.Sequence[typing.Union[Property, typing.Type[Property]]], + element_types: typing.Sequence[typing.Union[Property, type[Property]]], serialization_path: typing.Optional[str] = None, *, serializable: bool = True, @@ -602,7 +602,7 @@ def __init__(self, use_init=use_init) if not isinstance(element_types, list): raise ValueError("element types must be a list: {}".format(element_types)) - self.element_types: typing.List[Property, ...] = \ + self.element_types: list[Property, ...] = \ [el if isinstance(el, Property) else el() for el in element_types] @property @@ -665,7 +665,7 @@ def _set_elements(self, value): class Enumeration(Property[BaseEnumeration, str]): def __init__(self, - klass: typing.Type[typing.Any], + klass: type[typing.Any], serialization_path: typing.Optional[str] = None, *, serializable: bool = True, @@ -698,7 +698,7 @@ def _serialize(self, value: typing.Any) -> str: @lru_cache(maxsize=1024) -def _fields_map(klass: typing.Type) -> typing.Dict[str, Property]: +def _fields_map(klass: typing.Type) -> dict[str, Property]: """Compute the properties-relevant fields in a given class.""" return { k: v @@ -710,7 +710,7 @@ def _fields_map(klass: typing.Type) -> typing.Dict[str, Property]: class Object(PropertyCollection[typing.Any, dict]): def __init__(self, - klass: typing.Type[typing.Any], + klass: type[typing.Any], serialization_path: typing.Optional[str] = None, *, serializable: bool = True, @@ -727,7 +727,7 @@ def __init__(self, use_init=use_init) self.klass = klass # We need to use __dict__ here because other access methods will invoke __get__ - self.fields: typing.Dict[str, Property] = _fields_map(self.klass) + self.fields: dict[str, Property] = _fields_map(self.klass) self.polymorphic = "get_type" in self.klass.__dict__ and\ issubclass(self.klass, PolymorphicSerializable) @@ -836,7 +836,7 @@ class LinkOrElse(PropertyCollection[typing.Union[Serializable, LinkByUID], dict] """ def __init__(self, - klass: typing.Type[typing.Any] = Serializable, + klass: type[typing.Any] = Serializable, serialization_path: typing.Optional[str] = None, *, serializable: bool = True, @@ -893,7 +893,7 @@ def _set_elements(self, value): class Optional(PropertyCollection[typing.Optional[typing.Any], typing.Optional[typing.Any]]): def __init__(self, - prop: typing.Union[Property, typing.Type[Property]], + prop: typing.Union[Property, type[Property]], serialization_path: typing.Optional[str] = None, *, serializable: bool = True, @@ -959,8 +959,8 @@ class Mapping(PropertyCollection[dict, dict]): """ def __init__(self, - keys_type: typing.Union[Property, typing.Type[Property]], - values_type: typing.Union[Property, typing.Type[Property]], + keys_type: typing.Union[Property, type[Property]], + values_type: typing.Union[Property, type[Property]], serialization_path: typing.Optional[str] = None, *, serializable: bool = True, diff --git a/src/citrine/_utils/batcher.py b/src/citrine/_utils/batcher.py index dcc171807..67d20a7ec 100644 --- a/src/citrine/_utils/batcher.py +++ b/src/citrine/_utils/batcher.py @@ -11,7 +11,7 @@ class Batcher(ABC): """Base class for Data Concepts batching routines.""" @abstractmethod - def batch(self, objects: Iterable[DataConcepts], batch_size) -> List[List[DataConcepts]]: + def batch(self, objects: Iterable[DataConcepts], batch_size) -> list[list[DataConcepts]]: """Collect a list of DataConcepts into batches according to some batching algorithm.""" @staticmethod @@ -28,7 +28,7 @@ def by_dependency(): class BatchByType(Batcher): """Batching by object type.""" - def batch(self, objects: Iterable[DataConcepts], batch_size) -> List[List[DataConcepts]]: + def batch(self, objects: Iterable[DataConcepts], batch_size) -> list[list[DataConcepts]]: """Collect object batches by type, following an order that will satisfy prereqs.""" batches = list() by_type = defaultdict(list) @@ -58,7 +58,7 @@ def batch(self, objects: Iterable[DataConcepts], batch_size) -> List[List[DataCo class BatchByDependency(Batcher): """Batching by clusters where nothing references anything outside the cluster.""" - def batch(self, objects: Iterable[DataConcepts], batch_size) -> List[List[DataConcepts]]: + def batch(self, objects: Iterable[DataConcepts], batch_size) -> list[list[DataConcepts]]: """Collect object batches that are internally consistent for dry_run object tests.""" # Collect shallow dependences, UID references, and type-based clusters depends = dict() diff --git a/src/citrine/_utils/functions.py b/src/citrine/_utils/functions.py index e22826cf9..a93971e23 100644 --- a/src/citrine/_utils/functions.py +++ b/src/citrine/_utils/functions.py @@ -281,7 +281,7 @@ def format_escaped_url( the `format` template to which the escaped arguments will be bound *args : Iterable[str] Other arguments - **kwargs: Dict[str] + **kwargs: dict[str] Keyword arguments Returns @@ -299,7 +299,7 @@ def resource_path(*, path_template: str, uid: Optional[Union[UUID, str]] = None, action: Union[str, Sequence[str]] = [], - query_terms: Dict[str, str] = {}, + query_terms: dict[str, str] = {}, **kwargs ) -> str: """Construct a url from a base path and, optionally, id and/or action.""" diff --git a/src/citrine/_utils/template_util.py b/src/citrine/_utils/template_util.py index a2a63b677..359ae238e 100644 --- a/src/citrine/_utils/template_util.py +++ b/src/citrine/_utils/template_util.py @@ -12,7 +12,7 @@ from gemd.entity.attribute import PropertyAndConditions -def make_attribute_table(gems: List[DataConcepts]) -> List[Mapping[str, BaseValue]]: +def make_attribute_table(gems: list[DataConcepts]) -> list[dict[str, BaseValue]]: """[ALPHA] the current status of make_attribute_table. Given a list of GEMD Objects, this method returns a list of dictionaries @@ -31,12 +31,12 @@ def make_attribute_table(gems: List[DataConcepts]) -> List[Mapping[str, BaseValu Parameters ---------- - gems : List[DataConcepts] + gems : list[DataConcepts] List of GEMD objects whose attributes you would like to compare. Returns ------- - List[Mapping[str, BaseValue]] + list[dict[str, BaseValue]] A list of dictionaries where each dictionary represents an object and its attributes. """ diff --git a/src/citrine/exceptions.py b/src/citrine/exceptions.py index a528cce80..d042e1370 100644 --- a/src/citrine/exceptions.py +++ b/src/citrine/exceptions.py @@ -162,7 +162,7 @@ class PollingTimeoutError(NonRetryableException): class JobFailureError(NonRetryableException): """The asynchronous job completed with the given failure message.""" - def __init__(self, *, message: str, job_id: UUID, failure_reasons: List[str]): + def __init__(self, *, message: str, job_id: UUID, failure_reasons: list[str]): super().__init__(message) self.job_id = job_id self.failure_reasons = failure_reasons diff --git a/src/citrine/gemd_queries/criteria.py b/src/citrine/gemd_queries/criteria.py index 8c32dffb3..5fc8c1f75 100644 --- a/src/citrine/gemd_queries/criteria.py +++ b/src/citrine/gemd_queries/criteria.py @@ -45,9 +45,9 @@ class Criteria(PolymorphicSerializable): """Abstract concept of a criteria to apply when searching for materials.""" @classmethod - def get_type(cls, data) -> Type[Serializable]: + def get_type(cls, data) -> type[Serializable]: """Return the subtype.""" - classes: List[Type[Criteria]] = [ + classes: list[type[Criteria]] = [ AndOperator, OrOperator, PropertiesCriteria, NameCriteria, MaterialRunClassificationCriteria, MaterialTemplatesCriteria, TagsCriteria, ConnectivityClassCriteria @@ -91,7 +91,7 @@ class PropertiesCriteria(Serializable['PropertiesCriteria'], Criteria): Parameters ---------- - property_templates_filter: Set[UUID] + property_templates_filter: set[UUID] The citrine IDs of the property templates matches must reference. value_type_filter: Optional[PropertyFilterType] The value range matches must conform to. @@ -132,7 +132,7 @@ class MaterialRunClassificationCriteria( Parameters ---------- - classifications: Set[MaterialClassification] + classifications: set[MaterialClassification] The classification, based on where in a material history an object appears. """ @@ -155,9 +155,9 @@ class MaterialTemplatesCriteria(Serializable['MaterialTemplatesCriteria'], Crite Parameters ---------- - material_templates_identifiers: Set[UUID] + material_templates_identifiers: set[UUID] Which material templates to filter by. - tag_filters: Set[str] + tag_filters: set[str] Which tags to filter by. """ @@ -176,7 +176,7 @@ class TagsCriteria(Serializable['TagsCriteria'], Criteria): Parameters ---------- - tags: Set[str] + tags: set[str] The set of tags to filter by. The meaning of this set depends on the filter_type. filter_type: TagFilterType The type of filter to apply to the tags: diff --git a/src/citrine/gemd_queries/filter.py b/src/citrine/gemd_queries/filter.py index 0b8a555ca..4c67c2e52 100644 --- a/src/citrine/gemd_queries/filter.py +++ b/src/citrine/gemd_queries/filter.py @@ -12,9 +12,9 @@ class PropertyFilterType(PolymorphicSerializable): """Abstract concept of a criteria to apply when searching for materials.""" @classmethod - def get_type(cls, data) -> Type[Serializable]: + def get_type(cls, data) -> type[Serializable]: """Return the subtype.""" - classes: List[Type[PropertyFilterType]] = [ + classes: list[type[PropertyFilterType]] = [ NominalCategoricalFilter, AllRealFilter, AllIntegerFilter ] @@ -69,7 +69,7 @@ class NominalCategoricalFilter(Serializable['NominalCategoricalFilter'], Propert Parameters ---------- - categories: Set[str] + categories: set[str] Which categorical values match. """ diff --git a/src/citrine/gemtables/columns.py b/src/citrine/gemtables/columns.py index 8c1612059..cac6661d1 100644 --- a/src/citrine/gemtables/columns.py +++ b/src/citrine/gemtables/columns.py @@ -63,11 +63,11 @@ def __eq__(self, other): return False @classmethod - def get_type(cls, data) -> Type[Serializable]: + def get_type(cls, data) -> type[Serializable]: """Return the subtype.""" if "type" not in data: raise ValueError("Can only get types from dicts with a 'type' key") - types: List[Type[Serializable]] = [ + types: list[type[Serializable]] = [ IdentityColumn, MeanColumn, StdDevColumn, QuantileColumn, OriginalUnitsColumn, MostLikelyCategoryColumn, MostLikelyProbabilityColumn, diff --git a/src/citrine/gemtables/rows.py b/src/citrine/gemtables/rows.py index b74374bd2..42ce03e3d 100644 --- a/src/citrine/gemtables/rows.py +++ b/src/citrine/gemtables/rows.py @@ -25,11 +25,11 @@ def __eq__(self, other): return False @classmethod - def get_type(cls, data) -> Type[Serializable]: + def get_type(cls, data) -> type[Serializable]: """Return the subtype.""" if "type" not in data: raise ValueError("Can only get types from dicts with a 'type' key") - types: List[Type[Serializable]] = [ + types: list[type[Serializable]] = [ MaterialRunByTemplate ] res = next((x for x in types if x.typ == data["type"]), None) @@ -45,7 +45,7 @@ class MaterialRunByTemplate(Serializable['MaterialRunByTemplate'], Row): ---------- templates: list[Union[UUID, str, LinkByUID, MaterialTemplate]] templates of materials to include - tags: Set[str] + tags: set[str] optional list of tags for filtering. If a terminal material doesn't contain any of the tags it will be filtered out. @@ -58,8 +58,8 @@ class MaterialRunByTemplate(Serializable['MaterialRunByTemplate'], Row): template_type = Union[UUID, str, LinkByUID, MaterialTemplate] def __init__(self, *, - templates: List[template_type], - tags: Set[str] = None): + templates: list[template_type], + tags: set[str] = None): self.templates = [_make_link_by_uid(x) for x in templates] self.tags = tags diff --git a/src/citrine/gemtables/variables.py b/src/citrine/gemtables/variables.py index 646434326..765924a4e 100644 --- a/src/citrine/gemtables/variables.py +++ b/src/citrine/gemtables/variables.py @@ -66,11 +66,11 @@ def __eq__(self, other): return False @classmethod - def get_type(cls, data) -> Type[Serializable]: + def get_type(cls, data) -> type[Serializable]: """Return the subtype.""" if "type" not in data: raise ValueError("Can only get types from dicts with a 'type' key") - types: List[Type[Serializable]] = [ + types: list[type[Serializable]] = [ TerminalMaterialInfo, AttributeByTemplate, AttributeByTemplateAfterProcessTemplate, AttributeByTemplateAndObjectTemplate, LocalAttribute, LocalAttributeAndObject, IngredientIdentifierByProcessTemplateAndName, IngredientLabelByProcessAndName, @@ -109,7 +109,7 @@ class TerminalMaterialInfo(Serializable['TerminalMaterialInfo'], Variable): def __init__(self, name: str, *, - headers: List[str], + headers: list[str], field: str): self.name = name self.headers = headers @@ -127,7 +127,7 @@ class AttributeByTemplate(Serializable['AttributeByTemplate'], Variable): sequence of column headers template: Union[UUID, str, LinkByUID, AttributeTemplate] attribute template that identifies the attribute to assign to the variable - attribute_constraints: List[Tuple[Union[UUID, str, LinkByUID, AttributeTemplate], Bounds]] + attribute_constraints: list[tuple[Union[UUID, str, LinkByUID, AttributeTemplate], Bounds]] Optional constraints on object attributes in the target object that must be satisfied. Constraints are expressed as Bounds. Attributes are expressed with links. The attribute that the @@ -150,14 +150,14 @@ class AttributeByTemplate(Serializable['AttributeByTemplate'], Variable): typ = properties.String('type', default="attribute_by_template", deserializable=False) attribute_type = Union[UUID, str, LinkByUID, AttributeTemplate] - constraint_type = Tuple[attribute_type, BaseBounds] + constraint_type = tuple[attribute_type, BaseBounds] def __init__(self, name: str, *, - headers: List[str], + headers: list[str], template: attribute_type, - attribute_constraints: Optional[List[constraint_type]] = None, + attribute_constraints: Optional[list[constraint_type]] = None, type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN): self.name = name self.headers = headers @@ -181,7 +181,7 @@ class AttributeByTemplateAfterProcessTemplate( attribute template that identifies the attribute to assign to the variable process_template: Union[UUID, str, LinkByUID, ProcessTemplate] process template that identifies the originating process - attribute_constraints: List[Tuple[Union[UUID, str, LinkByUID, AttributeTemplate], Bounds]] + attribute_constraints: list[tuple[Union[UUID, str, LinkByUID, AttributeTemplate], Bounds]] Optional constraints on object attributes in the target object that must be satisfied. Constraints are expressed as Bounds. Attributes are expressed with links. The attribute that the @@ -206,15 +206,15 @@ class AttributeByTemplateAfterProcessTemplate( attribute_type = Union[UUID, str, LinkByUID, AttributeTemplate] process_type = Union[UUID, str, LinkByUID, ProcessTemplate] - constraint_type = Tuple[attribute_type, BaseBounds] + constraint_type = tuple[attribute_type, BaseBounds] def __init__(self, name: str, *, - headers: List[str], + headers: list[str], attribute_template: attribute_type, process_template: process_type, - attribute_constraints: Optional[List[constraint_type]] = None, + attribute_constraints: Optional[list[constraint_type]] = None, type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN): self.name = name self.headers = headers @@ -244,7 +244,7 @@ class AttributeByTemplateAndObjectTemplate( attribute template that identifies the attribute to assign to the variable object_template: Union[UUID, str, LinkByUID, BaseTemplate] template that identifies the associated object - attribute_constraints: List[Tuple[Union[UUID, str, LinkByUID, AttributeTemplate], Bounds]] + attribute_constraints: list[tuple[Union[UUID, str, LinkByUID, AttributeTemplate], Bounds]] Optional constraints on object attributes in the target object that must be satisfied. Constraints are expressed as Bounds. Attributes are expressed with links. The attribute that the @@ -269,15 +269,15 @@ class AttributeByTemplateAndObjectTemplate( attribute_type = Union[UUID, str, LinkByUID, AttributeTemplate] object_type = Union[UUID, str, LinkByUID, BaseTemplate] - constraint_type = Tuple[attribute_type, BaseBounds] + constraint_type = tuple[attribute_type, BaseBounds] def __init__(self, name: str, *, - headers: List[str], + headers: list[str], attribute_template: attribute_type, object_template: object_type, - attribute_constraints: Optional[List[constraint_type]] = None, + attribute_constraints: Optional[list[constraint_type]] = None, type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN): self.name = name self.headers = headers @@ -299,7 +299,7 @@ class LocalAttribute(Serializable['LocalAttribute'], Variable): sequence of column headers template: Union[UUID, str, LinkByUID, AttributeTemplate] attribute template that identifies the attribute to assign to the variable - attribute_constraints: List[Tuple[Union[UUID, str, LinkByUID, AttributeTemplate], Bounds]] + attribute_constraints: list[tuple[Union[UUID, str, LinkByUID, AttributeTemplate], Bounds]] Optional constraints on object attributes in the target object that must be satisfied. Constraints are expressed as Bounds. Attributes are expressed with links. The attribute that the @@ -322,14 +322,14 @@ class LocalAttribute(Serializable['LocalAttribute'], Variable): typ = properties.String('type', default="local_attribute", deserializable=False) attribute_type = Union[UUID, str, LinkByUID, AttributeTemplate] - constraint_type = Tuple[attribute_type, BaseBounds] + constraint_type = tuple[attribute_type, BaseBounds] def __init__(self, name: str, *, - headers: List[str], + headers: list[str], template: attribute_type, - attribute_constraints: Optional[List[constraint_type]] = None, + attribute_constraints: Optional[list[constraint_type]] = None, type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN): self.name = name self.headers = headers @@ -352,7 +352,7 @@ class LocalAttributeAndObject(Serializable['LocalAttributeAndObject'], Variable) attribute template that identifies the attribute to assign to the variable object_template: Union[UUID, str, LinkByUID, AttributeTemplate] attribute template that identifies the attribute to assign to the variable - attribute_constraints: List[Tuple[Union[UUID, str, LinkByUID, AttributeTemplate], Bounds]] + attribute_constraints: list[tuple[Union[UUID, str, LinkByUID, AttributeTemplate], Bounds]] Optional constraints on object attributes in the target object that must be satisfied. Constraints are expressed as Bounds. Attributes are expressed with links. The attribute that the @@ -377,15 +377,15 @@ class LocalAttributeAndObject(Serializable['LocalAttributeAndObject'], Variable) attribute_type = Union[UUID, str, LinkByUID, AttributeTemplate] object_type = Union[UUID, str, LinkByUID, BaseTemplate] - constraint_type = Tuple[attribute_type, BaseBounds] + constraint_type = tuple[attribute_type, BaseBounds] def __init__(self, name: str, *, - headers: List[str], + headers: list[str], template: attribute_type, object_template: object_type, - attribute_constraints: Optional[List[constraint_type]] = None, + attribute_constraints: Optional[list[constraint_type]] = None, type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN): self.name = name self.headers = headers @@ -430,7 +430,7 @@ class IngredientIdentifierByProcessTemplateAndName( def __init__(self, name: str, *, - headers: List[str], + headers: list[str], process_template: process_type, ingredient_name: str, scope: str, # Note that the default is set server side @@ -482,7 +482,7 @@ class IngredientLabelByProcessAndName(Serializable['IngredientLabelByProcessAndN def __init__(self, name: str, *, - headers: List[str], + headers: list[str], process_template: process_type, ingredient_name: str, label: str, @@ -529,7 +529,7 @@ class IngredientLabelsSetByProcessAndName( def __init__(self, name: str, *, - headers: List[str], + headers: list[str], process_template: process_type, ingredient_name: str): self.name = name @@ -580,7 +580,7 @@ class IngredientQuantityByProcessAndName( def __init__(self, name: str, *, - headers: List[str], + headers: list[str], process_template: process_type, ingredient_name: str, quantity_dimension: IngredientQuantityDimension, @@ -627,7 +627,7 @@ class TerminalMaterialIdentifier(Serializable['TerminalMaterialIdentifier'], Var def __init__(self, name: str, *, - headers: List[str], + headers: list[str], scope: str = CITRINE_SCOPE): self.name = name self.headers = headers @@ -667,7 +667,7 @@ class AttributeInOutput(Serializable['AttributeInOutput'], Variable): process_templates: list[LinkByUID] process templates that should not be traversed through when searching for a matching attribute. The attribute may be present in these processes but not their ingredients. - attribute_constraints: List[Tuple[Union[UUID, str, LinkByUID, AttributeTemplate], Bounds]] + attribute_constraints: list[tuple[Union[UUID, str, LinkByUID, AttributeTemplate], Bounds]] Optional constraints on object attributes in the target object that must be satisfied. Constraints are expressed as Bounds. Attributes are expressed with links. The attribute that the @@ -692,15 +692,15 @@ class AttributeInOutput(Serializable['AttributeInOutput'], Variable): attribute_type = Union[UUID, str, LinkByUID, AttributeTemplate] process_type = Union[UUID, str, LinkByUID, ProcessTemplate] - constraint_type = Tuple[attribute_type, BaseBounds] + constraint_type = tuple[attribute_type, BaseBounds] def __init__(self, name: str, *, - headers: List[str], + headers: list[str], attribute_template: attribute_type, - process_templates: List[process_type], - attribute_constraints: Optional[List[constraint_type]] = None, + process_templates: list[process_type], + attribute_constraints: Optional[list[constraint_type]] = None, type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN): self.name = name self.headers = headers @@ -769,9 +769,9 @@ class IngredientIdentifierInOutput(Serializable['IngredientIdentifierInOutput'], def __init__(self, name: str, *, - headers: List[str], + headers: list[str], ingredient_name: str, - process_templates: List[process_type], + process_templates: list[process_type], scope: str = CITRINE_SCOPE, type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN): self.name = name @@ -835,8 +835,8 @@ class IngredientLabelsSetInOutput(Serializable['IngredientLabelsSetInOutput'], V def __init__(self, name: str, *, - headers: List[str], - process_templates: List[process_type], + headers: list[str], + process_templates: list[process_type], ingredient_name: str): self.name = name self.headers = headers @@ -911,10 +911,10 @@ class IngredientQuantityInOutput(Serializable['IngredientQuantityInOutput'], Var def __init__(self, name: str, *, - headers: List[str], + headers: list[str], ingredient_name: str, quantity_dimension: IngredientQuantityDimension, - process_templates: List[process_type], + process_templates: list[process_type], type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN, unit: Optional[str] = None): self.name = name @@ -972,7 +972,7 @@ class LocalIngredientIdentifier(Serializable['LocalIngredientIdentifier'], Varia def __init__(self, name: str, *, - headers: List[str], + headers: list[str], ingredient_name: str, scope: str = CITRINE_SCOPE, type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN): @@ -1013,7 +1013,7 @@ class LocalIngredientLabelsSet(Serializable['LocalIngredientLabelsSet'], Variabl def __init__(self, name: str, *, - headers: List[str], + headers: list[str], ingredient_name: str): self.name = name self.headers = headers @@ -1062,7 +1062,7 @@ class LocalIngredientQuantity(Serializable['LocalIngredientQuantity'], Variable) def __init__(self, name: str, *, - headers: List[str], + headers: list[str], ingredient_name: str, quantity_dimension: IngredientQuantityDimension, type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN, diff --git a/src/citrine/informatics/catalyst/assistant.py b/src/citrine/informatics/catalyst/assistant.py index d9bf5939b..f0daf4134 100644 --- a/src/citrine/informatics/catalyst/assistant.py +++ b/src/citrine/informatics/catalyst/assistant.py @@ -36,7 +36,7 @@ class AssistantResponse(PolymorphicSerializable["AssistantResponse"]): """The parent type for all Model Assistant responses.""" @classmethod - def get_type(cls, data) -> Type['AssistantResponse']: + def get_type(cls, data) -> type['AssistantResponse']: """Return the subtype.""" type_dict = { "message": AssistantResponseMessage, diff --git a/src/citrine/informatics/constraints/categorical_constraint.py b/src/citrine/informatics/constraints/categorical_constraint.py index 3b381da6e..616013b0c 100644 --- a/src/citrine/informatics/constraints/categorical_constraint.py +++ b/src/citrine/informatics/constraints/categorical_constraint.py @@ -27,7 +27,7 @@ class AcceptableCategoriesConstraint(Serializable['AcceptableCategoriesConstrain def __init__(self, *, descriptor_key: str, - acceptable_categories: List[str]): + acceptable_categories: list[str]): self.descriptor_key = descriptor_key self.acceptable_categories = acceptable_categories diff --git a/src/citrine/informatics/constraints/ingredient_ratio_constraint.py b/src/citrine/informatics/constraints/ingredient_ratio_constraint.py index 8977470ed..bc6fcbcb3 100644 --- a/src/citrine/informatics/constraints/ingredient_ratio_constraint.py +++ b/src/citrine/informatics/constraints/ingredient_ratio_constraint.py @@ -63,10 +63,10 @@ def __init__(self, *, formulation_descriptor: FormulationDescriptor, min: float, max: float, - ingredient: Optional[Tuple[str, float]] = None, - label: Optional[Tuple[str, float]] = None, - basis_ingredients: Set[str] = set(), - basis_labels: Set[str] = set()): + ingredient: Optional[tuple[str, float]] = None, + label: Optional[tuple[str, float]] = None, + basis_ingredients: set[str] = set(), + basis_labels: set[str] = set()): self.formulation_descriptor = formulation_descriptor self.min = min self.max = max @@ -81,7 +81,7 @@ def ingredient(self): return self._numerator_read(self._ingredients) @ingredient.setter - def ingredient(self, value: Optional[Tuple[str, float]]): + def ingredient(self, value: Optional[tuple[str, float]]): """Set the ingredient and its multiplier in the numerator.""" self._ingredients = self._numerator_validate(value, "Ingredient") @@ -91,27 +91,27 @@ def label(self): return self._numerator_read(self._labels) @label.setter - def label(self, value: Optional[Tuple[str, float]]): + def label(self, value: Optional[tuple[str, float]]): """Set the label and its multiplier in the numerator.""" self._labels = self._numerator_validate(value, "Label") @property - def basis_ingredients(self) -> Set[str]: + def basis_ingredients(self) -> set[str]: """Retrieve the ingredients in the denominator of the ratio.""" return set(self._basis_ingredients.keys()) @basis_ingredients.setter - def basis_ingredients(self, value: Set[str]): + def basis_ingredients(self, value: set[str]): """Set the ingredients in the denominator of the ratio.""" self._basis_ingredients = dict.fromkeys(value, 1) @property - def basis_labels(self) -> Set[str]: + def basis_labels(self) -> set[str]: """Retrieve the labels in the denominator of the ratio.""" return set(self._basis_labels.keys()) @basis_labels.setter - def basis_labels(self, value: Set[str]): + def basis_labels(self, value: set[str]): """Set the labels in the denominator of the ratio.""" self._basis_labels = dict.fromkeys(value, 1) diff --git a/src/citrine/informatics/data_sources.py b/src/citrine/informatics/data_sources.py index 5b209100f..b3dfe02dd 100644 --- a/src/citrine/informatics/data_sources.py +++ b/src/citrine/informatics/data_sources.py @@ -31,11 +31,11 @@ def __eq__(self, other): return False @classmethod - def _subclass_list(self) -> List[Type[Serializable]]: + def _subclass_list(self) -> list[type[Serializable]]: return [GemTableDataSource, ExperimentDataSourceRef, SnapshotDataSource] @classmethod - def get_type(cls, data) -> Type[Serializable]: + def get_type(cls, data) -> type[Serializable]: """Return the subtype.""" if "type" not in data: raise ValueError("Can only get types from dicts with a 'type' key") diff --git a/src/citrine/informatics/descriptors.py b/src/citrine/informatics/descriptors.py index 692dfe91e..8154324be 100644 --- a/src/citrine/informatics/descriptors.py +++ b/src/citrine/informatics/descriptors.py @@ -38,7 +38,7 @@ class Descriptor(PolymorphicSerializable['Descriptor']): key = properties.String('descriptor_key') @classmethod - def get_type(cls, data) -> Type[Serializable]: + def get_type(cls, data) -> type[Serializable]: """Return the subtype.""" return { "Categorical": CategoricalDescriptor, @@ -60,7 +60,7 @@ def _equals(self, other, attrs): ---------- other: Description the Description instance to compare to - attrs: List[str] + attrs: list[str] A list of attribute names to lookup and compare """ @@ -216,7 +216,7 @@ class CategoricalDescriptor(Serializable['CategoricalDescriptor'], Descriptor): ---------- key: str the key corresponding to a descriptor - categories: Set[str] + categories: set[str] possible categories for this descriptor """ @@ -227,12 +227,12 @@ class CategoricalDescriptor(Serializable['CategoricalDescriptor'], Descriptor): def __eq__(self, other): return self._equals(other, ["key", "categories", "typ"]) - def __init__(self, key: str, *, categories: Set[str]): + def __init__(self, key: str, *, categories: set[str]): self.key: str = key for category in categories: if not isinstance(category, str): raise TypeError("All categories must be strings") - self.categories: Set[str] = categories + self.categories: set[str] = categories def __str__(self): return "".format(self.key) diff --git a/src/citrine/informatics/design_candidate.py b/src/citrine/informatics/design_candidate.py index 94fbcd275..760e7187d 100644 --- a/src/citrine/informatics/design_candidate.py +++ b/src/citrine/informatics/design_candidate.py @@ -40,7 +40,7 @@ def __init__(self, arg): pass # pragma: no cover @classmethod - def get_type(cls, data) -> Type[Serializable]: + def get_type(cls, data) -> type[Serializable]: """Return the subtype.""" return { "R": MeanAndStd, @@ -78,7 +78,7 @@ class TopCategories(Serializable["CategoriesAndProbabilities"], DesignVariable): """ probabilities = properties.Mapping(properties.String, properties.Float, 'cp') - """:Dict[str, float]: mapping from category names to their probabilities""" + """:dict[str, float]: mapping from category names to their probabilities""" typ = properties.String('type', default='C', deserializable=False) """:str: polymorphic type code""" @@ -95,9 +95,9 @@ class Mixture(Serializable["Mixture"], DesignVariable): """ quantities = properties.Mapping(properties.String, properties.Float, 'q') - """:Dict[str, float]: mapping from ingredient identifiers to their quantities""" + """:dict[str, float]: mapping from ingredient identifiers to their quantities""" labels = properties.Mapping(properties.String, properties.Set(properties.String), 'l') - """:Dict[str, Set[str]]: mapping from label identifiers to their associated ingredients""" + """:dict[str, set[str]]: mapping from label identifiers to their associated ingredients""" typ = properties.String('type', default='M', deserializable=False) """:str: polymorphic type code""" @@ -139,13 +139,13 @@ class DesignMaterial(Serializable["DesignMaterial"]): material_id = properties.UUID('identifiers.id') """:UUID: unique internal Citrine id of the material""" identifiers = properties.List(properties.String, 'identifiers.external', default=[]) - """:List[str]: globally unique identifiers assigned to the material""" + """:list[str]: globally unique identifiers assigned to the material""" process_template = properties.Optional(properties.UUID, 'identifiers.process_template') """:Optional[UUID]: GEMD process template that describes the process to create this material""" material_template = properties.Optional(properties.UUID, 'identifiers.material_template') """:Optional[UUID]: GEMD material template that describes this material""" values = properties.Mapping(properties.String, properties.Object(DesignVariable), 'vars') - """:Dict[str, DesignVariable]: mapping from descriptor keys to the value for this material""" + """:dict[str, DesignVariable]: mapping from descriptor keys to the value for this material""" def __init__(self, *, values: dict): self.values = values @@ -164,9 +164,9 @@ class HierarchicalDesignMaterial(Serializable["HierarchicalDesignMaterial"]): root = properties.Object(DesignMaterial, 'terminal') """:DesignMaterial: root material containing features and predicted properties""" sub_materials = properties.List(properties.Object(DesignMaterial), 'sub_materials') - """:List[DesignMaterial]: all other materials appearing in the history of the root""" + """:list[DesignMaterial]: all other materials appearing in the history of the root""" mixtures = properties.Mapping(properties.UUID, properties.Object(Mixture), 'mixtures') - """:Dict[UUID, Mixture]: mapping from Citrine ID to components the material is composed of""" + """:dict[UUID, Mixture]: mapping from Citrine ID to components the material is composed of""" class DesignCandidate(Serializable["DesignCandidate"]): @@ -180,7 +180,7 @@ class DesignCandidate(Serializable["DesignCandidate"]): material_id = properties.UUID('material_id') """:UUID: unique internal Citrine id of the material""" identifiers = properties.List(properties.String(), 'identifiers') - """:List[str]: globally unique identifiers assigned to the material""" + """:list[str]: globally unique identifiers assigned to the material""" primary_score = properties.Float('primary_score') """:float: numerical score describing how well the candidate satisfies the objectives and constraints (higher is better)""" diff --git a/src/citrine/informatics/design_spaces/formulation_design_space.py b/src/citrine/informatics/design_spaces/formulation_design_space.py index 216aec80b..1ca574396 100644 --- a/src/citrine/informatics/design_spaces/formulation_design_space.py +++ b/src/citrine/informatics/design_spaces/formulation_design_space.py @@ -20,14 +20,14 @@ class FormulationDesignSpace(Resource['FormulationDesignSpace'], DesignSubspace) the description of the design space formulation_descriptor: FormulationDescriptor descriptor used to store formulations sampled from the design space - ingredients: Set[str] + ingredients: set[str] set of ingredient names that can be used in a formulation - constraints: Set[IngredientConstraint] + constraints: set[IngredientConstraint] set of constraints that restricts formulations sampled from the space. This must include an :class:`~io.citrine.informatics.constraints.ingredient_count_constraint.IngredientCountConstraint` with maximum count of 32 or fewer. - labels: Optional[Mapping[str, Set[str]]] + labels: Optional[dict[str, set[str]]] map from a label to each ingredient that should given that label when it's included in a formulation, e.g., ``{'solvent': {'water', 'alcohol'}}`` resolution: float, optional @@ -52,16 +52,16 @@ def __init__(self, *, description: str, formulation_descriptor: FormulationDescriptor, - ingredients: Set[str], - constraints: Set[Constraint], - labels: Optional[Mapping[str, Set[str]]] = None, + ingredients: set[str], + constraints: set[Constraint], + labels: Optional[dict[str, set[str]]] = None, resolution: float = 0.0001): self.name: str = name self.description: str = description self.formulation_descriptor: FormulationDescriptor = formulation_descriptor - self.ingredients: Set[str] = ingredients - self.constraints: Set[Constraint] = constraints - self.labels: Optional[Mapping[str, Set[str]]] = labels + self.ingredients: set[str] = ingredients + self.constraints: set[Constraint] = constraints + self.labels: Optional[dict[str, set[str]]] = labels self.resolution: float = resolution def __str__(self): diff --git a/src/citrine/informatics/design_spaces/hierarchical_design_space.py b/src/citrine/informatics/design_spaces/hierarchical_design_space.py index 3a31e8b05..546f05cb6 100644 --- a/src/citrine/informatics/design_spaces/hierarchical_design_space.py +++ b/src/citrine/informatics/design_spaces/hierarchical_design_space.py @@ -63,7 +63,7 @@ class MaterialNodeDefinition(Serializable["MaterialNodeDefinition"]): in the formulation subspace of a different node. scope: Optional[str] An optional custom scope used to identify the materials produced by this node. - attributes: List[Dimension] + attributes: list[Dimension] Set of dimensions included on materials produced by this node. formulation_subspace: Optional[FormulationDesignSpace] An optional formulation design space defining the ingredients, labels, @@ -91,7 +91,7 @@ def __init__( *, name: str, scope: Optional[str] = None, - attributes: Optional[List[Dimension]] = None, + attributes: Optional[list[Dimension]] = None, formulation_subspace: Optional[FormulationDesignSpace] = None, template_link: Optional[TemplateLink] = None, display_name: Optional[str] = None @@ -144,9 +144,9 @@ class HierarchicalDesignSpace(EngineResource["HierarchicalDesignSpace"], TopLeve Description of the design space root: MaterialNodeDefinition Terminal material node produced by the design space - subspaces: List[MaterialNodeDefinition] + subspaces: list[MaterialNodeDefinition] Sub material nodes produced by the design space - data_sources: List[DataSource] + data_sources: list[DataSource] Data sources used to inject known materials into the hierarchical candidates """ @@ -170,14 +170,14 @@ def __init__( *, description: str, root: MaterialNodeDefinition, - subspaces: Optional[List[MaterialNodeDefinition]] = None, - data_sources: Optional[List[DataSource]] = None + subspaces: Optional[list[MaterialNodeDefinition]] = None, + data_sources: Optional[list[DataSource]] = None ): self.name: str = name self.description: str = description self.root: MaterialNodeDefinition = root - self.subspaces: List[MaterialNodeDefinition] = subspaces or list() - self.data_sources: List[DataSource] = data_sources or list() + self.subspaces: list[MaterialNodeDefinition] = subspaces or list() + self.data_sources: list[DataSource] = data_sources or list() def _post_dump(self, data: dict) -> dict: data = super()._post_dump(data) diff --git a/src/citrine/informatics/design_spaces/product_design_space.py b/src/citrine/informatics/design_spaces/product_design_space.py index ad0fed6be..458b52034 100644 --- a/src/citrine/informatics/design_spaces/product_design_space.py +++ b/src/citrine/informatics/design_spaces/product_design_space.py @@ -22,7 +22,7 @@ class ProductDesignSpace(EngineResource['ProductDesignSpace'], TopLevelDesignSpa the name of the design space description:str the description of the design space - subspaces: List[Union[UUID, DesignSubspace]] + subspaces: list[Union[UUID, DesignSubspace]] the list of subspaces to combine, defined in-line dimensions: list[Dimension] univariate dimensions that are factors of the design space; can be enumerated or continuous @@ -44,12 +44,12 @@ def __init__(self, name: str, *, description: str, - subspaces: Optional[List[Union[UUID, DesignSubspace]]] = None, - dimensions: Optional[List[Dimension]] = None): + subspaces: Optional[list[Union[UUID, DesignSubspace]]] = None, + dimensions: Optional[list[Dimension]] = None): self.name: str = name self.description: str = description - self.subspaces: List[Union[UUID, DesignSubspace]] = subspaces or [] - self.dimensions: List[Dimension] = dimensions or [] + self.subspaces: list[Union[UUID, DesignSubspace]] = subspaces or [] + self.dimensions: list[Dimension] = dimensions or [] def _post_dump(self, data: dict) -> dict: data = super()._post_dump(data) diff --git a/src/citrine/informatics/design_spaces/subspace.py b/src/citrine/informatics/design_spaces/subspace.py index a6a3a614e..684662ea7 100644 --- a/src/citrine/informatics/design_spaces/subspace.py +++ b/src/citrine/informatics/design_spaces/subspace.py @@ -18,7 +18,7 @@ class DesignSubspace(PolymorphicSerializable["DesignSubspace"], DesignSpace): description = properties.Optional(properties.String(), "description") @classmethod - def get_type(cls, data) -> Type['DesignSubspace']: + def get_type(cls, data) -> type['DesignSubspace']: """Return the subtype.""" from .data_source_design_space import DataSourceDesignSpace from .formulation_design_space import FormulationDesignSpace diff --git a/src/citrine/informatics/design_spaces/top_level_design_space.py b/src/citrine/informatics/design_spaces/top_level_design_space.py index 033178e31..817fba68c 100644 --- a/src/citrine/informatics/design_spaces/top_level_design_space.py +++ b/src/citrine/informatics/design_spaces/top_level_design_space.py @@ -57,7 +57,7 @@ def wrap_instance(subspace_data: dict) -> dict: _failed_statuses = ["INVALID", "ERROR"] @classmethod - def get_type(cls, data) -> Type[Serializable]: + def get_type(cls, data) -> type[Serializable]: """Return the subtype.""" from .product_design_space import ProductDesignSpace from .hierarchical_design_space import HierarchicalDesignSpace diff --git a/src/citrine/informatics/dimensions.py b/src/citrine/informatics/dimensions.py index db73e50aa..696a106b7 100644 --- a/src/citrine/informatics/dimensions.py +++ b/src/citrine/informatics/dimensions.py @@ -17,7 +17,7 @@ class Dimension(PolymorphicSerializable['Dimension']): """ @classmethod - def get_type(cls, data) -> Type[Serializable]: + def get_type(cls, data) -> type[Serializable]: """Return the subtype.""" return { 'ContinuousDimension': ContinuousDimension, @@ -100,6 +100,6 @@ class EnumeratedDimension(Serializable['EnumeratedDimension'], Dimension): def __init__(self, descriptor: Descriptor, *, - values: List[str]): + values: list[str]): self.descriptor: Descriptor = descriptor - self.values: List[str] = values + self.values: list[str] = values diff --git a/src/citrine/informatics/executions/design_execution.py b/src/citrine/informatics/executions/design_execution.py index 0511cd06f..49d25bd28 100644 --- a/src/citrine/informatics/executions/design_execution.py +++ b/src/citrine/informatics/executions/design_execution.py @@ -31,7 +31,7 @@ class DesignExecution(Resource["DesignExecution"], Execution): score = properties.Object(Score, 'score') """:Score: score by which this execution was evaluated""" descriptors = properties.List(properties.Object(Descriptor), 'descriptors') - """:List[Descriptor]: all of the descriptors in the candidates generated by this execution""" + """:list[Descriptor]: all of the descriptors in the candidates generated by this execution""" def _path(self): return format_escaped_url( diff --git a/src/citrine/informatics/executions/execution.py b/src/citrine/informatics/executions/execution.py index ea873f9eb..a00a07111 100644 --- a/src/citrine/informatics/executions/execution.py +++ b/src/citrine/informatics/executions/execution.py @@ -34,7 +34,7 @@ class Execution(Pageable, AsynchronousObject, ABC): status_detail = properties.List( properties.Object(StatusDetail), 'status_detail', default=[], serializable=False ) - """:List[StatusDetail]: a list of structured status info, containing the message and level""" + """:list[StatusDetail]: a list of structured status info, containing the message and level""" created_by = properties.Optional(properties.UUID, 'created_by', serializable=False) """:Optional[UUID]: id of the user who created the resource""" updated_by = properties.Optional(properties.UUID, 'updated_by', serializable=False) diff --git a/src/citrine/informatics/executions/predictor_evaluation.py b/src/citrine/informatics/executions/predictor_evaluation.py index f74dcd113..3f7a4599e 100644 --- a/src/citrine/informatics/executions/predictor_evaluation.py +++ b/src/citrine/informatics/executions/predictor_evaluation.py @@ -19,7 +19,7 @@ class PredictorEvaluatorsResponse(Serializable['EvaluatorsPayload']): evaluators = properties.List(properties.Object(PredictorEvaluator), "evaluators") - def __init__(self, evaluators: List[PredictorEvaluator]): + def __init__(self, evaluators: list[PredictorEvaluator]): self.evaluators = evaluators @@ -31,7 +31,7 @@ class PredictorEvaluationRequest(Serializable['EvaluatorsPayload']): def __init__(self, *, - evaluators: List[PredictorEvaluator], + evaluators: list[PredictorEvaluator], predictor_id: Union[UUID, str], predictor_version: Optional[Union[int, str]] = None): self.evaluators = evaluators @@ -45,7 +45,7 @@ class PredictorEvaluation(EngineResourceWithoutStatus['PredictorEvaluation'], As """:UUID: Unique identifier of the evaluation""" evaluators = properties.List(properties.Object(PredictorEvaluator), "data.evaluators", serializable=False) - """:List{PredictorEvaluator]:the predictor evaluators that were executed. These are used + """:list[PredictorEvaluator]:the predictor evaluators that were executed. These are used when calling the ``results()`` method.""" predictor_id = properties.UUID('metadata.predictor_id', serializable=False) """:UUID:""" @@ -56,7 +56,7 @@ class PredictorEvaluation(EngineResourceWithoutStatus['PredictorEvaluation'], As """:str: more detailed description of the evaluation's status""" status_detail = properties.List(properties.Object(StatusDetail), 'metadata.status.detail', default=[], serializable=False) - """:List[StatusDetail]: a list of structured status info, containing the message and level""" + """:list[StatusDetail]: a list of structured status info, containing the message and level""" project_id: Optional[UUID] = None _session: Optional[Session] = None diff --git a/src/citrine/informatics/experiment_values.py b/src/citrine/informatics/experiment_values.py index d73a62f0c..372021029 100644 --- a/src/citrine/informatics/experiment_values.py +++ b/src/citrine/informatics/experiment_values.py @@ -22,7 +22,7 @@ class ExperimentValue(PolymorphicSerializable['ExperimentValue']): """ @classmethod - def get_type(cls, data) -> Type[Serializable]: + def get_type(cls, data) -> type[Serializable]: """Return the subtype.""" return { "RealValue": RealExperimentValue, @@ -53,7 +53,7 @@ def _equals(self, other, attrs) -> bool: ---------- other: Description the Description instance to compare to - attrs: List[str] + attrs: list[str] A list of attribute names to lookup and compare """ @@ -104,7 +104,7 @@ class MixtureExperimentValue(Serializable['MixtureExperimentValue'], ExperimentV value = properties.Mapping(properties.String, properties.Float, 'value') typ = properties.String('type', default='MixtureValue', deserializable=False) - def __init__(self, value: Dict[str, float]): + def __init__(self, value: dict[str, float]): self.value = value diff --git a/src/citrine/informatics/feature_effects.py b/src/citrine/informatics/feature_effects.py index d0cd04d6e..08f2f8aed 100644 --- a/src/citrine/informatics/feature_effects.py +++ b/src/citrine/informatics/feature_effects.py @@ -20,7 +20,7 @@ class ShapleyFeature(Resource): serializable=False) @property - def material_dict(self) -> Dict[UUID, float]: + def material_dict(self) -> dict[UUID, float]: """Presents the feature's effects as a dictionary by material.""" return {material.material_id: material.value for material in self.materials} @@ -32,7 +32,7 @@ class ShapleyOutput(Resource): features = properties.List(properties.Object(ShapleyFeature), 'features', serializable=False) @property - def feature_dict(self) -> Dict[str, Dict[UUID, float]]: + def feature_dict(self) -> dict[str, dict[UUID, float]]: """Presents the output's feature effects as a dictionary by feature.""" return {feature.feature: feature.material_dict for feature in self.features} @@ -74,7 +74,7 @@ def _pre_build(cls, data: dict) -> Dict: return data @property - def as_dict(self) -> Dict[str, Dict[str, Dict[UUID, float]]]: + def as_dict(self) -> dict[str, dict[str, dict[UUID, float]]]: """Presents the feature effects as a dictionary by output.""" if self.outputs: return {output.output: output.feature_dict for output in self.outputs} diff --git a/src/citrine/informatics/generative_design.py b/src/citrine/informatics/generative_design.py index eb0432eb1..d1a49cd7f 100644 --- a/src/citrine/informatics/generative_design.py +++ b/src/citrine/informatics/generative_design.py @@ -96,7 +96,7 @@ class GenerativeDesignInput(Serializable['GenerativeDesignInput']): Parameters ---------- - seeds: List[str] + seeds: list[str] The seeds used to generate the molecules. fingerprint_type: FingerprintType The fingerprint type used to calculate the fingerprint similarity. @@ -106,10 +106,10 @@ class GenerativeDesignInput(Serializable['GenerativeDesignInput']): The number of initial mutations that will be attempted per seed. IMPORTANT, the total number of molecules generated will likely be lower than this value. Some mutations may be duplicates or may not meet the fingerprint similarity threshold. - structure_exclusions: List[StructureExclusion] + structure_exclusions: list[StructureExclusion] The structure exclusions used to limit molecule mutations. If None, no structure exclusions will be used. - min_substructure_counts: Dict[str, int] + min_substructure_counts: dict[str, int] Dictionary for constraining which substructures (represented by SMARTS strings, not SMILES) must appear in each mutated molecule, along with integer values representing the minimum number of times each substructure must appear in a @@ -131,16 +131,16 @@ class GenerativeDesignInput(Serializable['GenerativeDesignInput']): def __init__( self, *, - seeds: List[str], + seeds: list[str], fingerprint_type: FingerprintType, min_fingerprint_similarity: float, mutation_per_seed: int, - structure_exclusions: Optional[List[StructureExclusion]] = None, - min_substructure_counts: Optional[Dict[str, int]] = None, + structure_exclusions: Optional[list[StructureExclusion]] = None, + min_substructure_counts: Optional[dict[str, int]] = None, ): - self.seeds: List[str] = seeds + self.seeds: list[str] = seeds self.fingerprint_type: FingerprintType = fingerprint_type self.min_fingerprint_similarity: float = min_fingerprint_similarity self.mutation_per_seed: int = mutation_per_seed - self.structure_exclusions: List[StructureExclusion] = structure_exclusions or [] - self.min_substructure_counts: Dict[str, int] = min_substructure_counts or {} + self.structure_exclusions: list[StructureExclusion] = structure_exclusions or [] + self.min_substructure_counts: dict[str, int] = min_substructure_counts or {} diff --git a/src/citrine/informatics/predict_request.py b/src/citrine/informatics/predict_request.py index b2c2adab0..fdb8761e5 100644 --- a/src/citrine/informatics/predict_request.py +++ b/src/citrine/informatics/predict_request.py @@ -19,7 +19,7 @@ class PredictRequest(Serializable["PredictRequest"]): random_seed = properties.Optional(properties.Integer, 'random_seed') def __init__(self, material_id: UUID, - identifiers: List[str], + identifiers: list[str], material: DesignMaterial, created_from_id: UUID, *, diff --git a/src/citrine/informatics/predictor_evaluation_metrics.py b/src/citrine/informatics/predictor_evaluation_metrics.py index 1d1a37a66..390b315a5 100644 --- a/src/citrine/informatics/predictor_evaluation_metrics.py +++ b/src/citrine/informatics/predictor_evaluation_metrics.py @@ -35,7 +35,7 @@ def __eq__(self, other): return False @classmethod - def get_type(cls, data) -> Type[Serializable]: + def get_type(cls, data) -> type[Serializable]: """Return the subtype.""" t = data["type"] return { diff --git a/src/citrine/informatics/predictor_evaluation_result.py b/src/citrine/informatics/predictor_evaluation_result.py index b71176a1f..6e25e72ae 100644 --- a/src/citrine/informatics/predictor_evaluation_result.py +++ b/src/citrine/informatics/predictor_evaluation_result.py @@ -26,7 +26,7 @@ def __init__(self): pass # pragma: no cover @classmethod - def get_type(cls, data) -> Type[Serializable]: + def get_type(cls, data) -> type[Serializable]: """Return the subtype.""" return { "RealMetricValue": RealMetricValue, @@ -57,7 +57,7 @@ class PredictedVsActualRealPoint(Serializable["PredictedVsActualRealPoint"]): uuid = properties.UUID("uuid") """:UUID: Unique Citrine id given to the candidate""" identifiers = properties.Set(properties.String, "identifiers") - """:Set[str]: Set of globally unique identifiers given to the candidate""" + """:set[str]: Set of globally unique identifiers given to the candidate""" trial = properties.Integer("trial") """:int: 1-based index of the trial this candidate belonged to""" fold = properties.Integer("fold") @@ -77,16 +77,16 @@ class PredictedVsActualCategoricalPoint(Serializable["PredictedVsActualCategoric uuid = properties.UUID("uuid") """:UUID: Unique Citrine id given to the candidate""" identifiers = properties.Set(properties.String, "identifiers") - """:Set[str]: Set of globally unique identifiers given to the candidate""" + """:set[str]: Set of globally unique identifiers given to the candidate""" trial = properties.Integer("trial") """:int: 1-based index of the trial this candidate belonged to""" fold = properties.Integer("fold") """:int: 1-based index of the fold this candidate belonged to""" predicted = properties.Mapping(properties.String, properties.Float, "predicted") - """:Dict[str, float]: Predicted class probabilities defined as a map from each class name + """:dict[str, float]: Predicted class probabilities defined as a map from each class name to its relative frequency""" actual = properties.Mapping(properties.String, properties.Float, "actual") - """:Dict[str, float]: Actual class probabilities defined as a map from each class name + """:dict[str, float]: Actual class probabilities defined as a map from each class name to its relative frequency""" def __init__(self): @@ -97,7 +97,7 @@ class CategoricalPredictedVsActual(Serializable["CategoricalPredictedVsActual"], """List of predicted vs. actual data points for a categorical value.""" value = properties.List(properties.Object(PredictedVsActualCategoricalPoint), "value") - """:List[PredictedVsActualCategoricalPoint]: List of predicted vs. actual data computed during + """:list[PredictedVsActualCategoricalPoint]: List of predicted vs. actual data computed during a predictor evaluation. This is a flattened list that contains data for all trials and folds.""" typ = properties.String('type', default='CategoricalPredictedVsActual', deserializable=False) @@ -113,7 +113,7 @@ class RealPredictedVsActual(Serializable["RealPredictedVsActual"], MetricValue): """List of predicted vs. actual data points for a real value.""" value = properties.List(properties.Object(PredictedVsActualRealPoint), "value") - """:List[PredictedVsActualRealPoint]: List of predicted vs. actual data computed during + """:list[PredictedVsActualRealPoint]: List of predicted vs. actual data computed during a predictor evaluation. This is a flattened list that contains data for all trials and folds.""" typ = properties.String('type', default='RealPredictedVsActual', deserializable=False) @@ -134,7 +134,7 @@ class ResponseMetrics(Serializable["ResponseMetrics"]): """ metrics = properties.Mapping(properties.String, properties.Object(MetricValue), "metrics") - """:Dict[str, MetricValue]: Metrics computed for a single response, keyed by the + """:dict[str, MetricValue]: Metrics computed for a single response, keyed by the metric's ``__repr__``.""" def __init__(self): @@ -162,7 +162,7 @@ def __init__(self): pass # pragma: no cover @classmethod - def get_type(cls, data) -> Type[Serializable]: + def get_type(cls, data) -> type[Serializable]: """Return the subtype.""" return { "CrossValidationResult": CrossValidationResult, @@ -175,13 +175,13 @@ def evaluator(self) -> PredictorEvaluator: raise NotImplementedError # pragma: no cover @property - def responses(self) -> Set[str]: + def responses(self) -> set[str]: """Predictor responses that were evaluated.""" raise NotImplementedError # pragma: no cover @property - def metrics(self) -> Set[PredictorEvaluationMetric]: - """:Set[PredictorEvaluationMetric]: Metrics computed for predictor responses.""" + def metrics(self) -> set[PredictorEvaluationMetric]: + """:set[PredictorEvaluationMetric]: Metrics computed for predictor responses.""" raise NotImplementedError # pragma: no cover @@ -213,13 +213,13 @@ def evaluator(self) -> CrossValidationEvaluator: return self._evaluator @property - def responses(self) -> Set[str]: + def responses(self) -> set[str]: """Responses for which results are present.""" return set(self._response_results.keys()) @property - def metrics(self) -> Set[PredictorEvaluationMetric]: - """:Set[PredictorEvaluationMetric]: Metrics for which results are present.""" + def metrics(self) -> set[PredictorEvaluationMetric]: + """:set[PredictorEvaluationMetric]: Metrics for which results are present.""" return self._evaluator.metrics @@ -251,11 +251,11 @@ def evaluator(self) -> HoldoutSetEvaluator: return self._evaluator @property - def responses(self) -> Set[str]: + def responses(self) -> set[str]: """Responses for which results are present.""" return set(self._response_results.keys()) @property - def metrics(self) -> Set[PredictorEvaluationMetric]: - """:Set[PredictorEvaluationMetric]: Metrics for which results are present.""" + def metrics(self) -> set[PredictorEvaluationMetric]: + """:set[PredictorEvaluationMetric]: Metrics for which results are present.""" return self._evaluator.metrics diff --git a/src/citrine/informatics/predictor_evaluator.py b/src/citrine/informatics/predictor_evaluator.py index 499f6407b..e7208295c 100644 --- a/src/citrine/informatics/predictor_evaluator.py +++ b/src/citrine/informatics/predictor_evaluator.py @@ -16,7 +16,7 @@ class PredictorEvaluator(PolymorphicSerializable["PredictorEvaluator"]): """A Citrine Predictor Evaluator computes metrics on a predictor.""" @classmethod - def get_type(cls, data) -> Type[Serializable]: + def get_type(cls, data) -> type[Serializable]: """Return the subtype.""" return { "CrossValidationEvaluator": CrossValidationEvaluator, @@ -42,12 +42,12 @@ def __eq__(self, other): return False @property - def responses(self) -> Set[str]: + def responses(self) -> set[str]: """Responses to compute metrics for.""" raise NotImplementedError # pragma: no cover @property - def metrics(self) -> Set[PredictorEvaluationMetric]: + def metrics(self) -> set[PredictorEvaluationMetric]: """Metrics to compute for each response.""" raise NotImplementedError # pragma: no cover @@ -84,16 +84,16 @@ class CrossValidationEvaluator(Serializable["CrossValidationEvaluator"], Predict Name of the evaluator description: str Description of the evaluator - responses: Set[str] + responses: set[str] Set of descriptor keys to evaluate n_folds: int Number of cross-validation folds n_trials: int Number of cross-validation trials, each contains ``n_folds`` folds - metrics: Optional[Set[PredictorEvaluationMetric]] + metrics: Optional[set[PredictorEvaluationMetric]] Optional set of metrics to compute for each response. Default is all metrics. - ignore_when_grouping: Optional[Set[str]] + ignore_when_grouping: Optional[set[str]] Set of descriptor keys to group together. Candidates with different values for the given keys and identical values for all other descriptors will be in the same group. @@ -115,26 +115,26 @@ def __init__(self, name: str, *, description: str = "", - responses: Set[str], + responses: set[str], n_folds: int = 5, n_trials: int = 3, - metrics: Optional[Set[PredictorEvaluationMetric]] = None, - ignore_when_grouping: Optional[Set[str]] = None): + metrics: Optional[set[PredictorEvaluationMetric]] = None, + ignore_when_grouping: Optional[set[str]] = None): self.name: str = name self.description: str = description - self._responses: Set[str] = responses - self._metrics: Optional[Set[PredictorEvaluationMetric]] = metrics + self._responses: set[str] = responses + self._metrics: Optional[set[PredictorEvaluationMetric]] = metrics self.n_folds: int = n_folds self.n_trials: int = n_trials - self.ignore_when_grouping: Optional[Set[str]] = ignore_when_grouping + self.ignore_when_grouping: Optional[set[str]] = ignore_when_grouping @property - def responses(self) -> Set[str]: + def responses(self) -> set[str]: """Set of predictor responses cross-validated by the evaluator.""" return self._responses @property - def metrics(self) -> Set[PredictorEvaluationMetric]: + def metrics(self) -> set[PredictorEvaluationMetric]: """Set of metrics computed during cross-validation.""" return self._metrics @@ -150,11 +150,11 @@ class HoldoutSetEvaluator(Serializable["HoldoutSetEvaluator"], PredictorEvaluato ---------- name: str Name of the evaluator - responses: Set[str] + responses: set[str] Set of descriptor keys to evaluate data_source: DataSource Source of holdout data - metrics: Optional[Set[PredictorEvaluationMetric]] + metrics: Optional[set[PredictorEvaluationMetric]] Optional set of metrics to compute for each response. Default is all metrics. """ @@ -170,21 +170,21 @@ class HoldoutSetEvaluator(Serializable["HoldoutSetEvaluator"], PredictorEvaluato def __init__(self, name: str, *, description: str = "", - responses: Set[str], + responses: set[str], data_source: DataSource, - metrics: Optional[Set[PredictorEvaluationMetric]] = None): + metrics: Optional[set[PredictorEvaluationMetric]] = None): self.name: str = name self.description: str = description - self._responses: Set[str] = responses + self._responses: set[str] = responses self.data_source = data_source - self._metrics: Optional[Set[PredictorEvaluationMetric]] = metrics + self._metrics: Optional[set[PredictorEvaluationMetric]] = metrics @property - def responses(self) -> Set[str]: + def responses(self) -> set[str]: """Set of responses to predict and compare against the ground-truth values.""" return self._responses @property - def metrics(self) -> Set[PredictorEvaluationMetric]: + def metrics(self) -> set[PredictorEvaluationMetric]: """Set of metrics computed on the predictions.""" return self._metrics diff --git a/src/citrine/informatics/predictors/attribute_accumulation_predictor.py b/src/citrine/informatics/predictors/attribute_accumulation_predictor.py index 963da002d..c944653ec 100644 --- a/src/citrine/informatics/predictors/attribute_accumulation_predictor.py +++ b/src/citrine/informatics/predictors/attribute_accumulation_predictor.py @@ -22,7 +22,7 @@ def __init__(self, name: str, *, description: str, - attributes: List[Descriptor], + attributes: list[Descriptor], sequential: bool): self.name = name self.description = description diff --git a/src/citrine/informatics/predictors/auto_ml_predictor.py b/src/citrine/informatics/predictors/auto_ml_predictor.py index db7b0ae8d..bf6951994 100644 --- a/src/citrine/informatics/predictors/auto_ml_predictor.py +++ b/src/citrine/informatics/predictors/auto_ml_predictor.py @@ -47,7 +47,7 @@ class AutoMLPredictor(Resource["AutoMLPredictor"], PredictorNode): Descriptors that represent inputs to the model outputs: list[Descriptor] Descriptors that represents the output(s) of the model. - estimators: Optional[Set[AutoMLEstimator]] + estimators: Optional[set[AutoMLEstimator]] Set of estimators to consider during during AutoML model selection. If None is provided, defaults to AutoMLEstimator.RANDOM_FOREST. @@ -67,13 +67,13 @@ def __init__(self, name: str, *, description: str, - outputs: List[Descriptor], - inputs: List[Descriptor], - estimators: Optional[Set[AutoMLEstimator]] = None): + outputs: list[Descriptor], + inputs: list[Descriptor], + estimators: Optional[set[AutoMLEstimator]] = None): self.name: str = name self.description: str = description - self.inputs: List[Descriptor] = inputs - self.estimators: Set[AutoMLEstimator] = estimators or {AutoMLEstimator.RANDOM_FOREST} + self.inputs: list[Descriptor] = inputs + self.estimators: set[AutoMLEstimator] = estimators or {AutoMLEstimator.RANDOM_FOREST} self.outputs = outputs def __str__(self): diff --git a/src/citrine/informatics/predictors/chemical_formula_featurizer.py b/src/citrine/informatics/predictors/chemical_formula_featurizer.py index b22f93477..15140b3fb 100644 --- a/src/citrine/informatics/predictors/chemical_formula_featurizer.py +++ b/src/citrine/informatics/predictors/chemical_formula_featurizer.py @@ -120,12 +120,12 @@ class ChemicalFormulaFeaturizer(Resource["ChemicalFormulaFeaturizer"], Predictor ---------- input_descriptor: ChemicalFormulaDescriptor the descriptor to featurize - features: Optional[List[str]] + features: Optional[list[str]] The list of features to compute, either by name or by group alias. Default is "standard." - excludes: Optional[List[str]] + excludes: Optional[list[str]] The list of features to exclude, either by name or by group alias. Default is none. The final set of features generated by the predictor is set(features) - set(excludes). - powers: Optional[List[float]] + powers: Optional[list[int]] The list of powers to use when computing generalized weighted means of element properties. p=1.0 corresponds to the ordinary mean, p=2.0 is the root mean square, etc. @@ -143,9 +143,9 @@ def __init__(self, *, description: str, input_descriptor: ChemicalFormulaDescriptor, - features: Optional[List[str]] = None, - excludes: Optional[List[str]] = None, - powers: Optional[List[float]] = None): + features: Optional[list[str]] = None, + excludes: Optional[list[str]] = None, + powers: Optional[list[float]] = None): self.name = name self.description = description self.input_descriptor = input_descriptor @@ -154,7 +154,7 @@ def __init__(self, self.powers = powers if powers is not None else [1.0] @property - def powers_as_float(self) -> List[float]: + def powers_as_float(self) -> list[float]: """Powers when computing generalized weighted means of element properties.""" warn("'powers_as_float' is deprecated as of v4.0.0 in favor of 'powers', and will be " "removed in v5.0.0", diff --git a/src/citrine/informatics/predictors/expression_predictor.py b/src/citrine/informatics/predictors/expression_predictor.py index 47f5e36a9..09fdeacb1 100644 --- a/src/citrine/informatics/predictors/expression_predictor.py +++ b/src/citrine/informatics/predictors/expression_predictor.py @@ -24,7 +24,7 @@ class ExpressionPredictor(Resource["ExpressionPredictor"], PredictorNode): expression that computes an output from aliased inputs output: RealDescriptor descriptor that represents the output of the expression - aliases: Mapping[str, RealDescriptor] + aliases: dict[str, RealDescriptor] a mapping from each unknown argument to its descriptor. All unknown arguments must have an associated descriptor. @@ -44,12 +44,12 @@ def __init__(self, description: str, expression: str, output: RealDescriptor, - aliases: Mapping[str, RealDescriptor]): + aliases: dict[str, RealDescriptor]): self.name: str = name self.description: str = description self.expression: str = expression self.output: RealDescriptor = output - self.aliases: Mapping[str, RealDescriptor] = aliases + self.aliases: dict[str, RealDescriptor] = aliases def __str__(self): return ''.format(self.name) diff --git a/src/citrine/informatics/predictors/graph_predictor.py b/src/citrine/informatics/predictors/graph_predictor.py index 324a2fbb0..3027e953b 100644 --- a/src/citrine/informatics/predictors/graph_predictor.py +++ b/src/citrine/informatics/predictors/graph_predictor.py @@ -29,9 +29,9 @@ class GraphPredictor(VersionedEngineResource['GraphPredictor'], AsynchronousObje name of the configuration description: str the description of the predictor - predictors: List[Union[UUID, PredictorNode]], + predictors: list[Union[UUID, PredictorNode]], the list of individual predictors to use in the graph - training_data: Optional[List[DataSource]] + training_data: Optional[list[DataSource]] Optional sources of training data shared by all predictors in the graph. Training data provided by this graph predictor does not need to be specified as part of the configuration of sub-predictors. Shared training data and any training data specified @@ -73,12 +73,12 @@ def __init__(self, name: str, *, description: str, - predictors: List[PredictorNode], - training_data: Optional[List[DataSource]] = None): + predictors: list[PredictorNode], + training_data: Optional[list[DataSource]] = None): self.name: str = name self.description: str = description - self.training_data: List[DataSource] = training_data or [] - self.predictors: List[PredictorNode] = predictors + self.training_data: list[DataSource] = training_data or [] + self.predictors: list[PredictorNode] = predictors def __str__(self): return ''.format(self.name) diff --git a/src/citrine/informatics/predictors/ingredient_fractions_predictor.py b/src/citrine/informatics/predictors/ingredient_fractions_predictor.py index 449486950..deb30741d 100644 --- a/src/citrine/informatics/predictors/ingredient_fractions_predictor.py +++ b/src/citrine/informatics/predictors/ingredient_fractions_predictor.py @@ -19,7 +19,7 @@ class IngredientFractionsPredictor(Resource["IngredientFractionsPredictor"], Pre the description of the predictor input_descriptor: FormulationDescriptor descriptor that represents the input formulation - ingredients: Set[str] + ingredients: set[str] set of ingredients to featurize. If an unknown ingredient is encountered, an error will be thrown. @@ -35,11 +35,11 @@ def __init__(self, *, description: str, input_descriptor: FormulationDescriptor, - ingredients: Set[str]): + ingredients: set[str]): self.name: str = name self.description: str = description self.input_descriptor: FormulationDescriptor = input_descriptor - self.ingredients: Set[str] = ingredients + self.ingredients: set[str] = ingredients def __str__(self): return ''.format(self.name) diff --git a/src/citrine/informatics/predictors/ingredients_to_formulation_predictor.py b/src/citrine/informatics/predictors/ingredients_to_formulation_predictor.py index e068ee3b7..4fcd1a15f 100644 --- a/src/citrine/informatics/predictors/ingredients_to_formulation_predictor.py +++ b/src/citrine/informatics/predictors/ingredients_to_formulation_predictor.py @@ -19,10 +19,10 @@ class IngredientsToFormulationPredictor( name of the configuration description: str description of the predictor - id_to_quantity: Mapping[str, RealDescriptor] + id_to_quantity: dict[str, RealDescriptor] Map from ingredient identifier to the descriptor that represents its quantity, e.g., ``{'water': RealDescriptor('water quantity', 0, 1, "")}`` - labels: Mapping[str, Set[str]] + labels: dict[str, set[str]] Map from each label to all ingredients assigned that label, when present in a mixture, e.g., ``{'solvent': {'water'}}`` @@ -39,12 +39,12 @@ def __init__(self, name: str, *, description: str, - id_to_quantity: Mapping[str, RealDescriptor], - labels: Mapping[str, Set[str]]): + id_to_quantity: dict[str, RealDescriptor], + labels: dict[str, set[str]]): self.name: str = name self.description: str = description - self.id_to_quantity: Mapping[str, RealDescriptor] = id_to_quantity - self.labels: Mapping[str, Set[str]] = labels + self.id_to_quantity: dict[str, RealDescriptor] = id_to_quantity + self.labels: dict[str, set[str]] = labels def __str__(self): return ''.format(self.name) diff --git a/src/citrine/informatics/predictors/label_fractions_predictor.py b/src/citrine/informatics/predictors/label_fractions_predictor.py index 2bdf3ff0a..319249d3d 100644 --- a/src/citrine/informatics/predictors/label_fractions_predictor.py +++ b/src/citrine/informatics/predictors/label_fractions_predictor.py @@ -19,7 +19,7 @@ class LabelFractionsPredictor(Resource["LabelFractionsPredictor"], PredictorNode description of the predictor input_descriptor: FormulationDescriptor descriptor that contains formulation data - labels: Set[str] + labels: set[str] labels to compute the quantity fractions of """ @@ -34,11 +34,11 @@ def __init__(self, *, description: str, input_descriptor: FormulationDescriptor, - labels: Set[str]): + labels: set[str]): self.name: str = name self.description: str = description self.input_descriptor: FormulationDescriptor = input_descriptor - self.labels: Set[str] = labels + self.labels: set[str] = labels def __str__(self): return ''.format(self.name) diff --git a/src/citrine/informatics/predictors/mean_property_predictor.py b/src/citrine/informatics/predictors/mean_property_predictor.py index 7d8606bc7..4b6821688 100644 --- a/src/citrine/informatics/predictors/mean_property_predictor.py +++ b/src/citrine/informatics/predictors/mean_property_predictor.py @@ -28,7 +28,7 @@ class MeanPropertyPredictor(Resource["MeanPropertyPredictor"], PredictorNode): Description of the predictor input_descriptor: FormulationDescriptor Descriptor that represents the input formulation - properties: List[Union[RealDescriptor, CategoricalDescriptor]] + properties: list[Union[RealDescriptor, CategoricalDescriptor]] List of real or categorical descriptors to featurize p: float Power of the component-weighted mean. @@ -44,7 +44,7 @@ class MeanPropertyPredictor(Resource["MeanPropertyPredictor"], PredictorNode): label: Optional[str] Only ingredients with this label are counted when calculating the component-weighted mean. If ``None`` (default) all ingredients will be counted. - default_properties: Optional[Mapping[str, Union[str, float]]] + default_properties: Optional[dict[str, Union[str, float]]] Default values to use for imputed properties. Defaults are specified as a map from descriptor key to its default value. If not specified and ``impute_properties == True`` the average over the entire dataset @@ -79,19 +79,19 @@ def __init__(self, *, description: str, input_descriptor: FormulationDescriptor, - properties: List[Union[RealDescriptor, CategoricalDescriptor]], + properties: list[Union[RealDescriptor, CategoricalDescriptor]], p: float, impute_properties: bool, label: Optional[str] = None, - default_properties: Optional[Mapping[str, Union[str, float]]] = None): + default_properties: Optional[dict[str, Union[str, float]]] = None, self.name: str = name self.description: str = description self.input_descriptor: FormulationDescriptor = input_descriptor - self.properties: List[Union[RealDescriptor, CategoricalDescriptor]] = properties + self.properties: list[Union[RealDescriptor, CategoricalDescriptor]] = properties self.p: float = p self.impute_properties: bool = impute_properties self.label: Optional[str] = label - self.default_properties: Optional[Mapping[str, Union[str, float]]] = default_properties + self.default_properties: Optional[dict[str, Union[str, float]]] = default_properties def __str__(self): return ''.format(self.name) diff --git a/src/citrine/informatics/predictors/molecular_structure_featurizer.py b/src/citrine/informatics/predictors/molecular_structure_featurizer.py index 3b16b50eb..617b7dd58 100644 --- a/src/citrine/informatics/predictors/molecular_structure_featurizer.py +++ b/src/citrine/informatics/predictors/molecular_structure_featurizer.py @@ -70,9 +70,9 @@ class MolecularStructureFeaturizer(Resource["MolecularStructureFeaturizer"], Pre the description of the predictor input_descriptor: MolecularStructureDescriptor the descriptor to featurize - features: List[str] + features: list[str] the list of features to compute, either by name or by group alias. - excludes: List[str] + excludes: list[str] list of features to exclude (accepts same set of values as features). The final set of outputs generated by the predictor is set(features) - set(excludes). @@ -89,8 +89,8 @@ def __init__(self, *, description: str, input_descriptor: MolecularStructureDescriptor, - features: Optional[List[str]] = None, - excludes: Optional[List[str]] = None): + features: Optional[list[str]] = None, + excludes: Optional[list[str]] = None): self.name: str = name self.description: str = description self.input_descriptor = input_descriptor diff --git a/src/citrine/informatics/predictors/node.py b/src/citrine/informatics/predictors/node.py index d20b6cdef..23e915126 100644 --- a/src/citrine/informatics/predictors/node.py +++ b/src/citrine/informatics/predictors/node.py @@ -17,7 +17,7 @@ class PredictorNode(PolymorphicSerializable["PredictorNode"], Predictor): description = properties.Optional(properties.String(), "description") @classmethod - def get_type(cls, data) -> Type['PredictorNode']: + def get_type(cls, data) -> type['PredictorNode']: """Return the subtype.""" from .auto_ml_predictor import AutoMLPredictor from .attribute_accumulation_predictor import AttributeAccumulationPredictor diff --git a/src/citrine/informatics/predictors/single_predict_request.py b/src/citrine/informatics/predictors/single_predict_request.py index c97f076c3..6a021ce10 100644 --- a/src/citrine/informatics/predictors/single_predict_request.py +++ b/src/citrine/informatics/predictors/single_predict_request.py @@ -20,7 +20,7 @@ class SinglePredictRequest(Serializable["SinglePredictRequest"]): random_seed = properties.Optional(properties.Integer, 'random_seed') def __init__(self, material_id: UUID, - identifiers: List[str], + identifiers: list[str], material: DesignMaterial, *, random_seed: Optional[int] = None): diff --git a/src/citrine/informatics/predictors/single_prediction.py b/src/citrine/informatics/predictors/single_prediction.py index 9c44e09a1..cab1c1883 100644 --- a/src/citrine/informatics/predictors/single_prediction.py +++ b/src/citrine/informatics/predictors/single_prediction.py @@ -19,7 +19,7 @@ class SinglePrediction(Serializable["SinglePrediction"]): material = properties.Object(DesignMaterial, 'material') def __init__(self, material_id: UUID, - identifiers: List[str], + identifiers: list[str], material: DesignMaterial): self.material_id = material_id self.identifiers = identifiers diff --git a/src/citrine/informatics/reports.py b/src/citrine/informatics/reports.py index 143b4b0f5..2fa574543 100644 --- a/src/citrine/informatics/reports.py +++ b/src/citrine/informatics/reports.py @@ -26,7 +26,7 @@ class Report(PolymorphicSerializable['Report'], AsynchronousObject): _response_key = None @classmethod - def get_type(cls, data) -> Type[Serializable]: + def get_type(cls, data) -> type[Serializable]: """Return the only subtype.""" return PredictorReport @@ -90,7 +90,7 @@ def __iter__(self): return iter(self.responses) @property - def responses(self) -> Set[str]: + def responses(self) -> set[str]: """Responses the model was evaluated on.""" return set(self._response_results.keys()) @@ -129,17 +129,17 @@ class ModelSummary(Serializable['ModelSummary']): properties.Union([properties.Object(Descriptor), properties.String()]), 'inputs' ) - """:List[Descriptor]: list of input descriptors""" + """:list[Descriptor]: list of input descriptors""" outputs = properties.List( properties.Union([properties.Object(Descriptor), properties.String()]), 'outputs' ) - """:List[Descriptor]: list of output descriptors""" + """:list[Descriptor]: list of output descriptors""" model_settings = properties.Raw('model_settings') """:dict: model settings, as a dictionary (keys depend on the model type)""" feature_importances = properties.List( properties.Object(FeatureImportanceReport), 'feature_importances') - """:List[FeatureImportanceReport]: feature importance reports for each output""" + """:list[FeatureImportanceReport]: feature importance reports for each output""" selection_summary = properties.Optional( properties.Object(ModelSelectionReport), "selection_summary" ) @@ -173,9 +173,9 @@ class PredictorReport(Serializable['PredictorReport'], Report): status = properties.String('status') """:str: The status of the report. Possible statuses are PENDING, ERROR, and OK.""" descriptors = properties.List(properties.Object(Descriptor), 'report.descriptors', default=[]) - """:List[Descriptor]: All descriptors that appear in the predictor""" + """:list[Descriptor]: All descriptors that appear in the predictor""" model_summaries = properties.List(properties.Object(ModelSummary), 'report.models', default=[]) - """:List[ModelSummary]: Summaries of all models in the predictor""" + """:list[ModelSummary]: Summaries of all models in the predictor""" def __init__(self): pass # pragma: no cover @@ -232,7 +232,7 @@ def _get_sole_descriptor(it: Iterable): return as_list[0] @staticmethod - def _collapse_model_settings(raw_settings: Dict[str, Any]): + def _collapse_model_settings(raw_settings: dict[str, Any]): """Collapse a model's settings into a flat dictionary. Model settings are returned as a dictionary with a "name" field, a "value" field, @@ -240,7 +240,7 @@ def _collapse_model_settings(raw_settings: Dict[str, Any]): top-level dictionary with keys given by "name" and values given by "value." """ - def _recurse_model_settings(settings: Dict[str, str], list_or_dict): + def _recurse_model_settings(settings: dict[str, str], list_or_dict): """Recursively traverse the model settings, adding name-value pairs to dictionary.""" if isinstance(list_or_dict, list): for setting in list_or_dict: diff --git a/src/citrine/informatics/scores.py b/src/citrine/informatics/scores.py index ebb452c53..405f1ce6e 100644 --- a/src/citrine/informatics/scores.py +++ b/src/citrine/informatics/scores.py @@ -52,12 +52,12 @@ class LIScore(Serializable['LIScore'], Score): typ = properties.String('type', default='MLI') def __init__(self, *, - objectives: List[Objective], - baselines: List[float], - constraints: Optional[List[Constraint]] = None): - self.objectives: List[Objective] = objectives - self.baselines: List[float] = baselines - self.constraints: List[Constraint] = constraints or [] + objectives: list[Objective], + baselines: list[float], + constraints: Optional[list[Constraint]] = None): + self.objectives: list[Objective] = objectives + self.baselines: list[float] = baselines + self.constraints: list[Constraint] = constraints or [] self._name = "Likelihood of Improvement" self._description = "" @@ -87,12 +87,12 @@ class EIScore(Serializable['EIScore'], Score): typ = properties.String('type', default='MEI') def __init__(self, *, - objectives: List[Objective], - baselines: List[float], - constraints: Optional[List[Constraint]] = None): - self.objectives: List[Objective] = objectives - self.baselines: List[float] = baselines - self.constraints: List[Constraint] = constraints or [] + objectives: list[Objective], + baselines: list[float], + constraints: Optional[list[Constraint]] = None): + self.objectives: list[Objective] = objectives + self.baselines: list[float] = baselines + self.constraints: list[Constraint] = constraints or [] self._name = "Expected Improvement" self._description = "" @@ -121,10 +121,10 @@ class EVScore(Serializable['EVScore'], Score): typ = properties.String('type', default='MEV') def __init__(self, *, - objectives: List[Objective], - constraints: Optional[List[Constraint]] = None): - self.objectives: List[Objective] = objectives - self.constraints: List[Constraint] = constraints or [] + objectives: list[Objective], + constraints: Optional[list[Constraint]] = None): + self.objectives: list[Objective] = objectives + self.constraints: list[Constraint] = constraints or [] self._name = "Expected Value" self._description = "" diff --git a/src/citrine/informatics/workflows/analysis_workflow.py b/src/citrine/informatics/workflows/analysis_workflow.py index 08dad4b63..e46543f9e 100644 --- a/src/citrine/informatics/workflows/analysis_workflow.py +++ b/src/citrine/informatics/workflows/analysis_workflow.py @@ -37,7 +37,7 @@ def __init__(self, name: str, description: str, snapshot_id: Optional[Union[UUID, str]] = None, - plots: List[dict] = []): + plots: list[dict] = []): self.name = name self.description = description self.snapshot_id = snapshot_id diff --git a/src/citrine/jobs/job.py b/src/citrine/jobs/job.py index 397a99971..62bfd0974 100644 --- a/src/citrine/jobs/job.py +++ b/src/citrine/jobs/job.py @@ -47,7 +47,7 @@ class TaskNode(Resource['TaskNode']): """:str: the type of task running""" _status = properties.String("status") dependencies = PropertySet(String(), "dependencies") - """:Set[str]: all the tasks that this task is dependent on""" + """:set[str]: all the tasks that this task is dependent on""" failure_reason = properties.Optional(String(), "failure_reason") """:str: if a task has failed, the failure reason will be in this parameter""" @@ -80,7 +80,7 @@ class JobStatusResponse(Resource['JobStatusResponse']): _status = properties.String("status") """:str: The status of the job. One of "Running", "Success", or "Failure".""" tasks = properties.List(Object(TaskNode), "tasks") - """:List[TaskNode]: all of the constituent task required to complete this job""" + """:list[TaskNode]: all of the constituent task required to complete this job""" output = properties.Optional(properties.Mapping(String, String), 'output') """:Optional[dict[str, str]]: job output properties and results""" diff --git a/src/citrine/resources/_default_labels.py b/src/citrine/resources/_default_labels.py index f4ce943ea..a315e224a 100644 --- a/src/citrine/resources/_default_labels.py +++ b/src/citrine/resources/_default_labels.py @@ -6,8 +6,8 @@ def _inject_default_label_tags( - original_tags: Optional[List[str]], default_labels: Optional[List[str]] -) -> Optional[List[str]]: + original_tags: Optional[list[str]], default_labels: Optional[list[str]] +) -> Optional[list[str]]: if default_labels is None: all_tags = original_tags else: diff --git a/src/citrine/resources/condition_template.py b/src/citrine/resources/condition_template.py index af98f44bd..87c1ded5c 100644 --- a/src/citrine/resources/condition_template.py +++ b/src/citrine/resources/condition_template.py @@ -28,7 +28,7 @@ class ConditionTemplate( A collection of `unique IDs `_. - tags: List[str], optional + tags: list[str], optional `Tags `_ are hierarchical strings that store information about an entity. They can be used for filtering and discoverability. @@ -41,9 +41,9 @@ def __init__(self, name: str, *, bounds: BaseBounds, - uids: Optional[Dict[str, str]] = None, + uids: Optional[dict[str, str]] = None, description: Optional[str] = None, - tags: Optional[List[str]] = None + tags: Optional[list[str]] = None ): if uids is None: uids = dict() @@ -63,6 +63,6 @@ class ConditionTemplateCollection(AttributeTemplateCollection[ConditionTemplate] _resource = ConditionTemplate @classmethod - def get_type(cls) -> Type[ConditionTemplate]: + def get_type(cls) -> type[ConditionTemplate]: """Return the resource type in the collection.""" return ConditionTemplate diff --git a/src/citrine/resources/data_concepts.py b/src/citrine/resources/data_concepts.py index 98ff3399b..37cb2743d 100644 --- a/src/citrine/resources/data_concepts.py +++ b/src/citrine/resources/data_concepts.py @@ -66,7 +66,7 @@ class DataConcepts( collection_dict = dict() """ - Dict[str, class]: dictionary from the type key to the associated collection \ + dict[str, class]: dictionary from the type key to the associated collection \ for every class that extends DataConcepts. Only populated if the :func:`get_collection_type` method is invoked. @@ -100,7 +100,7 @@ def dataset(self) -> Optional[UUID]: return self._dataset @classmethod - def get_type(cls, data) -> Type[Serializable]: + def get_type(cls, data) -> type[Serializable]: """ Determine the class of a serialized object. @@ -124,7 +124,7 @@ def get_type(cls, data) -> Type[Serializable]: return DictSerializable.class_mapping[data['type']] @classmethod - def get_collection_type(cls, data) -> "Type[DataConceptsCollection]": + def get_collection_type(cls, data) -> "type[DataConceptsCollection]": """ Determine the associated collection type for a serialized data object. @@ -220,7 +220,7 @@ def __init__(self, *, session: Session, team_id: UUID, dataset_id: Optional[UUID @classmethod @abstractmethod - def get_type(cls) -> Type[Serializable]: + def get_type(cls) -> type[Serializable]: """Return the resource type in the collection.""" @property @@ -396,7 +396,7 @@ def register_all(self, Returns ------- - List[DataConcepts] + list[DataConcepts] Each object model as it now exists in the database. """ diff --git a/src/citrine/resources/data_objects.py b/src/citrine/resources/data_objects.py index c0b0839e2..c8df3e8fb 100644 --- a/src/citrine/resources/data_objects.py +++ b/src/citrine/resources/data_objects.py @@ -41,7 +41,7 @@ class DataObjectCollection(DataConceptsCollection[DataObjectResourceType], ABC): def list_by_attribute_bounds( self, - attribute_bounds: Dict[Union[AttributeTemplate, LinkByUID], BaseBounds], *, + attribute_bounds: dict[Union[AttributeTemplate, LinkByUID], BaseBounds], *, forward: bool = True, per_page: int = 100) -> Iterator[DataObject]: """ Get all objects in the collection with attributes within certain bounds. @@ -53,7 +53,7 @@ def list_by_attribute_bounds( Parameters ---------- - attribute_bounds: Dict[Union[AttributeTemplate, \ + attribute_bounds: dict[Union[AttributeTemplate, \ :py:class:`LinkByUID `], \ :py:class:`BaseBounds `] A dictionary from attributes to the bounds on that attribute. @@ -111,7 +111,7 @@ def validate_templates(self, *, model: DataObjectResourceType, object_template: Optional[ObjectTemplateResourceType] = None, ingredient_process_template: Optional[ProcessTemplate] = None)\ - -> List[ValidationError]: + -> list[ValidationError]: """ Validate a data object against its templates. @@ -122,7 +122,7 @@ def validate_templates(self, *, :param object_template: optional object template to validate against :param ingredient_process_template: optional process template to validate ingredient against. Ignored unless data object is an IngredientSpec or IngredientRun. - :return: List[ValidationError] of validation errors encountered. Empty if successful. + :return: list[ValidationError] of validation errors encountered. Empty if successful. """ path = self._get_path(ignore_dataset=True, action="validate-templates") diff --git a/src/citrine/resources/data_version_update.py b/src/citrine/resources/data_version_update.py index 2f3876b92..86f333704 100644 --- a/src/citrine/resources/data_version_update.py +++ b/src/citrine/resources/data_version_update.py @@ -30,8 +30,8 @@ class BranchDataUpdate(Resource['BranchDataUpdate']): def __init__(self, *, - data_updates: List[DataVersionUpdate], - predictors: List[PredictorRef]): + data_updates: list[DataVersionUpdate], + predictors: list[PredictorRef]): self.data_updates = data_updates self.predictors = predictors @@ -51,7 +51,7 @@ class NextBranchVersionRequest(Resource['NextBranchVersionRequest']): def __init__(self, *, - data_updates: List[DataVersionUpdate], - use_predictors: List[PredictorRef]): + data_updates: list[DataVersionUpdate], + use_predictors: list[PredictorRef]): self.data_updates = data_updates self.use_predictors = use_predictors diff --git a/src/citrine/resources/dataset.py b/src/citrine/resources/dataset.py index 99d7c4377..7b21861ed 100644 --- a/src/citrine/resources/dataset.py +++ b/src/citrine/resources/dataset.py @@ -218,7 +218,7 @@ def register_all(self, *, dry_run: bool = False, status_bar: bool = False, - include_nested: bool = False) -> List[DataConcepts]: + include_nested: bool = False) -> list[DataConcepts]: """ Register multiple GEMD objects to each of their appropriate collections. @@ -251,7 +251,7 @@ def register_all(self, Returns ------- - List[DataConcepts] + list[DataConcepts] The registered versions """ @@ -314,7 +314,7 @@ def delete_contents( How long to delay between each polling retry attempt. Returns ------- - List[Tuple[LinkByUID, ApiError]] + list[tuple[LinkByUID, ApiError]] A list of (LinkByUID, api_error) for each failure to delete an object. Note that this method doesn't raise an exception if an object fails to be deleted. @@ -347,11 +347,11 @@ def delete_contents( def gemd_batch_delete( self, - id_list: List[Union[LinkByUID, UUID, str, BaseEntity]], + id_list: list[Union[LinkByUID, UUID, str, BaseEntity]], *, timeout: float = 2 * 60, polling_delay: float = 1.0 - ) -> List[Tuple[LinkByUID, ApiError]]: + ) -> list[tuple[LinkByUID, ApiError]]: """ Remove a set of GEMD objects. @@ -372,7 +372,7 @@ def gemd_batch_delete( Parameters ---------- - id_list: List[Union[LinkByUID, UUID, str, BaseEntity]] + id_list: list[Union[LinkByUID, UUID, str, BaseEntity]] A list of the IDs of data objects to be removed. They can be passed as a LinkByUID tuple, a UUID, a string, or the object itself. A UUID or string is assumed to be a Citrine ID, whereas a LinkByUID or @@ -388,7 +388,7 @@ def gemd_batch_delete( Returns ------- - List[Tuple[LinkByUID, ApiError]] + list[tuple[LinkByUID, ApiError]] A list of (LinkByUID, api_error) for each failure to delete an object. Note that this method doesn't raise an exception if an object fails to be deleted. diff --git a/src/citrine/resources/delete.py b/src/citrine/resources/delete.py index dddb7b8d2..a2434392e 100644 --- a/src/citrine/resources/delete.py +++ b/src/citrine/resources/delete.py @@ -13,13 +13,13 @@ def _async_gemd_batch_delete( - id_list: List[Union[LinkByUID, UUID, str, BaseEntity]], + id_list: list[Union[LinkByUID, UUID, str, BaseEntity]], team_id: UUID, session: Session, dataset_id: Optional[UUID] = None, timeout: float = 2 * 60, polling_delay: float = 1.0 -) -> List[Tuple[LinkByUID, ApiError]]: +) -> list[tuple[LinkByUID, ApiError]]: """ Shared implementation of Async GEMD Batch deletion. @@ -30,7 +30,7 @@ def _async_gemd_batch_delete( Parameters ---------- - id_list: List[Union[LinkByUID, UUID, str, BaseEntity]] + id_list: list[Union[LinkByUID, UUID, str, BaseEntity]] A list of the IDs of data objects to be removed. They can be passed as a LinkByUID tuple, a UUID, a string, or the object itself. A UUID or string is assumed to be a Citrine ID, whereas a LinkByUID or @@ -56,7 +56,7 @@ def _async_gemd_batch_delete( Returns ------- - List[Tuple[LinkByUID, ApiError]] + list[tuple[LinkByUID, ApiError]] A list of (LinkByUID, api_error) for each failure to delete an object. Note that this method doesn't raise an exception if an object fails to be deleted. @@ -94,7 +94,7 @@ def _poll_for_async_batch_delete_result( job_id: str, timeout: float, polling_delay: float -) -> List[Tuple[LinkByUID, ApiError]]: +) -> list[tuple[LinkByUID, ApiError]]: """ Poll for the result of an asynchronous batch delete (or a deletion of dataset contents). @@ -119,7 +119,7 @@ def _poll_for_async_batch_delete_result( Returns ------- - List[Tuple[LinkByUID, ApiError]] + list[tuple[LinkByUID, ApiError]] A list of (LinkByUID, api_error) for each failure to delete an object. Note that this method doesn't raise an exception if an object fails to be deleted. diff --git a/src/citrine/resources/descriptors.py b/src/citrine/resources/descriptors.py index d34199ca1..56049fc4c 100644 --- a/src/citrine/resources/descriptors.py +++ b/src/citrine/resources/descriptors.py @@ -17,7 +17,7 @@ def __init__(self, project_id: UUID, session: Session): self.session: Session = session def from_predictor_responses(self, *, predictor: Union[GraphPredictor, PredictorNode], - inputs: List[Descriptor]) -> List[Descriptor]: + inputs: list[Descriptor]) -> list[Descriptor]: """ Get responses for a predictor, given an input space. @@ -26,12 +26,12 @@ def from_predictor_responses(self, *, predictor: Union[GraphPredictor, Predictor predictor : Union[Predictor, PredictorNode] Either a single predictor node or full predictor whose available responses are to be computed. - inputs : List[Descriptor] + inputs : list[Descriptor] The input space to the predictor. Returns ------- - List[Descriptor] + list[Descriptor] The computable responses of the predictor given the provided input space (as descriptors). @@ -51,7 +51,7 @@ def from_predictor_responses(self, *, predictor: Union[GraphPredictor, Predictor ) return [Descriptor.build(r) for r in response['responses']] - def from_data_source(self, *, data_source: DataSource) -> List[Descriptor]: + def from_data_source(self, *, data_source: DataSource) -> list[Descriptor]: """ Get all descriptors associated with a data source. @@ -62,7 +62,7 @@ def from_data_source(self, *, data_source: DataSource) -> List[Descriptor]: Returns ------- - List[Descriptor] + list[Descriptor] The list of descriptors associated with the given data_source. """ diff --git a/src/citrine/resources/design_workflow.py b/src/citrine/resources/design_workflow.py index 4fffa021a..6f37ba563 100644 --- a/src/citrine/resources/design_workflow.py +++ b/src/citrine/resources/design_workflow.py @@ -167,7 +167,7 @@ def _fetch_page(self, per_page: Optional[int] = None, json_body: Optional[dict] = None, additional_params: Optional[dict] = None, - ) -> Tuple[Iterable[dict], str]: + ) -> tuple[Iterable[dict], str]: params = additional_params or {} params["branch_root_id"] = self.branch_root_id params["branch_version"] = self.branch_version diff --git a/src/citrine/resources/experiment_datasource.py b/src/citrine/resources/experiment_datasource.py index ab4a9e412..ab6208772 100644 --- a/src/citrine/resources/experiment_datasource.py +++ b/src/citrine/resources/experiment_datasource.py @@ -36,7 +36,7 @@ def __init__(self, *args, **kwargs): """Candidate experiment snapshots are not directly instantiated by the user.""" pass # pragma: no cover - def _overrides_json(self) -> Dict[str, str]: + def _overrides_json(self) -> dict[str, str]: return {name: json.dumps(expt_value.value) for name, expt_value in self.overrides.items()} diff --git a/src/citrine/resources/file_link.py b/src/citrine/resources/file_link.py index dd8824c17..ba0947a0d 100644 --- a/src/citrine/resources/file_link.py +++ b/src/citrine/resources/file_link.py @@ -87,7 +87,7 @@ def __init__(cls, *args, **kwargs): cls.typ = properties.String('type', default="file_link", deserializable=False) -def _get_ids_from_url(url: str) -> Tuple[Optional[UUID], Optional[UUID]]: +def _get_ids_from_url(url: str) -> tuple[Optional[UUID], Optional[UUID]]: """Attempt to extract file_id and version_id from a URL.""" parsed = urlparse(url) if len(parsed.query) > 0 or len(parsed.fragment) > 0: @@ -207,7 +207,7 @@ def _get_path(self, ignore_dataset: Optional[bool] = False, version: Union[str, UUID] = None, action: Union[str, Sequence[str]] = [], - query_terms: Dict[str, str] = {},) -> str: + query_terms: dict[str, str] = {},) -> str: """Build the path for taking an action with a particular file version.""" if version is not None: action = ['versions', version] + ([action] if isinstance(action, str) else action) @@ -664,7 +664,7 @@ def ingest(self, Parameters ---------- - files: List[FileLink, Path, or str] + files: list[FileLink, Path, or str] A list of files from which GEMD objects should be built. A FileLink must contain an absolute URL or a relative path for an on-platform resource. Strings must be resolvable to a FileLink; if resolution fails, an exception is thrown. diff --git a/src/citrine/resources/gemd_resource.py b/src/citrine/resources/gemd_resource.py index 8ea8c7fc7..1b1dfa9dc 100644 --- a/src/citrine/resources/gemd_resource.py +++ b/src/citrine/resources/gemd_resource.py @@ -33,7 +33,7 @@ def __init__(self, *, dataset_id: UUID, session: Session, team_id: UUID): self.team_id = team_id @classmethod - def get_type(cls) -> Type[DataConcepts]: + def get_type(cls) -> type[DataConcepts]: """Return the resource type in the collection.""" return DataConcepts @@ -65,7 +65,7 @@ def register_all(self, *, dry_run=False, status_bar=False, - include_nested=False) -> List[DataConcepts]: + include_nested=False) -> list[DataConcepts]: """ Register multiple GEMD objects to each of their appropriate collections. @@ -102,7 +102,7 @@ def register_all(self, Returns ------- - List[DataConcepts] + list[DataConcepts] The registered versions """ @@ -173,11 +173,11 @@ def register_all(self, def batch_delete( self, - id_list: List[Union[LinkByUID, UUID, str, BaseEntity]], + id_list: list[Union[LinkByUID, UUID, str, BaseEntity]], *, timeout: float = 2 * 60, polling_delay: float = 1.0 - ) -> List[Tuple[LinkByUID, ApiError]]: + ) -> list[tuple[LinkByUID, ApiError]]: """ Remove a set of GEMD objects. @@ -198,7 +198,7 @@ def batch_delete( Parameters ---------- - id_list: List[Union[LinkByUID, UUID, str, BaseEntity]] + id_list: list[Union[LinkByUID, UUID, str, BaseEntity]] A list of the IDs of data objects to be removed. They can be passed as a LinkByUID tuple, a UUID, a string, or the object itself. A UUID or string is assumed to be a Citrine ID, whereas a LinkByUID or @@ -206,7 +206,7 @@ def batch_delete( Returns ------- - List[Tuple[LinkByUID, ApiError]] + list[tuple[LinkByUID, ApiError]] A list of (LinkByUID, api_error) for each failure to delete an object. Note that this method doesn't raise an exception if an object fails to be deleted. diff --git a/src/citrine/resources/gemtables.py b/src/citrine/resources/gemtables.py index 6252a301c..c7288b126 100644 --- a/src/citrine/resources/gemtables.py +++ b/src/citrine/resources/gemtables.py @@ -127,7 +127,7 @@ def list_versions(self, :return: An iterable of the versions of the Tables (as Table objects). """ def _fetch_versions(page: Optional[int], - per_page: int) -> Tuple[Iterable[dict], str]: + per_page: int) -> tuple[Iterable[dict], str]: data = self.session.get_resource(self._get_path(uid), params=self._page_params(page, per_page)) return data[self._collection_key], data.get('next', "") @@ -155,7 +155,7 @@ def list_by_config(self, :return: An iterable of the versions of the Tables (as Table objects). """ def _fetch_versions(page: Optional[int], - per_page: int) -> Tuple[Iterable[dict], str]: + per_page: int) -> tuple[Iterable[dict], str]: path_params = {'table_config_uid_str': str(table_config_uid)} path_params.update(self.__dict__) path = format_escaped_url( diff --git a/src/citrine/resources/ingestion.py b/src/citrine/resources/ingestion.py index 8b8807af8..4160ab3f0 100644 --- a/src/citrine/resources/ingestion.py +++ b/src/citrine/resources/ingestion.py @@ -117,7 +117,7 @@ class IngestionException(CitrineException): """Optional[UUID]""" status = properties.Enumeration(IngestionStatusType, "status") errors = properties.List(properties.Object(IngestionErrorTrace), "errors") - """List[IngestionErrorTrace]""" + """list[IngestionErrorTrace]""" def __init__(self, *, @@ -152,7 +152,7 @@ class IngestionStatus(Resource['IngestionStatus']): status = properties.Enumeration(IngestionStatusType, "status") """IngestionStatusType""" errors = properties.List(properties.Object(IngestionErrorTrace), "errors") - """List[IngestionErrorTrace]""" + """list[IngestionErrorTrace]""" def __init__(self, *, diff --git a/src/citrine/resources/ingredient_run.py b/src/citrine/resources/ingredient_run.py index 340ef69db..9653848d4 100644 --- a/src/citrine/resources/ingredient_run.py +++ b/src/citrine/resources/ingredient_run.py @@ -33,7 +33,7 @@ class IngredientRun( A collection of `unique IDs `_. - tags: List[str], optional + tags: list[str], optional `Tags `_ are hierarchical strings that store information about an entity. They can be used for filtering and discoverability. @@ -57,7 +57,7 @@ class IngredientRun( The absolute quantity of the ingredient in the process. spec: IngredientSpec The specification of which this ingredient is a realization. - file_links: List[FileLink], optional + file_links: list[FileLink], optional Links to associated files, with resource paths into the files API. """ @@ -84,8 +84,8 @@ class IngredientRun( def __init__(self, *, - uids: Optional[Dict[str, str]] = None, - tags: Optional[List[str]] = None, + uids: Optional[dict[str, str]] = None, + tags: Optional[list[str]] = None, notes: Optional[str] = None, material: Optional[GEMDMaterialRun] = None, process: Optional[GEMDProcessRun] = None, @@ -94,7 +94,7 @@ def __init__(self, number_fraction: Optional[ContinuousValue] = None, absolute_quantity: Optional[ContinuousValue] = None, spec: Optional[GEMDIngredientSpec] = None, - file_links: Optional[List[FileLink]] = None): + file_links: Optional[list[FileLink]] = None): if uids is None: uids = dict() super(ObjectRun, self).__init__() @@ -117,7 +117,7 @@ class IngredientRunCollection(ObjectRunCollection[IngredientRun]): _resource = IngredientRun @classmethod - def get_type(cls) -> Type[IngredientRun]: + def get_type(cls) -> type[IngredientRun]: """Return the resource type in the collection.""" return IngredientRun diff --git a/src/citrine/resources/ingredient_spec.py b/src/citrine/resources/ingredient_spec.py index 9c9e31f20..7caf2538d 100644 --- a/src/citrine/resources/ingredient_spec.py +++ b/src/citrine/resources/ingredient_spec.py @@ -32,7 +32,7 @@ class IngredientSpec( A collection of `unique IDs `_. - tags: List[str], optional + tags: list[str], optional `Tags `_ are hierarchical strings that store information about an entity. They can be used for filtering and discoverability. @@ -56,9 +56,9 @@ class IngredientSpec( The absolute quantity of the ingredient in the process. name: str Label on the ingredient that is unique within the process that contains it. - labels: List[str], optional + labels: list[str], optional Additional labels on the ingredient. - file_links: List[FileLink], optional + file_links: list[FileLink], optional Links to associated files, with resource paths into the files API. """ @@ -82,8 +82,8 @@ class IngredientSpec( def __init__(self, name: str, *, - uids: Optional[Dict[str, str]] = None, - tags: Optional[List[str]] = None, + uids: Optional[dict[str, str]] = None, + tags: Optional[list[str]] = None, notes: Optional[str] = None, material: Optional[GEMDMaterialSpec] = None, process: Optional[GEMDProcessSpec] = None, @@ -91,8 +91,8 @@ def __init__(self, volume_fraction: Optional[ContinuousValue] = None, number_fraction: Optional[ContinuousValue] = None, absolute_quantity: Optional[ContinuousValue] = None, - labels: Optional[List[str]] = None, - file_links: Optional[List[FileLink]] = None): + labels: Optional[list[str]] = None, + file_links: Optional[list[FileLink]] = None): if uids is None: uids = dict() @@ -116,7 +116,7 @@ class IngredientSpecCollection(ObjectSpecCollection[IngredientSpec]): _resource = IngredientSpec @classmethod - def get_type(cls) -> Type[IngredientSpec]: + def get_type(cls) -> type[IngredientSpec]: """Return the resource type in the collection.""" return IngredientSpec diff --git a/src/citrine/resources/material_run.py b/src/citrine/resources/material_run.py index fb2a62cc0..e721b3bbc 100644 --- a/src/citrine/resources/material_run.py +++ b/src/citrine/resources/material_run.py @@ -35,7 +35,7 @@ class MaterialRun( A collection of `unique IDs `_. - tags: List[str], optional + tags: list[str], optional `Tags `_ are hierarchical strings that store information about an entity. They can be used for filtering and discoverability. @@ -48,9 +48,9 @@ class MaterialRun( "unknown." Default is "unknown." spec: MaterialSpec The material specification of which this is an instance. - file_links: List[FileLink], optional + file_links: list[FileLink], optional Links to associated files, with resource paths into the files API. - default_labels: List[str], optional + default_labels: list[str], optional An optional set of default labels to apply to this material run. Default labels are used to: - Marking the material run as a potential replacement ingredient for a @@ -77,14 +77,14 @@ class MaterialRun( def __init__(self, name: str, *, - uids: Optional[Dict[str, str]] = None, - tags: Optional[List[str]] = None, + uids: Optional[dict[str, str]] = None, + tags: Optional[list[str]] = None, notes: Optional[str] = None, process: Optional[GEMDProcessRun] = None, sample_type: Optional[str] = "unknown", spec: Optional[GEMDMaterialSpec] = None, - file_links: Optional[List[FileLink]] = None, - default_labels: Optional[List[str]] = None): + file_links: Optional[list[FileLink]] = None, + default_labels: Optional[list[str]] = None): if uids is None: uids = dict() all_tags = _inject_default_label_tags(tags, default_labels) @@ -106,7 +106,7 @@ class MaterialRunCollection(ObjectRunCollection[MaterialRun]): _resource = MaterialRun @classmethod - def get_type(cls) -> Type[MaterialRun]: + def get_type(cls) -> type[MaterialRun]: """Return the resource type in the collection.""" return MaterialRun diff --git a/src/citrine/resources/material_spec.py b/src/citrine/resources/material_spec.py index 9a8654cf9..9b1f58bd4 100644 --- a/src/citrine/resources/material_spec.py +++ b/src/citrine/resources/material_spec.py @@ -33,7 +33,7 @@ class MaterialSpec( A collection of `unique IDs `_. - tags: List[str], optional + tags: list[str], optional `Tags `_ are hierarchical strings that store information about an entity. They can be used for filtering and discoverability. @@ -41,14 +41,14 @@ class MaterialSpec( Long-form notes about the material spec. process: ProcessSpec Process that produces this material. - properties: List[PropertyAndConditions], optional + properties: list[PropertyAndConditions], optional Properties of the material, along with an optional list of conditions under which those properties are measured. template: MaterialTemplate, optional A template bounding the valid values for this material's properties. - file_links: List[FileLink], optional + file_links: list[FileLink], optional Links to associated files, with resource paths into the files API. - default_labels: List[str], optional + default_labels: list[str], optional An optional set of default labels to apply to this material spec. Default labels are used to: - Populate labels on the ingredient spec, if none are explicitly @@ -75,14 +75,14 @@ class MaterialSpec( def __init__(self, name: str, *, - uids: Optional[Dict[str, str]] = None, - tags: Optional[List[str]] = None, + uids: Optional[dict[str, str]] = None, + tags: Optional[list[str]] = None, notes: Optional[str] = None, process: Optional[GEMDProcessSpec] = None, - properties: Optional[List[PropertyAndConditions]] = None, + properties: Optional[list[PropertyAndConditions]] = None, template: Optional[GEMDMaterialTemplate] = None, - file_links: Optional[List[FileLink]] = None, - default_labels: Optional[List[str]] = None): + file_links: Optional[list[FileLink]] = None, + default_labels: Optional[list[str]] = None): if uids is None: uids = dict() all_tags = _inject_default_label_tags(tags, default_labels) @@ -103,7 +103,7 @@ class MaterialSpecCollection(ObjectSpecCollection[MaterialSpec]): _resource = MaterialSpec @classmethod - def get_type(cls) -> Type[MaterialSpec]: + def get_type(cls) -> type[MaterialSpec]: """Return the resource type in the collection.""" return MaterialSpec diff --git a/src/citrine/resources/material_template.py b/src/citrine/resources/material_template.py index ea90bff58..54b053391 100644 --- a/src/citrine/resources/material_template.py +++ b/src/citrine/resources/material_template.py @@ -37,11 +37,11 @@ class MaterialTemplate( A collection of `unique IDs `_. - tags: List[str], optional + tags: list[str], optional `Tags `_ are hierarchical strings that store information about an entity. They can be used for filtering and discoverability. - properties: List[PropertyTemplate] or List[PropertyTemplate, \ + properties: list[PropertyTemplate] or list[PropertyTemplate, \ :py:class:`BaseBounds `], optional Templates for associated properties. Each template can be provided by itself, or as a list with the second entry being a separate, *more restrictive* Bounds object that defines @@ -62,14 +62,14 @@ class MaterialTemplate( def __init__(self, name: str, *, - uids: Optional[Dict[str, str]] = None, + uids: Optional[dict[str, str]] = None, properties: Optional[Sequence[Union[PropertyTemplate, LinkByUID, Sequence[Union[PropertyTemplate, LinkByUID, Optional[BaseBounds]]] ]]] = None, description: Optional[str] = None, - tags: Optional[List[str]] = None): + tags: Optional[list[str]] = None): # properties is a list, each element of which is a PropertyTemplate OR is a list with # 2 entries: [PropertyTemplate, BaseBounds]. Python typing is not expressive enough, so # the typing above is more general. @@ -92,6 +92,6 @@ class MaterialTemplateCollection(ObjectTemplateCollection[MaterialTemplate]): _resource = MaterialTemplate @classmethod - def get_type(cls) -> Type[MaterialTemplate]: + def get_type(cls) -> type[MaterialTemplate]: """Return the resource type in the collection.""" return MaterialTemplate diff --git a/src/citrine/resources/measurement_run.py b/src/citrine/resources/measurement_run.py index 02440dc9c..2c48a4dc9 100644 --- a/src/citrine/resources/measurement_run.py +++ b/src/citrine/resources/measurement_run.py @@ -35,17 +35,17 @@ class MeasurementRun( A collection of `unique IDs `_. - tags: List[str], optional + tags: list[str], optional `Tags `_ are hierarchical strings that store information about an entity. They can be used for filtering and discoverability. notes: str, optional Long-form notes about the measurement run. - conditions: List[Condition], optional + conditions: list[Condition], optional Conditions under which this measurement run occurs. - parameters: List[Parameter], optional + parameters: list[Parameter], optional Parameters of this measurement run. - properties: List[Property], optional + properties: list[Property], optional Properties that are measured during this measurement run. spec: MeasurementSpec The measurement specification of which this is an instance. @@ -53,7 +53,7 @@ class MeasurementRun( The material run being measured. spec: MaterialSpec The material specification of which this is an instance. - file_links: List[FileLink], optional + file_links: list[FileLink], optional Links to associated files, with resource paths into the files API. source: PerformedSource, optional Information about the person who performed the run and when. @@ -77,15 +77,15 @@ class MeasurementRun( def __init__(self, name: str, *, - uids: Optional[Dict[str, str]] = None, - tags: Optional[List[str]] = None, + uids: Optional[dict[str, str]] = None, + tags: Optional[list[str]] = None, notes: Optional[str] = None, - conditions: Optional[List[Condition]] = None, - properties: Optional[List[Property]] = None, - parameters: Optional[List[Parameter]] = None, + conditions: Optional[list[Condition]] = None, + properties: Optional[list[Property]] = None, + parameters: Optional[list[Parameter]] = None, spec: Optional[GEMDMeasurementSpec] = None, material: Optional[GEMDMaterialRun] = None, - file_links: Optional[List[FileLink]] = None, + file_links: Optional[list[FileLink]] = None, source: Optional[PerformedSource] = None): if uids is None: uids = dict() @@ -108,7 +108,7 @@ class MeasurementRunCollection(ObjectRunCollection[MeasurementRun]): _resource = MeasurementRun @classmethod - def get_type(cls) -> Type[MeasurementRun]: + def get_type(cls) -> type[MeasurementRun]: """Return the resource type in the collection.""" return MeasurementRun diff --git a/src/citrine/resources/measurement_spec.py b/src/citrine/resources/measurement_spec.py index 484026243..a8972fd33 100644 --- a/src/citrine/resources/measurement_spec.py +++ b/src/citrine/resources/measurement_spec.py @@ -33,20 +33,20 @@ class MeasurementSpec( A collection of `unique IDs `_. - tags: List[str], optional + tags: list[str], optional `Tags `_ are hierarchical strings that store information about an entity. They can be used for filtering and discoverability. notes: str, optional Long-form notes about the measurement spec. - conditions: List[Condition], optional + conditions: list[Condition], optional Conditions under which this measurement spec occurs. - parameters: List[Parameter], optional + parameters: list[Parameter], optional Parameters of this measurement spec. template: MeasurementTemplate A template bounding the valid values for the measurement's properties, parameters, and conditions. - file_links: List[FileLink], optional + file_links: list[FileLink], optional Links to associated files, with resource paths into the files API. """ @@ -65,13 +65,13 @@ class MeasurementSpec( def __init__(self, name: str, *, - uids: Optional[Dict[str, str]] = None, - tags: Optional[List[str]] = None, + uids: Optional[dict[str, str]] = None, + tags: Optional[list[str]] = None, notes: Optional[str] = None, - conditions: Optional[List[Condition]] = None, - parameters: Optional[List[Parameter]] = None, + conditions: Optional[list[Condition]] = None, + parameters: Optional[list[Parameter]] = None, template: Optional[GEMDMeasurementTemplate] = None, - file_links: Optional[List[FileLink]] = None): + file_links: Optional[list[FileLink]] = None): if uids is None: uids = dict() super(ObjectSpec, self).__init__() @@ -91,7 +91,7 @@ class MeasurementSpecCollection(ObjectSpecCollection[MeasurementSpec]): _resource = MeasurementSpec @classmethod - def get_type(cls) -> Type[MeasurementSpec]: + def get_type(cls) -> type[MeasurementSpec]: """Return the resource type in the collection.""" return MeasurementSpec diff --git a/src/citrine/resources/measurement_template.py b/src/citrine/resources/measurement_template.py index e6825f3cd..218178a3f 100644 --- a/src/citrine/resources/measurement_template.py +++ b/src/citrine/resources/measurement_template.py @@ -42,21 +42,21 @@ class MeasurementTemplate( A collection of `unique IDs `_. - tags: List[str], optional + tags: list[str], optional `Tags `_ are hierarchical strings that store information about an entity. They can be used for filtering and discoverability. - conditions: List[ConditionTemplate] or List[ConditionTemplate, \ + conditions: list[ConditionTemplate] or list[ConditionTemplate, \ :py:class:`BaseBounds `], optional Templates for associated conditions. Each template can be provided by itself, or as a list with the second entry being a separate, *more restrictive* Bounds object that defines the limits of the value for this condition. - parameters: List[ParameterTemplate] or List[ParameterTemplate, \ + parameters: list[ParameterTemplate] or list[ParameterTemplate, \ :py:class:`BaseBounds `], optional Templates for associated parameters. Each template can be provided by itself, or as a list with the second entry being a separate, *more restrictive* Bounds object that defines the limits of the value for this parameter. - properties: List[PropertyTemplate] or List[PropertyTemplate, \ + properties: list[PropertyTemplate] or list[PropertyTemplate, \ :py:class:`BaseBounds `], optional Templates for associated properties. Each template can be provided by itself, or as a list with the second entry being a separate, *more restrictive* Bounds object that defines @@ -100,7 +100,7 @@ class MeasurementTemplate( def __init__(self, name: str, *, - uids: Optional[Dict[str, str]] = None, + uids: Optional[dict[str, str]] = None, properties: Optional[Sequence[Union[PropertyTemplate, LinkByUID, Sequence[Union[PropertyTemplate, LinkByUID, @@ -117,7 +117,7 @@ def __init__(self, Optional[BaseBounds]]] ]]] = None, description: Optional[str] = None, - tags: Optional[List[str]] = None): + tags: Optional[list[str]] = None): if uids is None: uids = dict() super(ObjectTemplate, self).__init__() @@ -137,6 +137,6 @@ class MeasurementTemplateCollection(ObjectTemplateCollection[MeasurementTemplate _resource = MeasurementTemplate @classmethod - def get_type(cls) -> Type[MeasurementTemplate]: + def get_type(cls) -> type[MeasurementTemplate]: """Return the resource type in the collection.""" return MeasurementTemplate diff --git a/src/citrine/resources/parameter_template.py b/src/citrine/resources/parameter_template.py index 3227307fe..ae4a6ff0d 100644 --- a/src/citrine/resources/parameter_template.py +++ b/src/citrine/resources/parameter_template.py @@ -28,7 +28,7 @@ class ParameterTemplate( A collection of `unique IDs `_. - tags: List[str], optional + tags: list[str], optional `Tags `_ are hierarchical strings that store information about an entity. They can be used for filtering and discoverability. @@ -41,9 +41,9 @@ def __init__(self, name: str, *, bounds: BaseBounds, - uids: Optional[Dict[str, str]] = None, + uids: Optional[dict[str, str]] = None, description: Optional[str] = None, - tags: Optional[List[str]] = None): + tags: Optional[list[str]] = None): if uids is None: uids = dict() super(AttributeTemplate, self).__init__() @@ -62,6 +62,6 @@ class ParameterTemplateCollection(AttributeTemplateCollection[ParameterTemplate] _resource = ParameterTemplate @classmethod - def get_type(cls) -> Type[ParameterTemplate]: + def get_type(cls) -> type[ParameterTemplate]: """Return the resource type in the collection.""" return ParameterTemplate diff --git a/src/citrine/resources/predictor.py b/src/citrine/resources/predictor.py index 08b69aaf0..e905ca9f2 100644 --- a/src/citrine/resources/predictor.py +++ b/src/citrine/resources/predictor.py @@ -35,7 +35,7 @@ class AsyncDefaultPredictor(Resource["AsyncDefaultPredictor"]): status_detail = properties.List(properties.Object(StatusDetail), 'metadata.status_detail', default=[], serializable=False) - """:List[StatusDetail]: a list of structured status info, containing the message and level""" + """:list[StatusDetail]: a list of structured status info, containing the message and level""" @classmethod def _pre_build(cls, data: dict) -> dict: @@ -126,7 +126,7 @@ def get_featurized_training_data( uid: Union[UUID, str], *, version: Union[int, str] = MOST_RECENT_VER - ) -> List[HierarchicalDesignMaterial]: + ) -> list[HierarchicalDesignMaterial]: version_path = self._construct_path(uid, version) full_path = f"{version_path}/featurized-training-data" payload = self.session.get_resource(full_path, version=self._api_version) @@ -247,7 +247,7 @@ def get_featurized_training_data( uid: Union[UUID, str], *, version: Union[int, str] = MOST_RECENT_VER - ) -> List[HierarchicalDesignMaterial]: + ) -> list[HierarchicalDesignMaterial]: """Retrieve a list of featurized materials for a trained predictor. Featurized materials contain the input variables found in the training data source diff --git a/src/citrine/resources/predictor_evaluation.py b/src/citrine/resources/predictor_evaluation.py index 20156bd49..924ab2f11 100644 --- a/src/citrine/resources/predictor_evaluation.py +++ b/src/citrine/resources/predictor_evaluation.py @@ -165,7 +165,7 @@ def trigger(self, Unique identifier of the predictor to evaluate predictor_version: Option[Union[int, str]] The version of the predictor to evaluate. Defaults to the latest trained version. - evaluators: List[PredictorEvaluator] + evaluators: list[PredictorEvaluator] The evaluators to use to measure predictor performance. Returns diff --git a/src/citrine/resources/process_run.py b/src/citrine/resources/process_run.py index 7a960ff56..869f1d9a9 100644 --- a/src/citrine/resources/process_run.py +++ b/src/citrine/resources/process_run.py @@ -30,19 +30,19 @@ class ProcessRun(GEMDResource['ProcessRun'], ObjectRun, GEMDProcessRun, typ=GEMD A collection of `unique IDs `_. - tags: List[str], optional + tags: list[str], optional `Tags `_ are hierarchical strings that store information about an entity. They can be used for filtering and discoverability. notes: str, optional Long-form notes about the process run. - conditions: List[Condition], optional + conditions: list[Condition], optional Conditions under which this process run occurs. - parameters: List[Parameter], optional + parameters: list[Parameter], optional Parameters of this process run. spec: ProcessSpec Spec for this process run. - file_links: List[FileLink], optional + file_links: list[FileLink], optional Links to associated files, with resource paths into the files API. source: PerformedSource, optional Information about the person who performed the run and when. @@ -60,13 +60,13 @@ class ProcessRun(GEMDResource['ProcessRun'], ObjectRun, GEMDProcessRun, typ=GEMD def __init__(self, name: str, *, - uids: Optional[Dict[str, str]] = None, - tags: Optional[List[str]] = None, + uids: Optional[dict[str, str]] = None, + tags: Optional[list[str]] = None, notes: Optional[str] = None, - conditions: Optional[List[Condition]] = None, - parameters: Optional[List[Parameter]] = None, + conditions: Optional[list[Condition]] = None, + parameters: Optional[list[Parameter]] = None, spec: Optional[GEMDProcessSpec] = None, - file_links: Optional[List[FileLink]] = None, + file_links: Optional[list[FileLink]] = None, source: Optional[PerformedSource] = None): if uids is None: uids = dict() @@ -87,7 +87,7 @@ class ProcessRunCollection(ObjectRunCollection[ProcessRun]): _resource = ProcessRun @classmethod - def get_type(cls) -> Type[ProcessRun]: + def get_type(cls) -> type[ProcessRun]: """Return the resource type in the collection.""" return ProcessRun diff --git a/src/citrine/resources/process_spec.py b/src/citrine/resources/process_spec.py index 46f4de458..2e4efbc3c 100644 --- a/src/citrine/resources/process_spec.py +++ b/src/citrine/resources/process_spec.py @@ -34,19 +34,19 @@ class ProcessSpec( A collection of `unique IDs `_. - tags: List[str], optional + tags: list[str], optional `Tags `_ are hierarchical strings that store information about an entity. They can be used for filtering and discoverability. notes: str, optional Long-form notes about the process spec. - conditions: List[Condition], optional + conditions: list[Condition], optional Conditions under which this process spec occurs. - parameters: List[Parameter], optional + parameters: list[Parameter], optional Parameters of this process spec. template: ProcessTemplate, optional A template bounding the valid values for this process's parameters and conditions. - file_links: List[FileLink], optional + file_links: list[FileLink], optional Links to associated files, with resource paths into the files API. """ @@ -64,13 +64,13 @@ class ProcessSpec( def __init__(self, name: str, *, - uids: Optional[Dict[str, str]] = None, - tags: Optional[List[str]] = None, + uids: Optional[dict[str, str]] = None, + tags: Optional[list[str]] = None, notes: Optional[str] = None, - conditions: Optional[List[Condition]] = None, - parameters: Optional[List[Parameter]] = None, + conditions: Optional[list[Condition]] = None, + parameters: Optional[list[Parameter]] = None, template: Optional[GEMDProcessTemplate] = None, - file_links: Optional[List[FileLink]] = None + file_links: Optional[list[FileLink]] = None ): if uids is None: uids = dict() @@ -91,7 +91,7 @@ class ProcessSpecCollection(ObjectSpecCollection[ProcessSpec]): _resource = ProcessSpec @classmethod - def get_type(cls) -> Type[ProcessSpec]: + def get_type(cls) -> type[ProcessSpec]: """Return the resource type in the collection.""" return ProcessSpec diff --git a/src/citrine/resources/process_template.py b/src/citrine/resources/process_template.py index a53b692f3..6b6fadad9 100644 --- a/src/citrine/resources/process_template.py +++ b/src/citrine/resources/process_template.py @@ -40,16 +40,16 @@ class ProcessTemplate( A collection of `unique IDs `_. - tags: List[str], optional + tags: list[str], optional `Tags `_ are hierarchical strings that store information about an entity. They can be used for filtering and discoverability. - conditions: List[ConditionTemplate] or List[ConditionTemplate, \ + conditions: list[ConditionTemplate] or list[ConditionTemplate, \ :py:class:`BaseBounds `], optional Templates for associated conditions. Each template can be provided by itself, or as a list with the second entry being a separate, *more restrictive* Bounds object that defines the limits of the value for this condition. - parameters: List[ParameterTemplate] or List[ParameterTemplate, \ + parameters: list[ParameterTemplate] or list[ParameterTemplate, \ :py:class:`BaseBounds `], optional Templates for associated parameters. Each template can be provided by itself, or as a list with the second entry being a separate, *more restrictive* Bounds object that defines @@ -85,7 +85,7 @@ class ProcessTemplate( def __init__(self, name: str, *, - uids: Optional[Dict[str, str]] = None, + uids: Optional[dict[str, str]] = None, conditions: Optional[Sequence[Union[ConditionTemplate, LinkByUID, Sequence[Union[ConditionTemplate, LinkByUID, @@ -96,10 +96,10 @@ def __init__(self, Sequence[Union[ParameterTemplate, LinkByUID, Optional[BaseBounds]]] ]]] = None, - allowed_labels: Optional[List[str]] = None, - allowed_names: Optional[List[str]] = None, + allowed_labels: Optional[list[str]] = None, + allowed_names: Optional[list[str]] = None, description: Optional[str] = None, - tags: Optional[List[str]] = None): + tags: Optional[list[str]] = None): if uids is None: uids = dict() super(ObjectTemplate, self).__init__() @@ -120,6 +120,6 @@ class ProcessTemplateCollection(ObjectTemplateCollection[ProcessTemplate]): _resource = ProcessTemplate @classmethod - def get_type(cls) -> Type[ProcessTemplate]: + def get_type(cls) -> type[ProcessTemplate]: """Return the resource type in the collection.""" return ProcessTemplate diff --git a/src/citrine/resources/project.py b/src/citrine/resources/project.py index f59e7206c..ef6d5472c 100644 --- a/src/citrine/resources/project.py +++ b/src/citrine/resources/project.py @@ -225,13 +225,13 @@ def pull_in_resource(self, *, resource: Resource): json={'ids': [resource_access["id"]]}) return True - def list_members(self) -> Union[List[ProjectMember], List["TeamMember"]]: # noqa: F821 + def list_members(self) -> Union[list[ProjectMember], list["TeamMember"]]: # noqa: F821 """ List all of the members in the current project. Returns ------- - List[ProjectMember] | List[TeamMember] + list[ProjectMember] | list[TeamMember] The members of the current project, or the members of the team containing the project if teams have been released. diff --git a/src/citrine/resources/property_template.py b/src/citrine/resources/property_template.py index 1391669c2..deb1d3ce4 100644 --- a/src/citrine/resources/property_template.py +++ b/src/citrine/resources/property_template.py @@ -28,7 +28,7 @@ class PropertyTemplate( A collection of `unique IDs `_. - tags: List[str], optional + tags: list[str], optional `Tags `_ are hierarchical strings that store information about an entity. They can be used for filtering and discoverability. @@ -41,9 +41,9 @@ def __init__(self, name: str, *, bounds: BaseBounds, - uids: Optional[Dict[str, str]] = None, + uids: Optional[dict[str, str]] = None, description: Optional[str] = None, - tags: Optional[List[str]] = None): + tags: Optional[list[str]] = None): if uids is None: uids = dict() super(AttributeTemplate, self).__init__() @@ -62,6 +62,6 @@ class PropertyTemplateCollection(AttributeTemplateCollection[PropertyTemplate]): _resource = PropertyTemplate @classmethod - def get_type(cls) -> Type[PropertyTemplate]: + def get_type(cls) -> type[PropertyTemplate]: """Return the resource type in the collection.""" return PropertyTemplate diff --git a/src/citrine/resources/table_config.py b/src/citrine/resources/table_config.py index ad03a4de5..f0ea63592 100644 --- a/src/citrine/resources/table_config.py +++ b/src/citrine/resources/table_config.py @@ -120,10 +120,10 @@ def _get_dups(lst: List) -> List: def __init__(self, name: str, *, description: str, - datasets: List[UUID], - variables: List[Variable], - rows: List[Row], - columns: List[Column], + datasets: list[UUID], + variables: list[Variable], + rows: list[Row], + columns: list[Column], gemd_query: GemdQuery = None, generation_algorithm: Optional[TableFromGemdQueryAlgorithm] = None): self.name = name @@ -166,7 +166,7 @@ def uid(self, new_uid: Union[str, UUID]) -> None: def add_columns(self, *, variable: Variable, - columns: List[Column], + columns: list[Column], name: Optional[str] = None, description: Optional[str] = None ) -> 'TableConfig': @@ -306,7 +306,7 @@ def add_all_ingredients(self, *, return new_config def add_all_ingredients_in_output(self, *, - process_templates: List[LinkByUID], + process_templates: list[LinkByUID], team: 'Team', quantity_dimension: IngredientQuantityDimension, scope: str = CITRINE_SCOPE, @@ -322,7 +322,7 @@ def add_all_ingredients_in_output(self, *, Parameters ------------ - process_templates: List[LinkByUID] + process_templates: list[LinkByUID] registered process templates from which to pull allowed ingredients and at which to halt searching team: Team @@ -483,7 +483,7 @@ def default_for_material( name: str, description: str = None, algorithm: Optional[TableBuildAlgorithm] = None - ) -> Tuple[TableConfig, List[Tuple[Variable, Column]]]: + ) -> tuple[TableConfig, list[tuple[Variable, Column]]]: """ Build best-guess default table config for provided terminal material's history. @@ -510,7 +510,7 @@ def default_for_material( Returns ------- - List[Tuple[Variable, Column]] + list[tuple[Variable, Column]] A table config as well as addition variables/columns which would result in ambiguous matches if included in the config. @@ -545,7 +545,7 @@ def from_query( description: str = None, algorithm: Optional[TableFromGemdQueryAlgorithm] = None, register_config: bool = False - ) -> Tuple[TableConfig, List[Tuple[Variable, Column]]]: + ) -> tuple[TableConfig, list[tuple[Variable, Column]]]: """ Build a TableConfig based on the results of a database query. @@ -565,7 +565,7 @@ def from_query( Returns ------- - List[Tuple[Variable, Column]] + list[tuple[Variable, Column]] A table config as well as addition variables/columns which would result in ambiguous matches if included in the config. @@ -598,7 +598,7 @@ def from_query( def preview(self, *, table_config: TableConfig, - preview_materials: List[LinkByUID] = None + preview_materials: list[LinkByUID] = None ) -> dict: """Preview a Table Config on an explicit set of terminal materials. @@ -606,7 +606,7 @@ def preview(self, *, ---------- table_config: TableConfig Table Config to preview - preview_materials: List[LinkByUID] + preview_materials: list[LinkByUID] List of links to the material runs to use as terminal materials in the preview """ diff --git a/src/citrine/resources/team.py b/src/citrine/resources/team.py index 275babc59..3b31e5b9e 100644 --- a/src/citrine/resources/team.py +++ b/src/citrine/resources/team.py @@ -46,10 +46,10 @@ def __init__(self, *, user: User, team: 'Team', # noqa: F821 - actions: List[TEAM_ACTIONS]): + actions: list[TEAM_ACTIONS]): self.user = user self.team: 'Team' = team # noqa: F821 - self.actions: List[TEAM_ACTIONS] = actions + self.actions: list[TEAM_ACTIONS] = actions def __str__(self): return '' \ @@ -86,7 +86,7 @@ def __init__(self, def _path(self) -> str: return format_escaped_url(f'/teams/{self.team_id}') - def _list_ids(self, action: str) -> List[str]: + def _list_ids(self, action: str) -> list[str]: query_params = {"domain": self._path(), "action": action} return self.session.get_resource(f"/{self.resource_type}/authorized-ids", params=query_params, @@ -98,7 +98,7 @@ def list_readable(self): Returns ------- - List[str] + list[str] Returns a list of string UUIDs for each resource """ @@ -110,7 +110,7 @@ def list_writeable(self): Returns ------- - List[str] + list[str] Returns a list of string UUIDs for each resource """ @@ -122,7 +122,7 @@ def list_shareable(self): Returns ------- - List[str] + list[str] Returns a list of string UUIDs for each resource """ @@ -174,7 +174,7 @@ def __str__(self): def _path(self): return format_escaped_url('/teams/{team_id}', team_id=self.uid) - def list_members(self) -> List[TeamMember]: + def list_members(self) -> list[TeamMember]: """ List all of the members in the current team. @@ -182,7 +182,7 @@ def list_members(self) -> List[TeamMember]: Returns ------- - List[TeamMember] + list[TeamMember] The members of the current team """ @@ -252,7 +252,7 @@ def remove_user(self, user_id: Union[str, UUID, User]) -> bool: def add_user(self, user_id: Union[str, UUID, User], *, - actions: Optional[List[TEAM_ACTIONS]] = None) -> bool: + actions: Optional[list[TEAM_ACTIONS]] = None) -> bool: """ Add a User to a Team. @@ -286,7 +286,7 @@ def add_user(self, def update_user_action(self, user_id: Union[str, UUID, User], *, - actions: List[TEAM_ACTIONS]) -> bool: + actions: list[TEAM_ACTIONS]) -> bool: """ Overwrites a User's action permissions in the Team. @@ -376,13 +376,13 @@ def un_share(self, *, resource: Resource, target_team_id: Union[str, UUID, "Team ) return True - def owned_dataset_ids(self) -> List[str]: + def owned_dataset_ids(self) -> list[str]: """ List all the ids of the datasets owned by the current team. Returns ------- - List[str] + list[str] The ids of the modules owned by current team """ @@ -513,10 +513,10 @@ def gemd(self) -> GEMDResourceCollection: return GEMDResourceCollection(team_id=self.uid, dataset_id=None, session=self.session) def gemd_batch_delete(self, - id_list: List[Union[LinkByUID, UUID, str, BaseEntity]], + id_list: list[Union[LinkByUID, UUID, str, BaseEntity]], *, timeout: float = 2 * 60, - polling_delay: float = 1.0) -> List[Tuple[LinkByUID, ApiError]]: + polling_delay: float = 1.0) -> list[tuple[LinkByUID, ApiError]]: """ Remove a set of GEMD objects. @@ -530,7 +530,7 @@ def gemd_batch_delete(self, Parameters ---------- - id_list: List[Union[LinkByUID, UUID, str, BaseEntity]] + id_list: list[Union[LinkByUID, UUID, str, BaseEntity]] A list of the IDs of data objects to be removed. They can be passed as a LinkByUID tuple, a UUID, a string, or the object itself. A UUID or string is assumed to be a Citrine ID, whereas a LinkByUID or @@ -544,7 +544,7 @@ def gemd_batch_delete(self, Returns ------- - List[Tuple[LinkByUID, ApiError]] + list[tuple[LinkByUID, ApiError]] A list of (LinkByUID, api_error) for each failure to delete an object. Note that this method doesn't raise an exception if an object fails to be deleted. From 0929f11a5b87f2339dcf8712062ba03e3f929064 Mon Sep 17 00:00:00 2001 From: Austin Noto-Moniz Date: Fri, 13 Feb 2026 14:02:50 -0500 Subject: [PATCH 2/6] Use new union syntax. As of python 3.10, unions can be expressed with the pipe (|) operator. --- src/citrine/_rest/collection.py | 8 +- src/citrine/_rest/pageable.py | 4 +- src/citrine/_rest/resource.py | 2 +- src/citrine/_serialization/properties.py | 30 +++--- src/citrine/_utils/functions.py | 6 +- src/citrine/gemtables/columns.py | 56 +++++----- src/citrine/gemtables/rows.py | 4 +- src/citrine/gemtables/variables.py | 74 ++++++------- .../ingredient_ratio_constraint.py | 4 +- src/citrine/informatics/data_sources.py | 6 +- src/citrine/informatics/descriptors.py | 2 +- .../design_spaces/design_space_settings.py | 4 +- .../design_spaces/product_design_space.py | 7 +- .../executions/predictor_evaluation.py | 4 +- .../predictor_evaluation_metrics.py | 4 +- .../informatics/predictors/graph_predictor.py | 2 +- .../predictors/mean_property_predictor.py | 12 +-- .../workflows/analysis_workflow.py | 4 +- .../informatics/workflows/design_workflow.py | 4 +- src/citrine/jobs/job.py | 12 +-- src/citrine/jobs/waiting.py | 41 +++---- src/citrine/resources/analysis_workflow.py | 10 +- src/citrine/resources/branch.py | 48 ++++----- src/citrine/resources/data_concepts.py | 14 +-- src/citrine/resources/data_objects.py | 6 +- src/citrine/resources/dataset.py | 8 +- src/citrine/resources/delete.py | 4 +- src/citrine/resources/descriptors.py | 4 +- src/citrine/resources/design_execution.py | 6 +- src/citrine/resources/design_space.py | 30 +++--- src/citrine/resources/design_workflow.py | 10 +- .../resources/experiment_datasource.py | 8 +- src/citrine/resources/file_link.py | 28 ++--- src/citrine/resources/gemd_resource.py | 4 +- src/citrine/resources/gemtables.py | 16 +-- .../resources/generative_design_execution.py | 2 +- src/citrine/resources/ingestion.py | 8 +- src/citrine/resources/ingredient_run.py | 12 +-- src/citrine/resources/ingredient_spec.py | 8 +- src/citrine/resources/material_run.py | 16 +-- src/citrine/resources/material_spec.py | 8 +- src/citrine/resources/material_template.py | 10 +- src/citrine/resources/measurement_run.py | 8 +- src/citrine/resources/measurement_spec.py | 4 +- src/citrine/resources/measurement_template.py | 30 +++--- src/citrine/resources/predictor.py | 100 +++++++++--------- src/citrine/resources/predictor_evaluation.py | 32 +++--- src/citrine/resources/process_run.py | 4 +- src/citrine/resources/process_spec.py | 4 +- src/citrine/resources/process_template.py | 20 ++-- src/citrine/resources/project.py | 10 +- src/citrine/resources/report.py | 4 +- .../sample_design_space_execution.py | 2 +- src/citrine/resources/status_detail.py | 2 +- src/citrine/resources/table_config.py | 14 +-- src/citrine/resources/team.py | 22 ++-- tox.ini | 3 +- 57 files changed, 397 insertions(+), 412 deletions(-) diff --git a/src/citrine/_rest/collection.py b/src/citrine/_rest/collection.py index 35295a4aa..327cc7528 100644 --- a/src/citrine/_rest/collection.py +++ b/src/citrine/_rest/collection.py @@ -29,10 +29,10 @@ class Collection(Generic[ResourceType], Pageable): _api_version: str = "v1" def _get_path(self, - uid: Optional[Union[UUID, str]] = None, + uid: Optional[UUID | str] = None, *, ignore_dataset: bool = False, - action: Union[str, Sequence[str]] = [], + action: str | Sequence[str] = [], query_terms: dict[str, str] = {}, ) -> str: """Construct a url from __base_path__ and, optionally, id and/or action.""" @@ -44,7 +44,7 @@ def _get_path(self, def build(self, data: dict): """Build an individual element of the collection.""" - def get(self, uid: Union[UUID, str]) -> ResourceType: + def get(self, uid: UUID | str) -> ResourceType: """Get a particular element of the collection.""" if uid is None: raise ValueError("Cannot get when uid=None. Are you using a registered resource?") @@ -95,7 +95,7 @@ def update(self, model: CreationType) -> CreationType: data = updated[self._individual_key] if self._individual_key else updated return self.build(data) - def delete(self, uid: Union[UUID, str]) -> Response: + def delete(self, uid: UUID | str) -> Response: """Delete a particular element of the collection.""" url = self._get_path(uid) data = self.session.delete_resource(url, version=self._api_version) diff --git a/src/citrine/_rest/pageable.py b/src/citrine/_rest/pageable.py index 5e8b38fcd..0c46c8e10 100644 --- a/src/citrine/_rest/pageable.py +++ b/src/citrine/_rest/pageable.py @@ -9,10 +9,10 @@ class Pageable(): _api_version: str = "v1" def _get_path(self, - uid: Optional[Union[UUID, str]] = None, + uid: Optional[UUID | str] = None, *, ignore_dataset: bool = False, - action: Union[str, Sequence[str]] = [], + action: str | Sequence[str] = [], query_terms: dict[str, str] = {}, ) -> str: """Construct a url from __base_path__ and, optionally, id.""" diff --git a/src/citrine/_rest/resource.py b/src/citrine/_rest/resource.py index a0c1f492d..e572d5afa 100644 --- a/src/citrine/_rest/resource.py +++ b/src/citrine/_rest/resource.py @@ -100,6 +100,6 @@ class PredictorRef(Serializable['PredictorRef']): 'predictor_version' ) - def __init__(self, uid: Union[UUID, str], version: Optional[Union[int, str]] = None): + def __init__(self, uid: UUID | str, version: Optional[int | str] = None): self.uid = uid self.version = version diff --git a/src/citrine/_serialization/properties.py b/src/citrine/_serialization/properties.py index f3f947176..d7be5e14d 100644 --- a/src/citrine/_serialization/properties.py +++ b/src/citrine/_serialization/properties.py @@ -74,12 +74,12 @@ def __init__(self, @property @abstractmethod - def underlying_types(self) -> typing.Union[DeserializedType, tuple[DeserializedType]]: + def underlying_types(self) -> DeserializedType | tuple[DeserializedType]: """Return the python types handled by this property.""" @property @abstractmethod - def serialized_types(self) -> typing.Union[SerializedType, tuple[SerializedType]]: + def serialized_types(self) -> SerializedType | tuple[SerializedType]: """Return the types used to serialize this property.""" def _error_source(self, base_class: type) -> str: @@ -167,7 +167,7 @@ def __get__(self, obj, objtype=None) -> DeserializedType: else: return getattr(obj, self._key, self.default) - def __set__(self, obj, value: typing.Union[SerializedType, DeserializedType]): + def __set__(self, obj, value: SerializedType | DeserializedType): """Property setter, deferring to the setter of the parent class, if applicable.""" property_name, base_class = _get_key_and_base_class(self, type(obj)) if issubclass(type(value), self.underlying_types): @@ -197,7 +197,7 @@ def __str__(self): class PropertyCollection(Property[DeserializedType, SerializedType]): - def __set__(self, obj, value: typing.Union[SerializedType, DeserializedType]): + def __set__(self, obj, value: SerializedType | DeserializedType): """ Property setter for container property types. @@ -231,7 +231,7 @@ def __set__(self, obj, value: typing.Union[SerializedType, DeserializedType]): setattr(obj, self._key, value_to_set) @abstractmethod - def _set_elements(self, value: typing.Union[SerializedType, DeserializedType]): + def _set_elements(self, value: SerializedType | DeserializedType): """ Perform any needed underlying element specific deserialization. @@ -415,7 +415,7 @@ def _serialize(self, value: datetime) -> int: class List(PropertyCollection[list, list]): def __init__(self, - element_type: typing.Union[Property, type[Property]], + element_type: Property | type[Property], serialization_path: typing.Optional[str] = None, *, serializable: bool = True, @@ -469,7 +469,7 @@ def _set_elements(self, value): class Set(PropertyCollection[set, typing.Iterable]): def __init__(self, - element_type: typing.Union[Property, type[Property]], + element_type: Property | type[Property], serialization_path: typing.Optional[str] = None, *, serializable: bool = True, @@ -530,7 +530,7 @@ class Union(Property[typing.Any, typing.Any]): """ def __init__(self, - element_types: typing.Sequence[typing.Union[Property, type[Property]]], + element_types: typing.Sequence[Property | type[Property]], serialization_path: typing.Optional[str] = None, *, serializable: bool = True, @@ -585,7 +585,7 @@ class SpecifiedMixedList(PropertyCollection[list, list]): """A finite list in which the type of each entry is specified.""" def __init__(self, - element_types: typing.Sequence[typing.Union[Property, type[Property]]], + element_types: typing.Sequence[Property | type[Property]], serialization_path: typing.Optional[str] = None, *, serializable: bool = True, @@ -816,7 +816,7 @@ def _set_elements(self, value): return self.deserialize(value) -class LinkOrElse(PropertyCollection[typing.Union[Serializable, LinkByUID], dict]): +class LinkOrElse(PropertyCollection[Serializable | LinkByUID, dict]): """ A property that can either be a serializable object with IDs or a LinkByUID object. @@ -893,7 +893,7 @@ def _set_elements(self, value): class Optional(PropertyCollection[typing.Optional[typing.Any], typing.Optional[typing.Any]]): def __init__(self, - prop: typing.Union[Property, type[Property]], + prop: Property | type[Property], serialization_path: typing.Optional[str] = None, *, serializable: bool = True, @@ -959,8 +959,8 @@ class Mapping(PropertyCollection[dict, dict]): """ def __init__(self, - keys_type: typing.Union[Property, type[Property]], - values_type: typing.Union[Property, type[Property]], + keys_type: Property | type[Property], + values_type: Property | type[Property], serialization_path: typing.Optional[str] = None, *, serializable: bool = True, @@ -992,7 +992,7 @@ def serialized_types(self): else: return dict - def _deserialize(self, value: typing.Union[dict, list]) -> dict: + def _deserialize(self, value: dict | list) -> dict: deserialized = dict() if type(value) is list: @@ -1008,7 +1008,7 @@ def _deserialize(self, value: typing.Union[dict, list]) -> dict: deserialized[deserialized_key] = deserialized_value return deserialized - def _serialize(self, value: dict) -> typing.Union[dict, list]: + def _serialize(self, value: dict) -> dict | list: if self.ser_as_list_of_pairs: serialized = [] for key, value in value.items(): diff --git a/src/citrine/_utils/functions.py b/src/citrine/_utils/functions.py index a93971e23..bbb21a585 100644 --- a/src/citrine/_utils/functions.py +++ b/src/citrine/_utils/functions.py @@ -118,7 +118,7 @@ def rewrite_s3_links_locally(url: str, s3_endpoint_url: str = None) -> str: return url -def write_file_locally(content, local_path: Union[str, Path]): +def write_file_locally(content, local_path: str | Path): """Take content from remote and ensure path exists.""" if isinstance(local_path, str): if len(os.path.split(local_path)[-1]) == 0: @@ -297,8 +297,8 @@ def format_escaped_url( def resource_path(*, path_template: str, - uid: Optional[Union[UUID, str]] = None, - action: Union[str, Sequence[str]] = [], + uid: Optional[UUID | str] = None, + action: str | Sequence[str] = [], query_terms: dict[str, str] = {}, **kwargs ) -> str: diff --git a/src/citrine/gemtables/columns.py b/src/citrine/gemtables/columns.py index cac6661d1..bc3d35c8d 100644 --- a/src/citrine/gemtables/columns.py +++ b/src/citrine/gemtables/columns.py @@ -32,12 +32,12 @@ class ChemicalDisplayFormat(BaseEnumeration): INCHI = "inchi" -def _make_data_source(variable_rep: Union[str, Variable]) -> str: +def _make_data_source(variable_rep: str | Variable) -> str: """Return a string appropriate to use as a data_source. Parameters ---------- - variable_rep: Union[str, Variable] + variable_rep: str | Variable Either the name of the variable or the variable itself """ @@ -86,7 +86,7 @@ class MeanColumn(Serializable['MeanColumn'], Column): Parameters ---------- - data_source: Union[str, Variable] + data_source: str | Variable name of the variable to use when populating the column target_units: Optional[str] units to convert the real variable into. If not specified: @@ -102,7 +102,7 @@ class MeanColumn(Serializable['MeanColumn'], Column): typ = properties.String('type', default="mean_column", deserializable=False) def __init__(self, *, - data_source: Union[str, Variable], + data_source: str | Variable, target_units: Optional[str] = None): self.data_source = _make_data_source(data_source) self.target_units = target_units @@ -113,7 +113,7 @@ class StdDevColumn(Serializable["StdDevColumn"], Column): Parameters ---------- - data_source: Union[str, Variable] + data_source: str | Variable name of the variable to use when populating the column target_units: Optional[str] units to convert the real variable into. If not specified: @@ -129,7 +129,7 @@ class StdDevColumn(Serializable["StdDevColumn"], Column): typ = properties.String('type', default="std_dev_column", deserializable=False) def __init__(self, *, - data_source: Union[str, Variable], + data_source: str | Variable, target_units: Optional[str] = None): self.data_source = _make_data_source(data_source) self.target_units = target_units @@ -154,7 +154,7 @@ class QuantileColumn(Serializable["QuantileColumn"], Column): Parameters ---------- - data_source: Union[str, Variable] + data_source: str | Variable name of the variable to use when populating the column quantile: float the quantile to use for the column, defined between 0.0 and 1.0 @@ -173,7 +173,7 @@ class QuantileColumn(Serializable["QuantileColumn"], Column): typ = properties.String('type', default="quantile_column", deserializable=False) def __init__(self, *, - data_source: Union[str, Variable], + data_source: str | Variable, quantile: float, target_units: Optional[str] = None): self.data_source = _make_data_source(data_source) @@ -186,7 +186,7 @@ class OriginalUnitsColumn(Serializable["OriginalUnitsColumn"], Column): Parameters ---------- - data_source: Union[str, Variable] + data_source: str | Variable name of the variable to use when populating the column """ @@ -194,7 +194,7 @@ class OriginalUnitsColumn(Serializable["OriginalUnitsColumn"], Column): data_source = properties.String('data_source') typ = properties.String('type', default="original_units_column", deserializable=False) - def __init__(self, *, data_source: Union[str, Variable]): + def __init__(self, *, data_source: str | Variable): self.data_source = _make_data_source(data_source) @@ -203,7 +203,7 @@ class MostLikelyCategoryColumn(Serializable["MostLikelyCategoryColumn"], Column) Parameters ---------- - data_source: Union[str, Variable] + data_source: str | Variable name of the variable to use when populating the column """ @@ -211,7 +211,7 @@ class MostLikelyCategoryColumn(Serializable["MostLikelyCategoryColumn"], Column) data_source = properties.String('data_source') typ = properties.String('type', default="most_likely_category_column", deserializable=False) - def __init__(self, *, data_source: Union[str, Variable]): + def __init__(self, *, data_source: str | Variable): self.data_source = _make_data_source(data_source) @@ -220,7 +220,7 @@ class MostLikelyProbabilityColumn(Serializable["MostLikelyProbabilityColumn"], C Parameters ---------- - data_source: Union[str, Variable] + data_source: str | Variable name of the variable to use when populating the column """ @@ -228,7 +228,7 @@ class MostLikelyProbabilityColumn(Serializable["MostLikelyProbabilityColumn"], C data_source = properties.String('data_source') typ = properties.String('type', default="most_likely_probability_column", deserializable=False) - def __init__(self, *, data_source: Union[str, Variable]): + def __init__(self, *, data_source: str | Variable): self.data_source = _make_data_source(data_source) @@ -241,7 +241,7 @@ class FlatCompositionColumn(Serializable["FlatCompositionColumn"], Column): Parameters ---------- - data_source: Union[str, Variable] + data_source: str | Variable name of the variable to use when populating the column sort_order: CompositionSortOrder order with which to sort the components when generating the flat string @@ -253,7 +253,7 @@ class FlatCompositionColumn(Serializable["FlatCompositionColumn"], Column): typ = properties.String('type', default="flat_composition_column", deserializable=False) def __init__(self, *, - data_source: Union[str, Variable], + data_source: str | Variable, sort_order: CompositionSortOrder): self.data_source = _make_data_source(data_source) self.sort_order = sort_order @@ -266,7 +266,7 @@ class ComponentQuantityColumn(Serializable["ComponentQuantityColumn"], Column): Parameters ---------- - data_source: Union[str, Variable] + data_source: str | Variable name of the variable to use when populating the column component_name: str name of the component from which to extract the quantity @@ -281,7 +281,7 @@ class ComponentQuantityColumn(Serializable["ComponentQuantityColumn"], Column): typ = properties.String('type', default="component_quantity_column", deserializable=False) def __init__(self, *, - data_source: Union[str, Variable], + data_source: str | Variable, component_name: str, normalize: bool = False): self.data_source = _make_data_source(data_source) @@ -296,7 +296,7 @@ class NthBiggestComponentNameColumn(Serializable["NthBiggestComponentNameColumn" Parameters ---------- - data_source: Union[str, Variable] + data_source: str | Variable name of the variable to use when populating the column n: int index of the component name to extract, starting with 1 for the biggest @@ -308,7 +308,7 @@ class NthBiggestComponentNameColumn(Serializable["NthBiggestComponentNameColumn" typ = properties.String('type', default="biggest_component_name_column", deserializable=False) def __init__(self, *, - data_source: Union[str, Variable], + data_source: str | Variable, n: int): self.data_source = _make_data_source(data_source) self.n = n @@ -321,7 +321,7 @@ class NthBiggestComponentQuantityColumn(Serializable["NthBiggestComponentQuantit Parameters ---------- - data_source: Union[str, Variable] + data_source: str | Variable name of the variable to use when populating the column n: int index of the component quantity to extract, starting with 1 for the biggest @@ -337,7 +337,7 @@ class NthBiggestComponentQuantityColumn(Serializable["NthBiggestComponentQuantit default="biggest_component_quantity_column", deserializable=False) def __init__(self, *, - data_source: Union[str, Variable], + data_source: str | Variable, n: int, normalize: bool = False): self.data_source = _make_data_source(data_source) @@ -350,7 +350,7 @@ class IdentityColumn(Serializable['IdentityColumn'], Column): Parameters ---------- - data_source: Union[str, Variable] + data_source: str | Variable name of the variable to use when populating the column """ @@ -358,7 +358,7 @@ class IdentityColumn(Serializable['IdentityColumn'], Column): data_source = properties.String('data_source') typ = properties.String('type', default="identity_column", deserializable=False) - def __init__(self, *, data_source: Union[str, Variable]): + def __init__(self, *, data_source: str | Variable): self.data_source = _make_data_source(data_source) @@ -367,7 +367,7 @@ class MolecularStructureColumn(Serializable['MolecularStructureColumn'], Column) Parameters ---------- - data_source: Union[str, Variable] + data_source: str | Variable name of the variable to use when populating the column format: ChemicalDisplayFormat the format in which to display the molecular structure @@ -378,7 +378,7 @@ class MolecularStructureColumn(Serializable['MolecularStructureColumn'], Column) format = properties.Enumeration(ChemicalDisplayFormat, 'format') typ = properties.String('type', default="molecular_structure_column", deserializable=False) - def __init__(self, *, data_source: Union[str, Variable], format: ChemicalDisplayFormat): + def __init__(self, *, data_source: str | Variable, format: ChemicalDisplayFormat): self.data_source = _make_data_source(data_source) self.format = format @@ -392,7 +392,7 @@ class ConcatColumn(Serializable['ConcatColumn'], Column): Parameters ---------- - data_source: Union[str, Variable] + data_source: str | Variable name of the variable to use when populating the column subcolumn: Column a column of the type of the individual values to be concatenated @@ -403,6 +403,6 @@ class ConcatColumn(Serializable['ConcatColumn'], Column): subcolumn = properties.Object(Column, 'subcolumn') typ = properties.String('type', default="concat_column", deserializable=False) - def __init__(self, *, data_source: Union[str, Variable], subcolumn: Column): + def __init__(self, *, data_source: str | Variable, subcolumn: Column): self.data_source = _make_data_source(data_source) self.subcolumn = subcolumn diff --git a/src/citrine/gemtables/rows.py b/src/citrine/gemtables/rows.py index 42ce03e3d..8a1f5abea 100644 --- a/src/citrine/gemtables/rows.py +++ b/src/citrine/gemtables/rows.py @@ -43,7 +43,7 @@ class MaterialRunByTemplate(Serializable['MaterialRunByTemplate'], Row): Parameters ---------- - templates: list[Union[UUID, str, LinkByUID, MaterialTemplate]] + templates: list[UUID | str | LinkByUID | MaterialTemplate] templates of materials to include tags: set[str] optional list of tags for filtering. If a terminal material doesn't @@ -55,7 +55,7 @@ class MaterialRunByTemplate(Serializable['MaterialRunByTemplate'], Row): typ = properties.String('type', default="material_run_by_template", deserializable=False) tags = properties.Optional(properties.Set(properties.String), "tags") - template_type = Union[UUID, str, LinkByUID, MaterialTemplate] + template_type = UUID | str | LinkByUID | MaterialTemplate def __init__(self, *, templates: list[template_type], diff --git a/src/citrine/gemtables/variables.py b/src/citrine/gemtables/variables.py index 765924a4e..7582cbb13 100644 --- a/src/citrine/gemtables/variables.py +++ b/src/citrine/gemtables/variables.py @@ -125,9 +125,9 @@ class AttributeByTemplate(Serializable['AttributeByTemplate'], Variable): a short human-readable name to use when referencing the variable headers: list[str] sequence of column headers - template: Union[UUID, str, LinkByUID, AttributeTemplate] + template: UUID | str | LinkByUID | AttributeTemplate attribute template that identifies the attribute to assign to the variable - attribute_constraints: list[tuple[Union[UUID, str, LinkByUID, AttributeTemplate], Bounds]] + attribute_constraints: list[tuple[UUID | str | LinkByUID | AttributeTemplate, Bounds]] Optional constraints on object attributes in the target object that must be satisfied. Constraints are expressed as Bounds. Attributes are expressed with links. The attribute that the @@ -149,7 +149,7 @@ class AttributeByTemplate(Serializable['AttributeByTemplate'], Variable): type_selector = properties.Enumeration(DataObjectTypeSelector, "type_selector") typ = properties.String('type', default="attribute_by_template", deserializable=False) - attribute_type = Union[UUID, str, LinkByUID, AttributeTemplate] + attribute_type = UUID | str | LinkByUID | AttributeTemplate constraint_type = tuple[attribute_type, BaseBounds] def __init__(self, @@ -177,11 +177,11 @@ class AttributeByTemplateAfterProcessTemplate( a short human-readable name to use when referencing the variable headers: list[str] sequence of column headers - attribute_template: Union[UUID, str, LinkByUID, AttributeTemplate] + attribute_template: UUID | str | LinkByUID | AttributeTemplate attribute template that identifies the attribute to assign to the variable - process_template: Union[UUID, str, LinkByUID, ProcessTemplate] + process_template: UUID | str | LinkByUID | ProcessTemplate process template that identifies the originating process - attribute_constraints: list[tuple[Union[UUID, str, LinkByUID, AttributeTemplate], Bounds]] + attribute_constraints: list[tuple[UUID | str | LinkByUID | AttributeTemplate, Bounds]] Optional constraints on object attributes in the target object that must be satisfied. Constraints are expressed as Bounds. Attributes are expressed with links. The attribute that the @@ -204,8 +204,8 @@ class AttributeByTemplateAfterProcessTemplate( type_selector = properties.Enumeration(DataObjectTypeSelector, "type_selector") typ = properties.String('type', default="attribute_after_process", deserializable=False) - attribute_type = Union[UUID, str, LinkByUID, AttributeTemplate] - process_type = Union[UUID, str, LinkByUID, ProcessTemplate] + attribute_type = UUID | str | LinkByUID | AttributeTemplate + process_type = UUID | str | LinkByUID | ProcessTemplate constraint_type = tuple[attribute_type, BaseBounds] def __init__(self, @@ -240,11 +240,11 @@ class AttributeByTemplateAndObjectTemplate( a short human-readable name to use when referencing the variable headers: list[str] sequence of column headers - attribute_template: Union[UUID, str, LinkByUID, AttributeTemplate] + attribute_template: UUID | str | LinkByUID | AttributeTemplate attribute template that identifies the attribute to assign to the variable - object_template: Union[UUID, str, LinkByUID, BaseTemplate] + object_template: UUID | str | LinkByUID | BaseTemplate template that identifies the associated object - attribute_constraints: list[tuple[Union[UUID, str, LinkByUID, AttributeTemplate], Bounds]] + attribute_constraints: list[tuple[UUID | str | LinkByUID | AttributeTemplate, Bounds]] Optional constraints on object attributes in the target object that must be satisfied. Constraints are expressed as Bounds. Attributes are expressed with links. The attribute that the @@ -267,8 +267,8 @@ class AttributeByTemplateAndObjectTemplate( type_selector = properties.Enumeration(DataObjectTypeSelector, "type_selector") typ = properties.String('type', default="attribute_by_object", deserializable=False) - attribute_type = Union[UUID, str, LinkByUID, AttributeTemplate] - object_type = Union[UUID, str, LinkByUID, BaseTemplate] + attribute_type = UUID | str | LinkByUID | AttributeTemplate + object_type = UUID | str | LinkByUID | BaseTemplate constraint_type = tuple[attribute_type, BaseBounds] def __init__(self, @@ -297,9 +297,9 @@ class LocalAttribute(Serializable['LocalAttribute'], Variable): a short human-readable name to use when referencing the variable headers: list[str] sequence of column headers - template: Union[UUID, str, LinkByUID, AttributeTemplate] + template: UUID | str | LinkByUID | AttributeTemplate attribute template that identifies the attribute to assign to the variable - attribute_constraints: list[tuple[Union[UUID, str, LinkByUID, AttributeTemplate], Bounds]] + attribute_constraints: list[tuple[UUID | str | LinkByUID | AttributeTemplate, Bounds]] Optional constraints on object attributes in the target object that must be satisfied. Constraints are expressed as Bounds. Attributes are expressed with links. The attribute that the @@ -321,7 +321,7 @@ class LocalAttribute(Serializable['LocalAttribute'], Variable): type_selector = properties.Enumeration(DataObjectTypeSelector, "type_selector") typ = properties.String('type', default="local_attribute", deserializable=False) - attribute_type = Union[UUID, str, LinkByUID, AttributeTemplate] + attribute_type = UUID | str | LinkByUID | AttributeTemplate constraint_type = tuple[attribute_type, BaseBounds] def __init__(self, @@ -348,11 +348,11 @@ class LocalAttributeAndObject(Serializable['LocalAttributeAndObject'], Variable) a short human-readable name to use when referencing the variable headers: list[str] sequence of column headers - template: Union[UUID, str, LinkByUID, AttributeTemplate] + template: UUID | str | LinkByUID | AttributeTemplate attribute template that identifies the attribute to assign to the variable - object_template: Union[UUID, str, LinkByUID, AttributeTemplate] + object_template: UUID | str | LinkByUID | AttributeTemplate attribute template that identifies the attribute to assign to the variable - attribute_constraints: list[tuple[Union[UUID, str, LinkByUID, AttributeTemplate], Bounds]] + attribute_constraints: list[tuple[UUID | str | LinkByUID | AttributeTemplate, Bounds]] Optional constraints on object attributes in the target object that must be satisfied. Constraints are expressed as Bounds. Attributes are expressed with links. The attribute that the @@ -375,8 +375,8 @@ class LocalAttributeAndObject(Serializable['LocalAttributeAndObject'], Variable) type_selector = properties.Enumeration(DataObjectTypeSelector, "type_selector") typ = properties.String('type', default="local_attribute_and_object", deserializable=False) - attribute_type = Union[UUID, str, LinkByUID, AttributeTemplate] - object_type = Union[UUID, str, LinkByUID, BaseTemplate] + attribute_type = UUID | str | LinkByUID | AttributeTemplate + object_type = UUID | str | LinkByUID | BaseTemplate constraint_type = tuple[attribute_type, BaseBounds] def __init__(self, @@ -425,7 +425,7 @@ class IngredientIdentifierByProcessTemplateAndName( type_selector = properties.Enumeration(DataObjectTypeSelector, "type_selector") typ = properties.String('type', default="ing_id_by_process_and_name", deserializable=False) - process_type = Union[UUID, str, LinkByUID, ProcessTemplate] + process_type = UUID | str | LinkByUID | ProcessTemplate def __init__(self, name: str, @@ -477,7 +477,7 @@ class IngredientLabelByProcessAndName(Serializable['IngredientLabelByProcessAndN type_selector = properties.Enumeration(DataObjectTypeSelector, "type_selector") typ = properties.String('type', default="ing_label_by_process_and_name", deserializable=False) - process_type = Union[UUID, str, LinkByUID, ProcessTemplate] + process_type = UUID | str | LinkByUID | ProcessTemplate def __init__(self, name: str, @@ -524,7 +524,7 @@ class IngredientLabelsSetByProcessAndName( default="ing_labels_set_by_process_and_name", deserializable=False) - process_type = Union[UUID, str, LinkByUID, ProcessTemplate] + process_type = UUID | str | LinkByUID | ProcessTemplate def __init__(self, name: str, @@ -575,7 +575,7 @@ class IngredientQuantityByProcessAndName( deserializable=False) unit = properties.Optional(properties.String, "unit") - process_type = Union[UUID, str, LinkByUID, ProcessTemplate] + process_type = UUID | str | LinkByUID | ProcessTemplate def __init__(self, name: str, @@ -667,7 +667,7 @@ class AttributeInOutput(Serializable['AttributeInOutput'], Variable): process_templates: list[LinkByUID] process templates that should not be traversed through when searching for a matching attribute. The attribute may be present in these processes but not their ingredients. - attribute_constraints: list[tuple[Union[UUID, str, LinkByUID, AttributeTemplate], Bounds]] + attribute_constraints: list[tuple[UUID | str | LinkByUID | AttributeTemplate, Bounds]] Optional constraints on object attributes in the target object that must be satisfied. Constraints are expressed as Bounds. Attributes are expressed with links. The attribute that the @@ -690,8 +690,8 @@ class AttributeInOutput(Serializable['AttributeInOutput'], Variable): type_selector = properties.Enumeration(DataObjectTypeSelector, "type_selector") typ = properties.String('type', default="attribute_in_trunk", deserializable=False) - attribute_type = Union[UUID, str, LinkByUID, AttributeTemplate] - process_type = Union[UUID, str, LinkByUID, ProcessTemplate] + attribute_type = UUID | str | LinkByUID | AttributeTemplate + process_type = UUID | str | LinkByUID | ProcessTemplate constraint_type = tuple[attribute_type, BaseBounds] def __init__(self, @@ -748,7 +748,7 @@ class IngredientIdentifierInOutput(Serializable['IngredientIdentifierInOutput'], sequence of column headers ingredient_name: str Name of the ingredient to search for - process_templates: list[Union[UUID, str, LinkByUID, ProcessTemplate]] + process_templates: list[UUID | str | LinkByUID | ProcessTemplate] Process templates halt the search for a matching ingredient name. These process templates are inclusive. The ingredient may be present in these processes but not before. @@ -765,7 +765,7 @@ class IngredientIdentifierInOutput(Serializable['IngredientIdentifierInOutput'], type_selector = properties.Enumeration(DataObjectTypeSelector, "type_selector") typ = properties.String('type', default="ing_id_in_output", deserializable=False) - process_type = Union[UUID, str, LinkByUID, ProcessTemplate] + process_type = UUID | str | LinkByUID | ProcessTemplate def __init__(self, name: str, *, @@ -817,7 +817,7 @@ class IngredientLabelsSetInOutput(Serializable['IngredientLabelsSetInOutput'], V a short human-readable name to use when referencing the variable headers: list[str] sequence of column headers - process_templates: list[Union[UUID, str, LinkByUID, ProcessTemplate]] + process_templates: list[UUID | str | LinkByUID | ProcessTemplate] process templates that should not be traversed through when searching for a matching attribute. The attribute may be present in these processes but not their ingredients. ingredient_name: str @@ -831,7 +831,7 @@ class IngredientLabelsSetInOutput(Serializable['IngredientLabelsSetInOutput'], V ingredient_name = properties.String('ingredient_name') typ = properties.String('type', default="ing_label_set_in_output", deserializable=False) - process_type = Union[UUID, str, LinkByUID, ProcessTemplate] + process_type = UUID | str | LinkByUID | ProcessTemplate def __init__(self, name: str, *, @@ -885,7 +885,7 @@ class IngredientQuantityInOutput(Serializable['IngredientQuantityInOutput'], Var Dimension of the ingredient quantity: absolute quantity, number, mass, or volume fraction. Valid options are defined by :class:`~citrine.gemtables.variables.IngredientQuantityDimension` - process_templates: list[Union[UUID, str, LinkByUID, ProcessTemplate]] + process_templates: list[UUID | str | LinkByUID | ProcessTemplate] Process templates halt the search for a matching ingredient name. These process templates are inclusive. The ingredient may be present in these processes but not before. @@ -907,7 +907,7 @@ class IngredientQuantityInOutput(Serializable['IngredientQuantityInOutput'], Var unit = properties.Optional(properties.String, "unit") typ = properties.String('type', default="ing_quantity_in_output", deserializable=False) - process_type = Union[UUID, str, LinkByUID, ProcessTemplate] + process_type = UUID | str | LinkByUID | ProcessTemplate def __init__(self, name: str, *, @@ -968,7 +968,7 @@ class LocalIngredientIdentifier(Serializable['LocalIngredientIdentifier'], Varia type_selector = properties.Enumeration(DataObjectTypeSelector, "type_selector") typ = properties.String('type', default="local_ing_id", deserializable=False) - process_type = Union[UUID, str, LinkByUID, ProcessTemplate] + process_type = UUID | str | LinkByUID | ProcessTemplate def __init__(self, name: str, *, @@ -1009,7 +1009,7 @@ class LocalIngredientLabelsSet(Serializable['LocalIngredientLabelsSet'], Variabl ingredient_name = properties.String('ingredient_name') typ = properties.String('type', default="local_ing_label_set", deserializable=False) - process_type = Union[UUID, str, LinkByUID, ProcessTemplate] + process_type = UUID | str | LinkByUID | ProcessTemplate def __init__(self, name: str, *, @@ -1058,7 +1058,7 @@ class LocalIngredientQuantity(Serializable['LocalIngredientQuantity'], Variable) unit = properties.Optional(properties.String, "unit") typ = properties.String('type', default="local_ing_quantity", deserializable=False) - process_type = Union[UUID, str, LinkByUID, ProcessTemplate] + process_type = UUID | str | LinkByUID | ProcessTemplate def __init__(self, name: str, *, diff --git a/src/citrine/informatics/constraints/ingredient_ratio_constraint.py b/src/citrine/informatics/constraints/ingredient_ratio_constraint.py index bc6fcbcb3..396b9ad22 100644 --- a/src/citrine/informatics/constraints/ingredient_ratio_constraint.py +++ b/src/citrine/informatics/constraints/ingredient_ratio_constraint.py @@ -29,9 +29,9 @@ class IngredientRatioConstraint(Serializable['IngredientRatioConstraint'], Const multiplier for an ingredient in the numerator of the ratio label: Optional[tuple[str, float]] multiplier for a label in the numerator of the ratio - basis_ingredients: Optional[Union[list[str], dict[str, float]]] + basis_ingredients: Optional[list[str] | dict[str | float]] the ingredients which should appear in the denominator of the ratio - basis_labels: Optional[Union[list[str], dict[str, float]]] + basis_labels: Optional[list[str] | dict[str | float]] the labels which should appear in the denominator of the ratio """ diff --git a/src/citrine/informatics/data_sources.py b/src/citrine/informatics/data_sources.py index b3dfe02dd..2ee0733d6 100644 --- a/src/citrine/informatics/data_sources.py +++ b/src/citrine/informatics/data_sources.py @@ -75,7 +75,7 @@ class GemTableDataSource(Serializable['GemTableDataSource'], DataSource): ---------- table_id: UUID Unique identifier for the GEM Table - table_version: Union[str,int] + table_version: str | int Version number for the GEM Table. The first GEM table built from a configuration has version = 1. Strings are cast to ints. @@ -90,9 +90,9 @@ class GemTableDataSource(Serializable['GemTableDataSource'], DataSource): def __init__(self, *, table_id: UUID, - table_version: Union[int, str]): + table_version: int | str): self.table_id: UUID = table_id - self.table_version: Union[int, str] = table_version + self.table_version: int | str = table_version @classmethod def _data_source_id_builder(cls, *args) -> DataSource: diff --git a/src/citrine/informatics/descriptors.py b/src/citrine/informatics/descriptors.py index 8154324be..f55731f22 100644 --- a/src/citrine/informatics/descriptors.py +++ b/src/citrine/informatics/descriptors.py @@ -257,7 +257,7 @@ class FormulationDescriptor(Serializable['FormulationDescriptor'], Descriptor): 'type', default=FormulationKey.HIERARCHICAL.value, deserializable=False ) - def __init__(self, key: Union[FormulationKey, str]): + def __init__(self, key: FormulationKey | str): self.key = FormulationKey.from_str(key, exception=True) def __eq__(self, other): diff --git a/src/citrine/informatics/design_spaces/design_space_settings.py b/src/citrine/informatics/design_spaces/design_space_settings.py index 3c28ef0bd..584a7bd99 100644 --- a/src/citrine/informatics/design_spaces/design_space_settings.py +++ b/src/citrine/informatics/design_spaces/design_space_settings.py @@ -46,8 +46,8 @@ class DesignSpaceSettings(Resource["DesignSpaceSettings"]): def __init__(self, *, - predictor_id: Union[UUID, str], - predictor_version: Optional[Union[int, str]] = None, + predictor_id: UUID | str, + predictor_version: Optional[int | str] = None, mode: Optional[DefaultDesignSpaceMode] = None, exclude_intermediates: Optional[bool] = None, include_ingredient_fraction_constraints: Optional[bool] = None, diff --git a/src/citrine/informatics/design_spaces/product_design_space.py b/src/citrine/informatics/design_spaces/product_design_space.py index 458b52034..9a731d525 100644 --- a/src/citrine/informatics/design_spaces/product_design_space.py +++ b/src/citrine/informatics/design_spaces/product_design_space.py @@ -1,5 +1,4 @@ from typing import List, Union, Optional -from uuid import UUID from citrine._rest.engine_resource import EngineResource from citrine._serialization import properties @@ -22,7 +21,7 @@ class ProductDesignSpace(EngineResource['ProductDesignSpace'], TopLevelDesignSpa the name of the design space description:str the description of the design space - subspaces: list[Union[UUID, DesignSubspace]] + subspaces: list[DesignSubspace] the list of subspaces to combine, defined in-line dimensions: list[Dimension] univariate dimensions that are factors of the design space; can be enumerated or continuous @@ -44,11 +43,11 @@ def __init__(self, name: str, *, description: str, - subspaces: Optional[list[Union[UUID, DesignSubspace]]] = None, + subspaces: Optional[list[DesignSubspace]] = None, dimensions: Optional[list[Dimension]] = None): self.name: str = name self.description: str = description - self.subspaces: list[Union[UUID, DesignSubspace]] = subspaces or [] + self.subspaces: list[DesignSubspace] = subspaces or [] self.dimensions: list[Dimension] = dimensions or [] def _post_dump(self, data: dict) -> dict: diff --git a/src/citrine/informatics/executions/predictor_evaluation.py b/src/citrine/informatics/executions/predictor_evaluation.py index 3f7a4599e..7aa2c31a9 100644 --- a/src/citrine/informatics/executions/predictor_evaluation.py +++ b/src/citrine/informatics/executions/predictor_evaluation.py @@ -32,8 +32,8 @@ class PredictorEvaluationRequest(Serializable['EvaluatorsPayload']): def __init__(self, *, evaluators: list[PredictorEvaluator], - predictor_id: Union[UUID, str], - predictor_version: Optional[Union[int, str]] = None): + predictor_id: UUID | str, + predictor_version: Optional[int | str] = None): self.evaluators = evaluators self.predictor = PredictorRef(predictor_id, predictor_version) diff --git a/src/citrine/informatics/predictor_evaluation_metrics.py b/src/citrine/informatics/predictor_evaluation_metrics.py index 390b315a5..ae5eec754 100644 --- a/src/citrine/informatics/predictor_evaluation_metrics.py +++ b/src/citrine/informatics/predictor_evaluation_metrics.py @@ -155,7 +155,7 @@ class CoverageProbability(Serializable["CoverageProbability"], PredictorEvaluati Parameters ---------- - coverage_level: Union[str, float] + coverage_level: str | float Confidence-interval coverage level. The coverage level must be between 0 and 1.0 (non-inclusive) and will be rounded to 3 significant figures. Default: 0.683 corresponds to one std. deviation @@ -165,7 +165,7 @@ class CoverageProbability(Serializable["CoverageProbability"], PredictorEvaluati _level_str = properties.String("coverage_level") typ = properties.String("type", default="CoverageProbability", deserializable=False) - def __init__(self, *, coverage_level: Union[str, float] = "0.683"): + def __init__(self, *, coverage_level: str | float = "0.683"): if isinstance(coverage_level, str): try: raw_float = float(coverage_level) diff --git a/src/citrine/informatics/predictors/graph_predictor.py b/src/citrine/informatics/predictors/graph_predictor.py index 3027e953b..60c8bf32f 100644 --- a/src/citrine/informatics/predictors/graph_predictor.py +++ b/src/citrine/informatics/predictors/graph_predictor.py @@ -29,7 +29,7 @@ class GraphPredictor(VersionedEngineResource['GraphPredictor'], AsynchronousObje name of the configuration description: str the description of the predictor - predictors: list[Union[UUID, PredictorNode]], + predictors: list[UUID | PredictorNode], the list of individual predictors to use in the graph training_data: Optional[list[DataSource]] Optional sources of training data shared by all predictors in the graph. diff --git a/src/citrine/informatics/predictors/mean_property_predictor.py b/src/citrine/informatics/predictors/mean_property_predictor.py index 4b6821688..ee0282ac8 100644 --- a/src/citrine/informatics/predictors/mean_property_predictor.py +++ b/src/citrine/informatics/predictors/mean_property_predictor.py @@ -28,7 +28,7 @@ class MeanPropertyPredictor(Resource["MeanPropertyPredictor"], PredictorNode): Description of the predictor input_descriptor: FormulationDescriptor Descriptor that represents the input formulation - properties: list[Union[RealDescriptor, CategoricalDescriptor]] + properties: list[RealDescriptor | CategoricalDescriptor] List of real or categorical descriptors to featurize p: float Power of the component-weighted mean. @@ -44,7 +44,7 @@ class MeanPropertyPredictor(Resource["MeanPropertyPredictor"], PredictorNode): label: Optional[str] Only ingredients with this label are counted when calculating the component-weighted mean. If ``None`` (default) all ingredients will be counted. - default_properties: Optional[dict[str, Union[str, float]]] + default_properties: Optional[dict[str, str | float]] Default values to use for imputed properties. Defaults are specified as a map from descriptor key to its default value. If not specified and ``impute_properties == True`` the average over the entire dataset @@ -79,19 +79,19 @@ def __init__(self, *, description: str, input_descriptor: FormulationDescriptor, - properties: list[Union[RealDescriptor, CategoricalDescriptor]], + properties: list[RealDescriptor | CategoricalDescriptor], p: float, impute_properties: bool, label: Optional[str] = None, - default_properties: Optional[dict[str, Union[str, float]]] = None, + default_properties: Optional[dict[str, str | float]] = None): self.name: str = name self.description: str = description self.input_descriptor: FormulationDescriptor = input_descriptor - self.properties: list[Union[RealDescriptor, CategoricalDescriptor]] = properties + self.properties: list[RealDescriptor | CategoricalDescriptor] = properties self.p: float = p self.impute_properties: bool = impute_properties self.label: Optional[str] = label - self.default_properties: Optional[dict[str, Union[str, float]]] = default_properties + self.default_properties: Optional[dict[str, str | float]] = default_properties def __str__(self): return ''.format(self.name) diff --git a/src/citrine/informatics/workflows/analysis_workflow.py b/src/citrine/informatics/workflows/analysis_workflow.py index e46543f9e..227477e76 100644 --- a/src/citrine/informatics/workflows/analysis_workflow.py +++ b/src/citrine/informatics/workflows/analysis_workflow.py @@ -36,7 +36,7 @@ def __init__(self, *, name: str, description: str, - snapshot_id: Optional[Union[UUID, str]] = None, + snapshot_id: Optional[UUID | str] = None, plots: list[dict] = []): self.name = name self.description = description @@ -66,7 +66,7 @@ class AnalysisWorkflowUpdatePayload(Resource['AnalysisWorkflowUpdatePayload']): description = properties.Optional(properties.String, 'description') def __init__(self, - uid: Union[UUID, str], + uid: UUID | str, *, name: Optional[str] = None, description: Optional[str] = None): diff --git a/src/citrine/informatics/workflows/design_workflow.py b/src/citrine/informatics/workflows/design_workflow.py index a63848fe4..3dfb9816f 100644 --- a/src/citrine/informatics/workflows/design_workflow.py +++ b/src/citrine/informatics/workflows/design_workflow.py @@ -22,7 +22,7 @@ class DesignWorkflow(Resource['DesignWorkflow'], Workflow, AIResourceMetadata): the UUID corresponding to the design space to use predictor_id: Optional[UUID] the UUID corresponding to the predictor to use - predictor_version: Optional[Union[int, str]] + predictor_version: Optional[int | str] the version of the predictor to use description: Optional[str] a description of the workflow @@ -51,7 +51,7 @@ def __init__(self, *, design_space_id: Optional[UUID] = None, predictor_id: Optional[UUID] = None, - predictor_version: Optional[Union[int, str]] = None, + predictor_version: Optional[int | str] = None, data_source: Optional[DataSource] = None, description: Optional[str] = None): self.name = name diff --git a/src/citrine/jobs/job.py b/src/citrine/jobs/job.py index 62bfd0974..16bae0f0a 100644 --- a/src/citrine/jobs/job.py +++ b/src/citrine/jobs/job.py @@ -52,7 +52,7 @@ class TaskNode(Resource['TaskNode']): """:str: if a task has failed, the failure reason will be in this parameter""" @property - def status(self) -> Union[JobStatus, str]: + def status(self) -> JobStatus | str: """The last reported status of this particular task.""" if resolved := JobStatus.from_str(self._status, exception=False): return resolved @@ -60,7 +60,7 @@ def status(self) -> Union[JobStatus, str]: return self._status @status.setter - def status(self, value: Union[JobStatus, str]) -> None: + def status(self, value: JobStatus | str) -> None: if JobStatus.from_str(value, exception=False) is None: warn( f"{value} is not a recognized JobStatus; this will become an error as of v4.0.0.", @@ -85,7 +85,7 @@ class JobStatusResponse(Resource['JobStatusResponse']): """:Optional[dict[str, str]]: job output properties and results""" @property - def status(self) -> Union[JobStatus, str]: + def status(self) -> JobStatus | str: """The last reported status of this particular task.""" if resolved := JobStatus.from_str(self._status, exception=False): return resolved @@ -93,7 +93,7 @@ def status(self) -> Union[JobStatus, str]: return self._status @status.setter - def status(self, value: Union[JobStatus, str]) -> None: + def status(self, value: JobStatus | str) -> None: if resolved := JobStatus.from_str(value, exception=False): if resolved not in [JobStatus.RUNNING, JobStatus.SUCCESS, JobStatus.FAILURE]: warn( @@ -110,9 +110,9 @@ def status(self, value: Union[JobStatus, str]) -> None: def _poll_for_job_completion(session: Session, - job: Union[JobSubmissionResponse, UUID, str], + job: JobSubmissionResponse | UUID | str, *, - team_id: Union[UUID, str], + team_id: UUID | str, timeout: float = 2 * 60, polling_delay: float = 2.0, raise_errors: bool = True, diff --git a/src/citrine/jobs/waiting.py b/src/citrine/jobs/waiting.py index 78359f438..bea8bfbcf 100644 --- a/src/citrine/jobs/waiting.py +++ b/src/citrine/jobs/waiting.py @@ -10,6 +10,12 @@ from citrine.informatics.executions import PredictorEvaluation +ExecutionType = PredictorEvaluation \ + | DesignExecution \ + | GenerativeDesignExecution \ + | SampleDesignSpaceExecution + + class ConditionTimeoutError(RuntimeError): """Error that is raised when timeout is reached but the checked condition is still False.""" @@ -129,34 +135,18 @@ def wait_while_validating( def wait_while_executing( *, - collection: Union[ - Collection[PredictorEvaluation], - Collection[DesignExecution], - Collection[GenerativeDesignExecution], - Collection[SampleDesignSpaceExecution] - ], - execution: Union[ - PredictorEvaluation, - DesignExecution, - GenerativeDesignExecution, - SampleDesignSpaceExecution - ], + collection: Collection[ExecutionType], + execution: ExecutionType, print_status_info: bool = False, timeout: float = 1800.0, - interval: float = 3.0, -) -> Union[ - PredictorEvaluation, - DesignExecution, - GenerativeDesignExecution, - SampleDesignSpaceExecution, -]: + interval: float = 3.0 +) -> ExecutionType: """ Wait until execution is finished. Parameters ---------- - execution : Union[PredictorEvaluation, DesignExecution, GenerativeDesignExecution, - SampleDesignSpaceExecution] + execution : ExecutionType an execution to monitor print_status_info : bool, optional Whether to print status info, by default False @@ -164,16 +154,11 @@ def wait_while_executing( Maximum time spent inquiring in seconds, by default 1800.0 interval : float, optional Inquiry interval in seconds, by default 3.0 - collection : Union[Collection[PredictorEvaluationExecution], - Collection[DesignExecution], - Collection[GenerativeDesignExecution], - Collection[SampleDesignSpaceExecution]] - Collection containing executions + collection : Collection[ExecutionType] Returns ------- - Union[PredictorEvaluationExecution, DesignExecution, GenerativeDesignExecution, - SampleDesignSpaceExecution] + ExectutionType the updated execution after it has finished executing diff --git a/src/citrine/resources/analysis_workflow.py b/src/citrine/resources/analysis_workflow.py index ec9e8c794..293892509 100644 --- a/src/citrine/resources/analysis_workflow.py +++ b/src/citrine/resources/analysis_workflow.py @@ -65,20 +65,20 @@ def _list_with_params(self, *, per_page: int, **kwargs) -> Iterator[AnalysisWork collection_builder=self._build_collection_elements, per_page=per_page) - def archive(self, uid: Union[UUID, str]) -> AnalysisWorkflow: + def archive(self, uid: UUID | str) -> AnalysisWorkflow: """Archive an analysis workflow, hiding it from default listings.""" url = self._get_path(uid=uid, action="archive") entity = self.session.put_resource(url, {}, version=self._api_version) return self.build(entity) - def restore(self, uid: Union[UUID, str]) -> AnalysisWorkflow: + def restore(self, uid: UUID | str) -> AnalysisWorkflow: """Restore an analysis workflow, showing it in default listings.""" url = self._get_path(uid=uid, action="restore") entity = self.session.put_resource(url, {}, version=self._api_version) return self.build(entity) def update(self, - uid: Union[UUID, str], + uid: UUID | str, *, name: Optional[str] = None, description: Optional[str] = None) -> AnalysisWorkflow: @@ -86,12 +86,12 @@ def update(self, aw_update = AnalysisWorkflowUpdatePayload(uid=uid, name=name, description=description) return super().update(aw_update) - def rebuild(self, uid: Union[UUID, str]) -> AnalysisWorkflow: + def rebuild(self, uid: UUID | str) -> AnalysisWorkflow: """Rebuild the data source underlying the analysis workflow.""" url = self._get_path(uid=uid, action=("query", "rerun")) entity = self.session.put_resource(url, {}, version=self._api_version) return self.build(entity) - def delete(self, uid: Union[UUID, str]): + def delete(self, uid: UUID | str): """Analysis workflows cannot be deleted at this time.""" raise NotImplementedError("Deleting Analysis Workflows is not currently supported.") diff --git a/src/citrine/resources/branch.py b/src/citrine/resources/branch.py index 4d9099304..d7f53cc91 100644 --- a/src/citrine/resources/branch.py +++ b/src/citrine/resources/branch.py @@ -106,8 +106,8 @@ def build(self, data: dict) -> Branch: def get(self, *, - root_id: Union[UUID, str], - version: Optional[Union[int, str]] = LATEST_VER) -> Branch: + root_id: UUID | str, + version: Optional[int | str] = LATEST_VER) -> Branch: """ Retrieve a branch by its root ID and, optionally, its version number. @@ -115,10 +115,10 @@ def get(self, Parameters --------- - root_id: Union[UUID, str] + root_id: UUID | str Unique identifier of the branch root - version: Union[int, str], optional + version: int | str, optional The version of the branch to retrieve. If provided, must either be a positive integer, or "latest". Defaults to "latest". @@ -141,13 +141,13 @@ def get(self, params=params ) - def get_by_version_id(self, *, version_id: Union[UUID, str]) -> Branch: + def get_by_version_id(self, *, version_id: UUID | str) -> Branch: """ Given a branch version ID, retrieve the branch. Parameters --------- - version_id: Union[UUID, str] + version_id: UUID | str Unique ID of the branch version Returns @@ -226,17 +226,17 @@ def _list_with_params(self, *, per_page, **kwargs): def archive(self, *, - root_id: Union[UUID, str], - version: Optional[Union[int, str]] = LATEST_VER): + root_id: UUID | str, + version: Optional[int | str] = LATEST_VER): """ Archive a branch. Parameters ---------- - root_id: Union[UUID, str] + root_id: UUID | str Unique ID of the branch root - version: Union[int, str], optional + version: int | str, optional The version of the branch. If provided, must either be a positive integer, or "latest". Defaults to "latest". @@ -251,17 +251,17 @@ def archive(self, def restore(self, *, - root_id: Union[UUID, str], - version: Optional[Union[int, str]] = LATEST_VER): + root_id: UUID | str, + version: Optional[int | str] = LATEST_VER): """ Restore an archived branch. Parameters ---------- - root_id: Union[UUID, str] + root_id: UUID | str Unique ID of the branch root - version: Union[int, str], optional + version: int | str, optional The version of the branch. If provided, must either be a positive integer, or "latest". Defaults to "latest". @@ -276,8 +276,8 @@ def restore(self, def update_data(self, *, - root_id: Union[UUID, str], - version: Optional[Union[int, str]] = LATEST_VER, + root_id: UUID | str, + version: Optional[int | str] = LATEST_VER, use_existing: bool = True, retrain_models: bool = False) -> Optional[Branch]: """ @@ -288,10 +288,10 @@ def update_data(self, Parameters ---------- - root_id: Union[UUID, str] + root_id: UUID | str Unique ID of the branch root - version: Union[int, str], optional + version: int | str, optional The version of the branch. If provided, must either be a positive integer, or "latest". Defaults to "latest". @@ -328,17 +328,17 @@ def update_data(self, def data_updates(self, *, - root_id: Union[UUID, str], - version: Optional[Union[int, str]] = LATEST_VER) -> BranchDataUpdate: + root_id: UUID | str, + version: Optional[int | str] = LATEST_VER) -> BranchDataUpdate: """ Get data updates for a branch. Parameters ---------- - root_id: Union[UUID, str] + root_id: UUID | str Unique ID of the branch root - version: Union[int, str], optional + version: int | str, optional The version of the branch. If provided, must either be a positive integer, or "latest". Defaults to "latest". @@ -357,7 +357,7 @@ def data_updates(self, return BranchDataUpdate.build(data) def next_version(self, - root_id: Union[UUID, str], + root_id: UUID | str, *, branch_instructions: NextBranchVersionRequest, retrain_models: bool = True): @@ -366,7 +366,7 @@ def next_version(self, Parameters ---------- - root_id: Union[UUID, str] + root_id: UUID | str Unique identifier of the branch root to advance to next version branch_instructions: NextBranchVersionRequest diff --git a/src/citrine/resources/data_concepts.py b/src/citrine/resources/data_concepts.py index 37cb2743d..48065e328 100644 --- a/src/citrine/resources/data_concepts.py +++ b/src/citrine/resources/data_concepts.py @@ -178,7 +178,7 @@ def _make_collection_dict(): DataConcepts.collection_dict[collection._individual_key] = collection -def _make_link_by_uid(gemd_object_rep: Union[str, UUID, BaseEntity, LinkByUID]) -> LinkByUID: +def _make_link_by_uid(gemd_object_rep: str | UUID | BaseEntity | LinkByUID) -> LinkByUID: if isinstance(gemd_object_rep, BaseEntity): return gemd_object_rep.to_link(CITRINE_SCOPE, allow_fallback=True) elif isinstance(gemd_object_rep, LinkByUID): @@ -435,7 +435,7 @@ def async_update(self, model: ResourceType, *, wait_for_response: bool = True, timeout: float = 2 * 60, polling_delay: float = 1.0, - return_model: bool = False) -> Optional[Union[UUID, ResourceType]]: + return_model: bool = False) -> Optional[UUID | ResourceType]: """ Update a particular element of the collection with data validation. @@ -548,13 +548,13 @@ def poll_async_update_job(self, job_id: UUID, *, timeout: float = 2 * 60, # That worked, nothing returned in this case return None - def get(self, uid: Union[UUID, str, LinkByUID, BaseEntity]) -> ResourceType: + def get(self, uid: UUID | str | LinkByUID | BaseEntity) -> ResourceType: """ Get an element of the collection by its id. Parameters ---------- - uid: Union[UUID, str, LinkByUID, BaseEntity] + uid: UUID | str | LinkByUID | BaseEntity A representation of the object (Citrine id, LinkByUID, or the object itself) Returns @@ -641,13 +641,13 @@ def list_by_tag(self, tag: str, *, per_page: int = 100) -> Iterator[ResourceType params=params) return (self.build(raw) for raw in raw_objects) - def delete(self, uid: Union[UUID, str, LinkByUID, BaseEntity], *, dry_run: bool = False): + def delete(self, uid: UUID | str | LinkByUID | BaseEntity, *, dry_run: bool = False): """ Delete an element of the collection by its id. Parameters ---------- - uid: Union[UUID, str, LinkByUID, BaseEntity] + uid: UUID | str | LinkByUID | BaseEntity A representation of the object (Citrine id, LinkByUID, or the object itself) dry_run: bool Whether to actually delete the item or run a dry run of the delete operation. @@ -660,7 +660,7 @@ def delete(self, uid: Union[UUID, str, LinkByUID, BaseEntity], *, dry_run: bool self.session.delete_resource(path, params=params) return Response(status_code=200) # delete succeeded - def _get_relation(self, relation: str, uid: Union[UUID, str, LinkByUID, BaseEntity], + def _get_relation(self, relation: str, uid: UUID | str | LinkByUID | BaseEntity, forward: bool = True, per_page: int = 100) -> Iterator[ResourceType]: """ Generic method for searching this collection by relation to another object. diff --git a/src/citrine/resources/data_objects.py b/src/citrine/resources/data_objects.py index c8df3e8fb..b976d58f8 100644 --- a/src/citrine/resources/data_objects.py +++ b/src/citrine/resources/data_objects.py @@ -41,7 +41,7 @@ class DataObjectCollection(DataConceptsCollection[DataObjectResourceType], ABC): def list_by_attribute_bounds( self, - attribute_bounds: dict[Union[AttributeTemplate, LinkByUID], BaseBounds], *, + attribute_bounds: dict[AttributeTemplate | LinkByUID, BaseBounds], *, forward: bool = True, per_page: int = 100) -> Iterator[DataObject]: """ Get all objects in the collection with attributes within certain bounds. @@ -53,8 +53,8 @@ def list_by_attribute_bounds( Parameters ---------- - attribute_bounds: dict[Union[AttributeTemplate, \ - :py:class:`LinkByUID `], \ + attribute_bounds: dict[AttributeTemplate | \ + :py:class:`LinkByUID `, \ :py:class:`BaseBounds `] A dictionary from attributes to the bounds on that attribute. Currently only real and integer bounds are supported. diff --git a/src/citrine/resources/dataset.py b/src/citrine/resources/dataset.py index 7b21861ed..c846dc312 100644 --- a/src/citrine/resources/dataset.py +++ b/src/citrine/resources/dataset.py @@ -266,13 +266,13 @@ def update(self, model: DataConcepts) -> DataConcepts: """Update a data model object using the appropriate collection.""" return self.gemd._collection_for(model).update(model) - def delete(self, uid: Union[UUID, str, LinkByUID, DataConcepts], *, dry_run=False): + def delete(self, uid: UUID | str | LinkByUID | DataConcepts, *, dry_run=False): """ Delete a GEMD resource from the appropriate collection. Parameters ---------- - uid: Union[UUID, str, LinkByUID, DataConcepts] + uid: UUID | str | LinkByUID | DataConcepts A representation of the resource to delete (Citrine id, LinkByUID, or the object) dry_run: bool Whether to actually delete the item or run a dry run of the delete operation. @@ -347,7 +347,7 @@ def delete_contents( def gemd_batch_delete( self, - id_list: list[Union[LinkByUID, UUID, str, BaseEntity]], + id_list: list[LinkByUID | UUID | str | BaseEntity], *, timeout: float = 2 * 60, polling_delay: float = 1.0 @@ -372,7 +372,7 @@ def gemd_batch_delete( Parameters ---------- - id_list: list[Union[LinkByUID, UUID, str, BaseEntity]] + id_list: list[LinkByUID | UUID | str | BaseEntity] A list of the IDs of data objects to be removed. They can be passed as a LinkByUID tuple, a UUID, a string, or the object itself. A UUID or string is assumed to be a Citrine ID, whereas a LinkByUID or diff --git a/src/citrine/resources/delete.py b/src/citrine/resources/delete.py index a2434392e..91ac99876 100644 --- a/src/citrine/resources/delete.py +++ b/src/citrine/resources/delete.py @@ -13,7 +13,7 @@ def _async_gemd_batch_delete( - id_list: list[Union[LinkByUID, UUID, str, BaseEntity]], + id_list: list[LinkByUID | UUID | str | BaseEntity], team_id: UUID, session: Session, dataset_id: Optional[UUID] = None, @@ -30,7 +30,7 @@ def _async_gemd_batch_delete( Parameters ---------- - id_list: list[Union[LinkByUID, UUID, str, BaseEntity]] + id_list: list[LinkByUID | UUID | str | BaseEntity] A list of the IDs of data objects to be removed. They can be passed as a LinkByUID tuple, a UUID, a string, or the object itself. A UUID or string is assumed to be a Citrine ID, whereas a LinkByUID or diff --git a/src/citrine/resources/descriptors.py b/src/citrine/resources/descriptors.py index 56049fc4c..c13952b5c 100644 --- a/src/citrine/resources/descriptors.py +++ b/src/citrine/resources/descriptors.py @@ -16,14 +16,14 @@ def __init__(self, project_id: UUID, session: Session): self.project_id = project_id self.session: Session = session - def from_predictor_responses(self, *, predictor: Union[GraphPredictor, PredictorNode], + def from_predictor_responses(self, *, predictor: GraphPredictor | PredictorNode, inputs: list[Descriptor]) -> list[Descriptor]: """ Get responses for a predictor, given an input space. Parameters ---------- - predictor : Union[Predictor, PredictorNode] + predictor : Predictor | PredictorNode Either a single predictor node or full predictor whose available responses are to be computed. inputs : list[Descriptor] diff --git a/src/citrine/resources/design_execution.py b/src/citrine/resources/design_execution.py index 7bf87fa77..77bacddb3 100644 --- a/src/citrine/resources/design_execution.py +++ b/src/citrine/resources/design_execution.py @@ -47,12 +47,12 @@ def update(self, model: executions.DesignExecution) -> executions.DesignExecutio """Cannot update an execution.""" raise NotImplementedError("Cannot update a DesignExecution.") - def archive(self, uid: Union[UUID, str]): + def archive(self, uid: UUID | str): """Archive a Design Workflow execution. Parameters ---------- - uid: Union[UUID, str] + uid: UUID | str Unique identifier of the execution to archive """ @@ -95,7 +95,7 @@ def list(self, *, per_page: int = 100) -> Iterator[executions.DesignExecution]: collection_builder=self._build_collection_elements, per_page=per_page) - def delete(self, uid: Union[UUID, str]) -> Response: + def delete(self, uid: UUID | str) -> Response: """Design Workflow Executions cannot be deleted or archived.""" raise NotImplementedError( "Design Executions cannot be deleted") diff --git a/src/citrine/resources/design_space.py b/src/citrine/resources/design_space.py index bbef4cf22..c38c0eaaa 100644 --- a/src/citrine/resources/design_space.py +++ b/src/citrine/resources/design_space.py @@ -63,17 +63,17 @@ def update(self, design_space: TopLevelDesignSpace) -> TopLevelDesignSpace: else: return self._validate(updated_ds.uid) - def _validate(self, uid: Union[UUID, str]) -> TopLevelDesignSpace: + def _validate(self, uid: UUID | str) -> TopLevelDesignSpace: path = self._get_path(uid, action="validate") entity = self.session.put_resource(path, {}, version=self._api_version) return self.build(entity) - def archive(self, uid: Union[UUID, str]) -> TopLevelDesignSpace: + def archive(self, uid: UUID | str) -> TopLevelDesignSpace: """Archiving a design space removes it from view, but is not a hard delete. Parameters ---------- - uid: Union[UUID, str] + uid: UUID | str Unique identifier of the design space to archive """ @@ -81,12 +81,12 @@ def archive(self, uid: Union[UUID, str]) -> TopLevelDesignSpace: entity = self.session.put_resource(url, {}, version=self._api_version) return self.build(entity) - def restore(self, uid: Union[UUID, str]) -> TopLevelDesignSpace: + def restore(self, uid: UUID | str) -> TopLevelDesignSpace: """Restore an archived design space. Parameters ---------- - uid: Union[UUID, str] + uid: UUID | str Unique identifier of the design space to restore """ @@ -118,8 +118,8 @@ def list_archived(self, *, per_page: int = 20) -> Iterable[TopLevelDesignSpace]: def create_default(self, *, - predictor_id: Union[UUID, str], - predictor_version: Optional[Union[int, str]] = None, + predictor_id: UUID | str, + predictor_version: Optional[int | str] = None, mode: DefaultDesignSpaceMode = DefaultDesignSpaceMode.ATTRIBUTE, include_ingredient_fraction_constraints: bool = False, include_label_fraction_constraints: bool = False, @@ -143,7 +143,7 @@ def create_default(self, predictor_id: UUID UUID of the predictor used to construct the design space - predictor_version: Optional[Union[int, str]] + predictor_version: Optional[int | str] Version of the predictor used to construct the design space mode: DefaultDesignSpaceMode @@ -190,10 +190,10 @@ def create_default(self, def convert_to_hierarchical( self, - uid: Union[UUID, str], + uid: UUID | str, *, - predictor_id: Union[UUID, str], - predictor_version: Optional[Union[int, str]] = None + predictor_id: UUID | str, + predictor_version: Optional[int | str] = None ) -> HierarchicalDesignSpace: """Convert an existing ProductDesignSpace into an equivalent HierarchicalDesignSpace. @@ -205,11 +205,11 @@ def convert_to_hierarchical( Parameters ---------- - uid: Union[str, UUID] + uid: str | UUID UUID of the existing product design space to convert to a hierarchical version - predictor_id: Union[UUID, str] + predictor_id: UUID | str UUID of a predictor associated with the design space. - predictor_version: Optional[Union[int, str]] + predictor_version: Optional[int | str] Version of the predictor to use. Defaults to the most recent version. Returns @@ -231,7 +231,7 @@ def convert_to_hierarchical( data = self.session.post_resource(path, json=payload, version=self._api_version) return HierarchicalDesignSpace.build(TopLevelDesignSpace.wrap_instance(data["instance"])) - def delete(self, uid: Union[UUID, str]): + def delete(self, uid: UUID | str): """Design Spaces cannot be deleted at this time.""" msg = "Design Spaces cannot be deleted at this time. Use 'archive' instead." raise NotImplementedError(msg) diff --git a/src/citrine/resources/design_workflow.py b/src/citrine/resources/design_workflow.py index 6f37ba563..a2963381b 100644 --- a/src/citrine/resources/design_workflow.py +++ b/src/citrine/resources/design_workflow.py @@ -124,31 +124,31 @@ def update(self, model: DesignWorkflow) -> DesignWorkflow: return super().update(model) - def archive(self, uid: Union[UUID, str]): + def archive(self, uid: UUID | str): """Archive a design workflow. Parameters ---------- - uid: Union[UUID, str] + uid: UUID | str Unique identifier of the workflow to archive """ url = self._get_path(uid=uid, action="archive") self.session.put_resource(url, {}, version=self._api_version) - def restore(self, uid: Union[UUID, str]): + def restore(self, uid: UUID | str): """Restore an archived design workflow. Parameters ---------- - uid: Union[UUID, str] + uid: UUID | str Unique identifier of the workflow to restore """ url = self._get_path(uid=uid, action="restore") self.session.put_resource(url, {}, version=self._api_version) - def delete(self, uid: Union[UUID, str]) -> Response: + def delete(self, uid: UUID | str) -> Response: """Design Workflows cannot be deleted; they can be archived instead.""" raise NotImplementedError( "Design Workflows cannot be deleted; they can be archived instead.") diff --git a/src/citrine/resources/experiment_datasource.py b/src/citrine/resources/experiment_datasource.py index ab6208772..adf075a4f 100644 --- a/src/citrine/resources/experiment_datasource.py +++ b/src/citrine/resources/experiment_datasource.py @@ -106,8 +106,8 @@ def build(self, data: dict) -> ExperimentDataSource: def list(self, *, per_page: int = 100, - branch_version_id: Optional[Union[UUID, str]] = None, - version: Optional[Union[int, str]] = None) -> Iterator[ExperimentDataSource]: + branch_version_id: Optional[UUID | str] = None, + version: Optional[int | str] = None) -> Iterator[ExperimentDataSource]: """Paginate over the experiment data sources. Parameters @@ -118,7 +118,7 @@ def list(self, *, is specified it limits the maximum number of elements in the response. branch_version_id: UUID, optional Filter the list by the branch version ID. - version: Union[int, str], optional + version: int | str, optional Filter the list by the data source version. Also accepts "latest". Returns @@ -138,7 +138,7 @@ def list(self, *, collection_builder=self._build_collection_elements, per_page=per_page) - def read(self, datasource: Union[ExperimentDataSource, UUID, str]): + def read(self, datasource: ExperimentDataSource | UUID | str): """Reads the provided experiment data source into a CSV. If a UUID or str is provided, it's first retrieved from the platform. diff --git a/src/citrine/resources/file_link.py b/src/citrine/resources/file_link.py index ba0947a0d..b69214a14 100644 --- a/src/citrine/resources/file_link.py +++ b/src/citrine/resources/file_link.py @@ -164,7 +164,7 @@ def __init__(self, filename: str, url: str): self.typ = FileLink.typ @classmethod - def from_path(cls, path: Union[str, Path]) -> "FileLink": + def from_path(cls, path: str | Path) -> "FileLink": """Construct a FileLink from a local Path.""" path = Path(path) # In case it was a string return cls(filename=path.name, url=path.expanduser().absolute().as_uri()) @@ -202,11 +202,11 @@ def __init__(self, *, session: Session, dataset_id: UUID, team_id: UUID): self.team_id = team_id def _get_path(self, - uid: Optional[Union[UUID, str]] = None, + uid: Optional[UUID | str] = None, *, ignore_dataset: Optional[bool] = False, - version: Union[str, UUID] = None, - action: Union[str, Sequence[str]] = [], + version: str | UUID = None, + action: str | Sequence[str] = [], query_terms: dict[str, str] = {},) -> str: """Build the path for taking an action with a particular file version.""" if version is not None: @@ -230,15 +230,15 @@ def build(self, data: dict) -> FileLink: return FileLink.build(data) def get(self, - uid: Union[UUID, str], + uid: UUID | str, *, - version: Optional[Union[UUID, str, int]] = None) -> FileLink: + version: Optional[UUID | str | int] = None) -> FileLink: """ Retrieve an on-platform FileLink from its filename or file uuid. Parameters ---------- - uid: Union[UUID, str] + uid: UUID | str A representation of the FileLink (Citrine id or file name) version: Optional[UUID, str, int] The version, as a UUID or str(UUID) of the version_id or an int or @@ -293,7 +293,7 @@ def get(self, return file - def upload(self, *, file_path: Union[str, Path], dest_name: str = None) -> FileLink: + def upload(self, *, file_path: str | Path, dest_name: str = None) -> FileLink: """ Uploads a file to the dataset. @@ -581,7 +581,7 @@ def _complete_upload(self, dest_name: str, uploader: _Uploader): return self.build({"filename": dest_name, "id": file_id, "version": version_id}) - def download(self, *, file_link: Union[str, UUID, FileLink], local_path: Union[str, Path]): + def download(self, *, file_link: str | UUID | FileLink, local_path: str | Path): """ Download the file associated with a given FileLink to the local computer. @@ -610,7 +610,7 @@ def download(self, *, file_link: Union[str, UUID, FileLink], local_path: Union[s response_content = self.read(file_link=file_link) write_file_locally(response_content, final_path) - def read(self, *, file_link: Union[str, UUID, FileLink]) -> bytes: + def read(self, *, file_link: str | UUID | FileLink) -> bytes: """ Read the file associated with a given FileLink. @@ -648,7 +648,7 @@ def read(self, *, file_link: Union[str, UUID, FileLink]) -> bytes: return download_response.content def ingest(self, - files: Iterable[Union[FileLink, Path, str]], + files: Iterable[FileLink | Path | str], *, upload: bool = False, raise_errors: bool = True, @@ -657,7 +657,7 @@ def ingest(self, delete_templates: bool = True, timeout: float = None, polling_delay: Optional[float] = None, - project: Optional[Union["Project", UUID, str]] = None, # noqa: F821 + project: Optional["Project | UUID | str"] = None, # noqa: F821 ) -> "IngestionStatus": # noqa: F821 """ [ALPHA] Ingest a set of CSVs and/or Excel Workbooks formatted per the gemd-ingest protocol. @@ -709,7 +709,7 @@ def ingest(self, if build_table and project is None: raise ValueError("Building a table requires a target project.") - def resolve_with_local(candidate: Union[FileLink, Path, str]) -> FileLink: + def resolve_with_local(candidate: FileLink | Path | str) -> FileLink: """Resolve Path, str or FileLink to an absolute reference.""" if upload: if not isinstance(candidate, GEMDFileLink): @@ -777,7 +777,7 @@ def delete(self, file_link: FileLink): data = self.session.delete_resource(self._get_path(file_id)) return Response(body=data) - def _resolve_file_link(self, identifier: Union[str, UUID, FileLink]) -> FileLink: + def _resolve_file_link(self, identifier: str | UUID | FileLink) -> FileLink: """Generate the FileLink object referenced by the passed argument.""" if isinstance(identifier, GEMDFileLink): if not isinstance(identifier, FileLink): # Up-convert type with existing info diff --git a/src/citrine/resources/gemd_resource.py b/src/citrine/resources/gemd_resource.py index 1b1dfa9dc..86dbd85e4 100644 --- a/src/citrine/resources/gemd_resource.py +++ b/src/citrine/resources/gemd_resource.py @@ -173,7 +173,7 @@ def register_all(self, def batch_delete( self, - id_list: list[Union[LinkByUID, UUID, str, BaseEntity]], + id_list: list[LinkByUID | UUID | str | BaseEntity], *, timeout: float = 2 * 60, polling_delay: float = 1.0 @@ -198,7 +198,7 @@ def batch_delete( Parameters ---------- - id_list: list[Union[LinkByUID, UUID, str, BaseEntity]] + id_list: list[LinkByUID | UUID | str | BaseEntity] A list of the IDs of data objects to be removed. They can be passed as a LinkByUID tuple, a UUID, a string, or the object itself. A UUID or string is assumed to be a Citrine ID, whereas a LinkByUID or diff --git a/src/citrine/resources/gemtables.py b/src/citrine/resources/gemtables.py index c7288b126..18cb8d851 100644 --- a/src/citrine/resources/gemtables.py +++ b/src/citrine/resources/gemtables.py @@ -101,7 +101,7 @@ def __init__(self, *, team_id: UUID, project_id: UUID, session: Session): self.session: Session = session self.team_id = team_id - def get(self, uid: Union[UUID, str], *, version: Optional[int] = None) -> GemTable: + def get(self, uid: UUID | str, *, version: Optional[int] = None) -> GemTable: """Get a Table's metadata. If no version is specified, get the most recent version.""" if version is not None: path = self._get_path(uid, action=["versions", version]) @@ -175,8 +175,8 @@ def _build_versions(collection: Iterable[dict]) -> Iterable[GemTable]: # Don't deduplicate on uid since uids are shared between versions _fetch_versions, _build_versions, per_page, deduplicate=False) - def initiate_build(self, config: Union[TableConfig, str, UUID], *, - version: Union[str, UUID] = None) -> JobSubmissionResponse: + def initiate_build(self, config: TableConfig | str | UUID, *, + version: str | UUID = None) -> JobSubmissionResponse: """ Initiates tables build with provided config. @@ -228,7 +228,7 @@ def initiate_build(self, config: Union[TableConfig, str, UUID], *, ) return submission - def get_by_build_job(self, job: Union[JobSubmissionResponse, UUID], *, + def get_by_build_job(self, job: JobSubmissionResponse | UUID, *, timeout: float = 15 * 60) -> GemTable: """ Gets table by build job, waiting for it to complete if necessary. @@ -269,8 +269,8 @@ def get_by_build_job(self, job: Union[JobSubmissionResponse, UUID], *, logger.warning('\n\t'.join(warn_lines)) return self.get(table_id, version=table_version) - def build_from_config(self, config: Union[TableConfig, str, UUID], *, - version: Union[str, int] = None, + def build_from_config(self, config: TableConfig | str | UUID, *, + version: str | int = None, timeout: float = 15 * 60) -> GemTable: """ Builds table from table config, waiting for build job to complete. @@ -314,11 +314,11 @@ def update(self, model: GemTable) -> GemTable: "re-build the table, especially if new GEMD data are available." ) - def delete(self, uid: Union[UUID, str]): + def delete(self, uid: UUID | str): """Tables cannot be deleted at this time.""" raise NotImplementedError("Tables cannot be deleted at this time.") - table_type = Union[GemTable, UUID, str] + table_type = GemTable | UUID | str def _read_raw(self, table: table_type) -> requests.Response: """ diff --git a/src/citrine/resources/generative_design_execution.py b/src/citrine/resources/generative_design_execution.py index 8ec82a481..06ed4b813 100644 --- a/src/citrine/resources/generative_design_execution.py +++ b/src/citrine/resources/generative_design_execution.py @@ -69,7 +69,7 @@ def list(self, *, per_page: int = 10) -> Iterator[GenerativeDesignExecution]: collection_builder=self._build_collection_elements, per_page=per_page) - def delete(self, uid: Union[UUID, str]) -> Response: + def delete(self, uid: UUID | str) -> Response: """Generative Design Executions cannot be deleted or archived.""" raise NotImplementedError( "Generative Design Executions cannot be deleted" diff --git a/src/citrine/resources/ingestion.py b/src/citrine/resources/ingestion.py index 4160ab3f0..fca1ef0b8 100644 --- a/src/citrine/resources/ingestion.py +++ b/src/citrine/resources/ingestion.py @@ -194,7 +194,7 @@ class Ingestion(Resource['Ingestion']): def build_objects(self, *, build_table: bool = False, - project: Optional[Union["Project", UUID, str]] = None, # noqa: F821 + project: Optional["Project | UUID | str"] = None, # noqa: F821 delete_dataset_contents: bool = False, delete_templates: bool = True, timeout: float = None, @@ -251,7 +251,7 @@ def build_objects(self, def build_objects_async(self, *, build_table: bool = False, - project: Optional[Union["Project", UUID, str]] = None, # noqa: F821 + project: Optional["Project | UUID | str"] = None, # noqa: F821 delete_dataset_contents: bool = False, delete_templates: bool = True) -> JobSubmissionResponse: """ @@ -386,7 +386,7 @@ def __init__(self, errors: Iterable[IngestionErrorTrace]): def build_objects(self, *, build_table: bool = False, - project: Optional[Union["Project", UUID, str]] = None, # noqa: F821 + project: Optional["Project | UUID | str"] = None, # noqa: F821 delete_dataset_contents: bool = False, delete_templates: bool = True, timeout: float = None, @@ -398,7 +398,7 @@ def build_objects(self, def build_objects_async(self, *, build_table: bool = False, - project: Optional[Union["Project", UUID, str]] = None, # noqa: F821 + project: Optional["Project | UUID | str"] = None, # noqa: F821 delete_dataset_contents: bool = False, delete_templates: bool = True) -> JobSubmissionResponse: """[ALPHA] Satisfy the required interface for a failed ingestion.""" diff --git a/src/citrine/resources/ingredient_run.py b/src/citrine/resources/ingredient_run.py index 9653848d4..6397fbce3 100644 --- a/src/citrine/resources/ingredient_run.py +++ b/src/citrine/resources/ingredient_run.py @@ -122,14 +122,14 @@ def get_type(cls) -> type[IngredientRun]: return IngredientRun def list_by_spec(self, - uid: Union[UUID, str, LinkByUID, GEMDIngredientSpec] + uid: UUID | str | LinkByUID | GEMDIngredientSpec ) -> Iterator[IngredientRun]: """ Get the ingredient runs using the specified ingredient spec. Parameters ---------- - uid: Union[UUID, str, LinkByUID, GEMDIngredientSpec] + uid: UUID | str | LinkByUID | GEMDIngredientSpec A representation of the ingredient spec whose ingredient run usages are to be located. Returns @@ -141,14 +141,14 @@ def list_by_spec(self, return self._get_relation(relation='ingredient-specs', uid=uid) def list_by_process(self, - uid: Union[UUID, str, LinkByUID, GEMDProcessRun] + uid: UUID | str | LinkByUID | GEMDProcessRun ) -> Iterator[IngredientRun]: """ Get ingredients to a process. Parameters ---------- - uid: Union[UUID, str, LinkByUID, GEMDProcessRun] + uid: UUID | str | LinkByUID | GEMDProcessRun A representation of the process whose ingredients are to be located. Returns @@ -160,14 +160,14 @@ def list_by_process(self, return self._get_relation(relation='process-runs', uid=uid) def list_by_material(self, - uid: Union[UUID, str, LinkByUID, GEMDMaterialRun] + uid: UUID | str | LinkByUID | GEMDMaterialRun ) -> Iterator[IngredientRun]: """ Get ingredients using the specified material. Parameters ---------- - uid: Union[UUID, str, LinkByUID, GEMDMaterialRun] + uid: UUID | str | LinkByUID | GEMDMaterialRun A representation of the material whose ingredient run usages are to be located. Returns diff --git a/src/citrine/resources/ingredient_spec.py b/src/citrine/resources/ingredient_spec.py index 7caf2538d..846fbd568 100644 --- a/src/citrine/resources/ingredient_spec.py +++ b/src/citrine/resources/ingredient_spec.py @@ -121,14 +121,14 @@ def get_type(cls) -> type[IngredientSpec]: return IngredientSpec def list_by_process(self, - uid: Union[UUID, str, LinkByUID, GEMDProcessSpec] + uid: UUID | str | LinkByUID | GEMDProcessSpec ) -> Iterator[IngredientSpec]: """ Get ingredients to a process. Parameters ---------- - uid: Union[UUID, str, LinkByUID, GEMDProcessSpec] + uid: UUID | str | LinkByUID | GEMDProcessSpec A representation of the process spec whose ingredients are to be located. Returns @@ -140,14 +140,14 @@ def list_by_process(self, return self._get_relation(relation='process-specs', uid=uid) def list_by_material(self, - uid: Union[UUID, str, LinkByUID, GEMDMaterialSpec] + uid: UUID | str | LinkByUID | GEMDMaterialSpec ) -> Iterator[IngredientSpec]: """ Get ingredients using the specified material. Parameters ---------- - uid: Union[UUID, str, LinkByUID, GEMDMaterialSpec] + uid: UUID | str | LinkByUID | GEMDMaterialSpec A representation of the material spec whose ingredient usages are to be located. Returns diff --git a/src/citrine/resources/material_run.py b/src/citrine/resources/material_run.py index e721b3bbc..8aa91f122 100644 --- a/src/citrine/resources/material_run.py +++ b/src/citrine/resources/material_run.py @@ -110,7 +110,7 @@ def get_type(cls) -> type[MaterialRun]: """Return the resource type in the collection.""" return MaterialRun - def get_history(self, id: Union[str, UUID, LinkByUID, MaterialRun]) -> MaterialRun: + def get_history(self, id: str | UUID | LinkByUID | MaterialRun) -> MaterialRun: """ Get the history associated with a terminal material. @@ -120,7 +120,7 @@ def get_history(self, id: Union[str, UUID, LinkByUID, MaterialRun]) -> MaterialR Parameters ---------- - id: Union[UUID, str, LinkByUID, MaterialRun] + id: UUID | str | LinkByUID | MaterialRun A representation of the material whose history is to be retrieved Returns @@ -162,14 +162,14 @@ def get_history(self, id: Union[str, UUID, LinkByUID, MaterialRun]) -> MaterialR return None def get_by_process(self, - uid: Union[UUID, str, LinkByUID, GEMDProcessRun] + uid: UUID | str | LinkByUID | GEMDProcessRun ) -> Optional[MaterialRun]: """ Get output material of a process. Parameters ---------- - uid: Union[UUID, str, LinkByUID, GEMDProcessRun] + uid: UUID | str | LinkByUID | GEMDProcessRun A representation of the process whose output is to be located. Returns @@ -184,14 +184,14 @@ def get_by_process(self, ) def list_by_spec(self, - uid: Union[UUID, str, LinkByUID, GEMDMaterialSpec] + uid: UUID | str | LinkByUID | GEMDMaterialSpec ) -> Iterator[MaterialRun]: """ Get the material runs using the specified material spec. Parameters ---------- - uid: Union[UUID, str, LinkByUID, GEMDMaterialSpec] + uid: UUID | str | LinkByUID | GEMDMaterialSpec A representation of the material spec whose material run usages are to be located. Returns @@ -203,14 +203,14 @@ def list_by_spec(self, return self._get_relation('material-specs', uid=uid) def list_by_template(self, - uid: Union[UUID, str, LinkByUID, GEMDMaterialTemplate] + uid: UUID | str | LinkByUID | GEMDMaterialTemplate ) -> Iterator[MaterialRun]: """ Get the material runs using the specified material template. Parameters ---------- - uid: Union[UUID, str, LinkByUID, GEMDMaterialTemplate] + uid: UUID | str | LinkByUID | GEMDMaterialTemplate A representation of the material template whose material run usages are to be located. Returns diff --git a/src/citrine/resources/material_spec.py b/src/citrine/resources/material_spec.py index 9b1f58bd4..57d689bc0 100644 --- a/src/citrine/resources/material_spec.py +++ b/src/citrine/resources/material_spec.py @@ -108,14 +108,14 @@ def get_type(cls) -> type[MaterialSpec]: return MaterialSpec def list_by_template(self, - uid: Union[UUID, str, LinkByUID, GEMDMaterialTemplate] + uid: UUID | str | LinkByUID | GEMDMaterialTemplate ) -> Iterator[MaterialSpec]: """ Get the material specs using the specified material template. Parameters ---------- - uid: Union[UUID, str, LinkByUID, GEMDMaterialTemplate] + uid: UUID | str | LinkByUID | GEMDMaterialTemplate A representation of the material template whose material spec usages are to be located. Returns @@ -127,14 +127,14 @@ def list_by_template(self, return self._get_relation('material-templates', uid=uid) def get_by_process(self, - uid: Union[UUID, str, LinkByUID, GEMDProcessSpec] + uid: UUID | str | LinkByUID | GEMDProcessSpec ) -> Optional[MaterialSpec]: """ Get output material of a process. Parameters ---------- - uid: Union[UUID, str, LinkByUID, GEMDProcessSpec] + uid: UUID | str | LinkByUID | GEMDProcessSpec A representation of the process whose output is to be located. Returns diff --git a/src/citrine/resources/material_template.py b/src/citrine/resources/material_template.py index 54b053391..79d9c3ecf 100644 --- a/src/citrine/resources/material_template.py +++ b/src/citrine/resources/material_template.py @@ -63,11 +63,11 @@ def __init__(self, name: str, *, uids: Optional[dict[str, str]] = None, - properties: Optional[Sequence[Union[PropertyTemplate, - LinkByUID, - Sequence[Union[PropertyTemplate, LinkByUID, - Optional[BaseBounds]]] - ]]] = None, + properties: Optional[Sequence[PropertyTemplate + | LinkByUID + | Sequence[PropertyTemplate | LinkByUID + | Optional[BaseBounds]] + ]] = None, description: Optional[str] = None, tags: Optional[list[str]] = None): # properties is a list, each element of which is a PropertyTemplate OR is a list with diff --git a/src/citrine/resources/measurement_run.py b/src/citrine/resources/measurement_run.py index 2c48a4dc9..36107c62a 100644 --- a/src/citrine/resources/measurement_run.py +++ b/src/citrine/resources/measurement_run.py @@ -113,14 +113,14 @@ def get_type(cls) -> type[MeasurementRun]: return MeasurementRun def list_by_spec(self, - uid: Union[UUID, str, LinkByUID, GEMDMeasurementSpec] + uid: UUID | str | LinkByUID | GEMDMeasurementSpec ) -> Iterator[MeasurementRun]: """ Get the measurement runs using the specified measurement spec. Parameters ---------- - uid: Union[UUID, str, LinkByUID, GEMDMeasurementSpec] + uid: UUID | str | LinkByUID | GEMDMeasurementSpec A representation of the measurement spec whose measurement run usages are to be located Returns @@ -132,14 +132,14 @@ def list_by_spec(self, return self._get_relation('measurement-specs', uid=uid) def list_by_material(self, - uid: Union[UUID, str, LinkByUID, GEMDMaterialRun] + uid: UUID | str | LinkByUID | GEMDMaterialRun ) -> Iterator[MeasurementRun]: """ Get measurements of the specified material. Parameters ---------- - uid: Union[UUID, str, LinkByUID, GEMDMaterialRun] + uid: UUID | str | LinkByUID | GEMDMaterialRun A representation of the material whose measurements are to be queried. Returns diff --git a/src/citrine/resources/measurement_spec.py b/src/citrine/resources/measurement_spec.py index a8972fd33..0f199eb67 100644 --- a/src/citrine/resources/measurement_spec.py +++ b/src/citrine/resources/measurement_spec.py @@ -96,14 +96,14 @@ def get_type(cls) -> type[MeasurementSpec]: return MeasurementSpec def list_by_template(self, - uid: Union[UUID, str, LinkByUID, GEMDMeasurementTemplate] + uid: UUID | str | LinkByUID | GEMDMeasurementTemplate ) -> Iterator[MeasurementSpec]: """ Get the measurement specs using the specified measurement template. Parameters ---------- - uid: Union[UUID, str, LinkByUID, GEMDMeasurementTemplate] + uid: UUID | str | LinkByUID | GEMDMeasurementTemplate A representation of of the measurement template whose measurement spec usages are to be located. diff --git a/src/citrine/resources/measurement_template.py b/src/citrine/resources/measurement_template.py index 218178a3f..d1b229135 100644 --- a/src/citrine/resources/measurement_template.py +++ b/src/citrine/resources/measurement_template.py @@ -101,21 +101,21 @@ def __init__(self, name: str, *, uids: Optional[dict[str, str]] = None, - properties: Optional[Sequence[Union[PropertyTemplate, - LinkByUID, - Sequence[Union[PropertyTemplate, LinkByUID, - Optional[BaseBounds]]] - ]]] = None, - conditions: Optional[Sequence[Union[ConditionTemplate, - LinkByUID, - Sequence[Union[ConditionTemplate, LinkByUID, - Optional[BaseBounds]]] - ]]] = None, - parameters: Optional[Sequence[Union[ParameterTemplate, - LinkByUID, - Sequence[Union[ParameterTemplate, LinkByUID, - Optional[BaseBounds]]] - ]]] = None, + properties: Optional[Sequence[PropertyTemplate + | LinkByUID + | Sequence[PropertyTemplate | LinkByUID + | BaseBounds] + ]] = None, + conditions: Optional[Sequence[ConditionTemplate + | LinkByUID + | Sequence[ConditionTemplate | LinkByUID + | Optional[BaseBounds]] + ]] = None, + parameters: Optional[Sequence[ParameterTemplate + | LinkByUID + | Sequence[ParameterTemplate | LinkByUID + | Optional[BaseBounds]] + ]] = None, description: Optional[str] = None, tags: Optional[list[str]] = None): if uids is None: diff --git a/src/citrine/resources/predictor.py b/src/citrine/resources/predictor.py index e905ca9f2..c394e23a2 100644 --- a/src/citrine/resources/predictor.py +++ b/src/citrine/resources/predictor.py @@ -84,8 +84,8 @@ def __init__(self, project_id: UUID, session: Session): self.session: Session = session def _construct_path(self, - uid: Union[UUID, str], - version: Optional[Union[int, str]] = None, + uid: UUID | str, + version: Optional[int | str] = None, action: str = None) -> str: path = self._path_template.format(project_id=self.project_id, uid=str(uid)) if version is not None: @@ -99,7 +99,7 @@ def _construct_path(self, path += f"/{action}" if action else "" return path - def _page_fetcher(self, *, uid: Union[UUID, str], **additional_params): + def _page_fetcher(self, *, uid: UUID | str, **additional_params): fetcher_params = { "path": self._construct_path(uid), "additional_params": additional_params @@ -114,18 +114,18 @@ def build(self, data: dict) -> GraphPredictor: return predictor def get(self, - uid: Union[UUID, str], + uid: UUID | str, *, - version: Union[int, str] = MOST_RECENT_VER) -> GraphPredictor: + version: int | str = MOST_RECENT_VER) -> GraphPredictor: path = self._construct_path(uid, version) entity = self.session.get_resource(path, version=self._api_version) return self.build(entity) def get_featurized_training_data( self, - uid: Union[UUID, str], + uid: UUID | str, *, - version: Union[int, str] = MOST_RECENT_VER + version: int | str = MOST_RECENT_VER ) -> list[HierarchicalDesignMaterial]: version_path = self._construct_path(uid, version) full_path = f"{version_path}/featurized-training-data" @@ -133,7 +133,7 @@ def get_featurized_training_data( return [HierarchicalDesignMaterial.build(x) for x in payload] def list(self, - uid: Union[UUID, str], + uid: UUID | str, *, per_page: int = 100) -> Iterable[GraphPredictor]: """List non-archived versions of the given predictor.""" @@ -143,7 +143,7 @@ def list(self, per_page=per_page) def list_archived(self, - uid: Union[UUID, str], + uid: UUID | str, *, per_page: int = 20) -> Iterable[GraphPredictor]: """List archived versions of the given predictor.""" @@ -153,41 +153,41 @@ def list_archived(self, per_page=per_page) def archive(self, - uid: Union[UUID, str], + uid: UUID | str, *, - version: Union[int, str] = MOST_RECENT_VER) -> GraphPredictor: + version: int | str = MOST_RECENT_VER) -> GraphPredictor: url = self._construct_path(uid, version, "archive") entity = self.session.put_resource(url, {}, version=self._api_version) return self.build(entity) def restore(self, - uid: Union[UUID, str], + uid: UUID | str, *, - version: Union[int, str] = MOST_RECENT_VER) -> GraphPredictor: + version: int | str = MOST_RECENT_VER) -> GraphPredictor: url = self._construct_path(uid, version, "restore") entity = self.session.put_resource(url, {}, version=self._api_version) return self.build(entity) def is_stale(self, - uid: Union[UUID, str], + uid: UUID | str, *, - version: Union[int, str] = MOST_RECENT_VER) -> bool: + version: int | str = MOST_RECENT_VER) -> bool: path = self._construct_path(uid, version, "is-stale") response = self.session.get_resource(path, version=self._api_version) return response["is_stale"] def retrain_stale(self, - uid: Union[UUID, str], + uid: UUID | str, *, - version: Union[int, str] = MOST_RECENT_VER) -> GraphPredictor: + version: int | str = MOST_RECENT_VER) -> GraphPredictor: path = self._construct_path(uid, version, "retrain-stale") entity = self.session.put_resource(path, {}, version=self._api_version) return self.build(entity) def rename(self, - uid: Union[UUID, str], + uid: UUID | str, *, - version: Union[int, str], + version: int | str, name: Optional[str] = None, description: Optional[str] = None ) -> GraphPredictor: @@ -196,7 +196,7 @@ def rename(self, entity = self.session.put_resource(path, json, version=self._api_version) return self.build(entity) - def delete(self, uid: Union[UUID, str], *, version: Union[int, str] = MOST_RECENT_VER): + def delete(self, uid: UUID | str, *, version: int | str = MOST_RECENT_VER): """Predictor versions cannot be deleted at this time.""" msg = "Predictor versions cannot be deleted. Use 'archive_version' instead." raise NotImplementedError(msg) @@ -231,9 +231,9 @@ def build(self, data: dict) -> GraphPredictor: return predictor def get(self, - uid: Union[UUID, str], + uid: UUID | str, *, - version: Union[int, str] = MOST_RECENT_VER) -> GraphPredictor: + version: int | str = MOST_RECENT_VER) -> GraphPredictor: """Get a predictor by ID and (optionally) version. If version is omitted, the most recent version will be retrieved. @@ -244,9 +244,9 @@ def get(self, def get_featurized_training_data( self, - uid: Union[UUID, str], + uid: UUID | str, *, - version: Union[int, str] = MOST_RECENT_VER + version: int | str = MOST_RECENT_VER ) -> list[HierarchicalDesignMaterial]: """Retrieve a list of featurized materials for a trained predictor. @@ -298,7 +298,7 @@ def update(self, predictor: GraphPredictor, *, train: bool = True) -> GraphPredi else: return self.train(updated_predictor.uid) - def train(self, uid: Union[UUID, str]) -> GraphPredictor: + def train(self, uid: UUID | str) -> GraphPredictor: """Train a predictor. If the predictor is not a draft, a new version will be created which is a copy of the @@ -312,57 +312,57 @@ def train(self, uid: Union[UUID, str]) -> GraphPredictor: def archive_version( self, - uid: Union[UUID, str], + uid: UUID | str, *, - version: Union[int, str] + version: int | str ) -> GraphPredictor: """Archive a predictor version.""" return self._versions_collection.archive(uid, version=version) def restore_version( self, - uid: Union[UUID, str], + uid: UUID | str, *, - version: Union[int, str] + version: int | str ) -> GraphPredictor: """Restore a predictor version.""" return self._versions_collection.restore(uid, version=version) - def archive_root(self, uid: Union[UUID, str]): + def archive_root(self, uid: UUID | str): """Archive a root predictor. - uid: Union[UUID, str] + uid: UUID | str Unique identifier of the predictor to archive. """ path = self._get_path(uid=uid, action="archive") self.session.put_resource(path, {}, version=self._api_version) - def restore_root(self, uid: Union[UUID, str]): + def restore_root(self, uid: UUID | str): """Restore an archived root predictor. - uid: Union[UUID, str] + uid: UUID | str Unique identifier of the predictor to restore. """ path = self._get_path(uid, action="restore") self.session.put_resource(path, {}, version=self._api_version) - def root_is_archived(self, uid: Union[UUID, str]) -> bool: + def root_is_archived(self, uid: UUID | str) -> bool: """Determine if the predictor root is archived. - uid: Union[UUID, str] + uid: UUID | str Unique identifier of the predictor to check. """ uid = str(uid) return any(uid == str(archived_pred.uid) for archived_pred in self.list_archived()) - def archive(self, uid: Union[UUID, str]): + def archive(self, uid: UUID | str): """[UNSUPPORTED] Use archive_root or archive_version instead.""" raise NotImplementedError("The archive() method is no longer supported. You most likely " "want archive_root(), or possibly archive_version().") - def restore(self, uid: Union[UUID, str]): + def restore(self, uid: UUID | str): """[UNSUPPORTED] Use restore_root or restore_version instead.""" raise NotImplementedError("The restore() method is no longer supported. You most likely " "want restore_root(), or possibly restore_version().") @@ -392,20 +392,20 @@ def list_archived(self, *, per_page: int = 20) -> Iterable[GraphPredictor]: return self._list_base(per_page=per_page, archived=True) def list_versions(self, - uid: Union[UUID, str] = None, + uid: UUID | str = None, *, per_page: int = 100) -> Iterable[GraphPredictor]: """List all non-archived versions of the given Predictor.""" return self._versions_collection.list(uid, per_page=per_page) def list_archived_versions(self, - uid: Union[UUID, str] = None, + uid: UUID | str = None, *, per_page: int = 20) -> Iterable[GraphPredictor]: """List all archived versions of the given Predictor.""" return self._versions_collection.list_archived(uid, per_page=per_page) - def check_for_update(self, uid: Union[UUID, str]) -> Optional[GraphPredictor]: + def check_for_update(self, uid: UUID | str) -> Optional[GraphPredictor]: """ Check if there are updates available for a predictor. @@ -417,7 +417,7 @@ def check_for_update(self, uid: Union[UUID, str]) -> Optional[GraphPredictor]: Parameters ---------- - uid: Union[UUID, str] + uid: UUID | str Unique identifier of the predictor to check Returns @@ -438,7 +438,7 @@ def check_for_update(self, uid: Union[UUID, str]) -> Optional[GraphPredictor]: def create_default(self, *, training_data: DataSource, - pattern: Union[str, AutoConfigureMode] = AutoConfigureMode.INFER, + pattern: str | AutoConfigureMode = AutoConfigureMode.INFER, prefer_valid: bool = True) -> GraphPredictor: """Create a default predictor for some training data. @@ -486,7 +486,7 @@ def create_default(self, def create_default_async(self, *, training_data: DataSource, - pattern: Union[str, AutoConfigureMode] = AutoConfigureMode.INFER, + pattern: str | AutoConfigureMode = AutoConfigureMode.INFER, prefer_valid: bool = True) -> AsyncDefaultPredictor: """Similar to PredictorCollection.create_default, except asynchronous. @@ -526,7 +526,7 @@ def create_default_async(self, @staticmethod def _create_default_payload(training_data: DataSource, - pattern: Union[str, AutoConfigureMode] = AutoConfigureMode.INFER, + pattern: str | AutoConfigureMode = AutoConfigureMode.INFER, prefer_valid: bool = True) -> dict: # Continue handling string pattern inputs pattern = AutoConfigureMode.from_str(pattern, exception=True) @@ -534,7 +534,7 @@ def _create_default_payload(training_data: DataSource, return {"data_source": training_data.dump(), "pattern": pattern, "prefer_valid": prefer_valid} - def get_default_async(self, *, task_id: Union[UUID, str]) -> AsyncDefaultPredictor: + def get_default_async(self, *, task_id: UUID | str) -> AsyncDefaultPredictor: """Get the current async default predictor generation result. The status field will indicate if it's INPROGRESS, SUCCEEDED, or FAILED. While INPROGRESS, @@ -546,7 +546,7 @@ def get_default_async(self, *, task_id: Union[UUID, str]) -> AsyncDefaultPredict data = self.session.get_resource(path, version=self._api_version) return AsyncDefaultPredictor.build(data) - def is_stale(self, uid: Union[UUID, str], *, version: Union[int, str]) -> bool: + def is_stale(self, uid: UUID | str, *, version: int | str) -> bool: """Returns True if a predictor is stale, False otherwise. A predictor is stale if it's in the READY state, but the platform cannot load the @@ -554,7 +554,7 @@ def is_stale(self, uid: Union[UUID, str], *, version: Union[int, str]) -> bool: """ return self._versions_collection.is_stale(uid, version=version) - def retrain_stale(self, uid: Union[UUID, str], *, version: Union[int, str]) -> GraphPredictor: + def retrain_stale(self, uid: UUID | str, *, version: int | str) -> GraphPredictor: """Begins retraining a stale predictor. This can only be used on a stale predictor, which is when it's in the READY state, but the @@ -564,9 +564,9 @@ def retrain_stale(self, uid: Union[UUID, str], *, version: Union[int, str]) -> G return self._versions_collection.retrain_stale(uid, version=version) def rename(self, - uid: Union[UUID, str], + uid: UUID | str, *, - version: Union[int, str], + version: int | str, name: Optional[str] = None, description: Optional[str] = None) -> GraphPredictor: """Rename an existing predictor. @@ -578,7 +578,7 @@ def rename(self, uid, version=version, name=name, description=description ) - def delete(self, uid: Union[UUID, str]): + def delete(self, uid: UUID | str): """Predictors cannot be deleted at this time.""" msg = "Predictors cannot be deleted. Use 'archive_version' or 'archive_root' instead." raise NotImplementedError(msg) diff --git a/src/citrine/resources/predictor_evaluation.py b/src/citrine/resources/predictor_evaluation.py index 924ab2f11..60b1a5845 100644 --- a/src/citrine/resources/predictor_evaluation.py +++ b/src/citrine/resources/predictor_evaluation.py @@ -43,7 +43,7 @@ def _list_base(self, *, per_page: int = 100, predictor_id: Optional[UUID] = None, - predictor_version: Optional[Union[int, str]] = None, + predictor_version: Optional[int | str] = None, archived: Optional[bool] = None ) -> Iterator[PredictorEvaluation]: params = {"archived": archived} @@ -61,7 +61,7 @@ def list_all(self, *, per_page: int = 100, predictor_id: Optional[UUID] = None, - predictor_version: Optional[Union[int, str]] = None + predictor_version: Optional[int | str] = None ) -> Iterable[PredictorEvaluation]: """List all predictor evaluations.""" return self._list_base(per_page=per_page, @@ -72,7 +72,7 @@ def list(self, *, per_page: int = 100, predictor_id: Optional[UUID] = None, - predictor_version: Optional[Union[int, str]] = None + predictor_version: Optional[int | str] = None ) -> Iterable[PredictorEvaluation]: """List non-archived predictor evaluations.""" return self._list_base(per_page=per_page, @@ -84,7 +84,7 @@ def list_archived(self, *, per_page: int = 100, predictor_id: Optional[UUID] = None, - predictor_version: Optional[Union[int, str]] = None + predictor_version: Optional[int | str] = None ) -> Iterable[PredictorEvaluation]: """List archived predictor evaluations.""" return self._list_base(per_page=per_page, @@ -92,13 +92,13 @@ def list_archived(self, predictor_version=predictor_version, archived=True) - def archive(self, uid: Union[UUID, str]): + def archive(self, uid: UUID | str): """Archive an evaluation.""" url = self._get_path(uid, action="archive") result = self.session.put_resource(url, {}, version=self._api_version) return self.build(result) - def restore(self, uid: Union[UUID, str]): + def restore(self, uid: UUID | str): """Restore an archived evaluation.""" url = self._get_path(uid, action="restore") result = self.session.put_resource(url, {}, version=self._api_version) @@ -117,8 +117,8 @@ def default_from_config(self, config: GraphPredictor) -> List[PredictorEvaluator def default(self, *, - predictor_id: Union[UUID, str], - predictor_version: Union[int, str] = LATEST_PRED_VER + predictor_id: UUID | str, + predictor_version: int | str = LATEST_PRED_VER ) -> List[PredictorEvaluator]: """Retrieve the default evaluators for a stored predictor. @@ -139,7 +139,7 @@ def default(self, ---------- predictor_id: UUID Unique identifier of the predictor to evaluate - predictor_version: Option[Union[int, str]] + predictor_version: Option[int | str] The version of the predictor to evaluate Returns @@ -154,8 +154,8 @@ def default(self, def trigger(self, *, - predictor_id: Union[UUID, str], - predictor_version: Union[int, str] = LATEST_PRED_VER, + predictor_id: UUID | str, + predictor_version: int | str = LATEST_PRED_VER, evaluators: List[PredictorEvaluator]) -> PredictorEvaluation: """Evaluate a predictor using the provided evaluators. @@ -163,7 +163,7 @@ def trigger(self, ---------- predictor_id: UUID Unique identifier of the predictor to evaluate - predictor_version: Option[Union[int, str]] + predictor_version: Option[int | str] The version of the predictor to evaluate. Defaults to the latest trained version. evaluators: list[PredictorEvaluator] The evaluators to use to measure predictor performance. @@ -182,8 +182,8 @@ def trigger(self, def trigger_default(self, *, - predictor_id: Union[UUID, str], - predictor_version: Union[int, str] = LATEST_PRED_VER + predictor_id: UUID | str, + predictor_version: int | str = LATEST_PRED_VER ) -> PredictorEvaluation: """Evaluate a predictor using the default evaluators. @@ -193,7 +193,7 @@ def trigger_default(self, ---------- predictor_id: UUID Unique identifier of the predictor to evaluate - predictor_version: Option[Union[int, str]] + predictor_version: Option[int | str] The version of the predictor to evaluate Returns @@ -214,6 +214,6 @@ def update(self, model: PredictorEvaluation) -> PredictorEvaluation: """Cannot update an evaluation.""" raise NotImplementedError("Cannot update a PredictorEvaluation.") - def delete(self, uid: Union[UUID, str]): + def delete(self, uid: UUID | str): """Cannot delete an evaluation.""" raise NotImplementedError("Cannot delete a PredictorEvaluation.") diff --git a/src/citrine/resources/process_run.py b/src/citrine/resources/process_run.py index 869f1d9a9..b0289421b 100644 --- a/src/citrine/resources/process_run.py +++ b/src/citrine/resources/process_run.py @@ -92,14 +92,14 @@ def get_type(cls) -> type[ProcessRun]: return ProcessRun def list_by_spec(self, - uid: Union[UUID, str, LinkByUID, GEMDProcessSpec] + uid: UUID | str | LinkByUID | GEMDProcessSpec ) -> Iterator[ProcessRun]: """ Get the process runs using the specified process spec. Parameters ---------- - uid: Union[UUID, str, LinkByUID, GEMDProcessSpec] + uid: UUID | str | LinkByUID | GEMDProcessSpec A representation of the process spec whose process run usages are to be located. Returns diff --git a/src/citrine/resources/process_spec.py b/src/citrine/resources/process_spec.py index 2e4efbc3c..ce4839ee5 100644 --- a/src/citrine/resources/process_spec.py +++ b/src/citrine/resources/process_spec.py @@ -96,14 +96,14 @@ def get_type(cls) -> type[ProcessSpec]: return ProcessSpec def list_by_template(self, - uid: Union[UUID, str, LinkByUID, GEMDProcessTemplate] + uid: UUID | str | LinkByUID | GEMDProcessTemplate ) -> Iterator[ProcessSpec]: """ Get the process specs using the specified process template. Parameters ---------- - uid: Union[UUID, str, LinkByUID, GEMDProcessTemplate] + uid: UUID | str | LinkByUID | GEMDProcessTemplate A representation of the process template whose process spec usages are to be located. Returns diff --git a/src/citrine/resources/process_template.py b/src/citrine/resources/process_template.py index 6b6fadad9..e7eca81df 100644 --- a/src/citrine/resources/process_template.py +++ b/src/citrine/resources/process_template.py @@ -86,16 +86,16 @@ def __init__(self, name: str, *, uids: Optional[dict[str, str]] = None, - conditions: Optional[Sequence[Union[ConditionTemplate, - LinkByUID, - Sequence[Union[ConditionTemplate, LinkByUID, - Optional[BaseBounds]]] - ]]] = None, - parameters: Optional[Sequence[Union[ParameterTemplate, - LinkByUID, - Sequence[Union[ParameterTemplate, LinkByUID, - Optional[BaseBounds]]] - ]]] = None, + conditions: Optional[Sequence[ConditionTemplate + | LinkByUID + | Sequence[ConditionTemplate | LinkByUID + | Optional[BaseBounds]] + ]] = None, + parameters: Optional[Sequence[ParameterTemplate + | LinkByUID + | Sequence[ParameterTemplate | LinkByUID + | Optional[BaseBounds]] + ]] = None, allowed_labels: Optional[list[str]] = None, allowed_names: Optional[list[str]] = None, description: Optional[str] = None, diff --git a/src/citrine/resources/project.py b/src/citrine/resources/project.py index ef6d5472c..3649e47f3 100644 --- a/src/citrine/resources/project.py +++ b/src/citrine/resources/project.py @@ -225,7 +225,7 @@ def pull_in_resource(self, *, resource: Resource): json={'ids': [resource_access["id"]]}) return True - def list_members(self) -> Union[list[ProjectMember], list["TeamMember"]]: # noqa: F821 + def list_members(self) -> "list[ProjectMember] | list[TeamMember]": # noqa: F821 """ List all of the members in the current project. @@ -291,7 +291,7 @@ def build(self, data) -> Project: project.team_id = self.team_id return project - def get(self, uid: Union[UUID, str]) -> Project: + def get(self, uid: UUID | str) -> Project: """ Get a particular project. @@ -514,7 +514,7 @@ def search(self, return self._build_collection_elements(self.search_all(search_params)) # To avoid setting default to {} -> reduce mutation risk, and to make more extensible - def archive(self, uid: Union[UUID, str]) -> Response: + def archive(self, uid: UUID | str) -> Response: """Archive a project.""" # Only the team-agnostic project archive is implemented if self.team_id is None: @@ -523,7 +523,7 @@ def archive(self, uid: Union[UUID, str]) -> Response: else: return ProjectCollection(session=self.session).archive(uid) - def restore(self, uid: Union[UUID, str]) -> Response: + def restore(self, uid: UUID | str) -> Response: """Restore an archived project.""" # Only the team-agnostic project restore is implemented if self.team_id is None: @@ -532,7 +532,7 @@ def restore(self, uid: Union[UUID, str]) -> Response: else: return ProjectCollection(session=self.session).restore(uid) - def delete(self, uid: Union[UUID, str]) -> Response: + def delete(self, uid: UUID | str) -> Response: """ Delete a particular project. diff --git a/src/citrine/resources/report.py b/src/citrine/resources/report.py index 7a0a7efa8..51ab14825 100644 --- a/src/citrine/resources/report.py +++ b/src/citrine/resources/report.py @@ -27,8 +27,8 @@ def __init__(self, project_id: UUID, session: Session): def get(self, *, - predictor_id: Union[UUID, str], - predictor_version: Optional[Union[int, str]] = None) -> Report: + predictor_id: UUID | str, + predictor_version: Optional[int | str] = None) -> Report: """Gets a single report keyed on the predictor ID and (optionally) version.""" version = predictor_version or "most_recent" diff --git a/src/citrine/resources/sample_design_space_execution.py b/src/citrine/resources/sample_design_space_execution.py index 9c5d0f953..24810c80e 100644 --- a/src/citrine/resources/sample_design_space_execution.py +++ b/src/citrine/resources/sample_design_space_execution.py @@ -74,7 +74,7 @@ def list(self, *, collection_builder=self._build_collection_elements, per_page=per_page) - def delete(self, uid: Union[UUID, str]) -> Response: + def delete(self, uid: UUID | str) -> Response: """Sample Design Space Executions cannot be deleted or archived.""" raise NotImplementedError( "Sample Design Space Executions cannot be deleted" diff --git a/src/citrine/resources/status_detail.py b/src/citrine/resources/status_detail.py index c5a1c4bed..5cfbfe7b5 100644 --- a/src/citrine/resources/status_detail.py +++ b/src/citrine/resources/status_detail.py @@ -24,7 +24,7 @@ class StatusDetail(Serializable[StatusDetailType]): msg = properties.String("msg") level = properties.String("level") - def __init__(self, *, msg: str, level: Union[str, StatusLevelEnum]): + def __init__(self, *, msg: str, level: str | StatusLevelEnum): self.msg = msg self.level = StatusLevelEnum.from_str(level, exception=True) diff --git a/src/citrine/resources/table_config.py b/src/citrine/resources/table_config.py index f0ea63592..2336593df 100644 --- a/src/citrine/resources/table_config.py +++ b/src/citrine/resources/table_config.py @@ -160,7 +160,7 @@ def uid(self) -> UUID: return self.config_uid @uid.setter - def uid(self, new_uid: Union[str, UUID]) -> None: + def uid(self, new_uid: str | UUID) -> None: """Set the unique ID of the table config, independent of its version.""" self.config_uid = new_uid @@ -210,7 +210,7 @@ def add_columns(self, *, return new_config def add_all_ingredients(self, *, - process_template: Union[LinkByUID, ProcessTemplate, str, UUID], + process_template: LinkByUID | ProcessTemplate | str | UUID, team: 'Team', quantity_dimension: IngredientQuantityDimension, scope: str = CITRINE_SCOPE, @@ -224,7 +224,7 @@ def add_all_ingredients(self, *, Parameters ------------ - process_template: Union[LinkByUID, ProcessTemplate, str, UUID] + process_template: LinkByUID | ProcessTemplate | str | UUID representation of a registered process template team: Team a team that has access to the process template @@ -424,7 +424,7 @@ def __init__(self, *, team_id: UUID, project_id: UUID, session: Session): self.session: Session = session self.team_id = team_id - def get(self, uid: Union[UUID, str], *, version: Optional[int] = None): + def get(self, uid: UUID | str, *, version: Optional[int] = None): """Get a table config. If no version is specified, then the most recent version is returned. @@ -479,7 +479,7 @@ def build(self, data: dict) -> TableConfig: def default_for_material( self, *, - material: Union[MaterialRun, LinkByUID, str, UUID], + material: MaterialRun | LinkByUID | str | UUID, name: str, description: str = None, algorithm: Optional[TableBuildAlgorithm] = None @@ -498,7 +498,7 @@ def default_for_material( Parameters ---------- - material: Union[MaterialRun, LinkByUid, str, UUID] + material: MaterialRun | LinkByUid | str | UUID The terminal material whose history is used to construct a table config. name: str The name for the table config. @@ -672,6 +672,6 @@ def update(self, table_config: TableConfig) -> TableConfig: " update()") return self.register(table_config) - def delete(self, uid: Union[UUID, str]): + def delete(self, uid: UUID | str): """Table configs cannot be deleted at this time.""" raise NotImplementedError("Table configs cannot be deleted at this time.") diff --git a/src/citrine/resources/team.py b/src/citrine/resources/team.py index 3b31e5b9e..64f52bd06 100644 --- a/src/citrine/resources/team.py +++ b/src/citrine/resources/team.py @@ -77,7 +77,7 @@ class TeamResourceIDs: def __init__(self, session: Session, - team_id: Union[str, UUID], + team_id: str | UUID, resource_type: str) -> None: self.session = session self.team_id = team_id @@ -190,7 +190,7 @@ def list_members(self) -> list[TeamMember]: members = response["users"] return [TeamMember(user=User.build(m), team=self, actions=m["actions"]) for m in members] - def get_member(self, user_id: Union[str, UUID, User]) -> TeamMember: + def get_member(self, user_id: str | UUID | User) -> TeamMember: """ Get a particular member in the current team. @@ -226,7 +226,7 @@ def me(self) -> TeamMember: me = UserCollection(self.session).me() return self.get_member(me) - def remove_user(self, user_id: Union[str, UUID, User]) -> bool: + def remove_user(self, user_id: str | UUID | User) -> bool: """ Remove a User from a Team. @@ -250,7 +250,7 @@ def remove_user(self, user_id: Union[str, UUID, User]) -> bool: return True # note: only get here if checked_post doesn't raise error def add_user(self, - user_id: Union[str, UUID, User], + user_id: str | UUID | User, *, actions: Optional[list[TEAM_ACTIONS]] = None) -> bool: """ @@ -284,7 +284,7 @@ def add_user(self, return self.update_user_action(user_id, actions=actions) def update_user_action(self, - user_id: Union[str, UUID, User], + user_id: str | UUID | User, *, actions: list[TEAM_ACTIONS]) -> bool: """ @@ -315,7 +315,7 @@ def update_user_action(self, def share(self, *, resource: Resource, - target_team_id: Union[str, UUID, "Team"]) -> bool: + target_team_id: "str | UUID | Team") -> bool: """ Share a resource with another team. @@ -325,7 +325,7 @@ def share(self, ---------- resource: Resource The resource owned by this team, which will be shared - target_team_id: Union[str, UUID, Team] + target_team_id: str | UUID | Team The id of the team with which to share the resource Returns @@ -346,7 +346,7 @@ def share(self, version=self._api_version, json=payload) return True - def un_share(self, *, resource: Resource, target_team_id: Union[str, UUID, "Team"]) -> bool: + def un_share(self, *, resource: Resource, target_team_id: "str | UUID | Team") -> bool: """ Revoke the share of a particular resource to a secondary team. @@ -356,7 +356,7 @@ def un_share(self, *, resource: Resource, target_team_id: Union[str, UUID, "Team ---------- resource: Resource The resource owned by this team, which will be un-shared - target_team_id: Union[str, UUID, Team] + target_team_id: str | UUID | Team The id of the team which should not have access to the resource Returns @@ -513,7 +513,7 @@ def gemd(self) -> GEMDResourceCollection: return GEMDResourceCollection(team_id=self.uid, dataset_id=None, session=self.session) def gemd_batch_delete(self, - id_list: list[Union[LinkByUID, UUID, str, BaseEntity]], + id_list: list[LinkByUID | UUID | str | BaseEntity], *, timeout: float = 2 * 60, polling_delay: float = 1.0) -> list[tuple[LinkByUID, ApiError]]: @@ -530,7 +530,7 @@ def gemd_batch_delete(self, Parameters ---------- - id_list: list[Union[LinkByUID, UUID, str, BaseEntity]] + id_list: list[LinkByUID | UUID | str | BaseEntity] A list of the IDs of data objects to be removed. They can be passed as a LinkByUID tuple, a UUID, a string, or the object itself. A UUID or string is assumed to be a Citrine ID, whereas a LinkByUID or diff --git a/tox.ini b/tox.ini index 6b857390c..bd3bd3207 100644 --- a/tox.ini +++ b/tox.ini @@ -9,7 +9,8 @@ max-doc-length = 119 # D107: __init__ is self explanatory # D301: backslash is used in making docstrings for sphinx to parse # D401: Imperative mood requirement basically gets in the way -ignore = D100,D104,D105,D107,D301,D401 +# W503: Line breaks before a binary operator are best practice +ignore = D100,D104,D105,D107,D301,D401,W503 # D101, D102 would result in redundant documentation for subclasses. per-file-ignores = From 78ae26405862d1a1484110e97ad31ea1951861c1 Mon Sep 17 00:00:00 2001 From: Austin Noto-Moniz Date: Fri, 13 Feb 2026 15:01:26 -0500 Subject: [PATCH 3/6] Drop obsolete typing imports. Clean up all the unused imports created by the previous two changes. It was easier to handle them all at once rather than as I went. --- src/citrine/_rest/collection.py | 2 +- src/citrine/_rest/pageable.py | 2 +- src/citrine/_rest/paginator.py | 2 +- src/citrine/_rest/resource.py | 2 +- src/citrine/_serialization/polymorphic_serializable.py | 2 +- src/citrine/_utils/batcher.py | 2 +- src/citrine/_utils/functions.py | 2 +- src/citrine/_utils/template_util.py | 1 - src/citrine/exceptions.py | 2 +- src/citrine/gemd_queries/criteria.py | 1 - src/citrine/gemd_queries/filter.py | 1 - src/citrine/gemtables/columns.py | 2 +- src/citrine/gemtables/rows.py | 1 - src/citrine/gemtables/variables.py | 2 +- src/citrine/informatics/catalyst/assistant.py | 2 +- src/citrine/informatics/constraints/categorical_constraint.py | 1 - .../informatics/constraints/ingredient_ratio_constraint.py | 2 +- src/citrine/informatics/data_sources.py | 1 - src/citrine/informatics/descriptors.py | 1 - src/citrine/informatics/design_candidate.py | 2 +- .../informatics/design_spaces/design_space_settings.py | 2 +- .../informatics/design_spaces/formulation_design_space.py | 2 +- .../informatics/design_spaces/hierarchical_design_space.py | 2 +- src/citrine/informatics/design_spaces/product_design_space.py | 2 +- src/citrine/informatics/design_spaces/subspace.py | 2 -- .../informatics/design_spaces/top_level_design_space.py | 2 +- src/citrine/informatics/dimensions.py | 2 +- src/citrine/informatics/executions/predictor_evaluation.py | 2 +- src/citrine/informatics/experiment_values.py | 1 - src/citrine/informatics/feature_effects.py | 3 +-- src/citrine/informatics/generative_design.py | 2 +- src/citrine/informatics/predict_request.py | 2 +- src/citrine/informatics/predictor_evaluation_metrics.py | 1 - src/citrine/informatics/predictor_evaluation_result.py | 1 - src/citrine/informatics/predictor_evaluator.py | 2 +- .../predictors/attribute_accumulation_predictor.py | 1 - src/citrine/informatics/predictors/auto_ml_predictor.py | 2 +- .../informatics/predictors/chemical_formula_featurizer.py | 2 +- src/citrine/informatics/predictors/expression_predictor.py | 1 - src/citrine/informatics/predictors/graph_predictor.py | 2 +- .../informatics/predictors/ingredient_fractions_predictor.py | 1 - .../predictors/ingredients_to_formulation_predictor.py | 1 - .../informatics/predictors/label_fractions_predictor.py | 1 - src/citrine/informatics/predictors/mean_property_predictor.py | 2 +- .../informatics/predictors/molecular_structure_featurizer.py | 2 +- src/citrine/informatics/predictors/node.py | 1 - src/citrine/informatics/predictors/single_predict_request.py | 2 +- src/citrine/informatics/predictors/single_prediction.py | 1 - src/citrine/informatics/reports.py | 2 +- src/citrine/informatics/scores.py | 2 +- src/citrine/informatics/workflows/analysis_workflow.py | 2 +- src/citrine/informatics/workflows/design_workflow.py | 2 +- src/citrine/jobs/job.py | 1 - src/citrine/jobs/waiting.py | 1 - src/citrine/resources/_default_labels.py | 2 +- src/citrine/resources/analysis_workflow.py | 2 +- src/citrine/resources/branch.py | 2 +- src/citrine/resources/condition_template.py | 2 +- src/citrine/resources/data_concepts.py | 2 +- src/citrine/resources/data_objects.py | 2 +- src/citrine/resources/data_version_update.py | 1 - src/citrine/resources/dataset.py | 2 +- src/citrine/resources/delete.py | 2 +- src/citrine/resources/descriptors.py | 1 - src/citrine/resources/design_execution.py | 2 +- src/citrine/resources/design_space.py | 2 +- src/citrine/resources/design_workflow.py | 2 +- src/citrine/resources/experiment_datasource.py | 2 +- src/citrine/resources/file_link.py | 2 +- src/citrine/resources/gemd_resource.py | 2 +- src/citrine/resources/gemtables.py | 2 +- src/citrine/resources/generative_design_execution.py | 2 +- src/citrine/resources/ingestion.py | 2 +- src/citrine/resources/ingredient_run.py | 2 +- src/citrine/resources/ingredient_spec.py | 2 +- src/citrine/resources/material_run.py | 2 +- src/citrine/resources/material_spec.py | 2 +- src/citrine/resources/material_template.py | 2 +- src/citrine/resources/measurement_run.py | 2 +- src/citrine/resources/measurement_spec.py | 2 +- src/citrine/resources/measurement_template.py | 2 +- src/citrine/resources/parameter_template.py | 2 +- src/citrine/resources/predictor.py | 2 +- src/citrine/resources/predictor_evaluation.py | 2 +- src/citrine/resources/process_run.py | 2 +- src/citrine/resources/process_spec.py | 2 +- src/citrine/resources/process_template.py | 2 +- src/citrine/resources/project.py | 4 ++-- src/citrine/resources/property_template.py | 2 +- src/citrine/resources/report.py | 2 +- src/citrine/resources/sample_design_space_execution.py | 2 +- src/citrine/resources/status_detail.py | 2 +- src/citrine/resources/table_config.py | 4 ++-- src/citrine/resources/team.py | 2 +- 94 files changed, 74 insertions(+), 98 deletions(-) diff --git a/src/citrine/_rest/collection.py b/src/citrine/_rest/collection.py index 327cc7528..d6b005ae1 100644 --- a/src/citrine/_rest/collection.py +++ b/src/citrine/_rest/collection.py @@ -1,5 +1,5 @@ from abc import abstractmethod -from typing import Optional, Union, Generic, TypeVar, Iterable, Iterator, Sequence, Dict +from typing import Optional, Generic, TypeVar, Iterable, Iterator, Sequence from uuid import UUID from citrine._rest.pageable import Pageable diff --git a/src/citrine/_rest/pageable.py b/src/citrine/_rest/pageable.py index 0c46c8e10..81290cfeb 100644 --- a/src/citrine/_rest/pageable.py +++ b/src/citrine/_rest/pageable.py @@ -1,4 +1,4 @@ -from typing import Optional, Iterable, Dict, Tuple, Callable, Union, Sequence +from typing import Optional, Iterable, Callable, Sequence from uuid import UUID diff --git a/src/citrine/_rest/paginator.py b/src/citrine/_rest/paginator.py index ac2c54eb5..5385f9453 100644 --- a/src/citrine/_rest/paginator.py +++ b/src/citrine/_rest/paginator.py @@ -1,4 +1,4 @@ -from typing import TypeVar, Generic, Callable, Optional, Iterable, Any, Tuple, Iterator +from typing import TypeVar, Generic, Callable, Optional, Iterable, Any, Iterator from uuid import uuid4 ResourceType = TypeVar('ResourceType') diff --git a/src/citrine/_rest/resource.py b/src/citrine/_rest/resource.py index e572d5afa..a83d6905b 100644 --- a/src/citrine/_rest/resource.py +++ b/src/citrine/_rest/resource.py @@ -1,4 +1,4 @@ -from typing import TypeVar, Optional, Union +from typing import TypeVar, Optional from uuid import UUID from citrine._serialization.serializable import Serializable diff --git a/src/citrine/_serialization/polymorphic_serializable.py b/src/citrine/_serialization/polymorphic_serializable.py index 01218606f..109efc9e8 100644 --- a/src/citrine/_serialization/polymorphic_serializable.py +++ b/src/citrine/_serialization/polymorphic_serializable.py @@ -1,5 +1,5 @@ from abc import abstractmethod -from typing import Generic, TypeVar, Type +from typing import Generic, TypeVar from citrine._serialization.serializable import Serializable diff --git a/src/citrine/_utils/batcher.py b/src/citrine/_utils/batcher.py index 67d20a7ec..449f26171 100644 --- a/src/citrine/_utils/batcher.py +++ b/src/citrine/_utils/batcher.py @@ -1,6 +1,6 @@ from abc import ABC, abstractmethod from collections import defaultdict -from typing import List, Iterable +from typing import Iterable from citrine.resources.data_concepts import DataConcepts diff --git a/src/citrine/_utils/functions.py b/src/citrine/_utils/functions.py index bbb21a585..7949bdd06 100644 --- a/src/citrine/_utils/functions.py +++ b/src/citrine/_utils/functions.py @@ -1,7 +1,7 @@ from abc import ABCMeta import os from pathlib import Path -from typing import Any, Dict, Optional, Sequence, Union +from typing import Any, Optional, Sequence from urllib.parse import quote, urlencode, urlparse from uuid import UUID from warnings import warn diff --git a/src/citrine/_utils/template_util.py b/src/citrine/_utils/template_util.py index 359ae238e..8b2505793 100644 --- a/src/citrine/_utils/template_util.py +++ b/src/citrine/_utils/template_util.py @@ -8,7 +8,6 @@ ) from citrine.resources.data_concepts import DataConcepts from gemd.entity.value.base_value import BaseValue -from typing import Mapping, List from gemd.entity.attribute import PropertyAndConditions diff --git a/src/citrine/exceptions.py b/src/citrine/exceptions.py index d042e1370..d7bca5530 100644 --- a/src/citrine/exceptions.py +++ b/src/citrine/exceptions.py @@ -1,6 +1,6 @@ """Citrine-specific exceptions.""" from types import SimpleNamespace -from typing import Optional, List +from typing import Optional from urllib.parse import urlencode from uuid import UUID diff --git a/src/citrine/gemd_queries/criteria.py b/src/citrine/gemd_queries/criteria.py index 5fc8c1f75..223e94313 100644 --- a/src/citrine/gemd_queries/criteria.py +++ b/src/citrine/gemd_queries/criteria.py @@ -1,5 +1,4 @@ """Definitions for GemdQuery objects, and their sub-objects.""" -from typing import List, Type from gemd.enumeration.base_enumeration import BaseEnumeration diff --git a/src/citrine/gemd_queries/filter.py b/src/citrine/gemd_queries/filter.py index 4c67c2e52..b76540e0d 100644 --- a/src/citrine/gemd_queries/filter.py +++ b/src/citrine/gemd_queries/filter.py @@ -1,5 +1,4 @@ """Definitions for GemdQuery objects, and their sub-objects.""" -from typing import List, Type from citrine._serialization.serializable import Serializable from citrine._serialization.polymorphic_serializable import PolymorphicSerializable diff --git a/src/citrine/gemtables/columns.py b/src/citrine/gemtables/columns.py index bc3d35c8d..4690f26ef 100644 --- a/src/citrine/gemtables/columns.py +++ b/src/citrine/gemtables/columns.py @@ -1,5 +1,5 @@ """Column definitions for GEM Tables.""" -from typing import Type, Optional, List, Union +from typing import Optional from gemd.enumeration.base_enumeration import BaseEnumeration diff --git a/src/citrine/gemtables/rows.py b/src/citrine/gemtables/rows.py index 8a1f5abea..8e050a53c 100644 --- a/src/citrine/gemtables/rows.py +++ b/src/citrine/gemtables/rows.py @@ -1,5 +1,4 @@ """Row definitions for GEM Tables.""" -from typing import Type, List, Set, Union from uuid import UUID from gemd.entity.link_by_uid import LinkByUID diff --git a/src/citrine/gemtables/variables.py b/src/citrine/gemtables/variables.py index 7582cbb13..65e1ac5e4 100644 --- a/src/citrine/gemtables/variables.py +++ b/src/citrine/gemtables/variables.py @@ -1,5 +1,5 @@ """Variable definitions for GEM Tables.""" -from typing import Type, Optional, List, Union, Tuple +from typing import Optional from uuid import UUID from gemd.entity.bounds.base_bounds import BaseBounds diff --git a/src/citrine/informatics/catalyst/assistant.py b/src/citrine/informatics/catalyst/assistant.py index f0daf4134..93e3eb67d 100644 --- a/src/citrine/informatics/catalyst/assistant.py +++ b/src/citrine/informatics/catalyst/assistant.py @@ -1,4 +1,4 @@ -from typing import Optional, Type +from typing import Optional from citrine.informatics.predictors import GraphPredictor from citrine._serialization import properties diff --git a/src/citrine/informatics/constraints/categorical_constraint.py b/src/citrine/informatics/constraints/categorical_constraint.py index 616013b0c..d34c268ba 100644 --- a/src/citrine/informatics/constraints/categorical_constraint.py +++ b/src/citrine/informatics/constraints/categorical_constraint.py @@ -1,4 +1,3 @@ -from typing import List from citrine._serialization import properties from citrine._serialization.serializable import Serializable diff --git a/src/citrine/informatics/constraints/ingredient_ratio_constraint.py b/src/citrine/informatics/constraints/ingredient_ratio_constraint.py index 396b9ad22..04c5ef0f5 100644 --- a/src/citrine/informatics/constraints/ingredient_ratio_constraint.py +++ b/src/citrine/informatics/constraints/ingredient_ratio_constraint.py @@ -1,4 +1,4 @@ -from typing import Set, Optional, Tuple +from typing import Optional from citrine._serialization import properties from citrine._serialization.serializable import Serializable diff --git a/src/citrine/informatics/data_sources.py b/src/citrine/informatics/data_sources.py index 2ee0733d6..c9f957cbf 100644 --- a/src/citrine/informatics/data_sources.py +++ b/src/citrine/informatics/data_sources.py @@ -1,6 +1,5 @@ """Tools for working with Descriptors.""" from abc import abstractmethod -from typing import Type, List, Union from uuid import UUID from citrine._serialization import properties diff --git a/src/citrine/informatics/descriptors.py b/src/citrine/informatics/descriptors.py index f55731f22..fef37ae02 100644 --- a/src/citrine/informatics/descriptors.py +++ b/src/citrine/informatics/descriptors.py @@ -1,5 +1,4 @@ """Tools for working with Descriptors.""" -from typing import Type, Set, Union from gemd.enumeration.base_enumeration import BaseEnumeration diff --git a/src/citrine/informatics/design_candidate.py b/src/citrine/informatics/design_candidate.py index 760e7187d..85f9d3ec3 100644 --- a/src/citrine/informatics/design_candidate.py +++ b/src/citrine/informatics/design_candidate.py @@ -1,4 +1,4 @@ -from typing import Type, Optional +from typing import Optional from citrine._serialization import properties from citrine._serialization.polymorphic_serializable import PolymorphicSerializable diff --git a/src/citrine/informatics/design_spaces/design_space_settings.py b/src/citrine/informatics/design_spaces/design_space_settings.py index 584a7bd99..57c0a2dd9 100644 --- a/src/citrine/informatics/design_spaces/design_space_settings.py +++ b/src/citrine/informatics/design_spaces/design_space_settings.py @@ -1,4 +1,4 @@ -from typing import Optional, Union +from typing import Optional from uuid import UUID from gemd.enumeration.base_enumeration import BaseEnumeration diff --git a/src/citrine/informatics/design_spaces/formulation_design_space.py b/src/citrine/informatics/design_spaces/formulation_design_space.py index 1ca574396..202005dc4 100644 --- a/src/citrine/informatics/design_spaces/formulation_design_space.py +++ b/src/citrine/informatics/design_spaces/formulation_design_space.py @@ -1,4 +1,4 @@ -from typing import Mapping, Optional, Set +from typing import Optional from citrine._rest.resource import Resource from citrine._serialization import properties diff --git a/src/citrine/informatics/design_spaces/hierarchical_design_space.py b/src/citrine/informatics/design_spaces/hierarchical_design_space.py index 546f05cb6..217c8ff8c 100644 --- a/src/citrine/informatics/design_spaces/hierarchical_design_space.py +++ b/src/citrine/informatics/design_spaces/hierarchical_design_space.py @@ -1,4 +1,4 @@ -from typing import Optional, List +from typing import Optional from uuid import UUID from citrine._rest.engine_resource import EngineResource diff --git a/src/citrine/informatics/design_spaces/product_design_space.py b/src/citrine/informatics/design_spaces/product_design_space.py index 9a731d525..836bf59ae 100644 --- a/src/citrine/informatics/design_spaces/product_design_space.py +++ b/src/citrine/informatics/design_spaces/product_design_space.py @@ -1,4 +1,4 @@ -from typing import List, Union, Optional +from typing import Optional from citrine._rest.engine_resource import EngineResource from citrine._serialization import properties diff --git a/src/citrine/informatics/design_spaces/subspace.py b/src/citrine/informatics/design_spaces/subspace.py index 684662ea7..0287cccf3 100644 --- a/src/citrine/informatics/design_spaces/subspace.py +++ b/src/citrine/informatics/design_spaces/subspace.py @@ -1,5 +1,3 @@ -from typing import Type - from citrine._serialization import properties from citrine._serialization.polymorphic_serializable import PolymorphicSerializable from citrine.informatics.design_spaces.design_space import DesignSpace diff --git a/src/citrine/informatics/design_spaces/top_level_design_space.py b/src/citrine/informatics/design_spaces/top_level_design_space.py index 817fba68c..3861daade 100644 --- a/src/citrine/informatics/design_spaces/top_level_design_space.py +++ b/src/citrine/informatics/design_spaces/top_level_design_space.py @@ -1,5 +1,5 @@ """Tools for working with design spaces.""" -from typing import Optional, Type +from typing import Optional from uuid import UUID from citrine._rest.asynchronous_object import AsynchronousObject diff --git a/src/citrine/informatics/dimensions.py b/src/citrine/informatics/dimensions.py index 696a106b7..0e0878798 100644 --- a/src/citrine/informatics/dimensions.py +++ b/src/citrine/informatics/dimensions.py @@ -1,5 +1,5 @@ """Tools for working with Dimensions.""" -from typing import Optional, Type, List +from typing import Optional from citrine._serialization import properties from citrine._serialization.polymorphic_serializable import PolymorphicSerializable diff --git a/src/citrine/informatics/executions/predictor_evaluation.py b/src/citrine/informatics/executions/predictor_evaluation.py index 7aa2c31a9..520a521ea 100644 --- a/src/citrine/informatics/executions/predictor_evaluation.py +++ b/src/citrine/informatics/executions/predictor_evaluation.py @@ -1,5 +1,5 @@ from functools import lru_cache -from typing import List, Optional, Union +from typing import Optional from uuid import UUID from citrine._rest.asynchronous_object import AsynchronousObject diff --git a/src/citrine/informatics/experiment_values.py b/src/citrine/informatics/experiment_values.py index 372021029..a615057bf 100644 --- a/src/citrine/informatics/experiment_values.py +++ b/src/citrine/informatics/experiment_values.py @@ -1,4 +1,3 @@ -from typing import Dict, Type from citrine._serialization.serializable import Serializable from citrine._serialization.polymorphic_serializable import PolymorphicSerializable diff --git a/src/citrine/informatics/feature_effects.py b/src/citrine/informatics/feature_effects.py index 08f2f8aed..50289ac0d 100644 --- a/src/citrine/informatics/feature_effects.py +++ b/src/citrine/informatics/feature_effects.py @@ -1,4 +1,3 @@ -from typing import Dict from uuid import UUID from citrine._rest.resource import Resource @@ -50,7 +49,7 @@ class FeatureEffects(Resource): serializable=False) @classmethod - def _pre_build(cls, data: dict) -> Dict: + def _pre_build(cls, data: dict) -> dict: shapley = data.get("result") if not shapley: return data diff --git a/src/citrine/informatics/generative_design.py b/src/citrine/informatics/generative_design.py index d1a49cd7f..899757b2c 100644 --- a/src/citrine/informatics/generative_design.py +++ b/src/citrine/informatics/generative_design.py @@ -1,4 +1,4 @@ -from typing import Dict, List, Optional +from typing import Optional from citrine._serialization import properties from citrine._serialization.serializable import Serializable from gemd.enumeration.base_enumeration import BaseEnumeration diff --git a/src/citrine/informatics/predict_request.py b/src/citrine/informatics/predict_request.py index fdb8761e5..79eacfa95 100644 --- a/src/citrine/informatics/predict_request.py +++ b/src/citrine/informatics/predict_request.py @@ -1,4 +1,4 @@ -from typing import List, Optional +from typing import Optional from uuid import UUID from citrine._serialization import properties diff --git a/src/citrine/informatics/predictor_evaluation_metrics.py b/src/citrine/informatics/predictor_evaluation_metrics.py index ae5eec754..fb85e93e6 100644 --- a/src/citrine/informatics/predictor_evaluation_metrics.py +++ b/src/citrine/informatics/predictor_evaluation_metrics.py @@ -1,6 +1,5 @@ from logging import getLogger from math import isclose -from typing import Type, Union from citrine._serialization import properties from citrine._serialization.polymorphic_serializable import PolymorphicSerializable diff --git a/src/citrine/informatics/predictor_evaluation_result.py b/src/citrine/informatics/predictor_evaluation_result.py index 6e25e72ae..435468463 100644 --- a/src/citrine/informatics/predictor_evaluation_result.py +++ b/src/citrine/informatics/predictor_evaluation_result.py @@ -1,4 +1,3 @@ -from typing import Type, Set from citrine._serialization import properties from citrine._serialization.polymorphic_serializable import PolymorphicSerializable diff --git a/src/citrine/informatics/predictor_evaluator.py b/src/citrine/informatics/predictor_evaluator.py index e7208295c..3fdb63b6c 100644 --- a/src/citrine/informatics/predictor_evaluator.py +++ b/src/citrine/informatics/predictor_evaluator.py @@ -1,4 +1,4 @@ -from typing import Optional, Set, Type +from typing import Optional from citrine._serialization import properties from citrine._serialization.polymorphic_serializable import PolymorphicSerializable diff --git a/src/citrine/informatics/predictors/attribute_accumulation_predictor.py b/src/citrine/informatics/predictors/attribute_accumulation_predictor.py index c944653ec..7a3602d53 100644 --- a/src/citrine/informatics/predictors/attribute_accumulation_predictor.py +++ b/src/citrine/informatics/predictors/attribute_accumulation_predictor.py @@ -1,4 +1,3 @@ -from typing import List from citrine._rest.resource import Resource from citrine._serialization import properties as _properties diff --git a/src/citrine/informatics/predictors/auto_ml_predictor.py b/src/citrine/informatics/predictors/auto_ml_predictor.py index bf6951994..546928a8b 100644 --- a/src/citrine/informatics/predictors/auto_ml_predictor.py +++ b/src/citrine/informatics/predictors/auto_ml_predictor.py @@ -1,4 +1,4 @@ -from typing import List, Optional, Set +from typing import Optional from gemd.enumeration.base_enumeration import BaseEnumeration diff --git a/src/citrine/informatics/predictors/chemical_formula_featurizer.py b/src/citrine/informatics/predictors/chemical_formula_featurizer.py index 15140b3fb..8e1dc4d53 100644 --- a/src/citrine/informatics/predictors/chemical_formula_featurizer.py +++ b/src/citrine/informatics/predictors/chemical_formula_featurizer.py @@ -1,4 +1,4 @@ -from typing import List, Optional +from typing import Optional from warnings import warn from citrine._rest.resource import Resource diff --git a/src/citrine/informatics/predictors/expression_predictor.py b/src/citrine/informatics/predictors/expression_predictor.py index 09fdeacb1..4b294ec98 100644 --- a/src/citrine/informatics/predictors/expression_predictor.py +++ b/src/citrine/informatics/predictors/expression_predictor.py @@ -1,4 +1,3 @@ -from typing import Mapping from citrine._rest.resource import Resource from citrine._serialization import properties as _properties diff --git a/src/citrine/informatics/predictors/graph_predictor.py b/src/citrine/informatics/predictors/graph_predictor.py index 60c8bf32f..6d08565e2 100644 --- a/src/citrine/informatics/predictors/graph_predictor.py +++ b/src/citrine/informatics/predictors/graph_predictor.py @@ -1,4 +1,4 @@ -from typing import List, Optional +from typing import Optional from uuid import UUID from citrine._rest.asynchronous_object import AsynchronousObject diff --git a/src/citrine/informatics/predictors/ingredient_fractions_predictor.py b/src/citrine/informatics/predictors/ingredient_fractions_predictor.py index deb30741d..b0f5dc3b8 100644 --- a/src/citrine/informatics/predictors/ingredient_fractions_predictor.py +++ b/src/citrine/informatics/predictors/ingredient_fractions_predictor.py @@ -1,4 +1,3 @@ -from typing import Set from citrine._rest.resource import Resource from citrine._serialization import properties as _properties diff --git a/src/citrine/informatics/predictors/ingredients_to_formulation_predictor.py b/src/citrine/informatics/predictors/ingredients_to_formulation_predictor.py index 4fcd1a15f..61a69c2dd 100644 --- a/src/citrine/informatics/predictors/ingredients_to_formulation_predictor.py +++ b/src/citrine/informatics/predictors/ingredients_to_formulation_predictor.py @@ -1,4 +1,3 @@ -from typing import Set, Mapping from citrine._rest.resource import Resource from citrine._serialization import properties diff --git a/src/citrine/informatics/predictors/label_fractions_predictor.py b/src/citrine/informatics/predictors/label_fractions_predictor.py index 319249d3d..7a529d75d 100644 --- a/src/citrine/informatics/predictors/label_fractions_predictor.py +++ b/src/citrine/informatics/predictors/label_fractions_predictor.py @@ -1,4 +1,3 @@ -from typing import Set from citrine._rest.resource import Resource from citrine._serialization import properties as _properties diff --git a/src/citrine/informatics/predictors/mean_property_predictor.py b/src/citrine/informatics/predictors/mean_property_predictor.py index ee0282ac8..05fc346e4 100644 --- a/src/citrine/informatics/predictors/mean_property_predictor.py +++ b/src/citrine/informatics/predictors/mean_property_predictor.py @@ -1,4 +1,4 @@ -from typing import List, Mapping, Optional, Union +from typing import Optional from citrine._rest.resource import Resource from citrine._serialization import properties as _properties diff --git a/src/citrine/informatics/predictors/molecular_structure_featurizer.py b/src/citrine/informatics/predictors/molecular_structure_featurizer.py index 617b7dd58..6c53fdc8e 100644 --- a/src/citrine/informatics/predictors/molecular_structure_featurizer.py +++ b/src/citrine/informatics/predictors/molecular_structure_featurizer.py @@ -1,7 +1,7 @@ # flake8: noqa # The docstring includes many long links that violate flake8, and it's easier to noqa # the whole file than to pick out the offending lines. -from typing import List, Optional +from typing import Optional from citrine._rest.resource import Resource from citrine._serialization import properties as _properties diff --git a/src/citrine/informatics/predictors/node.py b/src/citrine/informatics/predictors/node.py index 23e915126..aacbae069 100644 --- a/src/citrine/informatics/predictors/node.py +++ b/src/citrine/informatics/predictors/node.py @@ -1,4 +1,3 @@ -from typing import Type from citrine._serialization import properties from citrine._serialization.polymorphic_serializable import PolymorphicSerializable diff --git a/src/citrine/informatics/predictors/single_predict_request.py b/src/citrine/informatics/predictors/single_predict_request.py index 6a021ce10..43a206480 100644 --- a/src/citrine/informatics/predictors/single_predict_request.py +++ b/src/citrine/informatics/predictors/single_predict_request.py @@ -1,4 +1,4 @@ -from typing import List, Optional +from typing import Optional from uuid import UUID from citrine._serialization import properties diff --git a/src/citrine/informatics/predictors/single_prediction.py b/src/citrine/informatics/predictors/single_prediction.py index cab1c1883..3680687d1 100644 --- a/src/citrine/informatics/predictors/single_prediction.py +++ b/src/citrine/informatics/predictors/single_prediction.py @@ -1,4 +1,3 @@ -from typing import List from uuid import UUID from citrine._serialization import properties diff --git a/src/citrine/informatics/reports.py b/src/citrine/informatics/reports.py index 2fa574543..dfab61810 100644 --- a/src/citrine/informatics/reports.py +++ b/src/citrine/informatics/reports.py @@ -1,5 +1,5 @@ """Tools for working with reports.""" -from typing import Type, Dict, TypeVar, Iterable, Any, Set +from typing import TypeVar, Iterable, Any from abc import abstractmethod from itertools import groupby from logging import getLogger diff --git a/src/citrine/informatics/scores.py b/src/citrine/informatics/scores.py index 405f1ce6e..acc8aac83 100644 --- a/src/citrine/informatics/scores.py +++ b/src/citrine/informatics/scores.py @@ -1,5 +1,5 @@ """Tools for working with Scores.""" -from typing import List, Optional +from typing import Optional from citrine._serialization import properties from citrine._serialization.polymorphic_serializable import PolymorphicSerializable diff --git a/src/citrine/informatics/workflows/analysis_workflow.py b/src/citrine/informatics/workflows/analysis_workflow.py index 227477e76..5594e80f9 100644 --- a/src/citrine/informatics/workflows/analysis_workflow.py +++ b/src/citrine/informatics/workflows/analysis_workflow.py @@ -1,4 +1,4 @@ -from typing import List, Optional, Union +from typing import Optional from uuid import UUID from citrine._rest.engine_resource import EngineResourceWithoutStatus diff --git a/src/citrine/informatics/workflows/design_workflow.py b/src/citrine/informatics/workflows/design_workflow.py index 3dfb9816f..695586f95 100644 --- a/src/citrine/informatics/workflows/design_workflow.py +++ b/src/citrine/informatics/workflows/design_workflow.py @@ -1,4 +1,4 @@ -from typing import Optional, Union +from typing import Optional from uuid import UUID from citrine._rest.resource import Resource diff --git a/src/citrine/jobs/job.py b/src/citrine/jobs/job.py index 16bae0f0a..b6e1ae420 100644 --- a/src/citrine/jobs/job.py +++ b/src/citrine/jobs/job.py @@ -1,7 +1,6 @@ from gemd.enumeration.base_enumeration import BaseEnumeration from logging import getLogger from time import time, sleep -from typing import Union from uuid import UUID from warnings import warn diff --git a/src/citrine/jobs/waiting.py b/src/citrine/jobs/waiting.py index bea8bfbcf..a688664e5 100644 --- a/src/citrine/jobs/waiting.py +++ b/src/citrine/jobs/waiting.py @@ -1,6 +1,5 @@ import time from pprint import pprint -from typing import Union from citrine._rest.collection import Collection from citrine._rest.asynchronous_object import AsynchronousObject diff --git a/src/citrine/resources/_default_labels.py b/src/citrine/resources/_default_labels.py index a315e224a..ede3de4bb 100644 --- a/src/citrine/resources/_default_labels.py +++ b/src/citrine/resources/_default_labels.py @@ -1,4 +1,4 @@ -from typing import List, Optional +from typing import Optional from citrine.resources.data_concepts import CITRINE_TAG_PREFIX diff --git a/src/citrine/resources/analysis_workflow.py b/src/citrine/resources/analysis_workflow.py index 293892509..817308ce7 100644 --- a/src/citrine/resources/analysis_workflow.py +++ b/src/citrine/resources/analysis_workflow.py @@ -1,5 +1,5 @@ import functools -from typing import Iterator, Optional, Union +from typing import Iterator, Optional from uuid import UUID from citrine.informatics.workflows.analysis_workflow import AnalysisWorkflow, \ diff --git a/src/citrine/resources/branch.py b/src/citrine/resources/branch.py index d7f53cc91..1c88ed771 100644 --- a/src/citrine/resources/branch.py +++ b/src/citrine/resources/branch.py @@ -1,5 +1,5 @@ import functools -from typing import Iterator, Optional, Union +from typing import Iterator, Optional from uuid import UUID from citrine._rest.collection import Collection diff --git a/src/citrine/resources/condition_template.py b/src/citrine/resources/condition_template.py index 87c1ded5c..ef4835336 100644 --- a/src/citrine/resources/condition_template.py +++ b/src/citrine/resources/condition_template.py @@ -1,5 +1,5 @@ """Resources that represent condition templates.""" -from typing import List, Dict, Optional, Type +from typing import Optional from citrine._rest.resource import GEMDResource from citrine.resources.attribute_templates import AttributeTemplate, AttributeTemplateCollection diff --git a/src/citrine/resources/data_concepts.py b/src/citrine/resources/data_concepts.py index 48065e328..a8ecbd25d 100644 --- a/src/citrine/resources/data_concepts.py +++ b/src/citrine/resources/data_concepts.py @@ -1,7 +1,7 @@ """Top-level class for all data concepts objects and collections thereof.""" import re from abc import abstractmethod, ABC -from typing import TypeVar, Type, List, Union, Optional, Iterator, Iterable +from typing import Iterable, Iterator, List, Optional, TypeVar from uuid import UUID, uuid4 from gemd.entity.dict_serializable import DictSerializable, DictSerializableMeta diff --git a/src/citrine/resources/data_objects.py b/src/citrine/resources/data_objects.py index b976d58f8..fb981b4f8 100644 --- a/src/citrine/resources/data_objects.py +++ b/src/citrine/resources/data_objects.py @@ -1,6 +1,6 @@ """Top-level class for all data object (i.e., spec and run) objects and collections thereof.""" from abc import ABC -from typing import Dict, Union, Optional, Iterator, List, TypeVar +from typing import Optional, Iterator, TypeVar from uuid import uuid4 from gemd.json import GEMDJson diff --git a/src/citrine/resources/data_version_update.py b/src/citrine/resources/data_version_update.py index 86f333704..1de1588e3 100644 --- a/src/citrine/resources/data_version_update.py +++ b/src/citrine/resources/data_version_update.py @@ -1,5 +1,4 @@ """Record to hold branch data version update information.""" -from typing import List from citrine._rest.resource import PredictorRef, Resource from citrine._serialization import properties as properties diff --git a/src/citrine/resources/dataset.py b/src/citrine/resources/dataset.py index c846dc312..c656b8254 100644 --- a/src/citrine/resources/dataset.py +++ b/src/citrine/resources/dataset.py @@ -1,5 +1,5 @@ """Resources that represent both individual and collections of datasets.""" -from typing import List, Optional, Union, Tuple, Iterator, Iterable +from typing import Optional, Iterator, Iterable from uuid import UUID from gemd.entity.base_entity import BaseEntity diff --git a/src/citrine/resources/delete.py b/src/citrine/resources/delete.py index 91ac99876..15335bc56 100644 --- a/src/citrine/resources/delete.py +++ b/src/citrine/resources/delete.py @@ -1,5 +1,5 @@ import json -from typing import List, Union, Tuple, Optional +from typing import Optional from uuid import UUID from gemd.entity.base_entity import BaseEntity diff --git a/src/citrine/resources/descriptors.py b/src/citrine/resources/descriptors.py index c13952b5c..f5e9569f2 100644 --- a/src/citrine/resources/descriptors.py +++ b/src/citrine/resources/descriptors.py @@ -1,4 +1,3 @@ -from typing import List, Union from uuid import UUID from citrine._session import Session diff --git a/src/citrine/resources/design_execution.py b/src/citrine/resources/design_execution.py index 77bacddb3..35bdc461c 100644 --- a/src/citrine/resources/design_execution.py +++ b/src/citrine/resources/design_execution.py @@ -1,5 +1,5 @@ """Resources that represent both individual and collections of design workflow executions.""" -from typing import Optional, Union, Iterator +from typing import Optional, Iterator from uuid import UUID from citrine._rest.collection import Collection diff --git a/src/citrine/resources/design_space.py b/src/citrine/resources/design_space.py index c38c0eaaa..dfb4ae591 100644 --- a/src/citrine/resources/design_space.py +++ b/src/citrine/resources/design_space.py @@ -1,6 +1,6 @@ """Resources that represent collections of design spaces.""" from functools import partial -from typing import Iterable, Optional, Union +from typing import Iterable, Optional from uuid import UUID diff --git a/src/citrine/resources/design_workflow.py b/src/citrine/resources/design_workflow.py index a2963381b..cba53dd5e 100644 --- a/src/citrine/resources/design_workflow.py +++ b/src/citrine/resources/design_workflow.py @@ -1,5 +1,5 @@ from copy import deepcopy -from typing import Callable, Union, Iterable, Optional, Tuple +from typing import Callable, Iterable, Optional from uuid import UUID from citrine._rest.collection import Collection diff --git a/src/citrine/resources/experiment_datasource.py b/src/citrine/resources/experiment_datasource.py index adf075a4f..8c1fa1622 100644 --- a/src/citrine/resources/experiment_datasource.py +++ b/src/citrine/resources/experiment_datasource.py @@ -2,7 +2,7 @@ import json from functools import partial from io import StringIO -from typing import Dict, Iterator, Optional, Union +from typing import Iterator, Optional from uuid import UUID from citrine._rest.collection import Collection diff --git a/src/citrine/resources/file_link.py b/src/citrine/resources/file_link.py index b69214a14..fa99890b9 100644 --- a/src/citrine/resources/file_link.py +++ b/src/citrine/resources/file_link.py @@ -3,7 +3,7 @@ import os from pathlib import Path from tempfile import TemporaryDirectory -from typing import Optional, Tuple, Union, Dict, Iterable, Sequence +from typing import Optional, Iterable, Sequence from urllib.parse import urlparse from urllib.request import url2pathname from uuid import UUID diff --git a/src/citrine/resources/gemd_resource.py b/src/citrine/resources/gemd_resource.py index 86dbd85e4..7c4d63d50 100644 --- a/src/citrine/resources/gemd_resource.py +++ b/src/citrine/resources/gemd_resource.py @@ -1,6 +1,6 @@ """Collection class for generic GEMD objects and templates.""" import re -from typing import Type, Union, List, Tuple, Iterable +from typing import Iterable from uuid import UUID, uuid4 from gemd.entity.base_entity import BaseEntity diff --git a/src/citrine/resources/gemtables.py b/src/citrine/resources/gemtables.py index 18cb8d851..cf598c3f7 100644 --- a/src/citrine/resources/gemtables.py +++ b/src/citrine/resources/gemtables.py @@ -1,6 +1,6 @@ import json from logging import getLogger -from typing import Union, Iterable, Optional, Any, Tuple +from typing import Iterable, Optional, Any import requests diff --git a/src/citrine/resources/generative_design_execution.py b/src/citrine/resources/generative_design_execution.py index 06ed4b813..ac6ef0c86 100644 --- a/src/citrine/resources/generative_design_execution.py +++ b/src/citrine/resources/generative_design_execution.py @@ -1,5 +1,5 @@ """Resources that represent both individual and collections of design workflow executions.""" -from typing import Union, Iterator +from typing import Iterator from uuid import UUID from citrine._rest.collection import Collection diff --git a/src/citrine/resources/ingestion.py b/src/citrine/resources/ingestion.py index fca1ef0b8..360f94de9 100644 --- a/src/citrine/resources/ingestion.py +++ b/src/citrine/resources/ingestion.py @@ -1,4 +1,4 @@ -from typing import Optional, Union, Iterator, Iterable, Collection as TypingCollection +from typing import Optional, Iterator, Iterable, Collection as TypingCollection from uuid import UUID from gemd.enumeration.base_enumeration import BaseEnumeration diff --git a/src/citrine/resources/ingredient_run.py b/src/citrine/resources/ingredient_run.py index 6397fbce3..951fe663a 100644 --- a/src/citrine/resources/ingredient_run.py +++ b/src/citrine/resources/ingredient_run.py @@ -1,5 +1,5 @@ """Resources that represent ingredient run data objects.""" -from typing import List, Dict, Optional, Type, Iterator, Union +from typing import Optional, Iterator from uuid import UUID from citrine._rest.resource import GEMDResource diff --git a/src/citrine/resources/ingredient_spec.py b/src/citrine/resources/ingredient_spec.py index 846fbd568..4fccfe977 100644 --- a/src/citrine/resources/ingredient_spec.py +++ b/src/citrine/resources/ingredient_spec.py @@ -1,5 +1,5 @@ """Resources that represent ingredient spec data objects.""" -from typing import List, Dict, Optional, Type, Iterator, Union +from typing import Optional, Iterator from uuid import UUID from citrine._rest.resource import GEMDResource diff --git a/src/citrine/resources/material_run.py b/src/citrine/resources/material_run.py index 8aa91f122..a6ae1a0c8 100644 --- a/src/citrine/resources/material_run.py +++ b/src/citrine/resources/material_run.py @@ -1,5 +1,5 @@ """Resources that represent material run data objects.""" -from typing import List, Dict, Optional, Type, Iterator, Union +from typing import Optional, Iterator from uuid import UUID from citrine._rest.resource import GEMDResource diff --git a/src/citrine/resources/material_spec.py b/src/citrine/resources/material_spec.py index 57d689bc0..5158d932e 100644 --- a/src/citrine/resources/material_spec.py +++ b/src/citrine/resources/material_spec.py @@ -1,5 +1,5 @@ """Resources that represent material spec data objects.""" -from typing import List, Dict, Optional, Type, Iterator, Union +from typing import Optional, Iterator from uuid import UUID from citrine._rest.resource import GEMDResource diff --git a/src/citrine/resources/material_template.py b/src/citrine/resources/material_template.py index 79d9c3ecf..a6d764038 100644 --- a/src/citrine/resources/material_template.py +++ b/src/citrine/resources/material_template.py @@ -1,5 +1,5 @@ """Resources that represent material templates.""" -from typing import List, Dict, Optional, Union, Sequence, Type +from typing import Optional, Sequence from citrine._rest.resource import GEMDResource from citrine._serialization.properties import List as PropertyList diff --git a/src/citrine/resources/measurement_run.py b/src/citrine/resources/measurement_run.py index 36107c62a..8885ae32d 100644 --- a/src/citrine/resources/measurement_run.py +++ b/src/citrine/resources/measurement_run.py @@ -1,5 +1,5 @@ """Resources that represent measurement run data objects.""" -from typing import List, Dict, Optional, Type, Iterator, Union +from typing import Optional, Iterator from uuid import UUID from citrine._rest.resource import GEMDResource diff --git a/src/citrine/resources/measurement_spec.py b/src/citrine/resources/measurement_spec.py index 0f199eb67..a1f8f1596 100644 --- a/src/citrine/resources/measurement_spec.py +++ b/src/citrine/resources/measurement_spec.py @@ -1,5 +1,5 @@ """Resources that represent measurement spec data objects.""" -from typing import List, Dict, Optional, Type, Union, Iterator +from typing import Optional, Iterator from uuid import UUID from citrine._rest.resource import GEMDResource diff --git a/src/citrine/resources/measurement_template.py b/src/citrine/resources/measurement_template.py index d1b229135..f66630957 100644 --- a/src/citrine/resources/measurement_template.py +++ b/src/citrine/resources/measurement_template.py @@ -1,5 +1,5 @@ """Resources that represent measurement templates.""" -from typing import List, Dict, Optional, Union, Sequence, Type +from typing import Optional, Sequence from citrine._rest.resource import GEMDResource from citrine._serialization.properties import List as PropertyList diff --git a/src/citrine/resources/parameter_template.py b/src/citrine/resources/parameter_template.py index ae4a6ff0d..1fc33bab3 100644 --- a/src/citrine/resources/parameter_template.py +++ b/src/citrine/resources/parameter_template.py @@ -1,5 +1,5 @@ """Resources that represent parameter templates.""" -from typing import List, Dict, Optional, Type +from typing import Optional from citrine._rest.resource import GEMDResource from citrine.resources.attribute_templates import AttributeTemplate, AttributeTemplateCollection diff --git a/src/citrine/resources/predictor.py b/src/citrine/resources/predictor.py index c394e23a2..24839dd66 100644 --- a/src/citrine/resources/predictor.py +++ b/src/citrine/resources/predictor.py @@ -1,6 +1,6 @@ """Resources that represent collections of predictors.""" from functools import partial -from typing import Any, Iterable, Optional, Union, List +from typing import Any, Iterable, Optional from uuid import UUID from gemd.enumeration.base_enumeration import BaseEnumeration diff --git a/src/citrine/resources/predictor_evaluation.py b/src/citrine/resources/predictor_evaluation.py index 60b1a5845..df2250f33 100644 --- a/src/citrine/resources/predictor_evaluation.py +++ b/src/citrine/resources/predictor_evaluation.py @@ -1,5 +1,5 @@ from functools import partial -from typing import Iterable, Iterator, List, Optional, Union +from typing import Iterable, Iterator, List, Optional from uuid import UUID from citrine.informatics.executions.predictor_evaluation import PredictorEvaluation, \ diff --git a/src/citrine/resources/process_run.py b/src/citrine/resources/process_run.py index b0289421b..47e6f119e 100644 --- a/src/citrine/resources/process_run.py +++ b/src/citrine/resources/process_run.py @@ -1,5 +1,5 @@ """Resources that represent process run data objects.""" -from typing import List, Dict, Optional, Type, Union, Iterator +from typing import Optional, Iterator from uuid import UUID from citrine._rest.resource import GEMDResource diff --git a/src/citrine/resources/process_spec.py b/src/citrine/resources/process_spec.py index ce4839ee5..d4cc485bb 100644 --- a/src/citrine/resources/process_spec.py +++ b/src/citrine/resources/process_spec.py @@ -1,5 +1,5 @@ """Resources that represent process spec objects.""" -from typing import Optional, Dict, List, Type, Union, Iterator +from typing import Optional, Iterator from uuid import UUID from citrine._rest.resource import GEMDResource diff --git a/src/citrine/resources/process_template.py b/src/citrine/resources/process_template.py index e7eca81df..2f99c4f78 100644 --- a/src/citrine/resources/process_template.py +++ b/src/citrine/resources/process_template.py @@ -1,5 +1,5 @@ """Resources that represent process templates.""" -from typing import List, Dict, Optional, Union, Sequence, Type +from typing import Optional, Sequence from citrine._rest.resource import GEMDResource from citrine._serialization.properties import List as PropertyList diff --git a/src/citrine/resources/project.py b/src/citrine/resources/project.py index 3649e47f3..870f239c3 100644 --- a/src/citrine/resources/project.py +++ b/src/citrine/resources/project.py @@ -1,6 +1,6 @@ """Resources that represent both individual and collections of projects.""" from functools import partial -from typing import Optional, Dict, List, Union, Iterable, Iterator +from typing import Optional, Iterable, Iterator from uuid import UUID from citrine._rest.collection import Collection @@ -398,7 +398,7 @@ def list_archived(self, *, per_page: int = 1000) -> Iterable[Project]: """ return self._list_base(per_page=per_page, archived=True) - def search_all(self, search_params: Optional[Dict]) -> Iterable[Dict]: + def search_all(self, search_params: Optional[dict]) -> Iterable[dict]: """ Search across all projects in a domain. diff --git a/src/citrine/resources/property_template.py b/src/citrine/resources/property_template.py index deb1d3ce4..7a25e09fe 100644 --- a/src/citrine/resources/property_template.py +++ b/src/citrine/resources/property_template.py @@ -1,5 +1,5 @@ """Resources that represent property templates.""" -from typing import List, Dict, Optional, Type +from typing import Optional from citrine._rest.resource import GEMDResource from citrine.resources.attribute_templates import AttributeTemplate, AttributeTemplateCollection diff --git a/src/citrine/resources/report.py b/src/citrine/resources/report.py index 51ab14825..e5c2c8c6e 100644 --- a/src/citrine/resources/report.py +++ b/src/citrine/resources/report.py @@ -1,5 +1,5 @@ """A resource that represents a single module report.""" -from typing import Optional, Union +from typing import Optional from uuid import UUID from citrine._rest.resource import Resource diff --git a/src/citrine/resources/sample_design_space_execution.py b/src/citrine/resources/sample_design_space_execution.py index 24810c80e..055b6656e 100644 --- a/src/citrine/resources/sample_design_space_execution.py +++ b/src/citrine/resources/sample_design_space_execution.py @@ -1,5 +1,5 @@ """Resources that represent both individual and collections of sample design space executions.""" -from typing import Union, Iterator +from typing import Iterator from uuid import UUID from citrine._rest.collection import Collection diff --git a/src/citrine/resources/status_detail.py b/src/citrine/resources/status_detail.py index 5cfbfe7b5..197a7878c 100644 --- a/src/citrine/resources/status_detail.py +++ b/src/citrine/resources/status_detail.py @@ -1,4 +1,4 @@ -from typing import TypeVar, Union +from typing import TypeVar from citrine._serialization.serializable import Serializable from citrine._serialization import properties diff --git a/src/citrine/resources/table_config.py b/src/citrine/resources/table_config.py index 2336593df..dfb8c0a5d 100644 --- a/src/citrine/resources/table_config.py +++ b/src/citrine/resources/table_config.py @@ -1,5 +1,5 @@ from copy import copy -from typing import List, Union, Optional, Tuple +from typing import Optional from uuid import UUID from gemd.entity.object import MaterialRun @@ -94,7 +94,7 @@ class TableConfig(Resource["TableConfig"]): _resource_type = ResourceTypeEnum.TABLE_DEFINITION @staticmethod - def _get_dups(lst: List) -> List: + def _get_dups(lst: list) -> list: # Hmmn, this looks like a potentially costly operation?! return [x for x in lst if lst.count(x) > 1] diff --git a/src/citrine/resources/team.py b/src/citrine/resources/team.py index 64f52bd06..a185bb3d2 100644 --- a/src/citrine/resources/team.py +++ b/src/citrine/resources/team.py @@ -1,5 +1,5 @@ """Resources that represent both individual and collections of teams.""" -from typing import List, Optional, Tuple, Union +from typing import Optional, Union from uuid import UUID from gemd.entity.base_entity import BaseEntity From f0b90d535f80988ddc97f6f565ae5c9c138777be Mon Sep 17 00:00:00 2001 From: Austin Noto-Moniz Date: Tue, 17 Feb 2026 14:15:23 -0500 Subject: [PATCH 4/6] Import from collections.abc where appropriate. Many types introduced as type annotations in typing are now available for use from collections.abc. The typing versions are deprecated, so we switch to these newer versions. For us, this impacts Sequence, Iterator, Iterable, Callable, and (in one place) Collection. --- src/citrine/_rest/admin_collection.py | 2 +- src/citrine/_rest/collection.py | 3 ++- src/citrine/_rest/pageable.py | 3 ++- src/citrine/_rest/paginator.py | 3 ++- src/citrine/_session.py | 3 ++- src/citrine/_utils/batcher.py | 2 +- src/citrine/_utils/functions.py | 5 +++-- src/citrine/informatics/executions/design_execution.py | 2 +- .../executions/generative_design_execution.py | 2 +- .../executions/sample_design_space_execution.py | 3 ++- src/citrine/informatics/reports.py | 3 ++- src/citrine/resources/analysis_workflow.py | 3 ++- src/citrine/resources/branch.py | 3 ++- src/citrine/resources/data_concepts.py | 3 ++- src/citrine/resources/data_objects.py | 3 ++- src/citrine/resources/dataset.py | 3 ++- src/citrine/resources/design_execution.py | 3 ++- src/citrine/resources/design_space.py | 3 ++- src/citrine/resources/design_workflow.py | 3 ++- src/citrine/resources/experiment_datasource.py | 3 ++- src/citrine/resources/file_link.py | 3 ++- src/citrine/resources/gemd_resource.py | 2 +- src/citrine/resources/gemtables.py | 3 ++- src/citrine/resources/generative_design_execution.py | 2 +- src/citrine/resources/ingestion.py | 3 ++- src/citrine/resources/ingredient_run.py | 3 ++- src/citrine/resources/ingredient_spec.py | 3 ++- src/citrine/resources/material_run.py | 3 ++- src/citrine/resources/material_spec.py | 3 ++- src/citrine/resources/material_template.py | 3 ++- src/citrine/resources/measurement_run.py | 3 ++- src/citrine/resources/measurement_spec.py | 3 ++- src/citrine/resources/measurement_template.py | 3 ++- src/citrine/resources/predictor.py | 3 ++- src/citrine/resources/predictor_evaluation.py | 3 ++- src/citrine/resources/process_run.py | 3 ++- src/citrine/resources/process_spec.py | 3 ++- src/citrine/resources/process_template.py | 3 ++- src/citrine/resources/project.py | 3 ++- src/citrine/resources/sample_design_space_execution.py | 2 +- src/citrine/seeding/find_or_create.py | 9 +++++---- 41 files changed, 79 insertions(+), 45 deletions(-) diff --git a/src/citrine/_rest/admin_collection.py b/src/citrine/_rest/admin_collection.py index 1a74f71c5..6eeb5585f 100644 --- a/src/citrine/_rest/admin_collection.py +++ b/src/citrine/_rest/admin_collection.py @@ -1,5 +1,5 @@ +from collections.abc import Iterator from functools import partial -from typing import Iterator from citrine._rest.collection import Collection, ResourceType diff --git a/src/citrine/_rest/collection.py b/src/citrine/_rest/collection.py index d6b005ae1..1cb52d2d4 100644 --- a/src/citrine/_rest/collection.py +++ b/src/citrine/_rest/collection.py @@ -1,5 +1,6 @@ from abc import abstractmethod -from typing import Optional, Generic, TypeVar, Iterable, Iterator, Sequence +from collections.abc import Iterable, Iterator, Sequence +from typing import Generic, Optional, TypeVar from uuid import UUID from citrine._rest.pageable import Pageable diff --git a/src/citrine/_rest/pageable.py b/src/citrine/_rest/pageable.py index 81290cfeb..1d70eda61 100644 --- a/src/citrine/_rest/pageable.py +++ b/src/citrine/_rest/pageable.py @@ -1,4 +1,5 @@ -from typing import Optional, Iterable, Callable, Sequence +from collections.abc import Callable, Iterable, Sequence +from typing import Optional from uuid import UUID diff --git a/src/citrine/_rest/paginator.py b/src/citrine/_rest/paginator.py index 5385f9453..8dd828684 100644 --- a/src/citrine/_rest/paginator.py +++ b/src/citrine/_rest/paginator.py @@ -1,4 +1,5 @@ -from typing import TypeVar, Generic, Callable, Optional, Iterable, Any, Iterator +from collections.abc import Callable, Iterable, Iterator +from typing import Any, Generic, Optional, TypeVar from uuid import uuid4 ResourceType = TypeVar('ResourceType') diff --git a/src/citrine/_session.py b/src/citrine/_session.py index c403a574b..d271013eb 100644 --- a/src/citrine/_session.py +++ b/src/citrine/_session.py @@ -1,9 +1,10 @@ import platform +from collections.abc import Callable, Iterator from datetime import datetime, timedelta, timezone from json.decoder import JSONDecodeError from logging import getLogger from os import environ -from typing import Optional, Callable, Iterator +from typing import Optional from urllib.parse import urlunsplit import jwt diff --git a/src/citrine/_utils/batcher.py b/src/citrine/_utils/batcher.py index 449f26171..3de4e02f4 100644 --- a/src/citrine/_utils/batcher.py +++ b/src/citrine/_utils/batcher.py @@ -1,6 +1,6 @@ from abc import ABC, abstractmethod from collections import defaultdict -from typing import Iterable +from collections.abc import Iterable from citrine.resources.data_concepts import DataConcepts diff --git a/src/citrine/_utils/functions.py b/src/citrine/_utils/functions.py index 7949bdd06..bee770633 100644 --- a/src/citrine/_utils/functions.py +++ b/src/citrine/_utils/functions.py @@ -1,7 +1,8 @@ -from abc import ABCMeta import os +from abc import ABCMeta +from collections.abc import Sequence from pathlib import Path -from typing import Any, Optional, Sequence +from typing import Any, Optional from urllib.parse import quote, urlencode, urlparse from uuid import UUID from warnings import warn diff --git a/src/citrine/informatics/executions/design_execution.py b/src/citrine/informatics/executions/design_execution.py index 49d25bd28..383cecdfa 100644 --- a/src/citrine/informatics/executions/design_execution.py +++ b/src/citrine/informatics/executions/design_execution.py @@ -1,5 +1,5 @@ +from collections.abc import Iterable from functools import partial -from typing import Iterable from citrine._rest.paginator import Paginator from citrine._rest.resource import Resource diff --git a/src/citrine/informatics/executions/generative_design_execution.py b/src/citrine/informatics/executions/generative_design_execution.py index 694bea7a0..97b4a0e71 100644 --- a/src/citrine/informatics/executions/generative_design_execution.py +++ b/src/citrine/informatics/executions/generative_design_execution.py @@ -1,5 +1,5 @@ +from collections.abc import Iterable from functools import partial -from typing import Iterable from uuid import UUID from citrine._rest.resource import Resource diff --git a/src/citrine/informatics/executions/sample_design_space_execution.py b/src/citrine/informatics/executions/sample_design_space_execution.py index 6db97626b..eb7b9e364 100644 --- a/src/citrine/informatics/executions/sample_design_space_execution.py +++ b/src/citrine/informatics/executions/sample_design_space_execution.py @@ -1,5 +1,6 @@ +from collections.abc import Iterable from functools import partial -from typing import Optional, Iterable +from typing import Optional from uuid import UUID from citrine.informatics.executions.execution import Execution diff --git a/src/citrine/informatics/reports.py b/src/citrine/informatics/reports.py index dfab61810..0624c1dca 100644 --- a/src/citrine/informatics/reports.py +++ b/src/citrine/informatics/reports.py @@ -1,8 +1,9 @@ """Tools for working with reports.""" -from typing import TypeVar, Iterable, Any from abc import abstractmethod +from collections.abc import Iterable from itertools import groupby from logging import getLogger +from typing import Any, TypeVar from citrine._serialization import properties from citrine._serialization.polymorphic_serializable import PolymorphicSerializable diff --git a/src/citrine/resources/analysis_workflow.py b/src/citrine/resources/analysis_workflow.py index 817308ce7..ae410848b 100644 --- a/src/citrine/resources/analysis_workflow.py +++ b/src/citrine/resources/analysis_workflow.py @@ -1,5 +1,6 @@ import functools -from typing import Iterator, Optional +from collections.abc import Iterator +from typing import Optional from uuid import UUID from citrine.informatics.workflows.analysis_workflow import AnalysisWorkflow, \ diff --git a/src/citrine/resources/branch.py b/src/citrine/resources/branch.py index 1c88ed771..522c72cc8 100644 --- a/src/citrine/resources/branch.py +++ b/src/citrine/resources/branch.py @@ -1,5 +1,6 @@ import functools -from typing import Iterator, Optional +from collections.abc import Iterator +from typing import Optional from uuid import UUID from citrine._rest.collection import Collection diff --git a/src/citrine/resources/data_concepts.py b/src/citrine/resources/data_concepts.py index a8ecbd25d..459f0387d 100644 --- a/src/citrine/resources/data_concepts.py +++ b/src/citrine/resources/data_concepts.py @@ -1,7 +1,8 @@ """Top-level class for all data concepts objects and collections thereof.""" import re from abc import abstractmethod, ABC -from typing import Iterable, Iterator, List, Optional, TypeVar +from collections.abc import Iterable, Iterator +from typing import List, Optional, TypeVar from uuid import UUID, uuid4 from gemd.entity.dict_serializable import DictSerializable, DictSerializableMeta diff --git a/src/citrine/resources/data_objects.py b/src/citrine/resources/data_objects.py index fb981b4f8..1c1f420c3 100644 --- a/src/citrine/resources/data_objects.py +++ b/src/citrine/resources/data_objects.py @@ -1,6 +1,7 @@ """Top-level class for all data object (i.e., spec and run) objects and collections thereof.""" from abc import ABC -from typing import Optional, Iterator, TypeVar +from collections.abc import Iterator +from typing import Optional, TypeVar from uuid import uuid4 from gemd.json import GEMDJson diff --git a/src/citrine/resources/dataset.py b/src/citrine/resources/dataset.py index c656b8254..97e8ea14c 100644 --- a/src/citrine/resources/dataset.py +++ b/src/citrine/resources/dataset.py @@ -1,5 +1,6 @@ """Resources that represent both individual and collections of datasets.""" -from typing import Optional, Iterator, Iterable +from collections.abc import Iterator, Iterable +from typing import Optional from uuid import UUID from gemd.entity.base_entity import BaseEntity diff --git a/src/citrine/resources/design_execution.py b/src/citrine/resources/design_execution.py index 35bdc461c..ba3020c53 100644 --- a/src/citrine/resources/design_execution.py +++ b/src/citrine/resources/design_execution.py @@ -1,5 +1,6 @@ """Resources that represent both individual and collections of design workflow executions.""" -from typing import Optional, Iterator +from collections.abc import Iterator +from typing import Optional from uuid import UUID from citrine._rest.collection import Collection diff --git a/src/citrine/resources/design_space.py b/src/citrine/resources/design_space.py index dfb4ae591..ad98dd6c0 100644 --- a/src/citrine/resources/design_space.py +++ b/src/citrine/resources/design_space.py @@ -1,6 +1,7 @@ """Resources that represent collections of design spaces.""" +from collections.abc import Iterable from functools import partial -from typing import Iterable, Optional +from typing import Optional from uuid import UUID diff --git a/src/citrine/resources/design_workflow.py b/src/citrine/resources/design_workflow.py index cba53dd5e..94f3bf9a4 100644 --- a/src/citrine/resources/design_workflow.py +++ b/src/citrine/resources/design_workflow.py @@ -1,5 +1,6 @@ +from collections.abc import Callable, Iterable from copy import deepcopy -from typing import Callable, Iterable, Optional +from typing import Optional from uuid import UUID from citrine._rest.collection import Collection diff --git a/src/citrine/resources/experiment_datasource.py b/src/citrine/resources/experiment_datasource.py index 8c1fa1622..c945a605c 100644 --- a/src/citrine/resources/experiment_datasource.py +++ b/src/citrine/resources/experiment_datasource.py @@ -1,8 +1,9 @@ import csv import json +from typing import Iterator from functools import partial from io import StringIO -from typing import Iterator, Optional +from typing import Optional from uuid import UUID from citrine._rest.collection import Collection diff --git a/src/citrine/resources/file_link.py b/src/citrine/resources/file_link.py index fa99890b9..86981214c 100644 --- a/src/citrine/resources/file_link.py +++ b/src/citrine/resources/file_link.py @@ -1,9 +1,10 @@ """A collection of FileLink objects.""" import mimetypes import os +from collections.abc import Iterable, Sequence from pathlib import Path from tempfile import TemporaryDirectory -from typing import Optional, Iterable, Sequence +from typing import Optional from urllib.parse import urlparse from urllib.request import url2pathname from uuid import UUID diff --git a/src/citrine/resources/gemd_resource.py b/src/citrine/resources/gemd_resource.py index 7c4d63d50..b364b6302 100644 --- a/src/citrine/resources/gemd_resource.py +++ b/src/citrine/resources/gemd_resource.py @@ -1,6 +1,6 @@ """Collection class for generic GEMD objects and templates.""" import re -from typing import Iterable +from collections.abc import Iterable from uuid import UUID, uuid4 from gemd.entity.base_entity import BaseEntity diff --git a/src/citrine/resources/gemtables.py b/src/citrine/resources/gemtables.py index cf598c3f7..03b657dc5 100644 --- a/src/citrine/resources/gemtables.py +++ b/src/citrine/resources/gemtables.py @@ -1,6 +1,7 @@ import json +from collections.abc import Iterable from logging import getLogger -from typing import Iterable, Optional, Any +from typing import Any, Optional import requests diff --git a/src/citrine/resources/generative_design_execution.py b/src/citrine/resources/generative_design_execution.py index ac6ef0c86..3330f82fb 100644 --- a/src/citrine/resources/generative_design_execution.py +++ b/src/citrine/resources/generative_design_execution.py @@ -1,5 +1,5 @@ """Resources that represent both individual and collections of design workflow executions.""" -from typing import Iterator +from collections.abc import Iterator from uuid import UUID from citrine._rest.collection import Collection diff --git a/src/citrine/resources/ingestion.py b/src/citrine/resources/ingestion.py index 360f94de9..c330eb1bc 100644 --- a/src/citrine/resources/ingestion.py +++ b/src/citrine/resources/ingestion.py @@ -1,4 +1,5 @@ -from typing import Optional, Iterator, Iterable, Collection as TypingCollection +from collections.abc import Collection as TypingCollection, Iterator, Iterable +from typing import Optional from uuid import UUID from gemd.enumeration.base_enumeration import BaseEnumeration diff --git a/src/citrine/resources/ingredient_run.py b/src/citrine/resources/ingredient_run.py index 951fe663a..0ed87483a 100644 --- a/src/citrine/resources/ingredient_run.py +++ b/src/citrine/resources/ingredient_run.py @@ -1,5 +1,6 @@ """Resources that represent ingredient run data objects.""" -from typing import Optional, Iterator +from collections.abc import Iterator +from typing import Optional from uuid import UUID from citrine._rest.resource import GEMDResource diff --git a/src/citrine/resources/ingredient_spec.py b/src/citrine/resources/ingredient_spec.py index 4fccfe977..f8c0db06a 100644 --- a/src/citrine/resources/ingredient_spec.py +++ b/src/citrine/resources/ingredient_spec.py @@ -1,5 +1,6 @@ """Resources that represent ingredient spec data objects.""" -from typing import Optional, Iterator +from collections.abc import Iterator +from typing import Optional from uuid import UUID from citrine._rest.resource import GEMDResource diff --git a/src/citrine/resources/material_run.py b/src/citrine/resources/material_run.py index a6ae1a0c8..329d7b8d7 100644 --- a/src/citrine/resources/material_run.py +++ b/src/citrine/resources/material_run.py @@ -1,5 +1,6 @@ """Resources that represent material run data objects.""" -from typing import Optional, Iterator +from collections.abc import Iterator +from typing import Optional from uuid import UUID from citrine._rest.resource import GEMDResource diff --git a/src/citrine/resources/material_spec.py b/src/citrine/resources/material_spec.py index 5158d932e..d0adbf4a3 100644 --- a/src/citrine/resources/material_spec.py +++ b/src/citrine/resources/material_spec.py @@ -1,5 +1,6 @@ """Resources that represent material spec data objects.""" -from typing import Optional, Iterator +from collections.abc import Iterator +from typing import Optional from uuid import UUID from citrine._rest.resource import GEMDResource diff --git a/src/citrine/resources/material_template.py b/src/citrine/resources/material_template.py index a6d764038..fc85e066c 100644 --- a/src/citrine/resources/material_template.py +++ b/src/citrine/resources/material_template.py @@ -1,5 +1,6 @@ """Resources that represent material templates.""" -from typing import Optional, Sequence +from typing import Optional +from collections.abc import Sequence from citrine._rest.resource import GEMDResource from citrine._serialization.properties import List as PropertyList diff --git a/src/citrine/resources/measurement_run.py b/src/citrine/resources/measurement_run.py index 8885ae32d..b6c620e8d 100644 --- a/src/citrine/resources/measurement_run.py +++ b/src/citrine/resources/measurement_run.py @@ -1,5 +1,6 @@ """Resources that represent measurement run data objects.""" -from typing import Optional, Iterator +from collections.abc import Iterator +from typing import Optional from uuid import UUID from citrine._rest.resource import GEMDResource diff --git a/src/citrine/resources/measurement_spec.py b/src/citrine/resources/measurement_spec.py index a1f8f1596..048e71ddf 100644 --- a/src/citrine/resources/measurement_spec.py +++ b/src/citrine/resources/measurement_spec.py @@ -1,5 +1,6 @@ """Resources that represent measurement spec data objects.""" -from typing import Optional, Iterator +from collections.abc import Iterator +from typing import Optional from uuid import UUID from citrine._rest.resource import GEMDResource diff --git a/src/citrine/resources/measurement_template.py b/src/citrine/resources/measurement_template.py index f66630957..55f606782 100644 --- a/src/citrine/resources/measurement_template.py +++ b/src/citrine/resources/measurement_template.py @@ -1,5 +1,6 @@ """Resources that represent measurement templates.""" -from typing import Optional, Sequence +from typing import Optional +from collections.abc import Sequence from citrine._rest.resource import GEMDResource from citrine._serialization.properties import List as PropertyList diff --git a/src/citrine/resources/predictor.py b/src/citrine/resources/predictor.py index 24839dd66..f4e113b6f 100644 --- a/src/citrine/resources/predictor.py +++ b/src/citrine/resources/predictor.py @@ -1,6 +1,7 @@ """Resources that represent collections of predictors.""" +from collections.abc import Iterable from functools import partial -from typing import Any, Iterable, Optional +from typing import Any, Optional from uuid import UUID from gemd.enumeration.base_enumeration import BaseEnumeration diff --git a/src/citrine/resources/predictor_evaluation.py b/src/citrine/resources/predictor_evaluation.py index df2250f33..f25cd828e 100644 --- a/src/citrine/resources/predictor_evaluation.py +++ b/src/citrine/resources/predictor_evaluation.py @@ -1,5 +1,6 @@ +from collections.abc import Iterable, Iterator from functools import partial -from typing import Iterable, Iterator, List, Optional +from typing import List, Optional from uuid import UUID from citrine.informatics.executions.predictor_evaluation import PredictorEvaluation, \ diff --git a/src/citrine/resources/process_run.py b/src/citrine/resources/process_run.py index 47e6f119e..fd7cf0622 100644 --- a/src/citrine/resources/process_run.py +++ b/src/citrine/resources/process_run.py @@ -1,5 +1,6 @@ """Resources that represent process run data objects.""" -from typing import Optional, Iterator +from collections.abc import Iterator +from typing import Optional from uuid import UUID from citrine._rest.resource import GEMDResource diff --git a/src/citrine/resources/process_spec.py b/src/citrine/resources/process_spec.py index d4cc485bb..b56bee6ac 100644 --- a/src/citrine/resources/process_spec.py +++ b/src/citrine/resources/process_spec.py @@ -1,5 +1,6 @@ """Resources that represent process spec objects.""" -from typing import Optional, Iterator +from collections.abc import Iterator +from typing import Optional from uuid import UUID from citrine._rest.resource import GEMDResource diff --git a/src/citrine/resources/process_template.py b/src/citrine/resources/process_template.py index 2f99c4f78..e16c3857a 100644 --- a/src/citrine/resources/process_template.py +++ b/src/citrine/resources/process_template.py @@ -1,5 +1,6 @@ """Resources that represent process templates.""" -from typing import Optional, Sequence +from typing import Optional +from collections.abc import Sequence from citrine._rest.resource import GEMDResource from citrine._serialization.properties import List as PropertyList diff --git a/src/citrine/resources/project.py b/src/citrine/resources/project.py index 870f239c3..ebb7be0f4 100644 --- a/src/citrine/resources/project.py +++ b/src/citrine/resources/project.py @@ -1,6 +1,7 @@ """Resources that represent both individual and collections of projects.""" +from collections.abc import Iterable, Iterator from functools import partial -from typing import Optional, Iterable, Iterator +from typing import Optional from uuid import UUID from citrine._rest.collection import Collection diff --git a/src/citrine/resources/sample_design_space_execution.py b/src/citrine/resources/sample_design_space_execution.py index 055b6656e..033baf1dc 100644 --- a/src/citrine/resources/sample_design_space_execution.py +++ b/src/citrine/resources/sample_design_space_execution.py @@ -1,5 +1,5 @@ """Resources that represent both individual and collections of sample design space executions.""" -from typing import Iterator +from collections.abc import Iterator from uuid import UUID from citrine._rest.collection import Collection diff --git a/src/citrine/seeding/find_or_create.py b/src/citrine/seeding/find_or_create.py index b8ff71a69..71863f42a 100644 --- a/src/citrine/seeding/find_or_create.py +++ b/src/citrine/seeding/find_or_create.py @@ -1,12 +1,13 @@ +from collections.abc import Callable from copy import deepcopy from logging import getLogger -from typing import TypeVar, Optional, Callable +from typing import Optional, TypeVar from citrine.exceptions import NotFound -from citrine.resources.team import TeamCollection, Team -from citrine.resources.project import ProjectCollection, Project -from citrine.resources.dataset import DatasetCollection, Dataset from citrine.informatics.workflows.design_workflow import DesignWorkflow +from citrine.resources.dataset import DatasetCollection, Dataset +from citrine.resources.project import ProjectCollection, Project +from citrine.resources.team import TeamCollection, Team from citrine._rest.collection import CreationType, Collection logger = getLogger(__name__) From 001596fb8b3ed9728fde0e8258ad7a38eb9ef1e4 Mon Sep 17 00:00:00 2001 From: Austin Noto-Moniz Date: Tue, 17 Feb 2026 15:03:43 -0500 Subject: [PATCH 5/6] dict update operator --- src/citrine/resources/ingestion.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/citrine/resources/ingestion.py b/src/citrine/resources/ingestion.py index c330eb1bc..db14f2ca0 100644 --- a/src/citrine/resources/ingestion.py +++ b/src/citrine/resources/ingestion.py @@ -521,7 +521,7 @@ def build_from_file_links(self, def build(self, data: dict) -> Ingestion: """Build an instance of an Ingestion.""" - result = Ingestion.build({**data, "session": self.session}) + result = Ingestion.build(data | {"session": self.session}) return result def register(self, model: Ingestion) -> Ingestion: From 2e5852f89687ccc5026761d7fe159145601306fc Mon Sep 17 00:00:00 2001 From: Austin Noto-Moniz Date: Wed, 18 Feb 2026 13:19:50 -0500 Subject: [PATCH 6/6] PR adjustments --- src/citrine/_rest/ai_resource_metadata.py | 14 +- src/citrine/_rest/asynchronous_object.py | 5 +- src/citrine/_rest/collection.py | 4 +- src/citrine/_rest/engine_resource.py | 14 +- src/citrine/_rest/pageable.py | 23 ++-- src/citrine/_rest/paginator.py | 8 +- src/citrine/_rest/resource.py | 6 +- src/citrine/_serialization/properties.py | 122 +++++++++--------- src/citrine/_session.py | 7 +- src/citrine/_utils/batcher.py | 10 +- src/citrine/_utils/functions.py | 14 +- src/citrine/_utils/template_util.py | 12 +- src/citrine/citrine.py | 5 +- src/citrine/exceptions.py | 3 +- src/citrine/gemd_queries/criteria.py | 6 +- src/citrine/gemtables/columns.py | 13 +- src/citrine/gemtables/variables.py | 19 ++- src/citrine/informatics/catalyst/assistant.py | 6 +- src/citrine/informatics/catalyst/insights.py | 10 +- .../constraints/categorical_constraint.py | 1 - .../ingredient_count_constraint.py | 8 +- .../ingredient_ratio_constraint.py | 18 ++- .../constraints/integer_range_constraint.py | 6 +- .../constraints/scalar_range_constraint.py | 10 +- src/citrine/informatics/design_candidate.py | 12 +- .../design_spaces/design_space_settings.py | 15 +-- .../design_spaces/formulation_design_space.py | 8 +- .../hierarchical_design_space.py | 43 +++--- .../design_spaces/product_design_space.py | 6 +- .../design_spaces/top_level_design_space.py | 11 +- src/citrine/informatics/dimensions.py | 9 +- .../informatics/executions/execution.py | 17 ++- .../executions/predictor_evaluation.py | 7 +- .../sample_design_space_execution.py | 5 +- src/citrine/informatics/experiment_values.py | 1 - src/citrine/informatics/generative_design.py | 5 +- src/citrine/informatics/predict_request.py | 3 +- .../predictor_evaluation_result.py | 3 +- .../informatics/predictor_evaluator.py | 20 ++- .../attribute_accumulation_predictor.py | 1 - .../predictors/auto_ml_predictor.py | 6 +- .../predictors/chemical_formula_featurizer.py | 13 +- .../predictors/expression_predictor.py | 7 +- .../informatics/predictors/graph_predictor.py | 11 +- .../ingredient_fractions_predictor.py | 1 - .../ingredients_to_formulation_predictor.py | 13 +- .../predictors/label_fractions_predictor.py | 1 - .../predictors/mean_property_predictor.py | 14 +- .../molecular_structure_featurizer.py | 5 +- src/citrine/informatics/predictors/node.py | 1 - .../predictors/single_predict_request.py | 3 +- src/citrine/informatics/reports.py | 4 +- src/citrine/informatics/scores.py | 7 +- .../workflows/analysis_workflow.py | 7 +- .../informatics/workflows/design_workflow.py | 34 +++-- src/citrine/informatics/workflows/workflow.py | 9 +- src/citrine/jobs/job.py | 2 +- src/citrine/jobs/waiting.py | 2 +- src/citrine/resources/_default_labels.py | 6 +- src/citrine/resources/analysis_workflow.py | 5 +- src/citrine/resources/attribute_templates.py | 5 +- src/citrine/resources/audit_info.py | 8 +- src/citrine/resources/branch.py | 19 ++- src/citrine/resources/condition_template.py | 7 +- src/citrine/resources/data_concepts.py | 30 ++--- src/citrine/resources/data_objects.py | 14 +- src/citrine/resources/dataset.py | 15 +-- src/citrine/resources/delete.py | 5 +- src/citrine/resources/design_execution.py | 5 +- src/citrine/resources/design_space.py | 11 +- src/citrine/resources/design_workflow.py | 17 ++- .../resources/experiment_datasource.py | 9 +- src/citrine/resources/file_link.py | 35 +++-- src/citrine/resources/gemtables.py | 8 +- src/citrine/resources/ingestion.py | 35 +++-- src/citrine/resources/ingredient_run.py | 49 +++---- src/citrine/resources/ingredient_spec.py | 46 +++---- src/citrine/resources/material_run.py | 34 ++--- src/citrine/resources/material_spec.py | 47 ++----- src/citrine/resources/material_template.py | 32 ++--- src/citrine/resources/measurement_run.py | 41 +++--- src/citrine/resources/measurement_spec.py | 30 ++--- src/citrine/resources/measurement_template.py | 82 +++++------- src/citrine/resources/object_templates.py | 4 +- src/citrine/resources/parameter_template.py | 7 +- src/citrine/resources/predictor.py | 20 +-- src/citrine/resources/predictor_evaluation.py | 20 +-- src/citrine/resources/process_run.py | 29 ++--- src/citrine/resources/process_spec.py | 28 ++-- src/citrine/resources/process_template.py | 68 ++++------ src/citrine/resources/project.py | 23 ++-- src/citrine/resources/property_template.py | 7 +- src/citrine/resources/report.py | 3 +- src/citrine/resources/table_config.py | 37 +++--- src/citrine/resources/team.py | 6 +- src/citrine/resources/user.py | 7 +- src/citrine/seeding/find_or_create.py | 4 +- 97 files changed, 661 insertions(+), 847 deletions(-) diff --git a/src/citrine/_rest/ai_resource_metadata.py b/src/citrine/_rest/ai_resource_metadata.py index 62e02fb08..5ff56e6d0 100644 --- a/src/citrine/_rest/ai_resource_metadata.py +++ b/src/citrine/_rest/ai_resource_metadata.py @@ -6,27 +6,27 @@ class AIResourceMetadata(): """Abstract class for representing common metadata for Resources.""" created_by = properties.Optional(properties.UUID, 'created_by', serializable=False) - """:Optional[UUID]: id of the user who created the resource""" + """:UUID | None: id of the user who created the resource""" create_time = properties.Optional(properties.Datetime, 'create_time', serializable=False) - """:Optional[datetime]: date and time at which the resource was created""" + """:datetime | None: date and time at which the resource was created""" updated_by = properties.Optional(properties.UUID, 'updated_by', serializable=False) - """:Optional[UUID]: id of the user who most recently updated the resource, + """:UUID | None: id of the user who most recently updated the resource, if it has been updated""" update_time = properties.Optional(properties.Datetime, 'update_time', serializable=False) - """:Optional[datetime]: date and time at which the resource was most recently updated, + """:datetime | None: date and time at which the resource was most recently updated, if it has been updated""" archived = properties.Boolean('archived', default=False) """:bool: whether the resource is archived (hidden but not deleted)""" archived_by = properties.Optional(properties.UUID, 'archived_by', serializable=False) - """:Optional[UUID]: id of the user who archived the resource, if it has been archived""" + """:UUID | None: id of the user who archived the resource, if it has been archived""" archive_time = properties.Optional(properties.Datetime, 'archive_time', serializable=False) - """:Optional[datetime]: date and time at which the resource was archived, + """:datetime | None: date and time at which the resource was archived, if it has been archived""" status = properties.Optional(properties.String(), 'status', serializable=False) - """:Optional[str]: short description of the resource's status""" + """:str | None: short description of the resource's status""" status_detail = properties.List(properties.Object(StatusDetail), 'status_detail', default=[], serializable=False) """:list[StatusDetail]: a list of structured status info, containing the message and level""" diff --git a/src/citrine/_rest/asynchronous_object.py b/src/citrine/_rest/asynchronous_object.py index b54480ae6..bc97e7a67 100644 --- a/src/citrine/_rest/asynchronous_object.py +++ b/src/citrine/_rest/asynchronous_object.py @@ -1,6 +1,3 @@ -from typing import Optional - - class AsynchronousObject: """Abstract class for objects that are asynchronously populated.""" @@ -8,7 +5,7 @@ class AsynchronousObject: _succeeded_statuses = [] # list of statuses that indicate 'succeeded' _failed_statuses = [] # list of statuses that indicate 'failed' - def _fetch_status(self) -> Optional[str]: + def _fetch_status(self) -> str | None: """Fetch the status of the resource. This is is the `status` attribute by default, but can be overridden if the status diff --git a/src/citrine/_rest/collection.py b/src/citrine/_rest/collection.py index 1cb52d2d4..770bfcf60 100644 --- a/src/citrine/_rest/collection.py +++ b/src/citrine/_rest/collection.py @@ -1,6 +1,6 @@ from abc import abstractmethod from collections.abc import Iterable, Iterator, Sequence -from typing import Generic, Optional, TypeVar +from typing import Generic, TypeVar from uuid import UUID from citrine._rest.pageable import Pageable @@ -30,7 +30,7 @@ class Collection(Generic[ResourceType], Pageable): _api_version: str = "v1" def _get_path(self, - uid: Optional[UUID | str] = None, + uid: UUID | str | None = None, *, ignore_dataset: bool = False, action: str | Sequence[str] = [], diff --git a/src/citrine/_rest/engine_resource.py b/src/citrine/_rest/engine_resource.py index 8957ffd57..d9058ca53 100644 --- a/src/citrine/_rest/engine_resource.py +++ b/src/citrine/_rest/engine_resource.py @@ -12,26 +12,26 @@ class EngineResourceWithoutStatus(Resource[Self]): """Base resource for metadata from stand-alone AI Engine modules.""" created_by = properties.Optional(properties.UUID, 'metadata.created.user', serializable=False) - """:Optional[UUID]: id of the user who created the resource""" + """:UUID | None: id of the user who created the resource""" create_time = properties.Optional(properties.Datetime, 'metadata.created.time', serializable=False) - """:Optional[datetime]: date and time at which the resource was created""" + """:datetime | None: date and time at which the resource was created""" updated_by = properties.Optional(properties.UUID, 'metadata.updated.user', serializable=False) - """:Optional[UUID]: id of the user who most recently updated the resource, + """:UUID | None: id of the user who most recently updated the resource, if it has been updated""" update_time = properties.Optional(properties.Datetime, 'metadata.updated.time', serializable=False) - """:Optional[datetime]: date and time at which the resource was most recently updated, + """:datetime | None: date and time at which the resource was most recently updated, if it has been updated""" archived_by = properties.Optional(properties.UUID, 'metadata.archived.user', serializable=False) - """:Optional[UUID]: id of the user who archived the resource, if it has been archived""" + """:UUID | None: id of the user who archived the resource, if it has been archived""" archive_time = properties.Optional(properties.Datetime, 'metadata.archived.time', serializable=False) - """:Optional[datetime]: date and time at which the resource was archived, + """:datetime | None: date and time at which the resource was archived, if it has been archived""" _resource_type = ResourceTypeEnum.MODULE @@ -60,7 +60,7 @@ class EngineResource(EngineResourceWithoutStatus[Self], IncludeParentProperties[ """Base resource for metadata from stand-alone AI Engine modules.""" status = properties.Optional(properties.String(), 'metadata.status.name', serializable=False) - """:Optional[str]: short description of the resource's status""" + """:str | None: short description of the resource's status""" status_detail = properties.List(properties.Object(StatusDetail), 'metadata.status.detail', default=[], serializable=False) """:list[StatusDetail]: a list of structured status info, containing the message and level""" diff --git a/src/citrine/_rest/pageable.py b/src/citrine/_rest/pageable.py index 1d70eda61..7fbe9ee38 100644 --- a/src/citrine/_rest/pageable.py +++ b/src/citrine/_rest/pageable.py @@ -1,5 +1,4 @@ from collections.abc import Callable, Iterable, Sequence -from typing import Optional from uuid import UUID @@ -10,7 +9,7 @@ class Pageable(): _api_version: str = "v1" def _get_path(self, - uid: Optional[UUID | str] = None, + uid: UUID | str | None = None, *, ignore_dataset: bool = False, action: str | Sequence[str] = [], @@ -20,14 +19,14 @@ def _get_path(self, raise NotImplementedError # pragma: no cover def _fetch_page(self, - path: Optional[str] = None, - fetch_func: Optional[Callable[..., dict]] = None, - page: Optional[int] = None, - per_page: Optional[int] = None, - json_body: Optional[dict] = None, - additional_params: Optional[dict] = None, + path: str | None = None, + fetch_func: Callable[..., dict] | None = None, + page: int | None = None, + per_page: int | None = None, + json_body: dict | None = None, + additional_params: dict | None = None, *, - version: Optional[str] = None + version: str | None = None ) -> tuple[Iterable[dict], str]: """ Fetch visible elements. This does not handle pagination. @@ -101,9 +100,9 @@ def _fetch_page(self, return collection, next_uri def _page_params(self, - page: Optional[int], - per_page: Optional[int], - module_type: Optional[str] = None) -> dict[str, int]: + page: int | None, + per_page: int | None, + module_type: str | None = None) -> dict[str, int]: params = {} if page is not None: params["page"] = page diff --git a/src/citrine/_rest/paginator.py b/src/citrine/_rest/paginator.py index 8dd828684..f912e0b61 100644 --- a/src/citrine/_rest/paginator.py +++ b/src/citrine/_rest/paginator.py @@ -1,5 +1,5 @@ from collections.abc import Callable, Iterable, Iterator -from typing import Any, Generic, Optional, TypeVar +from typing import Any, Generic, TypeVar from uuid import uuid4 ResourceType = TypeVar('ResourceType') @@ -14,10 +14,10 @@ class Paginator(Generic[ResourceType]): """ def paginate(self, - page_fetcher: Callable[[Optional[int], int], tuple[Iterable[dict], str]], + page_fetcher: Callable[[int | None, int], tuple[Iterable[dict], str]], collection_builder: Callable[[Iterable[dict]], Iterable[ResourceType]], per_page: int = 100, - search_params: Optional[dict] = None, + search_params: dict | None = None, deduplicate: bool = True) -> Iterator[ResourceType]: """ A generic support class to paginate requests into an iterable of a built object. @@ -30,7 +30,7 @@ def paginate(self, Parameters --------- - page_fetcher: Callable[[Optional[int], int], tuple[Iterable[dict], str]] + page_fetcher: Callable[[int | None, int], tuple[Iterable[dict], str]] Fetches the next page of elements collection_builder: Callable[[Iterable[dict]], Iterable[ResourceType]] Builds each element in the collection into the appropriate resource diff --git a/src/citrine/_rest/resource.py b/src/citrine/_rest/resource.py index a83d6905b..e3fc0e882 100644 --- a/src/citrine/_rest/resource.py +++ b/src/citrine/_rest/resource.py @@ -1,4 +1,4 @@ -from typing import TypeVar, Optional +from typing import TypeVar from uuid import UUID from citrine._serialization.serializable import Serializable @@ -37,7 +37,7 @@ class Resource(Serializable[Self]): """Abstract class for representing individual REST resource.""" _path_template: str = NotImplemented - _response_key: Optional[str] = None + _response_key: str | None = None _resource_type: ResourceTypeEnum = NotImplemented def access_control_dict(self) -> dict: @@ -100,6 +100,6 @@ class PredictorRef(Serializable['PredictorRef']): 'predictor_version' ) - def __init__(self, uid: UUID | str, version: Optional[int | str] = None): + def __init__(self, uid: UUID | str, version: int | str | None = None): self.uid = uid self.version = version diff --git a/src/citrine/_serialization/properties.py b/src/citrine/_serialization/properties.py index d7be5e14d..95d8aa81f 100644 --- a/src/citrine/_serialization/properties.py +++ b/src/citrine/_serialization/properties.py @@ -1,13 +1,15 @@ """Property objects for typed setting and ser/de.""" +import re +import uuid from abc import abstractmethod -import typing +from collections.abc import Iterable, Sequence from datetime import datetime +from functools import lru_cache from inspect import signature from itertools import chain -import uuid +from typing import Any, Generic, TypeVar + import arrow -from functools import lru_cache -import re from gemd.enumeration.base_enumeration import BaseEnumeration from gemd.entity.link_by_uid import LinkByUID @@ -17,13 +19,13 @@ from citrine._serialization.serializable import Serializable from citrine._serialization.polymorphic_serializable import PolymorphicSerializable -SerializedType = typing.TypeVar('SerializedType') -DeserializedType = typing.TypeVar('DeserializedType') -SerializedInteger = typing.TypeVar('SerializedInteger', int, str) -SerializedFloat = typing.TypeVar('SerializedFloat', float, str) +SerializedType = TypeVar('SerializedType') +DeserializedType = TypeVar('DeserializedType') +SerializedInteger = TypeVar('SerializedInteger', int, str) +SerializedFloat = TypeVar('SerializedFloat', float, str) -class Property(typing.Generic[DeserializedType, SerializedType]): +class Property(Generic[DeserializedType, SerializedType]): """ Basic operating unit of a serialization layer. @@ -52,11 +54,11 @@ class Property(typing.Generic[DeserializedType, SerializedType]): """ def __init__(self, - serialization_path: typing.Optional[str] = None, + serialization_path: str | None = None, *, serializable: bool = True, deserializable: bool = True, - default: typing.Optional[DeserializedType] = None, + default: DeserializedType | None = None, override: bool = False, use_init: bool = False ): @@ -67,19 +69,19 @@ def __init__(self, self._key: str = '__' + str(uuid.uuid4()) # Make this object key human-readable self.serializable: bool = serializable self.deserializable: bool = deserializable - self.default: typing.Optional[DeserializedType] = default + self.default: DeserializedType | None = default # Distinguish between no default being provided and the default being None self.optional: bool = False self.use_init: bool = use_init @property @abstractmethod - def underlying_types(self) -> DeserializedType | tuple[DeserializedType]: + def underlying_types(self) -> DeserializedType | tuple[DeserializedType, ...]: """Return the python types handled by this property.""" @property @abstractmethod - def serialized_types(self) -> SerializedType | tuple[SerializedType]: + def serialized_types(self) -> SerializedType | tuple[SerializedType, ...]: """Return the types used to serialize this property.""" def _error_source(self, base_class: type) -> str: @@ -92,7 +94,7 @@ def _error_source(self, base_class: type) -> str: return '' def serialize(self, value: DeserializedType, - base_class: typing.Optional[type] = None) -> SerializedType: + base_class: type | None = None) -> SerializedType: if not isinstance(value, self.underlying_types): base_name = self._error_source(base_class) raise ValueError( @@ -102,7 +104,7 @@ def serialize(self, value: DeserializedType, return self._serialize(value) def deserialize(self, value: SerializedType, - base_class: typing.Optional[type] = None) -> DeserializedType: + base_class: type | None = None) -> DeserializedType: if not isinstance(value, self.serialized_types): if isinstance(value, self.underlying_types): return value # Don't worry if it was already deserialized @@ -240,8 +242,8 @@ def _set_elements(self, value: SerializedType | DeserializedType): @lru_cache(maxsize=1024) -def _get_key_and_base_class(prop: Property, klass: typing.Any) -> \ - tuple[typing.Optional[str], typing.Optional[str]]: +def _get_key_and_base_class(prop: Property, klass: Any) -> \ + tuple[str | None, str | None]: """ Return the base class and class attribute name for the object and property. @@ -307,7 +309,7 @@ def __str__(self): return ''.format(self.serialization_path) -class Raw(Property[typing.Any, typing.Any]): +class Raw(Property[Any, Any]): @property def underlying_types(self): @@ -318,11 +320,11 @@ def serialized_types(self): return object @classmethod - def _deserialize(cls, value: typing.Any) -> typing.Any: + def _deserialize(cls, value: Any) -> Any: return value @classmethod - def _serialize(cls, value: typing.Any) -> typing.Any: + def _serialize(cls, value: Any) -> Any: return value def __str__(self): @@ -416,11 +418,11 @@ class List(PropertyCollection[list, list]): def __init__(self, element_type: Property | type[Property], - serialization_path: typing.Optional[str] = None, + serialization_path: str | None = None, *, serializable: bool = True, deserializable: bool = True, - default: typing.Optional[DeserializedType] = None, + default: DeserializedType | None = None, override: bool = False, use_init: bool = False ): @@ -466,15 +468,15 @@ def _set_elements(self, value): return elems -class Set(PropertyCollection[set, typing.Iterable]): +class Set(PropertyCollection[set, Iterable]): def __init__(self, element_type: Property | type[Property], - serialization_path: typing.Optional[str] = None, + serialization_path: str | None = None, *, serializable: bool = True, deserializable: bool = True, - default: typing.Optional[DeserializedType] = None, + default: DeserializedType | None = None, override: bool = False, use_init: bool = False ): @@ -492,9 +494,9 @@ def underlying_types(self): @property def serialized_types(self): - return typing.Iterable + return Iterable - def _deserialize(self, value: typing.Iterable) -> set: + def _deserialize(self, value: Iterable) -> set: deserialized = set() for element in value: deserialized.add(self.element_type.deserialize(element)) @@ -522,7 +524,7 @@ def _set_elements(self, value): return elems -class Union(Property[typing.Any, typing.Any]): +class Union(Property[Any, Any]): """ One of several possible property types. @@ -530,12 +532,12 @@ class Union(Property[typing.Any, typing.Any]): """ def __init__(self, - element_types: typing.Sequence[Property | type[Property]], - serialization_path: typing.Optional[str] = None, + element_types: Sequence[Property | type[Property]], + serialization_path: str | None = None, *, serializable: bool = True, deserializable: bool = True, - default: typing.Optional[DeserializedType] = None, + default: DeserializedType | None = None, override: bool = False, use_init: bool = False ): @@ -545,7 +547,7 @@ def __init__(self, default=default, override=override, use_init=use_init) - if not isinstance(element_types, typing.Iterable): + if not isinstance(element_types, Iterable): raise ValueError("element types must be iterable: {}".format(element_types)) self.element_types: list[Property, ...] = \ [el if isinstance(el, Property) else el() for el in element_types] @@ -562,7 +564,7 @@ def serialized_types(self): return tuple(set(chain(*[typ if isinstance(typ, tuple) else (typ,) for typ in all_serialized_types]))) - def _serialize(self, value: typing.Any) -> typing.Any: + def _serialize(self, value: Any) -> Any: for prop in self.element_types: try: return prop.serialize(value) @@ -571,7 +573,7 @@ def _serialize(self, value: typing.Any) -> typing.Any: raise ValueError("An unexpected error occurred while trying to serialize {} to one " "of the following types: {}.".format(value, self.serialized_types)) - def _deserialize(self, value: typing.Any) -> typing.Any: + def _deserialize(self, value: Any) -> Any: for prop in self.element_types: try: return prop.deserialize(value) @@ -585,12 +587,12 @@ class SpecifiedMixedList(PropertyCollection[list, list]): """A finite list in which the type of each entry is specified.""" def __init__(self, - element_types: typing.Sequence[Property | type[Property]], - serialization_path: typing.Optional[str] = None, + element_types: Sequence[Property | type[Property]], + serialization_path: str | None = None, *, serializable: bool = True, deserializable: bool = True, - default: typing.Optional[DeserializedType] = None, + default: DeserializedType | None = None, override: bool = False, use_init: bool = False ): @@ -665,12 +667,12 @@ def _set_elements(self, value): class Enumeration(Property[BaseEnumeration, str]): def __init__(self, - klass: type[typing.Any], - serialization_path: typing.Optional[str] = None, + klass: type[Any], + serialization_path: str | None = None, *, serializable: bool = True, deserializable: bool = True, - default: typing.Optional[DeserializedType] = None, + default: DeserializedType | None = None, override: bool = False, use_init: bool = False ): @@ -693,12 +695,12 @@ def serialized_types(self): def _deserialize(self, value: str) -> BaseEnumeration: return self.klass.from_str(value, exception=True) - def _serialize(self, value: typing.Any) -> str: + def _serialize(self, value: Any) -> str: return self.klass.from_str(value, exception=True).value @lru_cache(maxsize=1024) -def _fields_map(klass: typing.Type) -> dict[str, Property]: +def _fields_map(klass: type) -> dict[str, Property]: """Compute the properties-relevant fields in a given class.""" return { k: v @@ -707,15 +709,15 @@ def _fields_map(klass: typing.Type) -> dict[str, Property]: } -class Object(PropertyCollection[typing.Any, dict]): +class Object(PropertyCollection[Any, dict]): def __init__(self, - klass: type[typing.Any], - serialization_path: typing.Optional[str] = None, + klass: type[Any], + serialization_path: str | None = None, *, serializable: bool = True, deserializable: bool = True, - default: typing.Optional[DeserializedType] = None, + default: DeserializedType | None = None, override: bool = False, use_init: bool = False ): @@ -739,7 +741,7 @@ def underlying_types(self): def serialized_types(self): return dict - def _deserialize(self, data: dict) -> typing.Any: + def _deserialize(self, data: dict) -> Any: if self.polymorphic: return self.klass.get_type(data).build(data) if not self.fields: @@ -782,7 +784,7 @@ def _deserialize(self, data: dict) -> typing.Any: return instance - def _serialize(self, obj: typing.Any) -> dict: + def _serialize(self, obj: Any) -> dict: serialized = {} if type(obj) is not self.klass and isinstance(obj, Serializable): # If the object class doesn't match this one, then it is a subclass @@ -836,12 +838,12 @@ class LinkOrElse(PropertyCollection[Serializable | LinkByUID, dict]): """ def __init__(self, - klass: type[typing.Any] = Serializable, - serialization_path: typing.Optional[str] = None, + klass: type[Any] = Serializable, + serialization_path: str | None = None, *, serializable: bool = True, deserializable: bool = True, - default: typing.Optional[DeserializedType] = None, + default: DeserializedType | None = None, override: bool = False, use_init: bool = False ): @@ -862,7 +864,7 @@ def underlying_types(self): def serialized_types(self): return dict - def _serialize(self, value: typing.Any) -> dict: + def _serialize(self, value: Any) -> dict: if isinstance(value, LinkByUID): return value.as_dict() elif isinstance(value, Serializable): @@ -890,15 +892,15 @@ def _set_elements(self, value): return value -class Optional(PropertyCollection[typing.Optional[typing.Any], typing.Optional[typing.Any]]): +class Optional(PropertyCollection[Any | None, Any | None]): def __init__(self, prop: Property | type[Property], - serialization_path: typing.Optional[str] = None, + serialization_path: str | None = None, *, serializable: bool = True, deserializable: bool = True, - default: typing.Optional[DeserializedType] = None, + default: DeserializedType | None = None, override: bool = False, use_init: bool = False ): @@ -927,10 +929,10 @@ def serialized_types(self): else: return constituent_types, type(None) - def _deserialize(self, data: typing.Optional[typing.Any]) -> typing.Optional[typing.Any]: + def _deserialize(self, data: Any | None) -> Any | None: return self.prop.deserialize(data) if data is not None else None - def _serialize(self, obj: typing.Optional[typing.Any]) -> typing.Optional[typing.Any]: + def _serialize(self, obj: Any | None) -> Any | None: return self.prop.serialize(obj) if obj is not None else None def __str__(self): @@ -961,11 +963,11 @@ class Mapping(PropertyCollection[dict, dict]): def __init__(self, keys_type: Property | type[Property], values_type: Property | type[Property], - serialization_path: typing.Optional[str] = None, + serialization_path: str | None = None, *, serializable: bool = True, deserializable: bool = True, - default: typing.Optional[dict] = None, + default: dict | None = None, override: bool = False, use_init: bool = False, ser_as_list_of_pairs: bool = False): diff --git a/src/citrine/_session.py b/src/citrine/_session.py index d271013eb..1f91f00bb 100644 --- a/src/citrine/_session.py +++ b/src/citrine/_session.py @@ -4,7 +4,6 @@ from json.decoder import JSONDecodeError from logging import getLogger from os import environ -from typing import Optional from urllib.parse import urlunsplit import jwt @@ -38,7 +37,7 @@ def __init__(self, *, scheme: str = None, host: str = None, - port: Optional[str] = None): + port: str | None = None): super().__init__() if refresh_token is None: refresh_token = environ.get('CITRINE_API_KEY') @@ -53,7 +52,7 @@ def __init__(self, self.scheme: str = scheme self.authority = ':'.join(([host] if host else []) + ([port] if port else [])) self.refresh_token: str = refresh_token - self.access_token: Optional[str] = None + self.access_token: str | None = None self.access_token_expiration: datetime = datetime.now(timezone.utc) agent = "{}/{} python-requests/{} citrine-python/{}".format( @@ -213,7 +212,7 @@ def checked_request(self, method: str, path: str, raise CitrineException(response.text) @staticmethod - def _extract_response_stacktrace(response: Response) -> Optional[str]: + def _extract_response_stacktrace(response: Response) -> str | None: try: json_value = response.json() if isinstance(json_value, dict): diff --git a/src/citrine/_utils/batcher.py b/src/citrine/_utils/batcher.py index 3de4e02f4..6bed14d1f 100644 --- a/src/citrine/_utils/batcher.py +++ b/src/citrine/_utils/batcher.py @@ -11,16 +11,16 @@ class Batcher(ABC): """Base class for Data Concepts batching routines.""" @abstractmethod - def batch(self, objects: Iterable[DataConcepts], batch_size) -> list[list[DataConcepts]]: + def batch(self, objects: Iterable[DataConcepts], batch_size: int) -> list[list[DataConcepts]]: """Collect a list of DataConcepts into batches according to some batching algorithm.""" @staticmethod - def by_type(): + def by_type() -> 'BatchByType': """Return a BatchByType batcher.""" return BatchByType() @staticmethod - def by_dependency(): + def by_dependency() -> 'BatchByDependency': """Return a BatchByDependency batcher.""" return BatchByDependency() @@ -28,7 +28,7 @@ def by_dependency(): class BatchByType(Batcher): """Batching by object type.""" - def batch(self, objects: Iterable[DataConcepts], batch_size) -> list[list[DataConcepts]]: + def batch(self, objects: Iterable[DataConcepts], batch_size: int) -> list[list[DataConcepts]]: """Collect object batches by type, following an order that will satisfy prereqs.""" batches = list() by_type = defaultdict(list) @@ -58,7 +58,7 @@ def batch(self, objects: Iterable[DataConcepts], batch_size) -> list[list[DataCo class BatchByDependency(Batcher): """Batching by clusters where nothing references anything outside the cluster.""" - def batch(self, objects: Iterable[DataConcepts], batch_size) -> list[list[DataConcepts]]: + def batch(self, objects: Iterable[DataConcepts], batch_size: int) -> list[list[DataConcepts]]: """Collect object batches that are internally consistent for dry_run object tests.""" # Collect shallow dependences, UID references, and type-based clusters depends = dict() diff --git a/src/citrine/_utils/functions.py b/src/citrine/_utils/functions.py index bee770633..bcab2f768 100644 --- a/src/citrine/_utils/functions.py +++ b/src/citrine/_utils/functions.py @@ -2,7 +2,7 @@ from abc import ABCMeta from collections.abc import Sequence from pathlib import Path -from typing import Any, Optional +from typing import Any from urllib.parse import quote, urlencode, urlparse from uuid import UUID from warnings import warn @@ -119,7 +119,7 @@ def rewrite_s3_links_locally(url: str, s3_endpoint_url: str = None) -> str: return url -def write_file_locally(content, local_path: str | Path): +def write_file_locally(content: bytes, local_path: str | Path): """Take content from remote and ensure path exists.""" if isinstance(local_path, str): if len(os.path.split(local_path)[-1]) == 0: @@ -223,9 +223,9 @@ class _CustomMeta(MigratedClassMeta, type(target)): def migrate_deprecated_argument( - new_arg: Optional[Any], + new_arg: Any | None, new_arg_name: str, - old_arg: Optional[Any], + old_arg: Any | None, old_arg_name: str ) -> Any: """ @@ -238,11 +238,11 @@ def migrate_deprecated_argument( Parameters ---------- - new_arg: Optional[Any] + new_arg: Any | None the value provided using the new argument (or None, if not provided) new_arg_name: str the new name of the argument (used for creating user-facing messages) - old_arg: Optional[Any] + old_arg: Any | None the value provided using the old argument (or None, if not provided) old_arg_name: str the old name of the argument (used for creating user-facing messages) @@ -298,7 +298,7 @@ def format_escaped_url( def resource_path(*, path_template: str, - uid: Optional[UUID | str] = None, + uid: UUID | str | None = None, action: str | Sequence[str] = [], query_terms: dict[str, str] = {}, **kwargs diff --git a/src/citrine/_utils/template_util.py b/src/citrine/_utils/template_util.py index 8b2505793..f3b0abc86 100644 --- a/src/citrine/_utils/template_util.py +++ b/src/citrine/_utils/template_util.py @@ -1,4 +1,7 @@ -from gemd.util.impl import recursive_flatmap +from collections.abc import Mapping + +from citrine.resources.data_concepts import DataConcepts +from gemd.entity.attribute import PropertyAndConditions from gemd.entity.object import ( ProcessSpec, ProcessRun, @@ -6,12 +9,11 @@ MeasurementSpec, MeasurementRun, ) -from citrine.resources.data_concepts import DataConcepts from gemd.entity.value.base_value import BaseValue -from gemd.entity.attribute import PropertyAndConditions +from gemd.util.impl import recursive_flatmap -def make_attribute_table(gems: list[DataConcepts]) -> list[dict[str, BaseValue]]: +def make_attribute_table(gems: list[DataConcepts]) -> list[Mapping[str, BaseValue]]: """[ALPHA] the current status of make_attribute_table. Given a list of GEMD Objects, this method returns a list of dictionaries @@ -35,7 +37,7 @@ def make_attribute_table(gems: list[DataConcepts]) -> list[dict[str, BaseValue]] Returns ------- - list[dict[str, BaseValue]] + list[Mapping[str, BaseValue]] A list of dictionaries where each dictionary represents an object and its attributes. """ diff --git a/src/citrine/citrine.py b/src/citrine/citrine.py index e89d61d57..8bde3f245 100644 --- a/src/citrine/citrine.py +++ b/src/citrine/citrine.py @@ -1,5 +1,4 @@ from os import environ -from typing import Optional from citrine._session import Session from citrine.resources.catalyst import CatalystResource @@ -21,7 +20,7 @@ class Citrine: host: str Host URL, generally '.citrine-platform.com'. Default: environ.get('CITRINE_API_HOST') - port: Optional[str] + port: str | None Optional networking port. Default: None """ @@ -31,7 +30,7 @@ def __init__(self, *, scheme: str = None, host: str = None, - port: Optional[str] = None): + port: str | None = None): if api_key is None: api_key = environ.get('CITRINE_API_KEY') if scheme is None: diff --git a/src/citrine/exceptions.py b/src/citrine/exceptions.py index d7bca5530..28d27d382 100644 --- a/src/citrine/exceptions.py +++ b/src/citrine/exceptions.py @@ -1,6 +1,5 @@ """Citrine-specific exceptions.""" from types import SimpleNamespace -from typing import Optional from urllib.parse import urlencode from uuid import UUID @@ -34,7 +33,7 @@ class UnauthorizedRefreshToken(NonRetryableException): class NonRetryableHttpException(NonRetryableException): """An exception originating from an HTTP error from a Citrine API.""" - def __init__(self, path: str, response: Optional[Response] = None): + def __init__(self, path: str, response: Response | None = None): self.url = path self.detailed_error_info = [] if response is not None: diff --git a/src/citrine/gemd_queries/criteria.py b/src/citrine/gemd_queries/criteria.py index 223e94313..695d47007 100644 --- a/src/citrine/gemd_queries/criteria.py +++ b/src/citrine/gemd_queries/criteria.py @@ -92,7 +92,7 @@ class PropertiesCriteria(Serializable['PropertiesCriteria'], Criteria): ---------- property_templates_filter: set[UUID] The citrine IDs of the property templates matches must reference. - value_type_filter: Optional[PropertyFilterType] + value_type_filter: PropertyFilterType | None The value range matches must conform to. """ @@ -196,9 +196,9 @@ class ConnectivityClassCriteria(Serializable['ConnectivityClassCriteria'], Crite Parameters ---------- - is_consumed: Optional[bool] + is_consumed: bool | None Whether the material is consumed. - is_produced: Optional[bool] + is_produced: bool | None Whether the material is produced. """ diff --git a/src/citrine/gemtables/columns.py b/src/citrine/gemtables/columns.py index 4690f26ef..c09a3f3ee 100644 --- a/src/citrine/gemtables/columns.py +++ b/src/citrine/gemtables/columns.py @@ -1,5 +1,4 @@ """Column definitions for GEM Tables.""" -from typing import Optional from gemd.enumeration.base_enumeration import BaseEnumeration @@ -88,7 +87,7 @@ class MeanColumn(Serializable['MeanColumn'], Column): ---------- data_source: str | Variable name of the variable to use when populating the column - target_units: Optional[str] + target_units: str | None units to convert the real variable into. If not specified: a) If there is an OriginalUnitsColumnDefinition for that source, no conversion will be made. @@ -103,7 +102,7 @@ class MeanColumn(Serializable['MeanColumn'], Column): def __init__(self, *, data_source: str | Variable, - target_units: Optional[str] = None): + target_units: str | None = None): self.data_source = _make_data_source(data_source) self.target_units = target_units @@ -115,7 +114,7 @@ class StdDevColumn(Serializable["StdDevColumn"], Column): ---------- data_source: str | Variable name of the variable to use when populating the column - target_units: Optional[str] + target_units: str | None units to convert the real variable into. If not specified: a) If there is an OriginalUnitsColumnDefinition for that source, no conversion will be made. @@ -130,7 +129,7 @@ class StdDevColumn(Serializable["StdDevColumn"], Column): def __init__(self, *, data_source: str | Variable, - target_units: Optional[str] = None): + target_units: str | None = None): self.data_source = _make_data_source(data_source) self.target_units = target_units @@ -158,7 +157,7 @@ class QuantileColumn(Serializable["QuantileColumn"], Column): name of the variable to use when populating the column quantile: float the quantile to use for the column, defined between 0.0 and 1.0 - target_units: Optional[str] + target_units: str | None units to convert the real variable into. If not specified: a) If there is an OriginalUnitsColumnDefinition for that source, no conversion will be made. @@ -175,7 +174,7 @@ class QuantileColumn(Serializable["QuantileColumn"], Column): def __init__(self, *, data_source: str | Variable, quantile: float, - target_units: Optional[str] = None): + target_units: str | None = None): self.data_source = _make_data_source(data_source) self.quantile = quantile self.target_units = target_units diff --git a/src/citrine/gemtables/variables.py b/src/citrine/gemtables/variables.py index 65e1ac5e4..fdfa65244 100644 --- a/src/citrine/gemtables/variables.py +++ b/src/citrine/gemtables/variables.py @@ -1,5 +1,4 @@ """Variable definitions for GEM Tables.""" -from typing import Optional from uuid import UUID from gemd.entity.bounds.base_bounds import BaseBounds @@ -157,7 +156,7 @@ def __init__(self, *, headers: list[str], template: attribute_type, - attribute_constraints: Optional[list[constraint_type]] = None, + attribute_constraints: list[constraint_type] | None = None, type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN): self.name = name self.headers = headers @@ -214,7 +213,7 @@ def __init__(self, headers: list[str], attribute_template: attribute_type, process_template: process_type, - attribute_constraints: Optional[list[constraint_type]] = None, + attribute_constraints: list[constraint_type] | None = None, type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN): self.name = name self.headers = headers @@ -277,7 +276,7 @@ def __init__(self, headers: list[str], attribute_template: attribute_type, object_template: object_type, - attribute_constraints: Optional[list[constraint_type]] = None, + attribute_constraints: list[constraint_type] | None = None, type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN): self.name = name self.headers = headers @@ -329,7 +328,7 @@ def __init__(self, *, headers: list[str], template: attribute_type, - attribute_constraints: Optional[list[constraint_type]] = None, + attribute_constraints: list[constraint_type] | None = None, type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN): self.name = name self.headers = headers @@ -385,7 +384,7 @@ def __init__(self, headers: list[str], template: attribute_type, object_template: object_type, - attribute_constraints: Optional[list[constraint_type]] = None, + attribute_constraints: list[constraint_type] | None = None, type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN): self.name = name self.headers = headers @@ -585,7 +584,7 @@ def __init__(self, ingredient_name: str, quantity_dimension: IngredientQuantityDimension, type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN, - unit: Optional[str] = None): + unit: str | None = None): self.name = name self.headers = headers self.process_template = _make_link_by_uid(process_template) @@ -700,7 +699,7 @@ def __init__(self, headers: list[str], attribute_template: attribute_type, process_templates: list[process_type], - attribute_constraints: Optional[list[constraint_type]] = None, + attribute_constraints: list[constraint_type] | None = None, type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN): self.name = name self.headers = headers @@ -916,7 +915,7 @@ def __init__(self, quantity_dimension: IngredientQuantityDimension, process_templates: list[process_type], type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN, - unit: Optional[str] = None): + unit: str | None = None): self.name = name self.headers = headers self.ingredient_name = ingredient_name @@ -1066,7 +1065,7 @@ def __init__(self, ingredient_name: str, quantity_dimension: IngredientQuantityDimension, type_selector: DataObjectTypeSelector = DataObjectTypeSelector.PREFER_RUN, - unit: Optional[str] = None): + unit: str | None = None): self.name = name self.headers = headers self.ingredient_name = ingredient_name diff --git a/src/citrine/informatics/catalyst/assistant.py b/src/citrine/informatics/catalyst/assistant.py index 93e3eb67d..7cfbfe975 100644 --- a/src/citrine/informatics/catalyst/assistant.py +++ b/src/citrine/informatics/catalyst/assistant.py @@ -1,5 +1,3 @@ -from typing import Optional - from citrine.informatics.predictors import GraphPredictor from citrine._serialization import properties from citrine._serialization.polymorphic_serializable import PolymorphicSerializable @@ -19,8 +17,8 @@ class AssistantRequest(Serializable["AssistantRequest"]): def __init__(self, *, question: str, predictor: GraphPredictor, - temperature: Optional[float] = 0.0, - language_model: Optional[LanguageModelChoice] = LanguageModelChoice.GPT_4): + temperature: float | None = 0.0, + language_model: LanguageModelChoice | None = LanguageModelChoice.GPT_4): self.question = question self.predictor = predictor self.temperature = temperature diff --git a/src/citrine/informatics/catalyst/insights.py b/src/citrine/informatics/catalyst/insights.py index a0dc8a827..7b41cdbbf 100644 --- a/src/citrine/informatics/catalyst/insights.py +++ b/src/citrine/informatics/catalyst/insights.py @@ -1,5 +1,3 @@ -from typing import Optional - from citrine._serialization import properties from citrine._serialization.serializable import Serializable from citrine.informatics.catalyst.language_model import LanguageModelChoice @@ -22,10 +20,10 @@ def __init__( self, *, question: str, - temperature: Optional[float] = 0.0, - language_model: Optional[LanguageModelChoice] = LanguageModelChoice.GPT_35_TURBO, - n_documents: Optional[int] = 5, - response_size: Optional[int] = 100, + temperature: float | None = 0.0, + language_model: LanguageModelChoice | None = LanguageModelChoice.GPT_35_TURBO, + n_documents: int | None = 5, + response_size: int | None = 100, ): self.question = question self.temperature = temperature diff --git a/src/citrine/informatics/constraints/categorical_constraint.py b/src/citrine/informatics/constraints/categorical_constraint.py index d34c268ba..48c8ae864 100644 --- a/src/citrine/informatics/constraints/categorical_constraint.py +++ b/src/citrine/informatics/constraints/categorical_constraint.py @@ -1,4 +1,3 @@ - from citrine._serialization import properties from citrine._serialization.serializable import Serializable from citrine.informatics.constraints.constraint import Constraint diff --git a/src/citrine/informatics/constraints/ingredient_count_constraint.py b/src/citrine/informatics/constraints/ingredient_count_constraint.py index 7bdc0ef74..ee261cfff 100644 --- a/src/citrine/informatics/constraints/ingredient_count_constraint.py +++ b/src/citrine/informatics/constraints/ingredient_count_constraint.py @@ -1,5 +1,3 @@ -from typing import Optional - from citrine._serialization import properties from citrine._serialization.serializable import Serializable from citrine.informatics.constraints.constraint import Constraint @@ -19,7 +17,7 @@ class IngredientCountConstraint(Serializable['IngredientCountConstraint'], Const minimum ingredient count max: int maximum ingredient count - label: Optional[str] + label: str | None Optional label to constrain. If specified, then only ingredients with the specified label will count towards the total. Default is ``None``; all ingredients count towards the total @@ -36,11 +34,11 @@ def __init__(self, *, formulation_descriptor: FormulationDescriptor, min: int, max: int, - label: Optional[str] = None): + label: str | None = None): self.formulation_descriptor: FormulationDescriptor = formulation_descriptor self.min: int = min self.max: int = max - self.label: Optional[str] = label + self.label: str | None = label def __str__(self): return f"" diff --git a/src/citrine/informatics/constraints/ingredient_ratio_constraint.py b/src/citrine/informatics/constraints/ingredient_ratio_constraint.py index 04c5ef0f5..9d7683699 100644 --- a/src/citrine/informatics/constraints/ingredient_ratio_constraint.py +++ b/src/citrine/informatics/constraints/ingredient_ratio_constraint.py @@ -1,5 +1,3 @@ -from typing import Optional - from citrine._serialization import properties from citrine._serialization.serializable import Serializable from citrine.informatics.constraints.constraint import Constraint @@ -25,13 +23,13 @@ class IngredientRatioConstraint(Serializable['IngredientRatioConstraint'], Const minimum value for the ratio max: float maximum value for the ratio - ingredient: Optional[tuple[str, float]] + ingredient: tuple[str, float] | None multiplier for an ingredient in the numerator of the ratio - label: Optional[tuple[str, float]] + label: tuple[str, float] | None multiplier for a label in the numerator of the ratio - basis_ingredients: Optional[list[str] | dict[str | float]] + basis_ingredients: list[str] | dict[str, float] | None the ingredients which should appear in the denominator of the ratio - basis_labels: Optional[list[str] | dict[str | float]] + basis_labels: list[str] | dict[str, float] | None the labels which should appear in the denominator of the ratio """ @@ -63,8 +61,8 @@ def __init__(self, *, formulation_descriptor: FormulationDescriptor, min: float, max: float, - ingredient: Optional[tuple[str, float]] = None, - label: Optional[tuple[str, float]] = None, + ingredient: tuple[str, float] | None = None, + label: tuple[str, float] | None = None, basis_ingredients: set[str] = set(), basis_labels: set[str] = set()): self.formulation_descriptor = formulation_descriptor @@ -81,7 +79,7 @@ def ingredient(self): return self._numerator_read(self._ingredients) @ingredient.setter - def ingredient(self, value: Optional[tuple[str, float]]): + def ingredient(self, value: tuple[str, float] | None): """Set the ingredient and its multiplier in the numerator.""" self._ingredients = self._numerator_validate(value, "Ingredient") @@ -91,7 +89,7 @@ def label(self): return self._numerator_read(self._labels) @label.setter - def label(self, value: Optional[tuple[str, float]]): + def label(self, value: tuple[str, float] | None): """Set the label and its multiplier in the numerator.""" self._labels = self._numerator_validate(value, "Label") diff --git a/src/citrine/informatics/constraints/integer_range_constraint.py b/src/citrine/informatics/constraints/integer_range_constraint.py index a3ba9d699..cde368925 100644 --- a/src/citrine/informatics/constraints/integer_range_constraint.py +++ b/src/citrine/informatics/constraints/integer_range_constraint.py @@ -1,5 +1,3 @@ -from typing import Optional - from citrine._serialization import properties from citrine._serialization.serializable import Serializable from citrine.informatics.constraints.constraint import Constraint @@ -35,8 +33,8 @@ class IntegerRangeConstraint(Serializable['IntegerRangeConstraint'], Constraint) def __init__(self, *, descriptor_key: str, - lower_bound: Optional[int] = None, - upper_bound: Optional[int] = None): + lower_bound: int | None = None, + upper_bound: int | None = None): self.descriptor_key = descriptor_key self.lower_bound = lower_bound self.upper_bound = upper_bound diff --git a/src/citrine/informatics/constraints/scalar_range_constraint.py b/src/citrine/informatics/constraints/scalar_range_constraint.py index 48793406b..141c2412e 100644 --- a/src/citrine/informatics/constraints/scalar_range_constraint.py +++ b/src/citrine/informatics/constraints/scalar_range_constraint.py @@ -1,5 +1,3 @@ -from typing import Optional - from citrine._serialization import properties from citrine._serialization.serializable import Serializable from citrine.informatics.constraints.constraint import Constraint @@ -34,10 +32,10 @@ class ScalarRangeConstraint(Serializable['ScalarRangeConstraint'], Constraint): def __init__(self, *, descriptor_key: str, - lower_bound: Optional[float] = None, - upper_bound: Optional[float] = None, - lower_inclusive: Optional[bool] = None, - upper_inclusive: Optional[bool] = None): + lower_bound: float | None = None, + upper_bound: float | None = None, + lower_inclusive: bool | None = None, + upper_inclusive: bool | None = None): self.descriptor_key = descriptor_key self.lower_bound = lower_bound diff --git a/src/citrine/informatics/design_candidate.py b/src/citrine/informatics/design_candidate.py index 85f9d3ec3..dfef5e102 100644 --- a/src/citrine/informatics/design_candidate.py +++ b/src/citrine/informatics/design_candidate.py @@ -1,5 +1,3 @@ -from typing import Optional - from citrine._serialization import properties from citrine._serialization.polymorphic_serializable import PolymorphicSerializable from citrine._serialization.serializable import Serializable @@ -101,7 +99,7 @@ class Mixture(Serializable["Mixture"], DesignVariable): typ = properties.String('type', default='M', deserializable=False) """:str: polymorphic type code""" - def __init__(self, *, quantities: dict, labels: Optional[dict] = None): + def __init__(self, *, quantities: dict, labels: dict | None = None): self.quantities = quantities self.labels = labels or {} pass # pragma: no cover @@ -141,9 +139,9 @@ class DesignMaterial(Serializable["DesignMaterial"]): identifiers = properties.List(properties.String, 'identifiers.external', default=[]) """:list[str]: globally unique identifiers assigned to the material""" process_template = properties.Optional(properties.UUID, 'identifiers.process_template') - """:Optional[UUID]: GEMD process template that describes the process to create this material""" + """:UUID | None: GEMD process template that describes the process to create this material""" material_template = properties.Optional(properties.UUID, 'identifiers.material_template') - """:Optional[UUID]: GEMD material template that describes this material""" + """:UUID | None: GEMD material template that describes this material""" values = properties.Mapping(properties.String, properties.Object(DesignVariable), 'vars') """:dict[str, DesignVariable]: mapping from descriptor keys to the value for this material""" @@ -191,9 +189,9 @@ class DesignCandidate(Serializable["DesignCandidate"]): hidden = properties.Boolean('hidden') """:str: whether the candidate is marked hidden""" pinned_by = properties.Optional(properties.UUID, 'pinned.user') - """:Optional[UUID]: id of the user who pinned the candidate, if it's been pinned""" + """:UUID | None: id of the user who pinned the candidate, if it's been pinned""" pinned_time = properties.Optional(properties.Datetime, 'pinned.time') - """:Optional[datetime]: date and time at which the candidate was pinned, if it's been pinned""" + """:datetime | None: date and time at which the candidate was pinned, if it's been pinned""" comments = properties.List(properties.Object(DesignCandidateComment), 'comments', default=[]) """:list[DesignCandidateComment]: the list of comments on the candidate, with metadata.""" diff --git a/src/citrine/informatics/design_spaces/design_space_settings.py b/src/citrine/informatics/design_spaces/design_space_settings.py index 57c0a2dd9..68df574c7 100644 --- a/src/citrine/informatics/design_spaces/design_space_settings.py +++ b/src/citrine/informatics/design_spaces/design_space_settings.py @@ -1,4 +1,3 @@ -from typing import Optional from uuid import UUID from gemd.enumeration.base_enumeration import BaseEnumeration @@ -47,13 +46,13 @@ class DesignSpaceSettings(Resource["DesignSpaceSettings"]): def __init__(self, *, predictor_id: UUID | str, - predictor_version: Optional[int | str] = None, - mode: Optional[DefaultDesignSpaceMode] = None, - exclude_intermediates: Optional[bool] = None, - include_ingredient_fraction_constraints: Optional[bool] = None, - include_label_fraction_constraints: Optional[bool] = None, - include_label_count_constraints: Optional[bool] = None, - include_parameter_constraints: Optional[bool] = None): + predictor_version: int | str | None = None, + mode: DefaultDesignSpaceMode | None = None, + exclude_intermediates: bool | None = None, + include_ingredient_fraction_constraints: bool | None = None, + include_label_fraction_constraints: bool | None = None, + include_label_count_constraints: bool | None = None, + include_parameter_constraints: bool | None = None): self.predictor_id = predictor_id self.predictor_version = predictor_version self.mode = mode diff --git a/src/citrine/informatics/design_spaces/formulation_design_space.py b/src/citrine/informatics/design_spaces/formulation_design_space.py index 202005dc4..480b2ed76 100644 --- a/src/citrine/informatics/design_spaces/formulation_design_space.py +++ b/src/citrine/informatics/design_spaces/formulation_design_space.py @@ -1,4 +1,4 @@ -from typing import Optional +from collections.abc import Mapping from citrine._rest.resource import Resource from citrine._serialization import properties @@ -27,7 +27,7 @@ class FormulationDesignSpace(Resource['FormulationDesignSpace'], DesignSubspace) This must include an :class:`~io.citrine.informatics.constraints.ingredient_count_constraint.IngredientCountConstraint` with maximum count of 32 or fewer. - labels: Optional[dict[str, set[str]]] + labels: Mapping[str, set[str]] | None map from a label to each ingredient that should given that label when it's included in a formulation, e.g., ``{'solvent': {'water', 'alcohol'}}`` resolution: float, optional @@ -54,14 +54,14 @@ def __init__(self, formulation_descriptor: FormulationDescriptor, ingredients: set[str], constraints: set[Constraint], - labels: Optional[dict[str, set[str]]] = None, + labels: Mapping[str, set[str]] | None = None, resolution: float = 0.0001): self.name: str = name self.description: str = description self.formulation_descriptor: FormulationDescriptor = formulation_descriptor self.ingredients: set[str] = ingredients self.constraints: set[Constraint] = constraints - self.labels: Optional[dict[str, set[str]]] = labels + self.labels: Mapping[str, set[str]] | None = labels self.resolution: float = resolution def __str__(self): diff --git a/src/citrine/informatics/design_spaces/hierarchical_design_space.py b/src/citrine/informatics/design_spaces/hierarchical_design_space.py index 217c8ff8c..6f44a9be2 100644 --- a/src/citrine/informatics/design_spaces/hierarchical_design_space.py +++ b/src/citrine/informatics/design_spaces/hierarchical_design_space.py @@ -1,4 +1,3 @@ -from typing import Optional from uuid import UUID from citrine._rest.engine_resource import EngineResource @@ -26,9 +25,9 @@ class TemplateLink(Serializable["TemplateLink"]): Citrine ID referencing an on-platform material template. process_template: UUID Citrine ID referencing an on-platform process template. - material_template_name: Optional[str] + material_template_name: str | None Optional name of the material template. - process_template_name: Optional[str] + process_template_name: str | None Optional name of the process template. """ @@ -43,13 +42,13 @@ def __init__( *, material_template: UUID, process_template: UUID, - material_template_name: Optional[str] = None, - process_template_name: Optional[str] = None + material_template_name: str | None = None, + process_template_name: str | None = None ): self.material_template: UUID = material_template self.process_template: UUID = process_template - self.material_template_name: Optional[str] = material_template_name - self.process_template_name: Optional[str] = process_template_name + self.material_template_name: str | None = material_template_name + self.process_template_name: str | None = process_template_name class MaterialNodeDefinition(Serializable["MaterialNodeDefinition"]): @@ -61,17 +60,17 @@ class MaterialNodeDefinition(Serializable["MaterialNodeDefinition"]): A unique name used to reference the materials produced by this node in the design space. This name should be used to identify the material when used as an ingredient in the formulation subspace of a different node. - scope: Optional[str] + scope: str | None An optional custom scope used to identify the materials produced by this node. attributes: list[Dimension] Set of dimensions included on materials produced by this node. - formulation_subspace: Optional[FormulationDesignSpace] + formulation_subspace: FormulationDesignSpace | None An optional formulation design space defining the ingredients, labels, and constraints for formulations in materials produced by this node. - template_link: Optional[TemplateLink] + template_link: TemplateLink | None A set of identifiers linking the materials produced by this node to material and process templates on the Citrine Platform. - display_name: Optional[str] + display_name: str | None Optional name for identifying the node on the Citrine Platform. Solely for display purposes (does not appear in generated hierarchical candidates) @@ -90,18 +89,18 @@ def __init__( self, *, name: str, - scope: Optional[str] = None, - attributes: Optional[list[Dimension]] = None, - formulation_subspace: Optional[FormulationDesignSpace] = None, - template_link: Optional[TemplateLink] = None, - display_name: Optional[str] = None + scope: str | None = None, + attributes: list[Dimension] | None = None, + formulation_subspace: FormulationDesignSpace | None = None, + template_link: TemplateLink | None = None, + display_name: str | None = None ): self.name = name - self.scope: Optional[str] = scope + self.scope: str | None = scope self.attributes = attributes or list() - self.formulation_subspace: Optional[FormulationDesignSpace] = formulation_subspace - self.template_link: Optional[TemplateLink] = template_link - self.display_name: Optional[str] = display_name + self.formulation_subspace: FormulationDesignSpace | None = formulation_subspace + self.template_link: TemplateLink | None = template_link + self.display_name: str | None = display_name def __repr__(self): display_name = self.display_name or self.name @@ -170,8 +169,8 @@ def __init__( *, description: str, root: MaterialNodeDefinition, - subspaces: Optional[list[MaterialNodeDefinition]] = None, - data_sources: Optional[list[DataSource]] = None + subspaces: list[MaterialNodeDefinition] | None = None, + data_sources: list[DataSource] | None = None ): self.name: str = name self.description: str = description diff --git a/src/citrine/informatics/design_spaces/product_design_space.py b/src/citrine/informatics/design_spaces/product_design_space.py index 836bf59ae..3cfb9fb83 100644 --- a/src/citrine/informatics/design_spaces/product_design_space.py +++ b/src/citrine/informatics/design_spaces/product_design_space.py @@ -1,5 +1,3 @@ -from typing import Optional - from citrine._rest.engine_resource import EngineResource from citrine._serialization import properties from citrine.informatics.design_spaces.top_level_design_space import TopLevelDesignSpace @@ -43,8 +41,8 @@ def __init__(self, name: str, *, description: str, - subspaces: Optional[list[DesignSubspace]] = None, - dimensions: Optional[list[Dimension]] = None): + subspaces: list[DesignSubspace] | None = None, + dimensions: list[Dimension] | None = None): self.name: str = name self.description: str = description self.subspaces: list[DesignSubspace] = subspaces or [] diff --git a/src/citrine/informatics/design_spaces/top_level_design_space.py b/src/citrine/informatics/design_spaces/top_level_design_space.py index 3861daade..e1f8db6e6 100644 --- a/src/citrine/informatics/design_spaces/top_level_design_space.py +++ b/src/citrine/informatics/design_spaces/top_level_design_space.py @@ -1,5 +1,4 @@ """Tools for working with design spaces.""" -from typing import Optional from uuid import UUID from citrine._rest.asynchronous_object import AsynchronousObject @@ -22,17 +21,17 @@ class TopLevelDesignSpace(PolymorphicSerializable['TopLevelDesignSpace'], Asynch """ uid = properties.Optional(properties.UUID, 'id', serializable=False) - """:Optional[UUID]: Citrine Platform unique identifier""" + """:UUID | None: Citrine Platform unique identifier""" name = properties.String('data.name') description = properties.Optional(properties.String(), 'data.description') locked_by = properties.Optional(properties.UUID, 'metadata.locked.user', serializable=False) - """:Optional[UUID]: id of the user whose action cause the design space to + """:UUID | None: id of the user whose action cause the design space to be locked, if it is locked""" lock_time = properties.Optional(properties.Datetime, 'metadata.locked.time', serializable=False) - """:Optional[datetime]: date and time at which the resource was locked, + """:datetime | None: date and time at which the resource was locked, if it is locked""" @staticmethod @@ -50,8 +49,8 @@ def wrap_instance(subspace_data: dict) -> dict: } _response_key = None - _project_id: Optional[UUID] = None - _session: Optional[Session] = None + _project_id: UUID | None = None + _session: Session | None = None _in_progress_statuses = ["VALIDATING", "CREATED"] _succeeded_statuses = ["READY"] _failed_statuses = ["INVALID", "ERROR"] diff --git a/src/citrine/informatics/dimensions.py b/src/citrine/informatics/dimensions.py index 0e0878798..b16ef1b92 100644 --- a/src/citrine/informatics/dimensions.py +++ b/src/citrine/informatics/dimensions.py @@ -1,5 +1,4 @@ """Tools for working with Dimensions.""" -from typing import Optional from citrine._serialization import properties from citrine._serialization.polymorphic_serializable import PolymorphicSerializable @@ -47,8 +46,8 @@ class ContinuousDimension(Serializable['ContinuousDimension'], Dimension): def __init__(self, descriptor: RealDescriptor, *, - lower_bound: Optional[float] = None, - upper_bound: Optional[float] = None): + lower_bound: float | None = None, + upper_bound: float | None = None): self.descriptor: RealDescriptor = descriptor self.lower_bound = lower_bound if lower_bound is not None else descriptor.lower_bound self.upper_bound = upper_bound if upper_bound is not None else descriptor.upper_bound @@ -75,8 +74,8 @@ class IntegerDimension(Serializable['IntegerDimension'], Dimension): def __init__(self, descriptor: IntegerDescriptor, *, - lower_bound: Optional[int] = None, - upper_bound: Optional[int] = None): + lower_bound: int | None = None, + upper_bound: int | None = None): self.descriptor: IntegerDescriptor = descriptor self.lower_bound = lower_bound if lower_bound is not None else descriptor.lower_bound self.upper_bound = upper_bound if upper_bound is not None else descriptor.upper_bound diff --git a/src/citrine/informatics/executions/execution.py b/src/citrine/informatics/executions/execution.py index a00a07111..43e92f701 100644 --- a/src/citrine/informatics/executions/execution.py +++ b/src/citrine/informatics/executions/execution.py @@ -1,5 +1,4 @@ from abc import ABC -from typing import Optional from uuid import UUID from citrine._rest.asynchronous_object import AsynchronousObject @@ -21,29 +20,29 @@ class Execution(Pageable, AsynchronousObject, ABC): _in_progress_statuses = ["INPROGRESS"] _succeeded_statuses = ["SUCCEEDED"] _failed_statuses = ["FAILED"] - _session: Optional[Session] = None - project_id: Optional[UUID] = None + _session: Session | None = None + project_id: UUID | None = None uid: UUID = properties.UUID('id', serializable=False) """:UUID: Unique identifier of the execution""" status = properties.Optional(properties.String(), 'status', serializable=False) - """:Optional[str]: short description of the execution's status""" + """:str | None: short description of the execution's status""" status_description = properties.Optional( properties.String(), 'status_description', serializable=False) - """:Optional[str]: more detailed description of the execution's status""" + """:str | None: more detailed description of the execution's status""" status_detail = properties.List( properties.Object(StatusDetail), 'status_detail', default=[], serializable=False ) """:list[StatusDetail]: a list of structured status info, containing the message and level""" created_by = properties.Optional(properties.UUID, 'created_by', serializable=False) - """:Optional[UUID]: id of the user who created the resource""" + """:UUID | None: id of the user who created the resource""" updated_by = properties.Optional(properties.UUID, 'updated_by', serializable=False) - """:Optional[UUID]: id of the user who most recently updated the resource, + """:UUID | None: id of the user who most recently updated the resource, if it has been updated""" create_time = properties.Optional(properties.Datetime, 'create_time', serializable=False) - """:Optional[datetime]: date and time at which the resource was created""" + """:datetime | None: date and time at which the resource was created""" update_time = properties.Optional(properties.Datetime, 'update_time', serializable=False) - """:Optional[datetime]: date and time at which the resource was most recently updated, + """:datetime | None: date and time at which the resource was most recently updated, if it has been updated""" def __str__(self): diff --git a/src/citrine/informatics/executions/predictor_evaluation.py b/src/citrine/informatics/executions/predictor_evaluation.py index 520a521ea..fa99516b2 100644 --- a/src/citrine/informatics/executions/predictor_evaluation.py +++ b/src/citrine/informatics/executions/predictor_evaluation.py @@ -1,5 +1,4 @@ from functools import lru_cache -from typing import Optional from uuid import UUID from citrine._rest.asynchronous_object import AsynchronousObject @@ -33,7 +32,7 @@ def __init__(self, *, evaluators: list[PredictorEvaluator], predictor_id: UUID | str, - predictor_version: Optional[int | str] = None): + predictor_version: int | str | None = None): self.evaluators = evaluators self.predictor = PredictorRef(predictor_id, predictor_version) @@ -58,8 +57,8 @@ class PredictorEvaluation(EngineResourceWithoutStatus['PredictorEvaluation'], As default=[], serializable=False) """:list[StatusDetail]: a list of structured status info, containing the message and level""" - project_id: Optional[UUID] = None - _session: Optional[Session] = None + project_id: UUID | None = None + _session: Session | None = None _in_progress_statuses = ["INPROGRESS"] _succeeded_statuses = ["SUCCEEDED"] _failed_statuses = ["FAILED"] diff --git a/src/citrine/informatics/executions/sample_design_space_execution.py b/src/citrine/informatics/executions/sample_design_space_execution.py index eb7b9e364..63f68bc7e 100644 --- a/src/citrine/informatics/executions/sample_design_space_execution.py +++ b/src/citrine/informatics/executions/sample_design_space_execution.py @@ -1,6 +1,5 @@ from collections.abc import Iterable from functools import partial -from typing import Optional from uuid import UUID from citrine.informatics.executions.execution import Execution @@ -18,7 +17,7 @@ class SampleDesignSpaceExecution(Resource['SampleDesignSpaceExecution'], Executi """ _api_version = 'v3' - design_space_id: Optional[UUID] = None + design_space_id: UUID | None = None def _path(self): return format_escaped_url( @@ -48,7 +47,7 @@ def _build_results( def results( self, *, - page: Optional[int] = None, + page: int | None = None, per_page: int = 100, ) -> Iterable[SampleSearchSpaceResultCandidate]: """Fetch the Sample Design Space Results for the particular execution, paginated.""" diff --git a/src/citrine/informatics/experiment_values.py b/src/citrine/informatics/experiment_values.py index a615057bf..3a0f90bff 100644 --- a/src/citrine/informatics/experiment_values.py +++ b/src/citrine/informatics/experiment_values.py @@ -1,4 +1,3 @@ - from citrine._serialization.serializable import Serializable from citrine._serialization.polymorphic_serializable import PolymorphicSerializable from citrine._serialization import properties diff --git a/src/citrine/informatics/generative_design.py b/src/citrine/informatics/generative_design.py index 899757b2c..67f350a2a 100644 --- a/src/citrine/informatics/generative_design.py +++ b/src/citrine/informatics/generative_design.py @@ -1,4 +1,3 @@ -from typing import Optional from citrine._serialization import properties from citrine._serialization.serializable import Serializable from gemd.enumeration.base_enumeration import BaseEnumeration @@ -135,8 +134,8 @@ def __init__( fingerprint_type: FingerprintType, min_fingerprint_similarity: float, mutation_per_seed: int, - structure_exclusions: Optional[list[StructureExclusion]] = None, - min_substructure_counts: Optional[dict[str, int]] = None, + structure_exclusions: list[StructureExclusion] | None = None, + min_substructure_counts: dict[str, int] | None = None, ): self.seeds: list[str] = seeds self.fingerprint_type: FingerprintType = fingerprint_type diff --git a/src/citrine/informatics/predict_request.py b/src/citrine/informatics/predict_request.py index 79eacfa95..606f8d637 100644 --- a/src/citrine/informatics/predict_request.py +++ b/src/citrine/informatics/predict_request.py @@ -1,4 +1,3 @@ -from typing import Optional from uuid import UUID from citrine._serialization import properties @@ -23,7 +22,7 @@ def __init__(self, material_id: UUID, material: DesignMaterial, created_from_id: UUID, *, - random_seed: Optional[int] = None): + random_seed: int | None = None): self.material_id = material_id self.identifiers = identifiers self.material = material diff --git a/src/citrine/informatics/predictor_evaluation_result.py b/src/citrine/informatics/predictor_evaluation_result.py index 435468463..127d4c432 100644 --- a/src/citrine/informatics/predictor_evaluation_result.py +++ b/src/citrine/informatics/predictor_evaluation_result.py @@ -1,4 +1,3 @@ - from citrine._serialization import properties from citrine._serialization.polymorphic_serializable import PolymorphicSerializable from citrine._serialization.serializable import Serializable @@ -40,7 +39,7 @@ class RealMetricValue(Serializable["RealMetricValue"], MetricValue): mean = properties.Float("mean") """:float: Mean value""" standard_error = properties.Optional(properties.Float(), "standard_error") - """:Optional[float]: Standard error of the mean""" + """:float | None: Standard error of the mean""" typ = properties.String('type', default='RealMetricValue', deserializable=False) def __eq__(self, other): diff --git a/src/citrine/informatics/predictor_evaluator.py b/src/citrine/informatics/predictor_evaluator.py index 3fdb63b6c..2283e69ad 100644 --- a/src/citrine/informatics/predictor_evaluator.py +++ b/src/citrine/informatics/predictor_evaluator.py @@ -1,5 +1,3 @@ -from typing import Optional - from citrine._serialization import properties from citrine._serialization.polymorphic_serializable import PolymorphicSerializable from citrine._serialization.serializable import Serializable @@ -90,10 +88,10 @@ class CrossValidationEvaluator(Serializable["CrossValidationEvaluator"], Predict Number of cross-validation folds n_trials: int Number of cross-validation trials, each contains ``n_folds`` folds - metrics: Optional[set[PredictorEvaluationMetric]] + metrics: set[PredictorEvaluationMetric] | None Optional set of metrics to compute for each response. Default is all metrics. - ignore_when_grouping: Optional[set[str]] + ignore_when_grouping: set[str] | None Set of descriptor keys to group together. Candidates with different values for the given keys and identical values for all other descriptors will be in the same group. @@ -118,15 +116,15 @@ def __init__(self, responses: set[str], n_folds: int = 5, n_trials: int = 3, - metrics: Optional[set[PredictorEvaluationMetric]] = None, - ignore_when_grouping: Optional[set[str]] = None): + metrics: set[PredictorEvaluationMetric] | None = None, + ignore_when_grouping: set[str] | None = None): self.name: str = name self.description: str = description self._responses: set[str] = responses - self._metrics: Optional[set[PredictorEvaluationMetric]] = metrics + self._metrics: set[PredictorEvaluationMetric] | None = metrics self.n_folds: int = n_folds self.n_trials: int = n_trials - self.ignore_when_grouping: Optional[set[str]] = ignore_when_grouping + self.ignore_when_grouping: set[str] | None = ignore_when_grouping @property def responses(self) -> set[str]: @@ -154,7 +152,7 @@ class HoldoutSetEvaluator(Serializable["HoldoutSetEvaluator"], PredictorEvaluato Set of descriptor keys to evaluate data_source: DataSource Source of holdout data - metrics: Optional[set[PredictorEvaluationMetric]] + metrics: set[PredictorEvaluationMetric] | None Optional set of metrics to compute for each response. Default is all metrics. """ @@ -172,12 +170,12 @@ def __init__(self, description: str = "", responses: set[str], data_source: DataSource, - metrics: Optional[set[PredictorEvaluationMetric]] = None): + metrics: set[PredictorEvaluationMetric] | None = None): self.name: str = name self.description: str = description self._responses: set[str] = responses self.data_source = data_source - self._metrics: Optional[set[PredictorEvaluationMetric]] = metrics + self._metrics: set[PredictorEvaluationMetric] | None = metrics @property def responses(self) -> set[str]: diff --git a/src/citrine/informatics/predictors/attribute_accumulation_predictor.py b/src/citrine/informatics/predictors/attribute_accumulation_predictor.py index 7a3602d53..696eed6e6 100644 --- a/src/citrine/informatics/predictors/attribute_accumulation_predictor.py +++ b/src/citrine/informatics/predictors/attribute_accumulation_predictor.py @@ -1,4 +1,3 @@ - from citrine._rest.resource import Resource from citrine._serialization import properties as _properties from citrine.informatics.descriptors import Descriptor diff --git a/src/citrine/informatics/predictors/auto_ml_predictor.py b/src/citrine/informatics/predictors/auto_ml_predictor.py index 546928a8b..06dd21777 100644 --- a/src/citrine/informatics/predictors/auto_ml_predictor.py +++ b/src/citrine/informatics/predictors/auto_ml_predictor.py @@ -1,5 +1,3 @@ -from typing import Optional - from gemd.enumeration.base_enumeration import BaseEnumeration from citrine._rest.resource import Resource @@ -47,7 +45,7 @@ class AutoMLPredictor(Resource["AutoMLPredictor"], PredictorNode): Descriptors that represent inputs to the model outputs: list[Descriptor] Descriptors that represents the output(s) of the model. - estimators: Optional[set[AutoMLEstimator]] + estimators: set[AutoMLEstimator] | None Set of estimators to consider during during AutoML model selection. If None is provided, defaults to AutoMLEstimator.RANDOM_FOREST. @@ -69,7 +67,7 @@ def __init__(self, description: str, outputs: list[Descriptor], inputs: list[Descriptor], - estimators: Optional[set[AutoMLEstimator]] = None): + estimators: set[AutoMLEstimator] | None = None): self.name: str = name self.description: str = description self.inputs: list[Descriptor] = inputs diff --git a/src/citrine/informatics/predictors/chemical_formula_featurizer.py b/src/citrine/informatics/predictors/chemical_formula_featurizer.py index 8e1dc4d53..f595732e2 100644 --- a/src/citrine/informatics/predictors/chemical_formula_featurizer.py +++ b/src/citrine/informatics/predictors/chemical_formula_featurizer.py @@ -1,4 +1,3 @@ -from typing import Optional from warnings import warn from citrine._rest.resource import Resource @@ -120,12 +119,12 @@ class ChemicalFormulaFeaturizer(Resource["ChemicalFormulaFeaturizer"], Predictor ---------- input_descriptor: ChemicalFormulaDescriptor the descriptor to featurize - features: Optional[list[str]] + features: list[str] | None The list of features to compute, either by name or by group alias. Default is "standard." - excludes: Optional[list[str]] + excludes: list[str] | None The list of features to exclude, either by name or by group alias. Default is none. The final set of features generated by the predictor is set(features) - set(excludes). - powers: Optional[list[int]] + powers: list[float] | None The list of powers to use when computing generalized weighted means of element properties. p=1.0 corresponds to the ordinary mean, p=2.0 is the root mean square, etc. @@ -143,9 +142,9 @@ def __init__(self, *, description: str, input_descriptor: ChemicalFormulaDescriptor, - features: Optional[list[str]] = None, - excludes: Optional[list[str]] = None, - powers: Optional[list[float]] = None): + features: list[str] | None = None, + excludes: list[str] | None = None, + powers: list[float] | None = None): self.name = name self.description = description self.input_descriptor = input_descriptor diff --git a/src/citrine/informatics/predictors/expression_predictor.py b/src/citrine/informatics/predictors/expression_predictor.py index 4b294ec98..0382e4ed9 100644 --- a/src/citrine/informatics/predictors/expression_predictor.py +++ b/src/citrine/informatics/predictors/expression_predictor.py @@ -1,3 +1,4 @@ +from collections.abc import Mapping from citrine._rest.resource import Resource from citrine._serialization import properties as _properties @@ -23,7 +24,7 @@ class ExpressionPredictor(Resource["ExpressionPredictor"], PredictorNode): expression that computes an output from aliased inputs output: RealDescriptor descriptor that represents the output of the expression - aliases: dict[str, RealDescriptor] + aliases: Mapping[str, RealDescriptor] a mapping from each unknown argument to its descriptor. All unknown arguments must have an associated descriptor. @@ -43,12 +44,12 @@ def __init__(self, description: str, expression: str, output: RealDescriptor, - aliases: dict[str, RealDescriptor]): + aliases: Mapping[str, RealDescriptor]): self.name: str = name self.description: str = description self.expression: str = expression self.output: RealDescriptor = output - self.aliases: dict[str, RealDescriptor] = aliases + self.aliases: Mapping[str, RealDescriptor] = aliases def __str__(self): return ''.format(self.name) diff --git a/src/citrine/informatics/predictors/graph_predictor.py b/src/citrine/informatics/predictors/graph_predictor.py index 6d08565e2..a636e1b7b 100644 --- a/src/citrine/informatics/predictors/graph_predictor.py +++ b/src/citrine/informatics/predictors/graph_predictor.py @@ -1,4 +1,3 @@ -from typing import Optional from uuid import UUID from citrine._rest.asynchronous_object import AsynchronousObject @@ -31,7 +30,7 @@ class GraphPredictor(VersionedEngineResource['GraphPredictor'], AsynchronousObje the description of the predictor predictors: list[UUID | PredictorNode], the list of individual predictors to use in the graph - training_data: Optional[list[DataSource]] + training_data: list[DataSource] | None Optional sources of training data shared by all predictors in the graph. Training data provided by this graph predictor does not need to be specified as part of the configuration of sub-predictors. Shared training data and any training data specified @@ -43,7 +42,7 @@ class GraphPredictor(VersionedEngineResource['GraphPredictor'], AsynchronousObje """ uid = properties.Optional(properties.UUID, 'id', serializable=False) - """:Optional[UUID]: Citrine Platform unique identifier""" + """:UUID | None: Citrine Platform unique identifier""" name = properties.String('data.name') description = properties.Optional(properties.String(), 'data.description') @@ -63,8 +62,8 @@ class GraphPredictor(VersionedEngineResource['GraphPredictor'], AsynchronousObje _api_version = "v3" _response_key = None - _project_id: Optional[UUID] = None - _session: Optional[Session] = None + _project_id: UUID | None = None + _session: Session | None = None _in_progress_statuses = ["VALIDATING", "CREATED"] _succeeded_statuses = ["READY"] _failed_statuses = ["INVALID", "ERROR"] @@ -74,7 +73,7 @@ def __init__(self, *, description: str, predictors: list[PredictorNode], - training_data: Optional[list[DataSource]] = None): + training_data: list[DataSource] | None = None): self.name: str = name self.description: str = description self.training_data: list[DataSource] = training_data or [] diff --git a/src/citrine/informatics/predictors/ingredient_fractions_predictor.py b/src/citrine/informatics/predictors/ingredient_fractions_predictor.py index b0f5dc3b8..4fcc18d8e 100644 --- a/src/citrine/informatics/predictors/ingredient_fractions_predictor.py +++ b/src/citrine/informatics/predictors/ingredient_fractions_predictor.py @@ -1,4 +1,3 @@ - from citrine._rest.resource import Resource from citrine._serialization import properties as _properties from citrine.informatics.descriptors import FormulationDescriptor diff --git a/src/citrine/informatics/predictors/ingredients_to_formulation_predictor.py b/src/citrine/informatics/predictors/ingredients_to_formulation_predictor.py index 61a69c2dd..111e57c65 100644 --- a/src/citrine/informatics/predictors/ingredients_to_formulation_predictor.py +++ b/src/citrine/informatics/predictors/ingredients_to_formulation_predictor.py @@ -1,3 +1,4 @@ +from collections.abc import Mapping from citrine._rest.resource import Resource from citrine._serialization import properties @@ -18,10 +19,10 @@ class IngredientsToFormulationPredictor( name of the configuration description: str description of the predictor - id_to_quantity: dict[str, RealDescriptor] + id_to_quantity: Mapping[str, RealDescriptor] Map from ingredient identifier to the descriptor that represents its quantity, e.g., ``{'water': RealDescriptor('water quantity', 0, 1, "")}`` - labels: dict[str, set[str]] + labels: Mapping[str, set[str]] Map from each label to all ingredients assigned that label, when present in a mixture, e.g., ``{'solvent': {'water'}}`` @@ -38,12 +39,12 @@ def __init__(self, name: str, *, description: str, - id_to_quantity: dict[str, RealDescriptor], - labels: dict[str, set[str]]): + id_to_quantity: Mapping[str, RealDescriptor], + labels: Mapping[str, set[str]]): self.name: str = name self.description: str = description - self.id_to_quantity: dict[str, RealDescriptor] = id_to_quantity - self.labels: dict[str, set[str]] = labels + self.id_to_quantity: Mapping[str, RealDescriptor] = id_to_quantity + self.labels: Mapping[str, set[str]] = labels def __str__(self): return ''.format(self.name) diff --git a/src/citrine/informatics/predictors/label_fractions_predictor.py b/src/citrine/informatics/predictors/label_fractions_predictor.py index 7a529d75d..6bf2bbd96 100644 --- a/src/citrine/informatics/predictors/label_fractions_predictor.py +++ b/src/citrine/informatics/predictors/label_fractions_predictor.py @@ -1,4 +1,3 @@ - from citrine._rest.resource import Resource from citrine._serialization import properties as _properties from citrine.informatics.descriptors import FormulationDescriptor diff --git a/src/citrine/informatics/predictors/mean_property_predictor.py b/src/citrine/informatics/predictors/mean_property_predictor.py index 05fc346e4..9cd0c494a 100644 --- a/src/citrine/informatics/predictors/mean_property_predictor.py +++ b/src/citrine/informatics/predictors/mean_property_predictor.py @@ -1,4 +1,4 @@ -from typing import Optional +from collections.abc import Mapping from citrine._rest.resource import Resource from citrine._serialization import properties as _properties @@ -41,10 +41,10 @@ class MeanPropertyPredictor(Resource["MeanPropertyPredictor"], PredictorNode): entire dataset is used. If ``True`` and a default is specified in ``default_properties``, then the specified default is used in place of missing values. - label: Optional[str] + label: str | None Only ingredients with this label are counted when calculating the component-weighted mean. If ``None`` (default) all ingredients will be counted. - default_properties: Optional[dict[str, str | float]] + default_properties: Mapping[str, str | float] | None Default values to use for imputed properties. Defaults are specified as a map from descriptor key to its default value. If not specified and ``impute_properties == True`` the average over the entire dataset @@ -82,16 +82,16 @@ def __init__(self, properties: list[RealDescriptor | CategoricalDescriptor], p: float, impute_properties: bool, - label: Optional[str] = None, - default_properties: Optional[dict[str, str | float]] = None): + label: str | None = None, + default_properties: Mapping[str, str | float] | None = None): self.name: str = name self.description: str = description self.input_descriptor: FormulationDescriptor = input_descriptor self.properties: list[RealDescriptor | CategoricalDescriptor] = properties self.p: float = p self.impute_properties: bool = impute_properties - self.label: Optional[str] = label - self.default_properties: Optional[dict[str, str | float]] = default_properties + self.label: str | None = label + self.default_properties: Mapping[str, str | float] | None = default_properties def __str__(self): return ''.format(self.name) diff --git a/src/citrine/informatics/predictors/molecular_structure_featurizer.py b/src/citrine/informatics/predictors/molecular_structure_featurizer.py index 6c53fdc8e..0b5fd2af7 100644 --- a/src/citrine/informatics/predictors/molecular_structure_featurizer.py +++ b/src/citrine/informatics/predictors/molecular_structure_featurizer.py @@ -1,7 +1,6 @@ # flake8: noqa # The docstring includes many long links that violate flake8, and it's easier to noqa # the whole file than to pick out the offending lines. -from typing import Optional from citrine._rest.resource import Resource from citrine._serialization import properties as _properties @@ -89,8 +88,8 @@ def __init__(self, *, description: str, input_descriptor: MolecularStructureDescriptor, - features: Optional[list[str]] = None, - excludes: Optional[list[str]] = None): + features: list[str] | None = None, + excludes: list[str] | None = None): self.name: str = name self.description: str = description self.input_descriptor = input_descriptor diff --git a/src/citrine/informatics/predictors/node.py b/src/citrine/informatics/predictors/node.py index aacbae069..dd766ec1d 100644 --- a/src/citrine/informatics/predictors/node.py +++ b/src/citrine/informatics/predictors/node.py @@ -1,4 +1,3 @@ - from citrine._serialization import properties from citrine._serialization.polymorphic_serializable import PolymorphicSerializable from citrine.informatics.predictors import Predictor diff --git a/src/citrine/informatics/predictors/single_predict_request.py b/src/citrine/informatics/predictors/single_predict_request.py index 43a206480..7605561d0 100644 --- a/src/citrine/informatics/predictors/single_predict_request.py +++ b/src/citrine/informatics/predictors/single_predict_request.py @@ -1,4 +1,3 @@ -from typing import Optional from uuid import UUID from citrine._serialization import properties @@ -23,7 +22,7 @@ def __init__(self, material_id: UUID, identifiers: list[str], material: DesignMaterial, *, - random_seed: Optional[int] = None): + random_seed: int | None = None): self.material_id = material_id self.identifiers = identifiers self.material = material diff --git a/src/citrine/informatics/reports.py b/src/citrine/informatics/reports.py index 0624c1dca..5d3c37508 100644 --- a/src/citrine/informatics/reports.py +++ b/src/citrine/informatics/reports.py @@ -144,11 +144,11 @@ class ModelSummary(Serializable['ModelSummary']): selection_summary = properties.Optional( properties.Object(ModelSelectionReport), "selection_summary" ) - """:Optional[ModelSelectionReport]: optional results of AutoML model selection""" + """:ModelSelectionReport | None: optional results of AutoML model selection""" predictor_name = properties.String('predictor_configuration_name', default='') """:str: the name of the predictor that created this model""" predictor_uid = properties.Optional(properties.UUID(), 'predictor_configuration_uid') - """:Optional[UUID]: the unique Citrine id of the predictor that created this model""" + """:UUID | None: the unique Citrine id of the predictor that created this model""" training_data_count = properties.Optional(properties.Integer, "training_data_count") """:int: Number of rows in the training data for the model, if applicable.""" diff --git a/src/citrine/informatics/scores.py b/src/citrine/informatics/scores.py index acc8aac83..2caa89b8f 100644 --- a/src/citrine/informatics/scores.py +++ b/src/citrine/informatics/scores.py @@ -1,5 +1,4 @@ """Tools for working with Scores.""" -from typing import Optional from citrine._serialization import properties from citrine._serialization.polymorphic_serializable import PolymorphicSerializable @@ -54,7 +53,7 @@ class LIScore(Serializable['LIScore'], Score): def __init__(self, *, objectives: list[Objective], baselines: list[float], - constraints: Optional[list[Constraint]] = None): + constraints: list[Constraint] | None = None): self.objectives: list[Objective] = objectives self.baselines: list[float] = baselines self.constraints: list[Constraint] = constraints or [] @@ -89,7 +88,7 @@ class EIScore(Serializable['EIScore'], Score): def __init__(self, *, objectives: list[Objective], baselines: list[float], - constraints: Optional[list[Constraint]] = None): + constraints: list[Constraint] | None = None): self.objectives: list[Objective] = objectives self.baselines: list[float] = baselines self.constraints: list[Constraint] = constraints or [] @@ -122,7 +121,7 @@ class EVScore(Serializable['EVScore'], Score): def __init__(self, *, objectives: list[Objective], - constraints: Optional[list[Constraint]] = None): + constraints: list[Constraint] | None = None): self.objectives: list[Objective] = objectives self.constraints: list[Constraint] = constraints or [] self._name = "Expected Value" diff --git a/src/citrine/informatics/workflows/analysis_workflow.py b/src/citrine/informatics/workflows/analysis_workflow.py index 5594e80f9..383cc67d0 100644 --- a/src/citrine/informatics/workflows/analysis_workflow.py +++ b/src/citrine/informatics/workflows/analysis_workflow.py @@ -1,4 +1,3 @@ -from typing import Optional from uuid import UUID from citrine._rest.engine_resource import EngineResourceWithoutStatus @@ -36,7 +35,7 @@ def __init__(self, *, name: str, description: str, - snapshot_id: Optional[UUID | str] = None, + snapshot_id: UUID | str | None = None, plots: list[dict] = []): self.name = name self.description = description @@ -68,8 +67,8 @@ class AnalysisWorkflowUpdatePayload(Resource['AnalysisWorkflowUpdatePayload']): def __init__(self, uid: UUID | str, *, - name: Optional[str] = None, - description: Optional[str] = None): + name: str | None = None, + description: str | None = None): self.uid = uid self.name = name self.description = description diff --git a/src/citrine/informatics/workflows/design_workflow.py b/src/citrine/informatics/workflows/design_workflow.py index 695586f95..651679b8e 100644 --- a/src/citrine/informatics/workflows/design_workflow.py +++ b/src/citrine/informatics/workflows/design_workflow.py @@ -1,4 +1,3 @@ -from typing import Optional from uuid import UUID from citrine._rest.resource import Resource @@ -18,13 +17,13 @@ class DesignWorkflow(Resource['DesignWorkflow'], Workflow, AIResourceMetadata): ---------- name: str the name of the workflow - design_space_id: Optional[UUID] + design_space_id: UUID | None the UUID corresponding to the design space to use - predictor_id: Optional[UUID] + predictor_id: UUID | None the UUID corresponding to the predictor to use - predictor_version: Optional[int | str] + predictor_version: int | str | None the version of the predictor to use - description: Optional[str] + description: str | None a description of the workflow """ @@ -33,27 +32,26 @@ class DesignWorkflow(Resource['DesignWorkflow'], Workflow, AIResourceMetadata): predictor_id = properties.Optional(properties.UUID, 'predictor_id') predictor_version = properties.Optional( properties.Union([properties.Integer, properties.String]), 'predictor_version') - branch_root_id: Optional[UUID] = properties.Optional(properties.UUID, 'branch_root_id') - """:Optional[UUID]: Root ID of the branch that contains this workflow.""" - branch_version: Optional[int] = properties.Optional(properties.Integer, 'branch_version') - """:Optional[int]: Version number of the branch that contains this workflow.""" + branch_root_id: UUID | None = properties.Optional(properties.UUID, 'branch_root_id') + """:UUID | None: Root ID of the branch that contains this workflow.""" + branch_version: int | None = properties.Optional(properties.Integer, 'branch_version') + """:int | None: Version number of the branch that contains this workflow.""" data_source = properties.Optional(properties.Object(DataSource), "data_source") status_description = properties.String('status_description', serializable=False) """:str: more detailed description of the workflow's status""" typ = properties.String('type', default='DesignWorkflow', deserializable=False) - _branch_id: Optional[UUID] = properties.Optional(properties.UUID, 'branch_id', - serializable=False) + _branch_id: UUID | None = properties.Optional(properties.UUID, 'branch_id', serializable=False) def __init__(self, name: str, *, - design_space_id: Optional[UUID] = None, - predictor_id: Optional[UUID] = None, - predictor_version: Optional[int | str] = None, - data_source: Optional[DataSource] = None, - description: Optional[str] = None): + design_space_id: UUID | None = None, + predictor_id: UUID | None = None, + predictor_version: int | str | None = None, + data_source: DataSource | None = None, + description: str | None = None): self.name = name self.design_space_id = design_space_id self.predictor_id = predictor_id @@ -90,7 +88,7 @@ def design_executions(self) -> DesignExecutionCollection: project_id=self.project_id, session=self._session, workflow_id=self.uid) @property - def data_source_id(self) -> Optional[str]: + def data_source_id(self) -> str | None: """A resource referencing the workflow's data source.""" if self.data_source is None: return None @@ -98,7 +96,7 @@ def data_source_id(self) -> Optional[str]: return self.data_source.to_data_source_id() @data_source_id.setter - def data_source_id(self, value: Optional[str]): + def data_source_id(self, value: str | None): if value is None: self.data_source = None else: diff --git a/src/citrine/informatics/workflows/workflow.py b/src/citrine/informatics/workflows/workflow.py index 7ee23da63..101d07b36 100644 --- a/src/citrine/informatics/workflows/workflow.py +++ b/src/citrine/informatics/workflows/workflow.py @@ -1,5 +1,4 @@ """Tools for working with workflow resources.""" -from typing import Optional from uuid import UUID from citrine._rest.asynchronous_object import AsynchronousObject @@ -20,14 +19,14 @@ class Workflow(AsynchronousObject): """ _response_key = None - _session: Optional[Session] = None + _session: Session | None = None _in_progress_statuses = ["INPROGRESS"] _succeeded_statuses = ["SUCCEEDED"] _failed_statuses = ["FAILED"] - project_id: Optional[UUID] = None - """:Optional[UUID]: Unique ID of the project that contains this workflow.""" + project_id: UUID | None = None + """:UUID | None: Unique ID of the project that contains this workflow.""" name = properties.String('name') description = properties.Optional(properties.String, 'description') uid = properties.Optional(properties.UUID, 'id', serializable=False) - """:Optional[UUID]: Citrine Platform unique identifier""" + """:UUID | None: Citrine Platform unique identifier""" diff --git a/src/citrine/jobs/job.py b/src/citrine/jobs/job.py index b6e1ae420..79215c142 100644 --- a/src/citrine/jobs/job.py +++ b/src/citrine/jobs/job.py @@ -81,7 +81,7 @@ class JobStatusResponse(Resource['JobStatusResponse']): tasks = properties.List(Object(TaskNode), "tasks") """:list[TaskNode]: all of the constituent task required to complete this job""" output = properties.Optional(properties.Mapping(String, String), 'output') - """:Optional[dict[str, str]]: job output properties and results""" + """:dict[str, str] | None: job output properties and results""" @property def status(self) -> JobStatus | str: diff --git a/src/citrine/jobs/waiting.py b/src/citrine/jobs/waiting.py index a688664e5..ecf5c4378 100644 --- a/src/citrine/jobs/waiting.py +++ b/src/citrine/jobs/waiting.py @@ -157,7 +157,7 @@ def wait_while_executing( Returns ------- - ExectutionType + ExecutionType the updated execution after it has finished executing diff --git a/src/citrine/resources/_default_labels.py b/src/citrine/resources/_default_labels.py index ede3de4bb..3169ac0cf 100644 --- a/src/citrine/resources/_default_labels.py +++ b/src/citrine/resources/_default_labels.py @@ -1,13 +1,11 @@ -from typing import Optional - from citrine.resources.data_concepts import CITRINE_TAG_PREFIX _CITRINE_DEFAULT_LABEL_PREFIX = f'{CITRINE_TAG_PREFIX}::mat_label' def _inject_default_label_tags( - original_tags: Optional[list[str]], default_labels: Optional[list[str]] -) -> Optional[list[str]]: + original_tags: list[str] | None, default_labels: list[str] | None +) -> list[str] | None: if default_labels is None: all_tags = original_tags else: diff --git a/src/citrine/resources/analysis_workflow.py b/src/citrine/resources/analysis_workflow.py index ae410848b..9571d2007 100644 --- a/src/citrine/resources/analysis_workflow.py +++ b/src/citrine/resources/analysis_workflow.py @@ -1,6 +1,5 @@ import functools from collections.abc import Iterator -from typing import Optional from uuid import UUID from citrine.informatics.workflows.analysis_workflow import AnalysisWorkflow, \ @@ -81,8 +80,8 @@ def restore(self, uid: UUID | str) -> AnalysisWorkflow: def update(self, uid: UUID | str, *, - name: Optional[str] = None, - description: Optional[str] = None) -> AnalysisWorkflow: + name: str | None = None, + description: str | None = None) -> AnalysisWorkflow: """Update the name and/or description of the analysis workflow.""" aw_update = AnalysisWorkflowUpdatePayload(uid=uid, name=name, description=description) return super().update(aw_update) diff --git a/src/citrine/resources/attribute_templates.py b/src/citrine/resources/attribute_templates.py index f4a7aee8d..069e41df8 100644 --- a/src/citrine/resources/attribute_templates.py +++ b/src/citrine/resources/attribute_templates.py @@ -2,8 +2,7 @@ from abc import ABC from typing import TypeVar -from citrine._serialization.properties import Optional as PropertyOptional -from citrine._serialization.properties import String, Object +from citrine._serialization.properties import Object, Optional, String from gemd.entity.template.attribute_template import AttributeTemplate as GEMDAttributeTemplate from gemd.entity.bounds.base_bounds import BaseBounds from citrine.resources.templates import Template, TemplateCollection @@ -17,7 +16,7 @@ class AttributeTemplate(Template, GEMDAttributeTemplate, ABC): """ name = String('name') - description = PropertyOptional(String(), 'description') + description = Optional(String(), 'description') bounds = Object(BaseBounds, 'bounds', override=True) diff --git a/src/citrine/resources/audit_info.py b/src/citrine/resources/audit_info.py index 554b25ec5..2ff82a55c 100644 --- a/src/citrine/resources/audit_info.py +++ b/src/citrine/resources/audit_info.py @@ -7,13 +7,13 @@ class AuditInfo(Serializable, DictSerializable, typ="audit_info"): """Model that holds audit metadata. AuditInfo objects should not be created by the user.""" created_by = properties.Optional(properties.UUID, 'created_by') - """:Optional[UUID]: ID of the user who created the object""" + """:UUID | None: ID of the user who created the object""" created_at = properties.Optional(properties.Datetime, 'created_at') - """:Optional[datetime]: Time, in ms since epoch, at which the object was created""" + """:datetime | None: Time, in ms since epoch, at which the object was created""" updated_by = properties.Optional(properties.UUID, 'updated_by') - """:Optional[UUID]: ID of the user who most recently updated the object""" + """:UUID | None: ID of the user who most recently updated the object""" updated_at = properties.Optional(properties.Datetime, 'updated_at') - """:Optional[datetime]: Time, in ms since epoch, at which the object was + """:datetime | None: Time, in ms since epoch, at which the object was most recently updated""" def __init__(self): diff --git a/src/citrine/resources/branch.py b/src/citrine/resources/branch.py index 522c72cc8..83dc00d28 100644 --- a/src/citrine/resources/branch.py +++ b/src/citrine/resources/branch.py @@ -1,6 +1,5 @@ import functools from collections.abc import Iterator -from typing import Optional from uuid import UUID from citrine._rest.collection import Collection @@ -35,12 +34,12 @@ class Branch(Resource['Branch']): root_id = properties.UUID('metadata.root_id', serializable=False) version = properties.Integer('metadata.version', serializable=False) - project_id: Optional[UUID] = None + project_id: UUID | None = None def __init__(self, name: str, *, - session: Optional[Session] = None): + session: Session | None = None): self.name: str = name self.session: Session = session @@ -58,7 +57,7 @@ def design_workflows(self) -> DesignWorkflowCollection: branch_version=self.version) @property - def experiment_datasource(self) -> Optional[ExperimentDataSource]: + def experiment_datasource(self) -> ExperimentDataSource | None: """Return this branch's experiment data source, or None if one doesn't exist.""" if getattr(self, 'project_id', None) is None: raise AttributeError('Cannot retrieve datasource without project reference!') @@ -108,7 +107,7 @@ def build(self, data: dict) -> Branch: def get(self, *, root_id: UUID | str, - version: Optional[int | str] = LATEST_VER) -> Branch: + version: int | str | None = LATEST_VER) -> Branch: """ Retrieve a branch by its root ID and, optionally, its version number. @@ -228,7 +227,7 @@ def _list_with_params(self, *, per_page, **kwargs): def archive(self, *, root_id: UUID | str, - version: Optional[int | str] = LATEST_VER): + version: int | str | None = LATEST_VER): """ Archive a branch. @@ -253,7 +252,7 @@ def archive(self, def restore(self, *, root_id: UUID | str, - version: Optional[int | str] = LATEST_VER): + version: int | str | None = LATEST_VER): """ Restore an archived branch. @@ -278,9 +277,9 @@ def restore(self, def update_data(self, *, root_id: UUID | str, - version: Optional[int | str] = LATEST_VER, + version: int | str | None = LATEST_VER, use_existing: bool = True, - retrain_models: bool = False) -> Optional[Branch]: + retrain_models: bool = False) -> Branch | None: """ Automatically advance the branch to the next version. @@ -330,7 +329,7 @@ def update_data(self, def data_updates(self, *, root_id: UUID | str, - version: Optional[int | str] = LATEST_VER) -> BranchDataUpdate: + version: int | str | None = LATEST_VER) -> BranchDataUpdate: """ Get data updates for a branch. diff --git a/src/citrine/resources/condition_template.py b/src/citrine/resources/condition_template.py index ef4835336..77d1b9bb8 100644 --- a/src/citrine/resources/condition_template.py +++ b/src/citrine/resources/condition_template.py @@ -1,5 +1,4 @@ """Resources that represent condition templates.""" -from typing import Optional from citrine._rest.resource import GEMDResource from citrine.resources.attribute_templates import AttributeTemplate, AttributeTemplateCollection @@ -41,9 +40,9 @@ def __init__(self, name: str, *, bounds: BaseBounds, - uids: Optional[dict[str, str]] = None, - description: Optional[str] = None, - tags: Optional[list[str]] = None + uids: dict[str, str] | None = None, + description: str | None = None, + tags: list[str] | None = None ): if uids is None: uids = dict() diff --git a/src/citrine/resources/data_concepts.py b/src/citrine/resources/data_concepts.py index 459f0387d..d0cdbdad5 100644 --- a/src/citrine/resources/data_concepts.py +++ b/src/citrine/resources/data_concepts.py @@ -2,7 +2,7 @@ import re from abc import abstractmethod, ABC from collections.abc import Iterable, Iterator -from typing import List, Optional, TypeVar +from typing import List, TypeVar from uuid import UUID, uuid4 from gemd.entity.dict_serializable import DictSerializable, DictSerializableMeta @@ -13,10 +13,8 @@ from citrine._rest.collection import Collection from citrine._serialization.polymorphic_serializable import PolymorphicSerializable -from citrine._serialization.properties import String, Mapping, Object -from citrine._serialization.properties import Optional as PropertyOptional -from citrine._serialization.properties import List as PropertyList -from citrine._serialization.properties import UUID as PropertyUUID +from citrine._serialization.properties import List as PropertyList, UUID as PropertyUUID +from citrine._serialization.properties import Mapping, Object, Optional, String from citrine._serialization.serializable import Serializable from citrine._session import Session from citrine._utils.functions import format_escaped_url, replace_objects_with_links, scrub_none @@ -59,8 +57,8 @@ class DataConcepts( """ """Properties inherited from GEMD Base Entitiy.""" - uids = PropertyOptional(Mapping(String('scope'), String('id')), 'uids', override=True) - tags = PropertyOptional(PropertyList(String()), 'tags', override=True) + uids = Optional(Mapping(String('scope'), String('id')), 'uids', override=True) + tags = Optional(PropertyList(String()), 'tags', override=True) _type_key = "type" """str: key used to determine type of serialized object.""" @@ -79,24 +77,24 @@ class DataConcepts( * audit_info contains who/when information about the resource on the citrine platform * dataset is the unique Citrine id of the dataset that owns this resource """ - _audit_info = PropertyOptional(Object(AuditInfo), "audit_info", serializable=False) - _dataset = PropertyOptional(PropertyUUID, "dataset", serializable=False) + _audit_info = Optional(Object(AuditInfo), "audit_info", serializable=False) + _dataset = Optional(PropertyUUID, "dataset", serializable=False) def __init__(self): self.typ = self._typ_stash @property - def audit_info(self) -> Optional[AuditInfo]: + def audit_info(self) -> AuditInfo | None: """Get the audit info object.""" return self._audit_info @property - def uid(self) -> Optional[UUID]: + def uid(self) -> UUID | None: """Get the Citrine Identifier (scope = "id"), or None if not registered.""" return self.uids.get(CITRINE_SCOPE) @property - def dataset(self) -> Optional[UUID]: + def dataset(self) -> UUID | None: """Get the dataset of this object, if it was returned by the backend.""" return self._dataset @@ -214,7 +212,7 @@ class DataConceptsCollection(Collection[ResourceType], ABC): """ - def __init__(self, *, session: Session, team_id: UUID, dataset_id: Optional[UUID] = None): + def __init__(self, *, session: Session, team_id: UUID, dataset_id: UUID | None = None): self.dataset_id = dataset_id self.session = session self.team_id = team_id @@ -256,7 +254,7 @@ def build(self, data: dict) -> ResourceType: return self.get_type().build(data) def list(self, *, - per_page: Optional[int] = 100, + per_page: int | None = 100, forward: bool = True) -> Iterator[ResourceType]: """ Get all visible elements of the collection. @@ -436,7 +434,7 @@ def async_update(self, model: ResourceType, *, wait_for_response: bool = True, timeout: float = 2 * 60, polling_delay: float = 1.0, - return_model: bool = False) -> Optional[UUID | ResourceType]: + return_model: bool = False) -> UUID | ResourceType | None: """ Update a particular element of the collection with data validation. @@ -466,7 +464,7 @@ def async_update(self, model: ResourceType, *, Returns ------- - Optional[UUID] + UUID | None If wait_for_response if True, then this call will poll the backend, waiting for the eventual job result. In the case of successful validation/update, a return value of None is provided unless return_model is True, in which case diff --git a/src/citrine/resources/data_objects.py b/src/citrine/resources/data_objects.py index 1c1f420c3..a6a6f7d2d 100644 --- a/src/citrine/resources/data_objects.py +++ b/src/citrine/resources/data_objects.py @@ -1,16 +1,14 @@ """Top-level class for all data object (i.e., spec and run) objects and collections thereof.""" from abc import ABC from collections.abc import Iterator -from typing import Optional, TypeVar +from typing import TypeVar from uuid import uuid4 from gemd.json import GEMDJson from gemd.util import recursive_foreach from citrine._utils.functions import get_object_id, replace_objects_with_links, scrub_none -from citrine._serialization.properties import List as PropertyList -from citrine._serialization.properties import String, Object -from citrine._serialization.properties import Optional as PropertyOptional +from citrine._serialization.properties import List, Object, Optional, String from gemd.entity.file_link import FileLink from citrine.exceptions import BadRequest from citrine.resources.api_error import ValidationError @@ -30,8 +28,8 @@ class DataObject(DataConcepts, BaseObject, ABC): DataObject must be extended along with `Resource` """ - notes = PropertyOptional(String(), 'notes') - file_links = PropertyOptional(PropertyList(Object(FileLink)), 'file_links', override=True) + notes = Optional(String(), 'notes') + file_links = Optional(List(Object(FileLink)), 'file_links', override=True) DataObjectResourceType = TypeVar("DataObjectResourceType", bound="DataObject") @@ -110,8 +108,8 @@ def _get_attribute_bounds_search_body(attribute_bounds): def validate_templates(self, *, model: DataObjectResourceType, - object_template: Optional[ObjectTemplateResourceType] = None, - ingredient_process_template: Optional[ProcessTemplate] = None)\ + object_template: ObjectTemplateResourceType | None = None, + ingredient_process_template: ProcessTemplate | None = None)\ -> list[ValidationError]: """ Validate a data object against its templates. diff --git a/src/citrine/resources/dataset.py b/src/citrine/resources/dataset.py index 97e8ea14c..7e5de13f8 100644 --- a/src/citrine/resources/dataset.py +++ b/src/citrine/resources/dataset.py @@ -1,6 +1,5 @@ """Resources that represent both individual and collections of datasets.""" from collections.abc import Iterator, Iterable -from typing import Optional from uuid import UUID from gemd.entity.base_entity import BaseEntity @@ -47,11 +46,11 @@ class Dataset(Resource['Dataset']): ---------- name: str Name of the dataset. Can be used for searching. - summary: Optional[str] + summary: str | None An optional summary of this dataset. - description: Optional[str] + description: str | None An optional long-form description of the dataset. - unique_name: Optional[str] + unique_name: str | None An optional, globally unique name that can be used to retrieve the dataset. """ @@ -86,11 +85,11 @@ class Dataset(Resource['Dataset']): session = properties.Optional(properties.Object(Session), 'session', serializable=False, deserializable=False) - def __init__(self, name: str, *, summary: Optional[str] = None, - description: Optional[str] = None, unique_name: Optional[str] = None): + def __init__(self, name: str, *, summary: str | None = None, + description: str | None = None, unique_name: str | None = None): self.name: str = name - self.summary: Optional[str] = summary - self.description: Optional[str] = description + self.summary: str | None = summary + self.description: str | None = description self.unique_name = unique_name # The attributes below should not be set by the user. Instead they will be updated as the diff --git a/src/citrine/resources/delete.py b/src/citrine/resources/delete.py index 15335bc56..51c1a82d2 100644 --- a/src/citrine/resources/delete.py +++ b/src/citrine/resources/delete.py @@ -1,5 +1,4 @@ import json -from typing import Optional from uuid import UUID from gemd.entity.base_entity import BaseEntity @@ -16,7 +15,7 @@ def _async_gemd_batch_delete( id_list: list[LinkByUID | UUID | str | BaseEntity], team_id: UUID, session: Session, - dataset_id: Optional[UUID] = None, + dataset_id: UUID | None = None, timeout: float = 2 * 60, polling_delay: float = 1.0 ) -> list[tuple[LinkByUID, ApiError]]: @@ -42,7 +41,7 @@ def _async_gemd_batch_delete( session: Session The Citrine session. - dataset_id: Optional[UUID] = None + dataset_id: UUID | None = None An optional dataset ID, which if provided will mandate that all GEMD objects must be within the given dataset. diff --git a/src/citrine/resources/design_execution.py b/src/citrine/resources/design_execution.py index ba3020c53..cfa325737 100644 --- a/src/citrine/resources/design_execution.py +++ b/src/citrine/resources/design_execution.py @@ -1,6 +1,5 @@ """Resources that represent both individual and collections of design workflow executions.""" from collections.abc import Iterator -from typing import Optional from uuid import UUID from citrine._rest.collection import Collection @@ -21,7 +20,7 @@ class DesignExecutionCollection(Collection["DesignExecution"]): def __init__(self, project_id: UUID, session: Session, - workflow_id: Optional[UUID] = None): + workflow_id: UUID | None = None): self.project_id: UUID = project_id self.session: Session = session self.workflow_id: UUID = workflow_id @@ -33,7 +32,7 @@ def build(self, data: dict) -> executions.DesignExecution: execution.project_id = self.project_id return execution - def trigger(self, execution_input: Score, *, max_candidates: Optional[int] = None): + def trigger(self, execution_input: Score, *, max_candidates: int | None = None): """Trigger a Design Workflow execution given a score and a maximum number of candidates.""" path = self._get_path() json = {'score': execution_input.dump(), "max_candidates": max_candidates} diff --git a/src/citrine/resources/design_space.py b/src/citrine/resources/design_space.py index ad98dd6c0..8d0da2d4d 100644 --- a/src/citrine/resources/design_space.py +++ b/src/citrine/resources/design_space.py @@ -1,7 +1,6 @@ """Resources that represent collections of design spaces.""" from collections.abc import Iterable from functools import partial -from typing import Optional from uuid import UUID @@ -95,7 +94,7 @@ def restore(self, uid: UUID | str) -> TopLevelDesignSpace: entity = self.session.put_resource(url, {}, version=self._api_version) return self.build(entity) - def _list_base(self, *, per_page: int = 100, archived: Optional[bool] = None): + def _list_base(self, *, per_page: int = 100, archived: bool | None = None): filters = {} if archived is not None: filters["archived"] = archived @@ -120,7 +119,7 @@ def list_archived(self, *, per_page: int = 20) -> Iterable[TopLevelDesignSpace]: def create_default(self, *, predictor_id: UUID | str, - predictor_version: Optional[int | str] = None, + predictor_version: int | str | None = None, mode: DefaultDesignSpaceMode = DefaultDesignSpaceMode.ATTRIBUTE, include_ingredient_fraction_constraints: bool = False, include_label_fraction_constraints: bool = False, @@ -144,7 +143,7 @@ def create_default(self, predictor_id: UUID UUID of the predictor used to construct the design space - predictor_version: Optional[int | str] + predictor_version: int | str | None Version of the predictor used to construct the design space mode: DefaultDesignSpaceMode @@ -194,7 +193,7 @@ def convert_to_hierarchical( uid: UUID | str, *, predictor_id: UUID | str, - predictor_version: Optional[int | str] = None + predictor_version: int | str | None = None ) -> HierarchicalDesignSpace: """Convert an existing ProductDesignSpace into an equivalent HierarchicalDesignSpace. @@ -210,7 +209,7 @@ def convert_to_hierarchical( UUID of the existing product design space to convert to a hierarchical version predictor_id: UUID | str UUID of a predictor associated with the design space. - predictor_version: Optional[int | str] + predictor_version: int | str | None Version of the predictor to use. Defaults to the most recent version. Returns diff --git a/src/citrine/resources/design_workflow.py b/src/citrine/resources/design_workflow.py index 94f3bf9a4..cf729dc03 100644 --- a/src/citrine/resources/design_workflow.py +++ b/src/citrine/resources/design_workflow.py @@ -1,6 +1,5 @@ from collections.abc import Callable, Iterable from copy import deepcopy -from typing import Optional from uuid import UUID from citrine._rest.collection import Collection @@ -23,8 +22,8 @@ def __init__(self, project_id: UUID, session: Session, *, - branch_root_id: Optional[UUID] = None, - branch_version: Optional[int] = None): + branch_root_id: UUID | None = None, + branch_version: int | None = None): self.project_id: UUID = project_id self.session: Session = session @@ -162,12 +161,12 @@ def list_archived(self, *, per_page: int = 500) -> Iterable[DesignWorkflow]: per_page=per_page) def _fetch_page(self, - path: Optional[str] = None, - fetch_func: Optional[Callable[..., dict]] = None, - page: Optional[int] = None, - per_page: Optional[int] = None, - json_body: Optional[dict] = None, - additional_params: Optional[dict] = None, + path: str | None = None, + fetch_func: Callable[..., dict] | None = None, + page: int | None = None, + per_page: int | None = None, + json_body: dict | None = None, + additional_params: dict | None = None, ) -> tuple[Iterable[dict], str]: params = additional_params or {} params["branch_root_id"] = self.branch_root_id diff --git a/src/citrine/resources/experiment_datasource.py b/src/citrine/resources/experiment_datasource.py index c945a605c..5171c111f 100644 --- a/src/citrine/resources/experiment_datasource.py +++ b/src/citrine/resources/experiment_datasource.py @@ -1,9 +1,8 @@ import csv import json -from typing import Iterator +from collections.abc import Iterator from functools import partial from io import StringIO -from typing import Optional from uuid import UUID from citrine._rest.collection import Collection @@ -25,7 +24,7 @@ class CandidateExperimentSnapshot(Serializable['CandidateExperimentSnapshot']): name = properties.String('name', serializable=False) """:str: name of the experiment""" description = properties.Optional(properties.String, 'description', serializable=False) - """:Optional[str]: description of the experiment""" + """:str | None: description of the experiment""" updated_time = properties.Datetime('updated_time', serializable=False) """:datetime: date and time at which the experiment was updated""" @@ -107,8 +106,8 @@ def build(self, data: dict) -> ExperimentDataSource: def list(self, *, per_page: int = 100, - branch_version_id: Optional[UUID | str] = None, - version: Optional[int | str] = None) -> Iterator[ExperimentDataSource]: + branch_version_id: UUID | str | None = None, + version: int | str | None = None) -> Iterator[ExperimentDataSource]: """Paginate over the experiment data sources. Parameters diff --git a/src/citrine/resources/file_link.py b/src/citrine/resources/file_link.py index 86981214c..0348fa122 100644 --- a/src/citrine/resources/file_link.py +++ b/src/citrine/resources/file_link.py @@ -4,7 +4,6 @@ from collections.abc import Iterable, Sequence from pathlib import Path from tempfile import TemporaryDirectory -from typing import Optional from urllib.parse import urlparse from urllib.request import url2pathname from uuid import UUID @@ -88,7 +87,7 @@ def __init__(cls, *args, **kwargs): cls.typ = properties.String('type', default="file_link", deserializable=False) -def _get_ids_from_url(url: str) -> tuple[Optional[UUID], Optional[UUID]]: +def _get_ids_from_url(url: str) -> tuple[UUID | None, UUID | None]: """Attempt to extract file_id and version_id from a URL.""" parsed = urlparse(url) if len(parsed.query) > 0 or len(parsed.fragment) > 0: @@ -203,9 +202,9 @@ def __init__(self, *, session: Session, dataset_id: UUID, team_id: UUID): self.team_id = team_id def _get_path(self, - uid: Optional[UUID | str] = None, + uid: UUID | str | None = None, *, - ignore_dataset: Optional[bool] = False, + ignore_dataset: bool | None = False, version: str | UUID = None, action: str | Sequence[str] = [], query_terms: dict[str, str] = {},) -> str: @@ -233,7 +232,7 @@ def build(self, data: dict) -> FileLink: def get(self, uid: UUID | str, *, - version: Optional[UUID | str | int] = None) -> FileLink: + version: UUID | str | int | None = None) -> FileLink: """ Retrieve an on-platform FileLink from its filename or file uuid. @@ -241,7 +240,7 @@ def get(self, ---------- uid: UUID | str A representation of the FileLink (Citrine id or file name) - version: Optional[UUID, str, int] + version: UUID | str | int | None The version, as a UUID or str(UUID) of the version_id or an int or str(int) of the version number. If None, returns the file with the highest version number (most recent). @@ -387,8 +386,8 @@ def _make_upload_request(self, file_path: Path, dest_name: str): def _search_by_file_name(self, file_name: str, dset_id: UUID, - file_version_number: Optional[int] = None - ) -> Optional[FileLink]: + file_version_number: int | None = None + ) -> FileLink | None: """ Make a request to the backend to search a file by name. @@ -401,7 +400,7 @@ def _search_by_file_name(self, The name of the file. dset_id: UUID UUID that represents a dataset. - file_version_number: Optional[int] + file_version_number: int | None As optional, you can send a specific version number. Returns @@ -428,7 +427,7 @@ def _search_by_file_name(self, def _search_by_file_version_id(self, file_version_id: UUID - ) -> Optional[FileLink]: + ) -> FileLink | None: """ Make a request to the backend to search a file by file version id. @@ -459,8 +458,8 @@ def _search_by_file_version_id(self, def _search_by_dataset_file_id(self, dataset_file_id: UUID, dset_id: UUID, - file_version_number: Optional[int] = None - ) -> Optional[FileLink]: + file_version_number: int | None = None + ) -> FileLink | None: """ Make a request to the backend to search a file by dataset file id. @@ -473,7 +472,7 @@ def _search_by_dataset_file_id(self, UUID that represents a dataset file id. dset_id: UUID UUID that represents a dataset. - file_version_number: Optional[int] + file_version_number: int | None As optional, you can send a specific version number Returns @@ -657,8 +656,8 @@ def ingest(self, delete_dataset_contents: bool = False, delete_templates: bool = True, timeout: float = None, - polling_delay: Optional[float] = None, - project: Optional["Project | UUID | str"] = None, # noqa: F821 + polling_delay: float | None = None, + project: "Project | UUID | str | None" = None, # noqa: F821 ) -> "IngestionStatus": # noqa: F821 """ [ALPHA] Ingest a set of CSVs and/or Excel Workbooks formatted per the gemd-ingest protocol. @@ -684,17 +683,17 @@ def ingest(self, build_table: bool Whether to trigger a regeneration of the table config and building the table after ingestion. Default: False - project: Optional[Project, UUID, or str] + project: Project | UUID | str | None Which project to use for table build if build_table is True. delete_dataset_contents: bool Whether to delete old objects prior to creating new ones. Default: False delete_templates: bool Whether to delete old templates if deleting old objects. Default: True - timeout: Optional[float] + timeout: float | None Amount of time to wait on the job (in seconds) before giving up. Note that this number has no effect on the underlying job itself, which can also time out server-side. - polling_delay: Optional[float] + polling_delay: float | None How long to delay between each polling retry attempt. diff --git a/src/citrine/resources/gemtables.py b/src/citrine/resources/gemtables.py index 03b657dc5..2104b9ea2 100644 --- a/src/citrine/resources/gemtables.py +++ b/src/citrine/resources/gemtables.py @@ -1,7 +1,7 @@ import json from collections.abc import Iterable from logging import getLogger -from typing import Any, Optional +from typing import Any import requests @@ -102,7 +102,7 @@ def __init__(self, *, team_id: UUID, project_id: UUID, session: Session): self.session: Session = session self.team_id = team_id - def get(self, uid: UUID | str, *, version: Optional[int] = None) -> GemTable: + def get(self, uid: UUID | str, *, version: int | None = None) -> GemTable: """Get a Table's metadata. If no version is specified, get the most recent version.""" if version is not None: path = self._get_path(uid, action=["versions", version]) @@ -127,7 +127,7 @@ def list_versions(self, :param per_page: The number of items to fetch per-page. :return: An iterable of the versions of the Tables (as Table objects). """ - def _fetch_versions(page: Optional[int], + def _fetch_versions(page: int | None, per_page: int) -> tuple[Iterable[dict], str]: data = self.session.get_resource(self._get_path(uid), params=self._page_params(page, per_page)) @@ -155,7 +155,7 @@ def list_by_config(self, :param per_page: The number of items to fetch per-page. :return: An iterable of the versions of the Tables (as Table objects). """ - def _fetch_versions(page: Optional[int], + def _fetch_versions(page: int | None, per_page: int) -> tuple[Iterable[dict], str]: path_params = {'table_config_uid_str': str(table_config_uid)} path_params.update(self.__dict__) diff --git a/src/citrine/resources/ingestion.py b/src/citrine/resources/ingestion.py index db14f2ca0..e9bc9aa4d 100644 --- a/src/citrine/resources/ingestion.py +++ b/src/citrine/resources/ingestion.py @@ -1,5 +1,4 @@ from collections.abc import Collection as TypingCollection, Iterator, Iterable -from typing import Optional from uuid import UUID from gemd.enumeration.base_enumeration import BaseEnumeration @@ -115,14 +114,14 @@ class IngestionException(CitrineException): """[ALPHA] An exception that contains details of a failed ingestion.""" uid = properties.Optional(properties.UUID(), 'ingestion_id', default=None) - """Optional[UUID]""" + """UUID | None""" status = properties.Enumeration(IngestionStatusType, "status") errors = properties.List(properties.Object(IngestionErrorTrace), "errors") """list[IngestionErrorTrace]""" def __init__(self, *, - uid: Optional[UUID] = uid.default, + uid: UUID | None = uid.default, errors: Iterable[IngestionErrorTrace]): errors_ = list(errors) message = '; '.join(str(e) for e in errors_) @@ -157,7 +156,7 @@ class IngestionStatus(Resource['IngestionStatus']): def __init__(self, *, - uid: Optional[UUID] = uid.default, + uid: UUID | None = uid.default, status: IngestionStatusType = IngestionStatusType.INGESTION_CREATED, errors: Iterable[IngestionErrorTrace]): self.uid = uid @@ -195,11 +194,11 @@ class Ingestion(Resource['Ingestion']): def build_objects(self, *, build_table: bool = False, - project: Optional["Project | UUID | str"] = None, # noqa: F821 + project: "Project | UUID | str | None" = None, # noqa: F821 delete_dataset_contents: bool = False, delete_templates: bool = True, timeout: float = None, - polling_delay: Optional[float] = None + polling_delay: float | None = None ) -> IngestionStatus: """ [ALPHA] Perform a complete ingestion operation, from start to finish. @@ -211,18 +210,18 @@ def build_objects(self, ---------- build_table: bool Whether to build a table immediately after ingestion. Default : False - project: Optional[Project, UUID, or str] + project: Project | UUID | str | None Which project to use for table build if build_table is True. delete_dataset_contents: bool Whether to delete objects prior to generating new gemd objects. Default: False. delete_templates: bool Whether to delete all objects and templates (as opposed to not deleting templates) when `delete_dataset_contents` is True. Default: True - timeout: Optional[float] + timeout: float | None Amount of time to wait on the job (in seconds) before giving up. Note that this number has no effect on the underlying job itself, which can also time out server-side. - polling_delay: Optional[float] + polling_delay: float | None How long to delay between each polling retry attempt. Returns @@ -252,7 +251,7 @@ def build_objects(self, def build_objects_async(self, *, build_table: bool = False, - project: Optional["Project | UUID | str"] = None, # noqa: F821 + project: "Project | UUID | str | None" = None, # noqa: F821 delete_dataset_contents: bool = False, delete_templates: bool = True) -> JobSubmissionResponse: """ @@ -262,7 +261,7 @@ def build_objects_async(self, ---------- build_table: bool Whether to build a table immediately after ingestion. Default : False - project: Optional[Project, UUID, or str] + project: Project | UUID | str | None Which project to use for table build if build_table is True. delete_dataset_contents: bool Whether to delete objects prior to generating new gemd objects. Default: False. @@ -313,8 +312,8 @@ def build_objects_async(self, def poll_for_job_completion(self, job: JobSubmissionResponse, *, - timeout: Optional[float] = None, - polling_delay: Optional[float] = None + timeout: float | None = None, + polling_delay: float | None = None ) -> IngestionStatus: """ [ALPHA] Repeatedly ask server if a job associated with this ingestion has completed. @@ -387,11 +386,11 @@ def __init__(self, errors: Iterable[IngestionErrorTrace]): def build_objects(self, *, build_table: bool = False, - project: Optional["Project | UUID | str"] = None, # noqa: F821 + project: "Project | UUID | str | None" = None, # noqa: F821 delete_dataset_contents: bool = False, delete_templates: bool = True, timeout: float = None, - polling_delay: Optional[float] = None + polling_delay: float | None = None ) -> IngestionStatus: """[ALPHA] Satisfy the required interface for a failed ingestion.""" return self.status() @@ -399,7 +398,7 @@ def build_objects(self, def build_objects_async(self, *, build_table: bool = False, - project: Optional["Project | UUID | str"] = None, # noqa: F821 + project: "Project | UUID | str | None" = None, # noqa: F821 delete_dataset_contents: bool = False, delete_templates: bool = True) -> JobSubmissionResponse: """[ALPHA] Satisfy the required interface for a failed ingestion.""" @@ -412,8 +411,8 @@ def build_objects_async(self, def poll_for_job_completion(self, job: JobSubmissionResponse, *, - timeout: Optional[float] = None, - polling_delay: Optional[float] = None + timeout: float | None = None, + polling_delay: float | None = None ) -> IngestionStatus: """[ALPHA] Satisfy the required interface for a failed ingestion.""" raise JobFailureError( diff --git a/src/citrine/resources/ingredient_run.py b/src/citrine/resources/ingredient_run.py index 0ed87483a..90bb6667d 100644 --- a/src/citrine/resources/ingredient_run.py +++ b/src/citrine/resources/ingredient_run.py @@ -1,12 +1,9 @@ """Resources that represent ingredient run data objects.""" from collections.abc import Iterator -from typing import Optional from uuid import UUID from citrine._rest.resource import GEMDResource -from citrine._serialization.properties import List as PropertyList -from citrine._serialization.properties import String, LinkOrElse, Object -from citrine._serialization.properties import Optional as PropertyOptional +from citrine._serialization.properties import LinkOrElse, List, Object, Optional, String from citrine.resources.object_runs import ObjectRun, ObjectRunCollection from gemd.entity.file_link import FileLink from gemd.entity.link_by_uid import LinkByUID @@ -65,37 +62,33 @@ class IngredientRun( _response_key = GEMDIngredientRun.typ # 'ingredient_run' - material = PropertyOptional(LinkOrElse(GEMDMaterialRun), 'material', override=True) - process = PropertyOptional(LinkOrElse(GEMDProcessRun), - 'process', - override=True, - use_init=True, - ) - mass_fraction = PropertyOptional(Object(ContinuousValue), 'mass_fraction') - volume_fraction = PropertyOptional(Object(ContinuousValue), 'volume_fraction') - number_fraction = PropertyOptional(Object(ContinuousValue), 'number_fraction') - absolute_quantity = PropertyOptional(Object(ContinuousValue), 'absolute_quantity') - spec = PropertyOptional(LinkOrElse(GEMDIngredientSpec), 'spec', override=True, use_init=True) + material = Optional(LinkOrElse(GEMDMaterialRun), 'material', override=True) + process = Optional(LinkOrElse(GEMDProcessRun), 'process', override=True, use_init=True) + mass_fraction = Optional(Object(ContinuousValue), 'mass_fraction') + volume_fraction = Optional(Object(ContinuousValue), 'volume_fraction') + number_fraction = Optional(Object(ContinuousValue), 'number_fraction') + absolute_quantity = Optional(Object(ContinuousValue), 'absolute_quantity') + spec = Optional(LinkOrElse(GEMDIngredientSpec), 'spec', override=True, use_init=True) """ Intentionally private because they have some unusual dynamics """ - _name = PropertyOptional(String(), 'name') - _labels = PropertyOptional(PropertyList(String()), 'labels') + _name = Optional(String(), 'name') + _labels = Optional(List(String()), 'labels') def __init__(self, *, - uids: Optional[dict[str, str]] = None, - tags: Optional[list[str]] = None, - notes: Optional[str] = None, - material: Optional[GEMDMaterialRun] = None, - process: Optional[GEMDProcessRun] = None, - mass_fraction: Optional[ContinuousValue] = None, - volume_fraction: Optional[ContinuousValue] = None, - number_fraction: Optional[ContinuousValue] = None, - absolute_quantity: Optional[ContinuousValue] = None, - spec: Optional[GEMDIngredientSpec] = None, - file_links: Optional[list[FileLink]] = None): + uids: dict[str, str] | None = None, + tags: list[str] | None = None, + notes: str | None = None, + material: GEMDMaterialRun | None = None, + process: GEMDProcessRun | None = None, + mass_fraction: ContinuousValue | None = None, + volume_fraction: ContinuousValue | None = None, + number_fraction: ContinuousValue | None = None, + absolute_quantity: ContinuousValue | None = None, + spec: GEMDIngredientSpec | None = None, + file_links: list[FileLink] | None = None): if uids is None: uids = dict() super(ObjectRun, self).__init__() diff --git a/src/citrine/resources/ingredient_spec.py b/src/citrine/resources/ingredient_spec.py index f8c0db06a..21fc13fdd 100644 --- a/src/citrine/resources/ingredient_spec.py +++ b/src/citrine/resources/ingredient_spec.py @@ -1,12 +1,9 @@ """Resources that represent ingredient spec data objects.""" from collections.abc import Iterator -from typing import Optional from uuid import UUID from citrine._rest.resource import GEMDResource -from citrine._serialization.properties import List as PropertyList -from citrine._serialization.properties import String, LinkOrElse, Object -from citrine._serialization.properties import Optional as PropertyOptional +from citrine._serialization.properties import LinkOrElse, List, Object, Optional, String from citrine.resources.object_specs import ObjectSpec, ObjectSpecCollection from gemd.entity.file_link import FileLink from gemd.entity.link_by_uid import LinkByUID @@ -66,34 +63,29 @@ class IngredientSpec( _response_key = GEMDIngredientSpec.typ # 'ingredient_spec' - material = PropertyOptional(LinkOrElse(GEMDMaterialSpec), 'material', override=True) - process = PropertyOptional(LinkOrElse(GEMDProcessSpec), - 'process', - override=True, - use_init=True) - mass_fraction = PropertyOptional(Object(ContinuousValue), 'mass_fraction', override=True) - volume_fraction = PropertyOptional(Object(ContinuousValue), 'volume_fraction', override=True) - number_fraction = PropertyOptional(Object(ContinuousValue), 'number_fraction', override=True) - absolute_quantity = PropertyOptional(Object(ContinuousValue), - 'absolute_quantity', - override=True) + material = Optional(LinkOrElse(GEMDMaterialSpec), 'material', override=True) + process = Optional(LinkOrElse(GEMDProcessSpec), 'process', override=True, use_init=True) + mass_fraction = Optional(Object(ContinuousValue), 'mass_fraction', override=True) + volume_fraction = Optional(Object(ContinuousValue), 'volume_fraction', override=True) + number_fraction = Optional(Object(ContinuousValue), 'number_fraction', override=True) + absolute_quantity = Optional(Object(ContinuousValue), 'absolute_quantity', override=True) name = String('name', override=True, use_init=True) - labels = PropertyOptional(PropertyList(String()), 'labels', override=True, use_init=True) + labels = Optional(List(String()), 'labels', override=True, use_init=True) def __init__(self, name: str, *, - uids: Optional[dict[str, str]] = None, - tags: Optional[list[str]] = None, - notes: Optional[str] = None, - material: Optional[GEMDMaterialSpec] = None, - process: Optional[GEMDProcessSpec] = None, - mass_fraction: Optional[ContinuousValue] = None, - volume_fraction: Optional[ContinuousValue] = None, - number_fraction: Optional[ContinuousValue] = None, - absolute_quantity: Optional[ContinuousValue] = None, - labels: Optional[list[str]] = None, - file_links: Optional[list[FileLink]] = None): + uids: dict[str, str] | None = None, + tags: list[str] | None = None, + notes: str | None = None, + material: GEMDMaterialSpec | None = None, + process: GEMDProcessSpec | None = None, + mass_fraction: ContinuousValue | None = None, + volume_fraction: ContinuousValue | None = None, + number_fraction: ContinuousValue | None = None, + absolute_quantity: ContinuousValue | None = None, + labels: list[str] | None = None, + file_links: list[FileLink] | None = None): if uids is None: uids = dict() diff --git a/src/citrine/resources/material_run.py b/src/citrine/resources/material_run.py index 329d7b8d7..0af06bd3f 100644 --- a/src/citrine/resources/material_run.py +++ b/src/citrine/resources/material_run.py @@ -1,11 +1,9 @@ """Resources that represent material run data objects.""" from collections.abc import Iterator -from typing import Optional from uuid import UUID from citrine._rest.resource import GEMDResource -from citrine._serialization.properties import Optional as PropertyOptional -from citrine._serialization.properties import String, LinkOrElse +from citrine._serialization.properties import LinkOrElse, Optional, String from citrine._utils.functions import format_escaped_url from citrine.resources._default_labels import _inject_default_label_tags from citrine.resources.data_concepts import _make_link_by_uid @@ -65,27 +63,21 @@ class MaterialRun( _response_key = GEMDMaterialRun.typ # 'material_run' name = String('name', override=True, use_init=True) - process = PropertyOptional(LinkOrElse(GEMDProcessRun), - 'process', - override=True, - use_init=True,) - sample_type = PropertyOptional(String, 'sample_type', override=True) - spec = PropertyOptional(LinkOrElse(GEMDMaterialSpec), - 'spec', - override=True, - use_init=True,) + process = Optional(LinkOrElse(GEMDProcessRun), 'process', override=True, use_init=True) + sample_type = Optional(String, 'sample_type', override=True) + spec = Optional(LinkOrElse(GEMDMaterialSpec), 'spec', override=True, use_init=True) def __init__(self, name: str, *, - uids: Optional[dict[str, str]] = None, - tags: Optional[list[str]] = None, - notes: Optional[str] = None, - process: Optional[GEMDProcessRun] = None, - sample_type: Optional[str] = "unknown", - spec: Optional[GEMDMaterialSpec] = None, - file_links: Optional[list[FileLink]] = None, - default_labels: Optional[list[str]] = None): + uids: dict[str, str] | None = None, + tags: list[str] | None = None, + notes: str | None = None, + process: GEMDProcessRun | None = None, + sample_type: str | None = "unknown", + spec: GEMDMaterialSpec | None = None, + file_links: list[FileLink] | None = None, + default_labels: list[str] | None = None): if uids is None: uids = dict() all_tags = _inject_default_label_tags(tags, default_labels) @@ -164,7 +156,7 @@ def get_history(self, id: str | UUID | LinkByUID | MaterialRun) -> MaterialRun: def get_by_process(self, uid: UUID | str | LinkByUID | GEMDProcessRun - ) -> Optional[MaterialRun]: + ) -> MaterialRun | None: """ Get output material of a process. diff --git a/src/citrine/resources/material_spec.py b/src/citrine/resources/material_spec.py index d0adbf4a3..f7dedcae8 100644 --- a/src/citrine/resources/material_spec.py +++ b/src/citrine/resources/material_spec.py @@ -1,12 +1,9 @@ """Resources that represent material spec data objects.""" from collections.abc import Iterator -from typing import Optional from uuid import UUID from citrine._rest.resource import GEMDResource -from citrine._serialization.properties import List as PropertyList -from citrine._serialization.properties import Optional as PropertyOptional -from citrine._serialization.properties import String, LinkOrElse, Object +from citrine._serialization.properties import LinkOrElse, List, Object, Optional, String from citrine.resources._default_labels import _inject_default_label_tags from citrine.resources.object_specs import ObjectSpec, ObjectSpecCollection from gemd.entity.attribute.property_and_conditions import PropertyAndConditions @@ -60,30 +57,21 @@ class MaterialSpec( _response_key = GEMDMaterialSpec.typ # 'material_spec' name = String('name', override=True, use_init=True) - process = PropertyOptional(LinkOrElse(GEMDProcessSpec), - 'process', - override=True, - use_init=True, - ) - properties = PropertyOptional(PropertyList(Object(PropertyAndConditions)), - 'properties', - override=True) - template = PropertyOptional(LinkOrElse(GEMDMaterialTemplate), - 'template', - override=True, - use_init=True,) + process = Optional(LinkOrElse(GEMDProcessSpec), 'process', override=True, use_init=True) + properties = Optional(List(Object(PropertyAndConditions)), 'properties', override=True) + template = Optional(LinkOrElse(GEMDMaterialTemplate), 'template', override=True, use_init=True) def __init__(self, name: str, *, - uids: Optional[dict[str, str]] = None, - tags: Optional[list[str]] = None, - notes: Optional[str] = None, - process: Optional[GEMDProcessSpec] = None, - properties: Optional[list[PropertyAndConditions]] = None, - template: Optional[GEMDMaterialTemplate] = None, - file_links: Optional[list[FileLink]] = None, - default_labels: Optional[list[str]] = None): + uids: dict[str, str] | None = None, + tags: list[str] | None = None, + notes: str | None = None, + process: GEMDProcessSpec | None = None, + properties: list[PropertyAndConditions] | None = None, + template: GEMDMaterialTemplate | None = None, + file_links: list[FileLink] | None = None, + default_labels: list[str] | None = None): if uids is None: uids = dict() all_tags = _inject_default_label_tags(tags, default_labels) @@ -129,7 +117,7 @@ def list_by_template(self, def get_by_process(self, uid: UUID | str | LinkByUID | GEMDProcessSpec - ) -> Optional[MaterialSpec]: + ) -> MaterialSpec | None: """ Get output material of a process. @@ -144,11 +132,4 @@ def get_by_process(self, The output material of the specified process, or None if no such material exists. """ - return next( - self._get_relation( - relation='process-specs', - uid=uid, - per_page=1 - ), - None - ) + return next(self._get_relation(relation='process-specs', uid=uid, per_page=1), None) diff --git a/src/citrine/resources/material_template.py b/src/citrine/resources/material_template.py index fc85e066c..604c6d3c1 100644 --- a/src/citrine/resources/material_template.py +++ b/src/citrine/resources/material_template.py @@ -1,12 +1,9 @@ """Resources that represent material templates.""" -from typing import Optional from collections.abc import Sequence from citrine._rest.resource import GEMDResource -from citrine._serialization.properties import List as PropertyList -from citrine._serialization.properties import Union as PropertyUnion -from citrine._serialization.properties import Optional as PropertyOptional -from citrine._serialization.properties import Object, SpecifiedMixedList, LinkOrElse +from citrine._serialization.properties import LinkOrElse, List, Object, Optional, \ + SpecifiedMixedList, Union from citrine.resources.object_templates import ObjectTemplateCollection, ObjectTemplate from citrine.resources.property_template import PropertyTemplate from gemd.entity.bounds.base_bounds import BaseBounds @@ -52,25 +49,20 @@ class MaterialTemplate( _response_key = GEMDMaterialTemplate.typ # 'material_template' - properties = PropertyOptional( - PropertyList( - PropertyUnion([LinkOrElse(GEMDPropertyTemplate), - SpecifiedMixedList([LinkOrElse(GEMDPropertyTemplate), - PropertyOptional(Object(BaseBounds))])] - ) - ), 'properties', override=True) + properties = Optional(List(Union([LinkOrElse(GEMDPropertyTemplate), + SpecifiedMixedList([LinkOrElse(GEMDPropertyTemplate), + Optional(Object(BaseBounds))])])), + 'properties', override=True) def __init__(self, name: str, *, - uids: Optional[dict[str, str]] = None, - properties: Optional[Sequence[PropertyTemplate - | LinkByUID - | Sequence[PropertyTemplate | LinkByUID - | Optional[BaseBounds]] - ]] = None, - description: Optional[str] = None, - tags: Optional[list[str]] = None): + uids: dict[str, str] | None = None, + properties: Sequence[PropertyTemplate | LinkByUID + | Sequence[PropertyTemplate | LinkByUID | BaseBounds | None] + ] | None = None, + description: str | None = None, + tags: list[str] | None = None): # properties is a list, each element of which is a PropertyTemplate OR is a list with # 2 entries: [PropertyTemplate, BaseBounds]. Python typing is not expressive enough, so # the typing above is more general. diff --git a/src/citrine/resources/measurement_run.py b/src/citrine/resources/measurement_run.py index b6c620e8d..e7e7704f3 100644 --- a/src/citrine/resources/measurement_run.py +++ b/src/citrine/resources/measurement_run.py @@ -1,12 +1,9 @@ """Resources that represent measurement run data objects.""" from collections.abc import Iterator -from typing import Optional from uuid import UUID from citrine._rest.resource import GEMDResource -from citrine._serialization.properties import List as PropertyList -from citrine._serialization.properties import Optional as PropertyOptional -from citrine._serialization.properties import String, Object, LinkOrElse +from citrine._serialization.properties import LinkOrElse, List, Object, Optional, String from citrine.resources.object_runs import ObjectRun, ObjectRunCollection from gemd.entity.attribute.condition import Condition from gemd.entity.attribute.parameter import Parameter @@ -64,30 +61,26 @@ class MeasurementRun( _response_key = GEMDMeasurementRun.typ # 'measurement_run' name = String('name', override=True, use_init=True) - conditions = PropertyOptional(PropertyList(Object(Condition)), 'conditions', override=True) - parameters = PropertyOptional(PropertyList(Object(Parameter)), 'parameters', override=True) - properties = PropertyOptional(PropertyList(Object(Property)), 'properties', override=True) - spec = PropertyOptional(LinkOrElse(GEMDMeasurementSpec), 'spec', override=True, use_init=True,) - material = PropertyOptional(LinkOrElse(GEMDMaterialRun), - "material", - override=True, - use_init=True, - ) - source = PropertyOptional(Object(PerformedSource), "source", override=True) + conditions = Optional(List(Object(Condition)), 'conditions', override=True) + parameters = Optional(List(Object(Parameter)), 'parameters', override=True) + properties = Optional(List(Object(Property)), 'properties', override=True) + spec = Optional(LinkOrElse(GEMDMeasurementSpec), 'spec', override=True, use_init=True,) + material = Optional(LinkOrElse(GEMDMaterialRun), "material", override=True, use_init=True) + source = Optional(Object(PerformedSource), "source", override=True) def __init__(self, name: str, *, - uids: Optional[dict[str, str]] = None, - tags: Optional[list[str]] = None, - notes: Optional[str] = None, - conditions: Optional[list[Condition]] = None, - properties: Optional[list[Property]] = None, - parameters: Optional[list[Parameter]] = None, - spec: Optional[GEMDMeasurementSpec] = None, - material: Optional[GEMDMaterialRun] = None, - file_links: Optional[list[FileLink]] = None, - source: Optional[PerformedSource] = None): + uids: dict[str, str] | None = None, + tags: list[str] | None = None, + notes: str | None = None, + conditions: list[Condition] | None = None, + properties: list[Property] | None = None, + parameters: list[Parameter] | None = None, + spec: GEMDMeasurementSpec | None = None, + material: GEMDMaterialRun | None = None, + file_links: list[FileLink] | None = None, + source: PerformedSource | None = None): if uids is None: uids = dict() super(ObjectRun, self).__init__() diff --git a/src/citrine/resources/measurement_spec.py b/src/citrine/resources/measurement_spec.py index 048e71ddf..31412261d 100644 --- a/src/citrine/resources/measurement_spec.py +++ b/src/citrine/resources/measurement_spec.py @@ -1,12 +1,9 @@ """Resources that represent measurement spec data objects.""" from collections.abc import Iterator -from typing import Optional from uuid import UUID from citrine._rest.resource import GEMDResource -from citrine._serialization.properties import List as PropertyList -from citrine._serialization.properties import Optional as PropertyOptional -from citrine._serialization.properties import String, Object, LinkOrElse +from citrine._serialization.properties import LinkOrElse, List, Object, Optional, String from citrine.resources.object_specs import ObjectSpec, ObjectSpecCollection from gemd.entity.attribute.condition import Condition from gemd.entity.attribute.parameter import Parameter @@ -55,24 +52,21 @@ class MeasurementSpec( _response_key = GEMDMeasurementSpec.typ # 'measurement_spec' name = String('name', override=True, use_init=True) - conditions = PropertyOptional(PropertyList(Object(Condition)), 'conditions', override=True) - parameters = PropertyOptional(PropertyList(Object(Parameter)), 'parameters', override=True) - template = PropertyOptional(LinkOrElse(GEMDMeasurementTemplate), - 'template', - override=True, - use_init=True, - ) + conditions = Optional(List(Object(Condition)), 'conditions', override=True) + parameters = Optional(List(Object(Parameter)), 'parameters', override=True) + template = Optional(LinkOrElse(GEMDMeasurementTemplate), 'template', override=True, + use_init=True) def __init__(self, name: str, *, - uids: Optional[dict[str, str]] = None, - tags: Optional[list[str]] = None, - notes: Optional[str] = None, - conditions: Optional[list[Condition]] = None, - parameters: Optional[list[Parameter]] = None, - template: Optional[GEMDMeasurementTemplate] = None, - file_links: Optional[list[FileLink]] = None): + uids: dict[str, str] | None = None, + tags: list[str] | None = None, + notes: str | None = None, + conditions: list[Condition] | None = None, + parameters: list[Parameter] | None = None, + template: GEMDMeasurementTemplate | None = None, + file_links: list[FileLink] | None = None): if uids is None: uids = dict() super(ObjectSpec, self).__init__() diff --git a/src/citrine/resources/measurement_template.py b/src/citrine/resources/measurement_template.py index 55f606782..a48d2deac 100644 --- a/src/citrine/resources/measurement_template.py +++ b/src/citrine/resources/measurement_template.py @@ -1,12 +1,9 @@ """Resources that represent measurement templates.""" -from typing import Optional from collections.abc import Sequence from citrine._rest.resource import GEMDResource -from citrine._serialization.properties import List as PropertyList -from citrine._serialization.properties import Union as PropertyUnion -from citrine._serialization.properties import Optional as PropertyOptional -from citrine._serialization.properties import Object, SpecifiedMixedList, LinkOrElse +from citrine._serialization.properties import LinkOrElse, List, Object, Optional, \ + SpecifiedMixedList, Union from citrine.resources.condition_template import ConditionTemplate from citrine.resources.object_templates import ObjectTemplate, ObjectTemplateCollection from citrine.resources.parameter_template import ParameterTemplate @@ -67,58 +64,37 @@ class MeasurementTemplate( _response_key = GEMDMeasurementTemplate.typ # 'measurement_template' - properties = PropertyOptional( - PropertyList( - PropertyUnion([LinkOrElse(GEMDPropertyTemplate), - SpecifiedMixedList([LinkOrElse(GEMDPropertyTemplate), - PropertyOptional(Object(BaseBounds))])] - ) - ), - 'properties', - override=True - ) - conditions = PropertyOptional( - PropertyList( - PropertyUnion([LinkOrElse(GEMDConditionTemplate), - SpecifiedMixedList([LinkOrElse(GEMDConditionTemplate), - PropertyOptional(Object(BaseBounds))])] - ) - ), - 'conditions', - override=True - ) - parameters = PropertyOptional( - PropertyList( - PropertyUnion([LinkOrElse(GEMDParameterTemplate), - SpecifiedMixedList([LinkOrElse(GEMDParameterTemplate), - PropertyOptional(Object(BaseBounds))])] - ) - ), - 'parameters', - override=True - ) + properties = Optional(List(Union([LinkOrElse(GEMDPropertyTemplate), + SpecifiedMixedList([LinkOrElse(GEMDPropertyTemplate), + Optional(Object(BaseBounds))])])), + 'properties', + override=True) + conditions = Optional(List(Union([LinkOrElse(GEMDConditionTemplate), + SpecifiedMixedList([LinkOrElse(GEMDConditionTemplate), + Optional(Object(BaseBounds))])])), + 'conditions', + override=True) + parameters = Optional(List(Union([LinkOrElse(GEMDParameterTemplate), + SpecifiedMixedList([LinkOrElse(GEMDParameterTemplate), + Optional(Object(BaseBounds))])])), + 'parameters', + override=True) def __init__(self, name: str, *, - uids: Optional[dict[str, str]] = None, - properties: Optional[Sequence[PropertyTemplate - | LinkByUID - | Sequence[PropertyTemplate | LinkByUID - | BaseBounds] - ]] = None, - conditions: Optional[Sequence[ConditionTemplate - | LinkByUID - | Sequence[ConditionTemplate | LinkByUID - | Optional[BaseBounds]] - ]] = None, - parameters: Optional[Sequence[ParameterTemplate - | LinkByUID - | Sequence[ParameterTemplate | LinkByUID - | Optional[BaseBounds]] - ]] = None, - description: Optional[str] = None, - tags: Optional[list[str]] = None): + uids: dict[str, str] | None = None, + properties: Sequence[PropertyTemplate | LinkByUID + | Sequence[PropertyTemplate | LinkByUID | BaseBounds | None] + ] | None = None, + conditions: Sequence[ConditionTemplate | LinkByUID + | Sequence[ConditionTemplate | LinkByUID | BaseBounds | None] + ] | None = None, + parameters: Sequence[ParameterTemplate | LinkByUID + | Sequence[ParameterTemplate | LinkByUID | BaseBounds | None] + ] | None = None, + description: str | None = None, + tags: list[str] | None = None): if uids is None: uids = dict() super(ObjectTemplate, self).__init__() diff --git a/src/citrine/resources/object_templates.py b/src/citrine/resources/object_templates.py index 00836c9a2..54e46485e 100644 --- a/src/citrine/resources/object_templates.py +++ b/src/citrine/resources/object_templates.py @@ -2,7 +2,7 @@ from abc import ABC from typing import TypeVar -from citrine._serialization.properties import Optional as PropertyOptional +from citrine._serialization.properties import Optional from citrine._serialization.properties import String from citrine.resources.templates import Template, TemplateCollection from gemd.entity.template.base_template import BaseTemplate as GEMDTemplate @@ -16,7 +16,7 @@ class ObjectTemplate(Template, GEMDTemplate, ABC): """ name = String('name') - description = PropertyOptional(String(), 'description') + description = Optional(String(), 'description') ObjectTemplateResourceType = TypeVar("ObjectTemplateResourceType", bound="ObjectTemplate") diff --git a/src/citrine/resources/parameter_template.py b/src/citrine/resources/parameter_template.py index 1fc33bab3..379cc5013 100644 --- a/src/citrine/resources/parameter_template.py +++ b/src/citrine/resources/parameter_template.py @@ -1,5 +1,4 @@ """Resources that represent parameter templates.""" -from typing import Optional from citrine._rest.resource import GEMDResource from citrine.resources.attribute_templates import AttributeTemplate, AttributeTemplateCollection @@ -41,9 +40,9 @@ def __init__(self, name: str, *, bounds: BaseBounds, - uids: Optional[dict[str, str]] = None, - description: Optional[str] = None, - tags: Optional[list[str]] = None): + uids: dict[str, str] | None = None, + description: str | None = None, + tags: list[str] | None = None): if uids is None: uids = dict() super(AttributeTemplate, self).__init__() diff --git a/src/citrine/resources/predictor.py b/src/citrine/resources/predictor.py index f4e113b6f..4125f052c 100644 --- a/src/citrine/resources/predictor.py +++ b/src/citrine/resources/predictor.py @@ -1,7 +1,7 @@ """Resources that represent collections of predictors.""" from collections.abc import Iterable from functools import partial -from typing import Any, Optional +from typing import Any from uuid import UUID from gemd.enumeration.base_enumeration import BaseEnumeration @@ -29,7 +29,7 @@ class AsyncDefaultPredictor(Resource["AsyncDefaultPredictor"]): """:UUID: Citrine Platform unique identifier for this task.""" predictor = properties.Optional(properties.Object(GraphPredictor), 'data', serializable=False) - """:Optional[GraphPredictor]:""" + """:GraphPredictor | None:""" status = properties.String('metadata.status', serializable=False) """:str: short description of the resource's status""" @@ -86,7 +86,7 @@ def __init__(self, project_id: UUID, session: Session): def _construct_path(self, uid: UUID | str, - version: Optional[int | str] = None, + version: int | str | None = None, action: str = None) -> str: path = self._path_template.format(project_id=self.project_id, uid=str(uid)) if version is not None: @@ -189,8 +189,8 @@ def rename(self, uid: UUID | str, *, version: int | str, - name: Optional[str] = None, - description: Optional[str] = None + name: str | None = None, + description: str | None = None ) -> GraphPredictor: path = self._construct_path(uid, version, "rename") json = {"name": name, "description": description} @@ -368,7 +368,7 @@ def restore(self, uid: UUID | str): raise NotImplementedError("The restore() method is no longer supported. You most likely " "want restore_root(), or possibly restore_version().") - def _list_base(self, *, per_page: int = 100, archived: Optional[bool] = None): + def _list_base(self, *, per_page: int = 100, archived: bool | None = None): filters = {} if archived is not None: filters["archived"] = archived @@ -406,7 +406,7 @@ def list_archived_versions(self, """List all archived versions of the given Predictor.""" return self._versions_collection.list_archived(uid, per_page=per_page) - def check_for_update(self, uid: UUID | str) -> Optional[GraphPredictor]: + def check_for_update(self, uid: UUID | str) -> GraphPredictor | None: """ Check if there are updates available for a predictor. @@ -423,7 +423,7 @@ def check_for_update(self, uid: UUID | str) -> Optional[GraphPredictor]: Returns ------- - Optional[Predictor] + Predictor | None The update, if an update is available; None otherwise. """ @@ -568,8 +568,8 @@ def rename(self, uid: UUID | str, *, version: int | str, - name: Optional[str] = None, - description: Optional[str] = None) -> GraphPredictor: + name: str | None = None, + description: str | None = None) -> GraphPredictor: """Rename an existing predictor. Both the name and description can be changed. This does not trigger retraining. diff --git a/src/citrine/resources/predictor_evaluation.py b/src/citrine/resources/predictor_evaluation.py index f25cd828e..9840b836d 100644 --- a/src/citrine/resources/predictor_evaluation.py +++ b/src/citrine/resources/predictor_evaluation.py @@ -1,6 +1,6 @@ from collections.abc import Iterable, Iterator from functools import partial -from typing import List, Optional +from typing import List from uuid import UUID from citrine.informatics.executions.predictor_evaluation import PredictorEvaluation, \ @@ -43,9 +43,9 @@ def build(self, data: dict) -> PredictorEvaluation: def _list_base(self, *, per_page: int = 100, - predictor_id: Optional[UUID] = None, - predictor_version: Optional[int | str] = None, - archived: Optional[bool] = None + predictor_id: UUID | None = None, + predictor_version: int | str | None = None, + archived: bool | None = None ) -> Iterator[PredictorEvaluation]: params = {"archived": archived} if predictor_id is not None: @@ -61,8 +61,8 @@ def _list_base(self, def list_all(self, *, per_page: int = 100, - predictor_id: Optional[UUID] = None, - predictor_version: Optional[int | str] = None + predictor_id: UUID | None = None, + predictor_version: int | str | None = None ) -> Iterable[PredictorEvaluation]: """List all predictor evaluations.""" return self._list_base(per_page=per_page, @@ -72,8 +72,8 @@ def list_all(self, def list(self, *, per_page: int = 100, - predictor_id: Optional[UUID] = None, - predictor_version: Optional[int | str] = None + predictor_id: UUID | None = None, + predictor_version: int | str | None = None ) -> Iterable[PredictorEvaluation]: """List non-archived predictor evaluations.""" return self._list_base(per_page=per_page, @@ -84,8 +84,8 @@ def list(self, def list_archived(self, *, per_page: int = 100, - predictor_id: Optional[UUID] = None, - predictor_version: Optional[int | str] = None + predictor_id: UUID | None = None, + predictor_version: int | str | None = None ) -> Iterable[PredictorEvaluation]: """List archived predictor evaluations.""" return self._list_base(per_page=per_page, diff --git a/src/citrine/resources/process_run.py b/src/citrine/resources/process_run.py index fd7cf0622..17d3e9971 100644 --- a/src/citrine/resources/process_run.py +++ b/src/citrine/resources/process_run.py @@ -1,12 +1,9 @@ """Resources that represent process run data objects.""" from collections.abc import Iterator -from typing import Optional from uuid import UUID from citrine._rest.resource import GEMDResource -from citrine._serialization.properties import List as PropertyList -from citrine._serialization.properties import Optional as PropertyOptional -from citrine._serialization.properties import String, Object, LinkOrElse +from citrine._serialization.properties import LinkOrElse, List, Object, Optional, String from citrine.resources.object_runs import ObjectRun, ObjectRunCollection from gemd.entity.attribute.condition import Condition from gemd.entity.attribute.parameter import Parameter @@ -53,22 +50,22 @@ class ProcessRun(GEMDResource['ProcessRun'], ObjectRun, GEMDProcessRun, typ=GEMD _response_key = GEMDProcessRun.typ # 'process_run' name = String('name', override=True, use_init=True) - conditions = PropertyOptional(PropertyList(Object(Condition)), 'conditions', override=True) - parameters = PropertyOptional(PropertyList(Object(Parameter)), 'parameters', override=True) - spec = PropertyOptional(LinkOrElse(GEMDProcessSpec), 'spec', override=True, use_init=True,) - source = PropertyOptional(Object(PerformedSource), "source", override=True) + conditions = Optional(List(Object(Condition)), 'conditions', override=True) + parameters = Optional(List(Object(Parameter)), 'parameters', override=True) + spec = Optional(LinkOrElse(GEMDProcessSpec), 'spec', override=True, use_init=True,) + source = Optional(Object(PerformedSource), "source", override=True) def __init__(self, name: str, *, - uids: Optional[dict[str, str]] = None, - tags: Optional[list[str]] = None, - notes: Optional[str] = None, - conditions: Optional[list[Condition]] = None, - parameters: Optional[list[Parameter]] = None, - spec: Optional[GEMDProcessSpec] = None, - file_links: Optional[list[FileLink]] = None, - source: Optional[PerformedSource] = None): + uids: dict[str, str] | None = None, + tags: list[str] | None = None, + notes: str | None = None, + conditions: list[Condition] | None = None, + parameters: list[Parameter] | None = None, + spec: GEMDProcessSpec | None = None, + file_links: list[FileLink] | None = None, + source: PerformedSource | None = None): if uids is None: uids = dict() super(ObjectRun, self).__init__() diff --git a/src/citrine/resources/process_spec.py b/src/citrine/resources/process_spec.py index b56bee6ac..63a8233c4 100644 --- a/src/citrine/resources/process_spec.py +++ b/src/citrine/resources/process_spec.py @@ -1,12 +1,9 @@ """Resources that represent process spec objects.""" from collections.abc import Iterator -from typing import Optional from uuid import UUID from citrine._rest.resource import GEMDResource -from citrine._serialization.properties import List as PropertyList -from citrine._serialization.properties import Optional as PropertyOptional -from citrine._serialization.properties import String, Object, LinkOrElse +from citrine._serialization.properties import List, LinkOrElse, Object, Optional, String from citrine.resources.object_specs import ObjectSpec, ObjectSpecCollection from gemd.entity.attribute.condition import Condition from gemd.entity.attribute.parameter import Parameter @@ -55,23 +52,20 @@ class ProcessSpec( _response_key = GEMDProcessSpec.typ # 'process_spec' name = String('name', override=True, use_init=True) - conditions = PropertyOptional(PropertyList(Object(Condition)), 'conditions', override=True) - parameters = PropertyOptional(PropertyList(Object(Parameter)), 'parameters', override=True) - template = PropertyOptional(LinkOrElse(GEMDProcessTemplate), - 'template', override=True, - use_init=True, - ) + conditions = Optional(List(Object(Condition)), 'conditions', override=True) + parameters = Optional(List(Object(Parameter)), 'parameters', override=True) + template = Optional(LinkOrElse(GEMDProcessTemplate), 'template', override=True, use_init=True) def __init__(self, name: str, *, - uids: Optional[dict[str, str]] = None, - tags: Optional[list[str]] = None, - notes: Optional[str] = None, - conditions: Optional[list[Condition]] = None, - parameters: Optional[list[Parameter]] = None, - template: Optional[GEMDProcessTemplate] = None, - file_links: Optional[list[FileLink]] = None + uids: dict[str, str] | None = None, + tags: list[str] | None = None, + notes: str | None = None, + conditions: list[Condition] | None = None, + parameters: list[Parameter] | None = None, + template: GEMDProcessTemplate | None = None, + file_links: list[FileLink] | None = None ): if uids is None: uids = dict() diff --git a/src/citrine/resources/process_template.py b/src/citrine/resources/process_template.py index e16c3857a..0a98c64e7 100644 --- a/src/citrine/resources/process_template.py +++ b/src/citrine/resources/process_template.py @@ -1,13 +1,9 @@ """Resources that represent process templates.""" -from typing import Optional from collections.abc import Sequence from citrine._rest.resource import GEMDResource -from citrine._serialization.properties import List as PropertyList -from citrine._serialization.properties import Optional as PropertyOptional -from citrine._serialization.properties import Union as PropertyUnion -from citrine._serialization.properties import String, Object, SpecifiedMixedList, \ - LinkOrElse +from citrine._serialization.properties import LinkOrElse, List, Object, Optional, \ + SpecifiedMixedList, String, Union from citrine.resources.condition_template import ConditionTemplate from citrine.resources.object_templates import ObjectTemplate, ObjectTemplateCollection from citrine.resources.parameter_template import ParameterTemplate @@ -60,47 +56,33 @@ class ProcessTemplate( _response_key = GEMDProcessTemplate.typ # 'process_template' - conditions = PropertyOptional( - PropertyList( - PropertyUnion([LinkOrElse(GEMDConditionTemplate), - SpecifiedMixedList([LinkOrElse(GEMDConditionTemplate), - PropertyOptional(Object(BaseBounds))])] - ) - ), - 'conditions', - override=True - ) - parameters = PropertyOptional( - PropertyList( - PropertyUnion([LinkOrElse(GEMDParameterTemplate), - SpecifiedMixedList([LinkOrElse(GEMDParameterTemplate), - PropertyOptional(Object(BaseBounds))])] - ) - ), - 'parameters', - override=True - ) - allowed_labels = PropertyOptional(PropertyList(String()), 'allowed_labels', override=True) - allowed_names = PropertyOptional(PropertyList(String()), 'allowed_names', override=True) + conditions = Optional(List(Union([LinkOrElse(GEMDConditionTemplate), + SpecifiedMixedList([LinkOrElse(GEMDConditionTemplate), + Optional(Object(BaseBounds))])])), + 'conditions', + override=True) + parameters = Optional(List(Union([LinkOrElse(GEMDParameterTemplate), + SpecifiedMixedList([LinkOrElse(GEMDParameterTemplate), + Optional(Object(BaseBounds))])])), + 'parameters', + override=True) + allowed_labels = Optional(List(String()), 'allowed_labels', override=True) + allowed_names = Optional(List(String()), 'allowed_names', override=True) def __init__(self, name: str, *, - uids: Optional[dict[str, str]] = None, - conditions: Optional[Sequence[ConditionTemplate - | LinkByUID - | Sequence[ConditionTemplate | LinkByUID - | Optional[BaseBounds]] - ]] = None, - parameters: Optional[Sequence[ParameterTemplate - | LinkByUID - | Sequence[ParameterTemplate | LinkByUID - | Optional[BaseBounds]] - ]] = None, - allowed_labels: Optional[list[str]] = None, - allowed_names: Optional[list[str]] = None, - description: Optional[str] = None, - tags: Optional[list[str]] = None): + uids: dict[str, str] | None = None, + conditions: Sequence[ConditionTemplate | LinkByUID + | Sequence[ConditionTemplate | LinkByUID | BaseBounds | None] + ] | None = None, + parameters: Sequence[ParameterTemplate | LinkByUID + | Sequence[ParameterTemplate | LinkByUID | BaseBounds | None] + ] | None = None, + allowed_labels: list[str] | None = None, + allowed_names: list[str] | None = None, + description: str | None = None, + tags: list[str] | None = None): if uids is None: uids = dict() super(ObjectTemplate, self).__init__() diff --git a/src/citrine/resources/project.py b/src/citrine/resources/project.py index ebb7be0f4..8c24de12f 100644 --- a/src/citrine/resources/project.py +++ b/src/citrine/resources/project.py @@ -1,7 +1,6 @@ """Resources that represent both individual and collections of projects.""" from collections.abc import Iterable, Iterator from functools import partial -from typing import Optional from uuid import UUID from citrine._rest.collection import Collection @@ -59,13 +58,13 @@ class Project(Resource['Project']): def __init__(self, name: str, *, - description: Optional[str] = None, - session: Optional[Session] = None, - team_id: Optional[UUID] = None): + description: str | None = None, + session: Session | None = None, + team_id: UUID | None = None): self.name: str = name - self.description: Optional[str] = description + self.description: str | None = description self.session: Session = session - self._team_id: Optional[UUID] = team_id + self._team_id: UUID | None = team_id def _post_dump(self, data: dict) -> dict: return {key: value for key, value in data.items() if value is not None} @@ -87,7 +86,7 @@ def team_id(self): return self._team_id @team_id.setter - def team_id(self, value: Optional[UUID]): + def team_id(self, value: UUID | None): self._team_id = value @classmethod @@ -267,7 +266,7 @@ def _path_template(self): _resource = Project _api_version = 'v3' - def __init__(self, session: Session, *, team_id: Optional[UUID] = None): + def __init__(self, session: Session, *, team_id: UUID | None = None): self.session = session self.team_id = team_id @@ -308,7 +307,7 @@ def get(self, uid: UUID | str) -> Project: else: return ProjectCollection(session=self.session).get(uid) - def register(self, name: str, *, description: Optional[str] = None) -> Project: + def register(self, name: str, *, description: str | None = None) -> Project: """ Create and upload new project. @@ -332,7 +331,7 @@ def register(self, name: str, *, description: Optional[str] = None) -> Project: project = Project(name, description=description) return super().register(project) - def _list_base(self, *, per_page: int = 1000, archived: Optional[bool] = None): + def _list_base(self, *, per_page: int = 1000, archived: bool | None = None): filters = {} if archived is not None: filters["archived"] = str(archived).lower() @@ -399,7 +398,7 @@ def list_archived(self, *, per_page: int = 1000) -> Iterable[Project]: """ return self._list_base(per_page=per_page, archived=True) - def search_all(self, search_params: Optional[dict]) -> Iterable[dict]: + def search_all(self, search_params: dict | None) -> Iterable[dict]: """ Search across all projects in a domain. @@ -457,7 +456,7 @@ def search_all(self, search_params: Optional[dict]) -> Iterable[dict]: def search(self, *, - search_params: Optional[dict] = None, + search_params: dict | None = None, per_page: int = 1000) -> Iterable[Project]: """ Search for projects matching the desired name or description. diff --git a/src/citrine/resources/property_template.py b/src/citrine/resources/property_template.py index 7a25e09fe..dc3d5ab15 100644 --- a/src/citrine/resources/property_template.py +++ b/src/citrine/resources/property_template.py @@ -1,5 +1,4 @@ """Resources that represent property templates.""" -from typing import Optional from citrine._rest.resource import GEMDResource from citrine.resources.attribute_templates import AttributeTemplate, AttributeTemplateCollection @@ -41,9 +40,9 @@ def __init__(self, name: str, *, bounds: BaseBounds, - uids: Optional[dict[str, str]] = None, - description: Optional[str] = None, - tags: Optional[list[str]] = None): + uids: dict[str, str] | None = None, + description: str | None = None, + tags: list[str] | None = None): if uids is None: uids = dict() super(AttributeTemplate, self).__init__() diff --git a/src/citrine/resources/report.py b/src/citrine/resources/report.py index e5c2c8c6e..df643bcf6 100644 --- a/src/citrine/resources/report.py +++ b/src/citrine/resources/report.py @@ -1,5 +1,4 @@ """A resource that represents a single module report.""" -from typing import Optional from uuid import UUID from citrine._rest.resource import Resource @@ -28,7 +27,7 @@ def __init__(self, project_id: UUID, session: Session): def get(self, *, predictor_id: UUID | str, - predictor_version: Optional[int | str] = None) -> Report: + predictor_version: int | str | None = None) -> Report: """Gets a single report keyed on the predictor ID and (optionally) version.""" version = predictor_version or "most_recent" diff --git a/src/citrine/resources/table_config.py b/src/citrine/resources/table_config.py index dfb8c0a5d..086628836 100644 --- a/src/citrine/resources/table_config.py +++ b/src/citrine/resources/table_config.py @@ -1,5 +1,4 @@ from copy import copy -from typing import Optional from uuid import UUID from gemd.entity.object import MaterialRun @@ -82,7 +81,7 @@ class TableConfig(Resource["TableConfig"]): List of row definitions that define the rows of the table columns: list[Column] Column definitions, which describe how the variables are shaped into the table - gemd_query: Optional[GemdQuery] + gemd_query: GemdQuery | None The query used to define the materials underpinning this table generation_algorithm: TableFromGemdQueryAlgorithm Which algorithm was used to generate the config based on the GemdQuery results @@ -99,12 +98,12 @@ def _get_dups(lst: list) -> list: return [x for x in lst if lst.count(x) > 1] config_uid = properties.Optional(properties.UUID(), 'definition_id') - """:Optional[UUID]: Unique ID of the table config, independent of its version.""" + """:UUID | None: Unique ID of the table config, independent of its version.""" version_number = properties.Optional(properties.Integer, 'version_number') - """:Optional[int]: The version of the table config, starting from 1. + """:int | None: The version of the table config, starting from 1. It increases every time the table config is updated.""" version_uid = properties.Optional(properties.UUID(), 'id') - """:Optional[UUID]: Unique ID that specifies one version of one table config.""" + """:UUID | None: Unique ID that specifies one version of one table config.""" name = properties.String("name") description = properties.String("description") @@ -125,7 +124,7 @@ def __init__(self, name: str, rows: list[Row], columns: list[Column], gemd_query: GemdQuery = None, - generation_algorithm: Optional[TableFromGemdQueryAlgorithm] = None): + generation_algorithm: TableFromGemdQueryAlgorithm | None = None): self.name = name self.description = description self.datasets = datasets @@ -167,8 +166,8 @@ def uid(self, new_uid: str | UUID) -> None: def add_columns(self, *, variable: Variable, columns: list[Column], - name: Optional[str] = None, - description: Optional[str] = None + name: str | None = None, + description: str | None = None ) -> 'TableConfig': """Add a variable and one or more columns to this TableConfig (out-of-place). @@ -182,9 +181,9 @@ def add_columns(self, *, Variable to add and use in the added columns columns: list[Column] Columns to add, which must only reference the added variable - name: Optional[str] + name: str | None Optional renaming of the table - description: Optional[str] + description: str | None Optional re-description of the table """ @@ -214,7 +213,7 @@ def add_all_ingredients(self, *, team: 'Team', quantity_dimension: IngredientQuantityDimension, scope: str = CITRINE_SCOPE, - unit: Optional[str] = None + unit: str | None = None ): """Add variables and columns for all of the possible ingredients in a process. @@ -230,9 +229,9 @@ def add_all_ingredients(self, *, a team that has access to the process template quantity_dimension: IngredientQuantityDimension the dimension in which to report ingredient quantities - scope: Optional[str] + scope: str | None the scope for which to get ingredient ids (default is Citrine scope, 'id') - unit: Optional[str] + unit: str | None the units for the quantity, if selecting Absolute Quantity """ @@ -310,7 +309,7 @@ def add_all_ingredients_in_output(self, *, team: 'Team', quantity_dimension: IngredientQuantityDimension, scope: str = CITRINE_SCOPE, - unit: Optional[str] = None + unit: str | None = None ): """Add variables and columns for all possible ingredients in a list of processes. @@ -329,9 +328,9 @@ def add_all_ingredients_in_output(self, *, a team that has access to the process template quantity_dimension: IngredientQuantityDimension the dimension in which to report ingredient quantities - scope: Optional[str] + scope: str | None the scope for which to get ingredient ids (default is Citrine scope, 'id') - unit: Optional[str] + unit: str | None the units for the quantity, if selecting Absolute Quantity """ @@ -424,7 +423,7 @@ def __init__(self, *, team_id: UUID, project_id: UUID, session: Session): self.session: Session = session self.team_id = team_id - def get(self, uid: UUID | str, *, version: Optional[int] = None): + def get(self, uid: UUID | str, *, version: int | None = None): """Get a table config. If no version is specified, then the most recent version is returned. @@ -482,7 +481,7 @@ def default_for_material( material: MaterialRun | LinkByUID | str | UUID, name: str, description: str = None, - algorithm: Optional[TableBuildAlgorithm] = None + algorithm: TableBuildAlgorithm | None = None ) -> tuple[TableConfig, list[tuple[Variable, Column]]]: """ Build best-guess default table config for provided terminal material's history. @@ -543,7 +542,7 @@ def from_query( *, name: str = None, description: str = None, - algorithm: Optional[TableFromGemdQueryAlgorithm] = None, + algorithm: TableFromGemdQueryAlgorithm | None = None, register_config: bool = False ) -> tuple[TableConfig, list[tuple[Variable, Column]]]: """ diff --git a/src/citrine/resources/team.py b/src/citrine/resources/team.py index a185bb3d2..084360dc7 100644 --- a/src/citrine/resources/team.py +++ b/src/citrine/resources/team.py @@ -1,5 +1,5 @@ """Resources that represent both individual and collections of teams.""" -from typing import Optional, Union +from typing import Union from uuid import UUID from gemd.entity.base_entity import BaseEntity @@ -163,7 +163,7 @@ def __init__(self, name: str, *, description: str = "", - session: Optional[Session] = None): + session: Session | None = None): self.name: str = name self.description: str = description self.session: Session = session @@ -252,7 +252,7 @@ def remove_user(self, user_id: str | UUID | User) -> bool: def add_user(self, user_id: str | UUID | User, *, - actions: Optional[list[TEAM_ACTIONS]] = None) -> bool: + actions: list[TEAM_ACTIONS] | None = None) -> bool: """ Add a User to a Team. diff --git a/src/citrine/resources/user.py b/src/citrine/resources/user.py index 819736c33..ffc6ae7cd 100644 --- a/src/citrine/resources/user.py +++ b/src/citrine/resources/user.py @@ -1,5 +1,4 @@ """Resources that represent both individual and collections of users.""" -from typing import Optional from citrine._rest.admin_collection import AdminCollection from citrine._rest.resource import Resource, ResourceTypeEnum @@ -27,7 +26,7 @@ class User(Resource['User']): """ _resource_type = ResourceTypeEnum.USER - _session: Optional[Session] = None + _session: Session | None = None uid = properties.Optional(properties.UUID, 'id') screen_name = properties.String('screen_name') @@ -39,10 +38,10 @@ def __init__(self, *, screen_name: str, email: str, - position: Optional[str], + position: str | None, is_admin: bool): self.email: str = email - self.position: Optional[str] = position + self.position: str | None = position self.screen_name: str = screen_name self.is_admin: bool = is_admin diff --git a/src/citrine/seeding/find_or_create.py b/src/citrine/seeding/find_or_create.py index 71863f42a..e548d8fd1 100644 --- a/src/citrine/seeding/find_or_create.py +++ b/src/citrine/seeding/find_or_create.py @@ -1,7 +1,7 @@ from collections.abc import Callable from copy import deepcopy from logging import getLogger -from typing import Optional, TypeVar +from typing import TypeVar from citrine.exceptions import NotFound from citrine.informatics.workflows.design_workflow import DesignWorkflow @@ -14,7 +14,7 @@ T = TypeVar('T') -def find_collection(*, collection: Collection[T], name: str) -> Optional[T]: +def find_collection(*, collection: Collection[T], name: str) -> T | None: """ Looks through the pages of a collection for a resource with the specified name.