Repository: omni-us/jsonargparse

Issue:
Parsing `TYPE_CHECKING` guarded import doesn't work in combination with `Type`
<!-- If you like this project, please ⭐ star it https://github.com/omni-us/jsonargparse/ -->

## 🐛 Bug report

When using the `Type` annotation in conjunction with a `TYPE_CHECKING` guarded import, e.g.

```python
from typing import Type, TYPE_CHECKING
from jsonargparse import ArgumentParser

if TYPE_CHECKING:
    from pytorch.lightning.cli import LightningCLI

def dummy(cli_cls: Type["LightningCLI"]):
    print(cli_cls)


def main():
    parser = ArgumentParser()
    parser.add_function_arguments(dummy)
    args = parser.parse_args()
```
I get the following error

```console
ValueError: With fail_untyped=True, all mandatory parameters must have a supported type. Parameter 'cli_cls' from '__main__.test' does not specify a type.
```

Although, this parser set up works when removing the `TYPE_CHECKING` guarded import, and importing directly



<!--
Please include a code snippet that reproduces the bug and the output that
running it gives. The following snippet templates might help:

1. Using the CLI function

```python
from jsonargparse import CLI

# Here define one or more functions or classes
def func1(param1: int, ...):
    ...

# Run the CLI providing the components
CLI([func1, ...], exit_on_error=False)
```

2. Manually constructing a parser

```python
from jsonargparse import ArgumentParser

parser = ArgumentParser(exit_on_error=False)
# Here add to the parser only argument(s) relevant to the problem

# If a yaml config is required, it can be included in the same snippet as follows:
import yaml

parser.add_argument("--config", action="config")
config = yaml.safe_dump(
    {
        "key1": "val1",
    }
)

# Preferable that the command line arguments are given to the parse_args call
result = parser.parse_args([f"--config={config}", "--key2=val2", ...])

# If the problem is in the parsed result, print it to stdout
print(parser.dump(result))

# If the problem is in class instantiation
parser.instantiate_classes(result)
```
-->

### Expected behavior

<!-- Describe how the behavior or output of the reproduction snippet should be. -->

### Environment

<!-- Fill in the list below. -->

- jsonargparse version: 4.3.1
- Python version: 3.9 
- How jsonargparse was installed: poetry
- OS: linux

Discussion:
@mauvilsa: Thank you for reporting! Would you be interested in contributing the fix?@EthanMarx: Sure - would you be able to point me in the right direction? @mauvilsa: Certainly.

1. Setup a local environment as explained in [CONTRIBUTING.rst#development-environment](https://github.com/omni-us/jsonargparse/blob/main/CONTRIBUTING.rst#development-environment).
2. The tests related to `TYPE_CHECKING` are in `jsonargparse_tests/test_postponed_annotations.py`, so make sure those tests run, like
    ```
    pytest -v jsonargparse_tests/test_postponed_annotations.py
    ```
3. Have a look at the existing tests: [test_postponed_annotations.py#L192-L294](https://github.com/omni-us/jsonargparse/blob/1bab38ae7a5fe281c62fe784fc620bbbf259f2e8/jsonargparse_tests/test_postponed_annotations.py#L192-L294)
4. Maybe, debug through one of the tests to get a bit of understanding of how things work.
5. Before trying to fix, extend `test_postponed_annotations.py` to include a test for this case which is failing. That is, add an entry in the `if TYPE_CHECKING:` block and implement a `test_*` function that fails as you have observed with the current version of the code.

The unit test would already be a valuable contribution. The following step would be to understand what is currently happening and figure out where to fix/improve the code. This feature makes use of AST parsing, so it might not be trivial to understand and fix. But you can give it a shot. If it seems to complex just ask again, or I could continue from where you left off.@EthanMarx: Thank you! I actually think I found a solution. I have a PR with unit tests ready to go, but can't get past the `pre-push` testing hooks, I think due to #574 @mauvilsa: You can do `git push --no-verify`. Or push from an env that doesn't have pytorch installed.

Solution patch:
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index e0773fa1..3aef2827 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -27,6 +27,9 @@ Fixed
 - Callable type with subclass return not showing the ``--*.help`` option (`#567
   <https://github.com/omni-us/jsonargparse/pull/567>`__).
 
+- Forward referenced types not compatible with `Type` typehint (`#576
+  <https://github.com/omni-us/jsonargparse/pull/576/>`__)
+
 Changed
 ^^^^^^^
 - Removed shtab experimental warning (`#561
diff --git a/jsonargparse/_postponed_annotations.py b/jsonargparse/_postponed_annotations.py
index d1a5e112..5dbdffd4 100644
--- a/jsonargparse/_postponed_annotations.py
+++ b/jsonargparse/_postponed_annotations.py
@@ -229,6 +229,8 @@ def resolve_subtypes_forward_refs(typehint):
                             typehint_origin = Tuple
                         elif typehint_origin in mapping_origin_types:
                             typehint_origin = Dict
+                        elif typehint_origin == type:
+                            typehint_origin = Type
                     typehint = typehint_origin[tuple(subtypes)]
             except Exception as ex:
                 if logger:
@@ -240,6 +242,9 @@ def resolve_subtypes_forward_refs(typehint):
 
 def has_subtypes(typehint):
     typehint_origin = get_typehint_origin(typehint)
+    if typehint_origin is type and hasattr(typehint, "__args__"):
+        return True
+
     return (
         typehint_origin == Union
         or typehint_origin in sequence_origin_types
@@ -260,7 +265,6 @@ def get_types(obj: Any, logger: Optional[logging.Logger] = None) -> dict:
         types = get_type_hints(obj, global_vars)
     except Exception as ex1:
         types = ex1  # type: ignore[assignment]
-
     if isinstance(types, dict) and all(not type_requires_eval(t) for t in types.values()):
         return types
 


Test patch:
diff --git a/jsonargparse_tests/test_postponed_annotations.py b/jsonargparse_tests/test_postponed_annotations.py
index 0d6b6baf..05d7d907 100644
--- a/jsonargparse_tests/test_postponed_annotations.py
+++ b/jsonargparse_tests/test_postponed_annotations.py
@@ -10,7 +10,11 @@
 
 from jsonargparse import Namespace
 from jsonargparse._parameter_resolvers import get_signature_parameters as get_params
-from jsonargparse._postponed_annotations import TypeCheckingVisitor, evaluate_postponed_annotations, get_types
+from jsonargparse._postponed_annotations import (
+    TypeCheckingVisitor,
+    evaluate_postponed_annotations,
+    get_types,
+)
 from jsonargparse.typing import Path_drw
 from jsonargparse_tests.conftest import capture_logs, source_unavailable
 
@@ -267,6 +271,17 @@ def test_get_types_type_checking_tuple():
     assert str(types["p1"]) == f"{tpl}[{__name__}.TypeCheckingClass1, {__name__}.TypeCheckingClass2]"
 
 
+def function_type_checking_type(p1: Type["TypeCheckingClass2"]):
+    return p1
+
+
+def test_get_types_type_checking_type():
+    types = get_types(function_type_checking_type)
+    assert list(types.keys()) == ["p1"]
+    tpl = "typing.Type" if sys.version_info < (3, 10) else "type"
+    assert str(types["p1"]) == f"{tpl}[{__name__}.TypeCheckingClass2]"
+
+
 def function_type_checking_dict(p1: Dict[str, Union[TypeCheckingClass1, "TypeCheckingClass2"]]):
     return p1