I've come across the following code in a Python script
from pprint import pprint
why not simply import pprint?
Unless the module pprint contains a function called pprint which is being aliased as pprint (surely, this must be the definition of madness?)
It does contain a function pprint, and that is exactly what's going on. I much prefer typing pprint, not pprint.pprint, or decimal.Decimal, or datetime.datetime.now() - wouldn't you?
Yes, the syntax is from module import functions, so the first pprint is the module name and the second the function name.
Your belief is correct, but it is not "aliased" in any way. It is simply named pprint, which is no violation of any Python style guide.
Related
In Python, if I use this:
from typing import List
I have to use List[]
If I use this:
from ast import List
I have to use List()
What is the difference?
Thanks.
googled "typing" and "ast" but no luck
The difference is that one is a type-hint; it describes a value, not holds elements itself. It is also optional.
The other is a runtime-class describing the Python syntax-tree, and holds a sequential collection of Python expressions. ast.List is required if you are building/using a parser.
So I am confused as what the difference is...Here is some code to display my confusion:
>>> import collections.OrderedDict as od
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named OrderedDict
>>> from collections import OrderedDict as od
>>> od
<class 'collections.OrderedDict'>
explanation:
import collections.OrderedDict did not find the module, yet from collections import OrderedDict found it?! What is the difference between those two statements?
the class is read as collections.OrderedDict, so I don't understand why the first attempt was unable to find the module
note:
I am simply using collections as an example. I am not looking for specifically why my example acted the way it did for collections, but rather an explanation for what the different lines of code are actually requesting as far as imports go. If you would like to include an explanation on the error, feel free! Thanks!
OrderedDict is a class within the collections module. When you see things like x.y and something is being imported from it, that means that "y" in this case is actually a module.
You should read the docs about how import works: here. It's long and involved but at the same time fairly straight forward in how it looks into the different packages and modules to find what should be brought into play. Specifically, the import statement itself and import system.
PEP 221 talks about import as.
import foo.bar
is for importing a submodule bar of the module foo. This can be 'imported as'
import foo.bar as fb
An object is imported
from foo import baz
This, too, can be 'imported as'
from foo import baz as fb
collections.OrderedDict is not a submodule but an object so it can only be 'imported as' in the second way.
I know that from module import * will import all the functions in current namespace but it is a bad practice. I want to use two functions directly and use module.function when I have to use any other function from the module. What I am doing currently is:
import module
from module import func1, func2
# DO REST OF MY STUFF
Is it a good practice? Does the order of first two statements matter?
Is there a better way using which I can use these two functions directly and use rest of the functions as usual with the module's name prepended to them?
Using just import module results in very long statements with a lot of repetition if I use the same function from the given module five times in a single statement. That's what I want to avoid.
The order doesn't matter and it's not a pythonic way. When you import the module there is no need to import some of its functions separately again. If you are not sure how many of the functions you might need to use just import the module and access to the functions on demand with a simple reference.
# The only import you need
import module
# Use module.funcX when you need any of its functions
After all, if you want to use some of your functions (much) more than the others, as the cost of attribute access is greater than importing the functions separately, you better to import them as you've done.
And still, the order doesn't matter. You can do:
import module
from module import func1, func2
For more info read the documentation https://www.python.org/dev/peps/pep-0008/#imports
It is not good to do (may be opinion based):
import module
from module import func1, func2 # `func1` and `func2` are already part of module
Because you already hold a reference to module.
If I were you, I would import it in the form of import module. Since your issue is that module.func1() becomes too long. I may import the module and use as for creating a alias for the name. For example:
import module as mo
# ^ for illustration purpose. Even the name of
# your actual module wont be `module`.
# Alias should also be self-explanatory
# For example:
import database_manager as db_manager
Now I may access the functions as:
mo.func1()
mo.func2()
Edit: Based on the edit in actual question
If your are calling same function in the same line, there is possibility that your are already doing some thing wrong. It will be great if you can share what your that function does.
For example: Want to the rertun value of those functions to be passed as argument to another function? as:
test_func(mo.func1(x), mo.func1(y). mo.func1(z))
could be done as:
params_list = [x, y, z]
func_list = [mo.func1(param) for param in params_list]
test_func(*func_list)
This question already has answers here:
How can I import a module dynamically given its name as string?
(10 answers)
Closed 9 years ago.
I have a script which imports modules on-the-fly. Because modules name are changed as soon as a new version appears, it is difficult to check if the specific module name is also changed in the script. Because of this, I keep the modules name in the top of the script, in variables, like in this example:
var1 = 'moduleName1_v04'
var2 = 'moduleName2_v08'
...................
import var1
...................
import var2
...................
But if I am writing like this, I will get an error.
The question is: how to import a module using a variable like in the example? Is it possible?
Yes, you can achieve this quite easily by using importlib.import_module:
import importlib
module = importlib.import_module(var1)
Alternatively, you can use the __import__() built-in function
>>> sys = __import__("sys")
>>> sys
<module 'sys' (built-in)>
The __import__() function is the function that the interpreter uses to import modules. However, it's discouraged to use or modify this in favor of the simpler, safer import hooks, such as the first one i mentioned above. Quoting the important docs:
This function is invoked by the import statement. It can be replaced
(by importing the builtins module and assigning to
builtins.__import__) in order to change semantics of the import
statement, but doing so is strongly discouraged as it is usually
simpler to use import hooks (see PEP 302) to attain the same goals and
does not cause issues with code which assumes the default import
implementation is in use. Direct use of __import__() is also
discouraged in favor of importlib.import_module().
Hope this helps!
Yes, you can.
For example, using importlib.import_module:
>>> var1 = 'sys'
>>> import importlib
>>> mod = importlib.import_module(var1)
>>> mod
<module 'sys' (built-in)>
I am given a module as an object, and I need to import a submodule from it. Like this:
import logging
x = logging
Now I want to import logging.handlers using only x and not the name "logging". (This is because I am doing some dynamic imports and won't know the name of the module.)
How do I do this? If I do import x.handlers it fails.
Try:
__import__('%s.handlers' % x.__name__)
Note that this will return a reference to logging, which you probably won't care about. It will create x.handlers though.
You can use built-in function __import__:
http://docs.python.org/library/functions.html#import