Can Python be made statically typed?

I know that Python is generally slower than languages ​​like fortran and c / C ++ because they are interpreted rather than compiled.

Another reason I also read it is that it is quite slow because it is dynamically typed i.e. you don't need to declare the types of the variables, and that's automatic. This is very nice because it makes the code cleaner and you basically don't have to worry too much about variable types.

I know there won't be a very good reason for this, as you can just wrap for example. fortran with Python, but is it possible to manually override this dynamically typed nature of Python and declare all variable types manually and thereby increase Python's speed?

+3


source to share


2 answers


If I interpret your question as "Is there a statically typed mode for Python?" then Cython is probably the closest thing to providing this functionality.

Cython is a superset of Python syntax - almost any valid Python code is also valid Cython code. The Cython compiler converts quasi-Python source code into non-primary C eyes, which can then be compiled into a shared object and loaded as a Python module.



Basically you can take your Python code and add as many or more static type declarations as you like. Wherever types are declared, Cython will add to the required template to deduce them correctly at the expense of runtime performance. This essentially allows you to choose a point on the continuum between fully dynamically typed Python code and fully statically typed C code, depending on how much runtime you need and how long you are willing to optimize. It also allows you to call C functions directly, making it a very convenient way to write Python bindings for external libraries.

For a better understanding of how this works in practice, check out the official official tutorial .

+1


source


Just to be clear, your question is about as strange as asking if you can include C in a dynamically typed language. If you want to redefine the language, then by all means, you can do whatever you want. I don't think we'll call such a language "Python" though.

If you're looking for speedup based on dynamic static typing (static typing that is dynamically discovered), a language implementation take a look at pypy . It's also pretty quick if that's what you're looking for. A related pypy RPython that does what you want.



Also mentioned earlier is Cython , which does what you want.

+2


source







All Articles