Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a function that only accepts string

Hello I'm newbie in python and I wanted to know if I can create a function that only accepts certain types of values, in this case string, else error

 parameter that needs to be string
            |
            v
def isfloat(a):
    if a.count('.') > 1:
        return False
    for c in a:
        if c.isnumeric() or c == '.':
            v = True
        else:
            return False
    return v
like image 353
Thiago Axe Avatar asked Oct 19 '25 15:10

Thiago Axe


2 Answers

In Python 3.5+ you can use typing to annotate your function:

def isfloat(a: str):
    # More code here...

But type annotation doesn't actually check types!

So, it's better to add robust type check with assert statement:

def isfloat(a: str):
    assert isinstance(a, str), 'Strings only!'
    # More code here...

With assert your function will raise AssertationError if a is not a string.

like image 185
Mark Mishyn Avatar answered Oct 22 '25 04:10

Mark Mishyn


You could enclose your code within an if statement such as the following.

def enumerico(a):
    if (isinstance(a, str)):
        <your code>
    else:
        <throw exception or exit function>
like image 43
Jonathan Reynosa Avatar answered Oct 22 '25 03:10

Jonathan Reynosa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!