Возможности python 3, достойные того, чтобы ими пользовались

Синтаксис и семантика

Исключительные случаи

  • Выражения присваивания, не заключённые в скобки, запрещены на «верхнем» уровне:

    Это правило упростит программисту выбор между оператором присваивания и выражением присваивания — не будет существовать синтаксической ситуации, в которой оба варианта равноценны.

  • Не заключенные в скобки выражения присваивания запрещены в правой части каскадного присваивания. Пример:

    Не заключенные в скобки выражения присваивания запрещены в значениях ключевого аргумента при вызове функции. Пример:

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

  • Не заключенные в скобки выражения присваивания запрещены в значениях аргумента по умолчанию. Пример:

    Это правило создано для предотвращения побочных эффектов в местах, где точная семантика и так сбивает с толку многих пользователей (см. Рекомендацию по общему стилю, которая против использования изменяемых «сущностей» в качестве значений по умолчанию).

  • Не заключенные в скобки выражения присваивания запрещены в качестве аннотаций для аргументов, возвращаемых значений и присваиваний. Пример:

    Рассуждения по поводу введения этого правила аналогичны предыдущим: код, состоящий из комбинации операторов «=» и «:=» трудно правильно понять.

  • Не заключенные в скобки выражения присваивания запрещены в лямбда-функциях. Пример:

    Лямбда-функция имеет приоритет более высокий, чем «:=». Удобное присваивание лямбды к переменной здесь важнее. В случаях, когда переменная используется несколько раз, вам и так (наверняка) понадобятся скобки, потому это ограничение не сильно повлияет на ваш код.

  • Выражения присваивания внутри f-строк требуют скобок. Пример:

    Это показывает, что не всё выглядящее, как оператор присваивания в f-строке, является таковым. Парсер f-строки использует символ «:» для указания параметров форматирования. Чтобы сохранить обратную совместимость, при использовании оператора присваивания внутри f-строк он должен быть заключен в скобки. Как отмечено в примере выше, такое использование оператора присваивания не рекомендуется.

Различия между выражениями присваивания и инструкциями присваивания.

выражениеминструкциивыраженияинструкциях

  • Каскадное присваивание не поддерживается на прямую
  • Отдельные «цели», кроме простого имени переменной NAME, не поддерживаются:
  • Функционал и приоритет «вокруг» запятых отличается:
  • Распаковка и упаковка значений не имеют «чистую» эквивалентность или вообще не поддерживаются
  • Встроенные аннотации типов не поддерживаются:
  • Укороченная форма операций отсутствует:

Execution Modes in Python#

There are two primary ways that you can instruct the Python interpreter to execute or use code:

  1. You can execute the Python file as a script using the command line.
  2. You can import the code from one Python file into another file or into the interactive interpreter.

You can read a lot more about these approaches in How to Run Your Python Scripts. No matter which way of running your code you’re using, Python defines a special variable called that contains a string whose value depends on how the code is being used.

We’ll use this example file, saved as , to explore how the behavior of the code changes depending on the context:

In this file, there are three calls to defined. The first two print some introductory phrases. The third will first print the phrase , and then it will print the representation of the variable using Python’s built-in .

In Python, displays the printable representation of an object. This example uses to emphasize that the value of is a string. You can read more about in the .

You’ll see the words file, module, and script used throughout this article. Practically, there isn’t much difference between them. However, there are slight differences in meaning that emphasize the purpose of a piece of code:

  1. File: Typically, a Python file is any file that contains code. Most Python files have the extension .

  2. Script: A Python script is a file that you intend to execute from the command line to accomplish a task.

  3. Module: A Python module is a file that you intend to import from within another module or a script, or from the interactive interpreter. You can read more about modules in the Python documentation.

This distinction is also discussed in How to Run Your Python Scripts.

Python File Naming Conventions

The usual way of using and looks like this:

Let’s see how this works in real life, and how to actually use these variables.

Modify and to look like this:

file_one.py

file_two.py

Again, when running you will see that the program recognized which of these two modules is and executed the code according to our first statements.

The result should look like this:

Now run and you will see that the variable is set to :

When modules like this are being imported and run, their functions will be imported, and top level code executed.

To see this process in action, modify your files to look like this:

file_one.py

Now the functions are loaded but not run.

To run one of these functions modify the part of to look like this:

When running you should see should be like this:

Also, you can run functions from imported files. To do that, modify the part of to look like this:

And you can expect a result like this:

Now let’s say the module is really big with lot of functions (two in our case), and you don’t want to import all of them. Modify to look like this:

file_two.py

And to import the specific functions from the module, use the import block in the file:

file_one.py

What is __name__?

is a built-in variable in python that stores the name of the current module/script being executed. If the current module is executing then the variable is assigned the value __main__ otherwise it simply contains the name of the module or script.

So, when a python script is executing then its variable will always have the value __main__ and if that python file is imported in any other python script then the variable will have the name of the module.

Let’s take an example to understand. Create a python script with name test.py an add the following code in it:

Value of __name__: __main__

When we executed the test.py script, the value for the variable is set as __main__.

Now, let’s create another python script main.py and then import the above script in it.

Value of __name__: test

As you can see in the above code output, the value of the variable is test, because we printed the value of the variable of the test.py module.

Using

To specify some code in any python script which should be executed only when that script is executed directly, we can use the statement with the condition

For example,

Here __main__ is just a string that is used to check if the current module/script is running on its own or not. In the variable, the double underscores on both sides of name is for indicating the python interpreter to recognize it as a special/reserved keyword.

Python Modules Explained

Python files are called modules and they are identified by the file extension. A module can define functions, classes, and variables.

