October 2nd, 2013, 06:26 PM
General Advice: Building an internal interpreter
So, I want to build something of a scientific/graphing calculator esque program, with some stuff that most normal calculators do, but with python syntax and certain operations.
For example, I already want to import math on start-up.
Also, I want the last answer I did to be auto-saved into a variable 'Ans'.
Plus, Python doesn't coerce into floats when I need to do float operations, and I'm thinking I might be able to come up with a happy medium that doesn't convert unless necessary, but skips me having to remember the '.0' at the end of each number.
Basically, I'm looking to create an interpreter shell inside the interpreter, a place where I can temporarily suspend "The Rules" by adding some more steps in the mix to help with my math homework. :P
From here, I hope to integrate other functions with use of modules, such as an actual graph function, but that's for when I actually can get a GUI together.
How do I create a full-fledged internal namespace for my exec functions? What needs to be copied over, and how do I copy it? (Yes, I do want a second copy for proper containment purposes :P )
Is there something that an 'exec in namespace' won't do correctly?
Should I not take the exec approach? Why?
October 2nd, 2013, 09:40 PM
- Firstly, the interpreter does store the previous result in a variable named <underscore> as in _ .
- Secondly, (this is a python3 answer but you can look up the exec statement in python2) you can pass an environment to the exec function
You should be aware of the globals() and locals() functions.
Help on built-in function exec in module builtins:
exec(object[, globals[, locals]])
Read and execute code from an object, which can be a string or a code
The globals and locals are dictionaries, defaulting to the current
globals and locals. If only globals is given, locals defaults to it.
Yes, exec within a try: except: block is good for this. Just make sure you use the program with trusted friends only. At least on your own computer.
- thirdly, use floats internally. Convert to integer on output.
int(x) if round(abs(x))-abs(x) < tolerance else x
or something like that. uh oh---untested.
Hope some of this is new information and also useful.
Comments on this post
[/code] are essential for python code and Makefiles!
October 6th, 2013, 08:38 AM
Ooh, the underscore thingy is neat.
The point was I wanted to just do calculations on the command line, and since this was math homework, I WANTED a float in the output. It was inputting floats as floats that was bugging me.
There's other reasons that I want to build an internal interpreter state to play with things; the first thing that comes to mind is some of my recent Pygame experiments. I have not yet been sufficiently convinced that this isn't the way to go for the graphing calculator thing, though. I just don't know how to create a feasible internal namespace that will look like a complete Python shell.