Why can I call a function before defining it, with only a warning?

心已入冬 提交于 2019-12-06 11:23:44
Markus Meskanen

From my own comment:

Try restarting your interpreter, maybe you've accidentally defined my_func earlier on already?

And another one:

The code, as is, doesn't work. You've most likely defined my_func earlier on already in the same REPL session, try restarting your IDLE or w/e you're using. The code doesn't work unless you've done something else already.

As it turned out, this was the issue, and your IDE was somehow "caching" the function definition from earlier on during that session.

In general, when you usually run into weird problems that make no sense and shouldn't be there in the first place (such as this), you should restart your IDE. More often than not it solves the problem, and the issue was just something silly like caching.

Also, when using CPython, the default, most widely used implementation of the Python programming language, you're using Python as an interpreted language, thus your interpreter is going through the code in order from top to bottom. This is why you normally can't call a function before defining it in Python.

That doesn't work in the standard Python build, because the file is parsed in order. The other languages you refer to are compiled (in the traditional sense, not JIT or anything), so the order doesn't matter, but Python requires the first things to come first.

Define/assign/create/etc. things before using them.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!