Like we have python modules in the standard library from which we can import methods and use them, is there also a module where all the built-in functions are defined?
If yes, how can I view that module?
The builtins (Python 3) or __builtin__ (Python 2) module provides access to them.
This is even useful sometimes if you rebind the name of a builtin, eg list = [1, 2, 3]. You generally shouldn't do that, but if you do you can still access the builtin list constructor as builtins.list.
On python3, import builtins or import __builtin__ for older versions
You can check any modules content with the dir function
Related
At some arbitrary place in code, this exists:
builtins.open = my_open
I cannot change that code, but it's broken. I need to make sure any open calls, including those from other builtin libraries use the original open. What I need is something like:
orig_open = get_original_method("open")
builtins.open = orig_open
In Javascript, I typically solved that issue by creating new window frame and getting the methods from there. How to do it in python?
If the issue here is simply the open function, you can always grab io.open which is an alias for it:
import io
builtins.open = io.open
I am not aware of any generic solutions to this even though I would not be surprised if one existed.
I'm not exactly sure what you want, but you can use the __builtins__ magic variable to grab the "original" open function:
>>> builtins.open = __builtins__.open
The "magic variable" is simply an alias for the builtins module:
>>> __builtins__
<module 'builtins' (built-in)>
>>>
You should note however that this is an implementation detail, and other versions of the Python interpreter might not support it. From the Python 3 documentation on the builtins module.
As an implementation detail, most modules have the name __builtins__ made available as part of their globals. [...] Since this is an implementation detail, it may not be used by alternate implementations of Python.
In Python, when we import something:
import Module
when we later want to use functions created in the module we have to say
Module.foo()
Is there any way to "attach" the module so that if I simply call
foo()
It knows that I mean to use the foo defined in Module, as long as the name does not conflict with any name in the current file?
from Module import *
This imports all symbols in Module unless overriden by __all__.
You can also explicitly import (which is better) only the symbols you actually need.
from Module import foo
It's typically preferred to use the later. Even better is to use the module as namespacing. There's nothing wrong with Module.foo() vs. foo(). Once your program gets fairly large, this will help you quite a bit with refactoring.
You can just do from module import foo, and then refer to foo() directly.
I noticed Flask was using Werkzeug to __import__ a module, and I was a little confused. I went and checked out the docs on it and saw that it seems to give you more control somehow in terms of where it looks for the module, but I'm not sure exactly how and I have zero idea how it's different from importlib.import_module.
The odd thing in the Werkzeug example is that it just says __import__(import_name), so I don't see how that's any different from just using the import statement, since it's ignoring the optional extra parameters.
Can anyone explain? I looked at other people having asked similar questions on SO previously but they weren't very clearly phrased questions and the answers didn't address this at all.
__import__ is a low-level hook function that's used to import modules; it can be used to import a module dynamically by giving the module name to import as a variable, something the import statement won't let you do.
importlib.import_module() is a wrapper around that hook* to produce a nice API for the functionality; it is a very recent addition to Python 2, and has been more fleshed out in Python 3. Codebases that use __import__ generally do so because they want to remain compatible with older Python 2 releases, e.g. anything before Python 2.7.
One side-effect of using __import__ can be that it returns the imported module and doesn't add anything to the namespace; you can import with it without having then to delete the new name if you didn't want that new name; using import somename will add somename to your namespace, but __import__('somename') instead returns the imported module, which you can then ignore. Werkzeug uses the hook for that reason in one location.
All other uses are to do with dynamic imports. Werkzeug supports Python 2.6 still so cannot use importlib.
* importlib is a Pure-Python implementation, and import_module() will use that implementation, whist __import__ will use a C-optimised version. Both versions call back to importlib._bootstrap._find_and_load() so the difference is mostly academic.
__import__(import_name), so I don't see how that's any different from
just using the import statement
Both __import__() and importlib.import_module() allow you to import a module when you have the module name as a string. You cannot write:
x = 're'
import x
or you'll get:
File "1.py", line 3, in <module>
import x ImportError: No module named x
When I was exploring a solution for the StackOverflow problem, Python Use User Defined String Class, I came with this strange python behavior.
def overriden_print(x):
print "Overriden in the past!"
from __future__ import print_function
print = overriden_print
print("Hello World!")
Output:
Overriden in the past!
Now, how can I get back the original print behavior in python interpreter?
Just delete the override:
del print
This deletes the name from the globals() dictionary, letting search fall back to the built-ins.
You can always refer directly to the built-in via the __builtin__ module as well:
import __builtin__
__builtin__.print('Printing with the original built-in')
In Python 3, the module has been renamed to builtins.
I need to test if a variable is a module or not. How to do this in the cleanest way?
I need this for initializing some dispatcher function and I want that the function can accept either dict or module as an argument.
>>> import os, types
>>> isinstance(os, types.ModuleType)
True
(It also works for your own Python modules, as well as built-in ones like os.)
I like to use this so you don't have to import the types module:
isinstance(amodule, __builtins__.__class__)