[Types-sig] check_type()

Greg Stein gstein@lyra.org
Thu, 16 Dec 1999 15:29:21 -0800 (PST)


On Wed, 15 Dec 1999, Paul Prescod wrote:
> Greg Stein wrote:
...
> > > j=has_type( foo, types.StringType ) or has_type( foo, types.ListType ):
> > 
> > You'll have issues with empty strings and empty lists, as Guido pointed
> > out.
> 
> Yes, you have to use it in ways that follow Python's boolean rules. A
> better name would be check_type.
> 
> j=check_type( foo, types.StringType ) 
> 
> > has_type() does not create a *definitive* type assertion. The compiler
> > cannot extract any information from the presence of has_type(). Using an
> > operator which raises an exception allows the compiler to make the
> > assertion (and thereby assist with type inferencing and type checking).
> 
> j=check_type( foo, types.StringType)
> 
> j is *guaranteed* to be either a string or None.

But that is a problem right there: you've introduced the possibility that
<j> might be None. While the compiler / type-checker can certainly do
something useful with that concept, this does not provide a way to
guarantee a *single* type.

j = check_type(foo, String)
func_taking_string(j)

The above will fail because the compiler will flag the possibility of <j>
being None.

j = foo ! String
func_taking_string(j)

Now that works :-)

> Note that check_type is actually an operator in that it cannot be
> overwritten or shadowed. It just happens to be an operator that looks
> like a function and that returns a useful value instead of immediately
> causing an exception. It also happens to be compatible with the current
> Python grammar.

Icky. Either the compiler now has to understand that NAME(...) could
possibly require special processing, or the parser recognizes it and
constructs a new AST node. The former is badness, and the latter says
you're changing the parser, so why not use a "real" operator?

People might also be tempted to do:

ct = check_type

ct(x, String)
ct(y, Int)
ct(z, List)

Of course, this will fail because check_type isn't really a valid name.

> I have big aesthetic problems with adding a special character to a
> language that uses the word "or" to mean, well "or" and "not" to mean
> "not". I might be able to live with 
> 
> "k = eval('1') as int"
> 
> if it isn't too horribly ambiguous. 

Using "as" instead of "!" would be non-ambiguous. However, the word "as"
seems to imply "use it as an int" rather than an assertion that it *is* an
integer.

Of course, we can't use the word "is" because it can already be used
inside an expression. "isa" might even be more appropriate, and is
available for usage.

For now, I'll keeping using '!', but I'm on record as being open to
alternate representations for the operator.

Cheers,
-g

-- 
Greg Stein, http://www.lyra.org/