Skip to content

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.

Annotated[Type, Type.Args(...)]

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:

examples/file.py
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:

from typing import Annotated
import arc
from arc.types import File

@arc.command
def read(file: Annotated[File.Read, File.Args(encoding="ascii")]):
    print(file.readline())

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:

examples/dates.py
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 the File 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 the datetime.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