Reputation: 983
Can I change the core functionality of Python, for example, rewrite it to use say("Hello world")
instead of print("Hello world")
?
If this is possible, how can this be done?
Upvotes: 1
Views: 199
Reputation: 1341
I see a few possibilities as to how to accomplish this. I've arranged them in order of how much programming is needed/how obnoxious they are:
If, as in your example, you are simply more comfortable using say()
or printf()
than print()
, then you can, as others have answered, just alias the builtin function to your own function with something like say=print
.
Let's pretend we don't trust the official implementation of print()
and we want to implement our own. A lot of the internals in Python such as stdin
are contained in the sys
library. You could, if you wanted, implement your own. I asked a question a couple years ago here that discussed how to rename the _
variable to ans
which might be illuminating to take a look at.
Ok, so gcc
doesn't require C code as input. If you use the right precompiler flags, then you could get away with evaluating #define
macros in your source code before you send it to python. Technically a valid answer, but obnoxious as heck.
Cython (python written in C) can have modules written for it in C. You could build a wrapper for printf
in C (or assembly, if you'd rather) and use that library in your python code.
Unfortunately, doing the above is not possible with all tokens. What if, in a fit of fancy, we'd like to use whilst
loops instead of while
loops? The only way to accomplish this is actually altering the functioning of python itself. Now, this isn't for the faint of heart or the new programmer. Compilers are really complicated.
Since, however, Python is open source and you can download the source code here, in theory, you could go into the compiler and manually make all the edits you want, then compile your version of python and use that. By no means would your code be portable (as essentially you'd be making a fork of python) but you could technically do it.
Or just conform to the Python standards. That works too.
Python is a living language. It's constantly being updated. The ruling body of "What gets included" is the BDFL-delegate and the Council, but anyone can write a Python Enhancement Proposal that proposes to change the language in some way. Most features in Python started out as a PEP. See PEP 0001 for more details.
Upvotes: 5