0

I would like to place a function at the end of a script which is used in the script. This, of course, does not work as the function is not known yet. Can I therefore import this funtion in the same script?

If I do it like the following, I get the error " ImportError: cannot import name:'subfunction' "

from the_script_in_use import subfuction

a=subfunction(b)

def subfunction(value)
    do something
    return a
2
  • 1
    Why not placing the function at the top instead? Commented Dec 8, 2017 at 10:10
  • Sure, that is the classic way. In this case I have tons of little subfunctions which would make the script unreadable. OF course I could save them also in a different file (as I do at the moment) but they will only be used in this script. Commented Dec 8, 2017 at 10:12

3 Answers 3

1

One way to do this in Python is writing:

def main():
    b = 5
    a = subfunction(b)
    print a

def subfunction(value):
    a = value + 10
    return a

if __name__ == '__main__':
    main()

This way you can write your code in the order you like, as long as you keep calling the function main at the end.

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

1 Comment

Thanks, that is actually quite logic.
1

You may use the statement :

if __name__ == '__main__':

Which will be executed if you run this file as a script. In your case:

def main_function()
    a=subfunction(b)

def subfunction(value)
    do something
    return a

if __name__ == '__main__':
    main_function()

Note there is no need to import your function. Doing so you can order your fonction the way you want.

1 Comment

Thanks a lot. I choose the answer from nakulbansal as he was 4 min earlier :-) Have a nice day.
0

you can try to use pass :

def func1():
    pass

func1()

def func1():
    print "yes"

But this does not actually help you run the function.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.