Skip to content

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

Open
@Ganoash

Description

@Ganoash

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions