__builtin__ module in Python - python

If I have a module Test and if I need to list all the functions in them, I do this:
import Test
dir(Test)
Unless I import the module I won't be able to use the functions defined in them.
But all the functions in __builtin__ module can be used without importing. But without import __builtin__ I am not able to do a dir(__builtin__). Does that mean we use the functions without importing the entire module?
from __builtin__ import zip
Is it something like the above? But if I do del zip, I get
NameError: name 'zip' is not defined
Can anyone please explain this behavior?

As explained in the Python language docs, names in Python are resolved by first looking them up in the local scope, then in any enclosing local scope, then in the module-level scope and finally in the namespace of the built-ins. So built-ins are somehow special-cased. They are not imported in your module's scope, but if a name is not found anywhere else, Python will look it up in the scope __builtin__.
Note that you can access the contents of this scope without importing it. A portable way to do this is
import sys
print(dir(sys.modules["__builtin__"]))
In CPython, this also works
print(dir(__builtins__))
but this is considered an implementation detail and might not be available for other Python implementations or future versions.

I'm by no means knowledgeable about python, but maybe dir(__builtins__), with an "s", is what you're after?
Works for me on plain Python 3.1.

when python interpreter start, it will by default execute something like
from __builtin__ import *
which allows you to use all the functions/attributes defined inside __builtin__ module
However to use __builtin__ symbol itself, you need to do
import __builtin__
this is how import statement syntax works.

Related

Restore np.array after accidentally assigning to it [duplicate]

How do I reimport a module? I want to reimport a module after making changes to its .py file.
For Python 3.4+:
import importlib
importlib.reload(nameOfModule)
For Python < 3.4:
reload(my.module)
From the Python docs
Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter.
Don't forget the caveats of using this method:
When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem, but if the new version of a module does not define a name that was defined by the old version, the old definition is not removed.
If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.
If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.
In python 3, reload is no longer a built in function.
If you are using python 3.4+ you should use reload from the importlib library instead:
import importlib
importlib.reload(some_module)
If you are using python 3.2 or 3.3 you should:
import imp
imp.reload(module)
instead. See http://docs.python.org/3.0/library/imp.html#imp.reload
If you are using ipython, definitely consider using the autoreload extension:
%load_ext autoreload
%autoreload 2
Actually, in Python 3 the module imp is marked as DEPRECATED. Well, at least that's true for 3.4.
Instead the reload function from the importlib module should be used:
https://docs.python.org/3/library/importlib.html#importlib.reload
But be aware that this library had some API-changes with the last two minor versions.
If you want to import a specific function or class from a module, you can do this:
import importlib
import sys
importlib.reload(sys.modules['my_module'])
from my_module import my_function
Another small point: If you used the import some_module as sm syntax, then you have to re-load the module with its aliased name (sm in this example):
>>> import some_module as sm
...
>>> import importlib
>>> importlib.reload(some_module) # raises "NameError: name 'some_module' is not defined"
>>> importlib.reload(sm) # works
Although the provided answers do work for a specific module, they won't reload submodules, as noted in This answer:
If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.
However, if using the __all__ variable to define the public API, it is possible to automatically reload all publicly available modules:
# Python >= 3.5
import importlib
import types
def walk_reload(module: types.ModuleType) -> None:
if hasattr(module, "__all__"):
for submodule_name in module.__all__:
walk_reload(getattr(module, submodule_name))
importlib.reload(module)
walk_reload(my_module)
The caveats noted in the previous answer are still valid though. Notably, modifying a submodule that is not part of the public API as described by the __all__ variable won't be affected by a reload using this function. Similarly, removing an element of a submodule won't be reflected by a reload.
import sys
del sys.modules['module_name']
import module_name

Python import via exec does not work, while hardcoded import works

Inside a function, I have to import a variable (dict) from a module dynamically:
exec("from ctrl_%s import default_settings" % get_version_id(iid))
which doesnt work. When referencing this variable later, it says: UnboundLocalError: local variable 'default_settings' referenced before assignment
The variable is in the global scope of the module to import.
But:
This all works, if I hardcode this statement without exec(). The string is correctly formed, I can print it out.
Someone knows what to do?
I highly would discourage to use exec in the first place, it often does not do what you want especially if some special syntax is involved like here.
But fortunately there are some tricks:
e.g. you can import the module and use the dict or getattr:
import math
getattr(math,"sin")
math.__dict__['sin']
Edit just checked my answer and I saw you wanted to import a module ...
But there is also a trick for this:
https://docs.python.org/3/library/functions.html#__import__
Look also at this question for some examples:
How to import a module given its name as string?

