typer icon indicating copy to clipboard operation
typer copied to clipboard

Support for bytes in Options and Arguments

Open AlexanderPodorov opened this issue 2 years ago • 3 comments

First Check

  • [X] I added a very descriptive title to this issue.
  • [X] I used the GitHub search to find a similar issue and didn't find it.
  • [X] I searched the Typer documentation, with the integrated search.
  • [X] I already searched in Google "How to X in Typer" and didn't find any information.
  • [X] I already read and followed all the tutorial in the docs and didn't find an answer.
  • [X] I already checked if it is not related to Typer but to Click.

Commit to Help

  • [X] I commit to help with one of those options 👆

Example Code

import typer


def main(name: bytes):
    typer.echo(name)


if  __name__ == '__main__':
    typer.run(main)

Description

It would be nice if we could add support for bytes in order to use it in contexts where bytes are expected (e.g. base64 encode/decode, password hashing, etc.)

Wanted Solution

Support for bytes type. Currently typer says: RuntimeError: Type not yet supported: <class 'bytes'>

Wanted Code

import typer


def main(name: bytes):
    typer.echo(name)


if  __name__ == '__main__':
    typer.run(main)

Alternatives

Always use encode/decode methods.

Operating System

macOS

Operating System Details

No response

Typer Version

0.7.0

Python Version

3.11.1

Additional Context

No response

AlexanderPodorov avatar Jan 18 '23 21:01 AlexanderPodorov

Hi,

is there any news on this issue?

marcosschroh avatar Feb 02 '23 17:02 marcosschroh

Hello, I could look into adding this!

However just so you know, custom types can be made easily. A type for bytes could be made like:

import typer
from typing_extensions import Annotated
app = typer.Typer()
class Bytes(self, value):
    def __init__(self, value):
        self.value = value.encode()
def parse_bytes(val):
    return Bytes(val).value

def func(input: Annotated[Bytes, typer.Argument(parser=parse_bytes)]):
    ....
    ....
    return

The greatest hassle with this solution is remembering to add `parser=parse_bytes' to all the Bytes arguments. So, could be worth natively supporting it.

ESPR3SS0 avatar May 17 '24 01:05 ESPR3SS0

This would also be useful for my use cases (firmware / transport protocols). Though, instead of supporting "bytes" directly, wouldn't we need to support "encodings"?

For example, a type specified as:

  • utf-8 would take a string end encode it to utf-8 bytes
  • base64 would encode base64 bytes
  • hex would use bytes from_hex (or whatever that method is called
  • etc

It seems to me that the only arg that would make sense for simply "bytes" would be python byte literals, with all their downsides.

Would be good to scope this to common encodings since there are thousands.

JPHutchins avatar Aug 03 '24 19:08 JPHutchins