Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python custom module name not defined

I have a custom package called 'package' and a custom module in that package called 'module' which has a function returning 'test' when called. When I import my package if I do:

from package import module

Everything works fine but if I do:

from package import *

Or

import package

Then when trying to use the 'module' module it comes up with an error name 'module' is not defined. Why is it not importing the module when I use import * or when I import the package?

The code in the module I am trying to call is this:

def printTest():
    return("Test")

The code in the file calling the module is this:

import package

print(module.printTest())
like image 752
BSmith156 Avatar asked Dec 21 '16 21:12

BSmith156


1 Answers

This is a surprisingly common issue and this question was still without an proper answer, so here we go.

Let's suppose we have a module only with functions inside, say:

  • file app/foo.py:

      def a():
          print('Hello from foo.a')
    
      def b():
          print('Hello from foo.b')
    

I would genuinely expect this to work (but it DOESN'T):

  • file app/bar.py:

      import app.foo
    
      # These will not work!
      foo.a()
      foo.b()
    

It turns out that you have to import each element explicitly or give app.foo a name:

  • Import everything (usually considered a bad practice):

      from app.foo import *
    
      # Both will work fine
      a()
      b()
    
  • Import only what you want:

      from app.foo import b
    
      # This will work
      b()
    
      # But this will not
      a()
    
  • Give app.foo a (nice) name:

      import app.foo as baz
    
      # Both will work as expected
      baz.a()
      baz.b()
    

Even if the examples above use only functions, it works exactly the same for everything declared at the top most scope of the module, like classes or variables.

Hope it helps!

like image 135
Victor Schröder Avatar answered Oct 13 '22 20:10

Victor Schröder