Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most pythonic way to import all objects in a module as their name in the module

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?

like image 707
Michael Avatar asked Dec 10 '13 01:12

Michael


People also ask

Which symbol is used to import all objects of a 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.

How do I import everything into Python?

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.

How many ways can you import objects from a module?

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.


2 Answers

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.

like image 131
aorcsik Avatar answered Nov 10 '22 03:11

aorcsik


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

like image 30
John La Rooy Avatar answered Nov 10 '22 01:11

John La Rooy