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)
This may be an OS problem since I did saw on youtube videos where people were demoing how to use decorators in python in a Linux based system.
So I'm trying to play with decorators. In its usual form, you create a function of it first, and then you use the special keywoard "#func_name" in order to pass the next line of arguments into the function. This particular method of utilizing decorator is not working. I've tried in PyDev (Eclipse) and it is just reading as syntax error. I also tried the interactive Python.
Currently running windows OS 7 Python Version 2.78
Here are more specific examples
def c(n):
def d():
return "Hello world",n
return d()
c=c("of Python")
print c
output: ('Hello world', 'of Python')
#c
"of Python"
output: "of Python?"
^
SyntaxError: invalid syntax
Created a working version based on Jon's answer
def c(n):
def d():
return "Hello world" + n()
return d
#c
def decorate_this_func():
return " python"
print decorate_this_func()
then you use the special keywoard "#func_name" in order to pass the
next line of arguments into the function
That's not how decorators work. You can pass arguments to a decorator like this
#c("of python")
def decorate_this_func():
pass
But for that to work you need to tweak your decorator function a bit.
Give this a read https://stackoverflow.com/a/1594484/1843331
It's an excellent explanation of decorators, how they work, how to use arguments with decorators and much more.
In Python 2 I used:
print "a=%d,b=%d" % (f(x,n),g(x,n))
I've tried:
print("a=%d,b=%d") % (f(x,n),g(x,n))
In Python2, print was a keyword which introduced a statement:
print "Hi"
In Python3, print is a function which may be invoked:
print ("Hi")
In both versions, % is an operator which requires a string on the left-hand side and a value or a tuple of values or a mapping object (like dict) on the right-hand side.
So, your line ought to look like this:
print("a=%d,b=%d" % (f(x,n),g(x,n)))
Also, the recommendation for Python3 and newer is to use {}-style formatting instead of %-style formatting:
print('a={:d}, b={:d}'.format(f(x,n),g(x,n)))
Python 3.6 introduces yet another string-formatting paradigm: f-strings.
print(f'a={f(x,n):d}, b={g(x,n):d}')
The most recommended way to do is to use format method. Read more about it here
a, b = 1, 2
print("a={0},b={1}".format(a, b))
Simple printf() function from O'Reilly's Python Cookbook.
import sys
def printf(format, *args):
sys.stdout.write(format % args)
Example output:
i = 7
pi = 3.14159265359
printf("hi there, i=%d, pi=%.2f\n", i, pi)
# hi there, i=7, pi=3.14
Python 3.6 introduced f-strings for inline interpolation. What's even nicer is it extended the syntax to also allow format specifiers with interpolation. Something I've been working on while I googled this (and came across this old question!):
print(f'{account:40s} ({ratio:3.2f}) -> AUD {splitAmount}')
PEP 498 has the details. And... it sorted my pet peeve with format specifiers in other langs -- allows for specifiers that themselves can be expressions! Yay! See: Format Specifiers.
Simple Example:
print("foo %d, bar %d" % (1,2))
A simpler one.
def printf(format, *values):
print(format % values )
Then:
printf("Hello, this is my name %s and my age %d", "Martin", 20)
print("Name={}, balance={}".format(var-name, var-balance))
Because your % is outside the print(...) parentheses, you're trying to insert your variables into the result of your print call. print(...) returns None, so this won't work, and there's also the small matter of you already having printed your template by this time and time travel being prohibited by the laws of the universe we inhabit.
The whole thing you want to print, including the % and its operand, needs to be inside your print(...) call, so that the string can be built before it is printed.
print( "a=%d,b=%d" % (f(x,n), g(x,n)) )
I have added a few extra spaces to make it clearer (though they are not necessary and generally not considered good style).
You can literally use printf in Python through the ctypes module (or even your own C extension module).
On Linux, you should be able to do
import ctypes
libc = ctypes.cdll.LoadLibrary("libc.so.6")
printf = libc.printf
printf(b"Integer: %d\n"
b"String : %s\n"
b"Double : %f (%%f style)\n"
b"Double : %g (%%g style)\n",
42, b"some string", ctypes.c_double(3.20), ctypes.c_double(3.20))
On Windows, the equivalent would have
libc = ctypes.cdll.msvcrt
printf = libc.printf
As stated in the documentation:
None, integers, bytes objects and (unicode) strings are the only native Python objects that can directly be used as parameters in these function calls. None is passed as a C NULL pointer, bytes objects and strings are passed as pointer to the memory block that contains their data (char* or wchar_t*). Python integers are passed as the platforms default C int type, their value is masked to fit into the C type.
This explains why I wrapped the Python float objects using ctypes.c_double (FYI, a Python float is typically a double in C).
Output
Integer: 42
String : some string
Double : 3.200000 (%f style)
Double : 3.2 (%g style)
print("{:.4f} #\n".format(2))
Formatting helpful in situations like these.
You can refer to further details in the link below.
Python Formatting
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.