Skip to content

Weird behaviour in resolving class names when using forward references when the forward referenced class is not in scope #708

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Ganoash opened this issue Apr 18, 2025 · 1 comment
Labels
bug Something isn't working

Comments

@Ganoash
Copy link

Ganoash commented Apr 18, 2025

It took me a while to find a way to reproduce this bug, and it doesn't quite happen here in the way it's happening in our larger codebase, however I'd like to give it a go:

🐛 Bug report

Specifying types which have forward references included can lead to errors when the forward-referenced type is not in scope.

In this case ForwardReferenced is in scope when defining Direct, so adding class arguments will work. However, in the case of Indirect ForwardReferenced is not in scope when using NamedType leading to an error when adding class variables.

To reproduce

types_file

NamedType = list["ForwardReferenced"]

class ForwardReferenced:
    pass

class Direct:

    def __init__(self, data_type: NamedType):
        pass

minimal_reproduction.py

from jsonargparse import ArgumentParser

from types_file import NamedType, Direct


class Indirect:

    def __init__(self, data_type: NamedType):
        pass

parser = ArgumentParser()
parser.add_class_arguments(Direct, "direct")
parser.add_class_arguments(Indirect, "indirect") # <---- will raise error

Expected behavior

I expect both Direct and Indirect class arguments to be addable, instead adding Indirect will throw a ValueError:
ValueError: With fail_untyped=True, all mandatory parameters must have a supported type. Parameter 'data_type' from '__main__.Indirect.__init__' does not specify a type.

resolving it is trivial, you can either import the forward-referenced type within the current scope or remove the forward reference from the type.

I've found a similar case when using parser.link_arguments but have not quite been able to reproduce it. In our case it was quite hard to figure out the cause of the bug. At the very least there should be some impovement to error reporting.

Environment

  • jsonargparse version: 4.37.0
  • Python version: 3.11
  • How jsonargparse was installed: UV
  • OS: Pop!_OS 22.04 LTS
@Ganoash Ganoash added the bug Something isn't working label Apr 18, 2025
@mauvilsa
Copy link
Member

Thank you for reporting! I will take a look at it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants