What is the difference between Type and Type*? - lean

I have seen some instance of Type* in this project. Running #check Type* gives Type u_1 : Type (u_1+1) and #check Type gives Type : Type 1.
Performing a search over the language reference and Ctrl-Fing the Expressions chapter doesn't seem to give any information on Type*. What, conceptually, is it used for? Also, if possible, what is being used for in the project that I linked?
(The * is hard to search for, sorry if this is a duplicate.)

Related

python type hinting not generating error for wrong type

I was recently checking about type hinting and after reading some theory I tried an simple example as below
def myfun(num1: int, num2: int) -> int:
return str(num1) + num2
a = myfun(1,'abc')
print(a)
# output -> 1abc
Here you can see that I have define num1 and num2 of type int and even after passing num2 value as string it is not generating any error.
Also the function should expect to return int type value but it's not complaining on returning string type value.
Can someone please explain what's going wrong here?
It's called type hinting for a reason: you're giving a hint about what a variable should be to the IDE or to anyone else reading your code. At runtime, the type hints don't actually mean anything - they exist for documentation and usability by other developers. If you go against the type hints, python won't stop you (it assumes you know what you're doing), but it's poor practice.
Note that this differs from statically-typed languages like Java, where trying to pass an argument that's incompatible with the function's definition will produce a compile-time error, and if you pass a differently-typed but compatible argument (e.g. passing a float to a function that expects an int) it will be automatically typecast.
Note that the code you've given will encounter a TypeError if the programmer uses it like they're supposed to, because int cannot be concatenated to a str. Your IDE or linter should be able to see this and give you a warning on that line, which it does based on the type hints. That's what the type hints are for - informing the behavior of the IDE and documentation, and providing a red flag that you might not be using a function in the intended way - not anything at runtime.

Require that a specific Haskell type defined in code is invalid

Is it possible to instruct GHC compiler to require that a specific value in code has invalid type, without ever using this value?
A contrived example is:
data Box a = Num a => Box a
goodBoxSample :: Box Int
goodBoxSample = Box 1
-- below definition and binding are expected to fail compilation
badBoxSample :: Box String
badBoxSample = Box "foo"
Is there a way to inform the compiler that badBoxSample is expected to fail (e.g. with some pragma, rather than commenting it out as a known bad sample), so that the code compiles only if badBoxSample fails to type-check?
The motivation here is the same as for writing a test (in some other language) with the code that is required to throw exception for the test case to pass.
Not possible. You're basically asking for a way to prove that there's no instance Num String, but Haskell operates under the open-world assumption, which means that someone could always declare such an instance.
Somebody posted a very helpful answer here, but before I managed to accept it was removed... Thank you anyway, and here it is for the reference:
https://hackage.haskell.org/package/generic-lens-2.0.0.0/docs/Data-Generics-Product-Fields.html
In short, the goal of testing failing types can be achieved with doctest, in the way the linked library does it.

Problem with Python type hinting and standard libs

The following code works as expected, but the os.path.join produces a type error using pyright in VSCode, where shown.
# python 3.6.9
# pyright 1.1.25
# windows 10
# vscode 1.42.1
import os
import tempfile
with tempfile.TemporaryDirectory() as tmpfolder:
name = "hello.txt"
path = os.path.join(tmpfolder, name)
# No overloads for 'os.path.join(tmpfolder, name)' match parameters
# Argument types: (TypeVar['AnyStr', str, bytes], Literal['hello.txt'])
print(path)
I think I understand the immediate cause of the problem, but contend it should not be happening. Given that, I have some questions:
Is this the idiomatic way to write this code?
Is the problem in tempfile, os, pyright, or me?
If I cannot upgrade Python, what is the best (i.e. least clunky) way to suppress the error?
This seems like a limitation of pyright.
In short, the tempfile.TemporaryDirectory class is typed to be generic with respect to AnyStr. However, your example code omits specifying the generic type, leaving it up to the type checker to infer something appropriate.
In this case, I think there are several reasonable things for a type checker to do:
Pick some default generic type based on the typevar, such as 'str' or 'Union[str, bytes]'. For example, mypy ends up picking 'str' by default, giving 'tmpfolder' a type of 'str'.
Pick some placeholder type like either 'Any', the dynamic type, or NoReturn (aka 'bottom' aka 'nothing'). Both types are a valid subtype of every type, so are guaranteed to be valid placeholders and not cause downstream errors. This is what pyre and pytype does -- they deduce 'tmpfolder' has type 'Any' and 'nothing' respectively.
Attempt to infer the correct type based on context. Some type checkers may attempt to do this, but I don't know of any that handles this particular case perfectly.
Report an error and ask the user to specify the desired generic type.
What pyright seems to do instead is to just "leak" the generic variable. There is perhaps a principled reason why pyright is deciding to do this that I'm overlooking, but IMO this seems like a bug.
To answer your other questions, your example program is idiomatic Python, and type checkers should ideally support it without modification.
Adding a # type: ignore comment to the line with the error is the PEP 484 sanctioned way of suppressing error messages. I'm not familiar enough with pyright to know if it has a different preferred way of suppressing errors.

How to enforce variable typing in Named Tuple in Python?

I am following this tutorial on named tuple with specification of variable types. However, I modified the code (below), and even if I enter values of wrong types, there was no error message or programming break as a result. I understand you can write your own try/except to raise error exception, but is there a readily-available solution/syntax to enforce users entering the right type of variables.
from typing import NamedTuple
class Pet(NamedTuple):
pet_name: str
pet_type: str
def __repr__(self):
return f"{self.pet_name}, {self.pet_type}"
cleons_pet = Pet('Cotton', 'owl')
print('cleons_pet: ', cleons_pet)
cleons_pet_v2 = Pet(222, 1)
print('cleons_pet_v2: ', cleons_pet_v2)
# Output
cleons_pet: Cotton, owl
cleons_pet_v2: 222, 1
[Finished in 0.1s]
The type hints in python will not be evaluated by python itself! See PEP484
While these annotations are available at runtime through the usual annotations attribute, no type checking happens at runtime. Instead, the proposal assumes the existence of a separate off-line type checker which users can run over their source code voluntarily.
There are at least two projects which offer offline type checking (mypy and pyre). You should definitely use them if you are using type hints in your project.
If you want to validate the input while running the application, you have to either convince the offline type checkers by validating the data by yourself or use a third-party library. I know of attrs, where you can use validators or type annotations for online validation.

i'm confused about languages category, can anyone please explain?

Which of the following statements is FALSE?
(A) In statically typed languages, each variable in a program has a fixed type
(B) In un-typed languages, values do not have any types
(C) In dynamically typed languages, variables have no types
(D) In all statically typed languages, each variable in a program is associated with values of only a single type during the execution of the program
Can you please explain the theory as well?
C) (In dynamically typed languages, variables have no types) Is false.
The variable has a type, however it is simply not stated or decided until run time. This implies there is no type checking prior to running the program.
a useful link describing Types and what it means:
http://en.wikipedia.org/wiki/Type_system
If you have ever done much with PHP you will notice that when you declare a varialbe, you do not have to say whether it is an INT or a STRING. However, sometimes you know that you will be receiving a string, but need an int, so you can still type cast variables at runtime, even though when you declared the variable you did not explicitly state the variable would hold an int.
<?php
#some more code here.....
# over here $myValue could be of some different type, but it can dynamically change to another type
$myValue = '5'; #storing a string...so $myValue is currently of type String
$myNewValue = (int)$myValue + 5 #type casted to integer, so in this case $myValue is currently of type integer
?>
If that doesn't help, maybe take a look at this.
myPythonVariable = "I am currently a string" #the variable is of type string
myPythonVariable = 5 #the variable is now of type integer
In the above code sample, myPythonVariable always has a type, whether or not that type changes doesn't matter.

Resources