GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — `flag_value` is passed through `ParamType.convert` · Issue #2012 · pallets/click

flag_value is passed through ParamType.convert #2012

New issue
Copy link
New issue
Copy link
Closed
Bug
#3363
Closed
flag_value is passed through ParamType.convert#2012
Bug
#3363
Copy link
Assignees
kdeldycke
Labels
typingType annotations and stubs
Milestone
8.4.0

Description

@jgadling
jgadling
opened on Jul 16, 2021
Issue body actions

In upgrading from click 7.1.2 to 8.0.1, our click-based CLI started failing with type errors. We have click options whose default values are classes, and as of 8.0.1 they're being converted to strings.

This script is able to reproduce the behavior change:

import click

class Class1:
    pass

class Class2:
    pass

@click.command()
@click.option("--cls1", "config_cls", flag_value=Class1, default=True)
@click.option("--cls2", "config_cls", flag_value=Class2)
def test(config_cls):
    print(config_cls)
    print(type(config_cls))

if __name__ == "__main__":
    test()

Behavior with click 7.1.2:

# pip freeze | grep click
click==7.1.2
# python test.py
<class '__main__.Class1'>
<class 'type'>

Behavior with 8.0.1:

# pip freeze | grep click
click==8.0.1
# python test.py
<class '__main__.Class1'>
<class 'str'>

The type of config_cls should be the class we specified, not 'str'.

Environment:

  • Python version: 3.9
  • Click version: 8.0.1
Reacted by MHannila, Kimmo Parviainen-Jalanko, George, aliaksei-siarhei, Felix Uhl and JanEricNitschkeTNG

