Multiparadigm programming language – Python
Информатика, кибернетика и программирование
Multiprdigm progrmming lnguge Python.1 Python is generlpurpose progrmming lnguge tht blends procedurl functionl nd objectoriented prdigms. Python is powerful multiprdigm computer progrmming lnguge optimized for progrmmer productivity code redbility nd softwre qulity. Python is populr open source progrmming lnguge used for both stndlone progrms nd scripting pplictions in wide vriety of domins.
Lecture 13. Multiparadigm programming language Python.1
Python is a general-purpose programming language that blends procedural, functional, and object-oriented paradigms. Python is a powerful multiparadigm computer programming language, optimized for programmer productivity, code readability, and software quality.
Python is a popular open source programming language used for both standalone programs and scripting applications in a wide variety of domains. It is free, portable, powerful, and is both relatively easy and remarkably fun to use. Programmers from every corner of the software industry have found Pythons focus on developer productivity and software quality to be a strategic advantage in projects both large and small.
13.1 The Python 2.X and 3.X Lines
In 2009, Python had just become available in two flavors:
While 3.X was largely the same language, it ran almost no code written for prior releases:
The mutation of print from statement to function alone, aesthetically sound as it may be, broke nearly every Python program ever written. And strategic potential aside, 3.Xs mandatory Unicode and class models and ubiquitous generators made for a different programming experience.
Although many viewed Python 3.X as both an improvement and the future of Python, Python 2.X was still very widely used and was to be supported in parallel with Python 3.X for years to come. The majority of Python code in use was 2.X, and migration to 3.X seemed to be shaping up to be a slow process.
In 2013, Python has moved on to versions 3.3 and 2.7. In fact, Python is now a dual-version world, with many users running both 2.X and 3.X according to their software goals and dependencies. And for many newcomers, the choice between 2.X and 3.X remains one of existing software versus the languages cutting edge. Although many major Python packages have been ported to 3.X, many others are still 2.X-only today.
13.2 The language characteristics
The primary factors cited by Python users seem to be these: software quality, developer productivity, program portability, support libraries, component integration, enjoyment.
Software quality. For many, Pythons focus on readability, coherence, and software quality in general sets it apart from other tools in the scripting world. Python code is designed to be readable, and hence reusable and maintainablemuch more so than traditional scripting languages. The uniformity of Python code makes it easy to understand, even if you did not write it. In addition, Python has deep support for more advanced software reuse mechanisms, such as object-oriented (OO) and function programming.
Developer productivity. Python boosts developer productivity many times beyond compiled or statically typed languages such as C, C++, and Java. Python code is typically one-third to one-fifth the size of equivalent C++ or Java code. That means there is less to type, less to debug, and less to maintain after the fact. Python programs also run immediately, without the lengthy compile and link steps required by some other tools, further boosting programmer speed.
Program portability. Most Python programs run unchanged on all major computer platforms. Porting Python code between Linux and Windows, for example, is usually just a matter of copying a scripts code between machines. Moreover, Python offers multiple options for coding portable graphical user interfaces, database access programs, web-based systems, and more. Even operating system interfaces, including program launches and directory processing, are as portable in Python as they can possibly be.
Support libraries. Python comes with a large collection of prebuilt and portable functionality, known as the standard library. This library supports an array of application-level programming tasks, from text pattern matching to network scripting. In addition, Python can be extended with both homegrown libraries and a vast collection of third-party application support software. Pythons third-party domain offers tools for website construction, numeric programming, serial port access, game development, and much more. The NumPy extension, for instance, has been described as a free and more powerful equivalent to the Matlab numeric programming system.
Component integration. Python scripts can easily communicate with other parts of an application, using a variety of integration mechanisms. Such integrations allow Python to be used as a product customization and extension tool. Today, Python code can invoke C and C++ libraries, can be called from C and C++ programs, can integrate with Java and .NET components, can communicate over frameworks such as COM and Silverlight, can interface with devices over serial ports, and can interact over networks with interfaces like SOAP, XML-RPC, and CORBA. It is not a standalone tool.
Enjoyment. Because of Pythons ease of use and built-in toolset, it can make the act of programming more pleasure than chore. Although this may be an intangible benefit, its effect on productivity is an important asset.
There is one significant universal downside to Python: its execution speed may not always be as fast as that of fully compiled and lower-level languages such as C and C++.
The standard implementations of Python today compile (i.e., translate) source code statements to an intermediate format known as byte code and then interpret the byte code. Byte code provides portability, as it is a platform-independent format. However, because Python is not normally compiled all the way down to binary machine code (e.g., instructions for an Intel chip), some programs will run more slowly in Python than in a fully compiled language like C.
13.3 Python user base
There are roughly 1 million Python users around the world today (plus or minus a few). This estimate is based on various statistics, like download rates, web statistics, and developer surveys. Because Python is open source, a more exact count is difficultthere are no license registrations to tally. Moreover, Python is automatically included with Linux distributions, Macintosh computers, and a wide range of products and hardware, further clouding the user-base picture.
Python is also being applied in real revenue-generating products by real companies. For instance, among the generally known Python user base:
• Google makes extensive use of Python in its web search systems.
• The popular YouTube video sharing service is largely written in Python.
• The Dropbox storage service codes both its server and desktop client software primarily in Python.
• The Raspberry Pi single-board computer promotes Python as its educational language.
• EVE Online, a massively multiplayer online game (MMOG) by CCP Games, uses Python broadly.
• The widespread BitTorrent peer-to-peer file sharing system began its life as a Python program.
• Industrial Light & Magic, Pixar, and others use Python in the production of animated movies.
• ESRI uses Python as an end-user customization tool for its popular GIS mapping products.
• Googles App Engine web development framework uses Python as an application language.
• The IronPort email server product uses more than 1 million lines of Python code to do its job.
• Maya, a powerful integrated 3D modeling and animation system, provides a Python scripting API.
• The NSA uses Python for cryptography and intelligence analysis.
• iRobot uses Python to develop commercial and military robotic devices.
• Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware testing.
• JPMorgan Chase, UBS, Getco, and Citadel apply Python to financial market forecasting.
• NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific programming tasks.
13.4 Python application domains
Some of Pythons most common applications today, as well as tools used in each domain, include the following.
Pythons built-in interfaces to operating-system services make it ideal for writing portable, maintainable system-administration tools and utilities (sometimes called shell tools). Python programs can search files and directory trees, launch other programs, do parallel processing with processes and threads, and so on. Pythons standard library comes with POSIX bindings and support for all the usual OS tools: environment variables, files, sockets, pipes, processes, multiple threads, regular expression pattern matching, command-line arguments, standard stream interfaces, shell-command launchers, filename expansion, zip file utilities, XML and JSON parsers, CSV file handlers, and more. In addition, the bulk of Pythons system interfaces are designed to be portable; for example, a script that copies directory trees typically runs unchanged on all major Python platforms. The Stackless Python implementation, described in Chapter 2 and used by EVE Online, also offers advanced solutions to multiprocessing requirements.
Pythons simplicity and rapid turnaround also make it a good match for graphical user interface programming on the desktop. Python comes with a standard object-oriented interface to the Tk GUI API called tkinter (Tkinter in 2.X) that allows Python programs to implement portable GUIs with a native look and feel. Python/tkinter GUIs run unchanged on Microsoft Windows, X Windows (on Unix and Linux), and the Mac OS (both Classic and OS X). A free extension package, PMW, adds advanced widgets to the tkinter toolkit. In addition, the wxPython GUI API, based on a C++ library, offers an alternative toolkit for constructing portable GUIs in Python. Higher-level toolkits such as Dabo are built on top of base APIs such as wxPython and tkinter. With the proper library, you can also use GUI support in other toolkits in Python, such as Qt with PyQt, GTK with PyGTK, MFC with PyWin32, .NET with IronPython, and Swing with Jython or JPype. For applications that run in web browsers or have simple interface requirements, both Jython and Python web frameworks and server-side CGI scripts, described in the next section, provide additional user interface options.
Pythons ability to be extended by and embedded in C and C++ systems makes it useful as a flexible glue language for scripting the behavior of other systems and components. For instance, integrating a C library into Python enables Python to test and launch the librarys components, and embedding Python in a product enables onsite customizations to be coded without having to recompile the entire product (or ship its source code at all). Tools such as the SWIG and SIP code generators can automate much of the work needed to link compiled components into Python for use in scripts, and the Cython system allows coders to mix Python and C-like code. Larger frameworks, such as Pythons COM support on Windows, the Jython Java-based implementation, and the IronPython .NET-based implementation provide alternative ways to script components. On Windows, for example, Python scripts can use frameworks to script Word and Excel, access Silverlight, and much more.
For traditional database demands, there are Python interfaces to all commonly used relational database systemsSybase, Oracle, Informix, ODBC, MySQL, PostgreSQL, SQLite, and more. The Python world has also defined a portable database API for accessing SQL database systems from Python scripts, which looks the same on a variety of underlying database systems. For instance, because the vendor interfaces implement the portable API, a script written to work with the free MySQL system will work largely unchanged on other systems (such as Oracle); all you generally have to do is replace the underlying vendor interface. The in-process SQLite embedded SQL database engine is a standard part of Python itself since 2.5, supporting both prototyping and basic program storage needs. In the non-SQL department, Pythons standard pickle module provides a simple object persistence systemit allows programs to easily save and restore entire Python objects to files and file-like objects. On the Web, youll also find third-party open source systems named ZODB and Durus that provide complete object-oriented database systems for Python scripts; others, such as SQLObject and SQLAlchemy, that implement object relational mappers (ORMs), which graft Pythons class model onto relational tables; and PyMongo, an interface to MongoDB, a high-performance, non-SQL, open source JSON-style document database, which stores data in structures very similar to Pythons own lists and dictionaries, and whose text may be parsed and created with Pythons own standard library json module. Still other systems offer more specialized ways to store data, including the datastore in Googles App Engine, which models data with Python classes and provides extensive scalability, as well as additional emerging cloud storage options such as Azure, Pi-Cloud, OpenStack, and Stackato.
To Python programs, components written in Python and C look the same. Because of this, its possible to prototype systems in Python initially, and then move selected components to a compiled language such as C or C++ for delivery. Unlike some prototyping tools, Python doesnt require a complete rewrite once the prototype has solidified. Parts of the system that dont require the efficiency of a language such as C++ can remain coded in Python for ease of maintenance and use.
Numeric and Scientific Programming.
Python is also heavily used in numeric programminga domain that would not traditionally have been considered to be in the scope of scripting languages, but has grown to become one of Pythons most compelling use cases. Prominent here, the NumPy high-performance numeric programming extension for Python mentioned earlier includes such advanced tools as an array object, interfaces to standard mathematical libraries, and much more. By integrating Python with numeric routines coded in a compiled language for speed, NumPy turns Python into a sophisticated yet easy-to-use numeric programming tool that can often replace existing code written in traditional compiled languages such as FORTRAN or C++. Additional numeric tools for Python support animation, 3D visualization, parallel processing, and so on. The popular SciPy and ScientificPython extensions, for example, provide additional libraries of scientific programming tools and use NumPy as a core component. The PyPy implementation of Python has also gained traction in the numeric domain, in part because heavily algorithmic code of the sort thats common in this domain can run dramatically faster in PyPyoften 10X to 100X quicker.
And More: Gaming, Images, Data Mining, Robots, Excel...
Python is commonly applied in more domains than can be covered here. For example, youll find tools that allow you to use Python to do:
• Game programming and multimedia with pygame, cgkit, pyglet, PySoy, Panda3D, and others
• Serial port communication on Windows, Linux, and more with the PySerial extension
• Image processing with PIL and its newer Pillow fork, PyOpenGL, Blender, Maya, and more
• Robot control programming with the PyRo toolkit
• Natural language analysis with the NLTK package
• Instrumentation on the Raspberry Pi and Arduino boards
• Mobile computing with ports of Python to the Google Android and Apple iOS platforms
• Excel spreadsheet function and macro programming with the PyXLL or DataNitro add-ins
• Media file content and metadata tag processing with PyMedia, ID3, PIL/Pillow, and more
Artificial intelligence with the PyBrain neural net library and the Milk machine learning toolkit
• Expert system programming with PyCLIPS, Pyke, Pyrolog, and pyDatalog
• Network monitoring with zenoss, written in and customized with Python
• Python-scripted design and modeling with PythonCAD, PythonOCC, FreeCAD, and others
• Document processing and generation with ReportLab, Sphinx, Cheetah, PyPDF, and so on
• Data visualization with Mayavi, matplotlib, VTK, VPython, and more
• XML parsing with the xml library package, the xmlrpclib module, and third-party extensions
• JSON and CSV file processing with the json and csv modules
13.5 How Python Runs Programs
Python is a software package called an interpreter. An interpreter is a kind of program that executes other programs. When you write a Python program, the Python interpreter reads your program and carries out the instructions it contains. In effect, the interpreter is a layer of software logic between your code and the computer hardware on your machine.
When the Python package is installed on your machine, it generates a number of componentsminimally, an interpreter and a support library. Depending on how you use it, the Python interpreter may take the form of an executable program, or a set of libraries linked into another program. Depending on which flavor of Python you run, the interpreter itself may be implemented as a C program, a set of Java classes, or something else. Whatever form it takes, the Python code you write must always be run by this interpreter. And to enable that, you must install a Python interpreter on your computer.
Program Execution. What it means to write and run a Python script depends on whether you look at these tasks as a programmer, or as a Python interpreter. Both views offer important perspectives on Python programming.
The Programmers View. In its simplest form, a Python program is just a text file containing Python statements. For example, the following file, named prog1.py, is one of the simplest Python scripts, but it passes for a fully functional Python program:
print(2 ** 100)
This file contains two Python print statements, which simply print a string (the text in quotes) and a numeric expression result (2 to the power 100) to the output stream. After youve typed these statements into a text file, you must tell Python to execute the filewhich simply means to run all the statements in the file from top to bottom, one after another. As youll see in the next chapter, you can launch Python program files by shell command lines, by clicking their icons, from within IDEs, and with other standard techniques. If all goes well, when you execute the file, youll see the results of the two print statements show up somewhere on your computerby default, usually in the same window you were in when you ran the program:
Pythons View. When you instruct Python to run your script, there are a few steps that Python carries out before your code actually starts crunching away. Specifically, its first compiled to something called “byte code” and then routed to something called a “virtual machine.” Internally, and almost completely hidden from you, when you execute a program Python first compiles your source code (the statements in your file) into a format known as byte code. Compilation is simply a translation step, and byte code is a lower-level, platform-independent representation of your source code. Roughly, Python translates each of your source statements into a group of byte code instructions by decomposing them into individual steps. This byte code translation is performed to speed execution byte code can be run much more quickly than the original source code statements in your text file. If the Python process has write access on your machine, it will store the byte code of your programs in files that end with a .pyc extension (“.pyc” means compiled “.py” source). Prior to Python 3.2, you will see these files show up on your computer after youve run a few programs alongside the corresponding source code filesthat is, in the same directories. For instance, youll notice a prog1.pyc after importing a script.py.
Once your program has been compiled to byte code (or the byte code has been loaded from existing .pyc files), it is shipped off for execution to something generally known as the Python Virtual Machine (PVM). The PVM is just a big code loop that iterates through your byte code instructions, one by one, to carry out their operations. The PVM is the runtime engine of Python; its always present as part of the Python system, and its the component that truly runs your scripts. Technically, its just the last step of what is called the “Python interpreter.”
13.6 Python Implementation Alternatives
There are at least five implementations of the Python languageCPython, Jython, IronPython, Stackless, and PyPy. CPython is the standard implementation, All the other Python implementations have specific purposes and roles. All implement the same Python language but execute programs in different ways.
CPython: The standard. The original, and standard, implementation of Python is usually called CPython when you want to contrast it with the other options (and just plain “Python” otherwise). This name comes from the fact that it is coded in portable ANSI C language code.
Jython: Python for Java. The Jython system (originally known as JPython) is an alternative implementation of the Python language, targeted for integration with the Java programming language. Jython consists of Java classes that compile Python source code to Java byte code and then route the resulting byte code to the Java Virtual Machine (JVM).
IronPython: Python for .NET. A third implementation of Python, and newer than both CPython and Jython, IronPython is designed to allow Python programs to integrate with applications coded to work with Microsofts .NET Framework for Windows
Stackless: Python for concurrency. the Stackless Python system is an enhanced version and reimplementation of the standard CPython language oriented toward concurrency.
PyPy: Python for speed. The PyPy system is another standard CPython reimplementation, focused on performance. It provides a fast Python implementation with a JIT (just-in-time) compiler, provides tools for a “sandbox” model that can run untrusted code in a secure environ- ment, and by default includes support for the prior sections Stackless Python systems and its microthreads to support massive concurrency.
1 Mark Lutz. Learning Python. Fifth Edition. OReilly Media Inc. 2013.
А также другие работы, которые могут Вас заинтересовать
|65033.||Аноним Искандара как генеалогический источник||83.5 KB|
|Согласно Анониму в начале своего правления Узбек назначил Сасы Буку сына Нокая правителем улуса Орды. Также интерес вызывают новые данные о правителе улуса Ордаэджена: КалакКубак сын Мангитая Макидая стал правителем улуса в 1320-1321 и еще правил в 1327-1328...|
|65034.||Концепция базы данных “Дипломатические документы постордынских государств Джучиева улуса”||31.5 KB|
|Это позволяет рассматривать сохранившиеся архивные материалы как один документальный массив и следовательно пытаться анализировать не отдельные ярлыки и письма а их совокупность проводить формальный анализ именно комплекса документов.|
|65035.||Как называть Золотую Орду?||49.5 KB|
|Как называть Золотую Орду Под названием Золотая Орда обычно мы подразумеваем государство существовавшее в XIII XV веках на обширной территории с центром в Нижнем Поволжье. Золотая Орда в мировой геополитике играла ведущую роль.|
|65036.||РУСЬ И СТЕПЬ||643.5 KB|
|Эти встречи со степью и определяли причудливые изгибы исторических судеб Руси. Соседство со степными просторами предопределило же превращение Руси в Россию когда восторжествовав наконец над Золотой Ордой русский народ приступил к освоению необъятных пространств Евразии.|
|65037.||Золотоордынский город Сарай и роль ханской власти в его истории||32.5 KB|
|Особенно большое внимание проблемам возникновения, развития и упадка джучидских городов и роли центральной власти в их судьбах уделял Г.А. Федоров-Давыдов.|
|65038.||К вопросу о хронологии и топографии Селитренного городища эпохи Тохтамыша (1380 – 1396 гг.)||43.5 KB|
|Для исследования использовались помимо публикаций материала отчеты Поволжской археологической экспедиции ПАЭ и каталог коллекции монет с Селитренного городища за 1965-1997 гг. Федоровым-Давыдовым 4932 медных и 112 серебряных монет.|
|65039.||СЕЛИТРЕННОЕ ГОРОДИЩЕ: ХРОНОЛОГИЯ И ТОПОГРАФИЯ||254 KB|
|Исследование округи Селитренного городища также актуально так как эта тема ещё не была объектом изучения. Целью диссертационной работы является изучение хронологии и топографии Селитренного городища.|
|65040.||Неизвестное сочинение ХIII века||73.5 KB|
|Речь идет о вымышленной биографии Чингисхана насыщенной фантастическими эпизодами. Римскую курию интересовал прогноз на будущее: кто они монголы Кто ими правит и к чему они стремятся И хотя брат Иоанн не скрывает каким образом ему удалось получить различные сведения о монголах имя самого...|
|65041.||Образ Чингисхана в мировой литературе XIII-XV веков||101 KB|
|Мировую известность Чингисхану обеспечили преемники создавшие к 1260 г. Однако победив хорезмшаха Чингисхан даже не попытался занять всю территорию его царства.|