question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Feature Request] Validate against other arguments to a function

See original GitHub issue

I’m wondering if there’s functionality in beartype for doing something like this:

#!/usr/bin/env python3
""" This code does not work because these features are not implemented. """
import sys
import beartype
from beartype.vale import IsRelative
from typing import List
if sys.version_info >= (3, 9):
    from typing import Annotated
else:
    from typing_extensions import Annotated

LengthNList = Annotated[List[int], IsRelative[lambda lst, args: len(lst) == args["n"]]]

def print_list(lst: LengthNList, n: int) -> None:
    print(f"Length: {n}")
    print(f"List: {lst}")


# This should work.
print_list([0, 1, 2, 3], 4)


# This should raise a TypeError or something.
print_list([0, 1, 2, 3], 5)
~                          

I’d like to be able to check the type of an argument to a function against the value of another argument when the function is called. So instead of feeding our validator thing Is[] some lambda function that takes a single argument, we feed it a lambda function of the form lambda x, args: <boolean expression> where args is a dictionary mapping parameter names to argument values. Perhaps this is a variant of Is called IsRelative or something, since you’re checking relative to the other arguments.

Is this extant/possible/easy?

It’s been a while, but I’ve tried to do this before in a (deprecated/broken/unmaintained) typeguard-knockoff-for-tensors that I wrote before I learned beartype existed (which is much better). The closest I got was a very hacky implementation of “variable” shapes and such. See the “variable shapes and dimensions” and “dimension inference” sections in the README here: https://github.com/langfield/asta.

If it’s possible, I’d like to see stuff like this in beartype eventually, but I’m curious if it’s possible to do without incurring unacceptable performance costs. My thing was definitely a “full-fat O(n)” checker and it was slowwww.

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:1
  • Comments:32 (9 by maintainers)

github_iconTop GitHub Comments

4reactions
langfieldcommented, Jul 18, 2022

Of course, ASTs are a fathomless black hole from which few return alive and even fewer return sane. This may not necessarily happen within the expected lifetime of my life is what I’m saying. A drip-feed of corporate and/or governmental sponsorship would probably get us there sooner than later. Until Money Shangri La materializes, however, this is lower on the priority list than you’d like. Ugh!

tl;dr

Money. That’s what can make this happen. money_mouth_face

There you go @leycec. Now that @posita has thought of it, it is only a matter of time before someone writes bearcoin or typecoin. Remember those non-amortized negligible constant factors? Well one of them is a hash computation. That’s right, whenever you typecheck a function with @beartype, you’re actually mining bearcoin, of which 50% of the outstanding supply is held by @leycec to fund the development of beartype and advocacy for the runtime typechecking of every little bit of python code under the sun.

3reactions
positacommented, Jul 18, 2022

Peanut Gallery

<peanutgallery> I guess a runtime type checker already blurs those lines? Maybe calling it a type checker is confusingly limited. Jus’ spitballin’ here, but maybe it should be called something like a Runtime-Enforced Annotation-Based Contract (or Interface) Notation? REABIN¹? REABCoIN²? Not sure if you can keep the O(1) claim if that ends up being an explicit goal. Either way, it would be pretty ambitious if other goals were readability and concision. (Annotations seem like somewhat of a handicap.)


¹ Note that REAB is an anagram of BEAR. 😉 ² NFT riches, here we come! 🤑 </peanutgallery>

Read more comments on GitHub >

github_iconTop Results From Across the Web

Expand custom validator to Validate against other property ...
This is what I would like to have: RuleFor(e => e.AnswerPath).Custom( (e, context) => {[Validation logic that checks that this property ...
Read more >
Validation - Laravel - The PHP Framework For Web Artisans
To learn about Laravel's powerful validation features, let's look at a complete example of validating a form and ... public function store(Request $request)....
Read more >
CA1062: Validate arguments of public methods (code analysis)
Learn about code analysis rule CA1062: Validate arguments of public methods. ... has been validated by another method call in the function.
Read more >
Dynamic type validation in TypeScript - LogRocket Blog
As you can see, a new function has been defined, called validate , which receives as a parameter an ExampleType object, with which...
Read more >
Validating Input | Web Accessibility Initiative (WAI) - W3C
Be forgiving of different input formats; Client-side validation benefits; Validation by the user. Require user confirmation; Provide undo functionality.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found