noob import question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Brian Blazer

    noob import question

    OK, I have a very simple class here:

    class Student:
    """Defines the student class"""

    def __init__(self, lName, fName, mi):
    self.lName = lName
    self.fName = fName
    self.mi = mi

    Then I have a small script that I am using as a test:

    from Student import *

    s1 = Student("Brian" , "Smith", "N")

    print s1.lName

    This works as expected. However, if I change the import statement to:
    import Student

    I get an error:
    TypeError: 'module' object is not callable

    I have tried to look up what is going on, but I have not found
    anything. Would it be possible for someone to take a minute and give
    an explanation?

    Thank you - your time is appreciated.

    Brian
    brian@brianandk ate.com




  • Iain King

    #2
    Re: noob import question


    Brian Blazer wrote:[color=blue]
    > OK, I have a very simple class here:
    >
    > class Student:
    > """Defines the student class"""
    >
    > def __init__(self, lName, fName, mi):
    > self.lName = lName
    > self.fName = fName
    > self.mi = mi
    >
    > Then I have a small script that I am using as a test:
    >
    > from Student import *
    >
    > s1 = Student("Brian" , "Smith", "N")
    >
    > print s1.lName
    >
    > This works as expected. However, if I change the import statement to:
    > import Student
    >
    > I get an error:
    > TypeError: 'module' object is not callable
    >
    > I have tried to look up what is going on, but I have not found
    > anything. Would it be possible for someone to take a minute and give
    > an explanation?
    >[/color]

    I take it you are getting the error on the line
    s1 = Student("Brian" , "Smith", "N")

    This is because when you use 'import Student', it loads the file
    Student.py into a namespace called Student (unlike the 'from'
    statement, which loads it into the main namespace). to access anything
    from your Student module, prepend with Student. , so your line becomes:
    s1 = Student.Student ("Brian", "Smith", "N")

    Iain[color=blue]
    > Thank you - your time is appreciated.
    >
    > Brian
    > brian@brianandk ate.com[/color]

    Comment

    • Diez B. Roggisch

      #3
      Re: noob import question

      > I have tried to look up what is going on, but I have not found[color=blue]
      > anything. Would it be possible for someone to take a minute and give
      > an explanation?[/color]

      The

      from <module> import <*|nameslist>

      syntax imports some or all names found in <module> into the current modules
      namespace. Thus you can access your class.

      But if you do

      import <module>

      you only get <module> in your current namespace. So you need to access
      anything inside <module> by prefixing the expression. In your case, it is

      Student.Student

      If you only write Student, that in fact is the MODULE Student, which
      explains the error message.

      Now while this sounds as if the from <module> import * syntax is the way to
      go, you should refrain from that until you really know what you are doing
      (and you currently _don't_ know), as this can introduce subtle and
      difficult to debug bugs. If you don't want to write long module-names, you
      can alias them:

      import <moduel-with-long-name> as <shortname>


      And it seems as if you have some JAVA-background, putting one class in one
      file called the same as the class. Don't do that, it's a stupid restriction
      in JAVA and should be avoided in PYTHON.

      Diez

      Comment

      • Brian Blazer

        #4
        Re: noob import question

        Thank you for your responses. I had a feeling is had something to do
        with a namespace issue but I wasn't sure.

        You are right, I do come from a Java background. If it is poor form
        to name your class file the same as your class, can I ask what the
        standard is?

        Thanks again,
        Brian

        On May 19, 2006, at 8:33 AM, Diez B. Roggisch wrote:
        [color=blue][color=green]
        >> I have tried to look up what is going on, but I have not found
        >> anything. Would it be possible for someone to take a minute and give
        >> an explanation?[/color]
        >
        > The
        >
        > from <module> import <*|nameslist>
        >
        > syntax imports some or all names found in <module> into the current
        > modules
        > namespace. Thus you can access your class.
        >
        > But if you do
        >
        > import <module>
        >
        > you only get <module> in your current namespace. So you need to access
        > anything inside <module> by prefixing the expression. In your case,
        > it is
        >
        > Student.Student
        >
        > If you only write Student, that in fact is the MODULE Student, which
        > explains the error message.
        >
        > Now while this sounds as if the from <module> import * syntax is
        > the way to
        > go, you should refrain from that until you really know what you are
        > doing
        > (and you currently _don't_ know), as this can introduce subtle and
        > difficult to debug bugs. If you don't want to write long module-
        > names, you
        > can alias them:
        >
        > import <moduel-with-long-name> as <shortname>
        >
        >
        > And it seems as if you have some JAVA-background, putting one class
        > in one
        > file called the same as the class. Don't do that, it's a stupid
        > restriction
        > in JAVA and should be avoided in PYTHON.
        >
        > Diez
        > --
        > http://mail.python.org/mailman/listinfo/python-list[/color]

        Comment

        • Diez B. Roggisch

          #5
          Re: noob import question

          Brian Blazer wrote:
          [color=blue]
          > Thank you for your responses. I had a feeling is had something to do
          > with a namespace issue but I wasn't sure.
          >
          > You are right, I do come from a Java background. If it is poor form
          > to name your class file the same as your class, can I ask what the
          > standard is?[/color]

          Consider python modules what packages are in JAVA - aggregations of related
          classes. Only if your module grows to an unmanagable size, split it up into
          two modules.

          Diez

          Comment

          • PA

            #6
            Re: noob import question


            On May 19, 2006, at 15:33, Diez B. Roggisch wrote:
            [color=blue]
            > And it seems as if you have some JAVA-background, putting one class in
            > one
            > file called the same as the class. Don't do that, it's a stupid
            > restriction
            > in JAVA and should be avoided in PYTHON.[/color]

            Restrictive or not, what's so fundamentally devious in putting a class
            declaration in a separate file whose name is that of the declared class
            (class Queue -> Queue.py)?

            Sounds like a handy way of organizing your code, no?

            Cheers

            --
            PA, Onnay Equitursay


            Comment

            • Fredrik Lundh

              #7
              Re: noob import question

              "PA" <petite.abeille @gmail.com> wrote:
              [color=blue]
              > Restrictive or not, what's so fundamentally devious in putting a class
              > declaration in a separate file whose name is that of the declared class
              > (class Queue -> Queue.py)?[/color]

              nothing.
              [color=blue]
              > Sounds like a handy way of organizing your code, no?[/color]

              sure, if you prefer to do things that way.

              the Python style guide (PEP 8) used to recommend naming a module that con-
              tains only one class (plus support factories and other functions) after the class,
              but now recommends using other names for the module, to avoid confusion.

              for some reason, some people seem to treat the latest edition of each PEP as
              a divine truth, and all earlier editions as works of the devil. I guess they reset
              their brain before each svn update.

              </F>



              Comment

              • bruno at modulix

                #8
                Re: noob import question

                Brian Blazer wrote:[color=blue]
                > OK, I have a very simple class here:
                >
                > class Student:[/color]

                class Student(object) :
                [color=blue]
                > """Defines the student class"""
                >
                > def __init__(self, lName, fName, mi):
                > self.lName = lName
                > self.fName = fName
                > self.mi = mi[/color]

                Do yourself a favour: use meaningful names.
                [color=blue]
                > Then I have a small script that I am using as a test:
                >
                > from Student import *[/color]

                So your module is named Student.py ? The common convention is to use
                all_lower for modules, and CapNames for classes. BTW, unlike Java, the
                common use is to group closely related classes and functions in a same
                module.
                [color=blue]
                > s1 = Student("Brian" , "Smith", "N")
                >
                > print s1.lName
                >
                > This works as expected. However, if I change the import statement to:
                > import Student
                >
                > I get an error:
                > TypeError: 'module' object is not callable[/color]

                Of course. And that's one for the reason for naming modules all_lower
                and classes CapNames.

                With
                from Student import *

                you import all the names (well... not all, read the doc about this)
                defined in the module Student directly in the current namespace. So,
                since the module Student contains the class Student, in this current
                namespace, the name Student refers to the class Student.

                With
                import Student

                you import the module name Student in the current namespace. You can
                then refer to names defined in module Student with the qualified name
                module.name. So here, to refer to the class Student, you need to use the
                qualified name Student.Student .

                You wouldn't have such a confusion if your module was named students !-)

                [color=blue]
                > I have tried to look up what is going on, but I have not found
                > anything.[/color]

                you could have done something like this:

                import Student
                print dir()
                print dir(Student)
                print type(Student)
                del Student
                from Student import *
                print dir()
                print dir(Student)
                print type(Student)


                Also, reading the doc migh help:
                The official home of the Python Programming Language


                HTH
                --
                bruno desthuilliers
                python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
                p in 'onurb@xiludom. gro'.split('@')])"

                Comment

                • bruno at modulix

                  #9
                  Re: [OT] noob import question

                  Brian Blazer wrote:
                  <ot>
                  please, dont top-post, and edit out irrelevant material
                  </ot>
                  [color=blue]
                  > You are right, I do come from a Java background.[/color]

                  Then you may want to read this:


                  HTH
                  --
                  bruno desthuilliers
                  python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
                  p in 'onurb@xiludom. gro'.split('@')])"

                  Comment

                  • bruno at modulix

                    #10
                    Re: noob import question

                    PA wrote:[color=blue]
                    >
                    > On May 19, 2006, at 15:33, Diez B. Roggisch wrote:
                    >[color=green]
                    >> And it seems as if you have some JAVA-background, putting one class in
                    >> one
                    >> file called the same as the class. Don't do that, it's a stupid
                    >> restriction
                    >> in JAVA and should be avoided in PYTHON.[/color]
                    >
                    > Restrictive or not, what's so fundamentally devious in putting a class
                    > declaration in a separate file whose name is that of the declared class
                    > (class Queue -> Queue.py)?
                    >
                    > Sounds like a handy way of organizing your code, no?
                    >[/color]

                    Not in Python. Python classes tend to be smaller than Java classes.
                    Also, Python, while fully OO, is not anal-retentive about putting
                    everything in classes - functions are fine too. Would you advocate
                    putting each function in its own file ?-) And finally, with Python's
                    file<->module equivalence, grouping related classes and functions in a
                    same module greatly simplify imports.

                    wrt/ naming, having the module named after the class (your example)
                    leads to confusions like the one experimented by the OP. FWIW, Zope2
                    uses this convention, and I found this confusing too.


                    --
                    bruno desthuilliers
                    python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
                    p in 'onurb@xiludom. gro'.split('@')])"

                    Comment

                    • Ben Finney

                      #11
                      Re: noob import question

                      [Please don't top-post. Please don't indiscriminatel y quote the entire
                      message you respond to.
                      <URL:http://en.wikipedia.or g/wiki/Top_posting>]

                      Brian Blazer <brian@brianand kate.com> writes:
                      [color=blue]
                      > Thank you for your responses. I had a feeling is had something to
                      > do with a namespace issue but I wasn't sure.[/color]

                      Another point to note is that 'from foo import *' is bad practice. It
                      causes a problem known as "namespace pollution", where you can't tell
                      where a particular name you're using comes from, or if you have
                      accidentally clobbered an existing name.

                      Either import the module to a single name, so you can qualify the
                      names inside that module:

                      import foo
                      import awkward_long_mo dule_name as bar
                      foo.eggs()
                      bar.beans()

                      Or, if you only need a few objects from the module, import those
                      specifically and use their names directly:

                      from foo import spam, eggs
                      eggs()
                      spam()
                      [color=blue]
                      > You are right, I do come from a Java background. If it is poor form
                      > to name your class file the same as your class, can I ask what the
                      > standard is?[/color]

                      Since we don't need to have one file per class, the convention is to
                      group your modules by coherent functionality. Place any names,
                      functions, classes, whatever that all relate to a discrete, coherent
                      set of functionality in a single module.

                      The Python coding guidelines[0] also recommend that the module be
                      named all in lower-case, but that's more about consistency within your
                      own code base.

                      [0]: <URL:http://www.python.org/dev/peps/pep-0008>

                      --
                      \ "I have a map of the United States; it's actual size. It says |
                      `\ '1 mile equals 1 mile'... Last summer, I folded it." -- Steven |
                      _o__) Wright |
                      Ben Finney

                      Comment

                      • Carl Banks

                        #12
                        Re: noob import question

                        PA wrote:[color=blue]
                        > On May 19, 2006, at 15:33, Diez B. Roggisch wrote:
                        >[color=green]
                        > > And it seems as if you have some JAVA-background, putting one class in
                        > > one
                        > > file called the same as the class. Don't do that, it's a stupid
                        > > restriction
                        > > in JAVA and should be avoided in PYTHON.[/color]
                        >
                        > Restrictive or not, what's so fundamentally devious in putting a class
                        > declaration in a separate file whose name is that of the declared class
                        > (class Queue -> Queue.py)?
                        >
                        > Sounds like a handy way of organizing your code, no?[/color]

                        Handy for a lazy programmer, maybe. Confusing for the reader, though
                        (do you mean Queue module, or Queue class? I must scroll up...). And
                        highly tacky. I recommend avoiding it. For modules, I recommend "act
                        of" words (words ending in -ing and -ion) because such words aren't
                        common identitiers. So queuing instead of Queue.

                        Unfortunately, the Python library isn't setting a good example here.
                        Too much glob.glob, time.time, socket.socket, and Queue.Queue. I hope
                        all these go away in Python 3000.


                        Carl Banks

                        Comment

                        Working...