为何有效URI在LinkML中验证失败?升级runtime仍报错
Problem
When setting a valid, accessible URI (https://ceur-ws.org/Vol-2931/ICBO_2019_paper_20.pdf) in Python code generated from a LinkML YAML file, a ValueError is thrown claiming the URI is invalid. Upgrading linkml-runtime from version 1.4.5 to 1.4.10 and regenerating the code does not resolve the issue. Debugging identifies the root cause as the URI.is_valid() method using the overly simplistic regex ^\S+$ for validation.
Possible Causes & Fixes
1. Hidden Whitespace in the URI String
The regex ^\S+$ rejects any string containing whitespace (spaces, tabs, newlines, non-breaking spaces, etc.). Even an invisible trailing space or non-breaking space in your URI string would trigger the error.
Fix:
- Trim the URI string before passing it to the generated class:
uri = "https://ceur-ws.org/Vol-2931/ICBO_2019_paper_20.pdf".strip() # Or remove all whitespace characters: import re uri = re.sub(r"\s+", "", uri) - Verify the string has no hidden whitespace by printing its raw representation:
This will expose invisible characters (e.g.,print(repr(uri))'https://ceur-ws.org/Vol-2931/ICBO_2019_paper_20.pdf 'with a trailing space).
2. Override the Faulty URI Validation
The ^\S+$ regex is not a proper URI validator—it’s overly permissive for invalid URIs with no whitespace and can incorrectly reject valid URIs if hidden whitespace is present. Replace it with a robust validation method using Python’s built-in libraries.
Fix:
Subclass the generated URI class and override the is_valid method to use proper URI parsing:
from linkml_runtime.utils.formatutils import URI import urllib.parse class ValidURI(URI): @classmethod def is_valid(cls, value: str) -> bool: try: parsed = urllib.parse.urlparse(value) # Ensure scheme (http/https) and domain are present return bool(parsed.scheme and parsed.netloc) except ValueError: return False # Use this subclass instead of the auto-generated URI type in your code
3. Report the Bug to LinkML
The simplistic regex used in linkml-runtime versions 1.4.5–1.4.10 is inadequate for proper URI validation. The project should use standard URI parsing logic instead of a regex for this check.
Content of the question originates from Stack Exchange, question author: Wolfgang Fahl