print function is from which module

As a beginner, what I understood is that Python Standard Library (PSL) provides a lot of modules which provide a lot of functionalities, but still if I want to use those then I have to import the module, for example, sys, os etc. are PSL modules but still those need to be imported.
Now, I wonder if that is the case then how without importing anything I am able to use functions like print, list, len etc.? Is it that their "support is built-in into the interpreter"?
Yes. They're built-in functions (or in the case of list, a built-in class). You can explicitly import the __builtin__ module (Py2) or the builtins module (Py3) if you want qualified access to the names, but by default, those modules are searched whenever an attempt to access a global name doesn't find the name in the module globals. They're not normally needed though, per the docs:
This module is not normally accessed explicitly by most applications, but can be useful in modules that provide objects with the same name as a built-in value, but in which the built-in of that name is also needed.
The print function comes from the builtins module.
You can find its documentation here.
Here is an example session.
I first check what module print comes from,which is stored in its __module__ attribute.
Then, I import the builtins module, and checks if its print function is the same as the prefix-less print.
>>> print.__module__
'builtins'
>>> import builtins
>>> builtins.print("hello")
hello
>>> print is builtins.print
True
You should give the page on built-in functions a read
Quote:
The Python interpreter has a number of functions and types built into
it that are always available.

Having to evaluate a string to access a class from a module

I've loaded one of my modules <module my_modules.mymodule from .../my_modules/mymodule.pyc> with __import__.
Now I'm having the module saved in a variable, but I'd like to create an instance of the class mymodule. Thing is - I've gotten the module name passed as string into my script.
So I've got a variable containing the module, and I've got the module name but as string.
variable_containing_module.string_variable_with_correct_classname() doesn't work. Because it says there is no such thing in the module as "string_variable_with_correct_classname" - because it doesn't evaluate the string name. How can I do so?
Your problem is that __import__ is designed for use by the import internals, not really for direct usage. One symptom of this is that when importing a module from inside a package, the top-level package is returned rather than the module itself.
There are two ways to deal with this. The preferred way is to use importlib.import_module() instead of using __import__ directly.
If you're on an older version of Python that doesn't provide importlib, then you can create your own helper function:
import sys
def import_module(module_name):
__import__(module_name)
return sys.modules[module_name]
Also see http://bugs.python.org/issue9254

Reimport a module while interactive

How do I reimport a module? I want to reimport a module after making changes to its .py file.
For Python 3.4+:
import importlib
importlib.reload(nameOfModule)
For Python < 3.4:
reload(my.module)
From the Python docs
Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter.
Don't forget the caveats of using this method:
When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem, but if the new version of a module does not define a name that was defined by the old version, the old definition is not removed.
If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.
If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.
In python 3, reload is no longer a built in function.
If you are using python 3.4+ you should use reload from the importlib library instead:
import importlib
importlib.reload(some_module)
If you are using python 3.2 or 3.3 you should:
import imp
imp.reload(module)
instead. See http://docs.python.org/3.0/library/imp.html#imp.reload
If you are using ipython, definitely consider using the autoreload extension:
%load_ext autoreload
%autoreload 2
Actually, in Python 3 the module imp is marked as DEPRECATED. Well, at least that's true for 3.4.
Instead the reload function from the importlib module should be used:
https://docs.python.org/3/library/importlib.html#importlib.reload
But be aware that this library had some API-changes with the last two minor versions.
If you want to import a specific function or class from a module, you can do this:
import importlib
import sys
importlib.reload(sys.modules['my_module'])
from my_module import my_function
Another small point: If you used the import some_module as sm syntax, then you have to re-load the module with its aliased name (sm in this example):
>>> import some_module as sm
...
>>> import importlib
>>> importlib.reload(some_module) # raises "NameError: name 'some_module' is not defined"
>>> importlib.reload(sm) # works
Although the provided answers do work for a specific module, they won't reload submodules, as noted in This answer:
If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.
However, if using the __all__ variable to define the public API, it is possible to automatically reload all publicly available modules:
# Python >= 3.5
import importlib
import types
def walk_reload(module: types.ModuleType) -> None:
if hasattr(module, "__all__"):
for submodule_name in module.__all__:
walk_reload(getattr(module, submodule_name))
importlib.reload(module)
walk_reload(my_module)
The caveats noted in the previous answer are still valid though. Notably, modifying a submodule that is not part of the public API as described by the __all__ variable won't be affected by a reload using this function. Similarly, removing an element of a submodule won't be reflected by a reload.
import sys
del sys.modules['module_name']
import module_name

Categories