Python WDL package¶
miniwdl is a developer toolkit and local runner for
the bioinformatics-focused Workflow Description Language (WDL). This
documentation covers the Python WDL package, which provides parsing, static analysis, and
execution of WDL documents. Simply import WDL once miniwdl has been installed.
GitHub repo for installation and further background
Codelabs on using this package
- WDL.load(uri, path=None, check_quant=True, read_source=None, import_max_depth=10)[source]¶
Parse a WDL document given filename/URI, recursively descend into imported documents, then typecheck the tasks and workflow.
- Parameters:
uri (str) – filename/URI of the WDL document to load
path (list[str] | None) – local filesystem directories to search for imports, in addition to the current working directory
check_quant (bool) – set to
Falseto relax static typechecking of the optional (?) and nonempty (+) type quantifiers. This is discouraged, but may be useful for older WDL workflows which assume less-rigorous static validation of these annotations.read_source (Callable[[str, list[str], Document | None], Awaitable[ReadSourceResult]] | None) – async routine to read the WDL source code from filename/URI; see
read_source_default()below for detailsimport_max_depth (int) – to prevent recursive import infinite loops, fail when there are too many import nesting levels (default 10)
- Raises:
WDL.Error.SyntaxError – when the document is syntactically invalid under the WDL grammar
WDL.Error.ValidationError – when the document is syntactically OK, but fails typechecking or other static validity checks
WDL.Error.MultipleValidationErrors – when multiple validation errors are detected in one pass, listed in the
exceptionsattributeWDL.Error.ImportError – when an imported sub-document can’t be loaded; the
__cause__attribute has the specific error
- Return type:
- async WDL.load_async(uri, path=None, check_quant=True, read_source=None, import_max_depth=10)[source]¶
Async version of
load(), with all the same arguments
- async WDL.read_source_default(uri, path, importer)[source]¶
Default async routine for the
read_sourceparameter toload()andload_async(), which they use to read the desired WDL document and its imports. This default routine handles local files only, supplying the search path logic to resolve relative filenames; it fails with network URIs.- Parameters:
uri (str) – Filename/URI to read, as provided to
load()or the WDL import statement; may be relativepath (list[str]) – Local directories to search for relative imports
importer (Document | None) – The document importing the one here requested, if any; the
importer.pos.uriandimporter.pos.abspathfields may be relevant to resolve relative imports.
- Returns:
WDL.ReadSourceResult(source_text="...", abspath="...")- Return type:
The returned
NamedTupleprovides the WDL source code and the absolute filename/URI from which the source was read (e.g. after resolving a relative path).Callers may wish to override
read_sourcewith logic to download source code from network URIs, and for local filenames fall back toreturn await WDL.read_source_default(...).Note: the synchronous
load()merely runsload_async()in a new event loop (viaasyncio.run()) and returns the result.
- async WDL.resolve_file_import(uri, path, importer)[source]¶
Exposes the logic by which
read_source_default()resolvesurito the absolute path of an extant file. Ifuriis already an absolute path, it’s normalized and returned. A relativeuriis resolved by first joining it to either the directory of the importer document (if any), or the process current working directory (otherwise). Failing that, it’s searched in thepathdirectories (in reverse order).Security-focused applications may wish to override
read_sourcewith logic to restrict allowable results ofresolve_file_import, to prevent WDL source code from triggering access to arbitrary filesystem paths. No such restrictions are applied by default.
- WDL.values_from_json(values_json, available, required=None, namespace='')[source]¶
Given a dict parsed from Cromwell-style JSON and the available input (or output) declarations of a task or workflow, create a
WDL.Env.Bindings[Value.Base].
- WDL.values_to_json(values_env, namespace='')[source]¶
Convert a
WDL.Env.Bindings[WDL.Value.Base]to a dict whichjson.dumpsto Cromwell-style JSON.
Tree¶
Abstract syntax tree (AST) for WDL documents, containing tasks and workflows, which contain
declarations, calls, and scatter & if sections. The AST is typically constructed by
load().
The WDL.Tree.* classes are also exported by the base WDL module, i.e. WDL.Tree.Document
can be abbreviated WDL.Document.
- class WDL.Tree.StructTypeDef(pos, name, members, parameter_meta, meta, imported=None)[source]¶
Bases:
SourceNodeWDL struct type definition
- Parameters:
- imported: tuple[Document, StructTypeDef] | None¶
- Type:
tuple[Document,StructTypeDef] | None
If this struct is imported from another document, references that document and its definition there. The referenced definition might itself be imported from yet another document.
- class WDL.Tree.WorkflowNode(workflow_node_id, pos)[source]¶
Bases:
SourceNode,ABCBase class for workflow “nodes” including declarations, calls, and scatter/if sections and their bodies.
Each node has a human-readable ID string which is unique within the workflow. It also exposes the set of workflow node IDs upon which it depends. Abstractly, workflow execution can proceed by “visiting” each node once all of its dependencies have been visited, performing some action(s) appropriate to the specific node type (such as evaluating a WDL expression and binding a name in the environment, or executing a task and binding its outputs).
- Parameters:
workflow_node_id (str)
pos (SourcePosition)
- class WDL.Tree.Decl(pos, type, name, expr=None, id_prefix='decl')[source]¶
Bases:
WorkflowNodeA value declaration within a task or workflow.
Within a task, the declarations can be viewed as “workflow nodes” insofar as they must be evaluated in an order consistent with their dependency structure, and ensured acyclic. The “workflow node IDs” of a task’s declarations are unique within the task only, and unrelated to the top-level workflow, if any, in the WDL document.
- Parameters:
pos (SourcePosition)
type (Base)
name (str)
expr (Base | None)
- expr: Base | None¶
- Type:
WDL.Expr.Base | None
Bound expression, if any
- class WDL.Tree.Task(pos, name, inputs, postinputs, command, outputs, parameter_meta, runtime, meta, runtime_section_name=None, runtime_section_pos=None)[source]¶
Bases:
SourceNodeWDL task, with its input & output declarations, command, and requirements/runtime
- Parameters:
- inputs: list[Decl] | None¶
- Type:
list[WDL.Tree.Decl] | None
Declarations in the
input{}task section, if it’s present
- runtime: dict[str, Base]¶
- Type:
requirements{}section (runtime{}before WDL 1.2), with keys and corresponding expressions to be evaluated
- runtime_section_name: str | None¶
- Type:
str | None
Original keyword of the requirements/runtime section, either
"requirements"or"runtime"(None if absent)
- runtime_section_pos: SourcePosition | None¶
- Type:
WDL.SourcePosition | None
Source position of the requirements/runtime section, if present
- task_runtime_info_struct_type(*, output_section=False)[source]¶
Build the synthetic task runtime info struct type (WDL 1.2+).
- Parameters:
output_section (bool)
- Return type:
- property available_inputs: Bindings[Decl]¶
- Type:
Yields the task’s input declarations. This is all declarations in the task’s
input{}section, if it’s present. Otherwise, it’s all declarations in the task, excluding outputs. (This dichotomy bridges pre-1.0 and 1.0+ WDL versions.)Each input is at the top level of the Env, with no namespace.
- property required_inputs: Bindings[Decl]¶
- Type:
Yields the input declarations which are required to call the task (available inputs that are unbound and non-optional).
Each input is at the top level of the Env, with no namespace.
- class WDL.Tree.Call(pos, callee_id, alias, inputs, after=None)[source]¶
Bases:
WorkflowNodeA call (within a workflow) to a task or sub-workflow
- Parameters:
- callee_id: list[str]¶
-
The called task/workflow; either one string naming a task in the current document, or an import namespace and task/workflow name.
- callee: Task | Workflow | None¶
- Type:
Refers to the
Taskor importedWorkflowobject to be called (after AST typechecking)
- after: list[str]¶
-
Call names on which this call depends (even if none of their outputs are used in this call’s inputs)
- property available_inputs: Bindings[Decl]¶
- Type:
Yields the task/workflow inputs which are not supplied in the call
inputs:, and thus may be supplied at workflow launch; in namespaces according to the call names.
- property required_inputs: Bindings[Decl]¶
- Type:
Yields the required task/workflow inputs which are not supplied in the call
inputs:(incomplete calls), and thus must be supplied at workflow launch; in namespaces according to the call name.
- class WDL.Tree.CallTry(pos, callee_id, alias, inputs, after=None)[source]¶
Bases:
CallA call whose tolerated runtime failures produce null optional outputs
- Parameters:
- class WDL.Tree.Gather(section, referee)[source]¶
Bases:
WorkflowNodeA
Gathernode symbolizes the operation to gather an array of declared values or call outputs in a scatter section, or optional values from a conditional section. These operations are implicit in the WDL syntax, but explicating them in the AST facilitates analysis of the workflow’s data types and dependency structure.Each scatter/conditional section provides
Gathernodes to expose the section body’s products to the rest of the workflow. When aWDL.Expr.Identelsewhere identifies a node inside the section, itsrefereeattribute is the correspondingGathernode, which in turn references the interior node. The interior node might itself be anotherGathernode, from a nested scatter/conditional section.- Parameters:
section (WorkflowSection)
- section: WorkflowSection¶
- Type:
The
Scatter/Conditionalsection implying this Gather operation
- class WDL.Tree.WorkflowSection(body, *args, **kwargs)[source]¶
Bases:
WorkflowNodeBase class for workflow nodes representing scatter and conditional sections
- Parameters:
body (list[WorkflowNode])
- body: list[WorkflowNode]¶
- Type:
Section body, potentially including nested sections.
- gathers: dict[str, Gather]¶
-
Gathernodes exposing the section body’s products to the rest of the workflow. The dict is keyed byworkflow_node_idof the interior node, to expedite looking up the corresponding gather node.The section’s body and gather nodes do not explicitly include the section node among their dependencies. Such dependence is implicit because the body subgraph can be “instantiated” only upon visiting the section node at runtime.
- class WDL.Tree.Scatter(pos, variable, expr, body)[source]¶
Bases:
WorkflowSectionWorkflow scatter section
- Parameters:
pos (SourcePosition)
variable (str)
expr (Base)
body (list[WorkflowNode])
- class WDL.Tree.Conditional(pos, expr, body)[source]¶
Bases:
WorkflowSectionWorkflow conditional (if) section
- Parameters:
pos (SourcePosition)
expr (Base)
body (list[WorkflowNode])
- class WDL.Tree.Workflow(pos, name, inputs, body, outputs, parameter_meta, meta, output_idents=None, output_idents_pos=None)[source]¶
Bases:
SourceNodeWDL workflow, with its input & output declarations and body of calls, declarations, and
scatter/ifsections- Parameters:
- body: list[WorkflowNode]¶
- Type:
list[WDL.Tree.Decl | WDL.Tree.Call | WDL.Tree.Scatter | WDL.Tree.Conditional]
Workflow body in between
input{}andoutput{}sections, if any
- outputs: list[Decl] | None¶
- Type:
list[WDL.Tree.Decl] | None
Workflow output declarations, if the
output{}section is present
- complete_calls: bool¶
After typechecking, False if the workflow has a call which does not supply all required inputs (and thus cannot be called from another workflow).
- property available_inputs: Bindings[Decl]¶
- Type:
The workflow’s input declarations. This includes:
1. If the
input{}workflow section is present, all declarations within that section. Otherwise, all declarations in the top-level workflow body, excluding outputs. (This dichotomy bridges pre-1.0 and 1.0+ WDL versions.) These appear at the top level of the Env, with no namespace.Available inputs of all calls in the workflow, namespaced by the call names.
- property required_inputs: Bindings[Decl]¶
- Type:
The subset of available inputs which are required to start the workflow.
- property incomplete_calls: Iterable[Call]¶
- Type:
Iterable[WDL.Tree.Call]
Yields the calls in the workflow, including those nested within scatter and conditional sections, which don’t supply all of the callee’s required inputs. Such inputs must instead be supplied at workflow launch, which means the workflow can’t be used as a subworkflow (
complete_callsis False).
- property effective_outputs: Bindings[Base]¶
- Type:
If the
output{}workflow section is present, yields the names and types therein, at the top level of the Env. Otherwise, yield all the call outputs, namespaced and typed appropriately.
- class WDL.Tree.SourceComment(pos, text)[source]¶
Bases:
NamedTuplePosition and text of a comment. The text includes the
#and any preceding or trailing spaces/tabs.- Parameters:
pos (SourcePosition)
text (str)
- pos: SourcePosition¶
Alias for field number 0
- class WDL.Tree.DocImport(pos, uri, namespace, aliases, doc)[source]¶
Bases:
NamedTupleRepresents one imported document, with position of the import statement, import URI, namespace, struct type aliases, and (after typechecking) the
Documentobject.- Parameters:
- pos: SourcePosition¶
Alias for field number 0
- class WDL.Tree.Document(source_text, pos, imports, struct_typedefs, tasks, workflow, comments, wdl_version)[source]¶
Bases:
SourceNodeTop-level document, with imports, tasks, and up to one workflow. Typically returned by
load().- Parameters:
source_text (str)
pos (SourcePosition)
struct_typedefs (Bindings[StructTypeDef])
workflow (Workflow | None)
comments (list[SourceComment])
wdl_version (str | None)
- struct_typedefs: Bindings[StructTypeDef]¶
- workflow: Workflow | None¶
- Type:
WDL.Tree.Workflow | None
- source_lines: list[str]¶
-
Original WDL source code text split by newlines.
SourcePositionline numbers are one-based, so line numberLcorresponds tosource_lines[L-1].
- source_comments: list[SourceComment | None]¶
- Type:
list[SourceComment | None]
Lookup table for source code comments.
source_commentshas the same length assource_lines, and each entry is theWDL.Tree.SourceCommentfound on the corresponding source line, orNoneif the line has no comment.
- class WDL.Tree.ReadSourceResult(source_text, abspath)[source]¶
Bases:
NamedTupleResult of a
read_sourceroutine (seeWDL.read_source_default()): the WDL source text, and the absolute filename/URI from which it was read.
Expr¶
WDL expressions composing literal values, arithmetic, comparison, conditionals, string interpolation, arrays & maps, and function applications. These appear on the right-hand side of value declarations and in task command substitutions, task requirements/runtime sections, and workflow scatter and conditional sections.
The abstract syntax tree (AST) for any expression is represented by an instance
of a Python class deriving from WDL.Expr.Base. Any such node may have other
nodes attached “beneath” it. An expression can be evaluated to a Value
given a suitable WDL.Env.Bindings[Value.Base].
- class WDL.Expr.Base(pos)[source]¶
Bases:
SourceNode,ABCSuperclass of all expression AST nodes
- Parameters:
pos (SourcePosition)
- property type: Base¶
- Type:
WDL type of this expression. Undefined on construction; populated by one invocation of
infer_type.
- infer_type(type_env, stdlib, check_quant=True, struct_types=None)[source]¶
Infer the expression’s type within the given type environment. Must be invoked exactly once prior to use of other methods.
- Parameters:
stdlib (Base) – a context-specific standard function library for typechecking
check_quant (bool) – when
False, disables static validation of the optional (?) type quantifier whentypecheck()is called on this expression, so for example typeT?can satisfy an expected typeT. Applies recursively to the type inference and checking of any sub-expressions.struct_types (Bindings[dict[str, Base]] | None) – struct type definitions available in the document, if any
- Raises:
WDL.Error.StaticTypeMismatch – when the expression fails to type-check
- Returns:
self- Return type:
- typecheck(self, expected: Type.Base) WDL.Expr.Base[source]¶
Check that this expression’s type is, or can be coerced to,
expected.- Raises:
- Returns:
self- Parameters:
expected (Base)
- Return type:
- class WDL.Expr.Boolean(pos, literal)[source]¶
Bases:
BaseBoolean literal
- Parameters:
pos (SourcePosition)
literal (bool)
- class WDL.Expr.Int(pos, literal)[source]¶
Bases:
BaseInteger literal
- Parameters:
pos (SourcePosition)
literal (int)
- class WDL.Expr.Float(pos, literal)[source]¶
Bases:
BaseNumeric literal
- Parameters:
pos (SourcePosition)
literal (float)
- class WDL.Expr.Null(pos)[source]¶
Bases:
BaseWDL
Noneliteral(called
Nullto avoid conflict with PythonNone)- Parameters:
pos (SourcePosition)
- class WDL.Expr.Placeholder(pos, options, expr)[source]¶
Bases:
BaseHolds an expression interpolated within a string or command
- Parameters:
pos (SourcePosition)
expr (Base)
- property children: Iterable[SourceNode]¶
- Type:
Iterable[SourceNode]
Yield all child nodes
- class WDL.Expr.String(pos, parts, command=False)[source]¶
Bases:
BaseString literal, possibly interleaved with expression placeholders for interpolation
- Parameters:
pos (SourcePosition)
parts (list[str | Placeholder])
command (bool)
- parts: list[str | Placeholder]¶
- Type:
The parts list begins and ends with the original delimiters (quote marks, braces, or triple angle brackets). Between these is a sequence of literal strings and/or interleaved placeholder expressions. Escape sequences in the literals are NOT decoded until the string literal is evaluated (although the parser will have checked they’re valid).
- property children: Iterable[SourceNode]¶
- Type:
Iterable[SourceNode]
Yield all child nodes
- class WDL.Expr.TaskCommand(pos, parts)[source]¶
Bases:
StringSpecialization of
Stringfor task commands, with slightly different evaluation rules: common leading whitespace is removed (dedentation) and escape sequences are passed through for shell interpretation. Also, for historical reasons, thepartsdoes not include the beginning & ending delimiters.- Parameters:
pos (SourcePosition)
parts (list[str | Placeholder])
- class WDL.Expr.MultiLineString(pos, parts, command=False)[source]¶
Bases:
StringSpecialization of
Stringfor WDL 1.2 multi-line string literals, with special evaluation rules: trim whitespace following the<<<and preceding the>>>delimiters and dedent the remaining non-blank lines, while allowing newlines to be escaped.- Parameters:
pos (SourcePosition)
parts (list[str | Placeholder])
command (bool)
- class WDL.Expr.Array(pos, items)[source]¶
Bases:
BaseArray literal
- Parameters:
pos (SourcePosition)
- property children: Iterable[SourceNode]¶
- Type:
Iterable[SourceNode]
Yield all child nodes
- class WDL.Expr.Pair(pos, left, right)[source]¶
Bases:
BasePair literal
- Parameters:
pos (SourcePosition)
left (Base)
right (Base)
- property children: Iterable[SourceNode]¶
- Type:
Iterable[SourceNode]
Yield all child nodes
- class WDL.Expr.Map(pos, items)[source]¶
Bases:
BaseMap literal
- Parameters:
pos (SourcePosition)
- property children: Iterable[SourceNode]¶
- Type:
Iterable[SourceNode]
Yield all child nodes
- class WDL.Expr.Struct(pos, members, struct_type_name=None)[source]¶
Bases:
BaseStruct literal
- Parameters:
pos (SourcePosition)
struct_type_name (str | None)
- members: dict[str, Base]¶
- Type:
The struct literal is modelled initially as a bag of keys and values, which can be coerced to a specific struct type during typechecking.
- struct_type_name: str | None¶
- Type:
str | None
In WDL 1.1+ each struct literal may specify the intended struct type name.
- property children: Iterable[SourceNode]¶
- Type:
Iterable[SourceNode]
Yield all child nodes
- class WDL.Expr.IfThenElse(pos, condition, consequent, alternative)[source]¶
Bases:
BaseTernary conditional expression
- Parameters:
pos (SourcePosition)
condition (Base)
consequent (Base)
alternative (Base)
- property children: Iterable[SourceNode]¶
- Type:
Iterable[SourceNode]
Yield all child nodes
- class WDL.Expr.Ident(pos, name)[source]¶
Bases:
BaseAn identifier referencing a named value or call output.
Identnodes are wrapped inGetnodes, as discussed below.- Parameters:
pos (SourcePosition)
name (str)
- referee: None | Tree.Decl | Tree.Call | Tree.Scatter | Tree.Gather¶
After typechecking within a task or workflow, stores the AST node to which the identifier refers: a
WDL.Tree.Declfor value references; aWDL.Tree.Callfor call outputs; aWDL.Tree.Scatterfor scatter variables; or aWDL.Tree.Gatherobject representing a value or call output that resides within a scatter or conditional section.
- property children: Iterable[SourceNode]¶
- Type:
Iterable[SourceNode]
Yield all child nodes
- class WDL.Expr.Get(pos, expr, member)[source]¶
Bases:
BaseAST node representing access to a value by identifier (including namespaced ones), or accessing a member of a pair or struct as
.member.The entanglement of these two cases is inherent in WDL. Consider the syntax
leftname.midname.rightname. One interpretation is thatleftnameis an identifier for a struct value, and.midname.rightnamerepresents a chain of struct member accesses. But another possibility is thatleftnameis a call,midnameis a struct output of that call, andrightnameis a member of that struct. These cases can’t be distinguished by the syntax parser alone, but must be resolved during typechecking with reference to the calls and identifiers available in the environment.The typechecker does conveniently resolve such cases, and to minimize the extent to which it has to restructure the AST in doing so, all identifiers (with or without a namespace) are represented as a
Getnode wrapping anIdentnode. TheGetnode may specify a member name to access, but may not if the identifier is to be accessed directly. On the other hand, the expression inside aGetnode need not be a simple identifier, e.g.arr[1].memb.leftis represented as:Get(Get(Apply("_at", Get(Ident("arr")), 1),"memb"),"left")- Parameters:
pos (SourcePosition)
expr (Base)
member (str | None)
- member: str | None¶
- Type:
str | None
If the expression is accessing a pair/struct member, then
expr.typeisWDL.Type.PairorWDL.Type.StructInstanceand this field gives the desired member name (leftorrightfor pairs).Otherwise the expression accesses
exprdirectly, andmemberisNone.
- property children: Iterable[SourceNode]¶
- Type:
Iterable[SourceNode]
Yield all child nodes
- class WDL.Expr.Apply(pos, function, arguments)[source]¶
Bases:
BaseApplication of a built-in or standard library function
- Parameters:
pos (SourcePosition)
function (str)
- property children: Iterable[SourceNode]¶
- Type:
Iterable[SourceNode]
Yield all child nodes
Env¶
Environments, for identifier resolution during WDL typechecking and evaluation.
- class WDL.Env.Binding(name, value, info=None)[source]¶
Bases:
Generic[T]An individual, immutable binding of a possibly-namespaced name to a right-hand-side value of type
T.Tis typicallyValue.Base(value environments) orType.Base(type environments). The binding may also reference an additional informational value of arbitrary type.- property value: T¶
- Type:
T
- class WDL.Env.Bindings(binding: WDL.Env.Binding[T] | None = None, next: WDL.Env.Bindings[T] | None = None)[source]¶
Bases:
Generic[T]An environment consisting of an immutable linked-list of
WDL.Env.Bindingobjects.WDL.Env.Bindings()is the empty environment.Bindings[T]is iterable for the individualBinding[T]objects:env = WDL.Env.Bindings() env = env.bind("x", 1).bind("y", 42) print(env["x"]) # 1 print(",".join(str(b.value) for b in env)) # 1,42
- bind(name, value, info=None)[source]¶
Return an environment with a new binding prepended. Any existing binding for the same name is shadowed by the new one. (This should not usually arise in view of the immutability of WDL values.)
- resolve_binding(name)[source]¶
Look up a
WDL.Env.Bindingobject by name
- get(name, default=None)[source]¶
Look up a bound value by name, returning the default value or
Noneif there’s no such binding.- Parameters:
name (str)
default (T | None)
- Return type:
T | None
- map(f)[source]¶
Copy the environment with each binding transformed by the given function. If the function returns
Nonethen the binding is excluded.
- subtract(rhs)[source]¶
Copy the environment excluding any binding for which
rhshas a binding with the same name
- property namespaces: set[str]¶
-
Return the environment’s namespaces, all the distinct dot-separated prefixes of the binding names. Each element ends with a dot.
Type¶
WDL data types
WDL has both atomic types such as Int, Boolean, and String; and
parametric types like Array[String] and
Map[String,Array[Array[Float]]]. Here, each type is represented by an
immutable instance of a Python class inheriting from WDL.Type.Base. Such
types are associated with expressions, statically prior to evaluation, as well
as with values and identifier bindings after evaluation.
An atomic type like Int is represented by WDL.Type.Int(). Atomic types
can be checked either with isinstance(t,WDL.Type.Int), which ignores the
possible optional quantifier (thus satisfied by Int or Int?), or with
t == WDL.Type.Int(optional=True) to include the quantifier in the
comparison.
A parametric type like Array[String] is represented by
WDL.Type.Array(WDL.Type.String()). Any kind of array satisfies
isinstance(t,WDL.Type.Array), and
WDL.Type.Array(WDL.Type.String()) == WDL.Type.Array(WDL.Type.String()), but
for example
WDL.Type.Array(WDL.Type.String()) != WDL.Type.Array(WDL.Type.Float()).
The type classes include a method indicating if a value of the type can be coerced to some other desired type, according to the following rules:
Intcoerces toFloatBoolean,Int,Float,File, andDirectorycoerce toStringStringcoerces toFile,Directory,Int, andFloatArray[T]coerces toStringprovidedTdoes as wellTcoerces toT?but the reverse is not true in general*Array[T]+coerces toArray[T]but the reverse is not true in general*
(*) The reverse coercions are statically permitted in expressions set up with
Expr.infer_type(check_quant=False) although they may fail at runtime. This
also enables coercion of T to Array[T]+ (an array of length 1).
- class WDL.Type.Base[source]¶
Bases:
ABCThe abstract base class for WDL types
Each specific type inherits from this base, e.g.:
assert issubclass(WDL.Type.Int, WDL.Type.Base) assert isinstance(WDL.Type.Array(WDL.Type.Int()), WDL.Type.Base)
All instances are immutable.
- coerces(rhs, check_quant=True)[source]¶
True if this is the same type as, or can be coerced to,
rhs.
- check(rhs, check_quant=True)[source]¶
Verify this is the same type as, or can be coerced to
rhs. TheTypeErrorexception raised otherwise MAY include a specific error message (but not if the obvious “cannot coerce self to rhs” suffices).
- property parameters: Iterable[Base]¶
- Type:
Iterable[WDL.Type.Base]
The type’s parameters, if any (e.g. item type of Array; left & right types of Pair; etc.)
- copy(self, optional: bool | None = None) WDL.Type.Base[source]¶
Create a copy of the type, possibly with a different setting of the
optionalquantifier.
- equatable(rhs, *, compound=False)[source]¶
Check if values of the given types may be equated with the WDL == operator (and its negation). This mostly requires they have the same type, with quirks like ignoring quantifiers and Int/Float coercion (allowed at ‘top level’ but not within compound types).
- class WDL.Type.Any(optional=False, null=False)[source]¶
Bases:
BaseA symbolic type which coerces to any other type; used to represent e.g. the item type of an empty array literal, or the result of read_json().
The
optionalattribute shall be true only for WDLNoneliterals, which coerce to optional types only.- equatable(rhs, *, compound=False)[source]¶
Check if values of the given types may be equated with the WDL == operator (and its negation). This mostly requires they have the same type, with quirks like ignoring quantifiers and Int/Float coercion (allowed at ‘top level’ but not within compound types).
- Parameters:
compound (bool)
- class WDL.Type.Float(optional=False)[source]¶
Bases:
Base- Parameters:
optional (bool)
- equatable(rhs, *, compound=False)[source]¶
Check if values of the given types may be equated with the WDL == operator (and its negation). This mostly requires they have the same type, with quirks like ignoring quantifiers and Int/Float coercion (allowed at ‘top level’ but not within compound types).
- Parameters:
compound (bool)
- class WDL.Type.Int(optional=False)[source]¶
Bases:
Base- Parameters:
optional (bool)
- equatable(rhs, *, compound=False)[source]¶
Check if values of the given types may be equated with the WDL == operator (and its negation). This mostly requires they have the same type, with quirks like ignoring quantifiers and Int/Float coercion (allowed at ‘top level’ but not within compound types).
- Parameters:
compound (bool)
- class WDL.Type.File(optional=False)[source]¶
Bases:
Base- Parameters:
optional (bool)
- equatable(rhs, *, compound=False)[source]¶
Check if values of the given types may be equated with the WDL == operator (and its negation). This mostly requires they have the same type, with quirks like ignoring quantifiers and Int/Float coercion (allowed at ‘top level’ but not within compound types).
- Parameters:
compound (bool)
- class WDL.Type.Directory(optional=False)[source]¶
Bases:
Base- Parameters:
optional (bool)
- equatable(rhs, *, compound=False)[source]¶
Check if values of the given types may be equated with the WDL == operator (and its negation). This mostly requires they have the same type, with quirks like ignoring quantifiers and Int/Float coercion (allowed at ‘top level’ but not within compound types).
- Parameters:
compound (bool)
- class WDL.Type.String(optional=False)[source]¶
Bases:
Base- Parameters:
optional (bool)
- equatable(rhs, *, compound=False)[source]¶
Check if values of the given types may be equated with the WDL == operator (and its negation). This mostly requires they have the same type, with quirks like ignoring quantifiers and Int/Float coercion (allowed at ‘top level’ but not within compound types).
- Parameters:
compound (bool)
- class WDL.Type.Array(item_type, optional=False, nonempty=False)[source]¶
Bases:
BaseArray type, parameterized by the type of the constituent items.
- item_type: Base¶
- Type:
item_typemay beAnywhen not known statically, such as in a literal empty array[].
- property parameters: Iterable[Base]¶
- Type:
Iterable[WDL.Type.Base]
The type’s parameters, if any (e.g. item type of Array; left & right types of Pair; etc.)
- copy(self, optional: bool | None = None) WDL.Type.Base[source]¶
Create a copy of the type, possibly with a different setting of the
optionalquantifier.
- equatable(rhs, *, compound=False)[source]¶
Check if values of the given types may be equated with the WDL == operator (and its negation). This mostly requires they have the same type, with quirks like ignoring quantifiers and Int/Float coercion (allowed at ‘top level’ but not within compound types).
- Parameters:
compound (bool)
- class WDL.Type.Map(item_type, optional=False, literal_keys=None)[source]¶
Bases:
BaseMap type, parameterized by the (key,value) item type.
- item_type: tuple[Base, Base]¶
- Type:
The key and value types may be
Anywhen not known statically, such as in a literal empty map{}.
- property parameters: Iterable[Base]¶
- Type:
Iterable[WDL.Type.Base]
The type’s parameters, if any (e.g. item type of Array; left & right types of Pair; etc.)
- equatable(rhs, *, compound=False)[source]¶
Check if values of the given types may be equated with the WDL == operator (and its negation). This mostly requires they have the same type, with quirks like ignoring quantifiers and Int/Float coercion (allowed at ‘top level’ but not within compound types).
- Parameters:
compound (bool)
- class WDL.Type.Pair(left_type, right_type, optional=False)[source]¶
Bases:
BasePair type, parameterized by the left and right item types.
- property parameters: Iterable[Base]¶
- Type:
Iterable[WDL.Type.Base]
The type’s parameters, if any (e.g. item type of Array; left & right types of Pair; etc.)
- equatable(rhs, *, compound=True)[source]¶
Check if values of the given types may be equated with the WDL == operator (and its negation). This mostly requires they have the same type, with quirks like ignoring quantifiers and Int/Float coercion (allowed at ‘top level’ but not within compound types).
- Parameters:
compound (bool)
- class WDL.Type.StructInstance(type_name, optional=False)[source]¶
Bases:
BaseType of an instance of a struct
Not to be confused with struct type definition,
WDL.Tree.StructTypeDef. To find theWDL.Tree.StructTypeDefin the currentdoc: WDL.Tree.Documentcorresponding toty: WDL.Type.StructInstance, usedoc.struct_typedefs[ty.type_name].- type_name: str¶
- Type:
The struct type name with which the instance is declared; note that the same struct type can go by different names.
- members: dict[str, Base] | None¶
- Type:
Names and types of the struct members, from the struct type definition (available after typechecking)
- property type_id: str¶
- Type:
A string canonically describing the member names and their types, excluding the struct type name; useful to unify aliased struct types.
- property parameters: Iterable[Base]¶
- Type:
Iterable[WDL.Type.Base]
The type’s parameters, if any (e.g. item type of Array; left & right types of Pair; etc.)
- equatable(rhs, *, compound=False)[source]¶
Check if values of the given types may be equated with the WDL == operator (and its negation). This mostly requires they have the same type, with quirks like ignoring quantifiers and Int/Float coercion (allowed at ‘top level’ but not within compound types).
- Parameters:
compound (bool)
- WDL.Type.unify(types, check_quant=True, force_string=False)[source]¶
Given a list of types, compute a type to which they’re all coercible, or
WDL.Type.Anyif no more-specific inference is possible.
Value¶
WDL values instantiated at runtime
Each value is represented by an instance of a Python class inheriting from
WDL.Value.Base.
- class WDL.Value.Base(type, value, expr=None)[source]¶
Bases:
ABCThe abstract base class for WDL values
- property expr: Expr.Base | None¶
Reference to the WDL expression that generated this value, if it originated from
WDL.Expr.Base.eval()
- coerce(desired_type=None)[source]¶
Coerce the value to the desired type and return it. Types should be checked statically on
WDL.Expr.Baseprior to evaluation.- Raises:
WDL.Error.InputError – if the value can’t be coerced to the desired type
- Parameters:
desired_type (Base | None)
- Return type:
- class WDL.Value.String(value, expr=None, subtype=None)[source]¶
Bases:
Basevaluehas Python typestr
- class WDL.Value.Array(item_type, value, expr=None)[source]¶
Bases:
Basevalueis a Pythonlistof otherWDL.Value.Baseinstances
- class WDL.Value.Map(item_type, value, expr=None)[source]¶
Bases:
Basevalueis a Pythonlistof (key, value)tuplepairs ofWDL.Value.Base
- class WDL.Value.Pair(left_type, right_type, value, expr=None)[source]¶
Bases:
Basevalueis a Pythontupleof twoWDL.Value.Baseinstances
- class WDL.Value.Null(expr=None)[source]¶
Bases:
BaseRepresents the missing value which optional inputs may take.
valueis None andtypeisWDL.Type.Any(null=True).- Parameters:
expr (Expr.Base | None)
- class WDL.Value.Struct(type, value, expr=None, extra=None)[source]¶
Bases:
Basevalueis a Pythondictmapping member names toWDL.Value.Baseinstances- Parameters:
- WDL.Value.from_json(type, value)[source]¶
Instantiate a WDL value of the specified type from a parsed JSON value (str, int, float, list, dict, or null).
If type is
WDL.Type.Any, attempts to infer a WDL type & value from the JSON’s intrinsic types. This isn’t ideal; for example, Files can’t be distinguished from Strings, and JSON lists and dicts with heterogeneous item types may give undefined results.- Raises:
WDL.Error.InputError – if the given value isn’t coercible to the specified type
- Parameters:
- Return type:
- WDL.Value.rewrite_paths(v, f)[source]¶
Produce a deep copy of the given Value with all File & Directory paths (including those nested inside compound Values) rewritten by the given function. The function may return None to replace the File/Directory value with None/Null.
- WDL.Value.rewrite_env_paths(env, f)[source]¶
Produce a deep copy of the given Value Env with all File & Directory paths rewritten by the given function.
- WDL.Value.rewrite_files(v, f)[source]¶
Produce a deep copy of the given Value with all File names rewritten by the given function (including Files nested inside compound Values).
(deprecated: use
rewrite_pathsto handle Directory values as well)
Error¶
Exception classes raised by the WDL parser, typechecker, and runtime, along with
SourcePosition and SourceNode for locating errors in WDL source code
- class WDL.Error.SourcePosition(uri, abspath, line, column, end_line, end_column)[source]¶
Bases:
SourcePositionSource position attached to AST nodes and exceptions; NamedTuple of
urithe filename/URI passed toWDL.load()or a WDL import statement, which may be relative;abspaththe absolute filename/URI; and one-based int positionslineend_linecolumnend_column
- exception WDL.Error.SyntaxError(pos, msg, wdl_version, declared_wdl_version)[source]¶
Bases:
ExceptionFailure to lex/parse a WDL document
- Parameters:
pos (SourcePosition)
msg (str)
wdl_version (str)
declared_wdl_version (str | None)
- Return type:
None
- exception WDL.Error.ImportError(pos, import_uri, message=None)[source]¶
Bases:
ExceptionFailure to open/retrieve an imported WDL document
The
__cause__attribute may hold the inner error object.- Parameters:
pos (SourcePosition)
import_uri (str)
message (str | None)
- Return type:
None
- class WDL.Error.SourceNode(pos)[source]¶
Bases:
objectBase class for an AST node, recording the source position
- Parameters:
pos (SourcePosition)
- parent: SourceNode | None = None¶
- Type:
SourceNode | None
Parent node in the AST, if any
- pos: SourcePosition¶
- Type:
Source position for this AST node
- property source_dir: str¶
Local directory containing this source node, with trailing “/”, or “”.
Source-relative File/Directory paths need an explicit local source directory. Parsed buffers, remote URIs, and other non-local source locations are represented as an empty string so callers can produce context-specific errors only when relative path resolution is actually needed.
The directory is normalized but symlinks are intentionally preserved (abspath, not realpath): if the user reached the WDL through a symlinked path, that’s presumed deliberate and is kept in resolved File/Directory values. Symlink resolution is applied only where it’s a security boundary (see
path_really_withinusage in source-relative path resolution).
- property children: Iterable[SourceNode]¶
- Type:
Iterable[SourceNode]
Yield all child nodes
- exception WDL.Error.ValidationError(node, message)[source]¶
Bases:
ExceptionBase class for a WDL validation error (when the document loads and parses, but fails typechecking or other static validity tests)
- Parameters:
node (SourceNode | None)
message (str)
- Return type:
None
- source_text: str | None = None¶
- Type:
str | None
The complete source text of the WDL document (if available)
- node: SourceNode | None = None¶
- Type:
SourceNode | None
- pos: SourcePosition¶
- Type:
- exception WDL.Error.InvalidType(node, message)[source]¶
Bases:
ValidationError- Parameters:
node (SourceNode | None)
message (str)
- Return type:
None
- exception WDL.Error.IndeterminateType(node, message)[source]¶
Bases:
ValidationError- Parameters:
node (SourceNode | None)
message (str)
- Return type:
None
- exception WDL.Error.NoSuchTask(node, name)[source]¶
Bases:
ValidationError- Parameters:
node (SourceNode | None)
name (str)
- Return type:
None
- exception WDL.Error.NoSuchCall(node, name)[source]¶
Bases:
ValidationError- Parameters:
node (SourceNode | None)
name (str)
- Return type:
None
- exception WDL.Error.NoSuchFunction(node, name)[source]¶
Bases:
ValidationError- Parameters:
node (SourceNode | None)
name (str)
- Return type:
None
- exception WDL.Error.WrongArity(node, expected)[source]¶
Bases:
ValidationError- Parameters:
node (SourceNode | None)
expected (int)
- Return type:
None
- exception WDL.Error.NotAnArray(node)[source]¶
Bases:
ValidationError- Parameters:
node (SourceNode | None)
- Return type:
None
- exception WDL.Error.NoSuchMember(node, member)[source]¶
Bases:
ValidationError- Parameters:
node (SourceNode | None)
member (str)
- Return type:
None
- exception WDL.Error.StaticTypeMismatch(node, expected, actual, message='')[source]¶
Bases:
ValidationError- Parameters:
node (SourceNode | None)
expected (Base)
actual (Base)
message (str)
- Return type:
None
- exception WDL.Error.IncompatibleOperand(node, message)[source]¶
Bases:
ValidationError- Parameters:
node (SourceNode | None)
message (str)
- Return type:
None
- exception WDL.Error.UnknownIdentifier(node, message=None)[source]¶
Bases:
ValidationError- Parameters:
node (SourceNode | None)
message (str | None)
- Return type:
None
- exception WDL.Error.NoSuchInput(node, name)[source]¶
Bases:
ValidationError- Parameters:
node (SourceNode | None)
name (str)
- Return type:
None
- exception WDL.Error.UncallableWorkflow(node, name, reasons=None)[source]¶
Bases:
ValidationError- Parameters:
node (SourceNode | None)
name (str)
- Return type:
None
- exception WDL.Error.MultipleDefinitions(node, message)[source]¶
Bases:
ValidationError- Parameters:
node (SourceNode | None)
message (str)
- Return type:
None
- exception WDL.Error.StrayInputDeclaration(node, message)[source]¶
Bases:
ValidationError- Parameters:
node (SourceNode | None)
message (str)
- Return type:
None
- exception WDL.Error.CircularDependencies(node)[source]¶
Bases:
ValidationError- Parameters:
node (SourceNode | None)
- Return type:
None
- exception WDL.Error.MultipleValidationErrors(*exceptions)[source]¶
Bases:
ExceptionPropagates several validation/typechecking errors
- Parameters:
exceptions (list[ValidationError])
- Return type:
None
- exceptions: list[ValidationError]¶
- Type:
- exception WDL.Error.RuntimeError(*args, more_info=None, **kwargs)[source]¶
Bases:
ExceptionBase class for errors arising while running a WDL task or workflow
- value_path: list[str] | None = None¶
Location of the error within a nested value being built or coerced, e.g. the path from a workflow input to the offending item of JSON; None if the error has no such location. Rendered by
__str__()as an(in ...)suffix; see_extend_value_path(). The default is a class attribute, so it’s left immutable and_extend_value_path()rebinds instead.
- exception WDL.Error.EvalError(node, message)[source]¶
Bases:
RuntimeErrorError evaluating a WDL expression or declaration
- Parameters:
node (SourceNode | None)
message (str)
- Return type:
None
- node: SourceNode | None = None¶
- Type:
SourceNode | None
- pos: SourcePosition¶
- Type:
- exception WDL.Error.OutOfBounds(node, message)[source]¶
Bases:
EvalError- Parameters:
node (SourceNode | None)
message (str)
- Return type:
None
- exception WDL.Error.EmptyArray(node)[source]¶
Bases:
EvalError- Parameters:
node (SourceNode | None)
- Return type:
None
- exception WDL.Error.NullValue(node)[source]¶
Bases:
EvalError- Parameters:
node (SourceNode | None)
- Return type:
None
Lint¶
Annotate WDL document AST with hygiene warnings (underlies miniwdl check)
Given a doc: WDL.Document, the lint warnings can be retrieved like so:
import json
import WDL
import WDL.Lint
lint = WDL.Lint.collect(WDL.Lint.lint(doc, descend_imports=False))
for (pos, lint_class, message, suppressed) in lint:
assert isinstance(pos, WDL.SourcePosition)
assert isinstance(lint_class, str) and isinstance(message, str)
if not suppressed:
print(json.dumps({
"uri" : pos.uri,
"abspath" : pos.abspath,
"line" : pos.line,
"end_line" : pos.end_line,
"column" : pos.column,
"end_column" : pos.end_column,
"lint" : lint_class,
"message" : message,
}))
The descend_imports flag controls whether lint warnings are generated for imported documents
recursively (true, default), or otherwise only the given document (false).
Zip¶
Routines for packaging a WDL source file, with all imported source files, into a ZIP (or tar) archive.
New in v1.5.0
- WDL.Zip.build(top_doc, archive, logger, inputs=None, meta=None, archive_format='zip', additional_files=None)[source]¶
Generate zip archive of the WDL document, all its imports, optional default inputs, and a generated manifest JSON.
If imports are drawn from outside the main WDL’s directory (or by URI), they’ll be stored in a special subdirectory and import statements will be rewritten to match.
- Parameters:
top_doc (Document) – the loaded main WDL document
archive (str) – destination filename for the archive
inputs (dict[str, Any] | None) – default inputs to include in the archive (JSON-like dict), if any
meta (dict[str, Any] | None) – extra metadata to include in the manifest, if any
archive_format (str) –
"zip"or"tar"additional_files (list[str] | None) – other files, directories, or glob patterns to include, stored at the same location relative to the WDL source files
logger (Logger)
- WDL.Zip.add_additional_files(zip_dir, additional_files, zip_paths, wdls, logger)[source]¶
Add files/directories to an archive staging directory, preserving paths relative to WDL source directories represented in
zip_paths.Examples:
/proj/data/ref.fa->data/ref.fa(when/proj/main.wdlis archived asmain.wdl)/shared/lib/data/ref.fa->__outside_wdl/lib/data/ref.fa(when/shared/lib/tasks.wdlis rewritten under__outside_wdl/lib/tasks.wdl)
- class WDL.Zip.UnpackedZip(dir, main_wdl, input_file)[source]¶
Contextual value of
WDL.Zip.unpack(): absolute paths of source directory, main WDL, and default input JSON file (if any). The source directory prefixes the latter paths.
- WDL.Zip.unpack(archive_fn, tempdir_parent=None)[source]¶
Open a context with the WDL source archive unpacked into a temp directory, yielding
UnpackedZip. The temp directory will be deleted on context exit.A path to the MANIFEST.json of an already-unpacked source archive may also be used, or a directory containing one. In this case, it is NOT deleted on context exit.
with WDL.Zip.unpack("/path/to/source.zip") as unpacked: doc = WDL.load(unpacked.main_wdl) ...
- Parameters:
- Return type:
runtime¶
The recommended way to run a WDL workflow programmatically is to invoke miniwdl run as a
subprocess, capturing its JSON standard output. This leverages its logging, configuration, and
flexible input loading features; and avoids conflicting with the runtime’s thread pools and signal
handlers. Alternatively, it’s possible to call WDL.runtime.run() directly if needed.
- WDL.runtime.run(cfg, exe, inputs, **run_kwargs)[source]¶
Run the task or workflow given the inputs environment and configuration, returning the run directory and the outputs environment.
inputsmay be parsed from a JSON dict usingvalues_from_json(), which can also validate them; see example below.- Parameters:
run_id – a run identifier used in logs and filenames; defaults to executable name
run_dir – directory under which to create a timestamp-named subdirectory for this run (defaults to current working directory). If the final path component is
.then operate in run_dir directly.cfg (Loader)
run_kwargs (Any)
- Returns:
(run_dir, outputs_env)- Return type:
Typical usage:
import logging import WDL import WDL.runtime # Convert JSON-like inputs dict to WDL environment, validating them against exe's available # and required inputs. The dict keys should NOT be namespaced by the executable name; # if namespaces are present, then add namespace=exe.name to effectively remove them. inputs_env = WDL.values_from_json(inputs_dict, exe.available_inputs, exe.required_inputs) # Load configuration (see below) cfg = WDL.runtime.config.Loader(logging.getLogger(__name__)) # Run executable run_subdir, outputs_env = WDL.runtime.run(cfg, exe, inputs_env, run_dir="/tmp") # Generate JSON-like outputs dict, with keys namespaced by the executable name outputs_dict = WDL.values_to_json(outputs_env, exe.name)
runtime.config¶
Configuration loader for the miniwdl runtime, merging options from default.cfg, a custom
configuration file, environment variables, and overrides. See
Configuration
for an overview.
- exception WDL.runtime.config.ConfigMissing[source]¶
Raised when a requested configuration section or option isn’t present
- class WDL.runtime.config.Loader(logger, filenames=None, overrides=None)[source]¶
Runtime configuration options, identified by section & key, are sourced in the following priority order:
Supplied
overridesdict,{"section": {"key": value}}Environment variables
MINIWDL__SECTION__KEY(uppercased with double-underscores)Custom configuration file (mutually exclusive):
filename given to
__init__file named by environment variable
MINIWDL_CFGminiwdl.cfgin XDG_CONFIG_HOME or XDG_CONFIG_DIRS, usually~/.config/miniwdl.cfg
WDL/runtime/config_templates/default.cfgfrom installed package
If
filenamesis an empty list, then no custom configuration file is used. Orfilenamesmay be a prioritized list of candidate filenames instead of (a-c) above; the first extant file is used, if any.- Parameters:
Python codelabs¶
These tutorials introduce common ways to use and extend the WDL package:
Syntax tree traversal: basic syntax tree traversal
wdlviz: generating graphviz diagrams from WDL source code
Adding WDL functions: adding new functions to the standard library
WDL assertion statements: adding a new WDL language feature, with parsing, type-checking, and runtime execution