from past import print_statement - python

Is there some equivalent to from __future__ import print_function that forward-ports the print statement from python 2.x?
An answer involving some ipython magic that lets me print without need of surrounding parens during prototyping is also acceptable.

Some suggestion for IPython
%autocall
print "Hi"
Define magic with autocall on
from IPython.core.magic import register_line_magic
#register_line_magic
def p(line):
print(line)
p "Hi"
Define magic with autocall off
from IPython.core.magic import register_line_magic
#register_line_magic
def p(line):
print(eval(line))
%p "Again"
You could create a .config/ipython/profile_default/startup/autoprint.py file for you line magic functions.

Provisional answer (A solution that doesn't involve a leading / will be preferred.): IPython automatically calls an object if line begins with a /, even if it's indented:
def f():
/print 'foo'
f()
prints foo.
Edit:
IPython also has an %autocall magic function that, well, automatically calls functions, so after doing %autocall 1, typing print 3 in a cell acts like print in python 2.x (though this unfortunately doesn't work in function definitions like / does.
Also, since it's a function and not a statement, you can simply do p = print, so later /p 'foo' calls give you almost pdb-like behavior (something I was going for but that wasn't explicitly stated in the question).

Related

IPython custom tab-completion for user magic function

In IPython, it is fairly easy to provide tab-completion for user-defined object: simply define a __dir__ method that returns a list of strings to the object.
IPython also provide us with a way to define our own custom magic functions using the handy register_line_magic utility. In some ~/.ipython/profile_default/startup/magictest.py:
from IPython.core.magic import register_line_magic
#register_line_magic
def show(dataType):
# do something depending on the given `dataType` value
Now my question is: how to provide auto-completion to this magic function?
According to this email, one should look into IPython.core.interactiveshell.InteractiveShell.init_completer() for an example of magic function completers such as %reset, '%cd', etc...
However, in the same startup file as the one in which my magic function is defined, the following code didn't work:
from IPython.core.interactiveshell import InteractiveShell
def show_complete():
return ['dbs', 'databases', 'collections']
InteractiveShell._instance.set_hook(
'complete_command', show_complete, str_key='%show')
In the IPython shell, typing %show TAB triggers nothing (print statements in the function show that the function is not even called).
Could somebody point me out on some documentation or examples on how to define such user-magic command parameters completion from within the Ipython startup files?
Thanks!
You can use this:
def load_ipython_extension(ipython):
def apt_completers(self, event):
""" This should return a list of strings with possible completions.
Note that all the included strings that don't start with event.symbol
are removed, in order to not confuse readline.
"""
return ['update', 'upgrade', 'install', 'remove']
ipython.set_hook('complete_command', apt_completers, re_key = '%%apt')
%%apt is the magic keyword

Customize compile function in python?

RestrictedPython module has a restricted compiler in which you can compile code and customize some python features. For example, you can replace the builtin print function.
That's what I need to do. I need to compile some code but defining my own print function. I can't use this restricted compiler because it has a lot of restrictions I don't need at now.
Do you know any other compiler in which I can define my own print function?
Just use regular Python then; in Python 2 use:
from __future__ import print_function
or use Python 3, and print() is then a function. You can redefine that function:
from __future__ import print_function
try:
# Python 2
from __builtin__ import print as builtin_print
except ImportError:
from builtins import print as builtin_print
def print(*args, **kw):
# do something extra with *args or **kw, etc.
builtin_print(*args, **kw)
Like any other built-in function you can define your own function using the same name. In the above example I used the __builtin__ / builtins module to access the original.
If you are using exec(), you can pass in the print() function you defined as an extra name in the namespace you pass in:
exec(code_to_execute, {'print': your_print_function})
For Python 2, you do need to compile the code first to switch off the print statement and enable the print() function; use the compile() function to produce a code object to pass to the exec statement:
import __future__
code_to_execute = compile(
code_to_execute_in_string, '', 'exec',
flags=__future__.print_function.compiler_flag)
I used the __future__ module to obtain the right compiler flag.

How to make print() override work "globally"

From How to override python builtins with an import statement I obtained the following code:
from __future__ import print_function
def print(*args, **kwargs):
.
. some intervening logic
.
return __builtins__.print(*args, **kwargs)
This code works fine, but has module scope. That is, if there are print statements within this file they work as expected, going through the print() function as defined. However, importing it (from foo import *) has no effect within the module that imported it.
If I want to override the print function "globally" how is this best done. Ideally:
from MyOverrides import *
.
.
.
class foo():
.
.
def bar( self ):
print( "this is my overridden print statement" )
What am I missing about future, overrides, and print() here?
My environment is 2.6 and forward, but not 3.0.
You can't (and shouldn't) have a global override that turns on a future statement. Since future statements affect the way a Python source file is parsed and compiled, before Python can even tell that MyOverrides defines a print function, all future statements a module uses must be explicit. You can't import a future statement from another module.
The safest way to replace the print function is to explicitly use from __future__ import print_function in all your modules, then import a replacement for print from one of your modules. Don't replace __builtin__.print.
If you want to affect all output to stdout, whether by print statement or print function, anywhere at all, you can replace sys.stdout with a wrapper.
import sys
stdout = sys.stdout
class new_stdout(object):
def write(*args, **kwargs):
# do whatever
stdout.write(*args, **kwargs)
sys.stdout = new_stdout()
However, this is probably a bad idea, and it won't affect print statements or print functions that use an explicit file argument.
Another stackoverflow user provided most of the answer, but then apparently deleted it (?). Here is a working solution. Once again, I recognize this isn't necessarily a best practice, but it can be handy in certain situations.
Module MyOverrides.py:
from __future__ import print_function
import __builtin__
builtin_print = __builtin__.print
def print(*args, **kwargs):
.
.... whatever code you need here
.
return builtin_print(*args, **kwargs)
__builtin__.print = print
Module test.py:
from __future__ import print_function
from MyOverrides import *
.
.
.
As pointed out by another user, future import needs to happen in every module that intends to use future functionality.
Thanks to user #kindall who answered and then apparently withdrew the answer.

