Using class/function in another module
Question: I come from a mostly Java background, but have recently been delving into some
Python. I've been mostly getting it, but there's some syntax that seems really
weird to me. I have this project I'm working on that contains multiple files/
classes. I have one class, Mesh.py:

    
    
    class Mesh:
        def __init__(self, name):
            #dostuff
    

that I want to instantiate in another file, Main.py. I noticed two things,

  1. I have to import Mesh, which seems odd to me, since it's in my project, 
  2. To create a Mesh I have to do this:
    
        mesh = Mesh.Mesh('name')
    

which seems super awkward. Why can't I just do

    
    
    mesh = Mesh('name')
    

Am I doing something wrong here, or is this just an unavoidable part of
Python?


Answer: In Python, _every file you create is a module_ and a collection of modules can
be logically grouped as a
[package](https://docs.python.org/2/tutorial/modules.html#packages). Python is
little different than Java, which allows files in the same package to be used
without importing explicitly.

Since a module is a namespace, whenever you use an identifier in a module, it
must be defined in it, otherwise you will get a `NameError`.

When you import a module,

    
    
    import Mesh
    

Python understands that you have imported a module and all the items in it can
be referenced with the module's name. If you do

Mesh('name')

you will get an error, because only the `Mesh` module is imported in the
current module, not the `Mesh` class. That is why you have to explicitly
specify

    
    
    Mesh.Mesh('name')
    

It means that, you are telling Python that, I am referring to the `Mesh` class
in the `Mesh` module, which I imported.

But in your case, you can import only the particular class from the `Mesh`
module into the current module's namespace, like this

    
    
    from Mesh import Mesh
    

And then create an object of it, like this

    
    
    Mesh('name')
    

