goto python что это

Зачем goto в исходниках Python?

Стандартная практика обработки ошибок или освобождения ресурсов в Си. Обычно в таких случаях goto более удобен и читаем чем альтернативные решения.
Однако в данном конкретном примере функция очень короткая и в ней нет множества ветвлений, поэтому конечно проще написать без goto, но видимо сила привычки или задел на будущее.

Вот напиример функция из питона с более уместным использованием goto

Иногда читаемость, как в данном примере, повышается на порядок.

Goto перестали рекомендовать, из-за того, что очень просто с ним пропустить освобождение чего-то важного

Даже в C++ и управляемых языках?

Алексей Черемисин: вам нравится искать глазами метки?)

Добавьте в ваш пример еще пару ифов

Ну вот, пошли условности. Если код трудно читать, то нужно выделять функции, а не goto втыкать.

А холиваров нет, ибо в промышленном программировании goto табуирован практически.

Алексей Черемисин: опыт вам не смог подсказать, что конкретный пример с goto отвратителен для читающего.

Надеюсь, вы не думаете, что на системном программировании свет клином сошелся?

И, это, знаете, сколько тонн легаси в этом ядре?) Да, когда-то goto в Си процветало, помнится, даже в статях на Хабре о первых компиляторах Си-с-классами на это акцент делался.

Источник

‘goto` в Python

я мог бы пойти и создать байт-код вручную (т. е. написать мой собственный компилятор Python), потому что есть такая инструкция ( JUMP_ABSOLUTE и друзей). Но мне интересно, есть ли более простой способ. Возможно ли это через inspect или так, чтобы вызвать одну инструкцию байт-кода? Я также думал о компиляции через Python, а затем автоматически исправлять сгенерированный байт-код Python.

6 ответов

Я знаю, что все думают:

этот рецепт python обеспечивает goto команда в качестве декоратора функций.

использование

обновление

вот две дополнительные реализации, совместимые с Python 3:

у вас может быть единственный допустимый случай использования, который я когда-либо видел для нуждающихся goto в Python. 🙂

самый простой способ эмулировать вперед goto в Python используются исключения, так как они могут выскакивать из любой глубины вложенных структур управления.

это станет опасно, если вам нужно поддерживать более одного назначения, но я думаю, что это можно сделать с помощью вложенных элементов try/except структуры и несколько классов исключений, по одному для каждого назначения. С С пределы goto в рамках одной функции, по крайней мере, вам не придется беспокоиться о том, как сделать эту работу на функции. :- ) Конечно, это не работает для reverse goto s.

я обновил свой Python goto decorator для Python 3. Вы можете получить его в https://github.com/cdjc/goto. Использование goto вместо функций может сделать государственную машину примерно в 5 раз быстрее.

версия для python 2 по-прежнему доступна вhttp://code.activestate.com/recipes/576944-the-goto-decorator/ но у него есть ряд ошибок, которые исправлены в версии python 3.

в большинстве случаев я подозреваю, что все операторы goto перейдут в место, которое будет как позже, так и в более замкнутом блоке; если тело функции идеально следует этому шаблону, преобразуйте goto в исключения, с метками как блоки except.

другие случаи перехода goto из одного места в другое в том же блоке, что и в состоянии машина. Вероятно, это можно перевести в цикл отправки; каждая область между меткой и следующей становится функцией; goto заменяются на next_state = ‘labelname’; return

это не совсем то, что вы ищете, но выслушай меня.

много лет назад мы с сыном написали «приключенческую» игру на BASIC. Каждое место в подземной игре было номером линии. Например, когда вы покинули одно место через туннель, идущий на север, вы прибыли в другое место.

Я задавался вопросом, как это можно сделать в Python и придумал это.

возможно, такая техника может быть использована для других приложений, где требуется что-то вроде GOTO. Если вы разделите свою программу на куски, которые являются функциями, следующее «немного глупое» кодирование сделает трюк.

Примечание:это было предложено как первоапрельская шутка. (хотя)

разумеется. Да, это смешно, но не используйте его.

Источник

Есть ли метка /goto в Python?

Есть ли goto или любой эквивалент в Python, чтобы иметь возможность перейти к определенной строке кода?

Нет, Python не поддерживает метки и goto, если это то, что вам нужно. Это (высоко) структурированный язык программирования.

Читайте также:  google charts что это

Python предлагает вам возможность выполнять некоторые действия, которые вы можете сделать с помощью goto, используя функции первого класса. Например:

Может быть сделано в python следующим образом:

Конечно, это не лучший способ заменить goto. Но, не зная точно, что вы пытаетесь сделать с goto, трудно дать конкретные советы.

Лучше всего либо заключить его в функцию, либо использовать исключение. Для функции:

Недавно я написал декоратор функций, который позволяет goto в Python, точно так же:

Я не уверен, почему хочется делать что-то подобное. Тем не менее, я не слишком серьезно отношусь к этому. Но я хотел бы отметить, что такое мета-программирование реально возможно в Python, по крайней мере, в CPython и PyPy, а не только при неправильном использовании API отладчика в качестве другого парня сделал. Вы должны возиться с байт-кодом, хотя.

Вы можете использовать исключения, чтобы обеспечить «структурированную перестановку», которая даже работает через вызовы функций. Многие считают, что исключения могут подражать всем разумным применениям конструкций «go» или «goto» C, Фортране и других языках. Например:

Это не позволяет вам прыгать в середину цикла, но thats обычно считается злоупотреблением goto. Используйте экономно.

Очень приятно, что это даже упоминается в официальном FAQ, и что предоставляется хороший образец решения. Мне очень нравится python, потому что его сообщество обрабатывает даже goto как это;)

Чтобы ответить на вопрос @ascobol используя предложение @bobince из комментариев:

Отступ для блока else правильный. Код использует неясное else после циклы синтаксиса Python. См. Почему Python использует «else» после циклов for и while?

Примечание. Это было предложено в качестве шутки в апреле. (работает хотя)

Нет нужды говорить. Да, это смешно, но DONT его использовать.

Ярлыки для break и continue были предложены в Motivation иллюстрирует несколько общих (если неэлегантных) методов имитации помеченных break в Python.

Технически возможно добавить инструкцию ‘goto’ на python с некоторой работой. Мы будем использовать модули «dis» и «new», которые очень полезны для сканирования и изменения байтового кода python.

Основная идея реализации заключается в том, чтобы сначала отметить блок кода как использование операторов «goto» и «label». Специальный декоратор «@goto» будет использоваться для обозначения функций «goto». Затем мы сканируем этот код для этих двух операторов и применяем необходимые изменения к базовому байтовому коду. Это происходит во время компиляции исходного кода.

Источник

Goto python что это

Are you a professional Visual Studio developer?

Entrian Source Search is a powerful search addin for Visual Studio.

It displays syntax colored search results within a fraction of a second, whether you’re working with hundreds of lines of code or millions.

It’s the fastest and easiest way to navigate your source code.


The «goto» module was an April Fool’s joke, published on 1st April 2004. Yes, it works, but it’s a joke nevertheless. Please don’t use it in real code!

goto for Python

Adds the ‘goto’ and ‘comefrom’ keywords to Python.

The ‘goto’ and ‘comefrom’ keywords add flexibility to Python’s control flow mechanisms, and allow Python programmers to use many common control flow idioms that were previously denied to them. Some examples are given below.

To enable the new keywords, add the following line to the top of your code:

goto

‘goto’ jumps the program execution directly to another line of code. The target line must be identified using a ‘label’ statement. Labels are defined using the ‘label’ keyword, and have names which are arbitrary Python identifiers prefixed with a single dot, like this:

To jump to a label, use the ‘goto’ keyword like this:

Computed goto

You can use a computed goto by assigning the name of the label to a variable at runtime and referencing it using an asterisk like this:

The value of ‘x’ should not include the leading dot. See Example 5 below for a full example.

comefrom

‘comefrom’ is the opposite of ‘goto’. It allows a piece of code to say «Whenever label X is reached, jump to here instead.» For example:

Читайте также:  русалки настоящие фото какие бывают

Restrictions

There are some classes of goto and comefrom which would be unpythonic, and hence there are some restrictions on where jumps can go:

Examples

Here are some examples of how goto and comefrom can be used:

This module is released under the Python Software Foundation license, which can be found at http://www.python.org/ It requires Python 2.3 or later.

Version 1.0, released 1st April 2004. Download here.

Источник

Is there a label/goto in Python?

Is there a goto or any equivalent in Python to be able to jump to a specific line of code?

21 Answers 21

No, Python does not support labels and goto. It’s a (highly) structured programming language.

Python offers you the ability to do some of the things you could do with a goto using first class functions. For example:

Could be done in python like this:

Granted, that isn’t the best way to substitute for goto. But without knowing exactly what you’re trying to do with the goto, it’s hard to give specific advice.

Your best bet is to either enclose it in a function or use an exception. For the function:

Using exceptions to do stuff like this may feel a bit awkward if you come from another programming language. But I would argue that if you dislike using exceptions, Python isn’t the language for you. 🙂

I recently wrote a function decorator that enables goto in Python, just like that:

I’m not sure why one would like to do something like that though. That said, I’m not too serious about it. But I’d like to point out that this kind of meta programming is actual possible in Python, at least in CPython and PyPy, and not only by misusing the debugger API as that other guy did. You have to mess with the bytecode though.

You can use exceptions to provide a “structured goto” that even works across function calls. Many feel that exceptions can conveniently emulate all reasonable uses of the “go” or “goto” constructs of C, Fortran, and other languages. For example:

This doesn’t allow you to jump into the middle of a loop, but that’s usually considered an abuse of goto anyway. Use sparingly.

It’s very nice that this is even mentioned in the official FAQ, and that a nice solution sample is provided. I really like python because its community is treating even goto like this 😉

To answer the @ascobol ‘s question using @bobince ‘s suggestion from the comments:

The indent for the else block is correct. The code uses obscure else after a loop Python syntax. See Why does python use ‘else’ after for and while loops?

A working version has been made: http://entrian.com/goto/.

Note: It was offered as an April Fool’s joke. (working though)

Needless to say. Yes its funny, but DONT use it.

It is technically feasible to add a ‘goto’ like statement to python with some work. We will use the «dis» and «new» modules, both very useful for scanning and modifying python byte code.

The main idea behind the implementation is to first mark a block of code as using «goto» and «label» statements. A special «@goto» decorator will be used for the purpose of marking «goto» functions. Afterwards we scan that code for these two statements and apply the necessary modifications to the underlying byte code. This all happens at source code compile time.

Hope this answers the question.

Labels for break and continue were proposed in PEP 3136 back in 2007, but it was rejected. The Motivation section of the proposal illustrates several common (if inelegant) methods for imitating labeled break in Python.

Python 2 & 3

Tested on Python 2.6 through 3.6 and PyPy.

you can use User-defined Exceptions to emulate goto

I was looking for some thing similar to

So my approach was to use a boolean to help breaking out from the nested for loops:

Though there isn’t any code equivalent to goto/label in Python, you could still get such functionality of goto/label using loops.

Читайте также:  призрачный гонщик к какой вселенной относится

Lets take a code sample shown below where goto/label can be used in a arbitrary language other than python.

Now the same functionality of the above code sample can be achieved in python by using a while loop as shown below.

I think this might be useful for what you are looking for.

I have my own way of doing gotos. I use separate python scripts.

file1.py

file2.py

file3.py

(NOTE: This technique only works on Python 2.x versions)

For a forward Goto, you could just add:

This only helps for simple scenarios though (i.e. nesting these would get you into a mess)

In lieu of a python goto equivalent I use the break statement in the following fashion for quick tests of my code. This assumes you have structured code base. The test variable is initialized at the start of your function and I just move the «If test: break» block to the end of the nested if-then block or loop I want to test, modifying the return variable at the end of the code to reflect the block or loop variable I’m testing.

no there is an alternative way to implement goto statement

You can achieve it using nested methods inside python

I think while loop is alternate for the «goto_Statement». Because after 3.6 goto loop is not working anymore. I also write an example of the while loop.

When implementing «goto», one must first ask what a goto is. While it may seem obvious, most people don’t think about how goto relates to function stacks.

If you perform a «goto» inside a function, you are, in effect, abandoning the function call stack. This is considered bad practice, because function stacks are designed with the expectation that you will continue where you left off, after delegating an intermediate task. This is why gotos are used for exceptions, and exceptions can be used to emulate goto, which i will explain.

Finite state machines are probably the best use case for goto, which most of the time are implemented in a kludgy way with loops and switch statements, but I believe that «top level» gotos, are the cleanest, most semantic way to implement finite state machines. In this case, you want to make sure, if you have more variables, they are globals, and don’t require encapsulation. Make sure you first model your variable state space(which may be different from execution state, ie the finite state machine).

I believe there are legitimate design reasons to use goto, exception handling being the special case where mixing goto with functions makes sense. However, in most cases, you want to restrict yourself to «top level» goto, so you never call goto within a function, but only within a global scope.

The easiest way to emulate top level goto in modern languages, is to realize that top-level gotos, simply require global variables and an empty call stack. So to keep the call stack empty, you return whenever you call a new function. Here’s an example to print the first n fibonacci numbers:

While this example may be more verbose than loop implementations, it is also much more powerful and flexible, and requires no special cases. It lets you have a full finite state machine. You could also modify this with a goto runner.

To enforce the «return» part, you could write a goto function that simply throws an exception when finished.

So you see, a lot of this is overthinking, and a helper function that calls a function and then throws an error is all you need. You could further wrap it in a «start» function, so the error gets caught, but I don’t think that’s strictly necessary. While some of these implementations may use up your call stack, the first runner example keeps it empty, and if compilers can do tail call optimization, that helps as well.

Источник

Сказочный портал