1

It's a little hard to explain what I want to do because I don't know much python programming terminology.

Basically I want to be able to do something like this this:

var = list("blah blah")
print(str(var))

And get this:

Output:

list("blah blah")

And not this:

Output:

['b', 'l', 'a', 'h', ' ', 'b', 'l', 'a', 'h']

Or do something like this:

a = str(4+(6*3)) + " Test"
print(str(a))

And get this:

Output:

str(4+(6*3)) + " Test"

And not this:

Output:

22 Test
Zeeen
  • 312
  • 1
  • 2
  • 13
  • There is probably a simple answer to this question I am just too much of a rookie to find out what it is – Zeeen Sep 07 '20 at 18:43
  • It depends on what context you want to use this in. [This](https://stackoverflow.com/q/427453/3000206) may work in some cases if the code is wrapped in a function. Generally though, you'd need a macro that views the code before it's evaluated. – Carcigenicate Sep 07 '20 at 18:47
  • 1
    It seems like you're basically in https://stackoverflow.com/q/2749796/3001761 territory. Python evaluates the expression and stores the *result* in `var`. What's the *context* - what problem are you trying to solve? – jonrsharpe Sep 07 '20 at 18:48
  • @jonrsharpe Yeah like trying to get the original variable name, but instead trying to get the original variable value. – Zeeen Sep 07 '20 at 18:49
  • Do you know at which line in the file the variable is being assigned? – shreyasm-dev Sep 07 '20 at 18:54
  • Why not store everything in a string and evaluate it later, assuming you need it evaluated at all? – OneCricketeer Sep 07 '20 at 19:30
  • I guess I could store it in a string but it would be preferable to just get the raw value of something – Zeeen Sep 08 '20 at 01:03

1 Answers1

1

You can do it like so:

import re # 0
# 1
l = list('list') # 2

filecontent = open(__file__, "r").read()

varline = re.sub('\s*#.*$', '', re.split('\s*=\s*', filecontent.split('\n')[2])[1])
print(varline)

Explanation:

import re # Line 0 - import the regex module

l = list('list') # Line 2 - set the variable l

filecontent = open(__file__, "r").read() - read the current file's content

varline = re.sub('\s*#.*$', '', re.split('\s*=\s*', filecontent.split('\n')[2])[1]) - Get the 3rd line's content (where the variable is being declared) and filter it to only include the variable's content, and not even comments

print(varline) - print the content

shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34
  • 1
    I guess this works, I wish there was some library that made this less complex or something but this will have to do. Thank you. – Zeeen Sep 08 '20 at 01:04