Activity

  1. MHannila commented on Aug 4, 2021

    @MHannila
    MHannila
    on Aug 4, 2021
    More actions

    This seems to have already appeared in the 8.0.0 version.
    Ran into this myself using enum member as the flag_value and managed to get an integer to convert to string as well so I did some testing (with 8.0.1).

    A simple workaround solution for most cases seems to be just defining the type, but there are also issues if you have multiple flags for the same argument that are of different types. Then even defining the types doesn't help. That hopefully isn't a problem for many though, because why would you even do that.

    from enum import Enum
    
    import click
    import pkg_resources
    
    
    class EnumClass(Enum):
        FOO = 1
        BAR = 2
    
    
    @click.command()
    @click.option("--enum-no-type", flag_value=EnumClass.FOO, default=True)
    @click.option("--enum-with-type", flag_value=EnumClass.FOO, type=EnumClass, default=True)
    @click.option("--integer", flag_value=1, default=True)
    @click.option("--integer-as-int", 'multitype_borked', flag_value=1, default=True)
    @click.option("--integer-as-str", 'multitype_borked', flag_value='1')
    @click.option("--integer-as-int-with-type", 'multitype_borked2', flag_value=1, type=int, default=True)
    @click.option("--integer-as-str-with-type", 'multitype_borked2', flag_value='1', type=str)
    def test(**kwargs):
        for name, value in kwargs.items():
            print(name, value, type(value))
    
    
    if __name__ == '__main__':
        print('click version', pkg_resources.get_distribution('click').version)
        test()
    click version 8.0.1
    enum_no_type EnumClass.FOO <class 'str'>
    enum_with_type EnumClass.FOO <enum 'EnumClass'>
    integer 1 <class 'int'>
    multitype_borked 1 <class 'str'>
    multitype_borked2 1 <class 'str'>
    

    same with 7.1.2 works just as you'd expect

    click version 7.1.2
    enum_no_type EnumClass.FOO <enum 'EnumClass'>
    enum_with_type EnumClass.FOO <enum 'EnumClass'>
    integer 1 <class 'int'>
    multitype_borked 1 <class 'int'>
    multitype_borked2 1 <class 'int'>
    

    Trying to define type with class doesn't work, unsurprisingly

    import click
    
    class Class: pass
    
    @click.command()
    @click.option("--class-with-type", flag_value=Class, type=Class, default=True)
    def test(**kwargs):
        for name, value in kwargs.items():
            print(name, value, type(value))
    
    if __name__ == "__main__":
        test()
    Traceback (most recent call last):
      File "/Users/<REDACTED>/Library/Application Support/JetBrains/PyCharm2021.2/scratches/scratch_66.py", line 34, in <module>
        test()
      File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 1137, in __call__
        return self.main(*args, **kwargs)
      File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 1061, in main
        with self.make_context(prog_name, args, **extra) as ctx:
      File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 923, in make_context
        self.parse_args(ctx, args)
      File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 1379, in parse_args
        value, args = param.handle_parse_result(ctx, opts, args)
      File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 2364, in handle_parse_result
        value = self.process_value(ctx, value)
      File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 2320, in process_value
        value = self.type_cast_value(ctx, value)
      File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 2307, in type_cast_value
        return convert(value)
      File "/usr/local/lib/python3.6/dist-packages/click/types.py", line 75, in __call__
        return self.convert(value, param, ctx)
      File "/usr/local/lib/python3.6/dist-packages/click/types.py", line 170, in convert
        return self.func(value)
    TypeError: object() takes no parameters
    Reacted by Klemen Tusar
  2. techouse commented on Aug 7, 2021

    @techouse
    techouse
    on Aug 7, 2021
    More actions

    Had the same issue and just adding a type to the click options fixed it for me.

  3. davidism commented on Oct 6, 2021

    @davidism
    davidism
    on Oct 6, 2021
    Member
    More actions

    The processing pipeline was updated to be more strict about casing values to types consistently. Click (7 and 8) only detect some basic param types, and fall back to click.STRING otherwise. Since the custom class isn't a recognized type, Click falls back to string, and then applies that type conversion to the value during processing. You can avoid this for now by passing type=click.UNPROCESSED, although I'll see if I can think of a way to handle this type of case.

  4. davidism
    changed the title [-]Option type handling regression in 8.0.1[/-] [+]`flag_value` is passed through `ParamType.convert`[/+] on Oct 7, 2021
  5. kleinweby commented on Nov 4, 2021

    @kleinweby
    kleinweby
    on Nov 4, 2021
    More actions

    We've stumbled across this same issue. And I'm a bit confused.

    Looking at the docu, which states

    Changed in version 8.0.1: type is detected from flag_value if given.

    I would expect some behavior along the lines of

    if type is MISSING:
       type = type(flag_value)

    However reading davidism comment and looking at

    click/src/click/types.py

    Line 959 in 2996d3c

    def convert_type(ty: t.Optional[t.Any], default: t.Optional[t.Any] = None) -> ParamType:

    this only hold true, if the autoguessed type is one of str, int, float, bool. If that is the intended behavior I think the documentation should state so, as I find it very surprising.

    However I think, in the case of flag_value I would simply expect click not to touch that all and simply pass it back to me.

  6. Rowlando13
    added
    bug
    typingType annotations and stubs
    and removed
    bug
    on Jan 5, 2025
  7. davidism commented on Jul 1, 2025

    @davidism
    davidism
    on Jul 1, 2025
    Member
    More actions

    @kdeldycke was this addressed by #2956? I don't think so, but it came up in my quick search.

  8. kdeldycke
    linked a pull request that will close this issueDifferentiate absence of value and value of absence for `default` and `flag_value` arguments #3030on Aug 11, 2025
  9. kdeldycke
    added this to the This milestone has been deleted milestone on Aug 12, 2025
  10. kdeldycke commented on Aug 13, 2025

    @kdeldycke
    kdeldycke
    on Aug 13, 2025
    Collaborator
    More actions
    @click.option("--cls1", "config_cls", flag_value=Class1, default=True)
    @click.option("--cls2", "config_cls", flag_value=Class2)

    @jgadling This has been addressed in #3030. I made your use-case into a unittest there.

    This is a similar case as #3024 (comment) .

    So now a default is returned as-is. The cases are highlighted there:

    click/tests/test_options.py

    Lines 1749 to 1817 in da07421

    class Class1:
    pass
    class Class2:
    pass
    @pytest.mark.parametrize(
    ("opt_params", "default", "args", "expected"),
    [
    # Default type fallback to string.
    ({}, True, [], "True"),
    ({}, True, ["--cls1"], "<class 'test_options.Class1'>"),
    ({}, True, ["--cls2"], "<class 'test_options.Class2'>"),
    # Even the default is processed as a string.
    ({}, "True", [], "True"),
    ({}, None, [], None),
    # To get the classes as-is, we need to specify the type as UNPROCESSED.
    ({"type": click.UNPROCESSED}, True, [], True),
    ({"type": click.UNPROCESSED}, True, ["--cls1"], Class1),
    ({"type": click.UNPROCESSED}, True, ["--cls2"], Class2),
    # Setting the default to a class, an instance of the class is returned instead
    # of the class itself, because the default is allowed to be callable (and
    # consummd). And this what happens the type is.
    (
    {},
    Class1,
    [],
    re.compile(r"'<test_options.Class1 object at 0x[0-9A-Fa-f]+>'"),
    ),
    (
    {},
    Class2,
    [],
    re.compile(r"'<test_options.Class2 object at 0x[0-9A-Fa-f]+>'"),
    ),
    (
    {"type": click.UNPROCESSED},
    Class1,
    [],
    re.compile(r"<test_options.Class1 object at 0x[0-9A-Fa-f]+>"),
    ),
    (
    {"type": click.UNPROCESSED},
    Class2,
    [],
    re.compile(r"<test_options.Class2 object at 0x[0-9A-Fa-f]+>"),
    ),
    ],
    )
    def test_custom_type_python_class_flag_value(
    runner, opt_params, default, args, expected
    ):
    """A reproduction of https://github.com/pallets/click/issues/2012"""
    @click.command()
    @click.option(
    "--cls1", "config_cls", flag_value=Class1, **opt_params, default=default
    )
    @click.option("--cls2", "config_cls", flag_value=Class2, **opt_params)
    def cli(config_cls):
    click.echo(repr(config_cls), nl=False)
    result = runner.invoke(cli, args)
    if isinstance(expected, re.Pattern):
    assert re.match(expected, result.output)
    else:
    assert result.output == repr(expected)

  11. kdeldycke commented on Aug 13, 2025

    @kdeldycke
    kdeldycke
    on Aug 13, 2025
    Collaborator
    More actions
    @click.option("--enum-no-type", flag_value=EnumClass.FOO, default=True)
    @click.option("--enum-with-type", flag_value=EnumClass.FOO, type=EnumClass, default=True)
    @click.option("--integer", flag_value=1, default=True)
    @click.option("--integer-as-int", 'multitype_borked', flag_value=1, default=True)
    @click.option("--integer-as-str", 'multitype_borked', flag_value='1')
    @click.option("--integer-as-int-with-type", 'multitype_borked2', flag_value=1, type=int, default=True)
    @click.option("--integer-as-str-with-type", 'multitype_borked2', flag_value='1', type=str)

    @MHannila All your test-cases have been added in the unit-tests of #3030, which fix your issues.

    See:

    • click/tests/test_options.py

      Lines 1850 to 1864 in f9d006e

      ###
      ### Reproduces https://github.com/pallets/click/issues/2012#issuecomment-892437060
      ###
      (
      {"flag_value": 1, "default": True},
      {"flag_value": "1"},
      [],
      1,
      ),
      (
      {"flag_value": 1, "type": int, "default": True},
      {"flag_value": "1", "type": int},
      [],
      1,
      ),
    • click/tests/test_options.py

      Lines 1727 to 1744 in f9d006e

      # Reproduction of cases from
      # https://github.com/pallets/click/issues/2012#issuecomment-892437060
      (
      {"flag_value": EngineType.OSS, "default": True},
      [],
      "True",
      ),
      (
      {"type": EngineType, "flag_value": EngineType.OSS, "default": True},
      [],
      EngineType.OSS,
      ),
      ({"flag_value": 1, "default": True}, [], 1),
      ({"flag_value": "1", "default": True}, [], "True"),
      ({"flag_value": 1, "type": str, "default": True}, [], "True"),
      ({"flag_value": "1", "type": str, "default": True}, [], "True"),
      ({"flag_value": 1, "type": int, "default": True}, [], 1),
      ({"flag_value": "1", "type": int, "default": True}, [], 1),
  12. kdeldycke
    added the
    Bug
    issue type on Aug 13, 2025
  13. kdeldycke
    modified the milestones: This milestone has been deleted, 8.3.0 on Aug 14, 2025
  14. Rowlando13
    closed this as completedin #3030on Aug 24, 2025
  15. kdeldycke commented on Aug 25, 2025

    @kdeldycke
    kdeldycke
    on Aug 25, 2025
    Collaborator
    More actions

    Looks like some details pointed here are not completely solved by #3030.

    At least #3030 don't make things worse: it just lock-down the behavior pointed out in this issue by porting the unit-tests upstream and fixing a part of that issue (the case of default=True).

    I'm re-opening this while I investigate further.

  16. kdeldycke
    reopened this on Aug 25, 2025
  17. kdeldycke
    removed this from the 8.3.0 milestone on Aug 25, 2025
  18. kdeldycke
    self-assigned this
    on Aug 25, 2025
  19. kdeldycke
    removed a link to a pull requestDifferentiate absence of value and value of absence for `default` and `flag_value` arguments #3030on Aug 25, 2025
  20. kdeldycke commented on Apr 21, 2026

    @kdeldycke
    kdeldycke
    on Apr 21, 2026
    Collaborator
    More actions

    A PR to fix the remaining cases of this issue is available at: #3363

  21. kdeldycke
    added this to the 8.4.0 milestone on Apr 21, 2026
  22. kdeldycke
    linked a pull request that will close this issueAuto-detect `type=UNPROCESSED` when `flag_value` has non-basic types #3363on Apr 21, 2026
  23. kdeldycke
    added a commit that references this issue on Apr 21, 2026

    Auto-detect `type=UNPROCESSED` when `flag_value` has non-basic types

    This issue will close once commit 4e4c7a6 is merged into the 'main' branch.
    4e4c7a6
  24. Rowlando13
    closed this as completedin #3363on Apr 29, 2026
  25. github-actions
    locked as resolved and limited conversation to collaborators on May 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

  • @kdeldycke
    kdeldycke

Labels

typingType annotations and stubs

Type

Bug

Projects

No projects

    Milestone

    • 8.4.0

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

    You are visitor 01402775 — GeezerVison does not store the pages you look up.
    Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.