When you import a module, python protects the namespace by importing all objects in that module as module.objectname
instead of objectname
. import module.objectname as objectname
will import the object as its original name in the module, but writing out every object in this manner would be tedious for a large module. What is the most pythonic way to import all objects in a module as their name within the module?
The * symbol used with the from import statement is used to import all the names from a module to a current namespace. The use of * has its advantages and disadvantages.
So you will need to create a list of strings of everything in your package and then do a "from packageName import *" to import everything in this module so when you import this elsewhere, all those are also imported within this namespace.
Answer. Python provides at least three different ways to import modules. You can use the import statement, the from statement, or the builtin __import__ function.
This would import everything from modules as their name:
from module import *
But it's not really good practice. Import only what is really needed and use PEP8 tests for your code.
You only need to use this form
import module.objectname as objectname
If you wish to alias the objectname to a different name
Usually you say
from module import objectname, objectname2, objectname3
There is no "Pythonic" way to import all the objects as from module import *
is discouraged (causes fragile code) so can hardly be called Pythonic
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With