is print a function in Python?

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)

How to get module variable in function from another module?

I'd like to define a helper function that has the ability to modify a module-level variable (with known name) from surrounding context without explicitly passing it, e.g.
# mod1.py
mod_var = 1
modify_var()
# mod_var modified
print mod_var
The problem is - I can't reference variable by mod1.mod_var, because I want to use helper function across many modules (helper itself will be defined in other module); it should dynamically 'pick' mod_var from surrounding calling context/scope.
Is this possible? How to obtain this?
My use case is to enhance defining URL -> view mapping in Django. Those definitions are spread across many sub-modules that define urlpatterns module-level variable. Helper function should pick this variable from the module that calls it and modify it. Avoiding explicitly passing it as argument would be great.
Edit:
For additional solution - check this answer.
Edit2:
Wrong solution below! (left for references in comments)
Recently I've found another solution (the least magical in my opinion ;))
modify_var() function could be implemented like this:
def modify_var():
calling_module = __import__("__main__")
calling_module.mod_var = 42
Still, potential profits are arguable.
unittest module uses this technique in its main method.
It's a truly bad, horrible, and awful idea, which will lead to future maintenance nightmares. However, Python does offer "enough rope to shoot yourself in the foot", if you truly insist: introspection and metaprogramming tools which are mostly intended for debugging purposes, but can be abused to perform the ill-conceived task you so desperately crave.
For example, in evil.py:
import inspect
def modify_var():
callersframe = inspect.stack()[1][0]
callersglobals = callersframe.f_globals
if 'mod_var' not in callersglobals:
raise ValueError, 'calling module has no "mod_var"!'
callersglobals['mod_var'] += 1
now say you have two modules, a.py:
import evil
mod_var = 23
evil.modify_var()
print 'a mod_var now:', mod_var
and b.py:
import evil
mod_var = 100
evil.modify_var()
print 'b mod_var now:', mod_var
you could do:
$ python -c'import a; import b'
a mod_var now: 24
b mod_var now: 101
However, maintaining this kind of black-magic tricks in the future is going to be a headache, so I'd strongly recommend not doing things this way.
What you want to do sounds like too much magic. Pass in urlpatterns and be done with it. Explicit is better than implicit.
OK, here's the magic, but again, I recommend not using it:
import sys
def modify_var():
"""Mysteriously change `mod_var` in the caller's context."""
f = sys._getframe(1)
f.f_locals['mod_var'] += " (modified)"
mod_var = "Hello"
modify_var()
print mod_var
prints:
Hello (modified)
As a further warning against this technique: _getframe is one of those functions that other implementations of Python don't provide, and the docs include this sentence: "This function should be used for internal and specialized purposes only."
If you really want to do that then you'll need to import mod1 in either the other module or directly in the function, and then modify it off that import. But don't do that; seasoned programmers will point and laugh.

Categories