A
A
AveWycc2020-04-30 15:48:38
Python
AveWycc, 2020-04-30 15:48:38

Would this use of eval be safe?

I have an implementation of Set in a separate set.py module and it has a conversion of the value entered in the console, a conversion to the type that I originally entered.
The check itself:

def _conversion(self, val):
        """ Convert value in needed type """
        try:
            return eval(self.__set_type)(val)
        except ValueError:
            print("ValueError: Wrong input")
            return None

If I limit the input to a set of 'int' 'float' etc. at the very beginning in main.py using if , then can eval be considered safe now?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Pankov, 2020-04-30
@AveWycc

such an eval cannot be used just because it is unsafe. In fact, if using eval doesn't make things worse, then why not.
Pretty crazy idea to walk down the street with an open wound. But in a protected environment in a hospital between dressings, this is a normal situation, although it does not eliminate the need to be careful.
Bare wires in a residential area are unacceptable, but in phase tires with the correct marking in the switchboard, they are probably acceptable.
It's not just about eval.
Once I heard from a student about the following reasoning when he needed to write a simple calculator:

eval cannot be used (unsafe), so I write user input to a python file and import this file as a module...

A
Andrey Dugin, 2020-04-30
@adugin

Use safe eval:
from ast import literal_eval as eval

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question