Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the typing module in Python

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to use the typing module in Python". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Support for Python operation in Sublime Text

In our daily work, we usually use PyCharm to develop Python projects, and we can also use Vim to edit and view Python scripts. However, if we just want to create a separate script to implement certain functions, then using PyCharm will make a mountain out of a molehill, and using Vim will not be easy to edit. At this point, we can use a text editor, such as Sublime Text, to edit and run Python scripts.

Sublime Text is a text editor supported by Mac systems, while Notepad++ does not support Mac systems.

If we want to support Python running in Sublime Text, we need to make some settings.

Open the Tools of Sublime Text and select New Build System in Build System. A script appears, and we modify it as follows:

{"cmd": ["D:/Anaconda3/python3.7.exe", "- u", "$file"],}

The first item in the corresponding list in cmd is the installation path of Python. After editing, save the file in the default location, such as the file named Python3.7.sublime-build.

At this point, let's take a look at the Tools. The environment of the Python3.7 that you just edited appears. Select this item, and we can run the Python script in Sublime Text.

The Python script for our example is test.py, with the following code:

Import numpy as npmatrix = np.array ([[0,1,2], [2,4,5]]) print (matrix [1,2]) print ("Hello world from Sublime Text.")

Click Build or Ctrl+B in Tools to run the program, and the result is as follows:

Similarly, it can be set up in the Windows system, which is convenient and easy to use.

As to whether Notepad++ has similar functions, it remains to be studied.   

Support for viewing pictures in iTerm2 of Mac system

ITerm2 is a very useful terminal tool for Mac systems. This article does not introduce iTerm2 too much, but how to view pictures directly in iTerm2, which makes it convenient for us to view pictures directly on the terminal.

The tool we use is imgcat.

Create a new shell script imgcat.sh in iTerm2, save the file after editing, and grant execution permission with chmod Ubunx imgcat.sh.

So you can view the picture directly. What, it's that simple? Yes, it's that simple!

The effect on the author's computer is as follows:

Introduction of typing Module in Python

The typing module is a module that provides type support in Python, and its main functions are:

Type checking to prevent run-time parameter and return value type inconsistencies.

As an additional description of the development document, it is convenient for the user to pass in and return parameter types when calling.

The addition of the module will not affect the operation of the program, will not report formal errors, only reminders.

To put it simply, using the typing module, we can annotate and check the type of the parameter, which does not affect the running of the program, and this is a reminder. It is well known that when calling functions or variables in Python, there is no need for a type description of parameters or variables, which is convenient for programming, but not conducive to program reading. With the typing module, you can increase the readability of the program, and at the same time improve the maintainability and robustness of the code.

To take a simple example, we implement a function digits_sum, which inputs a string, such as "352", and outputs the sum of the digits on that number, such as 10. With the typing module, our code looks like this:

From typing import * # create function def digits_sum (num:str)-> int: digits_arr = map (lambda x: int (x), num) return sum (digits_arr) # Test num= "352" result = digits_sum (num=num) print (result)

The output is 10. To explain the above program, the from typing import * in the first sentence does not have to be written, because str,int is the built-in data type of Python. The function is declared as def digits_sum (num:str)-> int, the num type in parentheses is str, and the int after the arrow indicates that the output data type of the function is int.

Let's give you another example. Function dict_multipy, the input is a dictionary, if the data type of the value corresponding to the key value is float or int, it is multiplied by 2, otherwise skipped, then the output is also a dictionary. The procedure is as follows:

From typing import Dict, Any# creation function def dict_multipy (d: Dict [str, Any])-> Dict [str, float or int]: new_dict = {} for k, v in d.items (): if isinstance (v, (float, int)): new_ creation [k] = v * 2 return new_dict# test d = {"no": "100"," age ": 12," work_year ": 3 "name": "JC"} new_d = dict_multipy (daild) print (new_d) Python

The output is {'age': 24,' work_year': 6}. In the function declaration, d is a dictionary, its key value is str,val is any type (Any), the output is a dictionary, the key value is str, and the vale value is float or int.

Of course, we can also create aliases or new data types in typing. Here is an example.

From typing import List# aliases List [float] as VectorVector = list [float] def scale (scalar: float, vector: Vector)-> Vector: return [scalar * float] new_vector = scale (2.0,1.0,4.2,5.4]). Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report