Newbie NameError problem

Discussion in 'Python' started by MartinRinehart@gmail.com, Dec 12, 2007.

  1. Guest

    I don't understand what I don't understand in the following:
    ------------------------------------------
    # reader.py - testing char-by-char marching methods

    f = open('sample_decaf.d', 'r')
    text = f.readlines()
    f.close()

    # this is C-style, 15 lines, in Python:
    end_line = len(text)
    line_ptr = 0

    while line_ptr < end_line:

    input = text[line_ptr]
    output = ''
    char_ptr = 0
    end_char = len(input)

    while char_ptr < end_char:
    output += input[char_ptr]
    char_ptr += 1

    print output,
    line_ptr += 1

    # this is Python, 7 lines:

    for line in text:
    output = ''

    for char in line:
    output += char

    print output,

    # but I need locations, so this is impure, 11-line, Python:

    line_ptr = 0
    for line in text:
    output = ''
    char_ptr = 0

    for char in line:
    output += char
    char_ptr += 1

    print output,
    line_ptr += 1

    # with a Loc object, 10 lines (not counting the Loc class):

    loc = Loc(0,0) # Name error: name 'Loc' is not defined
    for line in text:
    output = ''

    for char in line:
    output += char
    loc.nextChar()

    print output + Loc.repr(),
    loc.nextLine()

    class Loc:
    line = 0
    char = 0

    def __init__(self, l, c):
    line = l
    char = c

    def nextChar(self):
    char += 1

    def nextLine(self):
    line += 1
    char = 0

    def repr(self):
    return 'Loc: line='+str(line)+', char='+str(char)

    # end of class Loc

    # end of reader.py
     
    , Dec 12, 2007
    #1
    1. Advertising

  2. On Dec 12, 2007, at 11:26 AM, wrote:

    > I don't understand what I don't understand in the following:


    You also don't understand how to ask for help properly. Your example
    is too large, for one. You want a "minimal working example" (http://
    ironfroggy-code.blogspot.com/2007/02/minimal-working-examples-how-to-
    why-and.html) where working means it works to demonstrate the problem
    you are having. You need to actually show us what is breaking, which
    means the traceback that gives you the NameError.

    As for the problem itself, I am not going to look through all that
    code or run it myself. That is why you want minimal examples and to
    include the errors for us to read. But, if you don't know, a
    NameError means you tried to use a variable before assigning to it,
    so look for that. It could also be as simple as misspelling something.
     
    Calvin Spealman, Dec 12, 2007
    #2
    1. Advertising

  3. Paul Rudin Guest

    writes:

    > I don't understand what I don't understand in the following:


    I haven't tried to understand what your code is doing - but the
    NameError arises because you try to use Loc before its definition. Put
    the definition first and the error should go away.
     
    Paul Rudin, Dec 12, 2007
    #3
  4. Guest

    On Dec 12, 5:51 pm, Paul Rudin <> wrote:
    > writes:
    > > I don't understand what I don't understand in the following:

    >
    > I haven't tried to understand what your code is doing - but the
    > NameError arises because you try to use Loc before its definition. Put
    > the definition first and the error should go away.


    Class Loc must be placed ABOVE the code that uses it.
     
    , Dec 12, 2007
    #4
  5. a écrit :
    > I don't understand what I don't understand in the following:


    You already have the answer (hint: a Python module is sequentially
    executed when loaded by the interpreter)

    Just a couple side notes:

    > # but I need locations, so this is impure, 11-line, Python:
    >
    > line_ptr = 0
    > for line in text:
    > output = ''
    > char_ptr = 0
    >
    > for char in line:
    > output += char
    > char_ptr += 1
    >
    > print output,
    > line_ptr += 1



    Use enumerate and a for loop.

    for line_ptr, line in enumerate(text):
    for char_ptr, char in enumerate(line):
    print "char %s of line %s is %s" % (char_ptr, line_ptr, char)

    > # with a Loc object, 10 lines (not counting the Loc class):
    >
    > loc = Loc(0,0) # Name error: name 'Loc' is not defined


    Indeed. It is not yet defined at this time. Remember that in Python,
    almost everything happens at runtime.


    (snip)

    I think you're going to have a hard time if you don't read about
    Python's object model...

    > class Loc:


    Better to use new-style classes unless you have compelling reasons to
    stick with the very outdated 'classic' model.

    class Loc(object):

    > line = 0
    > char = 0


    This define two class attributes - that is, attributes that are members
    of the Loc class object (*not* Loc instances), and so are shared by all
    instances. This is probably not what you want.

    > def __init__(self, l, c):
    > line = l
    > char = c


    This defines two local variables line and char, bind them to resp. l and
    c, then returns - discarding locals of course.

    The use of 'self' is *not* optional in Python. Within the function, it's
    a reference to the current instance. If you want to define instance
    attributes, you have to set these attributes on the current instance.

    def __init__(self, line, char):
    self.line = line
    self.char = char

    > def nextChar(self):
    > char += 1


    NameError here. You want self.char

    > def nextLine(self):
    > line += 1


    NameError here. You want self.line

    > char = 0


    Local variable, discarded when exiting the function. You want self.char

    > def repr(self):
    > return 'Loc: line='+str(line)+', char='+str(char)


    NameError * 2, etc...

    Also, Python has string formatting:

    def __repr__(self):
    return "<Loc: line=%s - char=%s>" % (self.line, self.char)

    HTH
     
    Bruno Desthuilliers, Dec 12, 2007
    #5
  6. <> wrote:
    >I don't understand what I don't understand in the following:
    > [ ... ]


    You've already got an answer as to what's causing your name error.
    But that's not your only problem. It looks like you need an
    introduction to enumerate():

    for line_ptr, text in enumerate(file('sample_decaf.d')):
    for char_ptr, char in enumerate(text):
    # whatever you want to do with your chacter-by-character
    # processing with line and charater positions

    --
    \S -- -- http://www.chaos.org.uk/~sion/
    "Frankly I have no feelings towards penguins one way or the other"
    -- Arthur C. Clarke
    her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
     
    Sion Arrowsmith, Dec 12, 2007
    #6
  7. Paul Rudin Guest

    writes:

    > On Dec 12, 5:51 pm, Paul Rudin <> wrote:
    >> writes:
    >> > I don't understand what I don't understand in the following:

    >>
    >> I haven't tried to understand what your code is doing - but the
    >> NameError arises because you try to use Loc before its definition. Put
    >> the definition first and the error should go away.

    >
    > Class Loc must be placed ABOVE the code that uses it.


    Isn't that what I said?
     
    Paul Rudin, Dec 12, 2007
    #7
  8. Guest

    Thanks to all!

    I will put my class defs first (tho not without expressing my
    disappointment that this is required in a late 20th century language);
    learn about enumerate as it looks like exactly what I need and discard
    my C++/Java based object model because this is a totally other thing.

    If someone who knows both object models would comment on Python's
    model v. C++/Java's model that would be helpful.
     
    , Dec 12, 2007
    #8
  9. On Wed, 2007-12-12 at 12:48 -0800, wrote:
    > Thanks to all!
    >
    > I will put my class defs first (tho not without expressing my
    > disappointment that this is required in a late 20th century language);


    You don't have to physically *put* class definitions first in your code.
    What matters is that they get *executed* first. They following will work
    just fine:

    #######################
    def main():
    x = SomeClass()
    x.DoSomething()

    class SomeClass:
    ...

    main()
    #######################

    Expecting to use a class before it's defined is equivalent to expecting
    this to work:

    ########################
    print a
    a = "Hello World"
    ########################

    Even here in the early 21st century, we don't have clairvoyant computers
    yet.

    --
    Carsten Haese
    http://informixdb.sourceforge.net
     
    Carsten Haese, Dec 12, 2007
    #9
  10. a écrit :
    > Thanks to all!
    >
    > I will put my class defs first (tho not without expressing my
    > disappointment that this is required in a late 20th century language);


    That's because you dont get the "execution model" of Python.

    First point, remember that Python in Python everything is an object -
    including classes and functions.

    Now a Python module is a list of statements, and all these statements (I
    mean, the ones at the top-level of the module) are executed sequentially
    when the module is loaded. The def and class statements actually
    *define* corresponding names in the defining namespace - and of course
    bind the newly created function or class objects to these names. So you
    can see def and class statements as name-binding (IOW: assignement)
    operations.

    So indeed, until the def or class statement has been fully executed, the
    corresponding object doesn't exist, and can't obviously be bound to a
    name.

    Would you expect the following code to work ?

    # dumb.py
    print foo
    foo = 42

    If you understand that the class statement is to be read as a convenient
    shortcut for an operation that otherwise looks like:

    ClassName = some_call_that_creates_a_class_object(all_required_params)

    you understand why you cannot expect to use class ClassName before this
    statement has been executed.

    Now this is seldom a problem since - except perhaps for trivial scripts
    - one usually put the effective code in functions. Python is not a
    "better bash" - it's really a full-blown application programming
    language that *also* happen to be usable for scripting.

    > learn about enumerate as it looks like exactly what I need and discard
    > my C++/Java based object model because this is a totally other thing.
    >
    > If someone who knows both object models would comment on Python's
    > model v. C++/Java's model that would be helpful.


    There have been a couple posts here about Python's object model recently
    IIRC. But anyway, starting with the online tutorial, then reading the
    doc section about new-style classes should be a good start. If you have
    questions then, please post here.
     
    Bruno Desthuilliers, Dec 12, 2007
    #10
  11. Guest

    On Dec 12, 7:03 pm, Paul Rudin <> wrote:
    > writes:
    > > On Dec 12, 5:51 pm, Paul Rudin <> wrote:
    > >> writes:
    > >> > I don't understand what I don't understand in the following:

    >
    > >> I haven't tried to understand what your code is doing - but the
    > >> NameError arises because you try to use Loc before its definition. Put
    > >> the definition first and the error should go away.

    >
    > > Class Loc must be placed ABOVE the code that uses it.

    >
    > Isn't that what I said?


    I had had a few too many Coffee's, had thought the extra commenting
    would aid :)
     
    , Dec 13, 2007
    #11
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. GMTaglia

    NameError

    GMTaglia, Oct 5, 2004, in forum: Python
    Replies:
    2
    Views:
    2,739
    GMTaglia
    Oct 5, 2004
  2. seancron

    nameerror upon calling function

    seancron, Sep 1, 2007, in forum: Python
    Replies:
    1
    Views:
    352
    Arnaud Delobelle
    Sep 1, 2007
  3. jolly
    Replies:
    2
    Views:
    574
    jolly
    Dec 19, 2007
  4. Replies:
    3
    Views:
    598
    Dan Bishop
    Mar 22, 2008
  5. Mustafa Cayci

    Newbie -> NameError: getopt

    Mustafa Cayci, Apr 4, 2011, in forum: Python
    Replies:
    1
    Views:
    541
    R. Tyler Croy
    Apr 4, 2011
Loading...

Share This Page