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.



50 KB

0 чел.

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 Python’s 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:

  •  Version 3.0 was the first in the line of an emerging and incompatible mutation of the language known generically as 3.X.
    •  Version 2.6 retained backward compatibility with the vast body of existing Python code, and was the latest in the line known collectively as 2.X.

While 3.X was largely the same language, it ran almost no code written for prior releases:

  •  Imposed a Unicode model with broad consequences for strings, files, and libraries
    •  Elevated iterators and generators to a more pervasive role, as part of fuller functional paradigm
    •  Mandated new-style classes, which merge with types, but grow more powerful and complex
    •  Changed many fundamental tools and libraries, and replaced or removed others entirely

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.X’s 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 language’s 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, Python’s 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 maintainable—much 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 script’s 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. Python’s 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 Python’s 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 difficult—there 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.

• Google’s 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 Python’s most common applications today, as well as tools used in each domain, include the following.

Systems Programming.

Python’s 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. Python’s 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 Python’s 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.


Python’s 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.

Internet Scripting.

Python comes with standard Internet modules that allow Python programs to perform a wide variety of networking tasks, in client and server modes. Scripts can communicate over sockets; extract form information sent to server-side CGI scripts; transfer files by FTP; parse and generate XML and JSON documents; send, receive, compose, and parse email; fetch web pages by URLs; parse the HTML of fetched web pages; communicate over XML-RPC, SOAP, and Telnet; and more. Python’s libraries make these tasks remarkably simple. In addition, a large collection of third-party tools are available on the Web for doing Internet programming in Python. For instance, the HTMLGen system generates HTML files from Python class-based descriptions, the mod_python package runs Python efficiently within the Apache web server and supports server-side templating with its Python Server Pages, and the Jython system provides for seamless Python/Java integration and supports coding of server-side applets that run on clients. In addition, full-blown web development framework packages for Python, such as Django, TurboGears, web2py, Pylons, Zope, and WebWare, support quick construction of full-featured and production-quality websites with Python. Many of these include features such as object-relational mappers, a Model/View/Controller architecture, server-side scripting and templating, and AJAX support, to provide complete and enterprise-level web development solutions. More recently, Python has expanded into rich Internet applications (RIAs), with tools such as Silverlight in IronPython, and pyjs (a.k.a. pyjamas) and its Python-to-JavaScript compiler, AJAX framework, and widget set. Python also has moved into cloud computing, with App Engine, and others described in the database section ahead. Where the Web leads, Python quickly follows.

Component Integration.

Python’s 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 library’s 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 Python’s 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.

Database Programming.

For traditional database demands, there are Python interfaces to all commonly used relational database systems—Sybase, 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, Python’s standard pickle module provides a simple object persistence system—it allows programs to easily save and restore entire Python objects to files and file-like objects. On the Web, you’ll 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 Python’s 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 Python’s own lists and dictionaries, and whose text may be parsed and created with Python’s own standard library json module. Still other systems offer more specialized ways to store data, including the datastore in Google’s 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.

Rapid Prototyping.

To Python programs, components written in Python and C look the same. Because of this, it’s 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 doesn’t require a complete rewrite once the prototype has solidified. Parts of the system that don’t 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 programming—a domain that would not traditionally have been considered to be in the scope of scripting languages, but has grown to become one of Python’s 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 that’s common in this domain can run dramatically faster in PyPy—often 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, you’ll 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 components—minimally, 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 Programmer’s 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('hello world')

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 you’ve typed these statements into a text file, you must tell Python to execute the file—which simply means to run all the statements in the file from top to bottom, one after another. As you’ll 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, you’ll see the results of the two print statements show up somewhere on your computer—by default, usually in the same window you were in when you ran the program:

hello world


Python’s 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, it’s 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 you’ve run a few programs alongside the corresponding source code files—that is, in the same directories. For instance, you’ll 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; it’s always present as part of the Python system, and it’s the component that truly runs your scripts. Technically, it’s 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 language—CPython, 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 Microsoft’s .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 section’s Stackless Python systems and its microthreads to support massive concurrency.

1 Mark Lutz. Learning Python. Fifth Edition. O’Reilly Media Inc. 2013.


А также другие работы, которые могут Вас заинтересовать

64616. Анализ показателей финансовой устойчивости закрытого акционерного общества «НК «Лукойл» 86.32 KB
  В рыночных условиях гарантом выживаемости и основой устойчивого положения предприятия является его финансовая устойчивость. С его помощью вырабатываются стратегия и тактика развития предприятия обосновываются планы и управленческие решения осуществляется контроль...
64617. Расчет широкополосного усилителя 724.71 KB
  Такие усилители применяются для усиления синусоидальных сигналов и для усиления импульсов. Основным требованием предъявляемым к ШУ является равномерность усиления сигнала в заданном частотном диапазоне.
64618. Правовые основы денежного обращения в России 47.33 KB
  Цель работы изучить денежно-кредитное регулирование в России. Задачи данной работы: раскрыть понятие денежной системы; рассмотреть правовые основы денежного обращения в России.
64619. Статистический анализ производства продукции растениеводства ООО «Николаевское» 50.45 KB
  Цель данной курсовой работы состоит в том, чтобы рассмотреть современный менеджмент, на роль человека в деятельности организации. и раскрыть в данной теме содержание управления персоналом в организации.
64620. Контроллинг в системе управления 610.1 KB
  Концепции системы контроллинга и инструментарий. Оперативный и стратегический контроллинга в процессе планирования на предприятии. Взаимосвязь стратегического и оперативного контроллинга в процессе планирования на предприятии.
64621. Мотивации в управлении персоналом 72.85 KB
  Но это не означает что на мотивации персонала тоже надо экономить потому как хорошо обученный мотивированный и организованный персонал определяет судьбу предприятия. В то же время теоретические аспекты построения механизмов мотивации нуждаются в дальнейшей разработке.
64622. Предложения по совершенствованию классификации затрат и по их снижению в ООО «Лентал» 113.58 KB
  Анализ издержек помогает выяснить их эффективность установить не будут ли они чрезмерными проверить качественные показатели работы правильно установить цены регулировать и контролировать расходы планировать уровень прибыли и рентабельности производства.
64623. Анализ дебиторской задолжности: цель, задачи, информационная обеспеченность 111.12 KB
  Неизбежным следствием существующей в настоящее время системы денежных расчетов между организациями является дебиторская задолженность, при которой всегда имеется разрыв времени платежа с моментом перехода права собственности на товар...
64624. Решение конечного разностного уравнения третьего порядка 86.55 KB
  Колмогоров один из основоположников современной теории вероятностей им получены фундаментальные результаты в топологии математической логике теории турбулентности теории сложности алгоритмов и ряде других областей математики и её приложений.