0

I want to restrict a string type by executing a function at the type hint. It seems to not cause any problems, but is it a well-defined practice or has any correspondences anywhere?

An example code excerpt:

class A:
  def __str__(self):
    return "a"

@dataclass
class B:
   var: str(A) + '.txt'

The idea would be var will be a string that is generated from an A and has '.txt' suffix.

  • 3
    Are you expecting something similar to TypeScript's [template literal types](https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html)? They don't exist in Python typing AFAIK. And certainly that "function" is only going to be evaluated _once_, when the annotation is (when exactly depends on whether you `from __future__ import annotations`), with the value being something like `".txt"`. – jonrsharpe Aug 16 '22 at 15:53
  • or just `f'{A!s}.txt'`; though the `!s` might be redundant too. – rv.kvetch Aug 16 '22 at 16:17
  • @jonrsharpe that's very similar to what I was trying to achieve yes. `str(A)` was meant to provide the semantics of `call string function on an object of type A` rather than `call string function of the class A` but I don't think that's really possible I guess? – Alperen Keleş Aug 16 '22 at 16:19
  • well, you need a `self` param to the str function, so yep you'd need to instantiate an instance of type A most likely. – rv.kvetch Aug 16 '22 at 16:27
  • @rv.kvetch the problem is that I don't wanna instantiate `some A`, I wanna be able to type-check it with `any A`. – Alperen Keleş Aug 16 '22 at 16:48
  • hmm, sounds like you want to define a class method instead, in that case – rv.kvetch Aug 16 '22 at 16:54
  • @Alperen As far as I'm aware, "any `A`" isn't really a thing with regards to typing. What are you actually trying to achieve with this? That is, If you were able to actually do this, what purpose would it serve? It can't be static typing cause what you're showing is dynamic. And it can't be type validation, [unless you're using PyDantic's `dataclass`](/a/55910982/4518341)? Beware the [XY problem](https://meta.stackexchange.com/q/66377/343832). Maybe, hypothetically, you'd be better off accepting `var: A` then creating the string you want in `B.__init__()`. – wjandrea Aug 16 '22 at 19:29
  • agreed, so maybe you just want the class name of `A` in that case? unless `A.__str__()` could return something random like `xyzq` or something. In either case, do second that would be good to have some clarifying statements on what you're trying to achieve exactly. – rv.kvetch Aug 16 '22 at 19:44

0 Answers0