0

So I started learning Python again, and I ran into an issue. Apparently you cannot call on method that is "below (in the editor)" the code that is calling it. For instance:

for check in lines:
  if is_number(check):
    print ("number: " + check)
  else:
    print ("String!" + check)

def is_number(s):
  try:
    float(s)
    return True
  except ValueError:
    return False;

This causes an error (name is undefined), which makes sense. In C++ I know you can create a pointer for the function before you use it so the compiler knows what to look for, but how do I do this in python?

And is the method is_number a module? I hear lots of odd terminology being thrown around.

3
  • 5
    Why not just put the function above the other code? Commented Jan 27, 2014 at 20:02
  • 1
    Also see: stackoverflow.com/questions/1590608/… Commented Jan 27, 2014 at 20:08
  • Couple of reasons. I don't like the look of it, and I'm spoiled because of Java. Commented Jan 27, 2014 at 20:09

5 Answers 5

4

You should simply move the function above the place that calls it, or put the loop in a function of its own. The following works fine, because the name is_number inside check_lines is not resolved until the function is called.

def check_lines(lines):
    for check in lines:
        if is_number(check):
            print ("number: " + check)
        else:
            print ("String!" + check)

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False;

check_lines(lines)

In my Python scripts, I always define the functions at the top, then put a few lines of code calling them at the bottom. This convention makes it easy to follow the control flow, because it's not interspersed with definitions, and it also makes it easier to later reuse your script as a module, which is similar to a Java package: just look at the "script" code near the bottom and remove that to get an importable module. (Or protect it with an if __name__ == '__main__' guard.)

Sign up to request clarification or add additional context in comments.

2 Comments

I understand that, but I was wondering if there was anyway to define the methods before calling them so I didn't have to put all of the methods on top. Its honestly a personal preference more than everything, mixed with the Java way of doing things.
@opiop65: then the answer is no, unless you put it in a different module and import that (in which case the rule is still import before use). "Script" code goes to the bottom of the file, not the top.
0

Actually, Python does act like C. The difference is, in C, before anything in module is executed, the entire file is compiled. In Python, it's run.

So, the following will work, just as it will in C:

def f(x):
    return f2(x) + 1

def f2(x):
    return x*2

The function definitions just load the code - they don't check anything in there for existence. So even though f2 doesn't exist yet when f is first seen, when you actually call f, f2 does exist in the module scope and it works fine.

This doesn't work:

print f2(x) + 1

def f2(x):
    return x*2

In this case, when the module is loaded, it is being interpreted. So if it hits a print, it will execute it immediately. This can be used to your benefit, but it does cause a problem here, since we'll lookup f2 immediately and try to dereference it, and it won't exist yet.

Comments

0

You just can't. You can't access something that has not been declared/defined. Which is what happens in every programming language.

7 Comments

That's not true. Neither Haskell nor Go require declaration before use.
Sorry, I mean "defined".
I am not very versed in Java, but can you print out a variable that has not been declared and defined yet?
Yes. You also don't have to define methods before using them, which has spoiled me.
Can you call object.method()... without defining object and method? and what is the result? the big bang? :)
|
0

Writing the code into main() function and adding the following line at the end of the code will make sure all the declared functions get loaded before start of the script.

if __name__=="__main__":
   main()

Comments

0

The reason this isn't working is because is_number() is being defined after it is accessed. When Python reaches that particular piece of code that is calling is_number, it hasn't been defined yet.

There are a few solutions to this:

1. Move the function

This is the simplest way to do it, so that the function is defined before it is accessed. Just put your function definition before you call it.

2. Put the function in a separate file and import it

Put your function in a separate file, like below:

isnum.py

def is_number(s):
  try:
    float(s)
    return True
  except ValueError:
    return False;

Then in your main file:

main.py

from isnum import is_number

for check in lines:
  if is_number(check):
    print ("number: " + check)
  else:
    print ("String!" + check)

3. Make a main() function

As @santosh-patil said in his answer, you can also make a main function that will be called.

def is_number(s):
  try:
    float(s)
    return True
  except ValueError:
    return False;

def main():
  for check in lines:
    if is_number(check):
      print ("number: " + check)
    else:
      print ("String!" + check)

if __name__ == '__main__':
  main()

4. Just don't make it a function

This is the simplest solution: just put the code directly into your main program. The way I see it, it's only being called once per loop, so you might as well just put your is_number code in your regular code.

for check in lines:
  try:
    float(check)
    print("number: "+check)
  except ValueError:
    print("String!"+check)

You should get in the habit of always defining your functions: in a program, you should do you things in this order:

  1. Import your modules
  2. Declare functions, and constants
  3. The rest of your code

Hope this answered your question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.