Forum Archive

Change syntax

jbap

How can I change Python syntax in Pythonista? I wish to create some sort of module that changes the syntax when imported and changes it back with a module.quit() function. I specifically want to create bind(obj1, obj2) where obj1.value =obj2 and vice versa. Any ideas?

dgelessus

Python's syntax cannot be changed by Python code. If it could, then it wouldn't be syntax. (It is possible to process Python code from a string in advanced ways using the tokenize, parser and ast modules and the compile function. That's probably not what you're looking for though.)

Can you give an example of how you'd use the bind function and what you want it to do? I don't quite understand what you mean with "obj1.value = obj2 and vice versa". It's possible that it could be written as a normal Python function.

jbap

bind(obj1, obj2)
print obj1.value #prints obj2
print obj2.value #prints obj1

Syntax would be:

bind(object1, object2)
jbap

I tried writing a module that defined the functions. This way, you pass a txt file with changed Python script through the module, and it would convert the changed syntax to normal syntax. Then exec it.
Am I on the right path? I aim overall to create a Python split-off language.

dgelessus
def bind(a, b):
    a.value = b
    b.value = a

Or am I missing something?

Webmaster4o

You're basically, as I understand it, talking about writing your own language, but still interpreting it with the Python interpreter. Either your language would have to manually parse the input string to 'translate' it to Python, or you'd have to write your own language. You can't merely reassign variables and constants to create a whole new language.

In any case, this isn't really a relevant Pythonista question, why don't you ask it on stackoverflow?

jbap

I figured that manually parsing the language through Pythonista would be the best way to go. I wanted to use the custom modules too.

dgelessus

If you want to write your own parser from the ground up (instead of using parts of Python's parser), then you should look into the pyparsing and ply modules. As far as I know, pyparsing is included with Pythonista. ply isn't, but it's a pure Python module, so you can easily install it with stash or by hand.

jbap

Neither is included

dgelessus

@jbap Are you sure?

>>> import pyparsing
>>> pyparsing
<module 'pyparsing' from '/var/mobile/Containers/Bundle/Application/E4982298-24E8-43A9-BE41-1B030744FB63/Pythonista.app/Frameworks/PythonistaKit.framework/pylib/site-packages/pyparsing.py'>

pyparsing.py is located inside PythonistaKit.framework, so it's not something that I had to install by hand.

stash has used pyparsing for a long time too, even before the 2.0 release, so it can't be a very recent addition.

(The documentation for pyparsing isn't included with Pythonista though, aside from docstrings that you can view with help(pyparsing).)