Evaluate in your application
Python SDK
The Python SDK evaluates flags, variations and variables inside your Python application, from a datafile it holds in memory, so no decision waits on the network. Its command line runs your project's test specs through this SDK, and an OpenFeature provider is available.
Install#
pip install "featurevisor>=4.0.0,<5"The SDK supports Python 3.10 and later. Upgrading an existing application? Follow the Python migration guide.
Create an instance#
Fetch a datafile and create an instance with it:
from urllib.request import urlopenimport jsonfrom featurevisor import create_featurevisordatafile_url = "https://cdn.example.com/featurevisor-all.json"with urlopen(datafile_url) as response: datafile_content = json.load(response)f = create_featurevisor({ "datafile": datafile_content,})try: print(f.is_enabled("checkout", {"userId": "user-4"}))finally: f.close()This example closes the instance at once. In a long running application, keep it for every evaluation and close it at shutdown. datafile takes parsed content or a JSON string. Every option is optional, so an instance can start without a datafile and receive one later:
| Option | Sets |
|---|---|
datafile | The datafile to evaluate |
context | The instance context |
stickyFeatures, stickyVariables | Sticky values |
logLevel, onDiagnostic | Diagnostics |
modules | Modules |
Create one instance and reuse it. On a server that handles many users, give each request a child instance.
Concurrency#
Evaluations are safe from many threads once an instance is set up. Apply changes, such as set_datafile, set_context, set_sticky_features, set_sticky_variables, add_module, remove_module and close, from one thread at a time, never during evaluations. Module, event and diagnostic callbacks synchronize any state of their own.
Every method also has a camelCase name, such as isEnabled and getVariable.
Context#
Context is a plain dictionary of attribute values. The instance keeps a context of its own, and each evaluation can add to it.
Set it when creating the instance:
f = create_featurevisor({ "datafile": datafile_content, "context": { "country": "nl", },})Add to it later with set_context, or replace it by passing True as the second argument:
f.set_context({ "userId": "user-4",})f.set_context( { "userId": "user-2", "country": "nl", }, True,)Context passed to an evaluation is merged over the instance context for that call only:
context = { "userId": "user-4", "country": "nl",}f.is_enabled("checkout", context)get_context() returns the instance context, and get_context({"country": "de"}) shows it merged with extra values without storing them.
Dates compare as portable timestamp strings or aware datetime values with a UTC offset. A plain date or a naive datetime is not accepted. Offsets stay within 14 hours, years within 0001 and 9999 in UTC, and fractions are truncated to milliseconds.
Check a flag#
is_enabled reads a flag. Dutch users have the new checkout:
context = { "userId": "user-4", "country": "nl",}if f.is_enabled("checkout", context): ... # show the new checkoutGet a variation#
get_variation returns the variation of a feature, or None if the feature is disabled or has none:
variation = f.get_variation("pricing", context)if variation == "treatment": ... # show the new pricingFor user-4 it returns "control", and for user-2 it returns "treatment".
Get a variable#
get_variable reads a feature variable with a feature key and a variable key. For user-4, the netherlands rule sets the buy button's label to "Nu kopen":
label = f.get_variable("buyButton", "label", context)With a context as its second argument, it reads a global variable instead. supportEmail returns "[email protected]" for user-4:
email = f.get_variable("supportEmail", context)A string second argument means a feature variable, and a dictionary means context for a global variable. The typed methods below follow the same rule.
Treat returned dictionaries and lists as read only. The SDK can share them with its datafile rather than copy them on every evaluation, so copy a value before changing it, and never change a datafile after passing it to the instance.
Typed methods#
Each typed method returns None when the value has a different type, and never converts it. get_variable_integer returns None for the string "1", and get_variable_boolean returns None for "true". A bool is never a number, although Python makes it an int.
get_variable_number reads a variable of type number as a float, and also double in datafiles built before v4.
| Method | Returns |
|---|---|
get_variable_boolean | bool |
get_variable_string | str |
get_variable_integer | int |
get_variable_number | float, whole or fractional |
get_variable_array | list |
get_variable_object | dict |
get_variable_json | Any JSON value |
settings = f.get_variable_object("checkoutSettings", context)# {"currency": "EUR", "paymentMethods": ["card"]}Composed variables#
Read a composed global variable like any other global variable. For a string compose alias, choose the getter for the source's type, such as get_variable_string for an alias of supportEmail. It returns what the source's own getter returns, including decoded JSON and None, with no wrapper or copy.
A composition is evaluated in this order:
- A sticky value for the whole variable, which skips everything after it.
- Root
conditions. When they miss, no source is read and no override runs. The result isdisabledValuewhen supplied, otherwiseNone, with reasonconditions_unmet. - The sources, with their own sticky values, the context and modules taking part as usual.
- The overrides, which run as they do for any global variable.
Compositions have no defaultValue or useDefaultWhenDisabled. With no override match, the reason is variable_composed, and a match reports variable_override_rule, with variableOverridePaths listing every override that changed the value. Only the outer dictionary of a composition is fresh, so treat what it holds as read only.
Cycles, and chains of more than 256 dependencies, fail the whole evaluation. Python's recursion limit can stop a deep chain sooner: with the default limit of 1000, about 120 feature handoffs fit, depending on your own stack. Lint warns about chains deeper than 32, which fit comfortably.
Default values#
Pass defaultVariationValue or defaultVariableValue in the options for when an evaluation produces no value, such as a feature missing from the datafile:
label = f.get_variable( "buyButton", "label", context, {"defaultVariableValue": "Buy"},)A default counts as given whenever the key is present, so "", 0, False and None are all valid defaults.
Evaluate everything at once#
get_feature_evaluations evaluates every loaded feature, or only the keys you pass:
f.get_feature_evaluations(context, [ "checkout", "pricing", "buyButton",])# {# "checkout": {"enabled": True},# "pricing": {"enabled": True, "variation": "control"},# "buyButton": {# "enabled": True,# "variation": "treatment",# "variables": {"label": "Nu kopen", "colour": "#2563eb"},# },# }get_variable_evaluations does the same for global variables:
f.get_variable_evaluations(context, [ "supportEmail", "checkoutSettings",])To see what is loaded without evaluating anything:
get_feature_keys()lists every feature in the datafile, enabled or not.get_variable_keys()lists global variables, andget_variable_keys("buyButton")lists that feature's variables.has_variations("pricing")isTruewhen a feature has variations, andFalsefor an unknown feature.
Hand results from server to client#
Both results have the shape sticky values take. A server can evaluate once per request and pass the results to the browser, so the first render matches what the server saw. The JavaScript SDK's sticky values read them there.
Sticky values#
Sticky values take precedence over the datafile. Use them to keep a user's result fixed, to answer before a datafile has loaded, or in unit tests:
f = create_featurevisor({ "stickyFeatures": { "checkout": {"enabled": True}, "pricing": { "enabled": True, "variation": "treatment", }, }, "stickyVariables": { },})A sticky feature can also set variables. Change sticky values later with set_sticky_features and set_sticky_variables. Both merge by default, and replace the whole map with replace=True:
f.set_sticky_features( { "checkout": {"enabled": False}, }, replace=True,)Treat sticky maps as read only once given to an instance, and change them only through these methods.
Update the datafile#
set_datafile gives the instance a newer datafile, parsed or as a JSON string:
f.set_datafile(datafile_content)It returns True when the datafile is accepted, even if nothing changed, and False when it is rejected or the instance is closed. A rejected datafile leaves the previous one in place and is reported through diagnostics.
Merge or replace#
By default, the new datafile is merged into the current one:
- Its features, segments and global variables replace those with the same keys.
- Definitions it does not contain are kept.
- Its
revisionandschemaVersionare taken.
Pass replace=True to replace the current datafile entirely. Do this when refreshing a complete datafile, so definitions removed from it do not linger:
f.set_datafile(datafile_content, replace=True)Merging is what lets one instance hold datafiles for several targets, loaded as each part of the application needs them. See Loading datafiles on demand.
Refresh on an interval#
Fetch the datafile again every few minutes, scheduling the next attempt even when one fails:
import jsonimport loggingimport threadingfrom urllib.request import urlopendef refresh_datafile(): try: with urlopen(datafile_url, timeout=30) as response: f.set_datafile(json.load(response), replace=True) except Exception: logging.exception("Could not refresh datafile") finally: threading.Timer(5 * 60, refresh_datafile).start()refresh_datafile()A failed fetch keeps the previous datafile. set_datafile does not raise for an invalid datafile, it reports it through diagnostics. Cancel the timer when you stop, since close() does not cancel your timers or requests. Each accepted update emits datafile_set.
Child instances#
A server handles many users at once, so give each request a child with its own context:
child = f.spawn({ "userId": "user-4", "country": "nl",})child.is_enabled("checkout")- The child copies the parent's context keys when it is spawned, and its own values win. Keys the parent adds later still reach it.
- Sticky values are not inherited. Pass
{"stickyFeatures": ...}as the second argument when the child needs some. - A child has the parent's evaluation methods, plus
get_context,set_context,set_sticky_features,set_sticky_variables,onandclose. close()removes the child's listeners, including the ones it registered on its parent.
Events#
on subscribes to an event and returns a function that unsubscribes.
datafile_set#
Emitted for every accepted datafile:
def on_datafile_set(event): revision = event["revision"] previous_revision = event["previousRevision"] revision_changed = event["revisionChanged"] replaced = event["replaced"] features = event["features"] variables = event["variables"] segments = event["segments"] # evaluate the listed features and variables againunsubscribe = f.on("datafile_set", on_datafile_set)unsubscribe()replaced says whether the datafile replaced the previous one or merged into it. features and variables list the keys whose results may have changed: those added, updated or removed, and those that depend on them through conditions, segments and composition sources, however indirectly. Evaluate those again and you have everything that changed.
segments lists the segments whose definitions were added, changed or, on a replace, removed. If a new datafile has the netherlands segment take Belgium too, segments is ["netherlands"], and features and variables include checkout and supportEmail, whose conditions read it. The first datafile lists every feature, global variable and segment. sections lists the changed entries of each datafile section, such as schemas.
context_set#
Emitted by set_context:
def on_context_set(event): context = event["context"] # the new instance context keys = event["keys"] # the top level keys whose values changedf.on("context_set", on_context_set)keys compares values, so a key set again to the value it already holds is not listed. Starting from the instance context {"userId": "user-4", "country": "nl"}:
f.set_context({ "country": "de",})# keys: ["country"]f.set_context({ "country": "de", "plan": "paid",})# keys: ["plan"]f.set_context({ "userId": "user-4", "country": "de",}, True)# keys: ["plan"]A replace also lists the keys it removed, as plan above. Dicts and lists compare item by item, and numbers by value, so 30 and 30.0 are the same while True and 1 are not, but a dict or list given again as the same object counts as changed, since it may have been changed in place.
sticky_features_set#
Emitted by set_sticky_features, with features, every feature that had a sticky value before the call or has one after it, and replaced:
f.on("sticky_features_set", lambda event: print(event["features"]))sticky_variables_set#
Emitted by set_sticky_variables, with variables and replaced:
f.on("sticky_variables_set", lambda event: print(event["variables"]))error#
Emitted for every diagnostic at error:
f.on("error", lambda event: print(event["diagnostic"]["message"]))Diagnostics#
The SDK reports what happens during evaluation as diagnostics, at one of five levels: fatal, error, warn, info and debug. By default, those at info and above go to the console with a [Featurevisor] prefix.
debug shows how each value was evaluated, which helps when a result surprises you. Set the level when creating the instance, or later:
f = create_featurevisor({ "logLevel": "debug",})f.set_log_level("warn")To send diagnostics somewhere other than the console, pass a handler:
def on_diagnostic(diagnostic): level, code, message = diagnostic["level"], diagnostic["code"], diagnostic["message"] # send to your observability systemf = create_featurevisor({ "onDiagnostic": on_diagnostic,})Every diagnostic has level, code, message and a details dictionary. Values about an evaluation, such as featureKey, variableKey, reason and evaluation, are in details. module, moduleName and originalError say where an error came from, when known. A handler that raises stops neither other handlers nor evaluations.
Evaluation errors#
conditions_parse_error is an error diagnostic for malformed stringified conditions. It fires once per selector per datafile load, on first read for v4 datafiles and during set_datafile for v3 datafiles. Its details contain conditions with the raw string, entityType and entityKey.
The whole malformed selector evaluates to False, even under not, while other entities keep working and set_datafile returns True for an otherwise valid datafile. A malformed root gate is unmet and reports conditions_unmet. Handlers may evaluate the same entity again, since results are cached before they run.
Dependency cycles fail the whole evaluation with reason error. SDK evaluation errors return the ordinary false or None result, and other entities keep working.
Evaluation details#
The evaluate methods return how a value was reached, not only the value:
f.evaluate_flag("checkout", context)f.evaluate_variation("pricing", context)f.evaluate_variable("buyButton", "label", context)f.evaluate_variable("supportEmail", context)For user-4, evaluate_flag returns:
{ "type": "flag", "featureKey": "checkout", "reason": "rule", "bucketKey": "user-4.checkout", "bucketValue": 89312, "ruleKey": "netherlands", "enabled": True,}Every evaluation has a type and a reason. Others appear when they apply:
featureKey, absent for global variables, so check for it before using itbucketKeyandbucketValue, from 0 to 100,000, and theruleKeythat matchedenabled,variationandvariationValuevariableKey,variableValue,variableSchemaandvariable, the global variable's definitionvariableOverrideKeyandvariableOverrideIndexwhen a keyed override matched, andvariableOverridePathfor a nested onevariableOverridePaths, every override path matched in order, for accumulating overrides. The singular fields describe the last matchconditionswhen a root gate stopped the evaluationerrorwhen evaluation failed
Evaluation reasons#
Test specs can assert them.
| Reason | Meaning |
|---|---|
feature_not_found | The feature is not in the datafile |
disabled | The feature is disabled |
no_variations | A variation was requested from a feature without variations |
variation_disabled | A disabled feature returned its disabledVariationValue |
variable_not_found | The feature variable or global variable is not in the datafile |
variable_default | The variable returned its default value |
variable_composed | A global variable read its composition sources with no override match |
variable_disabled | A disabled feature returned the variable's disabled value |
variable_override_variation | A feature variable override matched inside a variation |
variable_override_rule | A feature variable override or global variable override matched |
conditions_unmet | Root conditions did not match. See conditions |
no_match | No rule, allocation or variation matched, or the bucket fell outside the rollout |
forced | A force entry supplied the result |
sticky | A sticky value supplied the result |
rule | A matching rule supplied the result |
allocated | Bucketing allocated the result |
error | Evaluation failed. See error |
Modules#
A module hooks into evaluation. It can change the context before an evaluation, change the result after it, or decide how users are bucketed. Every part is optional:
def setup(api): api["onDiagnostic"](lambda diagnostic: ..., {"logLevel": "warn"}) api["reportDiagnostic"]({ "level": "info", "code": "module_ready", "message": f"Ready for revision {api['getRevision']()}", })audit_module = { "name": "audit", "setup": setup, # type, featureKey, variableKey and context "beforeEvaluation": lambda options: { **options, "context": {**options["context"], "plan": "paid"}, }, "afterEvaluation": lambda evaluation, options: evaluation, "bucketKey": lambda options: options["bucketKey"], # between 0 and 100,000 "bucketValue": lambda options: options["bucketValue"], "close": lambda: None,}beforeEvaluation and afterEvaluation run for flags, variations and both kinds of variable, every module in registration order, and must return the options and the evaluation, changed or not. A variable evaluation without a featureKey is a global one. Snake case keys, such as before_evaluation, work too.
beforeEvaluation also runs when a schema validates, with type schema and the schema's key instead of a featureKey, so context it adds reaches the schema's conditions too. afterEvaluation does not run then, since a validation's result is not an evaluation. Check type before reading the keys.
The before evaluation and after evaluation phases each use the module membership at the start of that phase, and the bucket key and bucket value phases each use their own. Adding or removing a module during a phase does not change the iteration already in progress.
If setup raises, the module is not registered. The SDK removes the diagnostic subscriptions it made, reports module_setup_error, and calls its close if it has one.
Dependency evaluations#
Conditions and composition members are evaluated through modules too. Their options include dependencyOf, naming the requesting evaluation by type, featureKey and variableKey. dependencyPurpose is "condition" for an eligibility check and "composition" for a consumed member value. Direct calls have neither.
When tracking consumed evaluations, skip eligibility checks, not every read with dependencyOf, since a variation read through a composition can be an experiment exposure. Within one call, repeated reads with the same inputs and purpose are memoized, so callbacks can run fewer times than there are reads. Return the same result for the same input during one evaluation, and pass values that change through the context.
Register a module#
Pass modules when creating the instance, or add them later:
f = create_featurevisor({ "modules": [audit_module],})remove = f.add_module(tracking_module)# laterremove()f.remove_module("audit")Read the datafile from a module#
A package, such as schemas, reads the datafile through the API setup receives:
get_entry(section, key)returns an entry of a section, a top level key besides Featurevisor's own whose value is an object, such asschemas. Treat it as read only.get_entry_keys(section)lists a section's keys.match_conditions(conditions, context, options)answers the package's own conditions with the instance's engine, segments and feature leaves included.options["readers"]answer leaves only the package knows, such asinput, returningfeaturevisor.conditions.MISSINGfor no value.evaluate({"type": ..., "key": ..., "context": ...}, callback)evaluates the package's own entry as a getter evaluates a flag. Every module'sbeforeEvaluationruns first, withtypeandkeynaming the entry, and the conditions the callback answers withscope.match_conditions(conditions, readers)read the context the modules leave, in one dependency session. The callback's result is returned.
Feature and variable leaves reach modules as dependencies, with dependencyOf naming the package's entry. A module with no evaluation callbacks, such as a package's, costs evaluations nothing.
Schemas#
Schemas validate data against the schemas your datafiles deliver, with the instance you already have, and the same rules, messages and conditions as @featurevisor/schemas in JavaScript.
Schemas are experimental, so their API may change in a minor release, as in JavaScript.
Create a schemas instance#
They are the featurevisor.schemas subpackage, installed with the SDK. Create it from the SDK instance. Call it s, as the SDK instance is f:
from featurevisor.schemas import create_schemass = create_schemas(f)It holds no copy of the schemas. Every call reads the datafile f has now, so a new datafile applies at the next validation. Compiled schemas are kept until a datafile changes them, and handles are safe to use from many threads.
Validate a value#
value = { "displayName": "A", "country": "nl",}result = s.validate("signUp", value)if not result.valid: ... # show result.issues beside the form's fieldss.validate(key, value)returns aValidationResultwith the value itself and itsissues. It never coerces, fills defaults or strips keys.s.is_valid(key, value)returns a boolean.s.parse(key, value)returns the value, or raises aSchemaValidationError, for a server or a script that wants a value or a stop.- All three take a context as a third argument, merged over the instance's, for the conditions a schema's rules read.
- A validation runs as the schema's own evaluation, so a module's
beforeEvaluationsees it, withtypeschemaand the schema'skey, and context the module adds reaches every condition, as it does for flags. s.keys()lists the schemas the datafile has, ands.has(key)says whether it has one.
A value can be dictionaries, lists, strings, numbers, booleans and None, or a dataclass, a pydantic model, a tuple or another mapping or sequence, converted first. A bool is never a number, although Python makes it an int, and an int too big for a double reads as infinity, so it fails a number with a type issue, as in JavaScript.
A key the datafile does not have fails closed, with one schemaNotFound issue, and a schema_not_found diagnostic at warn, once per key and datafile revision. A field a schema in the datafile lacks reports its schemaNotFound issue only, with no diagnostic. A type the package does not know fails every value with a type issue.
Read the issues#
Every issue has a message, a path of object keys and list indices, the code of the rule that failed, its params, and the schema validated. issue.field gives its path as a form names a field, such as items.0.name.
Validation reports every issue it finds, so a form can mark every field at once. An issue about a field with a title carries it in params["title"], and one whose rule a mutation set names it in mutation.
| Code | Raised when |
|---|---|
type | The value has another type |
const, enum | The value is not one allowed |
minimum, maximum | A number is out of range |
minLength, maxLength | A string is too short or too long |
pattern, format | A string has the wrong shape |
minItems, maxItems | A list has too few or too many items |
uniqueItems | A list repeats an item |
required, additionalProperties | A key is missing, or there is one it does not allow |
oneOf | No branch matches, or more than one does |
refine | An issues entry matches, or a check in code fails |
refineError | A check in code raises, or the schema itself cannot be applied |
schemaNotFound | The datafile has no such schema or field |
result.flatten() groups the messages by field, in the shape of Zod's flattenError, and so does flatten() on a SchemaValidationError, for an error response.
Get a handle#
A handle is one schema as an object your code holds: it validates, and describes the schema's fields, constraints, choices and annotations for a form. s.get(key) gives one:
sign_up = s.get("signUp")A handle is stable, and reads the current datafile whenever it is used, so keep one for the life of the application.
| Member | What it is |
|---|---|
validate, is_valid, parse | As on s, without the key |
avalidate | Validation awaiting your checks in code |
field(path) | The handle of one field, such as field("displayName") |
fields | An object's fields' handles, in order, each with its name |
constraints, field_constraints | HTML validation attributes, field_constraints by field path on an object, below |
options, field_options, option(value) | Its choices, field_options by field path on an object, and one choice by value |
render_as | What its rules say the field renders as, such as "select" |
annotations | Its annotations |
with_input(input) | The same handle with an input |
reads | The fields its rules' conditions read |
subscribe(listener) | A call when a new datafile changes the schema |
key, path, name | The schema's key, and the field's path and own name |
field takes a field name as form libraries write it: address.city, items.0.name or items[0].name, and items[].name for every item alike. It follows references and stops at oneOf. A path the schema lacks fails closed with schemaNotFound. Python has no "no value" for a field handle, since None is JSON null and a value, so a field validated alone is always checked as given. required holds the keys it lists whatever properties holds, so an object with only additionalProperties, or none of either, still reports each missing key as required.
Read constraints and choices#
constraints are named after HTML attributes:
sign_up.field("displayName").constraints# Constraints(required=True, min_length=2, max_length=40)sign_up.field("displayName").constraints.attributes()# {"required": True, "minlength": 2, "maxlength": 40}, for a templaterequired, when the key is required, so an input left empty failsmin_lengthandmax_length, from the same rules on a stringminandmax, fromminimumandmaximumon a numberstepof 1, for anintegermultiple, for a list, such as a multiple select
options lists a field's choices in the order of its rules, each with what its annotations say, and option(value) finds one, for showing a value saved earlier:
country = sign_up.field("country")country.options # nl, de and be, each a SchemaOptioncountry.option("nl").title # "Netherlands"country.option("fr") # NoneA schema the datafile lacks has no constraints and no choices, so a form renders before its datafile arrives. render_as answers the switch every generic form writes, from the field's rules alone: "text", "date-time", "version", "number", "boolean", "select", "multiselect", "object" or "list". Your own annotation, such as input: select, still wins over it.
Read annotations#
A handle's annotations are its node's own, and fields gives an object's fields in its order:
sign_up.annotations["title"] # "Create your account"[field.path for field in sign_up.fields]# ["displayName", "email", "country"]default is the value a form starts a field with, and a handle from with_input has the one a mutation sets. Fields an order annotation leaves out come after it, in name order by Unicode code point, as in every SDK. A field or schema the datafile lacks has no annotations, {}. Annotations on Schemas writes them.
Follow the values typed so far#
A handle's constraints and choices describe the schema's own rules, which no condition changes. with_input(input) gives the same handle with an input, such as a form's values, with the mutations that match it applied, so a tax ID shows as required once a business account is chosen:
values = { "accountType": "business", "country": "nl",}sign_up.field("taxId").constraints.required # Falsesign_up.with_input(values).field("taxId").constraints.required # TrueEvery member follows the input, at every depth. reads lists the fields the conditions of a handle's mutations and issues read, so a form can validate again only when one of them changes.
Choose the messages#
messages on create_schemas words every schema's issues, per code, as a template or a function of the params:
s = create_schemas( f, messages={ "required": "This field is required", "maxLength": lambda params, info: f"{params['length']} of {params['maxLength']} characters", },)messages on s.get words one form, by field and code, such as {"displayName": {"maxLength": "Names fit {maxLength} characters"}}. For each issue, the first of these that words it wins:
- A check in code's own message, then the form's.
- The schema's own, and then the
messageof its issues entry. - The application's, from
messagesoncreate_schemas. - The default, in English.
translate on create_schemas gets each issue, with the message chosen, and returns what the issue says, or None to keep it. With translations, messages holds keys, such as errors.required, and translate turns each into text.
Check in code#
Some checks need your application, such as whether a display name is taken. Give them to a handle in refine, each a Refinement with a key and a check, and the path it checks, a message and reads as it needs them:
from featurevisor.schemas import Refinementasync def name_available(display_name, info): return await names.available(display_name)sign_up = s.get("signUp", refine=[ Refinement("nameAvailable", name_available, path="displayName", message="That display name is taken"),])result = await sign_up.avalidate(value)checkgets the value at its path, andinfowith the wholeinputand thecontext. It returnsTruewhen the value passes, or a coroutine of it.- It runs after the schema's rules, and only when nothing at or inside its path has an issue already, so a name that is too short never reaches your database.
- Without a
path, the check gets the whole value, and runs only when the value has no issue at all.readsnames other fields whose issues hold it back too, such asitemsfor a check of an order's total. - Its issue has code
refineandparams["refine"]"nameAvailable", with the field's title. A check that raises givesrefineError, validation fails closed, and oneschema_check_errordiagnostic aterrorsays which check of which schema, once per schema and check and datafile revision, with the exception asoriginalErroranddetailsofschemaKey,checkandpath. A task that is cancelled reports nothing. In a field's handle fromfield,info.inputis the field's value, and only checks that read no other field run there. A field of a view from the schema's root, such aswith_input(values).field("city"), gets the whole input. avalidateawaits every check, running them concurrently, and returns the result, whose issues say what failed.validateanswers at once, so a check that is a coroutine function reportsrefineErrorthere.
Options from your application#
Some lists only your application can answer for, such as cities for a city field. Give a handle an OptionSource in option_sources, with a key, a path, and a search, a lookup or both:
from featurevisor.schemas import OptionSourcecities = OptionSource( "cities", "city", reads=["country"], search=lambda query, info: city_index.search(info.input["country"], query), lookup=lambda city, info: city_index.find(info.input["country"], city), message="Choose a city from the list",)sign_up = s.get("signUp", option_sources=[cities])city = sign_up.with_input({"country": "nl"}).field("city")await city.search("am")# [SchemaOption(value="Amsterdam"), SchemaOption(value="Amersfoort")]searchreturns choices shaped likeoptions, or values alone, now or as a coroutine. A handle'ssearchpasses it the values given towith_input, so the cities follow the country.can_searchsays whether a field has one.lookupreturns the choice for a value,Truewhen it carries nothing more, orNonewhen there is none. A handle'sawait lookup(value)returns the schema's own choice first, then the source's.- Validation runs
lookupas a check in code, after the schema's rules, only for a value that is there, and not while a fieldreadsnames has an issue. A value it cannot find has codeenum, worded bymessage.
Validate on the server#
parse answers a request with a value or a SchemaValidationError, whose flatten() gives the issues by field:
from featurevisor.schemas import SchemaValidationError@app.post("/sign-up")def sign_up_endpoint(body: dict): try: value = s.parse("signUp", body) except SchemaValidationError as error: raise HTTPException(status_code=400, detail=error.flatten()) return create_account(value)A rule changed in your project reaches the browser and the server at their next datafile, so the two never disagree.
Listen for changes#
subscribe calls back when a new datafile changes the schema, through a schema it references too, and returns a function that stops it:
stop = s.get("signUp").field("country").subscribe(lambda: render_choices())A datafile whose schema is unchanged calls nothing. s.close(), or leaving a with create_schemas(f) as s: block, stops every listener the instance started and removes its module from the Featurevisor instance.
Patterns#
Schema patterns are JavaScript regular expressions with the u flag, and they mean the same here: $ is the end of the value, \s is JavaScript's whitespace, and . reads an emoji as one character, as lengths do. A pattern that does not compile with u, such as [a-z\_], fails every value with one schema_pattern_unsupported diagnostic. A mutation whose operations cannot be applied fails the value with refineError and one schema_mutation_error diagnostic, and a check or lookup that raises fails it with refineError and one schema_check_error diagnostic. Validation follows at most 128 references inside one another, which limits how deep a value can nest through them: a tree whose nodes each reference the tree's schema can be 128 levels deep, and the node at the 129th fails closed with refineError and a schema_reference_depth diagnostic. A loop of references at one value reaches the limit too. Each of these diagnostics is reported once per datafile revision, and again for a new one. The translator translate runs last, once mutations have named their issues, so it sees issue.mutation. A with_input view recomputes its members when the instance's context or sticky values change.
Close#
close() removes event listeners and closes modules, on the instance and on a child:
f.close()OpenFeature#
The provider targets OpenFeature specification 0.8.0 through OpenFeature Python SDK 0.10.x, tested with 0.10.0. OpenFeature remains optional and is not installed or imported by the base Featurevisor package.
Installation#
pip install "featurevisor[openfeature]>=4.0.0,<5"If the extra is not installed, importing featurevisor.openfeature reports the installation command needed to enable it.
Provider setup#
from featurevisor.openfeature import FeaturevisorOpenFeatureProviderfrom openfeature import apifrom openfeature.evaluation_context import EvaluationContextprovider = FeaturevisorOpenFeatureProvider({"datafile": datafile_content})api.set_provider_and_wait(provider)client = api.get_client()enabled = client.get_boolean_value( "checkout", False, EvaluationContext(targeting_key="user-4", attributes={"country": "nl"}),)Call api.shutdown() during application shutdown. This closes a Featurevisor instance created by the provider and releases provider subscriptions.
Flag key mapping#
| OpenFeature key | Featurevisor evaluation |
|---|---|
checkout | Boolean flag for checkout |
checkout:variation | Variation value for checkout |
buyButton:label | Variable label for buyButton |
variable:supportEmail | Global variable supportEmail |
Boolean variables use the boolean resolver. Integer and double variables use their matching numeric resolvers. Arrays, objects, and JSON variables use the object resolver.
The first separator divides the feature key from the selector. Use key_separator and variation_key when project keys require a different grammar:
provider = FeaturevisorOpenFeatureProvider( {"datafile": datafile_content}, key_separator="/", variation_key="$variation", global_variable_prefix="$variable",)This makes checkout/$variation the variation key, buyButton/label a feature variable key, and $variable/supportEmail a global variable key. The global prefix defaults to variable and cannot contain the separator.
Context mapping#
OpenFeature's targeting key maps to userId by default. Use targeting_key_field to map it to another Featurevisor context field:
provider = FeaturevisorOpenFeatureProvider( {"datafile": datafile_content}, targeting_key_field="accountId",)The provider distinguishes a missing targeting key from an explicitly empty one when called directly. The upstream OpenFeature Python client merges contexts with a truthy fallback, so it drops an empty targeting key before the provider receives it. To override an existing targeting field with an empty string through that client, set the configured field itself in attributes, such as {"userId": ""}. Clear any inherited nonempty targeting key at its source first, since it would overwrite that attribute again. A narrower empty key may not clear it.
OpenFeature context attributes are copied without mutating the incoming context. Nested arrays and mappings are preserved. Datetimes are normalized to UTC ISO strings, matching the JavaScript provider.
Resolution details#
The provider maps Featurevisor evaluation results to OpenFeature details:
| Featurevisor result | OpenFeature result |
|---|---|
| Forced, sticky, rule match or composed variable | TARGETING_MATCH |
| Traffic allocation | SPLIT |
| Unmet root conditions, disabled variation or disabled variable | DISABLED |
| No match or variable default | DEFAULT |
| Missing feature, variable, or variations | ERROR with FLAG_NOT_FOUND |
| Wrong resolver type | ERROR with TYPE_MISMATCH |
| Invalid datafile | ERROR with PARSE_ERROR |
| Evaluation failure | ERROR with GENERAL |
Errors return the default value supplied to OpenFeature. A malformed datafile uses the stable message Could not parse datafile. A later successful set_datafile call clears the parse error.
Resolution metadata can include featureKey, variableKey, featurevisorReason, revision, schemaVersion, ruleKey, bucketKey, bucketValue, forceIndex, variableOverrideIndex, and variableOverrideKey. The selected variation is exposed as the OpenFeature variant when available.
Tracking#
Tracking is a no-op unless on_track is configured:
def handle_track(name, context, details): print(name, context, details)provider = FeaturevisorOpenFeatureProvider( {"datafile": datafile_content}, on_track=handle_track,)Using an existing Featurevisor instance#
from featurevisor import create_featurevisorfeaturevisor = create_featurevisor({"datafile": datafile_content})provider = FeaturevisorOpenFeatureProvider(featurevisor=featurevisor)The caller owns an instance passed this way. Provider shutdown does not close it. Call featurevisor.close() when every consumer is finished with it. When the provider creates the instance from options, the provider owns and closes it. If both are supplied, featurevisor takes precedence over the options dictionary.
An invalid initial datafile in an owned instance fails set_provider_and_wait with ParseError, independently of logLevel. A valid datafile update clears the error and emits readiness. Supplied diagnostic callbacks keep their normal filtering. Shutdown removes provider subscriptions and closes only an owned instance.
See the OpenFeature provider guide for resolution reasons, errors, metadata, tracking, lifecycle, and providers for other languages.
CLI usage#
Install the package in your Python environment:
python -m pip install "featurevisor>=4.0.0,<5"The native test runner requires Node.js 24 or later. Install the Node.js CLI in your Featurevisor project:
npm install --save-dev @featurevisor/cli@^4.0.0The native CLI provides test, benchmark and assess-distribution. Use the Node.js CLI for authoring commands such as init, lint and build. Native commands delegate project parsing, test listing, matrix expansion and datafile generation to npx featurevisor, then evaluate with this Python SDK. The SDK runtime has no Node.js dependency.
Options use kebab case, such as --project-directory-path. The camelCase forms from earlier releases still work, and --root-directory-path is an alias for --project-directory-path. Pass values as --name=value or --name value. Repeat --target to select several targets in order. Run <command> --help to list every option.
Duplicate targets are evaluated once, at their first position. --n and -n accept a positive integer.
Test#
python -m featurevisor test \ --project-directory-path=/path/to/featurevisor-project \ --only-failuresSee Testing for authoring specs and Checks for check syntax and operators.
Useful test options:
--key-pattern=<pattern>and--assertion-pattern=<pattern>filter tests.--entity-type=scenarioselects scenarios, and--entity-type=schemaschema specs, which validate their values withfeaturevisor.schemasas the JavaScript CLI does.--set=<set>selects one project set. Omitting--setruns all sets.--case=<id>reruns one expanded case. Copy the opaque ID or rerun command from a failure report.--json --prettyproduces an indented JSON report.--coveragereports observed rule and override selections.--uncoveredlists features and global variables without associated specs.--only-failures,--quiet,--verboseand--show-datafilecontrol diagnostic output.
Benchmark#
The examples below use a project without environments. Add --environment=<name> if your project configures environments. In a sets project, omit --set to run every set or pass --set=<name>. Repeat --target=<key> to evaluate specific target datafiles. The Node.js CLI validates these options and builds the datafiles. Python evaluates them. Replace checkout with a feature defined in your project.
python -m featurevisor benchmark \ --project-directory-path=/path/to/featurevisor-project \ --feature=checkout \ --context='{"country":"nl"}' \ --n=1000Use --variation for a variation or --variable=<key> for a feature variable. Omit --feature to benchmark a global variable. Do not combine --variation with --variable. See Benchmarking.
Assess distribution#
python -m featurevisor assess-distribution \ --project-directory-path=/path/to/featurevisor-project \ --feature=checkout \ --populate-uuid=userId \ --n=1000Repeat --populate-uuid=<key> to generate UUID values for multiple context attributes. Supply one key per option. See Assess distribution.
GitHub repositories#
- SDK: featurevisor/featurevisor-python
- Example application: featurevisor/featurevisor-example-python

