Eli Duenisch
Eli Duenisch

Reputation: 526

Python import to handle imports

I tried to write a script to handle my imports in Python (I want to avoid doing it via setting an environment variable etc.). The script 'imports.py' looks like this:

import re
import os
...

After starting python in bash I import the script by:

import imports

Python does not import anything and there is no error message. Any idea why this happens?

Best regards, Eli

Upvotes: 2

Views: 168

Answers (3)

hamza
hamza

Reputation: 2824

When you import your imports module, you still have to call each import within your imports module whenever you try to access it.

For example, let's assume you have imported the re module which contains somefunction in your imports:

Wrong:

import imports
Var = imports.somefunction()

Right:

import imports 
Var = imports.re.somefunction()

However if you are trying to avoid calling the re just to you use somefunction then you should update your imports module

Example: This is what you should do in your imports module

import re
def Myfunction():
    V = somefunction()
    return V

This way you can call Myfunction directly:

import imports
Var = imports.Myfunction()

right, and it produce the same thing as

Var = imports.re.somefunction()

Hope this helps.

Upvotes: 1

Kos
Kos

Reputation: 72279

You could use:

from imports import *

This will bring all the variables from the module imports into your current namespace.

In your case: the variables will be these which refer to the imported modules, so that will work as you'd want it to.

(It will make your code less clear too; is it that much work to import these modules whenever you need them? People do that.)

Upvotes: 0

mata
mata

Reputation: 69052

Now you have imported imports, which imports os, re, ...

That doesn't mean you can access these modules directly in your __main__, but that you can access them as

imports.os
imports.re
...

Upvotes: 0

Related Questions