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
click.option with a custom type class and default value tries to convert the default value twice.
For this example here:
Running
cli.main(['example', '-t', 'UTC'])works as expected and printsUTC <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: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: