String to Python statement? - python

I want to convert a string to a Python statement.
Taking string input from a text file e.g. 'dataframe['Column_name'].sum()'
Executing the string as a Python statement e.g. dataframe['Column_name'].sum()
Storing the result in some variable

It's possible to do this, but not recommended. You do not have any control over what the string contains if it comes from the user. There is probably a better way to achieve what you really want.
If you really, absolutely, unavoidably have to, you can use eval:
x = eval('dataframe["Column_name"].sum()')
But it is probably easier to only take, for example, the column name from the user and use that in a function call:
column_name = "Column_name" # or read it from the file
x = dataframe[column_name].sum()

#previous code
with open("file.txt","r") as f:
x = eval(f.readline())
#the rest of the code, using x however you want
I wouldn't do it if other users are supposed to be able to use the script however they want. If this is for learning purposes of for your own use, it's up to you.

Related

How can I put the input inside a string which already exist?

I have a string called data, you can see below. I just want to take an input from user and put the input inside ability_id field in data.
def main():
ability_id = input("Enter an ability id) # example:abc-123-abc-123
data = '{"paw":"1234","ability_id": f"{ability_id}" ,"obfuscator":"plain-text"}'
print(data)
While I don't think, saving the string like this has a lot of sense, I will still give you an answer to your question.
If you want to do it like this you can, as you already nearly did, use the f-string.
But you can't just simply start an f-string inside a normal string - this is not, how this works. Instead, you have to make the whole thing an f-string and then indicate inside this string, where you want to place the variable. Something like this:
data = f'{{"paw":"1234","ability_id": "{ability_id}" ,"obfuscator":"plain-text"}}'
Attention: Watch out, that you use the double curly-brackets at the beginning and ending of the string, otherwise it will not work

How do I let Sympy parse an expression while only regarding arbitrary previously defined strings as symbols?

So what I am trying to do is write a script that lets me input some function and a list of the variables inside it, then processes it into some other formular, computes a result, and then outputs both the new formular and the result as Latex code. Everything works fine as long as I only input variables which do not contain "^", "{", or "}". The problem is, I want to use, or, at the very least, output the names exactly as they are written in my Latex document, and as such they do often contain these characters.
I am aware that there is a built-in Latex-Parser in Sympy, but as I understood it requires some other package (antlr4), and I would like to try to avoid that, since I am planning to distribute the script to my fellow students, and don't want to add another requirement for running the script.
So what I thought of is that I could use the list of variable names (which I input anyway together with their values to allow the program to compute a final result): I tried to define a "transformation", as it is described on the Sympy documentation on parsing. It looks like this:
#Defining the transformation
def can_split(symbol):
#Check if symbol is in one of the lists of inputted values (the two lists contain tuples of variable names[0] and their corresponding values[1])
if symbol not in ([i[0] for i in uncertainValues]+[i[0] for i in certainValues]):
return _token_splittable(symbol)
return False
#Read function definition from TKinter text field, split only by custom defined symbols
function=parse_expr(functionEntry.get("1.0", "end-1c"),transformations = (split_symbols_custom(can_split)))
The problem is that if I run this script, and input e. g. "a^b*c", and the variable names "a^b" and "c", which should normally be read as "the variable 'a^b' multiplied with the variable 'c'"I get the exception: "NameError: name 'a' is not defined".
If anyone could help me with this, or maybe propose another way to do this properly, I would be very thankful. Also, if there is more code or context needed to find a better solution, I'll provide more - I just felt everything would get too long-winding if I explained the whole idea. But as I said, I'll be glad to do that if it helps.
Quick but dirty workaround:
For now I ended up using the dirty method of replacing all problematic characters with unique strings at input, and replacing them with their symbols again before outputting.

How to use single quotes in Python keywords/variable name?

I want to use single quote in a variable name and keyword. I know how to do this for a variable value using single and double quotes("5'_Exon_Annotation") or using black slash to escape the single quote. But not sure how to do this with variable name/ key word. Below are examples of how I want to assign values to column names and a variable that needs single quote.
5'co-ordinate = "something"
gene_df = gene_df.assign(gene_position = gene_pos,
5'_co-ordinate = bkpt1_list[1],
3'_co-ordinate = bkpt2_list[1])
First of all is it possible in Python? I couldn't find a post related to this.
While I wouldn't recommend it at all, it is possible to use all kinds of characters for attributes of classes using setattr(), like so:
class Test:
def __init__(self):
setattr(self, 'this variable has ""', 1)
test = Test()
print(getattr(test, 'this variable has ""'))
# test.this variable has "" does NOT work
But I really wouldn't recommend it. The intestesting thing about this is, that setting an attribute this way makes it kind of hidden, because you can only access it using getattr().
If you use globals() or locals() you can also set variables this way:
locals()['this variable has ""'] = 1 # or globals()
print(locals()['this variable has ""'])
# this variable has "" = 2 does NOT work
That makes it really cumbersome to access the variable though, and again, I really wouldn't recommend it. It's a neat trick (debateable I guess) if you really want to hide something though.
Here are the available characters for Python identifiers. You might find something which is close to an apostrophe but not the common one.
Btw. I'd not suggest to deviate from the ASCII table. If the language naturally support it and the editors offer helpers to write those, it's fine (like Julia) but for Python it can be quite confusing for others.
https://docs.python.org/3/reference/lexical_analysis.html#identifiers
Here is an example of a valid Python code using some kind of a quote in the function name (copy-paste it, but the single quote is for example not displayed in Safari on macOS, however it's there as you can see in the screenshot of my terminal):
In [1]: def f֜(x): return 2*x
In [2]: f֜(3)
Out[2]: 6

Read only a required function in python

I want to guess the type of a variable based on its usage in a function. For this, I decided to use Regex in which I will have a list of expressions for every type. Like, for an integer, a few possible expressions could be,
'''
pattern = [r"[a-z]\s\+", r"[a-z]\s\-", r"[a-z]\s\*", r"[a-z]\s\/", r"[a-z]\s\=\s[0-9]", r"[a-z]\s\=\=\s[0-9]*"]
'''
I want to search for these patterns for every variable in a function and decide the type.
But, To do this, I need to consider only the function,i.e, I need to read the lines of only the required function from a big python file.
Is there a way I can do this?

Parsing list to create python code

I have a list that I have successfully converted into a python statment
ex:
from operator import mul,add,sub,abs
l = ['add(4,mul(3,abs(-3)))']
I was wondering what would I use to RUN this string as actual python code? I should be expecting a output of 13. I want to input the 0th value of the list into a function that is able to run this value as actual python code.
You don't want to run this as Python code. You're trying to parse expressions in some language that isn't Python, even if it may be superficially similar. Even if it's a proper subset of Python, unless, say, __import__('os').system('rm -rf /') happens to be a valid string in the language that you want to handle by erasing the hard drive, using eval or exec is a bad idea.
If the grammar is a proper subset of Python, you can still use the ast module for parsing, and then write your own interpreter for the parsed nodes.
However, I think what you really want to do here is build a very simple parser for your very simple language. This is a great opportunity to learn how to use a parsing library like pyparsing or a parser-generator tool like pybison, or to build a simple recursive-descent parser from scratch. But for something this simple, even basic string operations (splitting on/finding parentheses) should be sufficient.
Here's an intentionally stupid example (which you definitely shouldn't turn in if you want a good grade) to show how easy it is:
import operator
OPERATORS = operator.__dict__
def evaluate_expression(expr):
try:
return int(expr)
except ValueError:
pass
op, _, args = expr.rpartition('(')
rest, _, thisop = op.rpartition(',')
args = args.rstrip(')').split(',')
argvalues = map(int, args)
thisvalue = OPERATORS[thisop](*argvalues)
if rest:
return evaluate_expression('{},{}'.format(rest, thisvalue))
return thisvalue
while True:
expr = input()
print(evaluate_expression(expr))
Normally, you want to find the outermost expression, then evaluate it recursively—that's a lot easier than finding the rightmost, substituting it into the string, and evaluating the result recursively. Again, I'm just showing how easy it is to do even if you don't do it the easy way.
use exec like this:
exec('add(4,mul(3,abs(-3)))')
That should work
more about exec
If you want to evaluate a Python expression, use eval. This returns the value of the evaluated expression. So, for example:
>>> eval(l[0])
13
>>> results = [eval(expr) for expr in l]
>>> results
[13]
However, any time you find yourself using eval (or exec or related functionality), you're almost always doing something wrong. This blog post explains some of the reasons why.
since you're evaluating an expression, eval would suit you better than exec. Example:
x = -3
y = eval('add(4,mul(3,abs(x)))')
print y
Note the security implication of exec and eval, since they can execute arbitrary code, including for example deleting all files you have access, installing Trojans to your doc files, etc.
Check out also ast.literal_eval for python 2.6+.

Categories