Skip to content

Commit 3108959

Browse files
committed
Add doc on Optional
1 parent 2c5cd3b commit 3108959

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

docs/python.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ This document defines the API of the `cog` Python module, which is used to defin
2828
- [`File()`](#file)
2929
- [`Path()`](#path)
3030
- [`Secret`](#secret)
31+
- [`Optional`](#optional)
3132
- [`List`](#list)
3233

3334
## `BasePredictor`
@@ -390,6 +391,31 @@ any value passed to a `Secret` input is redacted after being sent to the model.
390391
> Passing secret values to untrusted models can result in
391392
> unintended disclosure, exfiltration, or misuse of sensitive data.
392393
394+
## `Optional`
395+
396+
Optional inputs should be explicitly defined as `Optional[T]` so that type checker can warn us about error-prone `None` values.
397+
398+
For example, the following code might fail if `prompt` is not specified in the inputs:
399+
400+
```python
401+
class Predictor(BasePredictor):
402+
def predict(self, prompt: str=Input(description="prompt", default=None)) -> str:
403+
return "hello" + prompt # TypeError: can only concatenate str (not "NoneType") to str
404+
```
405+
406+
We can improve it by making `prompt` an `Optional[str]`. Note that `default=None` is now redundant as `Optional` implies it.
407+
408+
```python
409+
class Predictor(BasePredictor):
410+
def predict(self, prompt: Optional[str]=Input(description="prompt")) -> str:
411+
if prompt is None: # type check can warn us if we forget this
412+
return "hello"
413+
else:
414+
return "hello" + prompt
415+
```
416+
417+
Note that the error prone usage of `prompt: str=Input(default=None)` might throw an error in a future release of Cog.
418+
393419
## `List`
394420

395421
The List type is also supported in inputs. It can hold any supported type.

0 commit comments

Comments
 (0)