Type Arguments
Type Arguments are a way for types to recieve additional information that can be used during type conversion. Type arguments are attached to a types using an Annotated
type. They will generally take the form of.
For example, the arc.types.File
type uses a type argument to specify the mode to open the file in.
from typing import Annotated
import arc
from arc.types import File
@arc.command
def read(file: Annotated[File, File.Args("r")]):
print(file.readline())
This tells arc that the file
parameter should be opened in read mode.
Type Aliases
For convenience, arc provides several type aliases on the File
type with the mode already defined. So the above example could be written as:
import arc
from arc.types import File
@arc.command
def command(file: File.Read):
arc.print(file.readline())
command()
Note that using the alias doesn't actually prevent your from providing your own type arguments. So the following is also valid:
Check out the source for File.Args()
for information on how to define your own type arguments.
Non arc types¶
If it's neccessary for a builtin or standard lib type to implement type arguments, they will be provided in the types package. For example:
from typing import Annotated
import arc
from arc import types
import datetime
@arc.command
def command(date: Annotated[datetime.datetime, types.DateTimeArgs("%Y-%m-%d")]):
arc.print(date)
command()
Currently the following standard lib types have type arguments defined:
datetime.datetime
:arc.types.DateTimeArgs
datetime.date
:arc.types.DateArgs
datetime.time
:arc.types.TimeArgs
int
:arc.types.IntArgs
When to Use Type Arguments¶
Type arguments should be used to provide information that is necessary during type construction. For example:
arc.types.File
uses a type argument to specify the expected file mode. This is necessary because theFile
type needs to know the file mode before it can be opened.datetime.datetime
type uses a type argument to specify the expected format of the input string. This is necessary because thedatetime.datetime
type needs to know the format of the input string before it can be converted to a datetime object. In all other cases
If the information isn't needed until after the type has been constructed, then you should probably opt for a Type Middleware