So when the interpreter runs a module, the variable will be set as   if the module that is being run is the main program.

But if the code is importing the module from another module, then the  variable will be set to that module’s name.

Let’s take a look at an example. Create a Python module named and paste this top level code inside:

file_one.py

By running this file you will see exactly what we were talking about. The variable for this module is set to :

Now add another file named and paste this code inside:

file_two.py

Also, modify the code in like this so we import the module:

file_one.py

Running our code once again will show that the variable in the did not change, and still remains set to . But now the variable in is set as its module name, hence .

The result should look like this:

But run directly and you will see that its name is set to :

The variable for the file/module that is run will be always . But the variable for all other modules that are being imported will be set to their module’s name.

Python __name__: Code Example

As specified above, when we execute a code file, for that code snippet, the value of variable becomes __main__ as the code is being executed directly, without being imported into any other file.

For example: Here we have a code file Script1.py,

When we run python Script1.py then:

This function is in Script1.
Called from Script1.

Now, let’s create another python script file with name Script2.py and import the script Script1.py in it and try to call the function defined in the script Script1.

Here’s the code for Script2.py:

Now we run python Script2.py then:

Script1 is imported in some other file.
This function is in Script1.
Called from Script2.

When the statement is executed for Script1, inside the Script2, during that the variable had the value Script1(name of the module), but as the execution started with the script Script2, hence the variable for it will have the value __main__.

: Printing it’s Value

To understand it better, let’s print value of variable at every execution step.

Here is the code for the python script Script1.py:

That’s it, we won’t include anything else in the script. And here is the code for the script Script2.py:

Here is a live example:

NOTE: In the live example the scripts are main.py and Script1.py, the change in name of the scripts will not affect the functionality.

Most of the programming languages use the main method or function as the starting point of execution in any program. But what about Python? Generally, the execution of a python program(script) starts from the very first line that is at the indentation level 0 of that program. However, when a python program is executed, before its execution a variable is created. This variable can be used as an alternate for the main method in python.

  • ← Prev
  • Next →

Преимущества Python

  • Скорость выполнения программ написанных на Python очень высока. Это связанно с тем, что основные библиотеки Python
    написаны на C++ и выполнение задач занимает меньше времени, чем на других языках высокого уровня.
  • В связи с этим вы можете писать свои собственные модули для Python на C или C++
  • В стандартныx библиотеках Python вы можете найти средства для работы с электронной почтой, протоколами
    Интернета, FTP, HTTP, базами данных, и пр.
  • Скрипты, написанные при помощи Python выполняются на большинстве современных ОС. Такая переносимость обеспечивает Python применение в самых различных областях.
  • Python подходит для любых решений в области программирования, будь то офисные программы, вэб-приложения, GUI-приложения и т.д.
  • Над разработкой Python трудились тысячи энтузиастов со всего мира. Поддержкой современных технологий в стандартных библиотеках мы можем быть обязаны именно тому, что Python был открыт для всех желающих.

Dunder variable __name__ behind the scenes!!

Rachit TayalFollow

Nov 21, 2019 · 3 min read

Using the if __name__ == “__main__” statement is quite regular in Python files. However, it may seem confusing at times. This aim of this article is to uncover the behaviour of the statement and further discusses on where to use it. So let’s get started!

A Python module is a file that has a extension. All we need to do is create a file that contains legitimate Python code and give the file a name with extension. A module can be imported to other modules or run directly via command line.

The __name__ is a special built-in variable which evaluates to the name of the current module. However, if a module is being run directly (from command line), then __name__ instead is set to the string “__main__”.

Let’s put together this little code example for understanding. Suppose we create two modules, foo and bar with the following code:

# foo.pyimport barprint("foo.__name__ set to ", __name__)

And the bar module:

# bar.pyprint("bar.__name__ set to ", __name__)

On invoking the bar module from command line, its __name__ attribute will be set to “__main__”:

python bar.py>>>bar.__name__ set to __main__

However, on invoking the foo module in a similar fashion, the bar’s __name__ attribute will be set equivalent to it’s module name i.e bar:

python foo.py>>>bar.__name__ set to barfoo.__name__ set to __main__

Therefore, we can test whether our module is being run directly or being imported using the following check:

if __name__ == "__main__"...

In this way, modules can look at their own __name__ value to determine for themselves how they are being used, whether as support for another program or as the main application executed from the command line.

When a module is being imported into another module, its various function and class definitions will be imported and its top-level code will be executed. To illustrate this, let’s consider the following two modules:

# module person.pydef creds():    name = "Sarah"    age = 26print("person details {}, {}".format(name, age))print("top-level in person module")if __name__ == "__main__":print("person mod is run directly")else:print("person mod is imported into another module")# module utility.pyimport personperson.creds()if __name__ == "__main__":print("utility mod is run directly")else:print("utility mod is imported into another module")

On invoking the person module directly, __name__ attribute will be set to __main__, hence we’ll see the following output:

python person.py>>>top-level in person moduleperson mod is run directly

Whereas, when utility.py module is executed directly, __name__ attribute for person module will be set to “person” itself, while __name__ of the utility module will be set to __main__. Therefore, we’ll get the following output:

python utility.py>>>top-level in person moduleperson mod is imported into another moduleperson details Sarah, 26utility mod is run directly

Why it’s designed like this?

We might naturally wonder why it’s designed the way it is. Well, sometimes we want to write a file that can be both used by other programs and/or modules as a module, and can also be run as the main program itself.

This behaviour comes in handy for quick developing and testing our code. It also helps in debugging since it allows us to have a script mode where we can run unit tests directly.

Besides this, it’s elegant that running a module in Python directly is just setting up a single variable.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector