How can you rename functions in python, like renaming print to something like say?
Things like little changes in python's code that you could potentially make into a module (for something like an addon pack).
I am not sure why you would want to rename print but this is how I would do it.
For python 3.X:
myvar = "Hello World"
say = print
say (myvar)
my example for Python 3.X does not seam to be viable for Python 2.X unless anyone else knows a way similar to my example. Otherwise here is way you can do for Python 2.X
myvar = "Hello World"
def printFun(stuff):
print(stuff)
say = printFun
say (myvar) # note that like python 3 you must put this in ()
Anytime you want to "rename" a function all you need to do is assign that function to a variable and then use that variable as the function.
Edit: On a related note you can also import the python 3 function to python 2:
# this is good to use in 2.X to help future proof your code.
# for at least the print statement
from __future__ import print_function
myvar = 'Hello World'
say = print
say (myvar)
Related
I am trying to create functions dynamically on the fly or to create functions programmatically in python and am getting stuck at this.
def test(a,b):
print(a)
#Result:
def test(a,b,c):
print(a)
print(b,c)
I am trying it with AST module and failing to understand the AST syntax for function. I understand that a function details can be fetched using functionname.__code__.xxx. But I will be unable to make changes since it is readonly. Here is what I am trying:
I tried getting the AST dump of the above function and it didnt work.
Trying to get the string version of function definition (couldnt find reference)
I have also tried the below but feel that it may be an issue somewhere like when there is a re-assignation which makes it local:
def tests(a,b):
print(a,b)
def mytest(c):
print(a,b,c)
return mytest
def tests(a,b):
print(a,b)
def mytest(c):
print(a,b,c)
a = 10 # this will become local variable
return mytest
I am on python 3.x
Any help or any other easier way?
I would like to invoke the following python script in C :
#!/usr/bin/python2.7
import parser
def evaluate(text):
code = parser.expr(text).compile()
return eval(code)
as explained in the following page https://docs.python.org/2/extending/embedding.html, i can call this script from C using the pwd(path) of the file.
However, i would like to know if it's possible to not load the script by calling python on a C string directly, defining the script.
For example, i would like to let's say i put :
#define PYTHON_SCRIPT ((char*)(\
import parser\
\
def evaluate(text):\
code = parser.expr(text).compile()\
return eval(code)\
))
is it possible to call the python interpreter directly on that string?
Indeed, knowing that i need to pass text as a variable, i can't use this Pyrun_SimpleString function, and i was not able to find something to answer this question.
As mentioned in the comment there is no Pyrun_SimpleString. How to execute Python functions from C is covered here. One way to do it:
Compile your script using Py_CompileString
Create a dictionary for globals/locals.
Extract the function from your globals dict by using PyDict_GetItemString(name)
Build your arguments tuple with PyArg_ParseTuple
Execute your function object by using PyObject_CallFunction.
Take a look at Weave, it allows you to include C code directly in Python code.
In python everything is an object and you can pass it around easily.
So I can do :
>> def b():
....print "b"
>> a = b
>> a()
b
But if I do
a = print
I get SyntaxError . Why so ?
In Python 2.x, print is a statement not a function. In 2.6+ you can enable it to be a function within a given module using from __future__ import print_function. In Python 3.x it is a function that can be passed around.
In python2, print is a statement. If you do from __future__ import print_function, you can do as you described. In python3, what you tried works without any imports, since print was made a function.
This is covered in PEP3105
The other answers are correct. print is a statement, not a function in python2.x. What you have will work on python3. The only thing that I have to add is that if you want something that will work on python2 and python3, you can pass around sys.stdout.write. This doesn't write a newline (unlike print) -- it acts like any other file object.
print is not a function in pre 3.x python. It doesn't even look like one, you don't need to call it by (params)
Environment: python 2.x
If print is a built-in function, why does it not behave like other functions ? What is so special about print ?
-----------start session--------------
>>> ord 'a'
Exception : invalid syntax
>>> ord('a')
97
>>> print 'a'
a
>>> print('a')
a
>>> ord
<built-in function ord>
>>> print
-----------finish session--------------
The short answer is that in Python 2, print is not a function but a statement.
In all versions of Python, almost everything is an object. All objects have a type. We can discover an object's type by applying the type function to the object.
Using the interpreter we can see that the builtin functions sum and ord are exactly that in Python's type system:
>>> type(sum)
<type 'builtin_function_or_method'>
>>> type(ord)
<type 'builtin_function_or_method'>
But the following expression is not even valid Python:
>>> type(print)
SyntaxError: invalid syntax
This is because the name print itself is a keyword, like if or return. Keywords are not objects.
The more complete answer is that print can be either a statement or a function depending on the context.
In Python 3, print is no longer a statement but a function.
In Python 2, you can replace the print statement in a module with the equivalent of Python 3's print function by including this statement at the top of the module:
from __future__ import print_function
This special import is available only in Python 2.6 and above.
Refer to the documentation links in my answer for a more complete explanation.
print in Python versions below 3, is not a function. There's a separate print statement which is part of the language grammar. print is not an identifier. It's a keyword.
The deal is that print is built-in function only starting from python 3 branch. Looks like you are using python2.
Check out:
print "foo"; # Works in python2, not in python3
print("foo"); # Works in python3
print is more treated like a keyword than a function in python. The parser "knows" the special syntax of print (no parenthesis around the argument) and how to deal with it. I think the Python creator wanted to keep the syntax simple by doing so. As maverik already mentioned, in python3 print is being called like any other function and a syntx error is being thrown if you do it the old way.
Groovy has a concept of GStrings. I can write code like this:
def greeting = 'Hello World'
println """This is my first program ${greeting}"""
I can access the value of a variable from within the String.
How can I do this in Python?
--
Thanks
In Python, you have to explicitely pass a dictionary of possible variables, you cannot access arbitrary "outside" variables from within a string. But, you can use the locals() function that returns a dictionary with all variables of the local scope.
For the actual replacement, there are many ways to do it (how unpythonic!):
greeting = "Hello World"
# Use this in versions prior to 2.6:
print("My first programm; %(greeting)s" % locals())
# Since Python 2.6, the recommended example is:
print("My first program; {greeting}".format(**locals()))
# Works in 2.x and 3.x:
from string import Template
print(Template("My first programm; $greeting").substitute(locals()))
d = {'greeting': 'Hello World'}
print "This is my first program %(greeting)s" % d
You can't exactly...
I think the closest you can really get is using standard %-based substitution, e.g:
greeting = "Hello World"
print "This is my first program %s" % greeting
Having said that, there are some fancy new classes as of Python 2.6 which can do this in different ways: check out the string documentation for 2.6, specifically from section 8.1.2 onwards to find out more.
If your trying to do templating you might want to look into Cheetah. It lets you do exactly what your talking about, same syntax and all.
http://www.cheetahtemplate.org/
In Python 2.6+ you can do:
"My name is {0}".format('Fred')
Check out PEP 3101.