[Python-ideas] [Wild Idea] Static Ducks

ilya ilya.nikokoshev at gmail.com
Mon Sep 21 03:39:34 CEST 2009


I tried to read most of the thread, but I'm still not sure about the
exact meaning of the proposal. Here is how I understand it.

There are two ways to add strong typing to the language. One is called
"static typing", and it's done before you generate a bytecode,
another, "dynamic/run-time typing" is done at run-time.

Static typing is unlikely to work in Python. Suppose I do
$list a = ['string', 5+6]
$int index = some_very_complicated_calculation()
??? a[index]   # Compiler cannot know if this is string, int or IndexError.
or I could try accessing globals(name) or sys.module[name].attribute
-- compile-time check is impossible.

>From what I read I think you suggest to add run-time typing to the
language. That is partly possible now with decorators and the
annotations syntax -- you might want to check that out -- but how
useful is it really? The very fact that X is integer and Y is integer
doesn't mean that X + Y or X * Y always makes sense.


There was a very good question on StackOverflow that dealt with
typing: http://stackoverflow.com/questions/1275646/python-3-and-static-typing/1276582#1276582

My detailed opinion and links can be found there in the answer (the
accepted one).

Ilya.

On Sat, Sep 19, 2009 at 12:19 PM, Dj Gilcrease <digitalxero at gmail.com> wrote:
> I do not expect this idea to gain much traction but it has been an
> idea rolling around in my head for a year or two, so I decided to
> write it all down and see what other thought.
>
>
>
> Abstract:
>    Python does not currently support static typing of variables, which is
>    something I like, but there are times it would be nice to have static
>    typing for variables, or method/function return values.
>
>    Static Ducks should be able to run along side or imported to code that
>    does not use Static Ducks. Actual runtime enforcement of Static Ducks
>    should be off by default and require activation either via the command line
>    or at the top of a file (similar to the __future__ requirement)
> where it would
>    affect only that file (and any Static Ducks imported to it)
>
> Design Goals:
>    The new syntax should
>        * Be simple to read
>        * Make it obvious what is happening; at the very least it should be
>        obvious that new users can safely ignore it when writing their own code
>        * Allow future compilers to optimize for Static Typing.
>        * Work within a function or method definition to ensure a passed
>        variable is the proper type
>        * Allow Functions/Methods return values to be typed and checked
>        * Raise an TypeError exception when the variable is set to something
>        improper, or the function/method tries to return an improper value
>
> Issues:
>    If this PEP is implemented it may conflict with PEP 362
>    (Function Signature Object)
>
> Use Cases:
>    Python to C compilers could be enhanced by allowing static ducks.
>    IDE's code complete could be enhanced by having static ducks available
>    IDE's issues prediction could be enhanced to detect type issues for code
>    that uses static ducks (Like any static typed language)
>
> Syntax Idea:
>    """$type variable = value
>
>    $returnType def function($type variable):
>        #do stuff
>        return value
>
>    $returnType
>    def function($type variable):
>        #do stuff
>        return value
>
>    class test:
>        $type variable = value
>
>        $returnType def method(self, $type variable):
>            #do stuff
>            return value"""
>
>    The reason I selected $type is because I couldn't think of anything else
>    that $ was used for and I wanted a syntax similar to Decorators and similar
>    to other statically typed languages.
>
>    All types allow None or their proper type when setting, this so people
>    can have typed variables that can be "undefined" for checking
>
> Example:
>    $int count = 0
>
>    $bool def check($string testValue):
>        return testValue.lower() == "true"
>
>
>    class test:
>        $string _name = None
>
>        $string def get_name(self):
>            return self._name
>
>        def set_name(self, $string name):
>            self._name = name
>
> Usage Details:
>    When a variable has been statically type, any time it is set later its type
>    needs to be verified. I see this working in a similar way to how
>    properties work. Also using this style would allow people to create
>    their own static ducks.
>
>    """psudo-code
>        class StaticDuckBase(object):
>            _value = None
>
>        class IntTypeClass(StaticDuckBase):
>            def _get_value(self):
>                return self._value
>
>            def _set_value(self, val):
>                if isinstance(val, (int, type(None))):
>                    self._value = val
>                else:
>                    try:
>                        val = int(val)
>                        self._value = val
>                    except:
>                        raise TypeError("Expected int, got " +
> str(type(val)) + " instead!")
>
>            value = property(_get_value, _set_value, None)
>
>        class MyTypeClass(StaticDuckBase):
>            def _get_value(self):
>                return self._value
>
>            def _set_value(self, val):
>                if isinstance(val, MyType)):
>                    self._value = val
>                else:
>                    raise TypeError("Expected MyType, got " +
> str(type(val)) + " instead!")
>
>            value = property(_get_value, _set_value, None)
>
>        staticducks.add('mytype', MyTypeClass)
>    """
>
>    Though there will need to be some way to check if a variable is
>    statically typed so that when you do $int count = 0 then later count = 5 it
>    uses the static typing. Also if no static duck is specified it should
>    revert to nonstatic but emit a warning that is only show when run
>    with the -W option
>
> Type List:
>    Base Types:
>        $int
>        $float
>        $bool
>        $string
>        $tuple
>        $namedtuple
>        $list
>        $set
>        $frozenset
>        $dict
>        $byte
>        $bytearray
>        $memoryview
>        $nonstatic # This means treat it as if it were not statically typed
>
>    Composite type
>        $bytes -> $byte | $bytearray
>        $number -> $int | $float | Decimal
>        $seq -> $tuple | $list | $set | $frozenset | $namedtuple
>        $sets -> $set | $frozenset
>
>    Special Cases
>        #lets you require a specific type for keys and values
>        $dict($type key[, $type value])
>            """eg
>                $dict($int, $string) tmp = {} # creates a dict that requires
>                ints as keys and strings as values
>                $dict($nonstatic, $bool) tmp = {} # creates a dict that
>                requires values to be bool, but keys can be anything
>            """
>
>        $tuple($type value) # lets you specify the type for the tuples values
>        $list($type value) # lets you specify the type for the lists values
>        $set($type value) # lets you specify the type for the sets values
>        $frozenset($type value) # lets you specify the type for the sets values
>        $sets($type value) # lets you specify the type for the sets values
>        $seq($type value) # lets you specify the type for the sequence values
>
>        $string(encoding="UTF-8", normalized=False)
>        $normalized # This would be equiv of doing $string(normalized=True)
>        $normalized(encoding="UTF-8")
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>



More information about the Python-ideas mailing list