Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

282
Vistas
Does Raku has Python's Union type?

In Python, Python has Union type, which is convenient when a method can accept multi types:

from typing import Union

def test(x: Union[str,int,float,]):
    print(x)

if __name__ == '__main__':
    test(1)
    test('str')
    test(3.1415926)

Raku probably doesn't have Union type as Python, but a where clause can achieve a similar effect:

sub test(\x where * ~~ Int | Str | Rat) {
    say(x)
}

sub MAIN() {
    test(1);
    test('str');
    test(3.1415926);
}

I wander if Raku have a possibility to provide the Union type as Python?

#        vvvvvvvvvvvvvvvvvvvv - the Union type doesn't exist in Raku now.
sub test(Union[Int, Str, Rat] \x) {
    say(x)
}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

My answer (which is very similar to your first solution ;) would be:

subset Union where Int | Rat | Str;

sub test(Union \x) {
   say(x) 
}

sub MAIN() {
    test(1);
    test('str');
    test(pi);
}

Constraint type check failed in binding to parameter 'x'; 
expected Union but got Num (3.141592653589793e0)

(or you can put a where clause in the call signature, as you have it)

In contrast to Python:

  • this is native in raku and does not rely on a package like "typing" to be imported
  • Python Union / SumTypes are used for static hinting, which is good for eg. IDEs
  • but these types are unenforced in Python (per @freshpaste comment and this SO), in raku they are checked and will fail at runtime

So - the raku syntax is there to do what you ask ... sure, it's a different language so it does it in a different way.

Personally I think that a typed language should fail if type checks are breached. It seems to me that type hinting that is not always enforced is a false comfort blanket.

On a wider point, raku also offers built in Allomorph types for IntStr, RatStr, NumStr and ComplexStr - so you can work in a mixed mode using both string and math functions

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda