Alex Predescu
Alex Predescu

Reputation: 940

How can you write almost type safe code in Python

I am looking for a way to write maintainable code in Python. I find the language good for solving complex problems in simple style, though it seems to be a pain to work with in larger projects e.g. back-ends where you have to manually track lots of references to the same "models" without any kind of type safety implemented in the language itself.

I have found the following way of enforcing intellisense functionality (tested in vscode):

class MyObject(object):
    key1 = None

a = MyObject()
a.key1 = 1
print(a.__dict__)

I would like to be able to detect a wrong assignment such as:

a.key2 = 2
# should be highlighted

Upvotes: 0

Views: 1127

Answers (1)

gkhnavarro
gkhnavarro

Reputation: 466

If you are on Python 2.7 you can use a static type checker like mypy, which you can also use alongside dynamic typing. Python 3.6 also now has static type checking, so you can hint a variable type.

variable_name: type 
my_string: str = "My string value"

def my_function(first_arg: int) -> string:
    # do stuff here

Intellisense for Python supports highlighting for type hints in Python 3, so you don't need to implement one yourself.

Upvotes: 2

Related Questions