Skip to content

click.option with a custom type and default value tries to convert the default twice in click >= 8.0.0 #1976

@mayghalV

Description

@mayghalV

click.option with a custom type class and default value tries to convert the default value twice.

For this example here:

import click
from click.types import ParamType

import pytz

class TimeZone(ParamType):

    name = "timezone"

    def convert(self, value, param, ctx):
        try:
            return pytz.timezone(value)
        except pytz.exceptions.UnknownTimeZoneError:
            self.fail(f'invalid timezone: {value}')

    def __repr__(self):
        return "TimeZone"

@click.group()
def cli():
    pass


@cli.command()
@click.option('--t', '-t', type=TimeZone(), default='UTC')
def example(t):
    print(t, type(t))


if __name__ == '__main__':
    # cli.main(['example', '-t', 'UTC']) # Works
    cli.main(['example'])   # Doesn't work - tries to convert 'UTC' twice

Running
cli.main(['example', '-t', 'UTC']) works as expected and prints UTC <class 'pytz.UTC'> as the result.

However when I try to run without a default value for t: cli.main(['example']), I get the following error message:

File "../lib64/python3.6/site-packages/pytz/__init__.py", line 170, in timezone
    if zone.upper() == 'UTC':
AttributeError: 'UTC' object has no attribute 'upper'

After running the debugger and putting a breakpoint within TimeZone.convert defined above - the breakpoint is hit twice, first with the string 'UTC', followed by the timezone pytz.UTC the second time so it seems click is trying to convert the default value twice.

Environment:

  • Python version: 3.6
  • Click version: >=8.0.0. Works as expected on 7.1.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions