Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
type checking
#1
Python doesn't do type checking of passed arguments in function calls so i do that on my own. but, at least i can do checks that allow multiple types. and i can even check the types being passed inside dictionaries, lists, tuples, sets, and frozensets.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
TypeHints are not checked during runtime. They are helpers for IDEs.
For example I modify this code: https://python-forum.io/Thread-Counting-...0#pid88370

from typing import (
    NamedTuple,
    Iterable,
    Any,
)

 
class CountIndexResult(NamedTuple):
    count: int
    index: int

 
def count(iterable_or_gen: Iterable, value: Any) -> CountIndexResult:
    first_index = None
    count = 0
    for index, element in enumerate(iterable_or_gen):
        if element == value:
            if first_index is None:
                first_index = index
            count +=1
    return CountIndexResult(count, first_index)


print(count([2,2,2,2,2,2,1,1,1,1,1,1,2,2], 1))
If you use this code for exmaple with Pycharm, it will detect wrong data-types.
It's highlited, if you take for the first argument a non-iterable.
But this will not checked during runtime, but together with pydantic it will.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
how do you specify that your function needs a list or tuple of length 2 with an int and a string in any order?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
Why are you modelling whatever that is in that way? Why not with a class or at least a namedtuple?
Reply
#5
the function just needs an int and a string. it takes them as 2 arguments or as a 2-list or as a 2-tuple. it also accepts them in the order int,string or string,int. i should probably add set and frozenset to what it accepts. how is making it a class any better? how does requiring a named tuple help call this function?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020