4

I am currently doing a python tutorial, but they use IDLE, and I opted to use the interpreter on terminal. So I had to find out how to import a module I created. At first I tried

import my_file

then I tried calling the function inside the module by itself, and it failed. I looked around and doing

my_file.function

works. I am very confused why this needs to be done if it was imported. Also, is there a way around it so that I can just call the function? Can anyone point me in the right direction. Thanks in advance.

Andy
  • 10,553
  • 21
  • 75
  • 125
  • I posted an answer in order to try and put together some of the information in the comments. [Here](http://effbot.org/zone/import-confusion.htm)'s a good article that also summarizes python imports. – Casey Kuball Apr 26 '12 at 21:58

5 Answers5

8

If you wanted to use my_file.function by just calling function, try using the from keyword.

Instead of import my_file try from my_file import *.

You can also do this to only import parts of a module like so : from my_file import function1, function2, class1

To avoid clashes in names, you can import things with a different name: from my_file import function as awesomePythonFunction

EDIT: Be careful with this, if you import two modules (myfile, myfile2) that both have the same function inside, function will will point to the function in whatever module you imported last. This could make interesting things happen if you are unaware of it.

Owen Johnson
  • 2,416
  • 2
  • 19
  • 23
  • 5
    Just keep in mind that doing a `from .. import *` is [not recommended](http://stackoverflow.com/q/2386714/936083). It's better to explicitly name what you're importing, or access it from the module name. – Casey Kuball Apr 26 '12 at 21:17
  • I really appreciate your response! Exactly what I wanted. And @Darthfett I also appreciate your input on that as well I will keep that in mind as I continue learning python. But I am curious, why is import my_file not doing what from my_file import * does?? – Andy Apr 26 '12 at 21:20
  • `import my_file` brings `my_file` itself into the current namespace, where `from my_file import *` brings everything from `my_file` into the current namespace—very messy. By the way, since Owen's answer solved your problem, could you accept it? – Mattie Apr 26 '12 at 21:23
  • 2
    You can also rename the module you're importing to something shorter like this: `import my_file as mf`. Then it's `mf.function` instead, which is nice and short. This is a common idiom when using libraries like pyplot (`import matplotlib.pyplot as plt`) and numpy (`import numpy as np`). – Lauritz V. Thaulow Apr 26 '12 at 21:24
  • 1
    I would read up on [python modules](http://docs.python.org/tutorial/modules.html). It does several things: 1. Forces you to refer to it by name, for easier maintainability (you know where every name comes from in the file). 2. It does not require for all names to be defined at the time of import. This can be useful to avoid circular references. 3. Under that python modules link, there is a way for a module to define special treatment for `from ... import *`. – Casey Kuball Apr 26 '12 at 21:25
5

This is a central concept to python. It uses namespaces (see the last line of import this). The idea is that with thousands of people writing many different modules, the likelihood of a name collision is reasonably high. For example, I write module foo which provides function baz and Joe Smith writes module bar which provides a function baz. My baz is not the same as Joe Smiths, so in order to differentiate the two, we put them in a namespace (foo and bar) so mine can be called by foo.baz() and Joe's can be called by bar.baz().

Of course, typing foo.baz() all the time gets annoying if you just want baz() and are sure that none of your other modules imported will provide any problems... That is why python provides the from foo import * syntax, or even from foo import baz to only import the function/object/constant baz (as others have already noted).

Note that things can get even more complex: Assume you have a module foo which provides function bar and baz, below are a few ways to import and then call the functions contained inside foo...

import foo                 # >>> foo.bar();foo.baz()
import foo as bar          # >>> bar.bar();bar.baz()
from foo import bar,baz    # >>> bar(); baz()  
from foo import *          # >>> bar(); baz()
from foo import bar as cow # >>> cow()  # This calls bar(), baz() is not available
...
mgilson
  • 300,191
  • 65
  • 633
  • 696
5

A basic import statement is an assignment of the module object (everything's an object in Python) to the specified name. I mean this literally: you can use an import anywhere in your program you can assign a value to a variable, because they're the same thing. Behind the scenes, Python is calling a built-in function called __import__() to do the import, then returning the result and assigning it to the variable name you provided.

import foo

means "import module foo and assign it the name foo in my namespace. This is the same as:

foo = __import__("foo")

Similarly, you can do:

import foo as f

which means "import module foo and assign it the name f in my namespace." This is the same as:

f = __import__("foo")

Since in this case, you have only a reference to the module object, referring to things contained by the module requires attribute access: foo.bar etc.

You can also do from foo import bar. This creates a variable named bar in your namespace that points to the bar function in the foo module. It's syntactic sugar for:

bar = __import__("foo").bar
kindall
  • 178,883
  • 35
  • 278
  • 309
  • Oooo ... `__import__`. You're pulling out all the stops. +1 :) – mgilson Apr 26 '12 at 22:03
  • Haha, funny comment @mgilson , but indeed a good post. Brings up an important point of which I will look into as well (meaning __import__). Thank you very much. – Andy Apr 26 '12 at 22:23
  • When you get deeper into Python you'll discover that a lot of language features you first took as obscure magic are just nicer "wrappers" for straightforward things like (in this case) calling a function and binding a name to the result. – kindall Apr 26 '12 at 22:43
1

I don't really understand your confusion. You've imported the name my_file, not anything underneath it, so that's how you reference it.

If you want to import functions or classes inside a module directly, you can use:

from my_file import function
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Yes, exactly. Why is my confusion confusing? If you are importing the file, why would everything in it not be directly accessible. Putting it another way, Java, C, etc. – Andy Apr 26 '12 at 21:17
  • 1
    Think of it this way, by importing it, you are making the various functions available form the module you imported, but you use the .function_name to specify which function you would like to use form the file you imported. Does that help? – Levon Apr 26 '12 at 21:20
  • @Levon Yes, it makes sense now. Thank you very much for that. Its not the usual way to do this, at least coming from other languages. – Andy Apr 26 '12 at 21:22
  • @Andy - Java works the same way as Python AFAIK, and C's `#include` is just about the worst possible approach. You might want to look up the concept of a ["namespace"](http://en.wikipedia.org/wiki/Namespace_(computer_science)) too. – detly Apr 26 '12 at 21:25
  • Thanks for the advice @detly I guess I have been looking at it all wrong. I just got comfortable with the java way of doing things. – Andy Apr 26 '12 at 22:24
0

I'm going to incorporate many of the comments already posted.

To have access to function without having to refer to the module my_file, you can do one of the following:

from my_file import function

or

from my_file import *

For a more in-depth description of how modules work, I would refer to the documentation on python modules.

The first is the preferred solution, and the second is not recommended for many reasons:

  • It pollutes your namespace
  • It is not a good practice for maintainability (it becomes more difficult to find where specific names reside.
  • You typically don't know exactly what is imported
  • You can't use tools such as pyflakes to statically detect errors in your code

Python imports work differently than the #includes/imports in a static language like C or Java, in that python executes the statements in a module. Thus if two modules need to import a specific name (or *) out of each other, you can run into circular referencing problems, such as an ImportError when importing a specific name, or simply not getting the expected names defined (in the case you from ... import *). When you don't request specific names, you don't run into the, risk of having circular references, as long as the name is defined by the time you actually want to use it.

The from ... import * also doesn't guarantee you get everything. As stated in the documentation on python modules, a module can defined the __all__ name, and cause from ... import * statements to miss importing all of the subpackages, except those listed by __all__.

Community
  • 1
  • 1
Casey Kuball
  • 7,717
  • 5
  • 38
  • 70