Python safe casting

How to make safe cast in Python

In C #, I can safely cite by keyword, for example:

string word="15"; var x=word as int32// here I get 15 string word="fifteen"; var x=word as int32// here I get null 

Is there anything similar to this in Python?

+10
source share
4 answers

Do not think, but you can implement your own:

 def safe_cast(val, to_type, default=None): try: return to_type(val) except (ValueError, TypeError): return default safe_cast('tst', int) # will return None safe_cast('tst', int, 0) # will return 0 
+44
source

I believe you have heard of " pythonic ." In this way, safe casting will really rely on the rule โ€œAsk for forgiveness, not permissionโ€.

 s = 'abc' try: val = float(s) # or int # here goes the code that relies on val except ValueError: # here goes the code that handles failed parsing # ... 
+4
source

There is something like this:

 >>> word="15" >>> x=int(word) >>> x 15 >>> word="fifteen" >>> x=int(word) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'fifteen' >>> try: ... x=int(word) ... except ValueError: ... x=None ... >>> x is None True 
+3
source

Casting only makes sense for a variable (= memory fragment whose contents may vary)

There are no variables in Python whose contents can change. There are only objects that are not contained in anything: they have existence itself. Then the type of the object cannot change, AFAIK.

Then, casting doesn't make sense in Python. This is my faith and opinion. Correct me if I'm wrong, please.

.

Since casting does not make sense in Python, it makes no sense to try to answer this question.

The question reveals some misunderstandings of the Python foundations, and you will get more profit by getting answers, explaining what led you to think that you need to quit

-4
source

Source: https://habr.com/ru/post/890400/


All Articles