text
stringlengths
313
1.33M
# Python Programming/Creating Python programs Welcome to Python! This tutorial will show you how to start writing programs. Python programs are nothing more than text files, and they may be edited with a standard text editor program.[^1] What text editor you use will probably depend on your operating system: any text editor can create Python programs. However, it is easier to use a text editor that includes Python syntax highlighting. ## Hello, World The very first program that beginning programmers usually write or learn is the \"Hello, World!\" program. This program simply outputs the phrase \"Hello, World!\" then terminates itself. Let\'s write \"Hello, World!\" in Python! Open up your text editor and create a new file called `hello.py` containing just this line (you can copy-paste if you want): ``` python print('Hello, World!') ``` The below line is used for Python 3.x.x ``` python print("Hello, World!") ``` You can also put the below line to pause the program at the end until you press anything. ``` python input() ``` This program uses the `print` function, which simply outputs its parameters to the terminal. By default, `print` appends a `newline` character to its output, which simply moves the cursor to the next line. Now that you\'ve written your first program, let\'s run it in Python! This process differs slightly depending on your operating system. ### Windows - Create a folder on your computer to use for your Python programs, such as `C:\pythonpractice`, and save your `hello.py` program in that folder. - In the Start menu, select \"Run\...\", and type in `cmd`. This will cause the Windows terminal to open. - Type `cd \pythonpractice` to **c**hange **d**irectory to your `pythonpractice` folder, and hit Enter. - Type `hello.py` to run your program! If it didn\'t work, make sure your PATH contains the python directory. See Getting Python. ### Mac - Create a folder on your computer to use for your Python programs. A good suggestion would be to name it `pythonpractice` and place it in your Home folder (the one that contains folders for Documents, Movies, Music, Pictures, etc). Save your `hello.py` program into it. Open the Applications folder, go into the Utilities folder, and open the Terminal program. - Type `cd pythonpractice` to **c**hange **d**irectory to your `pythonpractice` folder, and hit Enter. - Type `python ./hello.py` to run your program! ### Linux - Create a folder on your computer to use for your Python programs, such as `~/pythonpractice`, and save your `hello.py` program in that folder. - Open up the terminal program. In KDE, open the main menu and select \"Run Command\...\" to open . In GNOME, open the main menu, open the Applications folder, open the Accessories folder, and select Terminal. - Type `cd ~/pythonpractice` to **c**hange **d**irectory to your `pythonpractice` folder, and hit Enter. - Don\'t forget to make the script executable by chmod +x. - Type `python ./hello.py` to run your program! ### Linux (advanced) - Create a folder on your computer to use for your Python programs, such as `~/pythonpractice`. ```{=html} <!-- --> ``` - Open up your favorite text editor and create a new file called `hello.py` containing just the following 2 lines (you can copy-paste if you want):`<ref>`{=html} A Quick Introduction to Unix/My First Shell Script explains what a hash bang line does. ```{=html} </ref> ``` ``` python #! /usr/bin/python print('Hello, world!') ``` - save your `hello.py` program in the `~/pythonpractice` folder. - Open up the terminal program. In KDE, open the main menu and select \"Run Command\...\" to open Konsole. In GNOME, open the main menu, open the Applications folder, open the Accessories folder, and select Terminal. - Type `cd ~/pythonpractice` to **c**hange **d**irectory to your `pythonpractice` folder, and hit Enter. - Type `chmod a+x hello.py` to tell Linux that it is an executable program. - Type `./hello.py` to run your program! - In addition, you can also use `ln -s hello.py /usr/bin/hello` to make a **s**ymbolic **l**i**n**k `hello.py` to `/usr/bin` under the name `hello`, then run it by simply executing `hello`. Note that this mainly should be done for complete, compiled programs, if you have a script that you made and use frequently, then it might be a good idea to put it somewhere in your home directory and put a link to it in /usr/bin. If you want a playground, a good idea is to invoke `mkdir ~/.local/bin` and then put scripts in there. To make \~/.local/bin content executable the same way /usr/bin does type `$PATH = $PATH:~/local/bin` (you can add this line to your shell rc file, for example \~/.bashrc). ### Result The program should print: `Hello, world!` Congratulations! You\'re well on your way to becoming a Python programmer. ## Exercises 1. Modify the `hello.py` program to say hello to someone from your family or your friends (or to Ada Lovelace). 2. Change the program so that after the greeting, it asks, \"How did you get here?\". 3. Re-write the original program to use two `print` statements: one for \"Hello\" and one for \"world\". The program should still only print out on one line. Solutions ## Notes ```{=html} <references /> ``` \_\_NOTOC\_\_ [^1]: Sometimes, Python programs are distributed in compiled form. We won\'t have to worry about that for quite a while.
# Python Programming/Variables and Strings In this section, you will be introduced to two different kinds of data in Python: variables and strings. Please follow along by running the included programs and examining their output. ## Variables A *variable* is something that holds a value that may change. In simplest terms, a variable is just a box that you can put stuff in. You can use variables to store all kinds of stuff, but for now, we are just going to look at storing numbers in variables. ``` python lucky = 7 print (lucky) 7 ``` This code creates a variable called `lucky`, and assigns to it the integer number `7`. When we ask Python to tell us what is stored in the variable `lucky`, it returns that number again. We can also change what is inside a variable. For example: ``` python changing = 3 print (changing) 3 changing = 9 print (changing) 9 different = 12 print (different) 12 print (changing) 9 changing = 15 print (changing) 15 ``` We declare a variable called `changing`, put the integer `3` in it, and verify that the assignment was properly done. Then, we assign the integer `9` to `changing`, and ask again what is stored in `changing`. Python has thrown away the `3`, and has replaced it with `9`. Next, we create a second variable, which we call `different`, and put `12` in it. Now we have two independent variables, `different` and `changing`, that hold different information, i.e., assigning a new value to one of them is not affecting the other. You can also assign the value of a variable to be the value of another variable. For example: ``` python red = 5 blue = 10 print (red, blue) 5 10 yellow = red print (yellow, red, blue) 5 5 10 red = blue print (yellow, red, blue) 5 10 10 ``` To understand this code, keep in mind that the **name** of the variable is always on the left side of the equals sign (the assignment operator), and the **value** of the variable is on the right side of the equals sign. First the name, then the value. We start out declaring that `red` is `5`, and `blue` is `10`. As you can see, you can pass several arguments to `print` to tell it to print multiple items on one line, separating them by spaces. As expected, Python reports that `red` stores `5`, and `blue` holds `10`. Now we create a third variable, called `yellow`. To set its value, we tell Python that we want `yellow` to be whatever `red` is. (Remember: name to the left, value to the right.) Python knows that `red` is `5`, so it also sets `yellow` to be `5`. Now we\'re going to take the `red` variable, and set it to the value of the `blue` variable. Don\'t get confused --- name on the left, value on the right. Python looks up the value of `blue`, and finds that it is `10`. So, Python throws away `red`\'s old value (`5`), and replaces it with `10`. After this assignment Python reports that `yellow` is `5`, `red` is `10`, and `blue` is `10`. But didn\'t we say that `yellow` should be whatever value `red` is? The reason that `yellow` is still `5` when `red` is `10`, is because we only said that `yellow` should be whatever `red` is *at the moment of the assignment.* After Python has figured out what `red` is and assigned that value to `yellow`, `yellow` doesn\'t care about `red` any more. `yellow` has a value now, and that value is going to stay the same no matter what happens to `red`. For the **name** of the variable, it can only consist of uppercase and lowercase letters (A-Z, a-z), digits (0-9), and the underscore character (\_), and the *first* character of the name *cannot* be a digit. For example, `1abc` and `_#$ad` are *not* valid variable names, while `_123` and `a__bc` are valid variable names. ## String A \'string\' is simply a list of characters in order. A *character* is anything you can type on the keyboard in one keystroke, like a letter, a number, or a backslash. For example, \"`hello`\" is a string. It is five characters long --- `h`, `e`, `l`, `l`, `o`. Strings can also have spaces: \"`hello world`\" contains 11 characters: 10 letters and the space between \"`hello`\" and \"`world`\". There are no limits to the number of characters you can have in a string --- you can have anywhere from one to a million or more. You can even have a string that has 0 characters, which is usually called an \"empty string.\" There are three ways you can declare a string in Python: single quotes (`'`), double quotes (`"`), and triple quotes (`"""`). **In all cases, you start and end the string with your chosen string declaration.** For example: ``` python >>> print ('I am a single quoted string') I am a single quoted string >>> print ("I am a double quoted string") I am a double quoted string >>> print ("""I am a triple quoted string""") I am a triple quoted string ``` You can use quotation marks within strings by placing a backslash directly before them, so that Python knows you want to include the quotation marks in the string, instead of ending the string there. Placing a backslash directly before another symbol like this is known as *escaping* the symbol. ``` python >>> print ("So I said, \"You don't know me! You'll never understand me!\"") So I said, "You don't know me! You'll never understand me!" >>> print ('So I said, "You don\'t know me! You\'ll never understand me!"') So I said, "You don't know me! You'll never understand me!" >>> print ("""The double quotation mark (\") is used to indicate direct quotations.""") The double quotation mark (") is used to indicate direct quotations. ``` If you want to include a backslash in a string, you have to escape said backslash. This tells Python that you want to include the backslash in the string, instead of using it as an escape character. For example: ``` python >>> print ("This will result in only three backslashes: \\ \\ \\") This will result in only three backslashes: \ \ \ ``` As you can see from the above examples, only the specific character used to quote the string needs to be escaped. This makes for more readable code. To see how to use strings, let\'s go back for a moment to an old, familiar program: ``` python >>> print("Hello, world!") Hello, world! ``` Look at that! You\'ve been using strings since the very beginning! You can add two strings together using the `+` operator: this is called *concatenating* them. ``` python >>> print ("Hello, " + "world!") Hello, world! ``` Notice that there is a space at the end of the first string. If you don\'t put that in, the two words will run together, and you\'ll end up with `Hello,world!` You can also repeat strings by using the `*` operator, like so: ``` python >>> print ("bouncy " * 5) bouncy bouncy bouncy bouncy bouncy >>> print ("bouncy " * 10) bouncy bouncy bouncy bouncy bouncy bouncy bouncy bouncy bouncy bouncy ``` The string `bouncy` gets repeated 5 times in the 1st example and 10 times in the 2nd. If you want to find out how long a string is, you use the `len()` function, which simply takes a string and counts the number of characters in it. (`len` stands for \"length.\") Just put the string that you want to find the length of *inside* the parentheses of the function. For example: ``` python >>> print (len("Hello, world!")) 13 ``` ## Strings and Variables Now that you\'ve learned about variables and strings separately, let\'s see how they work together. Variables can store much more than just numbers. You can also use them to store strings! Here\'s how: ``` python question = "What did you have for lunch?" print (question) What did you have for lunch? ``` In this program, we are creating a variable called `question`, and storing the string \"`What did you have for lunch?`\" in it. Then, we just tell Python to print out whatever is inside the `question` variable. Notice that when we tell Python to print out `question`, there are **no quotation marks** around the word `question`: this tells Python that we are using a variable, not a string. If we put in quotation marks around `question`, Python would treat it as a string, as shown below: ``` python question = "What did you have for lunch?" print ("question") question ``` Let\'s try something different. Sure, it\'s all fine and dandy to ask the user what they had for lunch, but it doesn\'t make much difference if they can\'t respond! Let\'s edit this program so that the user can type in what they ate. ``` python question = "What did you have for lunch?" print (question) answer = raw_input() #You should use "input()" in python 3.x, because python 3.x doesn't have a function named "raw_input". print ("You had " + answer + "! That sounds delicious!") ``` To ask the user to write something, we used a function called `raw_input()`, which waits until the user writes something and presses enter, and then returns what the user wrote. Don\'t forget the parentheses! Even though there\'s nothing inside of them, they\'re still important, and Python will give you an error if you don\'t put them in. You can also use a different function called `input()`, which works in nearly the same way. We will learn the differences between these two functions later. In this program, we created a variable called `answer`, and put whatever the user wrote into it. Then, we print out a new string, which contains whatever the user wrote. Notice the extra space at the end of the \"`You had`\" string, and the exclamation mark at the start of the \"`! That sounds delicious!`\" string. They help format the output and make it look nice, so that the strings don\'t all run together. ## Combining Numbers and Strings Take a look at this program, and see if you can figure out what it\'s supposed to do. ``` python print ("Please give me a number: ") number = raw_input() plusTen = number + 10 print ("If we add 10 to your number, we get " + plusTen) ``` This program should take a number from the user, add 10 to it, and print out the result. But if you try running it, it won\'t work! You\'ll get an error that looks like this: `Traceback (most recent call last):`\ `  File "test.py", line 5, in ``<module>`{=html}\ `    print "If we add 10 to your number, we get " + plusTen`\ `TypeError: cannot concatenate 'str' and 'int' objects` What\'s going on here? Python is telling us that there is a `TypeError`, which means there is a problem with the types of information being used. Specifically, Python can\'t figure out how to reconcile the two types of data that are being used simultaneously: integers and strings. For example, Python thinks that the `number` variable is holding a string, instead of a number. If the user enters `15`, then `number` will contain a string that is two characters long: a `1`, followed by a `5`. So how can we tell Python that `15` should be a number, instead of a string? Also, when printing out the answer, we are telling Python to concatenate together a string (\"`If we add 10 to your number, we get`\") and a number (`plusTen`). Python doesn\'t know how to do that \-- it can only concatenate strings together. How do we tell Python to treat a number as a string, so that we can print it out with another string? Luckily, there are two functions that are perfect solutions for these problems. The `int()` function will take a string and turn it into an integer, while the `str()` function will take an integer and turn it into a string. In both cases, we put what we want to change inside the parentheses. Therefore, our modified program will look like this: ``` python print ("Please give me a number:",) response = raw_input() number = int(response) plusTen = number + 10 print ("If we add 10 to your number, we get " + str(plusTen)) ``` That\'s all you need to know about strings and variables! We\'ll learn more about types later. ## List of Learned Functions - **`print()`**: Print the output information to the user - **`input()`** or **`raw_input()`**: asks the user for a response, and returns that response. (Note that in version 3.x **`raw_input()`** does not exist and has been replaced by **`input()`**) - **`len()`**: returns the length of a string (number of characters) - **`str()`**: returns the string representation of an object - **`int()`**: given a string or number, returns an integer ## Exercises 1. Write a program that asks the user to type in a string, and then tells the user how long that string was. 2. Ask the user for a string, and then for a number. Print out that string, that many times. (For example, if the string is `hello` and the number is `3` you should print out `hello hello hello`.) 3. What would happen if a mischievous user typed in a word when you ask for a number? Try it. Solutions `<span style="font-size: 14pt;">`{=html}Quiz`</span>`{=html}
# Python Programming/Basic syntax There are five fundamental concepts in Python. ### Semicolons Python does not normally use semicolons, but they are allowed to separate statements on the same line, if your code has semicolons; your code isn\'t \"Pythonic\" ### Case Sensitivity All variables are case-sensitive. Python treats \'number\' and \'Number\' as separate, unrelated entities. ### Spaces and tabs don\'t mix Instead of block delimiters (braces → \"{}\" in the C family of languages), indentation is used to indicate where blocks begin and end. Because whitespace is significant, remember that spaces and tabs don\'t mix, so use only one or the other when indenting your programs. A common error is to mix them. While they may look the same in editor, the interpreter will read them differently and it will result in either an error or unexpected behavior. Most decent text editors can be configured to let tab key emit spaces instead. Python\'s Style Guideline described that the preferred way is using 4 spaces. Tips: If you invoked python from the command-line, you can give -t or -tt argument to python to make python issue a warning or error on inconsistent tab usage. ``` bash pythonprogrammer@wikibook:~$ python -tt myscript.py ``` This will issue an error if you have mixed spaces and tabs. ### Objects In Python, like all object-oriented languages, there are aggregations of code and data called *objects*, which typically represent the pieces in a conceptual model of a system. Objects in Python are created (i.e., instantiated) from templates called *classes* (which are covered later, as much of the language can be used without understanding classes). They have *attributes*, which represent the various pieces of code and data which make up the object. To access attributes, one writes the name of the object followed by a period (henceforth called a dot), followed by the name of the attribute. An example is the \'upper\' attribute of strings, which refers to the code that returns a copy of the string in which all the letters are uppercase. To get to this, it is necessary to have a way to refer to the object (in the following example, the way is the literal string that constructs the object). ``` python 'bob'.upper ``` Code attributes are called *methods*. So in this example, upper is a method of \'bob\' (as it is of all strings). To execute the code in a method, use a matched pair of parentheses surrounding a comma separated list of whatever arguments the method accepts (upper doesn\'t accept any arguments). So to find an uppercase version of the string \'bob\', one could use the following: ``` python 'bob'.upper() ``` ### Scope In a large system, it is important that one piece of code does not affect another in difficult to predict ways. One of the simplest ways to further this goal is to prevent one programmer\'s choice of a name from blocking another\'s use of that name. The concept of scope was invented to do this. A scope is a \"region\" of code in which a name can be used and outside of which the name cannot be easily accessed. There are two ways of delimiting regions in Python: with functions or with modules. They each have different ways of accessing from outside the scope useful data that was produced within the scope. With functions, that way is to return the data. The way to access names from other modules leads us to another concept. ### Namespaces It would be possible to teach Python without the concept of namespaces because they are so similar to attributes, which we have already mentioned, but the concept of namespaces is one that transcends any particular programming language, and so it is important to teach. To begin with, there is a built-in function **`dir()`** that can be used to help one understand the concept of namespaces. When you first start the Python interpreter (i.e., in interactive mode), you can list the objects in the current (or default) namespace using this function. ``` python Python 2.3.4 (#53, Oct 18 2004, 20:35:07) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> dir() ['__builtins__', '__doc__', '__name__'] ``` This function can also be used to show the names available within a module\'s namespace. To demonstrate this, first we can use the **`type()`** function to show what kind of object \_\_builtins\_\_ is: ``` python >>> type(__builtins__) <type 'module'> ``` Since it is a module, it has a namespace. We can list the names within the \_\_builtins\_\_ namespace, again using the **`dir()`** function (note that the complete list of names has been abbreviated): ``` python >>> dir(__builtins__) ['ArithmeticError', ... 'copyright', 'credits', ... 'help', ... 'license', ... 'zip'] >>> ``` Namespaces are a simple concept. A namespace is a particular place in which names specific to a module reside. Each name within a namespace is distinct from names outside of that namespace. This layering of namespaces is called scope. A name is placed within a namespace when that name is given a value. For example: ``` python >>> dir() ['__builtins__', '__doc__', '__name__'] >>> name = "Bob" >>> import math >>> dir() ['__builtins__', '__doc__', '__name__', 'math', 'name'] ``` Note that I was able to add the \"name\" variable to the namespace using a simple assignment statement. The import statement was used to add the \"math\" name to the current namespace. To see what math is, we can simply: ``` python >>> math <module 'math' (built-in)> ``` Since it is a module, it also has a namespace. To display the names within this namespace, we: ``` python >>> dir(math) ['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] >>> ``` If you look closely, you will notice that both the default namespace and the math module namespace have a \'\_\_name\_\_\' object. The fact that each layer can contain an object with the same name is what scope is all about. To access objects inside a namespace, simply use the name of the module, followed by a dot, followed by the name of the object. This allows us to differentiate between the `__name__` object within the current namespace, and that of the object with the same name within the `math` module. For example: ``` python >>> print (__name__) __main__ >>> print (math.__name__) math >>> print (math.__doc__) This module is always available. It provides access to the mathematical functions defined by the C standard. >>> print (math.pi) 3.1415926535897931 ```
# Python Programming/Sequences Sequences allow you to store multiple values in an organized and efficient fashion. There are seven sequence types: strings, bytes, lists, tuples, bytearrays, buffers, and range objects. Dictionaries and sets are containers for sequential data. ## Strings We already covered strings, but that was before you knew what a sequence is. In other languages, the elements in arrays and sometimes the characters in strings may be accessed with the square brackets, or subscript operator. This works in Python too: ``` python >>> "Hello, world!"[0] 'H' >>> "Hello, world!"[1] 'e' >>> "Hello, world!"[2] 'l' >>> "Hello, world!"[3] 'l' >>> "Hello, world!"[4] 'o' ``` Indexes are numbered from 0 to n-1 where n is the number of items (or characters), and they are given to the characters from the start of the string: H e l l o , w o r l d ! 0 1 2 3 4 5 6 7 8 9 10 11 12 Negative indexes (numbered from -1 to -n) are counted from the end of the string: H e l l o , w o r l d ! -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 ``` python >>> "Hello, world!"[-2] 'd' >>> "Hello, world!"[-9] 'o' >>> "Hello, world!"[-13] 'H' >>> "Hello, world!"[-1] '!' ``` If the number given in the bracket is less than -n or greater than n-1, then we will get an IndexError. But in Python, the colon : allows the square brackets to take two numbers. For any sequence which only uses numeric indexes, this will return the portion which is between the specified indexes. This is known as \"slicing\" and the result of slicing a string is often called a \"substring.\" ``` python >>> "Hello, world!"[3:9] 'lo, wo' >>> string = "Hello, world!" >>> string[:5] 'Hello' >>> string[-6:-1] 'world' >>> string[-9:] 'o, world!' >>> string[:-8] 'Hello' >>> string[:] 'Hello, world!' ``` As demonstrated above, if the first and second number is omitted, then they take their default values, which are 0 and n-1 respectively, corresponding to the beginning and end of the sequence respectively (in this case). Note also that the brackets are inclusive on the left but *exclusive* on the right: in the first example above with \[3:9\] the character at index 3, \'l\', is included while the character at index 9, \'r\', is excluded. We can add a third number in the bracket, by adding one more colon in the bracket, which indicates the *increment step* of the slicing: ``` python >>> s = "Hello, world!" >>> s[3:9:2] #returns the substring s[3]s[5]s[7] 'l,w' >>> s[3:6:3] #returns the substring s[3] 'l' >>> s[:5:2] #returns the substring s[0]s[2]s[4] 'Hlo' >>> s[::-1] #returns the reverted string '!dlrow ,olleH' >>> s[::-2] #returns the substring s[-1]s[-3]s[-5]s[-7]s[-9]s[-11]s[-13] '!lo olH' ``` The increment step can be positive or negative. For positive increment step, the slicing is from left to right, and for negative increment step, the slicing is from right to left. Also, we should aware that - the default value of the increment step is 1 ```{=html} <!-- --> ``` - the default value for the first and second number becomes -1 (or n) and -n (or 0) respectively, when the increment step is negative (same default value as above when the increment step is positive) - the increment step cannot be 0 ## Lists A list is just what it sounds like: a list of values, organized in order. A list is created using square brackets. For example, an empty list would be initialized like this: ``` python spam = [] ``` The values of the list are separated by commas. For example: ``` python spam = ["bacon", "eggs", 42] ``` Lists may contain objects of varying types. It may hold both the strings \"eggs\" and \"bacon\" as well as the number 42. Like characters in a string, items in a list can be accessed by indexes starting at 0. To access a specific item in a list, you refer to it by the name of the list, followed by the item\'s number in the list inside brackets. For example: ``` python >>> spam ['bacon', 'eggs', 42] >>> spam[0] 'bacon' >>> spam[1] 'eggs' >>> spam[2] 42 ``` You can also use negative numbers, which count backwards from the end of the list: ``` python >>> spam[-1] 42 >>> spam[-2] 'eggs' >>> spam[-3] 'bacon' ``` The `len()` function also works on lists, returning the number of items in the array: ``` python >>> len(spam) 3 ``` Note that the `len()` function counts the number of item inside a list, so the last item in spam (42) has the index (len(spam) - 1). The items in a list can also be changed, just like the contents of an ordinary variable: ``` python >>> spam = ["bacon", "eggs", 42] >>> spam ['bacon', 'eggs', 42] >>> spam[1] 'eggs' >>> spam[1] = "ketchup" >>> spam ['bacon', 'ketchup', 42] ``` (Strings, being *immutable*, are impossible to modify.) As with strings, lists may be sliced: ``` python >>> spam[1:] ['eggs', 42] >>> spam[:-1] ['bacon', 'eggs'] ``` It is also possible to add items to a list. There are many ways to do it, the easiest way is to use the append() method of list: ``` python >>> spam.append(10) >>> spam ['bacon', 'eggs', 42, 10] ``` Note that you cannot manually insert an element by specifying the index outside of its range. The following code would fail: ``` python >>> spam[4] = 10 IndexError: list assignment index out of range ``` Instead, you must use the insert() function. If you want to insert an item inside a list at a certain index, you may use the insert() method of list, for example: ``` python >>> spam.insert(1, 'and') >>> spam ['bacon', 'and', 'eggs', 42, 10] ``` You can also delete items from a list using the `del` statement: ``` python >>> spam ['bacon', 'and', 'eggs', 42, 10] >>> del spam[1] >>> spam ['bacon', 'eggs', 42, 10] >>> spam[0] 'bacon' >>> spam[1] 'eggs' >>> spam[2] 42 >>> spam[3] 10 ``` As you can see, the list re-orders itself, so there are no gaps in the numbering. Lists have an unusual characteristic. Given two lists a and b, if you set b to a, and change a, b will also be changed. ``` python >>> a=[2, 3, 4, 5] >>> b=a >>> del a[3] >>> print(a) [2, 3, 4] >>> print(b) [2, 3, 4] ``` This can easily be worked around by using `b=a[:]` instead. For further explanation on lists, or to find out how to make 2D arrays, see Data Structure/Lists ## Tuples Tuples are similar to lists, except they are immutable. Once you have set a tuple, there is no way to change it whatsoever: you cannot add, change, or remove elements of a tuple. Otherwise, tuples work identically to lists. To declare a tuple, you use commas: ``` python unchanging = "rocks", 0, "the universe" ``` It is often necessary to use parentheses to differentiate between different tuples, such as when doing multiple assignments on the same line: ``` python foo, bar = "rocks", 0, "the universe" # 3 elements here foo, bar = "rocks", (0, "the universe") # 2 elements here because the second element is a tuple ``` Unnecessary parentheses can be used without harm, but nested parentheses denote nested tuples: ``` python >>> var = "me", "you", "us", "them" >>> var = ("me", "you", "us", "them") ``` both produce: ``` python >>> print(var) ('me', 'you', 'us', 'them') ``` but: ``` python >>> var = ("me", "you", ("us", "them")) >>> print(var) ('me', 'you', ('us', 'them')) # A tuple of 3 elements, the last of which is itself a tuple. ``` For further explanation on tuple, see *Data Structure/Tuples* ## Dictionaries Dictionaries are also like lists, and they are mutable \-- you can add, change, and remove elements from a dictionary. However, the elements in a dictionary are not bound to numbers, the way a list is. Every element in a dictionary has two parts: a key, and a value. Calling a key of a dictionary returns the value linked to that key. You could consider a list to be a special kind of dictionary, in which the key of every element is a number, in numerical order. Dictionaries are declared using curly braces, and each element is declared first by its key, then a colon, and then its value. For example: ``` python >>> definitions = {"guava": "a tropical fruit", "python": "a programming language", "the answer": 42} >>> definitions {'python': 'a programming language', 'the answer': 42, 'guava': 'a tropical fruit'} >>> definitions["the answer"] 42 >>> definitions["guava"] 'a tropical fruit' >>> len(definitions) 3 ``` Also, adding an element to a dictionary is much simpler: simply declare it as you would a variable. ``` python >>> definitions["new key"] = "new value" >>> definitions {'python': 'a programming language', 'the answer': 42, 'guava': 'a tropical fruit', 'new key': 'new value'} ``` For further explanation on dictionary, see *Data Structure/Dictionaries* ## Sets Sets are just like lists except that they are **unordered** and they do not allow duplicate values. Elements of a set are neither bound to a number (like list and tuple) nor to a key (like dictionary). The reason for using a set over other data types is that a set is much faster for a large number of items than a list or tuple and sets provide fast data insertion, deletion, and membership testing. Sets also support mathematical set operations such as testing for subsets and finding the union or intersection of two sets. ``` python >>> mind = set([42, 'a string', (23, 4)]) #equivalently, we can use {42, 'a string', (23, 4)} >>> mind set([(23, 4), 42, 'a string']) ``` ``` python >>> mind = set([42, 'a string', 40, 41]) >>> mind set([40, 41, 42, 'a string']) >>> mind = set([42, 'a string', 40, 0]) >>> mind set([40, 0, 42, 'a string']) >>> mind.add('hello') >>> mind set([40, 0, 42, 'a string', 'hello']) ``` Note that sets are unordered, items you add into sets will end up in an indeterminable position, and it may also change from time to time. ``` python >>> mind.add('duplicate value') >>> mind.add('duplicate value') >>> mind set([0, 'a string', 40, 42, 'hello', 'duplicate value']) ``` Sets cannot contain a single value more than once. Unlike lists, which can contain anything, the types of data that can be included in sets are restricted. A set can only contain hashable, immutable data types. Integers, strings, and tuples are hashable; lists, dictionaries, and other sets (except frozensets, see below) are not. ### Frozenset The relationship between frozenset and set is like the relationship between tuple and list. Frozenset is an immutable version of set. An example: ``` python >>> frozen=frozenset(['life','universe','everything']) >>> frozen frozenset(['universe', 'life', 'everything']) ``` ## Other data types Python also has other types of sequences, though these are used less frequently and need to be imported from the standard library before being used. We will only brush over them here. array: A typed-list, an array may only contain homogeneous values.\ collections.defaultdict: A dictionary that, when an element is not found, returns a default value instead of error.\ collections.deque: A double ended queue, allows fast manipulation on both sides of the queue.\ heapq: A priority queue.\ Queue: A thread-safe multi-producer, multi-consumer queue for use with multi-threaded programs. Note that a list can also be used as queue in a single-threaded code. For further explanation on set, see *Data Structure/Sets* ### 3rd party data structure Some useful data types in Python do not come in the standard library. Some of these are very specialized in their use. We will mention some of the more well known 3rd party types. numpy.array: useful for heavy number crunching =\> see numpy section\ sorteddict: like the name says, a sorted dictionary ## Exercises 1. Write a program that puts 5, 10, and \"twenty\" into a list. Then remove 10 from the list. 2. Write a program that puts 5, 10, and \"twenty\" into a tuple. 3. Write a program that puts 5, 10, and \"twenty\" into a set. Put \"twenty\", 10, and 5 into another set purposefully in a different order. Print both of them out and notice the ordering. 4. Write a program that constructs a tuple, one element of which is a frozenset. 5. Write a program that creates a dictionary mapping 1 to \"Monday,\" 2 to \"Tuesday,\" etc. ## External links - Sequence Types --- list, tuple, range in The Python Library Reference, docs.python.org
# Python Programming/Data types Data types determine whether an object can do something, or whether it just would not make sense. Other programming languages often determine whether an operation makes sense for an object by making sure the object can never be stored somewhere where the operation will be performed on the object (this type system is called static typing). Python does not do that. Instead it stores the type of an object with the object, and checks when the operation is performed whether that operation makes sense for that object (this is called dynamic typing). ##### Built-in Data types Python\'s built-in (or standard) data types can be grouped into several classes. Sticking to the hierarchy scheme used in the official Python documentation these are **numeric types, sequences, sets and mappings** (and a few more not discussed further here). Some of the types are only available in certain versions of the language as noted below. - boolean: the type of the built-in values `True` and `False`. Useful in conditional expressions, and anywhere else you want to represent the truth or falsity of some condition. Mostly interchangeable with the integers 1 and 0. In fact, conditional expressions will accept values of any type, treating special ones like boolean `False`, integer 0 and the empty string `""` as equivalent to `False`, and all other values as equivalent to `True`. Numeric types: - int: Integers; equivalent to C longs in Python 2.x, non-limited length in Python 3.x - long: Long integers of non-limited length; exists only in Python 2.x - float: Floating-Point numbers, equivalent to C doubles - complex: Complex Numbers Sequences: - str: String; represented as a sequence of 8-bit characters in Python 2.x, but as a sequence of Unicode characters (in the range of U+0000 - U+10FFFF) in Python 3.x - bytes: a sequence of integers in the range of 0-255; only available in Python 3.x - byte array: like bytes, but mutable (see below); only available in Python 3.x - list - tuple Sets: - set: an unordered collection of unique objects; available as a standard type since Python 2.6 - frozen set: like set, but immutable (see below); available as a standard type since Python 2.6 Mappings: - dict: Python dictionaries, also called hashmaps or associative arrays, which means that an element of the list is associated with a definition, rather like a Map in Java\ Some others, such as type and callables ##### Mutable vs Immutable Objects In general, data types in Python can be distinguished based on whether objects of the type are mutable or immutable. The content of objects of immutable types cannot be changed after they are created. +-------------------------+----------------------+ | Some *immutable* types | Some *mutable* types | +=========================+======================+ | - int, float, complex | - array | | - str | - bytearray | | - bytes | - list | | - tuple | - set | | - frozenset | - dict | | - bool | | +-------------------------+----------------------+ Only mutable objects support methods that change the object in place, such as reassignment of a sequence slice, which will work for lists, but raise an error for tuples and strings. It is important to understand that variables in Python are really just references to objects in memory. If you assign an object to a variable as below, ``` python a = 1 s = 'abc' l = ['a string', 456, ('a', 'tuple', 'inside', 'a', 'list')] ``` all you really do is make this variable (`a`, `s`, or `l`) point to the object (`1`, `'abc'`, `['a string', 456, ('a', 'tuple', 'inside', 'a', 'list')]`), which is kept somewhere in memory, as a convenient way of accessing it. If you reassign a variable as below ``` python a = 7 s = 'xyz' l = ['a simpler list', 99, 10] ``` you make the variable point to a different object (newly created ones in our examples). As stated above, only mutable objects can be changed in place (`l[0] = 1` is ok in our example, but `s[0] = 'a'` raises an error). This becomes tricky, when an operation is not explicitly asking for a change to happen in place, as is the case for the `+=` (increment) operator, for example. When used on an immutable object (as in `a += 1` or in `s += 'qwertz'`), Python will silently create a new object and make the variable point to it. However, when used on a mutable object (as in `l += [1,2,3]`), the object pointed to by the variable will be changed in place. While in most situations, you do not have to know about this different behavior, it is of relevance when several variables are pointing to the same object. In our example, assume you set `p = s` and `m = l`, then `s += 'etc'` and `l += [9,8,7]`. This will change `s` and leave `p` unaffected, but will change both `m` and `l` since both point to the same list object. Python\'s built-in `id()` function, which returns a unique object identifier for a given variable name, can be used to trace what is happening under the hood.\ Typically, this behavior of Python causes confusion in functions. As an illustration, consider this code: ``` python def append_to_sequence (myseq): myseq += (9,9,9) return myseq tuple1 = (1,2,3) # tuples are immutable list1 = [1,2,3] # lists are mutable tuple2 = append_to_sequence(tuple1) list2 = append_to_sequence(list1) print('tuple1 = ', tuple1) # outputs (1, 2, 3) print('tuple2 = ', tuple2) # outputs (1, 2, 3, 9, 9, 9) print('list1 = ', list1) # outputs [1, 2, 3, 9, 9, 9] print('list2 = ', list2) # outputs [1, 2, 3, 9, 9, 9] ``` This will give the above indicated, and usually unintended, output. `myseq` is a local variable of the `append_to_sequence` function, but when this function gets called, `myseq` will nevertheless point to the same object as the variable that we pass in (`t` or `l` in our example). If that object is immutable (like a tuple), there is no problem. The += operator will cause the creation of a new tuple, and `myseq` will be set to point to it. However, if we pass in a reference to a mutable object, that object will be manipulated in place (so `myseq` and `l`, in our case, end up pointing to the same list object). Links: - 3.1. Objects, values and types, The Python Language Reference, docs.python.org - 5.6.4. Mutable Sequence Types, The Python Standard Library, docs.python.org ##### Creating Objects of Defined Types Literal integers can be entered in three ways: - decimal numbers can be entered directly - hexadecimal numbers can be entered by prepending a 0x or 0X (0xff is hex FF, or 255 in decimal) - the format of octal literals depends on the version of Python: :\* Python 2.x: octals can be entered by prepending a 0 (0732 is octal 732, or 474 in decimal) :\* Python 3.x: octals can be entered by prepending a 0o or 0O (0o732 is octal 732, or 474 in decimal) Floating point numbers can be entered directly. Long integers are entered either directly (1234567891011121314151617181920 is a long integer) or by appending an L (0L is a long integer). Computations involving short integers that overflow are automatically turned into long integers. Complex numbers are entered by adding a real number and an imaginary one, which is entered by appending a j (i.e. 10+5j is a complex number. So is 10j). Note that j by itself does not constitute a number. If this is desired, use 1j. Strings can be either single or triple quoted strings. The difference is in the starting and ending delimiters, and in that single quoted strings cannot span more than one line. Single quoted strings are entered by entering either a single quote (\') or a double quote (\") followed by its match. So therefore `'foo' works, and`\ `"moo" works as well,`\ `     but`\ `'bar" does not work, and`\ `"baz' does not work either.`\ `"quux'' is right out.` Triple quoted strings are like single quoted strings, but can span more than one line. Their starting and ending delimiters must also match. They are entered with three consecutive single or double quotes, so `'''foo''' works, and`\ `"""moo""" works as well,`\ `     but`\ `'"'bar'"' does not work, and`\ `"""baz''' does not work either.`\ `'"'quux"'" is right out.` Tuples are entered in parentheses, with commas between the entries: ``` python (10, 'Mary had a little lamb') ``` Also, the parenthesis can be left out when it\'s not ambiguous to do so: ``` python 10, 'whose fleece was as white as snow' ``` Note that one-element tuples can be entered by surrounding the entry with parentheses and adding a comma like so: ``` python ('this is a singleton tuple',) ``` Lists are similar, but with brackets: ``` python ['abc', 1,2,3] ``` Dicts are created by surrounding with curly braces a list of key/value pairs separated from each other by a colon and from the other entries with commas: ``` python { 'hello': 'world', 'weight': 'African or European?' } ``` Any of these composite types can contain any other, to any depth: ``` python ((((((((('bob',),['Mary', 'had', 'a', 'little', 'lamb']), { 'hello' : 'world' } ),),),),),),) ``` ## Null object The Python analogue of null pointer known from other programming languages is *None*. *None* is not a null pointer or a null reference but an actual object of which there is only one instance. One of the uses of *None* is in default argument values of functions, for which see ../Functions#Default_Argument_Values. Comparisons to *None* are usually made using *is* rather than ==. Testing for None and assignment: ``` python if item is None: ... another = None if not item is None: ... if item is not None: # Also possible ... ``` Using None in a default argument value: ``` python def log(message, type = None): ... ``` PEP8 states that \"Comparisons to singletons like None should always be done with is or is not, never the equality operators.\" Therefore, \"if item == None:\" is inadvisable. A class can redefine the equality operator (==) such that instances of it will equal None. You can verify that None is an object by dir(None) or id(None). See also ../Operators/#Identity chapter. Links: - 4. Built-in Constants, docs.python.org - 3.11.7 The Null Object, docs.python.org - Python None comparison: should I use "is" or ==?, stackoverflow.com - PEP 0008 \-- Style Guide for Python Code, python.org ## Type conversion Type conversion in Python by example: ``` Python v1 = int(2.7) # 2 v2 = int(-3.9) # -3 v3 = int("2") # 2 v4 = int("11", 16) # 17, base 16 v5 = long(2) # Python 2.x only, not Python 3.x v6 = float(2) # 2.0 v7 = float("2.7") # 2.7 v8 = float("2.7E-2") # 0.027 v9 = float(False) # 0.0 vA = float(True) # 1.0 vB = str(4.5) # "4.5" vC = str([1, 3, 5]) # "[1, 3, 5]" vD = bool(0) # False; bool fn since Python 2.2.1 vE = bool(3) # True vF = bool([]) # False - empty list vG = bool([False]) # True - non-empty list vH = bool({}) # False - empty dict; same for empty tuple vI = bool("") # False - empty string vJ = bool(" ") # True - non-empty string vK = bool(None) # False vL = bool(len) # True vM = set([1, 2]) vN = set((1, 2)) # Converts any sequence, not just a list vO = set("abc") # {'c', 'b', 'a'} vP = set(b"abc") # {97, 98, 99} vQ = list(vM) vR = list({1: "a", 2: "b"}) # dict -> list of keys vS = tuple(vQ) vT = list("abc") # ['a', 'b', 'c'] print(v1, v2, v3, type(v1), type(v2), type(v3)) ``` Implicit type conversion: ``` Python int1 = 4 float1 = int1 + 2.1 # 4 converted to float # str1 = "My int:" + int1 # Error: no implicit type conversion from int to string str1 = "My int:" + str(int1) int2 = 4 + True # 5: bool is implicitly converted to int float2 = 4.5 + True # 5.5: True is converted to 1, which is converted to 1.0 ``` Keywords: type casting. Links: - 2. Built-in Functions \# bool, docs.python.org - 2. Built-in Functions \# list, docs.python.org - 2. Built-in Functions \# float, docs.python.org - 2. Built-in Functions \# int, docs.python.org - 2. Built-in Functions \# set, docs.python.org - 2. Built-in Functions \# str, docs.python.org - 2. Built-in Functions \# type, docs.python.org - 2. Built-in Functions \# tuple, docs.python.org ## Exercises 1. Write a program that instantiates a single object, adds \[1,2\] to the object, and returns the result. 1. Find an object that returns an output of the same length (if one exists?). 2. Find an object that returns an output length 2 greater than it started. 3. Find an object that causes an error. 2. Find two data types X and Y such that X = X + Y will cause an error, but X += Y will not.
# Python Programming/Numbers Python 2.x supports 4 built-in numeric types - int, long, float and complex. Of these, the long type has been dropped in Python 3.x - the int type is now of unlimited length by default. You don't have to specify what type of variable you want; Python does that automatically. - *Int:* The basic integer type in python, equivalent to the hardware \'c long\' for the platform you are using in Python 2.x, unlimited in length in Python 3.x. - *Long:* Integer type with unlimited length. In python 2.2 and later, Ints are automatically turned into long ints when they overflow. Dropped since Python 3.0, use int type instead. - *Float:* This is a binary floating point number. Longs and Ints are automatically converted to floats when a float is used in an expression, and with the true-division `/` operator. In CPython, floats are usually implemented using the C languages *double*, which often yields 52 bits of significand, 11 bits of exponent, and 1 sign bit, but this is machine dependent. - *Complex:* This is a complex number consisting of two floats. Complex literals are written as a + bj where a and b are floating-point numbers denoting the real and imaginary parts respectively. In general, the number types are automatically \'up cast\' in this order: Int → Long → Float → Complex. The farther to the right you go, the higher the precedence. ``` python >>> x = 5 >>> type(x) <type 'int'> >>> x = 187687654564658970978909869576453 >>> type(x) <type 'long'> >>> x = 1.34763 >>> type(x) <type 'float'> >>> x = 5 + 2j >>> type(x) <type 'complex'> ``` The result of divisions is somewhat confusing. In Python 2.x, using the / operator on two integers will return another integer, using floor division. For example, `5/2` will give you 2. You have to specify one of the operands as a float to get true division, e.g. `5/2.` or `5./2` (the dot specifies you want to work with float) will yield 2.5. Starting with Python 2.2 this behavior can be changed to true division by the future division statement `from __future__ import division`. In Python 3.x, the result of using the / operator is always true division (you can ask for floor division explicitly by using the // operator since Python 2.2). This illustrates the behavior of the / operator in Python 2.2+: ``` python >>> 5/2 2 >>> 5/2. 2.5 >>> 5./2 2.5 >>> from __future__ import division >>> 5/2 2.5 >>> 5//2 2 ``` For operations on numbers, see chapters ../Basic Math/ and ../Math/. ## Links - 5.4. Numeric Types --- int, float, long, complex, docs.python.org
# Python Programming/Strings ## Overview Strings in Python at a glance: ``` python str1 = "Hello" # A new string using double quotes str2 = 'Hello' # Single quotes do the same str3 = "Hello\tworld\n" # One with a tab and a newline str4 = str1 + " world" # Concatenation str5 = str1 + str(4) # Concatenation with a number str6 = str1[2] # 3rd character str6a = str1[-1] # Last character #str1[0] = "M" # No way; strings are immutable for char in str1: print(char) # For each character str7 = str1[1:] # Without the 1st character str8 = str1[:-1] # Without the last character str9 = str1[1:4] # Substring: 2nd to 4th character str10 = str1 * 3 # Repetition str11 = str1.lower() # Lowercase str12 = str1.upper() # Uppercase str13 = str1.rstrip() # Strip right (trailing) whitespace str14 = str1.replace('l','h') # Replacement list15 = str1.split('l') # Splitting if str1 == str2: print("Equ") # Equality test if "el" in str1: print("In") # Substring test length = len(str1) # Length pos1 = str1.find('llo') # Index of substring or -1 pos2 = str1.rfind('l') # Index of substring, from the right count = str1.count('l') # Number of occurrences of a substring print(str1, str2, str3, str4, str5, str6, str7, str8, str9, str10) print(str11, str12, str13, str14, list15) print(length, pos1, pos2, count) ``` See also chapter ../Regular Expression/ for advanced pattern matching on strings in Python. ## String operations ### Equality Two strings are equal if they have *exactly* the same contents, meaning that they are both the same length and each character has a one-to-one positional correspondence. Many other languages compare strings by identity instead; that is, two strings are considered equal only if they occupy the same space in memory. Python uses the `is` operator to test the identity of strings and any two objects in general. Examples: ``` python >>> a = 'hello'; b = 'hello' # Assign 'hello' to a and b. >>> a == b # check for equality True >>> a == 'hello' # True >>> a == "hello" # (choice of delimiter is unimportant) True >>> a == 'hello ' # (extra space) False >>> a == 'Hello' # (wrong case) False ``` ### Numerical There are two quasi-numerical operations which can be done on strings \-- addition and multiplication. String addition is just another name for concatenation, which is simply sticking the strings together. String multiplication is repetitive addition, or concatenation. So: ``` python >>> c = 'a' >>> c + 'b' 'ab' >>> c * 5 'aaaaa' ``` ### Containment There is a simple operator \'in\' that returns True if the first operand is contained in the second. This also works on substrings: ``` python >>> x = 'hello' >>> y = 'ell' >>> x in y False >>> y in x True ``` Note that \'print(x in y)\' would have also returned the same value. ### Indexing and Slicing Much like arrays in other languages, the individual characters in a string can be accessed by an integer representing its position in the string. The first character in string s would be s\[0\] and the nth character would be at s\[n-1\]. ``` python >>> s = "Xanadu" >>> s[1] 'a' ``` Unlike arrays in other languages, Python also indexes the arrays backwards, using negative numbers. The last character has index -1, the second to last character has index -2, and so on. ``` python >>> s[-4] 'n' ``` We can also use \"slices\" to access a substring of s. s\[a:b\] will give us a string starting with s\[a\] and ending with s\[b-1\]. ``` python >>> s[1:4] 'ana' ``` None of these are assignable. ``` python >>> print(s) >>> s[0] = 'J' Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object does not support item assignment >>> s[1:3] = "up" Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object does not support slice assignment >>> print(s) ``` Outputs (assuming the errors were suppressed): `Xanadu`\ `Xanadu` Another feature of slices is that if the beginning or end is left empty, it will default to the first or last index, depending on context: ``` python >>> s[2:] 'nadu' >>> s[:3] 'Xan' >>> s[:] 'Xanadu' ``` You can also use negative numbers in slices: ``` python >>> print(s[-2:]) 'du' ``` To understand slices, it\'s easiest not to count the elements themselves. It is a bit like counting not on your fingers, but in the spaces between them. The list is indexed like this: `Element:     1     2     3     4`\ `Index:    0     1     2     3     4`\ `         -4    -3    -2    -1` So, when we ask for the \[1:3\] slice, that means we start at index 1, and end at index 2, and take everything in between them. If you are used to indexes in C or Java, this can be a bit disconcerting until you get used to it. ## String constants String constants can be found in the standard string module. An example is string.digits, which equals to \'0123456789\'. Links: - Python documentation of \"string\" module \-- python.org ## String methods There are a number of methods or built-in string functions: - **capitalize** - **center** - **count** - decode - encode - endswith - **expandtabs** - **find** - **index** - **isalnum** - **isalpha** - **isdigit** - **islower** - **isspace** - **istitle** - **isupper** - **join** - **ljust** - **lower** - **lstrip** - **replace** - **rfind** - **rindex** - **rjust** - **rstrip** - **split** - **splitlines** - startswith - **strip** - **swapcase** - **title** - translate - **upper** - zfill Only emphasized items will be covered. ### is\* isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(), and istitle() fit into this category. The length of the string object being compared must be at least 1, or the is\* methods will return False. In other words, a string object of len(string) == 0, is considered \"empty\", or False. - **isalnum** returns True if the string is entirely composed of alphabetic and/or numeric characters (i.e. no punctuation). - **isalpha** and **isdigit** work similarly for alphabetic characters or numeric characters only. - **isspace** returns True if the string is composed entirely of whitespace. - **islower**, **isupper**, and **istitle** return True if the string is in lowercase, uppercase, or titlecase respectively. Uncased characters are \"allowed\", such as digits, but there must be at least one cased character in the string object in order to return True. Titlecase means the first cased character of each word is uppercase, and any immediately following cased characters are lowercase. Curiously, \'Y2K\'.istitle() returns True. That is because uppercase characters can only follow uncased characters. Likewise, lowercase characters can only follow uppercase or lowercase characters. Hint: whitespace is uncased. Example: ``` python >>> '2YK'.istitle() False >>> 'Y2K'.istitle() True >>> '2Y K'.istitle() True ``` ### Title, Upper, Lower, Swapcase, Capitalize Returns the string converted to title case, upper case, lower case, inverts case, or capitalizes, respectively. The **title** method capitalizes the first letter of each word in the string (and makes the rest lower case). Words are identified as substrings of alphabetic characters that are separated by non-alphabetic characters, such as digits, or whitespace. This can lead to some unexpected behavior. For example, the string \"x1x\" will be converted to \"X1X\" instead of \"X1x\". The **swapcase** method makes all uppercase letters lowercase and vice versa. The **capitalize** method is like title except that it considers the entire string to be a word. (i.e. it makes the first character upper case and the rest lower case) Example: ``` python s = 'Hello, wOrLD' print(s) # 'Hello, wOrLD' print(s.title()) # 'Hello, World' print(s.swapcase()) # 'hELLO, WoRld' print(s.upper()) # 'HELLO, WORLD' print(s.lower()) # 'hello, world' print(s.capitalize())# 'Hello, world' ``` Keywords: to lower case, to upper case, lcase, ucase, downcase, upcase. ### count Returns the number of the specified substrings in the string. i.e. ``` python >>> s = 'Hello, world' >>> s.count('o') # print the number of 'o's in 'Hello, World' (2) 2 ``` Hint: .count() is case-sensitive, so this example will only count the number of lowercase letter \'o\'s. For example, if you ran: ``` python >>> s = 'HELLO, WORLD' >>> s.count('o') # print the number of lowercase 'o's in 'HELLO, WORLD' (0) 0 ``` ### strip, rstrip, lstrip Returns a copy of the string with the leading (lstrip) and trailing (rstrip) whitespace removed. strip removes both. ``` python >>> s = '\t Hello, world\n\t ' >>> print(s) Hello, world >>> print(s.strip()) Hello, world >>> print(s.lstrip()) Hello, world # ends here >>> print(s.rstrip()) Hello, world ``` Note the leading and trailing tabs and newlines. Strip methods can also be used to remove other types of characters. ``` python import string s = 'www.wikibooks.org' print(s) print(s.strip('w')) # Removes all w's from outside print(s.strip(string.lowercase)) # Removes all lowercase letters from outside print(s.strip(string.printable)) # Removes all printable characters ``` Outputs: `www.wikibooks.org`\ `.wikibooks.org`\ `.wikibooks.`\ ` ` Note that string.lowercase and string.printable require an import string statement ### ljust, rjust, center left, right or center justifies a string into a given field size (the rest is padded with spaces). ``` python >>> s = 'foo' >>> s 'foo' >>> s.ljust(7) 'foo ' >>> s.rjust(7) ' foo' >>> s.center(7) ' foo ' ``` ### join Joins together the given sequence with the string as separator: ``` python >>> seq = ['1', '2', '3', '4', '5'] >>> ' '.join(seq) '1 2 3 4 5' >>> '+'.join(seq) '1+2+3+4+5' ``` map may be helpful here: (it converts numbers in seq into strings) ``` python >>> seq = [1,2,3,4,5] >>> ' '.join(map(str, seq)) '1 2 3 4 5' ``` now arbitrary objects may be in seq instead of just strings. ### find, index, rfind, rindex The find and index methods return the index of the first found occurrence of the given subsequence. If it is not found, find returns -1 but index raises a ValueError. rfind and rindex are the same as find and index except that they search through the string from right to left (i.e. they find the last occurrence) ``` python >>> s = 'Hello, world' >>> s.find('l') 2 >>> s[s.index('l'):] 'llo, world' >>> s.rfind('l') 10 >>> s[:s.rindex('l')] 'Hello, wor' >>> s[s.index('l'):s.rindex('l')] 'llo, wor' ``` Because Python strings accept negative subscripts, index is probably better used in situations like the one shown because using find instead would yield an unintended value. ### replace Replace works just like it sounds. It returns a copy of the string with all occurrences of the first parameter replaced with the second parameter. ``` python >>> 'Hello, world'.replace('o', 'X') 'HellX, wXrld' ``` Or, using variable assignment: ``` python string = 'Hello, world' newString = string.replace('o', 'X') print(string) print(newString) ``` Outputs: `Hello, world`\ `HellX, wXrld` Notice, the original variable (`string`) remains unchanged after the call to `replace`. ### expandtabs Replaces tabs with the appropriate number of spaces (default number of spaces per tab = 8; this can be changed by passing the tab size as an argument). ``` python s = 'abcdefg\tabc\ta' print(s) print(len(s)) t = s.expandtabs() print(t) print(len(t)) ``` Outputs: `abcdefg abc     a`\ `13`\ `abcdefg abc     a`\ `17` Notice how (although these both look the same) the second string (t) has a different length because each tab is represented by spaces not tab characters. To use a tab size of 4 instead of 8: ``` python v = s.expandtabs(4) print(v) print(len(v)) ``` Outputs: `abcdefg abc a`\ `13` Please note each tab is not always counted as eight spaces. Rather a tab \"pushes\" the count to the next multiple of eight. For example: ``` python s = '\t\t' print(s.expandtabs().replace(' ', '*')) print(len(s.expandtabs())) ``` Output: ` ****************`\ ` 16` ``` python s = 'abc\tabc\tabc' print(s.expandtabs().replace(' ', '*')) print(len(s.expandtabs())) ``` Outputs: ` abc*****abc*****abc`\ ` 19` ### split, splitlines The **split** method returns a list of the words in the string. It can take a separator argument to use instead of whitespace. ``` python >>> s = 'Hello, world' >>> s.split() ['Hello,', 'world'] >>> s.split('l') ['He', '', 'o, wor', 'd'] ``` Note that in neither case is the separator included in the split strings, but empty strings are allowed. The **splitlines** method breaks a multiline string into many single line strings. It is analogous to split(\'\\n\') (but accepts \'\\r\' and \'\\r\\n\' as delimiters as well) except that if the string ends in a newline character, **splitlines** ignores that final character (see example). ``` python >>> s = """ ... One line ... Two lines ... Red lines ... Blue lines ... Green lines ... """ >>> s.split('\n') ['', 'One line', 'Two lines', 'Red lines', 'Blue lines', 'Green lines', ''] >>> s.splitlines() ['', 'One line', 'Two lines', 'Red lines', 'Blue lines', 'Green lines'] ``` The method **split** also accepts multi-character string literals: ``` python txt = 'May the force be with you' spl = txt.split('the') print(spl) # ['May ', ' force be with you'] ``` ## Unicode In Python 3.x, all strings (the type str) contain Unicode per default. In Python 2.x, there is a dedicated unicode type in addition to the str type: u = u\"Hello\"; type(u) is unicode. The topic name in the internal help is UNICODE. Examples for Python 3.x: - v = \"Hello Günther\" - Uses a Unicode code point directly in the source code; that has to be in UTF-8 encoding. - v = \"Hello G\\xfcnther\" - Specifies 8-bit Unicode code point using \\xfc. - v = \"Hello G\\u00fcnther\" - Specifies 16-bit Unicode code point using \\u00fc. - v = \"Hello G\\U000000fcnther\" - Specifies 32-bit Unicode code point using \\U000000fc, the U being capitalized. - v = \"Hello G\\N{LATIN SMALL LETTER U WITH DIAERESIS}nther\" - Specifies a Unicode code point using \\N followed by the unicode point name. - v = \"Hello G\\N{latin small letter u with diaeresis}nther\" - The code point name can be in lowercase. - n = unicodedata.name(chr(252)) - Obtains Unicode code point name given a Unicode character, here of ü. - v = \"Hello G\" + chr(252) + \"nther\" - chr() accepts Unicode code points and returns a string having one Unicode character. - c = ord(\"ü\") - Yields the code point number. - b = \"Hello Günther\".encode(\"UTF-8\") - Creates a byte sequence (bytes) out of a Unicode string. - b = \"Hello Günther\".encode(\"UTF-8\"); u = b.decode(\"UTF-8\") - Decodes bytes into a Unicode string via decode() method. - v = b\"Hello \" + \"G\\u00fcnther\" - Throws TypeError: can\'t concat bytes to str. - v = b\"Hello\".decode(\"ASCII\") + \"G\\u00fcnther\" - Now it works. - f = open(\"File.txt\", encoding=\"UTF-8\"); lines = f.readlines(); f.close() - Opens a file for reading with a specific encoding and reads from it. If no encoding is specified, the one of locale.getpreferredencoding() is used. - f = open(\"File.txt\", \"w\", encoding=\"UTF-8\"); f.write(\"Hello G\\u00fcnther\"); f.close() - Writes to a file in a specified encoding. - f = open(\"File.txt\", encoding=\"UTF-8-sig\"); lines = f.readlines(); f.close() - The -sig encoding means that any leading byte order mark (BOM) is automatically stripped. - f = tokenize.open(\"File.txt\"); lines = f.readlines(); f.close() - Automatically detects encoding based on an encoding marker present in the file, such as BOM, stripping the marker. - f = open(\"File.txt\", \"w\", encoding=\"UTF-8-sig\"); f.write(\"Hello G\\u00fcnther\"); f.close() - Writes to a file in UTF-8, writing BOM at the beginning. Examples for Python 2.x: - v = u\"Hello G\\u00fcnther\" - Specifies 16-bit Unicode code point using \\u00fc. - v = u\"Hello G\\U000000fcnther\" - Specifies 32-bit Unicode code point using \\U000000fc, the U being capitalized. - v = u\"Hello G\\N{LATIN SMALL LETTER U WITH DIAERESIS}nther\" - Specifies a Unicode code point using \\N followed by the unicode point name. - v = u\"Hello G\\N{latin small letter u with diaeresis}nther\" - The code point name can be in lowercase. - unicodedata.name(unichr(252)) - Obtains Unicode code point name given a Unicode character, here of ü. - v = \"Hello G\" + unichr(252) + \"nther\" - chr() accepts Unicode code points and returns a string having one Unicode character. - c = ord(u\"ü\") - Yields the code point number. - b = u\"Hello Günther\".encode(\"UTF-8\") - Creates a byte sequence (str) out of a Unicode string. type(b) is str. - b = u\"Hello Günther\".encode(\"UTF-8\"); u = b.decode(\"UTF-8\") - Decodes bytes (type str) into a Unicode string via decode() method. - v = \"Hello\" + u\"Hello G\\u00fcnther\" - Concatenates str (bytes) and Unicode string without an error. - f = codecs.open(\"File.txt\", encoding=\"UTF-8\"); lines = f.readlines(); f.close() - Opens a file for reading with a specific encoding and reads from it. If no encoding is specified, the one of locale.getpreferredencoding() is used\[VERIFY\]. - f = codecs.open(\"File.txt\", \"w\", encoding=\"UTF-8\"); f.write(u\"Hello G\\u00fcnther\"); f.close() - Writes to a file in a specified encoding. - Unlike the Python 3 variant, if told to write newline via \\n, does not write operating system specific newline but rather literal \\n; this makes a difference e.g. on Windows. - To ensure text mode like operation one can write os.linesep. - f = codecs.open(\"File.txt\", encoding=\"UTF-8-sig\"); lines = f.readlines(); f.close() - The -sig encoding means that any leading byte order mark (BOM) is automatically stripped. Links: - Unicode HOWTO for Python 3, docs.python.org - Unicode HOWTO for Python 2, docs.python.org - Processing Text Files in Python 3, curiousefficiency.org - PEP 263 -- Defining Python Source Code Encodings, python.org - unicodedata --- Unicode Database in Python Library Reference, docs.python.org - Get a list of all the encodings Python can encode to, stackoverflow.com ## External links - \"String Methods\" chapter \-- python.org - Python documentation of \"string\" module \-- python.org
# Python Programming/Lists A list in Python is an ordered group of items (or *elements*). It is a very general structure, and list elements don\'t have to be of the same type: you can put numbers, letters, strings and nested lists all on the same list. ## Overview Lists in Python at a glance: ``` python list1 = [] # A new empty list list2 = [1, 2, 3, "cat"] # A new non-empty list with mixed item types list1.append("cat") # Add a single member, at the end of the list list1.extend(["dog", "mouse"]) # Add several members list1.insert(0, "fly") # Insert at the beginning list1[0:0] = ["cow", "doe"] # Add members at the beginning doe = list1.pop(1) # Remove item at index if "cat" in list1: # Membership test list1.remove("cat") # Remove AKA delete #list1.remove("elephant") - throws an error for item in list1: # Iteration AKA for each item print(item) print("Item count:", len(list1))# Length AKA size AKA item count list3 = [6, 7, 8, 9] for i in range(0, len(list3)): # Read-write iteration AKA for each item list3[i] += 1 # Item access AKA element access by index last = list3[-1] # Last item nextToLast = list3[-2] # Next-to-last item isempty = len(list3) == 0 # Test for emptiness set1 = set(["cat", "dog"]) # Initialize set from a list list4 = list(set1) # Get a list from a set list5 = list4[:] # A shallow list copy list4equal5 = list4==list5 # True: same by value list4refEqual5 = list4 is list5 # False: not same by reference list6 = list4[:] del list6[:] # Clear AKA empty AKA erase list7 = [1, 2] + [2, 3, 4] # Concatenation print(list1, list2, list3, list4, list5, list6, list7) print(list4equal5, list4refEqual5) print(list3[1:3], list3[1:], list3[:2]) # Slices print(max(list3 ), min(list3 ), sum(list3)) # Aggregates print([x for x in range(10)]) # List comprehension print([x for x in range(10) if x % 2 == 1]) print([x for x in range(10) if x % 2 == 1 if x < 5]) print([x + 1 for x in range(10) if x % 2 == 1]) print([x + y for x in '123' for y in 'abc']) ``` ## List creation There are two different ways to make a list in Python. The first is through assignment (\"statically\"), the second is using list comprehensions (\"actively\"). ### Plain creation To make a static list of items, write them between square brackets. For example: ``` python [ 1,2,3,"This is a list",'c',Donkey("kong") ] ``` Observations: 1. The list contains items of different data types: integer, string, and Donkey class. 2. Objects can be created \'on the fly\' and added to lists. The last item is a new instance of Donkey class. Creation of a new list whose members are constructed from non-literal expressions: ``` python a = 2 b = 3 myList = [a+b, b+a, len(["a","b"])] ``` ### List comprehensions Using list comprehension, you describe the process using which the list should be created. To do that, the list is broken into two pieces. The first is a picture of what each element will look like, and the second is what you do to get it. For instance, let\'s say we have a list of words: ``` python listOfWords = ["this","is","a","list","of","words"] ``` To take the first letter of each word and make a list out of it using list comprehension, we can do this: ``` python >>> listOfWords = ["this","is","a","list","of","words"] >>> items = [ word[0] for word in listOfWords ] >>> print(items) ['t', 'i', 'a', 'l', 'o', 'w'] ``` List comprehension supports more than one for statement. It will evaluate the items in all of the objects sequentially and will loop over the shorter objects if one object is longer than the rest. ``` python >>> item = [x+y for x in 'cat' for y in 'pot'] >>> print(item) ['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt'] ``` List comprehension supports an if statement, to only include members into the list that fulfill a certain condition: ``` python >>> print([x+y for x in 'cat' for y in 'pot']) ['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt'] >>> print([x+y for x in 'cat' for y in 'pot' if x != 't' and y != 'o' ]) ['cp', 'ct', 'ap', 'at'] >>> print([x+y for x in 'cat' for y in 'pot' if x != 't' or y != 'o' ]) ['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'tt'] ``` In version 2.x, Python\'s list comprehension does not define a scope. Any variables that are bound in an evaluation remain bound to whatever they were last bound to when the evaluation was completed. In version 3.x Python\'s list comprehension uses local variables: ``` python >>> print(x, y) #Input to python version 2 t t #Output using python 2 >>> print(x, y) #Input to python version 3 NameError: name 'x' is not defined #Python 3 returns an error because x and y were not leaked ``` This is exactly the same as if the comprehension had been expanded into an explicitly-nested group of one or more \'for\' statements and 0 or more \'if\' statements. ### List creation shortcuts You can initialize a list to a size, with an initial value for each element: ``` python >>> zeros=[0]*5 >>> print zeros [0, 0, 0, 0, 0] ``` This works for any data type: ``` python >>> foos=['foo']*3 >>> print(foos) ['foo', 'foo', 'foo'] ``` But there is a caveat. When building a new list by multiplying, Python copies each item by reference. This poses a problem for mutable items, for instance in a multidimensional array where each element is itself a list. You\'d guess that the easy way to generate a two dimensional array would be: ``` python listoflists=[ [0]*4 ] *5 ``` and this works, but probably doesn\'t do what you expect: ``` python >>> listoflists=[ [0]*4 ] *5 >>> print(listoflists) [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] >>> listoflists[0][2]=1 >>> print(listoflists) [[0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0]] ``` What\'s happening here is that Python is using the same reference to the inner list as the elements of the outer list. Another way of looking at this issue is to examine how Python sees the above definition: ``` python >>> innerlist=[0]*4 >>> listoflists=[innerlist]*5 >>> print(listoflists) [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] >>> innerlist[2]=1 >>> print(listoflists) [[0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0]] ``` Assuming the above effect is not what you intend, one way around this issue is to use list comprehensions: ``` python >>> listoflists=[[0]*4 for i in range(5)] >>> print(listoflists) [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] >>> listoflists[0][2]=1 >>> print(listoflists) [[0, 0, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] ``` ## List size To find the length of a list use the built in len() method. ``` python >>> len([1,2,3]) 3 >>> a = [1,2,3,4] >>> len( a ) 4 ``` ## Combining lists Lists can be combined in several ways. The easiest is just to \'add\' them. For instance: ``` python >>> [1,2] + [3,4] [1, 2, 3, 4] ``` Another way to combine lists is with `<b>`{=html}extend`</b>`{=html}. If you need to combine lists inside of a lambda, `<b>`{=html}extend`</b>`{=html} is the way to go. ``` python >>> a = [1,2,3] >>> b = [4,5,6] >>> a.extend(b) >>> print(a) [1, 2, 3, 4, 5, 6] ``` The other way to append a value to a list is to use **append**. For example: ``` python >>> p=[1,2] >>> p.append([3,4]) >>> p [1, 2, [3, 4]] >>> # or >>> print(p) [1, 2, [3, 4]] ``` However, \[3,4\] is an element of the list, and not part of the list. **append** always adds one element only to the end of a list. So if the intention was to concatenate two lists, always use **extend**. ## Getting pieces of lists (slices) ### Continuous slices Like strings, lists can be indexed and sliced: ``` python >>> list = [2, 4, "usurp", 9.0, "n"] >>> list[2] 'usurp' >>> list[3:] [9.0, 'n'] ``` Much like the slice of a string is a substring, the slice of a list is a list. However, lists differ from strings in that we can assign new values to the items in a list: ``` python >>> list[1] = 17 >>> list [2, 17, 'usurp', 9.0, 'n'] ``` We can assign new values to slices of the lists, which don\'t even have to be the same length: ``` python >>> list[1:4] = ["opportunistic", "elk"] >>> list [2, 'opportunistic', 'elk', 'n'] ``` It\'s even possible to append items onto the start of lists by assigning to an empty slice: ``` python >>> list[:0] = [3.14, 2.71] >>> list [3.14, 2.71, 2, 'opportunistic', 'elk', 'n'] ``` Similarly, you can append to the end of the list by specifying an empty slice after the end: ``` python >>> list[len(list):] = ['four', 'score'] >>> list [3.14, 2.71, 2, 'opportunistic', 'elk', 'n', 'four', 'score'] ``` You can also completely change the contents of a list: ``` python >>> list[:] = ['new', 'list', 'contents'] >>> list ['new', 'list', 'contents'] ``` The right-hand side of a list assignment statement can be any iterable type: ``` python >>> list[:2] = ('element',('t',),[]) >>> list ['element', ('t',), [], 'contents'] ``` With slicing you can create copy of list since slice returns a new list: ``` python >>> original = [1, 'element', []] >>> list_copy = original[:] >>> list_copy [1, 'element', []] >>> list_copy.append('new element') >>> list_copy [1, 'element', [], 'new element'] >>> original [1, 'element', []] ``` Note, however, that this is a shallow copy and contains references to elements from the original list, so be careful with mutable types: ``` python >>> list_copy[2].append('something') >>> original [1, 'element', ['something']] ``` ### Non-Continuous slices It is also possible to get non-continuous parts of an array. If one wanted to get every n-th occurrence of a list, one would use the :: operator. The syntax is a:b:n where a and b are the start and end of the slice to be operated upon. ``` python >>> list = [i for i in range(10) ] >>> list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list[::2] [0, 2, 4, 6, 8] >>> list[1:7:2] [1, 3, 5] ``` ## Comparing lists Lists can be compared for equality. ``` python >>> [1,2] == [1,2] True >>> [1,2] == [3,4] False ``` Lists can be compared using a less-than operator, which uses lexicographical order: ``` python >>> [1,2] < [2,1] True >>> [2,2] < [2,1] False >>> ["a","b"] < ["b","a"] True ``` ## Sorting lists Sorting at a glance: ``` python list1 = [2, 3, 1, 'a', 'B'] list1.sort() # list1 gets modified, case sensitive list2 = sorted(list1) # list1 is unmodified; since Python 2.4 list3 = sorted(list1, key=lambda x: x.lower()) # case insensitive ; will give error as not all elements of list are strings and .lower() is not applicable list4 = sorted(list1, reverse=True) # Reverse sorting order: descending print(list1, list2, list3, list4) ``` Sorting lists is easy with a sort method. ``` python >>> list1 = [2, 3, 1, 'a', 'b'] >>> list1.sort() >>> list1 [1, 2, 3, 'a', 'b'] ``` Note that the list is sorted in place, and the sort() method returns **None** to emphasize this side effect. If you use Python 2.4 or higher there are some more sort parameters: - sort(cmp,key,reverse) - cmp : method to be used for sorting - key : function to be executed with key element. List is sorted by return-value of the function - reverse : sort(reverse=True) or sort(reverse=False) Python also includes a sorted() function. ``` python >>> list1 = [5, 2, 3, 'q', 'p'] >>> sorted(list1) [2, 3, 5, 'p', 'q'] >>> list1 [5, 2, 3, 'q', 'p'] ``` Note that unlike the sort() method, sorted(list) does not sort the list in place, but instead returns the sorted list. The sorted() function, like the sort() method also accepts the reverse parameter. Links: - 2. Built-in Functions \# sorted, docs.python.org - Sorting HOW TO, docs.python.org ## Iteration Iteration over lists: Read-only iteration over a list, AKA for each element of the list: ``` python list1 = [1, 2, 3, 4] for item in list1: print(item) ``` Writable iteration over a list: ``` python list1 = [1, 2, 3, 4] for i in range(0, len(list1)): list1[i]+=1 # Modify the item at an index as you see fit print(list) ``` From a number to a number with a step: ``` python for i in range(1, 13+1, 3): # For i=1 to 13 step 3 print(i) for i in range(10, 5-1, -1): # For i=10 to 5 step -1 print(i) ``` For each element of a list satisfying a condition (filtering): ``` python for item in list: if not condition(item): continue print(item) ``` See also ../Loops#For_Loops. ## Removing Removing aka deleting an item at an index (see also #pop(i) "wikilink")): ``` python list1 = [1, 2, 3, 4] list1.pop() # Remove the last item list1.pop(0) # Remove the first item , which is the item at index 0 print(list1) list1 = [1, 2, 3, 4] del list1[1] # Remove the 2nd element; an alternative to list.pop(1) print(list1) ``` Removing an element by value: ``` python list1 = ["a", "a", "b"] list1.remove("a") # Removes only the 1st occurrence of "a" print(list1) ``` Keeping only items in a list satisfying a condition, and thus removing the items that do not satisfy it: ``` python list1 = [1, 2, 3, 4] newlist = [item for item in list1 if item > 2] print(newlist) ``` This uses a list comprehension. Removing items failing a condition can be done *without losing the identity* of the list being made shorter, by using \"\[:\]\": ``` python list1 = [1, 2, 3, 4] sameList = list1 list1[:] = [item for item in list1 if item > 2] print(sameList, sameList is list1) ``` Removing items failing a condition can be done by having the condition in a *separate function*: ``` python list1 = [1, 2, 3, 4] def keepingCondition(item): return item > 2 sameList = list1 list1[:] = [item for item in list1 if keepingCondition(item)] print(sameList, sameList is list1) ``` Removing items *while iterating a list* usually leads to unintended outcomes unless you do it carefully by using an index: ``` python list1 = [1, 2, 3, 4] index = len(list1) while index > 0: index -= 1 if not list1[index] < 2: list1.pop(index) ``` Links: - Remove items from a list while iterating, stackoverflow.com ## Aggregates There are some built-in functions for arithmetic aggregates over lists. These include minimum, maximum, and sum: ``` python list = [1, 2, 3, 4] print(max(list), min(list), sum(list)) average = sum(list) / float(len(list)) # Provided the list is non-empty # The float above ensures the division is a float one rather than integer one. print(average) ``` The max and min functions also apply to lists of strings, returning maximum and minimum with respect to alphabetical order: ``` python list = ["aa", "ab"] print(max(list), min(list)) # Prints "ab aa" ``` ## Copying Copying AKA cloning of lists: Making a shallow copy: ``` python list1= [1, 'element'] list2 = list1[:] # Copy using "[:]" list2[0] = 2 # Only affects list2, not list1 print(list1[0]) # Displays 1 # By contrast list1 = [1, 'element'] list2 = list1 list2[0] = 2 # Modifies the original list print(list1[0]) # Displays 2 ``` The above does not make a deep copy, which has the following consequence: ``` python list1 = [1, [2, 3]] # Notice the second item being a nested list list2 = list1[:] # A shallow copy list2[1][0] = 4 # Modifies the 2nd item of list1 as well print(list1[1][0]) # Displays 4 rather than 2 ``` Making a deep copy: ``` python import copy list1 = [1, [2, 3]] # Notice the second item being a nested list list2 = copy.deepcopy(list1) # A deep copy list2[1][0] = 4 # Leaves the 2nd item of list1 unmodified print list1[1][0] # Displays 2 ``` See also #Continuous slices. Links: - 8.17. copy --- Shallow and deep copy operations at docs.python.org ## Clearing Clearing a list: ``` python del list1[:] # Clear a list list1 = [] # Not really clear but rather assign to a new empty list ``` Clearing using a proper approach makes a difference when the list is passed as an argument: ``` python def workingClear(ilist): del ilist[:] def brokenClear(ilist): ilist = [] # Lets ilist point to a new list, losing the reference to the argument list list1=[1, 2]; workingClear(list1); print(list1) list1=[1, 2]; brokenClear(list1); print(list1) ``` Keywords: emptying a list, erasing a list, clear a list, empty a list, erase a list. ## Removing duplicate items Removing duplicate items from a list (keeping only unique items) can be achieved as follows. If each item in the list is **hashable**, using list comprehension, which is fast: ``` python list1 = [1, 4, 4, 5, 3, 2, 3, 2, 1] seen = {} list1[:] = [seen.setdefault(e, e) for e in list1 if e not in seen] ``` If each item in the list is hashable, using index iteration, much slower: ``` python list1 = [1, 4, 4, 5, 3, 2, 3, 2, 1] seen = set() for i in range(len(list1) - 1, -1, -1): if list1[i] in seen: list1.pop(i) seen.add(list1[i]) ``` If some items are **not hashable**, the set of visited items can be kept in a list: ``` python list1 = [1, 4, 4, ["a", "b"], 5, ["a", "b"], 3, 2, 3, 2, 1] seen = [] for i in range(len(list1) - 1, -1, -1): if list1[i] in seen: list1.pop(i) seen.append(list1[i]) ``` If each item in the list is **hashable** and preserving element **order does not matter**: ``` python list1 = [1, 4, 4, 5, 3, 2, 3, 2, 1] list1[:] = list(set(list1)) # Modify list1 list2 = list(set(list1)) ``` In the above examples where index iteration is used, scanning happens from the end to the beginning. When these are rewritten to scan from the beginning to the end, the result seems hugely slower. Links: - How do you remove duplicates from a list? at python.org Programming FAQ - Remove duplicates from a sequence (Python recipe) at activestate.com - Removing duplicates in lists at stackoverflow.com ## List methods ### append(x) Add item *x* onto the end of the list. ``` python >>> list = [1, 2, 3] >>> list.append(4) >>> list [1, 2, 3, 4] ``` See pop(i) "wikilink") ### pop(i) Remove the item in the list at the index *i* and return it. If *i* is not given, remove the last item in the list and return it. ``` python >>> list = [1, 2, 3, 4] >>> a = list.pop(0) >>> list [2, 3, 4] >>> a 1 >>> b = list.pop() >>>list [2, 3] >>> b 4 ``` ## Operators ### + To concatenate two lists. ### \* To multiply one list several times. ### in The operator \'in\' is used for two purposes; either to iterate over every item in a list in a for loop, or to check if a value is in a list returning true or false. ``` python >>> list = [1, 2, 3, 4] >>> if 3 in list: >>> .... >>> l = [0, 1, 2, 3, 4] >>> 3 in l True >>> 18 in l False >>>for x in l: >>> print(x) 0 1 2 3 4 ``` ## Difference To get the difference between two lists, just iterate: ``` python a = [0, 1, 2, 3, 4, 4] b = [1, 2, 3, 4, 4, 5] print([item for item in a if item not in b]) # [0] ``` ## Intersection To get the intersection between two lists (by preserving its elements order, and their doubles), apply the difference with the difference: ``` python a = [0, 1, 2, 3, 4, 4] b = [1, 2, 3, 4, 4, 5] dif = [item for item in a if item not in b] print([item for item in a if item not in dif]) # [1, 2, 3, 4, 4] ``` ## Exercises 1. Use a list comprehension to construct the list \[\'ab\', \'ac\', \'ad\', \'bb\', \'bc\', \'bd\'\]. 2. Use a slice on the above list to construct the list \[\'ab\', \'ad\', \'bc\'\]. 3. Use a list comprehension to construct the list \[\'1a\', \'2a\', \'3a\', \'4a\'\]. 4. Simultaneously remove the element \'2a\' from the above list and print it. 5. Copy the above list and add \'2a\' back into the list such that the original is still missing it. 6. Use a list comprehension to construct the list \[\'abe\', \'abf\', \'ace\', \'acf\', \'ade\', \'adf\', \'bbe\', \'bbf\', \'bce\', \'bcf\', \'bde\', \'bdf\'\] ## Solutions Question 1 : `List1 = [a + b for a in 'ab' for b in 'bcd']`\ `print(List1)`\ `>>> ['ab', 'ac', 'ad', 'bb', 'bc', 'bd']` Question 2 : `List2 = List1[::2]`\ `print(List2)`\ `>>> ['ab', 'ad', 'bc']` Question 3 : `List3 = [a + b for a in '1234' for b in 'a']`\ `print(List3)`\ `>>> ['1a', '2a', '3a', '4a']` Question 4 : `print(List3.pop(List3.index('3a')))`\ `print(List3)`\ `>>> 3a`\ `>>> ['1a', '2a', '4a']` Question 5 : `List4 = List3[:]`\ `List4.insert(2, '3a')`\ `print(List4)`\ `>>> ['1a', '2a', '3a', '4a']` Question 6 : `List5 = [a + b + c for a in 'ab' for b in 'bcd' for c in 'ef']`\ `print(List5)`\ `>>> ['abe', 'abf', 'ace', 'acf', 'ade', 'adf', 'bbe', 'bbf', 'bce', 'bcf', 'bde', 'bdf']` ## External links - Python documentation, chapter \"Sequence Types\" \-- python.org - Python Tutorial, chapter \"Lists\" \-- python.org
# Python Programming/Tuples A tuple in Python is much like a list except that it is immutable (unchangeable) once created. A tuple of hashable objects is hashable and thus suitable as a key in a dictionary and as a member of a set. ## Overview Tuples in Python at a glance: ``` python tup1 = (1, 'a') tup2 = 1, 'a' # Brackets not needed tup3 = (1,) # Singleton tup4 = 1, # Singleton without brackets tup5 = () # Empty tuple list1 = [1, 'a'] it1, it2 = tup1 # Assign items print(tup1 == tup2) # True print(tup1 == list1) # False print(tup1 == tuple(list1)) # True print(list(tup1) == list1) # True print(tup1[0]) # First member for item in tup1: print(item) # Iteration print((1, 2) + (3, 4)) # (1, 2, 3, 4) tup1 += (3,) print(tup1) # (1, 'a', 3), despite immutability print(len(tup1)) # Length AKA size AKA item count print(3 in tup1) # Membership - true return r1, r2 # Return multiple values r1, r2 = myfun() # Receive multiple values tup6 = ([1,2],) tup6[0][0]=3 print(tup6) # The list within is mutable set1 = set( (1,2) ) # Can be placed into a set #set1 = set( ([1,2], 2) ) # Error: The list within makes it unhashable ``` ## Tuple notation Tuples may be created directly or converted from lists. Generally, tuples are enclosed in parentheses. ``` python >>> l = [1, 'a', [6, 3.14]] >>> t = (1, 'a', [6, 3.14]) >>> t (1, 'a', [6, 3.14]) >>> tuple(l) (1, 'a', [6, 3.14]) >>> t == tuple(l) True >>> t == l False ``` A one item tuple is created by an item in parentheses followed by a comma: ``` python >>> t = ('A single item tuple',) >>> t ('A single item tuple',) ``` Also, tuples will be created from items separated by commas. ``` python >>> t = 'A', 'tuple', 'needs', 'no', 'parens' >>> t ('A', 'tuple', 'needs', 'no', 'parens') ``` ## Packing and Unpacking You can also perform multiple assignment using tuples. ``` python >>> article, noun, verb, adjective, direct_object = t #t is defined above >>> noun 'tuple' ``` Note that either, or both sides of an assignment operator can consist of tuples. ``` python >>> a, b = 1, 2 >>> b 2 ``` The example above: article, noun, verb, adjective, direct_object = t is called \"tuple unpacking\" because the tuple *t* was unpacked and its values assigned to each of the variables on the left. \"Tuple packing\" is the reverse: t=article, noun, verb, adjective, direct_object. When unpacking a tuple, or performing multiple assignment, you must have the same number of variables being assigned to as values being assigned. ## Operations on tuples These are the same as for lists except that we may not assign to indices or slices, and there is no \"append\" operator. ``` python >>> a = (1, 2) >>> b = (3, 4) >>> a + b (1, 2, 3, 4) >>> a (1, 2) >>> b (3, 4) >>> a.append(3) Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: 'tuple' object has no attribute 'append' >>> a (1, 2) >>> a[0] = 0 Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object does not support item assignment >>> a (1, 2) ``` For lists we would have had: ``` python >>> a = [1, 2] >>> b = [3, 4] >>> a + b [1, 2, 3, 4] >>> a [1, 2] >>> b [3, 4] >>> a.append(3) >>> a [1, 2, 3] >>> a[0] = 0 >>> a [0, 2, 3] ``` ### Tuple Attributes Length: Finding the length of a tuple is the same as with lists; use the built in len() method. ``` python >>> len( ( 1, 2, 3) ) 3 >>> a = ( 1, 2, 3, 4 ) >>> len( a ) 4 ``` ### Conversions Convert list to tuples using the built in tuple() method. ``` python >>> l = [4, 5, 6] >>> tuple(l) (4, 5, 6) ``` Converting a tuple into a list using the built in list() method to cast as a list: ``` python >>> t = (4, 5, 6) >>> list(t) [4, 5, 6] ``` Dictionaries can also be converted to tuples of tuples using the items method of dictionaries: ``` python >>> d = {'a': 1, 'b': 2} >>> tuple(d.items()) (('a', 1), ('b', 2)) ``` ## Uses of Tuples Tuples can be used in place of lists where the number of items is known and small, for example when returning multiple values from a function. Many other languages require creating an object or container to return, but with Python\'s tuple assignment, multiple-value returns are easy: ``` python def func(x, y): # code to compute x and y return x, y ``` This resulting tuple can be easily unpacked with the tuple assignment technique explained above: ``` python x, y = func(1, 2) ``` ## Using List Comprehension to process Tuple elements Occasionally, there is a need to manipulate the values contained within a tuple in order to create a new tuple. For example, if we wanted a way to double all of the values within a tuple, we can combine some of the above information in addition to list comprehension like this: ``` python def double(T): 'double() - return a tuple with each tuple element (e) doubled.' return tuple( [ e * 2 for e in T ] ) ``` ## Exercises 1. Create the list \[\'a\', \'b\', \'c\'\], then create a tuple from that list. 2. Create the tuple (\'a\', \'b\', \'c\'), then create a list from that tuple. (Hint: the material needed to do this has been covered, but it\'s not entirely obvious) 3. Make the following instantiations simultaneously: a = \'a\', b=2, c=\'gamma\'. (That is, in one line of code). 4. Create a tuple containing just a single element which in turn contains the three elements \'a\', \'b\', and \'c\'. Verify that the length is actually 1 by using the len() function. ## External links - Python documentation, chapter \"Sequence Types\" \-- python.org - Python documentation, chapter \"Tuples and Sequences\" \-- python.org
# Python Programming/Dictionaries A dictionary in Python is a collection of unordered values accessed by key rather than by index. The keys have to be hashable: integers, floating point numbers, strings, tuples, and, frozensets are hashable, while lists, dictionaries, and sets other than frozensets are not. Dictionaries were available as early as in Python 1.4. ## Overview Dictionaries in Python at a glance: ``` python dict1 = {} # Create an empty dictionary dict2 = dict() # Create an empty dictionary 2 dict2 = {"r": 34, "i": 56} # Initialize to non-empty value dict3 = dict([("r", 34), ("i", 56)]) # Init from a list of tuples dict4 = dict(r=34, i=56) # Initialize to non-empty value 3 dict1["temperature"] = 32 # Assign value to a key if "temperature" in dict1: # Membership test of a key AKA key exists del dict1["temperature"] # Delete AKA remove equalbyvalue = dict2 == dict3 itemcount2 = len(dict2) # Length AKA size AKA item count isempty2 = len(dict2) == 0 # Emptiness test for key in dict2: # Iterate via keys print (key, dict2[key]) # Print key and the associated value dict2[key] += 10 # Modify-access to the key-value pair for key in sorted(dict2): # Iterate via keys in sorted order of the keys print (key, dict2[key]) # Print key and the associated value for value in dict2.values(): # Iterate via values print (value) for key, value in dict2.items(): # Iterate via pairs print (key, value) dict5 = {} # {x: dict2[x] + 1 for x in dict2 } # Dictionary comprehension in Python 2.7 or later dict6 = dict2.copy() # A shallow copy dict6.update({"i": 60, "j": 30}) # Add or overwrite; a bit like list's extend dict7 = dict2.copy() dict7.clear() # Clear AKA empty AKA erase sixty = dict6.pop("i") # Remove key i, returning its value print (dict1, dict2, dict3, dict4, dict5, dict6, dict7, equalbyvalue, itemcount2, sixty) ``` ## Dictionary notation Dictionaries may be created directly or converted from sequences. Dictionaries are enclosed in curly braces, `{}` ``` python >>> d = {'city':'Paris', 'age':38, (102,1650,1601):'A matrix coordinate'} >>> seq = [('city','Paris'), ('age', 38), ((102,1650,1601),'A matrix coordinate')] >>> d {'city': 'Paris', 'age': 38, (102, 1650, 1601): 'A matrix coordinate'} >>> dict(seq) {'city': 'Paris', 'age': 38, (102, 1650, 1601): 'A matrix coordinate'} >>> d == dict(seq) True ``` Also, dictionaries can be easily created by zipping two sequences. ``` python >>> seq1 = ('a','b','c','d') >>> seq2 = [1,2,3,4] >>> d = dict(zip(seq1,seq2)) >>> d {'a': 1, 'c': 3, 'b': 2, 'd': 4} ``` ## Operations on Dictionaries The operations on dictionaries are somewhat unique. Slicing is not supported, since the items have no intrinsic order. ``` python >>> d = {'a':1,'b':2, 'cat':'Fluffers'} >>> d.keys() ['a', 'b', 'cat'] >>> d.values() [1, 2, 'Fluffers'] >>> d['a'] 1 >>> d['cat'] = 'Mr. Whiskers' >>> d['cat'] 'Mr. Whiskers' >>> 'cat' in d True >>> 'dog' in d False ``` ## Combining two Dictionaries You can combine two dictionaries by using the update method of the primary dictionary. Note that the update method will merge existing elements if they conflict. ``` python >>> d = {'apples': 1, 'oranges': 3, 'pears': 2} >>> ud = {'pears': 4, 'grapes': 5, 'lemons': 6} >>> d.update(ud) >>> d {'grapes': 5, 'pears': 4, 'lemons': 6, 'apples': 1, 'oranges': 3} >>> ``` ## Deleting from dictionary ``` python del dictionaryName[membername] ``` ## Exercises Write a program that: 1. Asks the user for a string, then creates the following dictionary. The values are the letters in the string, with the corresponding key being the place in the string. <https://docs.python.org/2/tutorial/datastructures.html#looping-techniques> 2. Replaces the entry whose key is the integer 3, with the value \"Pie\". 3. Asks the user for a string of digits, then prints out the values corresponding to those digits. ## External links - 5.5. Dictionaries in Tutorial, docs.python.org - 5.8. Mapping Types in Library Doc, docs.python.org
# Python Programming/Sets Starting with version 2.3, Python comes with an implementation of the mathematical set. Initially this implementation had to be imported from the standard module `set`, but with Python 2.6 the types set and frozenset became built-in types. A set is an unordered collection of objects, unlike sequence objects such as lists and tuples, in which each element is indexed. Sets cannot have duplicate members - a given object appears in a set 0 or 1 times. All members of a set have to be hashable, just like dictionary keys. Integers, floating point numbers, tuples, and strings are hashable; dictionaries, lists, and other sets (except frozensets) are not. ### Overview Sets in Python at a glance: ``` python set1 = set() # A new empty set set1.add("cat") # Add a single member set1.update(["dog", "mouse"]) # Add several members, like list's extend set1 |= set(["doe", "horse"]) # Add several members 2, like list's extend if "cat" in set1: # Membership test set1.remove("cat") #set1.remove("elephant") - throws an error set1.discard("elephant") # No error thrown print(set1) for item in set1: # Iteration AKA for each element print(item) print("Item count:", len(set1))# Length AKA size AKA item count #1stitem = set1[0] # Error: no indexing for sets isempty = len(set1) == 0 # Test for emptiness set1 = {"cat", "dog"} # Initialize set using braces; since Python 2.7 #set1 = {} # No way; this is a dict set1 = set(["cat", "dog"]) # Initialize set from a list set2 = set(["dog", "mouse"]) set3 = set1 & set2 # Intersection set4 = set1 | set2 # Union set5 = set1 - set3 # Set difference set6 = set1 ^ set2 # Symmetric difference issubset = set1 <= set2 # Subset test issuperset = set1 >= set2 # Superset test set7 = set1.copy() # A shallow copy set7.remove("cat") print(set7.pop()) # Remove an arbitrary element set8 = set1.copy() set8.clear() # Clear AKA empty AKA erase set9 = {x for x in range(10) if x % 2} # Set comprehension; since Python 2.7 print(set1, set2, set3, set4, set5, set6, set7, set8, set9, issubset, issuperset) ``` ### Constructing Sets One way to construct sets is by passing any sequential object to the \"set\" constructor. ``` python >>> set([0, 1, 2, 3]) set([0, 1, 2, 3]) >>> set("obtuse") set(['b', 'e', 'o', 's', 'u', 't']) ``` We can also add elements to sets one by one, using the \"add\" function. ``` python >>> s = set([12, 26, 54]) >>> s.add(32) >>> s set([32, 26, 12, 54]) ``` Note that since a set does not contain duplicate elements, if we add one of the members of s to s again, the add function will have no effect. This same behavior occurs in the \"update\" function, which adds a group of elements to a set. ``` python >>> s.update([26, 12, 9, 14]) >>> s set([32, 9, 12, 14, 54, 26]) ``` Note that you can give any type of sequential structure, or even another set, to the update function, regardless of what structure was used to initialize the set. The set function also provides a copy constructor. However, remember that the copy constructor will copy the set, but not the individual elements. ``` python >>> s2 = s.copy() >>> s2 set([32, 9, 12, 14, 54, 26]) ``` ### Membership Testing We can check if an object is in the set using the same \"in\" operator as with sequential data types. ``` python >>> 32 in s True >>> 6 in s False >>> 6 not in s True ``` We can also test the membership of entire sets. Given two sets $S_1$ and $S_2$, we check if $S_1$ is a subset or a superset of $S_2$. ``` python >>> s.issubset(set([32, 8, 9, 12, 14, -4, 54, 26, 19])) True >>> s.issuperset(set([9, 12])) True ``` Note that \"issubset\" and \"issuperset\" can also accept sequential data types as arguments ``` python >>> s.issuperset([32, 9]) True ``` Note that the \<= and \>= operators also express the issubset and issuperset functions respectively. ``` python >>> set([4, 5, 7]) <= set([4, 5, 7, 9]) True >>> set([9, 12, 15]) >= set([9, 12]) True ``` Like lists, tuples, and string, we can use the \"len\" function to find the number of items in a set. ### Removing Items There are three functions which remove individual items from a set, called pop, remove, and discard. The first, pop, simply removes an item from the set. Note that there is no defined behavior as to which element it chooses to remove. ``` python >>> s = set([1,2,3,4,5,6]) >>> s.pop() 1 >>> s set([2,3,4,5,6]) ``` We also have the \"remove\" function to remove a specified element. ``` python >>> s.remove(3) >>> s set([2,4,5,6]) ``` However, removing a item which isn\'t in the set causes an error. ``` python >>> s.remove(9) Traceback (most recent call last): File "<stdin>", line 1, in ? KeyError: 9 ``` If you wish to avoid this error, use \"discard.\" It has the same functionality as remove, but will simply do nothing if the element isn\'t in the set We also have another operation for removing elements from a set, clear, which simply removes all elements from the set. ``` python >>> s.clear() >>> s set([]) ``` ### Iteration Over Sets We can also have a loop move over each of the items in a set. However, since sets are unordered, it is undefined which order the iteration will follow. ``` python >>> s = set("blerg") >>> for n in s: ... print(n, "", end="") ... r b e l g ``` ### Set Operations Python allows us to perform all the standard mathematical set operations, using members of set. Note that each of these set operations has several forms. One of these forms, s1.function(s2) will return another set which is created by \"function\" applied to $S_1$ and $S_2$. The other form, s1.function_update(s2), will change $S_1$ to be the set created by \"function\" of $S_1$ and $S_2$. Finally, some functions have equivalent special operators. For example, s1 & s2 is equivalent to s1.intersection(s2) #### Intersection Any element which is in both $S_1$ and $S_2$ will appear in their intersection "wikilink"). ``` python >>> s1 = set([4, 6, 9]) >>> s2 = set([1, 6, 8]) >>> s1.intersection(s2) set([6]) >>> s1 & s2 set([6]) >>> s1.intersection_update(s2) >>> s1 set([6]) ``` #### Union The union "wikilink") is the merger of two sets. Any element in $S_1$ or $S_2$ will appear in their union. ``` python >>> s1 = set([4, 6, 9]) >>> s2 = set([1, 6, 8]) >>> s1.union(s2) set([1, 4, 6, 8, 9]) >>> s1 | s2 set([1, 4, 6, 8, 9]) ``` Note that union\'s update function is simply \"update\" above. #### Symmetric Difference The symmetric difference of two sets is the set of elements which are in one of either set, but not in both. ``` python >>> s1 = set([4, 6, 9]) >>> s2 = set([1, 6, 8]) >>> s1.symmetric_difference(s2) set([8, 1, 4, 9]) >>> s1 ^ s2 set([8, 1, 4, 9]) >>> s1.symmetric_difference_update(s2) >>> s1 set([8, 1, 4, 9]) ``` #### Set Difference Python can also find the set difference#Relative_Complement "wikilink") of $S_1$ and $S_2$, which is the elements that are in $S_1$ but not in $S_2$. ``` python >>> s1 = set([4, 6, 9]) >>> s2 = set([1, 6, 8]) >>> s1.difference(s2) set([9, 4]) >>> s1 - s2 set([9, 4]) >>> s1.difference_update(s2) >>> s1 set([9, 4]) ``` ### Multiple sets Starting with Python 2.6, \"union\", \"intersection\", and \"difference\" can work with multiple input by using the set constructor. For example, using \"set.intersection()\": ``` python >>> s1 = set([3, 6, 7, 9]) >>> s2 = set([6, 7, 9, 10]) >>> s3 = set([7, 9, 10, 11]) >>> set.intersection(s1, s2, s3) set([9, 7]) ``` ### frozenset A frozenset is basically the same as a set, except that it is immutable - once it is created, its members cannot be changed. Since they are immutable, they are also hashable, which means that frozensets can be used as members in other sets and as dictionary keys. frozensets have the same functions as normal sets, except none of the functions that change the contents (update, remove, pop, etc.) are available. ``` python >>> fs = frozenset([2, 3, 4]) >>> s1 = set([fs, 4, 5, 6]) >>> s1 set([4, frozenset([2, 3, 4]), 6, 5]) >>> fs.intersection(s1) frozenset([4]) >>> fs.add(6) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'frozenset' object has no attribute 'add' ``` ### Exercises 1. Create the set {\'cat\', 1, 2, 3}, call it s. 2. Create the set {\'c\', \'a\', \'t\', \'1\', \'2\', \'3\'}. 3. Create the frozen set {\'cat\', 1, 2, 3}, call it fs. 4. Create a set containing the frozenset fs, it should look like {frozenset({\'cat\', 2, 3, 1})}. ### Reference - Python Tutorial, section \"Data Structures\", subsection \"Sets\" \-- python.org - Python Library Reference on Set Types \-- python.org - PEP 218 \-- Adding a Built-In Set Object Type, python.org, a nice concise overview of the set type
# Python Programming/Operators ## Basics Python math works as expected: ``` {.python .numberLines} >>> x = 2 >>> y = 3 >>> z = 5 >>> x * y 6 >>> x + y 5 >>> y - x 1 >>> x * y + z 11 >>> (x + y) * z 25 >>> 3.0 / 2.0 # True division 1.5 >>> 3 // 2 # Floor division 1 >>> 2 ** 3 # Exponentiation 8 ``` Note that Python adheres to the PEMDAS order of operations. ## Powers There is a built in exponentiation operator *\*\**, which can take either integers, floating point or complex numbers. This occupies its proper place in the order of operations. ``` python >>> 2**8 256 ``` ## Floor Division and True Division In Python 3.x, slash operator (\"/\") does *true division* for all types including integers, and therefore, e.g. `3/2==1.5`[^1][^2]. The result is of a floating-point type even if both inputs are integers: 4 / 2 yields 2.0. In Python 3.x and latest 2.x, *floor division* for both integer arguments and floating-point arguments is achieved by using the double slash (\"//\") operator. For negative results, this is unlike the integer division in the C language since -3 // 2 == -2 in Python while -3 / 2 == -1 in C: C rounds the negative result toward zero while Python toward negative infinity. Beware that due to the limitations of floating point arithmetic, rounding errors can cause unexpected results. For example: `>>> print(0.6/0.2)`\ `3.0`\ `>>> print(0.6//0.2)`\ `2.0` For Python 2.x, dividing two integers or longs using the slash operator (\"/\") uses *floor division* (applying the floor function after division) and results in an integer or long. Thus, 5 / 2 == 2 and -3 / 2 == -2. Using \"/\" to do division this way is deprecated; if you want floor division, use \"//\" (available in Python 2.2 and later). Dividing by or into a floating point number will cause Python to use true division. Thus, to ensure true division in Python 2.x: `x=3; y=2; float(x)/y == 1.5`. Links: - 6.7. Binary arithmetic operations, in The Python Language Reference, docs.python.org - Python-style integer division & modulus in C, stackoverflow.com - Integer division rounding with negatives in C++, stackoverflow.com - In Python, what is a good way to round towards zero in integer division?, stackoverflow.com - Why Python\'s Integer Division Floors, python-history.blogspot.com ## Modulus The modulus (remainder of the division of the two operands, rather than the quotient) can be found using the *%* operator, or by the *divmod* builtin function. The *divmod* function returns a *tuple* containing the quotient and remainder. ``` python >>> 10 % 7 3 >>> -10 % 7 4 ``` Note that -10 % 7 is equal to 4 while it is equal to -3 in the C language. Python calculates the remainder as one after floor division while the C language calculates the remainder after C integer division, which differs from Python\'s floor division on integers: C integer division rounds negative results toward zero. Links: - 6.7. Binary arithmetic operations, in The Python Language Reference, docs.python.org ## Negation Unlike some other languages, variables can be negated directly: ``` python >>> x = 5 >>> -x -5 ``` ## Comparison Operation Means ----------- -------------------------- \< Less than \> Greater than \<= Less than or equal to \>= Greater than or equal to == Equal to != Not equal to Numbers, strings and other types can be compared for equality/inequality and ordering: ``` python >>> 2 == 3 False >>> 3 == 3 True >>> 3 == '3' False >>> 2 < 3 True >>> "a" < "aa" True ``` ## Identity The operators `is` and `is not` test for object identity and stand in contrast to == (equals): `x is y` is true if and only if x and y are references to the same object in memory. `x is not y` yields the inverse truth value. Note that an identity test is more stringent than an equality test since two distinct objects may have the same value. ``` python >>> [1,2,3] == [1,2,3] True >>> [1,2,3] is [1,2,3] False ``` For the built-in immutable data types (like int, str and tuple) Python uses caching mechanisms to improve performance, i.e., the interpreter may decide to reuse an existing immutable object instead of generating a new one with the same value. The details of object caching are subject to changes between different Python versions and are not guaranteed to be system-independent, so identity checks on immutable objects like `'hello' is 'hello'`, `(1,2,3) is (1,2,3)`, `4 is 2**2` may give different results on different machines. In some Python implementations, the following results are applicable: ``` python print(8 is 8) # True print("str" is "str") # True print((1, 2) is (1, 2)) # False - whyever, it is immutable print([1, 2] is [1, 2]) # False print(id(8) == id(8)) # True int1 = 8 print(int1 is 8) # True oldid = id(int1) int1 += 2 print(id(int1) == oldid)# False ``` Links: - 3. Data model, python.org - 2. Built-in Functions \# id, python.org - 5. Expressions \# is, python.org ## Augmented Assignment There is shorthand for assigning the output of an operation to one of the inputs: ``` python >>> x = 2 >>> x # 2 2 >>> x *= 3 >>> x # 2 * 3 6 >>> x += 4 >>> x # 2 * 3 + 4 10 >>> x /= 5 >>> x # (2 * 3 + 4) / 5 2 >>> x **= 2 >>> x # ((2 * 3 + 4) / 5) ** 2 4 >>> x %= 3 >>> x # ((2 * 3 + 4) / 5) ** 2 % 3 1 >>> x = 'repeat this ' >>> x # repeat this repeat this >>> x *= 3 # fill with x repeated three times >>> x repeat this repeat this repeat this ``` ## Logical Operators Logical operators are operators that act on booleans. ### or The or operator returns true if any one of the booleans involved are true. If none of them are true (in other words, they are all false), the or operator returns false. ``` python if a or b: do_this else: do_this ``` ### and The and operator only returns true if all of the booleans are true. If any one of them is false, the and operator returns false. ``` python if a and b: do_this else: do_this ``` ### not The not operator only acts on one boolean and simply returns its opposite. So, true turns into false and false into true. ``` python if not a: do_this else: do_this ``` The order of operations here is: *not* first, *and* second, *or* third. In particular, \"True or True and False or False\" becomes \"True or False or False\" which is True. Warning, logical operators can act on things other than booleans. For instance \"1 and 6\" will return 6. Specifically, \"and\" returns either the first value considered to be false, or the last value if all are considered true. \"or\" returns the first true value, or the last value if all are considered false. In Python, (floating-point) number with value *zero*, and *empty* strings, lists, sets, etc. are considered to be false. You may use `bool()` to check whether a thing is considered to be true or false in Python. For instance, `bool(0.0)` and `bool([])` both return `False`. ## Bitwise Operators Python operators for bitwise arithmetic are like those in the C language. They include & (bitwise and), \| (bitwise or), \^ (exclusive or AKA xor), \<\< (shift left), \>\> (shift right), and \~ (complement). Augmented assignment operators (AKA compound assignment operators) for the bitwise operations include &=, \|=, \^=, \<\<=, and \>\>=. Bitwise operators apply to integers, even negative ones and very large ones; for the shift operators, the second operand must be non-negative. In the Python internal help, this is covered under the topics of EXPRESSIONS and BITWISE. Examples: - 0b1101 & 0b111 == 0b101 - Note: 0b starts a binary literal, just like 0x starts a hexadecimal literal. - 0b1 \| 0b100 == 0b101 - 0b111 \^ 0b101 == 0b10 - 1 \<\< 4 == 16 - 7 \>\> 1 == 3 - 1 \<\< 100 == 0x10000000000000000000000000 - Large results are supported. - 1 \<\< -1 - An error: the 2nd operand must be non-negative. - -2 & 15 == 14 - For bitwise operations, negative integers are treated as if represented using two\'s complement with an infinite sequence of leading ones. Thus -2 is as if 0x\...FFFFFFFFFE, which ANDed with 15 (0xF) yields 0xE, which is 14. - format(-2 % (1 \<\< 32), \"032b\") - Determines a string showing the last 32 bits of the implied two\'s complement representation of -2. - \~-2 == 1 - The above note about treatment of negative integers applies. For the complement (\~), this treatment yields \~x == -1 \* (x + 1). This can be verified: min((\~x == -1 \* (x + 1) for x in range(-10 \*\* 6, 10 \*\* 6))) == True. - \~1 == -2 - The formula \~x == -1 \* (x + 1) mentioned above applies. In the bitwise complement interpretation, all the imaginary leading leading zeros of 1 are toggled to leading ones, which is then interpreted as two\'s complement representation of -2, which is as if 0x\...FFFFFFFFFE. - x = 0b11110101; x &= \~(0xF \<\< 1); x == 0b11100001 - A common idiom clears the least significant bits 5 to 2 using complement, showing the usefulness of the infinite-leading-ones two\'s complement implied representation of negative numbers for bitwise operations. Works for arbitrarily large x. - \~2 & 0xFFFFFFFF == 0xFFFFFFFD - We can emulate bitwise complement on 32-bit integers by ANDing the complement with the maximum unsigned 32-bit integer, 0xFFFFFFFF. We can proceed similarly for 8-bit complement, 16-bit complement, etc., by ANDing the complement with 0xFF, 0xFFFF, etc. - 2 \^ 0xFFFFFFFF == 0xFFFFFFFD - Another way to emulate fixed-size bitwise complement is by XORing with all Fs for the size. - v = 2.0 & 2 - Yields an error: no automatic conversion of floats to ints, and no operation on the underlying representation of the float. - int.bit_length(0x8000) == 16 - Determines how many bits are needed to represent the integer. Therefore, min((int.bit_length(1 \<\< x) == x + 1 for x in range(100000))) == True. Examples of augmented assignment operators: - a = 0b1101; a &= 0b111; a == 0b101 - a = 0b1; a \|= 0b100; a == 0b101 - a = 0b111; a \^= 0b101; a == 0b10 - a = 1; a \<\<= 4; a == 16 - a = 7; a \>\>= 1; a == 3 Class definitions can overload the operators for the instances of the class; thus, for instance, sets overload the pipe (\|) operator to mean set union: {1,2} \| {3,4} == {1,2,3,4}. The names of the override methods are \_\_and\_\_ for &, \_\_or\_\_ for \|, \_\_xor\_\_ for \^, \_\_invert\_\_ for \~, \_\_lshift\_\_ for \<\<, \_\_rshift\_\_ for \>\>, \_\_iand\_\_ for &=, \_\_ior\_ for \|=, \_\_ixor\_\_ for \^=, \_\_ilshift\_\_ for \<\<=, and \_\_irshift\_\_ for \>\>=. Examples of use of bitwise operations include calculation of CRC and MD5. Admittedly, these would usually be implemented in C rather than Python for maximum speed; indeed, Python has libraries for these written in C. Nonetheless, implementations in Python are possible and are shown in the links to Rosetta Code below. Links: - BitwiseOperators, wiki.python.org - BitManipulation, wiki.python.org - Bitwise Operations on Integer Types in Library Reference, docs.python.org - 2.5. Operators in The Python Language Reference, docs.python.org - 6. Expressions in The Python Language Reference, docs.python.org - 3. Data model in in The Python Language Reference, docs.python.org : \"Integers (int) \[\...\] For the purpose of shift and mask operations, a binary representation is assumed, and negative numbers are represented in a variant of 2's complement which gives the illusion of an infinite string of sign bits extending to the left.\" - , wikipedia.org - , wikipedia.org - PEP 203 -- Augmented Assignments, python.org - Bitwise operation and usage, stackoverflow.com - CRC-32 \# Python, rosettacode.org - MD5/Implementation \# Python, rosettacode.org - longobject.c at python/cpython, github.com - functions long_bitwise, long_rshift, long_lshift, and long_invert ## References ## External Links - 3.1.1. Numbers in The Python Tutorial, docs.python.org - 6. Expressions in The Python Language Reference, docs.python.org [^1]: What\'s New in Python 2.2 [^2]: PEP 238 \-- Changing the Division Operator
# Python Programming/Control Flow As with most imperative languages, there are three main categories of program control flow: - loops - branches - function calls Function calls are covered in the next section. Generators and list comprehensions are advanced forms of program control flow, but they are not covered here. ### Overview Control flow in Python at a glance: ``` python x = -6 # Branching if x > 0: # If print("Positive") elif x == 0: # Else if AKA elseif print("Zero") else: # Else print("Negative") list1 = [100, 200, 300] for i in list1: print(i) # A for loop for i in range(0, 5): print(i) # A for loop from 0 to 4 for i in range(5, 0, -1): print(i) # A for loop from 5 to 1 for i in range(0, 5, 2): print(i) # A for loop from 0 to 4, step 2 list2 = [(1, 1), (2, 4), (3, 9)] for x, xsq in list2: print(x, xsq) # A for loop with a two-tuple as its iterator l1 = [1, 2]; l2 = ['a', 'b'] for i1, i2 in zip(l1, l2): print(i1, i2) # A for loop iterating two lists at once. i = 5 while i > 0: # A while loop i -= 1 list1 = ["cat", "dog", "mouse"] i = -1 # -1 if not found for item in list1: i += 1 if item=="dog": break # Break; also usable with while loop print("Index of dog:", i) for i in range(1,6): if i <= 4: continue # Continue; also usable with while loop print("Greater than 4:", i) ``` ### Loops In Python, there are two kinds of loops, \'for\' loops and \'while\' loops. #### For loops A for loop iterates over elements of a sequence (tuple or list). A variable is created to represent the object in the sequence. For example, ``` python x = [100,200,300] for i in x: print (i) ``` This will output `100`\ `200`\ `300` The `for` loop loops over each of the elements of a list or iterator, assigning the current element to the variable name given. In the example above, each of the elements in `x` is assigned to `i`. A built-in function called range exists to make creating sequential lists such as the one above easier. The loop above is equivalent to: ``` python l = range(100, 301,100) for i in l: print (i) ``` Similar to the slicing operation, in the range function, the first argument is the starting integer (we can just pass one argument to the range, which will be interpreted as the *second* argument, and then the default value: 0 is used for the first argument), and the second argument is the ending integer *but excluded* from the list. ``` python >>> range(5) range(0, 5) >>> list(range(5)) #need to use list() to really print the list out [0, 1, 2, 3, 4] >>> set(range(5)) #we can also print a set out {0, 1, 2, 3, 4} >>> list(range(1,5)) [1, 2, 3, 4] >>> list(range(1,1)) #starting from 1, but 1 itself is excluded from the list [] ``` The next example uses a negative *step* (the third argument for the built-in range function, which is similar to the slicing operation): ``` python for i in range(5, 0, -1): print (i) ``` This will output `5`\ `4`\ `3`\ `2`\ `1` The negative step can be -2: ``` python for i in range(10, 0, -2): print (i) ``` This will output `10`\ `8`\ `6`\ `4`\ `2` For loops can have names for each element of a tuple, if it loops over a sequence of tuples: ``` python l = [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)] for x, xsquared in l: print(x, ':', xsquared) ``` This will output `1 : 1`\ `2 : 4`\ `3 : 9`\ `4 : 16`\ `5 : 25` Links: - 4.2. for Statements, The Python Tutorial, docs.python.org - 4.3. The range() Function, The Python Tutorial, docs.python.org #### While loops A while loop repeats a sequence of statements until the condition becomes false. For example: ``` python x = 5 while x > 0: print (x) x = x - 1 ``` Will output: `5`\ `4`\ `3`\ `2`\ `1` Python\'s while loops can also have an \'else\' clause, which is a block of statements that is executed (once) when the while condition evaluates to false. The break statement (see the next section) inside the while loop will not direct the program flow to the else clause. For example: ``` python x = 5 y = x while y > 0: print (y) y = y - 1 else: print (x) ``` This will output: `5`\ `4`\ `3`\ `2`\ `1`\ `5` Unlike some languages, there is no post-condition loop. When the while condition never evaluates to false, i.e., is always true, then we have an *infinite loop*. For example, ``` python x = 1 while x > 0: print(x) x += 1 ``` This results in an infinite loop, which prints 1,2,3,4,\... . To stop an infinite loop, we need to use the break statement. Links: - 3.2. First Steps Towards Programming, The Python Tutorial, docs.python.org #### Breaking and continuing Python includes statements to exit a loop (either a for loop or a while loop) prematurely. To exit a loop, use the break statement: ``` python x = 5 while x > 0: print(x) break x -= 1 print(x) ``` This will output `5` The statement to begin the next iteration of the loop without waiting for the end of the current loop is \'continue\'. ``` python l = [5,6,7] for x in l: continue print(x) ``` This will not produce any output. #### Else clause of loops The else clause of loops will be executed if no break statements are met in the loop. ``` python l = range(1,100) for x in l: if x == 100: print(x) break else: print(x, " is not 100") else: print("100 not found in range") ``` Another example of a while loop using the break statement and the else statement: ``` python expected_str = "melon" received_str = "apple" basket = ["banana", "grapes", "strawberry", "melon", "orange"] x = 0 step = int(raw_input("Input iteration step: ")) while received_str != expected_str: if x >= len(basket): print("No more fruits left on the basket."); break received_str = basket[x] x += step # Change this to 3 to make the while statement # evaluate to false, avoiding the break statement, using the else clause. if received_str==basket[2]: print("I hate", basket[2], "!"); break if received_str != expected_str: print("I am waiting for my ", expected_str,".") else: print("Finally got what I wanted! my precious ", expected_str, "!") print("Going back home now !") ``` This will output: Input iteration step: 2 I am waiting for my melon . I hate strawberry ! Going back home now ! #### White Space Python determines where a loop repeats itself by the indentation in the whitespace. Everything that is indented is part of the loop, the next entry that is not indented is not. For example, the code below prints \"1 1 2 1 1 2\" ``` python for i in [0, 1]: for j in ["a","b"]: print("1") print("2") ``` On the other hand, the code below prints \"1 2 1 2 1 2 1 2\" ``` python for i in [0, 1]: for j in ["a","b"]: print("1") print("2") ``` ### Branches There is basically only one kind of branch in Python, the \'if\' statement. The simplest form of the if statement simple executes a block of code only if a given predicate is true, and skips over it if the predicate is false For instance, ``` python >>> x = 10 >>> if x > 0: ... print("Positive") ... Positive >>> if x < 0: ... print("Negative") ... ``` You can also add \"elif\" (short for \"else if\") branches onto the if statement. If the predicate on the first "if" is false, it will test the predicate on the first elif, and run that branch if it's true. If the first elif is false, it tries the second one, and so on. Note, however, that it will stop checking branches as soon as it finds a true predicate, and skip the rest of the if statement. You can also end your if statements with an \"else\" branch. If none of the other branches are executed, then python will run this branch. ``` python >>> x = -6 >>> if x > 0: ... print("Positive") ... elif x == 0: ... print("Zero") ... else: ... print("Negative") ... 'Negative' ``` Links: - 4.1. if Statements, The Python Tutorial, docs.python.org ### Conclusion Any of these loops, branches, and function calls can be nested in any way desired. A loop can loop over a loop, a branch can branch again, and a function can call other functions, or even call itself. ## Exercises 1. Print the numbers from 0 to 1000 (including both 0 and 1000). 2. Print the numbers from 0 to 1000 that are multiples of 5. 3. Print the numbers from 1 to 1000 that are multiples of 5. 4. Use a nested for-loop to prints the 3x3 multiplication table below ``` python 1 2 3 2 4 6 3 6 9 ``` 1. Print the 3x3 multiplication table below. ``` python 1 2 3 ------ 1|1 2 3 2|2 4 6 3|3 6 9 ``` ## External links - 4. More Control Flow Tools, The Python Tutorial, docs.python.org
# Python Programming/Decision Control Python, like many other computer programming languages, uses Boolean logic for its decision control. That is, the Python interpreter compares one or more values in order to decide whether to execute a piece of code or not, given the proper syntax and instructions. Decision control is then divided into two major categories, conditional and repetition. Conditional logic simply uses the keyword **if** and a Boolean expression to decide whether or not to execute a code block. Repetition builds on the conditional constructs by giving us a simple method in which to repeat a block of code while a Boolean expression evaluates to *true*. ## Boolean Expressions Here is a little example of boolean expressions (you don\'t have to type it in): ``` python a = 6 b = 7 c = 42 print (1, a == 6) print (2, a == 7) print (3, a == 6 and b == 7) print (4, a == 7 and b == 7) print (5, not a == 7 and b == 7) print (6, a == 7 or b == 7) print (7, a == 7 or b == 6) print (8, not (a == 7 and b == 6)) print (9, not a == 7 and b == 6) ``` With the output being: 1 True 2 False 3 True 4 False 5 True 6 True 7 False 8 True 9 False What is going on? The program consists of a bunch of funny looking `print` statements. Each `print` statement prints a number and an expression. The number is to help keep track of which statement I am dealing with. Notice how each expression ends up being either True or False; these are built-in Python values. The lines: ``` python print (1, a == 6) print (2, a == 7) ``` print out True and False respectively, just as expected, since the first is true and the second is false. The third print, `print (3, a == 6 and b == 7)`, is a little different. The operator `and` means if both the statement before and the statement after are true then the whole expression is true otherwise the whole expression is false. The next line, `print (4, a == 7 and b == 7)`, shows how if part of an `and` expression is false, the whole thing is false. The behavior of `and` can be summarized as follows: expression result ----------------- -------- true and true true true and false false false and true false false and false false Note that if the first expression is false Python does not check the second expression since it knows the whole expression is false. The next line, `print (5, not a == 7 and b == 7)`, uses the `not` operator. `not` just gives the opposite of the expression (The expression could be rewritten as `print (5, a != 7 and b == 7)`). Here\'s the table: expression result ------------ -------- not true false not false true The two following lines, `print (6, a == 7 or b == 7)` and `print (7, a == 7 or b == 6)`, use the `or` operator. The `or` operator returns true if the first expression is true, or if the second expression is true or both are true. If neither are true it returns false. Here\'s the table: expression result ---------------- -------- true or true true true or false true false or true true false or false false Note that if the first expression is true Python doesn\'t check the second expression since it knows the whole expression is true. This works since `or` is true if at least one of the expressions are true. The first part is true so the second part could be either false or true, but the whole expression is still true. The next two lines, `print (8, not (a == 7 and b == 6))` and `print (9, not a == 7 and b == 6)`, show that parentheses can be used to group expressions and force one part to be evaluated first. Notice that the parentheses changed the expression from false to true. This occurred since the parentheses forced the `not` to apply to the whole expression instead of just the `a == 7` portion. Here is an example of using a boolean expression: ``` python list = ["Life","The Universe","Everything","Jack","Jill","Life","Jill"] # Make a copy of the list. copy = list[:] # Sort the copy copy.sort() prev = copy[0] del copy[0] count = 0 # Go through the list searching for a match while count < len(copy) and copy[count] != prev: prev = copy[count] count = count + 1 # If a match was not found then count can't be < len # since the while loop continues while count is < len # and no match is found if count < len(copy): print ("First Match:",prev) ``` See the Lists chapter to explain what \[:\] means on the first line. Here is the output: First Match: Jill This program works by continuing to check for a match `while count < len(copy) and copy[count] != prev`. When either `count` is greater than the last index of `copy` or a match has been found the `and` is no longer true so the loop exits. The `if` simply checks to make sure that the `while` exited because a match was found. The other \'trick\' of `and` is used in this example. If you look at the table for `and` notice that the third entry is \"false and won\'t check\". If `count >= len(copy)` (in other words `count < len(copy)` is false) then copy\[count\] is never looked at. This is because Python knows that if the first is false then they both can\'t be true. This is known as a short circuit and is useful if the second half of the `and` will cause an error if something is wrong. I used the first expression (`count < len(copy)`) to check and see if `count` was a valid index for `copy`. (If you don\'t believe me remove the matches \`Jill\' and \`Life\', check that it still works and then reverse the order of `count < len(copy) and copy[count] != prev` to `copy[count] != prev and count < len(copy)`.) Boolean expressions can be used when you need to check two or more different things at once. ## Examples password1.py ``` python ## This programs asks a user for a name and a password. # It then checks them to make sure that the user is allowed in. # Note that this is a simple and insecure example, # real password code should never be implemented this way. name = raw_input("What is your name? ") password = raw_input("What is the password? ") if name == "Josh" and password == "Friday": print ("Welcome Josh") elif name == "Fred" and password == "Rock": print ("Welcome Fred") else: print ("I don't know you.") ``` Sample runs What is your name? Josh What is the password? Friday Welcome Josh What is your name? Bill What is the password? Saturday I don't know you. ## Exercises 1. Write a program that has a user guess your name, but they only get 3 chances to do so until the program quits. Solutions
# Python Programming/Conditional Statements ## Decisions A **Decision** is when a program has more than one choice of actions depending on a variable\'s value. Think of a traffic light. When it is green, we continue our drive. When we see the light turn yellow, we reduce our speed, and when it is red, we stop. These are logical decisions that depend on the value of the traffic light. Luckily, Python has a decision statement to help us when our application needs to make such decision for the user. ## If statements Here is a warm-up exercise - a short program to compute the absolute value of a number:\ `absoval.py` ``` python n = input("Integer? ")#Pick an integer. And remember, if raw_input is not supported by your OS, use input() n = int(n)#Defines n as the integer you chose. (Alternatively, you can define n yourself) if n < 0: print ("The absolute value of",n,"is",-n) else: print ("The absolute value of",n,"is",n) ``` Here is the output from the two times that I ran this program: Integer? -34 The absolute value of -34 is 34 Integer? 1 The absolute value of 1 is 1 What does the computer do when it sees this piece of code? First it prompts the user for a number with the statement \"`n = input("Integer? ")`\". Next it reads the line \"`if n < 0:`\". If `n` is less than zero Python runs the line \"`print ("The absolute value of",n,"is",-n)`\". Otherwise python runs the line \"`print ("The absolute value of",n,"is",n)`\". More formally, Python looks at whether the *expression* `n < 0` is true or false. An `if` statement is followed by an indented *block* of statements that are run when the expression is true. After the `if` statement is an optional `else` statement and another indented *block* of statements. This 2nd block of statements is run if the expression is false. Expressions can be tested several different ways. Here is a table of all of them: operator function ---------- -------------------------- `<` less than `<=` less than or equal to `>` greater than `>=` greater than or equal to `==` equal `!=` not equal Another feature of the `if` command is the `elif` statement. It stands for \"else if,\" which means that if the original `if` statement is false and the `elif` statement is true, execute the block of code following the `elif` statement. Here\'s an example:\ ifloop.py ``` python a = 0 while a < 10: a = a + 1 if a > 5: print (a,">",5) elif a <= 7: print (a,"<=",7) else: print ("Neither test was true") ``` and the output: 1 <= 7 2 <= 7 3 <= 7 4 <= 7 5 <= 7 6 > 5 7 > 5 8 > 5 9 > 5 10 > 5 Notice how the `elif a <= 7` is only tested when the `if` statement fails to be true. `elif` allows multiple tests to be done in a single if statement. ### If Example `High_low.py` ``` python # Plays the guessing game higher or lower # (originally written by Josh Cogliati, improved by Quique, now improved # by Sanjith, further improved by VorDd, with continued improvement from # the various Wikibooks contributors.) # This should actually be something that is semi random like the # last digits of the time or something else, but that will have to # wait till a later chapter. (Extra Credit, modify it to be random # after the Modules chapter) # This is for demonstration purposes only. # It is not written to handle invalid input like a full program would. answer = 23 question = 'What number am I thinking of? ' print ('Let\'s play the guessing game!') while True: guess = int(input(question)) if guess < answer: print ('Little higher') elif guess > answer: print ('Little lower') else: # guess == answer print ('MINDREADER!!!') break ``` Sample run: Let's play the guessing game! What number am I thinking of? 22 Little higher What number am I thinking of? 25 Little Lower What number am I thinking of? 23 MINDREADER!!! As it states in its comments, this code is not prepared to handle invalid input (*i.e.*, strings instead of numbers). If you are wondering how you would implement such functionality in Python, you are referred to the Errors Chapter of this book, where you will learn about error handling. For the above code you may try this slight modification of the `while` loop: ``` python while True: inp = input(question) try: guess = int(inp) except ValueError: print('Your guess should be a number') else: if guess < answer: print ('Little higher') elif guess > answer: print ('Little lower') else: # guess == answer print ('MINDREADER!!!') break ``` `even.py` ``` python #Asks for a number. #Prints if it is even or odd print ("Input [x] for exit.") while True: inp = input("Tell me a number: ") if inp == 'x': break # catch any resulting ValueError during the conversion to float try: number = float(inp) except ValueError: print('I said: Tell me a NUMBER!') else: test = number % 2 if test == 0: print (int(number),"is even.") elif test == 1: print (int(number),"is odd.") else: print (number,"is very strange.") ``` Sample runs. Tell me a number: 3 3 is odd. Tell me a number: 2 2 is even. Tell me a number: 3.14159 3.14159 is very strange. `average1.py` ``` python #Prints the average value. print ("Welcome to the average calculator program") print ("NOTE- THIS PROGRAM ONLY CALCULATES AVERAGES FOR 3 NUMBERS") x = int(input("Please enter the first number ")) y = int(input("Please enter the second number ")) z = int(input("Please enter the third number ")) str = x+y+z print (float (str/3.0)) #MADE BY SANJITH sanrubik@gmail.com ``` Sample runs Welcome to the average calculator program NOTE- THIS PROGRAM ONLY CALCULATES AVERAGES FOR 3 NUMBERS Please enter the first number 7 Please enter the second number 6 Please enter the third number 4 5.66666666667 `<code>`{=html}`average2.py``</code>`{=html} ``` python #keeps asking for numbers until count have been entered. #Prints the average value. sum = 0.0 print ("This program will take several numbers, then average them.") count = int(input("How many numbers would you like to sum: ")) current_count = 0 while current_count < count: print ("Number",current_count) number = float(input("Enter a number: ")) sum = sum + number current_count += 1 print("The average was:",sum/count) ``` Sample runs This program will take several numbers, then average them. How many numbers would you like to sum: 2 Number 0 Enter a number: 3 Number 1 Enter a number: 5 The average was: 4.0 This program will take several numbers, then average them. How many numbers would you like to sum: 3 Number 0 Enter a number: 1 Number 1 Enter a number: 4 Number 2 Enter a number: 3 The average was: 2.66666666667 `<code>`{=html}`average3.py``</code>`{=html} ``` python #Continuously updates the average as new numbers are entered. print ("Welcome to the Average Calculator, please insert a number") currentaverage = 0 numofnums = 0 while True: newnumber = int(input("New number ")) numofnums = numofnums + 1 currentaverage = (round((((currentaverage * (numofnums - 1)) + newnumber) / numofnums), 3)) print ("The current average is " + str((round(currentaverage, 3)))) ``` Sample runs Welcome to the Average Calculator, please insert a number New number 1 The current average is 1.0 New number 3 The current average is 2.0 New number 6 The current average is 3.333 New number 6 The current average is 4.0 New number ### If Exercises 1. Write a password guessing program to keep track of how many times the user has entered the password wrong. If it is more than 3 times, print *You have been denied access.* and terminate the program. If the password is correct, print *You have successfully logged in.* and terminate the program. 2. Write a program that asks for two numbers. If the sum of the numbers is greater than 100, print *That is a big number* and terminate the program. 3. Write a program that asks the user their name. If they enter your name, say \"That is a nice name.\" If they enter \"John Cleese\" or \"Michael Palin\", tell them how you feel about them ;), otherwise tell them \"You have a nice name.\" 4. Ask the user to enter the password. If the password is correct print \"You have successfully logged in\" and exit the program. If the password is wrong print \"Sorry the password is wrong\" and ask the user to enter the password 3 times. If the password is wrong print \"You have been denied access\" and exit the program. ``` python ## Password guessing program using if statement and while statement only ### source by zain guess_count = 0 correct_pass = 'dee234' while True: pass_guess = input("Please enter your password: ") guess_count += 1 if pass_guess == correct_pass: print ('You have successfully logged in.') break elif pass_guess != correct_pass: if guess_count >= 3: print ("You have been denied access.") break ``` ``` python def mard(): for i in range(1,4): a = input("enter a password: ") # to ask password b = "sefinew" # the password if a == b: # if the password entered and the password are the same to print. print("You have successfully logged in") exit()# to terminate the program. Using 'break' instead of 'exit()' will allow your shell or idle to dump the block and continue to run. else: # if the password entered and the password are not the same to print. print("Sorry the password is wrong ") if i == 3: print("You have been denied access") exit() # to terminate the program mard() ``` \ ``` python #Source by Vanchi import time import getpass password = getpass.getpass("Please enter your password") print ("Waiting for 3 seconds") time.sleep(3) got_it_right = False for number_of_tries in range(1,4): reenter_password = getpass.getpass("Please reenter your password") if password == reenter_password: print ("You are Logged in! Welcome User :)") got_it_right = True break if not got_it_right: print ("Access Denied!!") ``` ### Conditional Statements Many languages (like Java and PHP) have the concept of a one-line conditional (called The Ternary Operator), often used to simplify conditionally accessing a value. For instance (in Java): ``` java int in= ; // read from program input // a normal conditional assignment int res; if(number < 0) res = -number; else res = number; ``` For many years Python did not have the same construct natively, however you could replicate it by constructing a tuple of results and calling the test as the index of the tuple, like so: ``` python number = int(input("Enter a number to get its absolute value:")) res = (-number, number)[number > 0] ``` It is important to note that, unlike a built in conditional statement, both the true and false branches are evaluated before returning, which can lead to unexpected results and slower executions if you\'re not careful. To resolve this issue, and as a better practice, wrap whatever you put in the tuple in anonymous function calls (lambda notation) to prevent them from being evaluated until the desired branch is called: ``` python number = int(input("Enter a number to get its absolute value:")) res = (lambda: number, lambda: -number)[number < 0]() ``` Since Python 2.5 however, there has been an equivalent operator to The Ternary Operator (though not called such, and with a totally different syntax): ``` python number = int(input("Enter a number to get its absolute value:")) res = -number if number < 0 else number ``` ## Switch A switch is a control statement present in most computer programming languages to minimize a bunch of If - elif statements. Sadly Python doesn\'t officially support this statement, but with the clever use of an array or dictionary, we can recreate this Switch statement that depends on a value. ``` python x = 1 def hello(): print ("Hello") def bye(): print ("Bye") def hola(): print ("Hola is Spanish for Hello") def adios(): print ("Adios is Spanish for Bye") # Notice that our switch statement is a regular variable, only that we added the function's name inside # and there are no quotes menu = [hello,bye,hola,adios] # To call our switch statement, we simply make reference to the array with a pair of parentheses # at the end to call the function menu[3]() # calls the adios function since is number 3 in our array. menu[0]() # Calls the hello function being our first element in our array. menu[x]() # Calls the bye function as is the second element on the array x = 1 ``` This works because Python stores a reference of the function in the array at its particular index, and by adding a pair of parentheses we are actually calling the function. Here the last line is equivalent to: ## Another way. Using function through user Input ``` python go = "y" x = 0 def hello(): print ("Hello") def bye(): print ("Bye") def hola(): print ("Hola is Spanish for Hello") def adios(): print ("Adios is Spanish for Bye") menu = [hello, bye, hola, adios] while x < len(menu) : print ("function", menu[x].__name__, ", press " , "[" + str(x) + "]") x += 1 while go != "n": c = int(input("Select Function: ")) menu[c]() go = input("Try again? [y/n]: ") print ("\nBye!") #end ``` ### Another way ``` python if x == 0: hello() elif x == 1: bye() elif x == 2: hola() else: adios() ``` ### Another way Another way is to use lambdas. Code pasted here with permissions1 ``` python result = { 'a': lambda x: x * 5, 'b': lambda x: x + 7, 'c': lambda x: x - 2 }value ``` For more information on *lambda* see anonymous functions in the function section.
# Python Programming/Loops ## While loops This is our first control structure.The version used is 2.7. Ordinarily the computer starts with the first line and then goes down from there. Control structures change the order that statements are executed or decide if a certain statement will be run. As a side note, decision statements (e.g., if statements) also influence whether or not a certain statement will run. Here\'s the source for a program that uses the while control structure: ``` python a = 0 while a < 5: a += 1 # Same as a = a + 1 print (a) ``` And here is the output: 1 2 3 4 5 So what does the program do? First it sees the line `a = 0` and sets the variable a to zero. Then it sees `while a < 5:` and so the computer checks to see if `a < 5`. The first time the computer sees this statement, a is zero, and zero is less than 5. In other words, while a is less than five, the computer will run the indented statements. Here is another example of the use of `while`: ``` python a = 1 s = 0 print ('Enter Numbers to add to the sum.') print ('Enter 0 to quit.') while a != 0: print ('Current Sum: ', s) a = input('Number? ') #raw_input() will not work anymore. a = float(a) s += a print ('Total Sum = ',s) ``` Enter Numbers to add to the sum. Enter 0 to quit. Current Sum: 0 Number? 200 Current Sum: 200 Number? -15.25 Current Sum: 184.75 Number? -151.85 Current Sum: 32.9 Number? 10.00 Current Sum: 42.9 Number? 0 Total Sum = 42.9 Notice how `print 'Total Sum =',s` is only run at the end. The `while` statement only affects the lines that are tabbed in (a.k.a. indented). The `!=` means does not equal so `while a != 0 :` means until a is zero run the tabbed in statements that are afterwards. Now that we have while loops, it is possible to have programs that run forever. An easy way to do this is to write a program like this: ``` python while 1 == 1: print ("Help, I'm stuck in a loop.") ``` This program will output `Help, I'm stuck in a loop.` until the heat death of the universe or you stop it. The way to stop it is to hit the Control (or Ctrl) button and \`c\' (the letter) at the same time. This will kill the program. (Note: sometimes you will have to hit enter after the Control C.) ### Examples Fibonacci.py ``` python #This program calculates the Fibonacci sequence a = 0 b = 1 count = 0 max_count = 20 while count < max_count: count = count + 1 #we need to keep track of a since we change it old_a = a old_b = b a = old_b b = old_a + old_b #Notice that the , at the end of a print statement keeps it # from switching to a new line print (old_a), ``` Output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 Password.py ``` python # Waits until a password has been entered. Use control-C to break out without # the password. # Note that this must not be the password so that the # while loop runs at least once. password = "foobar" #note that != means not equal while password != "unicorn": password = input("Password: ") print ("Welcome in") ``` Sample run: Password:auo Password:y22 Password:password Password:open sesame Password:unicorn Welcome in ## For Loops The next type of loop in Python is the `for` loop. Unlike in most languages, `for` requires some `__iterable__` object like a `Set` or `List` to work. ``` python onetoten = range(1,11) for count in onetoten: print (count) ``` The output: 1 2 3 4 5 6 7 8 9 10 The output looks very familiar, but the program code looks different. The first line uses the `range` function. The `range` function uses two arguments like this `range(start,finish)`. `start` is the first number that is produced. `finish` is one larger than the last number. Note that this program could have been done in a shorter way: ``` python for count in range(1,11): print (count) ``` Here are some examples to show what happens with the `range` function: >>> range(1,10) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(-32, -20) [-32, -31, -30, -29, -28, -27, -26, -25, -24, -23, -22, -21] >>> range(5,21) [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] >>> range(21,5) [] **Remark**: for the current version of Python, we need to pass the range function to `list()` to actually print a list. For instance, we need to use `list(range(1,10))` to get `[1, 2, 3, 4, 5, 6, 7, 8, 9]`. Another way to use the `range()` function in a `for` loop is to supply only one argument: ``` python for a in range(10): print (a) ``` The above code acts exactly the same as: ``` python for a in range(0, 10): print (a) ``` with 0 implied as the starting point. The output is 0 1 2 3 4 5 6 7 8 9 The code would cycle through the `for` loop 10 times as expected, but starting with 0 instead of 1. The next line `for count in onetoten:` uses the `for` control structure. A `for` control structure looks like `for variable in list:`. `list` is gone through starting with the first element of the list and going to the last. As `for` goes through each element in a list it puts each into `variable`. That allows `variable` to be used in each successive time the for loop is run through. Here is another example to demonstrate: ``` python demolist = ['life',42, 'the universe', 6,'and',7,'everything'] for item in demolist: print ("The Current item is: %s" % item) ``` The output is: The Current item is: life The Current item is: 42 The Current item is: the universe The Current item is: 6 The Current item is: and The Current item is: 7 The Current item is: everything Notice how the for loop goes through and sets item to each element in the list. (Notice how if you don\'t want `print` to go to the next line add a comma at the end of the statement (i.e. if you want to print something else on that line). ) So, what is `for` good for? The first use is to go through all the elements of a list and do something with each of them. Here a quick way to add up all the elements: ``` python list = [2,4,6,8] sum = 0 for num in list: sum = sum + num print ("The sum is: %d" % sum) ``` with the output simply being: The sum is: 20 Or you could write a program to find out if there are any duplicates in a list like this program does: ``` python list = [4, 5, 7, 8, 9, 1,0,7,10] list.sort() prev = list[0] del list[0] for item in list: if prev == item: print ("Duplicate of ",prev," Found") prev = item ``` and for good measure: Duplicate of 7 Found How does it work? Here is a special debugging version: ``` python l = [4, 5, 7, 8, 9, 1,0,7,10] print ("l = [4, 5, 7, 8, 9, 1,0,7,10]","\tl:",l) l.sort() print ("l.sort()","\tl:",l) prev = l[0] print ("prev = l[0]","\tprev:",prev) del l[0] print ("del l[0]","\tl:",l) for item in l: if prev == item: print ("Duplicate of ",prev," Found") print ("if prev == item:","\tprev:",prev,"\titem:",item) prev = item print ("prev = item","\t\tprev:",prev,"\titem:",item) ``` with the output being: l = [4, 5, 7, 8, 9, 1,0,7,10] l: [4, 5, 7, 8, 9, 1, 0, 7, 10] l.sort() l: [0, 1, 4, 5, 7, 7, 8, 9, 10] prev = l[0] prev: 0 del l[0] l: [1, 4, 5, 7, 7, 8, 9, 10] if prev == item: prev: 0 item: 1 prev = item prev: 1 item: 1 if prev == item: prev: 1 item: 4 prev = item prev: 4 item: 4 if prev == item: prev: 4 item: 5 prev = item prev: 5 item: 5 if prev == item: prev: 5 item: 7 prev = item prev: 7 item: 7 if prev == item: prev: 7 item: 7 Duplicate of 7 Found prev = item prev: 7 item: 7 if prev == item: prev: 7 item: 8 prev = item prev: 8 item: 8 if prev == item: prev: 8 item: 9 prev = item prev: 9 item: 9 if prev == item: prev: 9 item: 10 prev = item prev: 10 item: 10 Note: The reason there are so many `print` statements is because print statements can show the value of each variable at different times, and help debug the program. First the program starts with a old list. Next the program sorts the list. This is so that any duplicates get put next to each other. The program then initializes a prev(ious) variable. Next the first element of the list is deleted so that the first item is not incorrectly thought to be a duplicate. Next a for loop is gone into. Each item of the list is checked to see if it is the same as the previous. If it is a duplicate was found. The value of prev is then changed so that the next time the for loop is run through prev is the previous item to the current. Sure enough, the 7 is found to be a duplicate. The other way to use for loops is to do something a certain number of times. Here is some code to print out the first 9 numbers of the Fibonacci series: ``` python a = 1 b = 1 for c in range(1,10): print (a) n = a + b a = b b = n print ("") ``` with the surprising output: 1 1 2 3 5 8 13 21 34 Everything that can be done with `for` loops can also be done with `while` loops but `for` loops give an easy way to go through all the elements in a list or to do something a certain number of times. ## range Versus xrange ***Python 3 Note:** In Python 3.*x*, there is no function named `xrange`. Instead, the `range` function has the behaviour described below for `xrange`. The following applies to the legacy Python 2.* Above, you were introduced to the `range` function, which returns a list of all the integers in a specified range. Supposing you were to write an expression like `range(0, 1000000)`: that would construct a list consisting of a million integers! That can take up a lot of memory. Often, you do indeed need to process all the numbers over a very wide range. But you might only need to do so one at a time; as each number is processed, it can be discarded from memory before the next one is obtained. To do this, you can use the `xrange` function instead of `range`. For example, the following simple loop for i in xrange(0, 1000000): print(i) will print the million integers from 0 to 999999, but it will get them one at a time from the `xrange` call, instead of getting them all at once as a single list and going through that. This is an example of an *iterator*, which yields values one at a time as they are needed, rather than all at once. As you learn more about Python, you will see a lot more examples of iterators in use, and you will learn how to write your own. ## The `break` Statement A `while`-loop checks its termination condition before each entry into the loop body, and terminates if the condition has gone `False`. Thus, the loop body will normally iterate zero, one or more *complete* times. A `for`-loop iterates its body once for each value returned from the iterator expression. Again, each iteration is normally of the *complete* loop body. Sometimes you want to conditionally stop the loop in the *middle* of the loop body. An example situation might look like this: 1. Obtain the next value to check 2. Is there in fact another value to check? If not, exit the loop with failure. 3. Is the value what I'm looking for? If so, exit the loop with success. 4. Otherwise, go back to step 1. As you can see, there are two possible exits from this loop. You can exit from the middle of a Python `while`- or `for`-loop with the `break`-statement. Here is one way to write such a loop: ``` python found = False # initial assumption for value in values_to_check(): if is_what_im_looking_for(value): found = True break # ... found is True on success, False on failure ``` The trouble with this is the asymmetry between the two ways out of the loop: one through normal `for`-loop termination, the other through the `break`. As a stylistic matter, it would be more consistent to follow this principle: : If one exit from a loop is represented by a `break`, then *all* exits from the loop should be represented by `break`s. In particular, this means that the loop construct itself becomes a "loop-forever" loop; the only out of it is via a `break` statement. We can do this by explicitly dealing with an iterator yielding the values to be checked. Perhaps the `values_to_check()` call above already yields an iterator; if not, it can be converted to one by wrapping it in a call to the `iter()` built-in function, and then using the `next()` built-in function to obtain successive values from this iterator. Then the loop becomes: ``` python values = iter(values_to_check()) while True: value = next(values, None) if value is None: found = False break if is_what_im_looking_for(value): found = True break # ... found is True on success, False on failure ``` This uses the special Python value `None` to indicate that the iterator has reached its end. This is a common Python convention. But if you need to use `None` as a valid item in your sequence of values, then it is easy enough to define some other unique value (e.g. a custom dummy class) to represent the end of the list. ## Exercises 1. Create a program to count by prime numbers. Ask the user to input a number, then print each prime number up to that number. 2. Instruct the user to pick an arbitrary number from 1 to 100 and proceed to guess it correctly within seven tries. After each guess, the user must tell whether their number is higher than, lower than, or equal to your guess. Solutions
# Python Programming/Functions ## Function Calls A *callable object* is an object that can accept some arguments (also called parameters) and possibly return an object (often a tuple containing multiple objects). A function is the simplest callable object in Python, but there are others, such as classes or certain class instances. #### Defining Functions A function is defined in Python by the following format: ``` python def functionname(arg1, arg2, ...): statement1 statement2 ... ``` ``` python >>> def functionname(arg1,arg2): ... return arg1+arg2 ... >>> t = functionname(24,24) # Result: 48 ``` If a function takes no arguments, it must still include the parentheses, but without anything in them: ``` python def functionname(): statement1 statement2 ... ``` The arguments in the function definition bind the arguments passed at function invocation (i.e. when the function is called), which are called actual parameters, to the names given when the function is defined, which are called formal parameters. The interior of the function has no knowledge of the names given to the actual parameters; the names of the actual parameters may not even be accessible (they could be inside another function). A function can \'return\' a value, for example: ``` python def square(x): return x*x ``` A function can define variables within the function body, which are considered \'local\' to the function. The locals together with the arguments comprise all the variables within the scope of the function. Any names within the function are unbound when the function returns or reaches the end of the function body. You can **return multiple values** as follows: ``` python def first2items(list1): return list1[0], list1[1] a, b = first2items(["Hello", "world", "hi", "universe"]) print(a + " " + b) ``` Keywords: returning multiple values, multiple return values. ### Declaring Arguments When calling a function that takes some values for further processing, we need to send some values as Function **Arguments**. For example: ``` python >>> def find_max(a,b): if(a > b): return str(a) + " is greater than " + str(b) elif(b > a): return str(b) + " is greater than " + str(a) >>> find_max(30, 45) #Here (30, 45) are the arguments passing for finding max between this two numbers The output will be: 45 is greater than 30 ``` #### Default Argument Values If any of the formal parameters in the function definition are declared with the format \"arg = value,\" then you will have the option of not specifying a value for those arguments when calling the function. If you do not specify a value, then that parameter will have the default value given when the function executes. ``` python >>> def display_message(message, truncate_after=4): ... print(message[:truncate_after]) ... >>> display_message("message") mess >>> display_message("message", 6) messag ``` Links: - 4.7.1. Default Argument Values, The Python Tutorial, docs.python.org #### Variable-Length Argument Lists Python allows you to declare two special arguments which allow you to create arbitrary-length argument lists. This means that each time you call the function, you can specify any number of arguments above a certain number. ``` python def function(first,second,*remaining): statement1 statement2 ... ``` When calling the above function, you must provide value for each of the first two arguments. However, since the third parameter is marked with an asterisk, any actual parameters after the first two will be packed into a tuple and bound to \"remaining.\" ``` python >>> def print_tail(first,*tail): ... print(tail) ... >>> print_tail(1, 5, 2, "omega") (5, 2, 'omega') ``` If we declare a formal parameter prefixed with *two* asterisks, then it will be bound to a dictionary containing any keyword arguments in the actual parameters which do not correspond to any formal parameters. For example, consider the function: ``` python def make_dictionary(max_length=10, **entries): return dict([(key, entries[key]) for i, key in enumerate(entries.keys()) if i < max_length]) ``` If we call this function with any keyword arguments other than max_length, they will be placed in the dictionary \"entries.\" If we include the keyword argument of max_length, it will be bound to the formal parameter max_length, as usual. ``` python >>> make_dictionary(max_length=2, key1=5, key2=7, key3=9) {'key3': 9, 'key2': 7} ``` Links: - 4.7.3. Arbitrary Argument Lists, The Python Tutorial, docs.python.org #### By Value and by Reference Objects passed as arguments to functions are passed *by reference*; they are not being copied around. Thus, passing a large list as an argument does not involve copying all its members to a new location in memory. Note that even integers are objects. However, the distinction of *by value* and *by reference* present in some other programming languages often serves to distinguish whether the passed arguments can be *actually changed* by the called function and whether the *calling function can see the changes*. Passed objects of *mutable* types such as lists and dictionaries can be changed by the called function and the changes are visible to the calling function. Passed objects of *immutable* types such as integers and strings cannot be changed by the called function; the calling function can be certain that the called function will not change them. For mutability, see also Data Types chapter. An example: ``` python def appendItem(ilist, item): ilist.append(item) # Modifies ilist in a way visible to the caller def replaceItems(ilist, newcontentlist): del ilist[:] # Modification visible to the caller ilist.extend(newcontentlist) # Modification visible to the caller ilist = [5, 6] # No outside effect; lets the local ilist point to a new list object, # losing the reference to the list object passed as an argument def clearSet(iset): iset.clear() def tryToTouchAnInteger(iint): iint += 1 # No outside effect; lets the local iint to point to a new int object, # losing the reference to the int object passed as an argument print("iint inside:",iint) # 4 if iint was 3 on function entry list1 = [1, 2] appendItem(list1, 3) print(list1) # [1, 2, 3] replaceItems(list1, [3, 4]) print(list1) # [3, 4] set1 = set([1, 2]) clearSet(set1 ) print(set1) # set([]) int1 = 3 tryToTouchAnInteger(int1) print(int1) # 3 ``` ### Preventing Argument Change An argument cannot be declared to be constant, not to be changed by the called function. If an argument is of an immutable type, it cannot be changed anyway, but if it is of a mutable type such as list, the calling function is at the mercy of the called function. Thus, if the calling function wants to make sure a passed list does not get changed, it has to pass a copy of the list. An example: ``` python def evil_get_length(ilist): length = len(ilist) del ilist[:] # Muhaha: clear the list return length list1 = [1, 2] print(evil_get_length(list1[:])) # Pass a copy of list1 print(list1) # list1 = [1, 2] print(evil_get_length(list1)) # list1 gets cleared print(list1) # list1 = [] ``` ### Calling Functions A function can be called by appending the arguments in parentheses to the function name, or an empty matched set of parentheses if the function takes no arguments. ``` python foo() square(3) bar(5, x) ``` A function\'s return value can be used by assigning it to a variable, like so: ``` python x = foo() y = bar(5,x) ``` As shown above, when calling a function you can specify the parameters by name and you can do so in any order ``` python def display_message(message, start=0, end=4): print(message[start:end]) display_message("message", end=3) ``` This above is valid and start will have the default value of 0. A restriction placed on this is after the first named argument then all arguments after it must also be named. The following is not valid ``` python display_message(end=5, start=1, "my message") ``` because the third argument (\"my message\") is an unnamed argument. ## Nested functions Nested functions are functions defined within other functions. Arbitrary level of nesting is possible. Nested functions can read variables declared in the immediately outside function. For such variables that are mutable, nested functions can even modify them. For such variables that are immutable such as integers, attempt at modification in the nested function throws UnboundLocalError. In Python 3, an immutable immediately outside variable can be declared in the nested function to be *nonlocal*, in an analogy to *global*. Once this is done, the nested function can assign a new value to that variable and that modification is going to be seen outside of the nested function. Nested functions can be used in #Closures, on which see below. Furthermore, they can be used to reduce repetion of code that pertains only to a single function, often with reduced argument list owing to seeing the immediately outside variables. An example of a nested function that modifies an immediately outside variable that is a list and therefore mutable: ``` python def outside(): outsideList = [1, 2] def nested(): outsideList.append(3) nested() print(outsideList) ``` An example in which the outside variable is first accessed *below* the nested function definition and it still works: ``` python def outside(): def nested(): outsideList.append(3) outsideList = [1, 2] nested() print(outsideList) ``` Keywords: inner functions, internal functions, local functions. Links: - Nested Function in Python stackoverflow.com - 7. Simple statements \# 7.13. The nonlocal statement, docs.python.org/3 - Python nonlocal statement, stackoverflow.com ## Closures A *closure* is a nested function with an after-return access to the data of the outer function, where the nested function is returned by the outer function as a function object. Thus, even when the outer function has finished its execution after being called, the closure function returned by it can refer to the values of the variables that the outer function had when it defined the closure function. An example: ``` python def adder(outer_argument): # outer function def adder_inner(inner_argument): # inner function, nested function return outer_argument + inner_argument # Notice outer_argument return adder_inner add5 = adder(5) # a function that adds 5 to its argument add7 = adder(7) # a function that adds 7 to its argument print(add5(3)) # prints 8 print(add7(3)) # prints 10 ``` Closures are possible in Python because functions are *first-class objects*. A function is merely an object of type function. Being an object means it is possible to pass a function object (an uncalled function) around as argument or as return value or to assign another name to the function object. A unique feature that makes closure useful is that the enclosed function may use the names defined in the parent function\'s scope. ## Lambda Expressions A lambda is an anonymous (unnamed) function. It is used primarily to write very short functions that are a hassle to define in the normal way. A function like this: ``` python >>> def add(a, b): ... return a + b ... >>> add(4, 3) 7 ``` may also be defined using lambda ``` python >>> print ((lambda a, b: a + b)(4, 3)) 7 ``` Lambda is often used as an argument to other functions that expects a function object, such as sorted()\'s \'key\' argument. ``` python >>> sorted([[3, 4], [3, 5], [1, 2], [7, 3]], key=lambda x: x[1]) [[1, 2], [7, 3], [3, 4], [3, 5]] ``` The lambda form is often useful as a closure, such as illustrated in the following example: ``` python >>> def attribution(name): ... return lambda x: x + ' -- ' + name ... >>> pp = attribution('John') >>> pp('Dinner is in the fridge') 'Dinner is in the fridge -- John' ``` Note that the lambda function can use the values of variables from the scope in which it was created (like pre and post). This is the essence of closure. Links: - 4.7.5. Lambda Expressions, The Python Tutorial, docs.python.org ## Generator Functions When discussing loops, you came across the concept of an *iterator*. This yields in turn each element of some sequence, rather than the entire sequence at once, allowing you to deal with sequences much larger than might be able to fit in memory at once. You can create your own iterators, by defining what is known as a *generator function*. To illustrate the usefulness of this, let us start by considering a simple function to return the *concatenation* of two lists: ``` python def concat(a, b): return a + b print(concat([5, 4, 3], ["a", "b", "c"])) # prints [5, 4, 3, 'a', 'b', 'c'] ``` Imagine wanting to do something like `concat(list(range(0, 1000000)), list(range(1000000, 2000000)))` That would work, but it would consume a lot of memory. Consider an alternative definition, which takes two iterators as arguments: ``` python def concat(a, b): for i in a: yield i for i in b: yield i ``` Notice the use of the **yield** statement, instead of **return**. We can now use this something like ``` python for i in concat(range(0, 1000000), range(1000000, 2000000)): print(i) ``` and print out an awful lot of numbers, without using a lot of memory at all. Note: You can still pass a list or other sequence type wherever Python expects an iterator (like to an argument of your `concat` function); this will still work, and makes it easy not to have to worry about the difference where you don't need to. Links: - Functional Programming HOWTO \# Generators, docs.python.org ## External Links - 4.6. Defining Functions, The Python Tutorial, docs.python.org de:Python unter Linux: Funktionen es:Inmersión en Python/Su primer programa en Python/Declaración de funciones fr:Programmation_Python/Fonction pt:Python/Conceitos básicos/Funções
# Python Programming/Scoping ### Variables Variables in Python are automatically declared by assignment. Variables are always references to objects, and are never typed. Variables exist only in the current scope or global scope. When they go out of scope, the variables are destroyed, but the objects to which they refer are not (unless the number of references to the object drops to zero). Scope is delineated by function and class blocks. Both functions and their scopes can be nested. So therefore ``` python def foo(): def bar(): x = 5 # x is now in scope return x + y # y is defined in the enclosing scope later y = 10 return bar() # now that y is defined, bar's scope includes y ``` Now when this code is tested, ``` python >>> foo() 15 >>> bar() Traceback (most recent call last): File "<pyshell#26>", line 1, in -toplevel- bar() NameError: name 'bar' is not defined ``` The name \'bar\' is not found because a higher scope does not have access to the names lower in the hierarchy. It is a common pitfall to fail to lookup an attribute (such as a method) of an object (such as a container) referenced by a variable before the variable is assigned the object. In its most common form: ``` python >>> for x in range(10): y.append(x) # append is an attribute of lists Traceback (most recent call last): File "<pyshell#46>", line 2, in -toplevel- y.append(x) NameError: name 'y' is not defined ``` Here, to correct this problem, one must add y = \[\] before the for loop. A loop does not create its own scope: ``` python for x in [1, 2, 3]: inner = x print(inner) # 3 rather than an error ``` ### Keyword global Global variables of a Python module are read-accessible from functions in that module. In fact, if they are mutable, they can be also modified via method call. However, they cannot modified via a plain assignment unless declared *global* in the function. An example to clarify: ``` python count1 = 1 count2 = 1 list1 = [] list2 = [] def test1(): print(count1) # Read access is unproblematic, referring to the global def test2(): try: print(count1) # This print would be unproblematic, but it throws an error ... count1 += 1 # ... since count1 += 1 causes count1 to be local. except UnboundLocalError as error: print("Error caught:", error) def test3(): list1 = [2] # No outside effect; this rebinds list1 to be a local variable def test4(): global count2, list2 print(count1) # Read access is unproblematic, referring to the global count2 += 1 # We can modify count2 via assignment list1.append(1) # Impacts the global list1 even without global declaration list2 = [2] # Impacts the global list2 test1() test2() test3() test4() print("count1:", count1) # 1 print("count2:", count2) # 2 print("list1:", list1) # [1] print("list2:", list2) # [2] ``` Links: - 6.13. The global statement, docs.python.org - What are the rules for local and global variables in Python? in Programming FAQ, docs.python.org ### Keyword nonlocal Keyword nonlocal, available since Python 3.0, is an analogue of *global* for nested scopes. It enables a nested function of assign-modify a variable that is local to the outer function. An example: ``` python # Requires Python 3 def outer(): outerint = 0 outerint2 = 10 def inner(): nonlocal outerint outerint = 1 # Impacts outer's outerint only because of the nonlocal declaration outerint2 = 1 # No impact inner() print(outerint) print(outerint2) outer() ``` Simulation of nonlocal in Python 2 via a mutable object: ``` python def outer(): outerint = [1] # Technique 1: Store int in a list class outerNL: pass # Technique 2: Store int in a class outerNL.outerint2 = 11 def inner(): outerint[0] = 2 # List members can be modified outerNL.outerint2 = 12 # Class members can be modified inner() print(outerint[0]) print(outerNL.outerint2) outer() ``` Links: - 7.13. The nonlocal statement, docs.python.org ### globals and locals To find out which variables exist in the global and local scopes, you can use *locals()* and *globals()* functions, which return dictionaries: ``` python int1 = 1 def test1(): int1 = 2 globals()["int1"] = 3 # Write access seems possible print(locals()["int1"])# 2 test1() print(int1) # 3 ``` Write access to locals() dictionary is discouraged by the Python documentation. Links: - 2. Built-in Functions \# globals, docs.python.org - 2. Built-in Functions \# locals, docs.python.org ### External links - 4. Execution model, docs.python.org - 7.13. The nonlocal statement, docs.python.org - PEP 3104 \-- Access to Names in Outer Scopes, python.org
# Python Programming/Input and Output ## Input Python 3.x has one function for input from user, `input()`. By contrast, legacy Python 2.x has two functions for input from user: `input()` and `raw_input()`. There are also very simple ways of reading a file and, for stricter control over input, reading from stdin if necessary. ### input() in Python 3.x In Python 3.x, input() asks the user for a string of data (ended with a newline), and simply returns the string. It can also take an argument, which is displayed as a prompt before the user enters the data. E.g. ``` python print(input('What is your name?')) ``` prints out What is your name? <user input data here> Example: to assign the user\'s name, i.e. string data, to a variable \"x\" you would type ``` python x = input('What is your name?') ``` In legacy Python 2.x, the above applies to what was `raw_input()` function, and there was also `input()` function that behaved differently, automatically evaluating what the user entered; in Python 3, the same would be achieved via `eval(input())`. Links: - input() in Built-in Functions in Library Reference for Python 3, docs.python.org - raw_input() in Built-in Functions in Library Reference for Python 2, docs.python.org ### input() in Python 2.x In legacy Python 2.x, input() takes the input from the user as a string and evaluates it. Therefore, if a script says: ``` python x = input('What are the first 10 perfect squares? ') ``` it is possible for a user to input: ``` python map(lambda x: x*x, range(10)) ``` which yields the correct answer in list form. Note that no inputted statement can span more than one line. input() should not be used for anything but the most trivial program, for security reasons. Turning the strings returned from raw_input() into Python types using an idiom such as: ``` python x = None while not x: try: x = int(raw_input()) except ValueError: print('Invalid Number') ``` is preferable, as input() uses eval() to turn a literal into a Python type, which allows a malicious person to run arbitrary code from inside your program trivially. Links: - input() in Built-in Functions in Library Reference for Python 2, docs.python.org ### File Input #### File Objects To read from a file, you can iterate over the lines of the file using *open*: ``` python f = open('test.txt', 'r') for line in f: print(line[0]) f.close() ``` This will print the first character of each line. A newline is attached to the end of each line read this way. The second argument to *open* can be \'r\', \'w\', or \'rw\', among some others. The newer and better way to read from a file: ``` python with open("test.txt", "r") as txt: for line in txt: print(line) ``` The advantage is that the opened file will close itself after finishing the part within the *with* statement, and will do so even if an exception is thrown. Because files are automatically closed when the file object goes out of scope, there is no real need to close them explicitly. So, the loop in the previous code can also be written as: ``` python for line in open('test.txt', 'r'): print(line[0]) ``` You can read a specific numbers of characters at a time: ``` python c = f.read(1) while len(c) > 0: if len(c.strip()) > 0: print(c) c = f.read(1) ``` This will read the characters from f one at a time, and then print them if they\'re not whitespace. A file object implicitly contains a marker to represent the current position. If the file marker should be moved back to the beginning, one can either close the file object and reopen it or just move the marker back to the beginning with: ``` python f.seek(0) ``` #### Standard File Objects There are built-in file objects representing standard input, output, and error. These are in the sys module and are called stdin, stdout, and stderr. There are also immutable copies of these in \_\_stdin\_\_, \_\_stdout\_\_, and \_\_stderr\_\_. This is for IDLE and other tools in which the standard files have been changed. You must import the sys module to use the special stdin, stdout, stderr I/O handles. ``` python import sys ``` For finer control over input, use sys.stdin.read(). To implement the UNIX \'cat\' program in Python, you could do something like this: ``` python import sys for line in sys.stdin: print(line, end="") ``` Note that sys.stdin.read() will read from standard input till EOF. (which is usually Ctrl+D.) ### Parsing command line Command-line arguments passed to a Python program are stored in sys.argv list. The first item in the list is name of the Python program, which may or may not contain the full path depending on the manner of invocation. sys.argv list is modifiable. Printing all passed arguments except for the program name itself: ``` python import sys for arg in sys.argv[1:]: print(arg) ``` Parsing passed arguments for passed minus options: ``` python import sys option_f = False option_p = False option_p_argument = "" i = 1 while i < len(sys.argv): if sys.argv[i] == "-f": option_f = True sys.argv.pop(i) elif sys.argv[i] == "-p": option_p = True sys.argv.pop(i) option_p_argument = sys.argv.pop(i) else: i += 1 ``` Above, the arguments at which options are found are removed so that sys.argv can be looped for all remaining arguments. Parsing of command-line arguments is further supported by library modules optparse (deprecated), argparse (since Python 2.7) and getopt (to make life easy for C programmers). A minimum parsing example for argparse: ``` python import argparse parser = argparse.ArgumentParser(description="Concatenates two strings") addarg = parser.add_argument addarg("s1", help="First string to concatenate") addarg("s2", help="Second string to concatenate") args = parser.parse_args() result = args.s1 + args.s2 print(result) ``` Parse with argparse\--specify the arg type as int: ``` python import argparse parser = argparse.ArgumentParser(description="Sum two ints") addarg = parser.add_argument addarg("i1", help="First int to add", type=int) addarg("i2", help="Second int to add", type=int) args = parser.parse_args() result = args.i1 + args.i2 print(result) ``` Parse with argparse\--add optional switch -m to yield multiplication instead of addition: ``` python import argparse parser = argparse.ArgumentParser(description="Sums or multiplies two ints.") addarg = parser.add_argument addarg("i1", help="First int", type=int) addarg("i2", help="Second int", type=int) addarg("-m", help="Multiplies rather than adds.", action="store_true") args = parser.parse_args() if args.m: result = args.i1 * args.i2 else: result = args.i1 + args.i2 print(result) ``` Parse with argparse\--set an argument to consume one or more items: ``` python import argparse parser = argparse.ArgumentParser(description="Sums one or more ints.") addarg = parser.add_argument addarg("intlist", help="Ints", type=int, nargs="+") args = parser.parse_args() result = 0 for item in args.intlist: result += item print(result) ``` Usage example: python ArgparseTest.py 1 3 5 Parse with argparse\--as above but with a help epilog to be output after parameter descriptions upon -h: ``` python import argparse parser = argparse.ArgumentParser(description="Sums one or more ints.", epilog="Example: python ArgparseTest.py 1 3 5") addarg = parser.add_argument addarg("intlist", help="Ints", type=int, nargs="+") args = parser.parse_args() result = 0 for item in args.intlist: result += item print(result) ``` Parse with argparse\--make second integer argument optional via nargs: ``` python import argparse parser = argparse.ArgumentParser(description="Sums one or two integers.", epilog="Example: python ArgparseTest.py 3 4\n" "Example: python ArgparseTest.py 3") addarg = parser.add_argument addarg("i1", help="First int", type=int) addarg("i2", help="Second int, optional, defaulting to 1.", type=int, default=1, nargs="?") args = parser.parse_args() result = args.i1 + args.i2 print(result) ``` Links: - The Python Standard Library - 28.1. sys, docs.python.org - The Python Standard Library - 15.4. argparse, docs.python.org - The Python Standard Library - 15.5. optparse, docs.python.org - The Python Standard Library - 15.6. getopt, docs.python.org - Argparse Tutorial, docs.python.org ## Output The basic way to do output is the print statement. ``` python print('Hello, world') ``` To print multiple things on the same line separated by spaces, use commas between them: ``` python print('Hello,', 'World') ``` This will print out the following: `Hello, World` While neither string contained a space, a space was added by the print statement because of the comma between the two objects. Arbitrary data types can be printed: ``` python print(1, 2, 0xff, 0777, 10+5j, -0.999, map, sys) ``` This will output the following: `1 2 255 511 (10+5j) -0.999 ``<built-in function map>`{=html}` <module 'sys' (built-in)>` Objects can be printed on the same line without needing to be on the same line: ``` python for i in range(10): print(i, end=" ") ``` This will output the following: `0 1 2 3 4 5 6 7 8 9` To end the printed line with a newline, add a print statement without any objects. ``` python for i in range(10): print(i, end=" ") print() for i in range(10,20): print(i, end=" ") ``` This will output the following: `0 1 2 3 4 5 6 7 8 9`\ `10 11 12 13 14 15 16 17 18 19` If the bare print statement were not present, the above output would look like: `0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19` You can print to a file instead of to standard output: ``` python print('Hello, world', file=f) ``` This will print to any object that implements write(), which includes file objects. Note on legacy Python 2: in Python 2, print is a statement rather than a function and there is no need to put brackets around its arguments. Instead of `print(i, end=" ")`, one would write `print i,`. ### Omitting newlines In Python 3.x, you can output without a newline by passing end=\"\" to the print function or by using the method write: ``` python import sys print("Hello", end="") sys.stdout.write("Hello") # Or stderr to write to standard error stream. ``` In Python 2.x, to avoid adding spaces and newlines between objects\' output with subsequent print statements, you can do one of the following: *Concatenation*: Concatenate the string representations of each object, then later print the whole thing at once. ``` python print(str(1)+str(2)+str(0xff)+str(0777)+str(10+5j)+str(-0.999)+str(map)+str(sys)) ``` This will output the following: `12255511(10+5j)-0.999``<built-in function map>`{=html}`<module 'sys' (built-in)>` *Write function*: You can make a shorthand for *sys.stdout.write* and use that for output. ``` python import sys write = sys.stdout.write write('20') write('05\n') ``` This will output the following: `2005` You may need sys.stdout.flush() to get that text on the screen quickly. ### Examples Examples of output with *Python 3.x*: - from \_\_future\_\_ import print_function - Ensures Python 2.6 and later Python 2.x can use Python 3.x print function. - print(\"Hello\", \"world\") - Prints the two words separated with a space. Notice the surrounding brackets, ununsed in Python 2.x. - print(\"Hello world\", end=\"\") - Prints without the ending newline. - print(\"Hello\", \"world\", sep=\"-\") - Prints the two words separated with a dash. - print(\"Hello\", 34) - Prints elements of various data types, separating them by a space. - print(\"Hello \" + 34) - Throws an error as a result of trying to concatenate a string and an integer. - print(\"Hello \" + str(34)) - Uses \"+\" to concatenate strings, after converting a number to a string. - sum=2+2; print \"The sum: %i\" % sum - Prints a string that has been formatted with the use of an integer passed as an argument. See also #Formatting. ```{=html} <!-- --> ``` - print (\"Error\", file=sys.stderr) - Outputs to a file handle, in this case standard error stream. Examples of output with *Python 2.x*: - print \"Hello\" - print \"Hello\", \"world\" - Separates the two words with a space. - print \"Hello\", 34 - Prints elements of various data types, separating them by a space. - print \"Hello \" + 34 - Throws an error as a result of trying to concatenate a string and an integer. - print \"Hello \" + str(34) - Uses \"+\" to concatenate strings, after converting a number to a string. - print \"Hello\", - Prints \"Hello \" without a newline, with a space at the end. - sys.stdout.write(\"Hello\") - Prints \"Hello\" without a newline. Doing \"import sys\" is a prerequisite. Needs a subsequent \"sys.stdout.flush()\" in order to display immediately on the user\'s screen. - sys.stdout.write(\"Hello\\n\") - Prints \"Hello\" with a newline. - print \>\> sys.stderr, \"An error occurred.\" - Prints to standard error stream. - sys.stderr.write(\"Hello\\n\") - Prints to standard error stream. - sum=2+2; print \"The sum: %i\" % sum - Prints a string that has been formatted with the use of an integer passed as an argument. - formatted_string = \"The sum: %i\" % (2+2); print formatted_string - Like the previous, just that the formatting happens outside of the print statement. - print \"Float: %6.3f\" % 1.23456 - Outputs \"Float: 1.234\". The number 3 after the period specifies the number of decimal digits after the period to be displayed, while 6 before the period specifies the total number of characters the displayed number should take, to be padded with spaces if needed. - print \"%s is %i years old\" % (\"John\", 23) - Passes two arguments to the formatter. ### File Output Printing numbers from 1 to 10 to a file, one per line: ``` python file1 = open("TestFile.txt","w") for i in range(1,10+1): print(i, file=file1) file1.close() ``` With \"w\", the file is opened for writing. With \"file=file1\", print sends its output to a file rather than standard output. Printing numbers from 1 to 10 to a file, separated with a dash: ``` python file1 = open("TestFile.txt", "w") for i in range(1, 10+1): if i > 1: file1.write("-") file1.write(str(i)) file1.close() ``` Opening a file for appending rather than overwriting: ``` python file1 = open("TestFile.txt", "a") ``` In Python 2.x, a redirect to a file is done like `print >>file1, i`. See also ../Files/ chapter. ### Formatting Formatting numbers and other values as strings using the string percent operator: ``` Python v1 = "Int: %i" % 4 # 4 v2 = "Int zero padded: %03i" % 4 # 004 v3 = "Int space padded: %3i" % 4 # 4 v4 = "Hex: %x" % 31 # 1f v5 = "Hex 2: %X" % 31 # 1F - capitalized F v6 = "Oct: %o" % 8 # 10 v7 = "Float: %f" % 2.4 # 2.400000 v8 = "Float: %.2f" % 2.4 # 2.40 v9 = "Float in exp: %e" % 2.4 # 2.400000e+00 vA = "Float in exp: %E" % 2.4 # 2.400000E+00 vB = "List as string: %s" % [1, 2, 3] vC = "Left padded str: %10s" % "cat" vD = "Right padded str: %-10s" % "cat" vE = "Truncated str: %.2s" % "cat" vF = "Dict value str: %(age)s" % {"age": 20} vG = "Char: %c" % 65 # A vH = "Char: %c" % "A" # A ``` Formatting numbers and other values as strings using the format() string method, since Python 2.6: ``` Python v1 = "Arg 0: {0}".format(31) # 31 v2 = "Args 0 and 1: {0}, {1}".format(31, 65) v3 = "Args 0 and 1: {}, {}".format(31, 65) v4 = "Arg indexed: {0[0]}".format(["e1", "e2"]) v5 = "Arg named: {a}".format(a=31) v6 = "Hex: {0:x}".format(31) # 1f v7 = "Hex: {:x}".format(31) # 1f - arg 0 is implied v8 = "Char: {0:c}".format(65) # A v9 = "Hex: {:{h}}".format(31, h="x") # 1f - nested evaluation ``` Formatting numbers and other values as strings using literal string interpolation, since Python 3.6: ``` Python int1 = 31; int2 = 41; str1="aaa"; myhex = "x" v1 = f"Two ints: {int1} {int2}" v2 = f"Int plus 1: {int1+1}" # 32 - expression evaluation v3 = f"Str len: {len(str1)}" # 3 - expression evaluation v4 = f"Hex: {int1:x}" # 1f v5 = f"Hex: {int1:{myhex}}" # 1f - nested evaluation ``` Links: - 5.6.2. String Formatting Operations, docs.python.org - 2. Built-in Functions \# format, docs.python.org - 7.1.2. Custom String Formatting, docs.python.org - 7.1.3.1. Format Specification Mini-Language, docs.python.org - 7.1.4. Template strings, docs.python.org - PEP 3101 \-- Advanced String Formatting, python.org - PEP 498 \-- Literal String Interpolation, python.org ## External Links - 7. Input and Output in The Python Tutorial, python.org - 6.6. The print statement in The Python Language Reference, python.org - 2. Built-in Functions #open in The Python Standard Library at Python Documentation, python.org - 5. Built-in Types #file.write in The Python Standard Library at Python Documentation, python.org - 27.1. sys --- System-specific parameters and functions in Python Documentation, python org \-- mentions sys.stdout, and sys.stderr - 2.3.8 File Objects in Python Library Reference, python.org, for \"flush\" - 5.6.2. String Formatting Operations in The Python Standard Library at Python Documentation, python.org \-- for \"%i\", \"%s\" and similar string formatting - 7.2.2. The string format operator, in Python 2.5 quick reference, nmt.edu, for \"%i\", \"%s\" and similar string formatting
# Python Programming/Files ## File I/O Read entire file: ``` python inputFileText = open("testit.txt", "r").read() print(inputFileText) ``` In this case the \"r\" parameter means the file will be opened in read-only mode. Read certain amount of bytes from a file: ``` python inputFileText = open("testit.txt", "r").read(123) print(inputFileText) ``` When opening a file, one starts reading at the beginning of the file, if one would want more random access to the file, it is possible to use `seek()` to change the current position in a file and `tell()` to get to know the current position in the file. This is illustrated in the following example: ``` python >>> f=open("/proc/cpuinfo","r") >>> f.tell() 0L >>> f.read(10) 'processor\t' >>> f.read(10) ': 0\nvendor' >>> f.tell() 20L >>> f.seek(10) >>> f.tell() 10L >>> f.read(10) ': 0\nvendor' >>> f.close() >>> f <closed file '/proc/cpuinfo', mode 'r' at 0xb7d79770> ``` Here a file is opened, twice ten bytes are read, `tell()` shows that the current offset is at position 20, now `seek()` is used to go back to position 10 (the same position where the second read was started) and ten bytes are read and printed again. And when no more operations on a file are needed the `close()` function is used to close the file we opened. Read one line at a time: ``` python for line in open("testit.txt", "r"): print(line) ``` In this case `readlines()` will return an array containing the individual lines of the file as array entries. Reading a single line can be done using the `readline()` function which returns the current line as a string. This example will output an additional newline between the individual lines of the file, this is because one is read from the file and print introduces another newline. Write to a file requires the second parameter of `open()` to be \"w\", this will overwrite the existing contents of the file if it already exists when opening the file: ``` python outputFileText = "Here's some text to save in a file" open("testit.txt", "w").write(outputFileText) ``` Append to a file requires the second parameter of `open()` to be \"a\" (from append): ``` python outputFileText = "Here's some text to add to the existing file." open("testit.txt", "a").write(outputFileText) ``` Note that this does not add a line break between the existing file content and the string to be added. Since Python 2.5, you can use *with* keyword to ensure the file handle is released as soon as possible and to make it exception-safe: ``` python with open("input.txt") as file1: data = file1.read() # process the data ``` Or one line at a time: ``` python with open("input.txt") as file1: for line in file1: print(line) ``` Related to the *with* keywords is ../Context Managers/ chapter. Links: - 7.5. The with statement, python.org - PEP 343 \-- The \"with\" Statement, python.org ## Testing Files Determine whether path exists: ``` python import os os.path.exists('<path string>') ``` When working on systems such as Microsoft Windows™, the directory separators will conflict with the path string. To get around this, do the following: ``` python import os os.path.exists('C:\\windows\\example\\path') ``` A better way however is to use \"raw\", or `r`: ``` python import os os.path.exists(r'C:\windows\example\path') ``` But there are some other convenient functions in `os.path`, where `os.path.exists()` only confirms whether or not path exists, there are functions which let you know if the path is a file, a directory, a mount point or a symlink. There is even a function `os.path.realpath()` which reveals the true destination of a symlink: ``` python >>> import os >>> os.path.isfile("/") False >>> os.path.isfile("/proc/cpuinfo") True >>> os.path.isdir("/") True >>> os.path.isdir("/proc/cpuinfo") False >>> os.path.ismount("/") True >>> os.path.islink("/") False >>> os.path.islink("/vmlinuz") True >>> os.path.realpath("/vmlinuz") '/boot/vmlinuz-2.6.24-21-generic' ``` ## Common File Operations To copy or move a file, use the shutil library. ``` python import shutil shutil.move("originallocation.txt","newlocation.txt") shutil.copy("original.txt","copy.txt") ``` To perform a recursive copy it is possible to use `copytree()`, to perform a recursive remove it is possible to use `rmtree()` ``` python import shutil shutil.copytree("dir1","dir2") shutil.rmtree("dir1") ``` To remove an individual file there exists the `remove()` function in the os module: ``` python import os os.remove("file.txt") ``` ## Finding Files Files can be found using *glob*: ``` python glob.glob('*.txt') # Finds files in the current directory ending in dot txt glob.glob('*\\*.txt') # Finds files in any of the direct subdirectories # of the currect directory ending in dot txt glob.glob('C:\\Windows\\*.exe') for fileName in glob.glob('C:\\Windows\\*.exe'): print(fileName) glob.glob('C:\\Windows\\**.exe', recursive=True) # Py 3.5: ** allows recursive nesting ``` The content of a directory can be listed using *listdir*: ``` python filesAndDirectories=os.listdir('.') for item in filesAndDirectories: if os.path.isfile(item) and item.endswith('.txt'): print("Text file: " + item) if os.path.isdir(item): print("Directory: " + item) ``` Getting a list of all items in a directory, including the nested ones: ``` python for root, directories, files in os.walk('/user/Joe Hoe'): print("Root: " + root) # e.g. /user/Joe Hoe/Docs for dir1 in directories: print("Dir.: " + dir1) # e.g. Fin print("Dir. 2: " + os.path.join(root, dir1)) # e.g. /user/Joe Hoe/Docs/Fin for file1 in files: print("File: " + file1) # e.g. MyFile.txt print("File 2: " + os.path.join(root, file1))# e.g. /user/Joe Hoe/Docs/MyFile.txt ``` Above, root takes value of each directory in /user/Joe Hoe including /user/Joe Hoe itself, and directories and files are only those directly present in each root. Getting a list of all *files* in a directory, including the nested ones, ending in .txt, using list comprehension: ``` python files = [os.path.join(r, f) for r, d, fs in os.walk(".") for f in fs if f.endswith(".txt")] # As iterator files = (os.path.join(r, f) for r, d, fs in os.walk(".") for f in fs if f.endswith(".txt")) ``` Links: - glob, python.org - glob, Py 3, python.org - os.listdir, python.org - os.walk, python.org - os.path.join, python.org ## Current Directory Getting current working directory: ``` python os.getcwd() ``` Changing current working directory: ``` python os.chdir('C:\\') ``` ## External Links - os --- Miscellaneous operating system interfaces in Python documentation - glob --- Unix style pathname pattern expansion in Python documentation - shutil --- High-level file operations in Python documentation - Brief Tour of the Standard Library in The Python Tutorial
# Python Programming/Modules Modules are a way to structure a program and create reusable libraries. A module is usually stored in and corresponds to a separate .py file. Many modules are available from the standard library. You can create your own modules. Python searches for modules in the current directory and other locations; the list of module search locations can be expanded by expanding PYTHONPATH environment variable and by other means. ## Importing a Module To use the functions and classes offered by a module, you have to import the module: ``` python import math print(math.sqrt(10)) ``` The above imports the math standard module, making all of the functions in that module namespaced by the module name. It imports all functions and all classes, if any. You can import the module under a different name: ``` python import math as Mathematics print(Mathematics.sqrt(10)) ``` You can import a single function, making it available without the module name namespace: ``` python from math import sqrt print(sqrt(10)) ``` You can import a single function and make it available under a different name: ``` python from math import cos as cosine print(cosine(10)) ``` You can import multiple modules in a row: ``` python import os, sys, re ``` You can make an import as late as in a function definition: ``` python def sqrtTen(): import math print(math.sqrt(10)) ``` Such an import only takes place when the function is called. You can import all functions from the module without the module namespace, using an asterisk notation: ``` python from math import * print(sqrt(10)) ``` However, if you do this inside a function, you get a warning in Python 2 and error in Python 3: ``` python def sqrtTen(): from math import * print(sqrt(10)) ``` You can guard for a module not found: ``` python try: import custommodule except ImportError: pass ``` Modules can be different kinds of things: - Python files - Shared Objects (under Unix and Linux) with the .so suffix - DLL\'s (under Windows) with the .pyd suffix - Directories Modules are loaded in the order they\'re found, which is controlled by sys.path. The current directory is always on the path. Directories should include a file in them called \_\_init\_\_.py, which should probably include the other files in the directory. Creating a DLL that interfaces with Python is covered in another section. ## Imported Check You can check whether a module has been imported as follows: ``` python if "re" in sys.modules: print("Regular expression module is ready for use.") ``` Links: - 28.1. sys \# sys.modules, docs.python.org ## Creating a Module ### From a File The easiest way to create a module is by having a file called mymod.py either in a directory recognized by the PYTHONPATH variable or (even easier) in the same directory where you are working. If you have the following file mymod.py ``` python class Object1: def __init__(self): self.name = 'object 1' ``` you can already import this \"module\" and create instances of the object *Object1*. ``` python import mymod myobject = mymod.Object1() from mymod import * myobject = Object1() ``` ### From a Directory It is not feasible for larger projects to keep all classes in a single file. It is often easier to store all files in directories and load all files with one command. Each directory needs to have a `__init__.py` file which contains python commands that are executed upon loading the directory. Suppose we have two more objects called `Object2` and `Object3` and we want to load all three objects with one command. We then create a directory called *mymod* and we store three files called `Object1.py`, `Object2.py` and `Object3.py` in it. These files would then contain one object per file but this not required (although it adds clarity). We would then write the following `__init__.py` file: ``` python from Object1 import * from Object2 import * from Object3 import * __all__ = ["Object1", "Object2", "Object3"] ``` The first three commands tell python what to do when somebody loads the module. The last statement defining \_\_all\_\_ tells python what to do when somebody executes *from mymod import \**. Usually we want to use parts of a module in other parts of a module, e.g. we want to use Object1 in Object2. We can do this easily with an *from . import \** command as the following file *Object2.py* shows: ``` python from . import * class Object2: def __init__(self): self.name = 'object 2' self.otherObject = Object1() ``` We can now start python and import *mymod* as we have in the previous section. ## Making a program usable as a module In order to make a program usable both as a standalone program to be called from a command line and as a module, it is advisable that you place all code in functions and methods, designate one function as the main one, and call then main function when \_\_name\_\_ built-in equals \'\_\_main\_\_\'. The purpose of doing so is to make sure that the code you have placed in the main function is not called when your program is imported as a module; the code would be called upon import if it were placed outside of functions and methods. Your program, stored in mymodule.py, can look as follows: ``` python def reusable_function(x, y): return x + y def main(): pass # Any code you like if __name__ == '__main__': main() ``` The uses of the above program can look as follows: ``` python from mymodule import reusable_function my_result = reusable_function(4, 5) ``` Links: - The Python Tutorial - 6.1.1. Executing modules as scripts, python.org ## Extending Module Path When import is requested, modules are searched in the directories (and zip files?) in the module path, accessible via sys.path, a Python list. The module path can be extended as follows: ``` python import sys sys.path.append("/My/Path/To/Module/Directory") from ModuleFileName import my_function ``` Above, if ModuleFileName.py is located at /My/Path/To/Module/Directory and contains a definition of my_function, the 2nd line ensures the 3rd line actually works. Links: - The Module Search Path at Python doc ## Module Names Module names seem to be limited to alphanumeric characters and underscore; dash cannot be used. While my-module.py can be created and run, importing my-module fails. The name of a module is the name of the module file minus the .py suffix. Module names are case sensitive. If the module file is called MyModule.py, doing \"import mymodule\" fails while \"import MyModule\" is fine. PEP 0008 recommends module names to be in all lowercase, with possible use of underscores. Examples of module names from the standard library include math, sys, io, re, urllib, difflib, and unicodedata. Links: - Package and Module Names at PEP 0008 \-- Style Guide for Python Code - The Python Standard Library at docs.python.org ## Built-in Modules For a module to be built-in is not the same as to be part of the standard library. For instance, re is not a built-in module but rather a module written in Python. By contrast, \_sre is a built-in module. Obtaining a list of built-in module names: `print(sys.builtin_module_names)`\ `print("_sre" in sys.builtin_module_names) # True`\ `print("math" in sys.builtin_module_names) # True` Links: - 28.1. sys \# sys.builtin_module_names, docs.python.org - The Python Standard Library, docs.python.org ## External links - 6. Modules, The Python Tutorial, python.org - Python Module Index, python.org - 31. Importing Modules, python.org - Installing Python Modules, python.org - Idioms and Anti-Idioms in Python, python.org - Python: Why should \'from `<module>`{=html} import \*\' be prohibited?, stackoverflow.com - Error handling when importing modules, stackoverflow.com
# Python Programming/Classes Classes are a way of aggregating similar data and functions. A class is basically a scope inside which various code (especially function definitions) is executed, and the locals to this scope become *attributes* of the class, and of any objects constructed by this class. An object constructed by a class is called an *instance* of that class. ### Overview Classes in Python at a glance: ``` python import math class MyComplex: """A complex number""" # Class documentation classvar = 0.0 # A class attribute, not an instance one def phase(self): # A method return math.atan2(self.imaginary, self.real) def __init__(self): # A constructor """A constructor""" self.real = 0.0 # An instance attribute self.imaginary = 0.0 c1 = MyComplex() c1.real = 3.14 # No access protection c1.imaginary = 2.71 phase = c1.phase() # Method call c1.undeclared = 9.99 # Add an instance attribute del c1.undeclared # Delete an instance attribute print(vars(c1)) # Attributes as a dictionary vars(c1)["undeclared2"] = 7.77 # Write access to an attribute print(c1.undeclared2) # 7.77, indeed MyComplex.classvar = 1 # Class attribute access print(c1.classvar == 1) # True; class attribute access, not an instance one print("classvar" in vars(c1)) # False c1.classvar = -1 # An instance attribute overshadowing the class one MyComplex.classvar = 2 # Class attribute access print(c1.classvar == -1) # True; instance attribute access print("classvar" in vars(c1)) # True class MyComplex2(MyComplex): # Class derivation or inheritance def __init__(self, re = 0, im = 0): self.real = re # A constructor with multiple arguments with defaults self.imaginary = im def phase(self): print("Derived phase") return MyComplex.phase(self) # Call to a base class; "super" c3 = MyComplex2() c4 = MyComplex2(1, 1) c4.phase() # Call to the method in the derived class class Record: pass # Class as a record/struct with arbitrary attributes record = Record() record.name = "Joe" record.surname = "Hoe" ``` ### Defining a Class To define a class, use the following format: ``` python class ClassName: "Here is an explanation about your class" pass ``` The capitalization in this class definition is the convention, but is not required by the language. It\'s usually good to add at least a short explanation of what your class is supposed to do. The pass statement in the code above is just to say to the python interpreter just go on and do nothing. You can remove it as soon as you are adding your first statement. ### Instance Construction The class is a callable object that constructs an instance of the class when called. Let\'s say we create a class Foo. ``` python class Foo: "Foo is our new toy." pass ``` To construct an instance of the class, Foo, \"call\" the class object: ``` python f = Foo() ``` This constructs an instance of class Foo and creates a reference to it in f. ### Class Members In order to access the member of an instance of a class, use the syntax `<class instance>`{=html}.`<member>`{=html}. It is also possible to access the members of the class definition with `<class name>`{=html}.`<member>`{=html}. #### Methods A method is a function within a class. The first argument (methods must always take at least one argument) is always the instance of the class on which the function is invoked. For example ``` python >>> class Foo: ... def setx(self, x): ... self.x = x ... def bar(self): ... print(self.x) ``` If this code were executed, nothing would happen, at least until an instance of Foo were constructed, and then bar were called on that instance. ##### Why a mandatory argument? In a normal function, if you were to set a variable, such as `test = 23`, you could not access the test variable. Typing `test` would say it is not defined. This is true in class functions unless they use the `self` variable. Basically, in the previous example, if we were to remove self.x, function bar could not do anything because it could not access x. The x in setx() would disappear. The self argument saves the variable into the class\'s \"shared variables\" database. ##### Why self? You do not need to use self. However, it is a norm to use self. #### Invoking Methods Calling a method is much like calling a function, but instead of passing the instance as the first parameter like the list of formal parameters suggests, use the function as an attribute of the instance. ``` python >>> f = Foo() >>> f.setx(5) >>> f.bar() ``` This will output `5` It is possible to call the method on an arbitrary object, by using it as an attribute of the defining class instead of an instance of that class, like so: ``` python >>> Foo.setx(f,5) >>> Foo.bar(f) ``` This will have the same output. #### Dynamic Class Structure As shown by the method setx above, the members of a Python class can change during runtime, not just their values, unlike classes in languages like C++ or Java. We can even delete f.x after running the code above. ``` python >>> del f.x >>> f.bar() ``` `Traceback (most recent call last):`\ `  File "``<stdin>`{=html}`", line 1, in ?`\ `  File "``<stdin>`{=html}`", line 5, in bar`\ `AttributeError: Foo instance has no attribute 'x'` Another effect of this is that we can change the definition of the Foo class during program execution. In the code below, we create a member of the Foo class definition named y. If we then create a new instance of Foo, it will now have this new member. ``` python >>> Foo.y = 10 >>> g = Foo() >>> g.y 10 ``` ##### Viewing Class Dictionaries At the heart of all this is a dictionary that can be accessed by \"vars(ClassName)\" ``` python >>> vars(g) {} ``` At first, this output makes no sense. We just saw that g had the member y, so why isn\'t it in the member dictionary? If you remember, though, we put y in the class definition, Foo, not g. ``` python >>> vars(Foo) {'y': 10, 'bar': <function bar at 0x4d6a3c>, '__module__': '__main__', 'setx': <function setx at 0x4d6a04>, '__doc__': None} ``` And there we have all the members of the Foo class definition. When Python checks for g.member, it first checks g\'s vars dictionary for \"member,\" then Foo. If we create a new member of g, it will be added to g\'s dictionary, but not Foo\'s. ``` python >>> g.setx(5) >>> vars(g) {'x': 5} ``` Note that if we now assign a value to g.y, we are not assigning that value to Foo.y. Foo.y will still be 10, but g.y will now override Foo.y ``` python >>> g.y = 9 >>> vars(g) {'y': 9, 'x': 5} >>> vars(Foo) {'y': 10, 'bar': <function bar at 0x4d6a3c>, '__module__': '__main__', 'setx': <function setx at 0x4d6a04>, '__doc__': None} ``` Sure enough, if we check the values: ``` python >>> g.y 9 >>> Foo.y 10 ``` Note that f.y will also be 10, as Python won\'t find \'y\' in vars(f), so it will get the value of \'y\' from vars(Foo). Some may have also noticed that the methods in Foo appear in the class dictionary along with the x and y. If you remember from the section on lambda functions, we can treat functions just like variables. This means that we can assign methods to a class during runtime in the same way we assigned variables. If you do this, though, remember that if we call a method of a class instance, the first parameter passed to the method will always be the class instance itself. ##### Changing Class Dictionaries We can also access the members dictionary of a class using the \_\_dict\_\_ member of the class. ``` python >>> g.__dict__ {'y': 9, 'x': 5} ``` If we add, remove, or change key-value pairs from g.\_\_dict\_\_, this has the same effect as if we had made those changes to the members of g. ``` python >>> g.__dict__['z'] = -4 >>> g.z -4 ``` ### Why use classes? Classes are special due to the fact once an instance is made, the instance is independent of all other instances. I could have two instances, each with a different x value, and they will not affect the other\'s x. ``` python f = Foo() f.setx(324) f.boo() g = Foo() g.setx(100) g.boo() ``` `f.boo()` and `g.boo()` will print different values. ### New Style Classes New style classes were introduced in python 2.2. A new-style class is a class that has a built-in as its base, most commonly object. At a low level, a major difference between old and new classes is their type. Old class instances were all of type `instance`. New style class instances will return the same thing as x.\_\_class\_\_ for their type. This puts user defined classes on a level playing field with built-ins. Old/Classic classes are slated to disappear in Python 3. With this in mind all development should use new style classes. New Style classes also add constructs like properties and static methods familiar to Java programmers. Old/Classic Class ``` python >>> class ClassicFoo: ... def __init__(self): ... pass ``` New Style Class ``` python >>> class NewStyleFoo(object): ... def __init__(self): ... pass ``` #### Properties Properties are attributes with getter and setter methods. ``` python >>> class SpamWithProperties(object): ... def __init__(self): ... self.__egg = "MyEgg" ... def get_egg(self): ... return self.__egg ... def set_egg(self, egg): ... self.__egg = egg ... egg = property(get_egg, set_egg) >>> sp = SpamWithProperties() >>> sp.egg 'MyEgg' >>> sp.egg = "Eggs With Spam" >>> sp.egg 'Eggs With Spam' >>> ``` and since Python 2.6, with \@property decorator ``` python >>> class SpamWithProperties(object): ... def __init__(self): ... self.__egg = "MyEgg" ... @property ... def egg(self): ... return self.__egg ... @egg.setter ... def egg(self, egg): ... self.__egg = egg ``` #### Static Methods Static methods in Python are just like their counterparts in C++ or Java. Static methods have no \"self\" argument and don\'t require you to instantiate the class before using them. They can be defined using staticmethod() ``` python >>> class StaticSpam(object): ... def StaticNoSpam(): ... print("You can't have have the spam, spam, eggs and spam without any spam... that's disgusting") ... NoSpam = staticmethod(StaticNoSpam) >>> StaticSpam.NoSpam() You can't have have the spam, spam, eggs and spam without any spam... that's disgusting ``` They can also be defined using the function decorator \@staticmethod. ``` python >>> class StaticSpam(object): ... @staticmethod ... def StaticNoSpam(): ... print("You can't have have the spam, spam, eggs and spam without any spam... that's disgusting") ``` ### Inheritance Like all object oriented languages, Python provides support for inheritance. Inheritance is a simple concept by which a class can extend the facilities of another class, or in Python\'s case, multiple other classes. Use the following format for this: ``` python class ClassName(BaseClass1, BaseClass2, BaseClass3,...): ... ``` ClassName is what is known as the derived class, that is, derived from the base classes. The derived class will then have all the members of its base classes. If a method is defined in the derived class and in the base class, the member in the derived class will override the one in the base class. In order to use the method defined in the base class, it is necessary to call the method as an attribute on the defining class, as in Foo.setx(f,5) above: ``` python >>> class Foo: ... def bar(self): ... print("I'm doing Foo.bar()") ... x = 10 ... >>> class Bar(Foo): ... def bar(self): ... print("I'm doing Bar.bar()") ... Foo.bar(self) ... y = 9 ... >>> g = Bar() >>> Bar.bar(g) I'm doing Bar.bar() I'm doing Foo.bar() >>> g.y 9 >>> g.x 10 ``` Once again, we can see what\'s going on under the hood by looking at the class dictionaries. ``` python >>> vars(g) {} >>> vars(Bar) {'y': 9, '__module__': '__main__', 'bar': <function bar at 0x4d6a04>, '__doc__': None} >>> vars(Foo) {'x': 10, '__module__': '__main__', 'bar': <function bar at 0x4d6994>, '__doc__': None} ``` When we call g.x, it first looks in the vars(g) dictionary, as usual. Also as above, it checks vars(Bar) next, since g is an instance of Bar. However, thanks to inheritance, Python will check vars(Foo) if it doesn\'t find x in vars(Bar). ### Multiple inheritance As shown in section #Inheritance, a class can be derived from multiple classes: ``` python class ClassName(BaseClass1, BaseClass2, BaseClass3): pass ``` A tricky part about multiple inheritance is method resolution: upon a method call, if the method name is available from multiple base classes or their base classes, which base class method should be called. The method resolution order depends on whether the class is an old-style class or a new-style class. For old-style classes, derived classes are considered from left to right, and base classes of base classes are considered before moving to the right. Thus, above, BaseClass1 is considered first, and if method is not found there, the base classes of BaseClass1 are considered. If that fails, BaseClass2 is considered, then its base classes, and so on. For new-style classes, see the Python documentation online. Links: - 9.5.1. Multiple Inheritance, docs.python.org - The Python 2.3 Method Resolution Order, python.org ### Special Methods There are a number of methods which have reserved names which are used for special purposes like mimicking numerical or container operations, among other things. All of these names begin and end with two underscores. It is convention that methods beginning with a single underscore are \'private\' to the scope they are introduced within. #### Initialization and Deletion ##### \_\_init\_\_ One of these purposes is constructing an instance, and the special name for this is \'\_\_init\_\_\'. \_\_init\_\_() is called before an instance is returned (it is not necessary to return the instance manually). As an example, ``` python class A: def __init__(self): print('A.__init__()') a = A() ``` outputs `A.__init__()` \_\_init\_\_() can take arguments, in which case it is necessary to pass arguments to the class in order to create an instance. For example, ``` python class Foo: def __init__ (self, printme): print(printme) foo = Foo('Hi!') ``` outputs `Hi!` Here is an example showing the difference between using \_\_init\_\_() and not using \_\_init\_\_(): ``` python class Foo: def __init__ (self, x): print(x) foo = Foo('Hi!') class Foo2: def setx(self, x): print(x) f = Foo2() Foo2.setx(f,'Hi!') ``` outputs `Hi!`\ `Hi!` ##### \_\_del\_\_ Similarly, \'\_\_del\_\_\' is called when an instance is destroyed; e.g. when it is no longer referenced. ##### \_\_enter\_\_ and \_\_exit\_\_ These methods are also a constructor and a destructor but they\'re only executed when the class is instantiated with `with`. Example: ``` python class ConstructorsDestructors: def __init__(self): print('init') def __del__(self): print('del') def __enter__(self): print('enter') def __exit__(self, exc_type, exc_value, traceback): print('exit') with ConstructorsDestructors(): pass ``` `init`\ `enter`\ `exit`\ `del` ##### \_\_new\_\_ constructor. #### Representation +----------------------------------+---------------------------------:+ | ##### \_\_str\_\_ | Function Operator | | | --------- | | Converting an object to a | -------- ----------------------- | | string, as with the print | \_\_str\_\_ str(A) | | statement or with the str() | \_\_repr\_\_ repr(A) | | conversion function, can be | \_\_uni | | overridden by overriding | code\_\_ unicode(x) (2.x only) | | \_\_str\_\_. Usually, | | | \_\_str\_\_ returns a formatted | : String Representation | | version of the objects content. | Override Functions | | This will NOT usually be | | | something that can be executed. | | | | | | For example: | | | | | | ``` python | | | class Bar: | | | | | | def __init__ (self, iamthis): | | | self.iamthis = iamthis | | | def __str__ (self): | | | return self.iamthis | | | bar = Bar('apple') | | | print(bar) | | | ``` | | | | | | outputs | | | | | | `apple` | | | | | | ##### \_\_repr\_\_ | | | | | | This function is much like | | | \_\_str\_\_(). If \_\_str\_\_ is | | | not present but this one is, | | | this function\'s output is used | | | instead for printing. | | | \_\_repr\_\_ is used to return a | | | representation of the object in | | | string form. In general, it can | | | be executed to get back the | | | original object. | | | | | | For example: | | | | | | ``` python | | | class Bar: | | | | | | def __init__ (self, iamthis): | | | self.iamthis = iamthis | | | def __repr__(self): | | | r | | | eturn "Bar('%s')" % self.iamthis | | | bar = Bar('apple') | | | bar | | | ``` | | | | | | outputs (note the difference: it | | | may not be necessary to put it | | | inside a print, however in | | | Python 2.7 it does) | | | | | | `Bar('apple')` | | +----------------------------------+----------------------------------+ #### Attributes +----------------------------------+---------------------------------:+ | ## | Function | | ### \_\_setattr\_\_ | Indirect form Direct Form | | | ----------------- | | This is the function which is in | ------------------ ------------- | | charge of setting attributes of | \_\_geta | | a class. It is provided with the | ttr\_\_ getattr(A, B) A.B | | name and value of the variables | \_\_setattr\ | | being assigned. Each class, of | _\_ setattr(A, B, C) A.B = C | | course, comes with a default | \_\_delattr\ | | \_\_setattr\_\_ which simply | _\_ delattr(A, B) del A.B | | sets the value of the variable, | | | but we can override it. | : Attribute Override Functions | | | | | ``` python | | | >>> class Unchangable: | | | ... def | | | __setattr__(self, name, value): | | | ... print("Nice try") | | | ... | | | >>> u = Unchangable() | | | >>> u.x = 9 | | | Nice try | | | >>> u.x | | | ``` | | | | | | `Trac | | | eback (most recent call last):`\ | | | `  File "``< | | | stdin>`{=html}`", line 1, in ?`\ | | | `AttributeError: Unchangabl | | | e instance has no attribute 'x'` | | | | | | ##### | | | \_\_getattr\_\_\_ | | | | | | Similar to \_\_setattr\_\_, | | | except this function is called | | | when we try to access a class | | | member, and the default simply | | | returns the value. | | | | | | ``` python | | | >>> class HiddenMembers: | | | ... | | | def __getattr__(self, name): | | | ... retur | | | n "You don't get to see " + name | | | ... | | | >>> h = HiddenMembers() | | | >>> h.anything | | | "You don't get to see anything" | | | ``` | | | | | | ## | | | ### \_\_delattr\_\_ | | | | | | This function is called to | | | delete an attribute. | | | | | | ``` python | | | >>> class Permanent: | | | ... | | | def __delattr__(self, name): | | | ... | | | print(name, "cannot be deleted") | | | ... | | | >>> p = Permanent() | | | >>> p.x = 9 | | | >>> del p.x | | | x cannot be deleted | | | >>> p.x | | | 9 | | | ``` | | +----------------------------------+----------------------------------+ #### Operator Overloading Operator overloading allows us to use the built-in Python syntax and operators to call functions which we define. ##### Binary Operators +----------------------------------+---------------------------------:+ | If a class has the \_\_add\_\_ | + | | function, we can use the \'+\' | ------------------+------------+ | | operator to add instances of the | | | | class. This will call | Function | Operator | | | \_\_add\_\_ with the two | + | | instances of the class passed as | ==================+============+ | | parameters, and the return value | | | | will be the result of the | \_\_add\_\_ | A + B | | | addition. | + | | | ------------------+------------+ | | ``` python | | | | >>> class FakeNumber: | \_\_sub\_\_ | A - B | | | ... n = 5 | + | | ... def __add__(A,B): | ------------------+------------+ | | ... return A.n + B.n | | | | ... | \_\_mul\_\_ | A \* B | | | >>> c = FakeNumber() | + | | >>> d = FakeNumber() | ------------------+------------+ | | >>> d.n = 7 | | | | >>> c + d | \_\_truediv\_\_ | A / B | | | 12 | + | | ``` | ------------------+------------+ | | | | | | To override the augmented | \_\_floordiv\_\_ | A // B | | | assignmen | + | | t | | | | operators, merely add \'i\' in | \_\_mod\_\_ | A % B | | | front of the normal binary | + | | operator, i.e. for \'+=\' use | ------------------+------------+ | | \'\_\_iadd\_\_\' instead of | | | | \'\_\_add\_\_\'. The function | \_\_pow\_\_ | A \*\* B | | | will be given one argument, | + | | which will be the object on the | ------------------+------------+ | | right side of the augmented | | | | assignment operator. The | \_\_and\_\_ | A & B | | | returned value of the function | + | | will then be assigned to the | ------------------+------------+ | | object on the left of the | | | | operator. | \_\_or\_\_ | A \| B | | | | + | | ``` python | ------------------+------------+ | | >> | | | | > c.__imul__ = lambda B: B.n - 6 | \_\_xor\_\_ | A \^ B | | | >>> c *= d | + | | >>> c | ------------------+------------+ | | 1 | | | | ``` | \_\_eq\_\_ | A == B | | | | + | | It is important to note that the | ------------------+------------+ | | augmented | | | | assignmen | \_\_ne\_\_ | A != B | | | t | ------------------+------------+ | | operators will also use the | | | | normal operator functions if the | \_\_gt\_\_ | A \> B | | | augmented operator function | + | | hasn\'t been set directly. This | ------------------+------------+ | | will work as expected, with | | | | \"\_\_add\_\_\" being called for | \_\_lt\_\_ | A \< B | | | \"+=\" and so on. | + | | | ------------------+------------+ | | ``` python | | | | >>> c = FakeNumber() | \_\_ge\_\_ | A \>= B | | | >>> c += d | + | | >>> c | ------------------+------------+ | | 12 | | | | ``` | \_\_le\_\_ | A \<= B | | | | + | | | ------------------+------------+ | | | | | | | \_\_lshift\_\_ | A \<\< B | | | | + | | | ------------------+------------+ | | | | | | | \_\_rshift\_\_ | A \>\> B | | | | + | | | ------------------+------------+ | | | | | | | \_\_contains\_\_ | A in B\ | | | | | | | | | A not in B | | | | + | | | ------------------+------------+ | | | | | | : Binary Operator Override | | | Functions | +----------------------------------+----------------------------------+ ##### Unary Operators +----------------------------------+---------------------------------:+ | Unary operators will be passed | Function Operator | | simply the instance of the class | ------------- ---------- | | that they are called on. | \_\_pos\_\_ +A | | | \_\_neg\_\_ -A | | ``` python | \_\_inv\_\_ \~A | | >>> FakeNum | \_\_abs\_\_ abs(A) | | ber.__neg__ = lambda A : A.n + 6 | \_\_len\_\_ len(A) | | >>> -d | | | 13 | : Unary Operator Override | | ``` | Functions | +----------------------------------+----------------------------------+ ##### Item Operators +----------------------------------+---------------------------------:+ | It is also possible in Python to | Function Operator | | override the indexing and | - | | slic | ----------------- -------------- | | ing | \_\_setitem\_\_ C\[i\] = v | | operators. This allows us to use | \_\_delitem\_\_ del C\[i\] | | the class\[i\] and class\[a:b\] | \_\_getslice\_\_ C\[s:e\] | | syntax on our own objects. | | | | \_\_setslice\_\_ C\[s:e\] = v | | The simplest form of item | | | operator is \_\_getitem\_\_. | \_\_delslice\_\_ del C\[s:e\] | | This takes as a parameter the | | | instance of the class, then the | : Item Operator Override | | value of the index. | Functions | | | | | ``` python | | | >>> class FakeList: | | | ... | | | def __getitem__(self,index): | | | ... return index * 2 | | | ... | | | >>> f = FakeList() | | | >>> f['a'] | | | 'aa' | | | ``` | | | | | | We can also define a function | | | for the syntax associated with | | | assigning a value to an item. | | | The parameters for this function | | | include the value being | | | assigned, in addition to the | | | parameters from \_\_getitem\_\_ | | | | | | ``` python | | | >>> class FakeList: | | | ... de | | | f __setitem__(self,index,value): | | | ... self.str | | | ing = index + " is now " + value | | | ... | | | >>> f = FakeList() | | | >>> f['a'] = 'gone' | | | >>> f.string | | | 'a is now gone' | | | ``` | | | | | | We can do the same thing with | | | slices. Once again, each syntax | | | has a different parameter list | | | associated with it. | | | | | | ``` python | | | >>> class FakeList: | | | ... de | | | f __getslice___(self,start,end): | | | ... retur | | | n str(start) + " to " + str(end) | | | ... | | | >>> f = FakeList() | | | >>> f[1:4] | | | '1 to 4' | | | ``` | | | | | | Keep in mind that one or both of | | | the start and end parameters can | | | be blank in slice syntax. Here, | | | Python has default value for | | | both the start and the end, as | | | show below. | | | | | | ``` python | | | >> f[:] | | | '0 to 2147483647' | | | ``` | | | | | | Note that the default value for | | | the end of the slice shown here | | | is simply the largest possible | | | signed integer on a 32-bit | | | system, and may vary depending | | | on your system and C compiler. | | | | | | - \_\_setslice\_\_ has the | | | parameters | | | (self,start,end,value) | | | | | | We also have operators for | | | deleting items and slices. | | | | | | - \_\_delitem\_\_ has the | | | parameters (self,index) | | | - \_\_delslice\_\_ has the | | | parameters (self,start,end) | | | | | | Note that these are the same as | | | \_\_getitem\_\_ and | | | \_\_getslice\_\_. | | +----------------------------------+----------------------------------+ #### Other Overrides +---+-----------------------------------------------:+ | | Function Operator | | | ------------------ ------------------------- | | | \_\_cmp\_\_ cmp(x, y) | | | \_\_hash\_\_ hash(x) | | | \_\_nonzero\_\_ bool(x) | | | \_\_call\_\_ f(x) | | | \_\_iter\_\_ iter(x) | | | \_\_reversed\_\_ reversed(x) (2.6+) | | | \_\_divmod\_\_ divmod(x, y) | | | \_\_int\_\_ int(x) | | | \_\_long\_\_ long(x) | | | \_\_float\_\_ float(x) | | | \_\_complex\_\_ complex(x) | | | \_\_hex\_\_ hex(x) | | | \_\_oct\_\_ oct(x) | | | \_\_index\_\_ | | | \_\_copy\_\_ copy.copy(x) | | | \_\_deepcopy\_\_ copy.deepcopy(x) | | | \_\_sizeof\_\_ sys.getsizeof(x) (2.6+) | | | \_\_trunc\_\_ math.trunc(x) (2.6+) | | | \_\_format\_\_ format(x, \...) (2.6+) | | | | | | : Other Override Functions | +---+------------------------------------------------+ ### Programming Practices The flexibility of python classes means that classes can adopt a varied set of behaviors. For the sake of understandability, however, it\'s best to use many of Python\'s tools sparingly. Try to declare all methods in the class definition, and always use the `<class>`{=html}.`<member>`{=html} syntax instead of \_\_dict\_\_ whenever possible. Look at classes in C++ and Java#Java "wikilink") to see what most programmers will expect from a class. #### Encapsulation Since all python members of a python class are accessible by functions/methods outside the class, there is no way to enforce encapsulation short of overriding \_\_getattr\_\_, \_\_setattr\_\_ and \_\_delattr\_\_. General practice, however, is for the creator of a class or module to simply trust that users will use only the intended interface and avoid limiting access to the workings of the module for the sake of users who do need to access it. When using parts of a class or module other than the intended interface, keep in mind that the those parts may change in later versions of the module, and you may even cause errors or undefined behaviors in the module.since encapsulation is private. #### Doc Strings When defining a class, it is convention to document the class using a string literal at the start of the class definition. This string will then be placed in the \_\_doc\_\_ attribute of the class definition. ``` python >>> class Documented: ... """This is a docstring""" ... def explode(self): ... """ ... This method is documented, too! The coder is really serious about ... making this class usable by others who don't know the code as well ... as he does. ... ... """ ... print("boom") >>> d = Documented() >>> d.__doc__ 'This is a docstring' ``` Docstrings are a very useful way to document your code. Even if you never write a single piece of separate documentation (and let\'s admit it, doing so is the lowest priority for many coders), including informative docstrings in your classes will go a long way toward making them usable. Several tools exist for turning the docstrings in Python code into readable API documentation, *e.g.*, EpyDoc. Don\'t just stop at documenting the class definition, either. Each method in the class should have its own docstring as well. Note that the docstring for the method *explode* in the example class *Documented* above has a fairly lengthy docstring that spans several lines. Its formatting is in accordance with the style suggestions of Python\'s creator, Guido van Rossum in PEP 8. #### Adding methods at runtime ##### To a class It is fairly easy to add methods to a class at runtime. Lets assume that we have a class called *Spam* and a function cook. We want to be able to use the function cook on all instances of the class Spam: ``` python class Spam: def __init__(self): self.myeggs = 5 def cook(self): print("cooking %s eggs" % self.myeggs) Spam.cook = cook #add the function to the class Spam eggs = Spam() #NOW create a new instance of Spam eggs.cook() #and we are ready to cook! ``` This will output `cooking 5 eggs` ##### To an instance of a class It is a bit more tricky to add methods to an instance of a class that has already been created. Lets assume again that we have a class called *Spam* and we have already created eggs. But then we notice that we wanted to cook those eggs, but we do not want to create a new instance but rather use the already created one: ``` python class Spam: def __init__(self): self.myeggs = 5 eggs = Spam() def cook(self): print("cooking %s eggs" % self.myeggs) import types f = types.MethodType(cook, eggs, Spam) eggs.cook = f eggs.cook() ``` Now we can cook our eggs and the last statement will output: `cooking 5 eggs` ##### Using a function We can also write a function that will make the process of adding methods to an instance of a class easier. ``` python def attach_method(fxn, instance, myclass): f = types.MethodType(fxn, instance, myclass) setattr(instance, fxn.__name__, f) ``` All we now need to do is call the attach_method with the arguments of the function we want to attach, the instance we want to attach it to and the class the instance is derived from. Thus our function call might look like this: ``` python attach_method(cook, eggs, Spam) ``` Note that in the function add_method we cannot write `instance.fxn = f` since this would add a function called fxn to the instance. ### External links - 9. Classes, docs.python.org - 2. Built-in Functions \# vars, docs.python.org fr:Programmation Python/Programmation orienté objet pt:Python/Conceitos básicos/Classes
# Python Programming/Exceptions Python 2 handles all errors with exceptions. An *exception* is a signal that an error or other unusual condition has occurred. There are a number of built-in exceptions, which indicate conditions like reading past the end of a file, or dividing by zero. You can also define your own exceptions. ### Overview Exceptions in Python at a glance: ``` Python import random try: ri = random.randint(0, 2) if ri == 0: infinity = 1/0 elif ri == 1: raise ValueError("Message") #raise ValueError, "Message" # Deprecated elif ri == 2: raise ValueError # Without message except ZeroDivisionError: pass except ValueError as valerr: # except ValueError, valerr: # Deprecated? print(valerr) raise # Raises the exception just caught except: # Any other exception pass finally: # Optional pass # Clean up class CustomValueError(ValueError): pass # Custom exception try: raise CustomValueError raise TypeError except (ValueError, TypeError): # Value error catches custom, a derived class, as well pass # A tuple catches multiple exception classes ``` ### Raising exceptions Whenever your program attempts to do something erroneous or meaningless, Python raises exception to such conduct: ``` python >>> 1 / 0 Traceback (most recent call last): File "<stdin>", line 1, in ? ZeroDivisionError: integer division or modulo by zero ``` This *traceback* indicates that the `ZeroDivisionError` exception is being raised. This is a built-in exception \-- see below for a list of all the other ones. ### Catching exceptions In order to handle errors, you can set up *exception handling blocks* in your code. The keywords `try` and `except` are used to catch exceptions. When an error occurs within the `try` block, Python looks for a matching `except` block to handle it. If there is one, execution jumps there. If you execute this code: ``` python try: print(1/0) except ZeroDivisionError: print("You can't divide by zero!") ``` Then Python will print this: You can\'t divide by zero! If you don\'t specify an exception type on the `except` line, it will cheerfully catch all exceptions. This is generally a bad idea in production code, since it means your program will blissfully ignore *unexpected* errors as well as ones which the `except` block is actually prepared to handle. Exceptions can propagate up the call stack: ``` python def f(x): return g(x) + 1 def g(x): if x < 0: raise ValueError, "I can't cope with a negative number here." else: return 5 try: print(f(-6)) except ValueError: print("That value was invalid.") ``` In this code, the `print` statement calls the function `f`. That function calls the function `g`, which will raise an exception of type ValueError. Neither `f` nor `g` has a `try`/`except` block to handle ValueError. So the exception raised propagates out to the main code, where there *is* an exception-handling block waiting for it. This code prints: That value was invalid. Sometimes it is useful to find out exactly what went wrong, or to print the python error text yourself. For example: ``` python try: the_file = open("the_parrot") except IOError, (ErrorNumber, ErrorMessage): if ErrorNumber == 2: # file not found print("Sorry, 'the_parrot' has apparently joined the choir invisible.") else: print("Congratulation! you have managed to trip a #%d error" % ErrorNumber) print(ErrorMessage) ``` Which will print: Sorry, \'the_parrot\' has apparently joined the choir invisible. #### Custom Exceptions Code similar to that seen above can be used to create custom exceptions and pass information along with them. This can be very useful when trying to debug complicated projects. Here is how that code would look; first creating the custom exception class: ``` python class CustomException(Exception): def __init__(self, value): self.parameter = value def __str__(self): return repr(self.parameter) ``` And then using that exception: ``` python try: raise CustomException("My Useful Error Message") except CustomException, (instance): print("Caught: " + instance.parameter) ``` #### Trying over and over again ### Recovering and continuing with `finally` Exceptions could lead to a situation where, after raising an exception, the code block where the exception occurred might not be revisited. In some cases this might leave external resources used by the program in an unknown state. `finally` clause allows programmers to close such resources in case of an exception. Between 2.4 and 2.5 version of python there is change of syntax for `finally` clause. - Python 2.4 ``` python try: result = None try: result = x/y except ZeroDivisionError: print("division by zero!") print("result is ", result) finally: print("executing finally clause") ``` - Python 2.5 ``` python try: result = x / y except ZeroDivisionError: print("division by zero!") else: print("result is", result) finally: print("executing finally clause") ``` ### Built-in exception classes All built-in Python exceptions ### Exotic uses of exceptions Exceptions are good for more than just error handling. If you have a complicated piece of code to choose which of several courses of action to take, it can be useful to use exceptions to jump out of the code as soon as the decision can be made. The Python-based mailing list software Mailman does this in deciding how a message should be handled. Using exceptions like this may seem like it\'s a sort of GOTO \-- and indeed it is, but a limited one called an *escape continuation*. Continuations are a powerful functional-programming tool and it can be useful to learn them. Just as a simple example of how exceptions make programming easier, say you want to add items to a list but you don\'t want to use \"if\" statements to initialize the list we could replace this: ``` python if hasattr(self, 'items'): self.items.extend(new_items) else: self.items = list(new_items) ``` Using exceptions, we can emphasize the normal program flow---that usually we just extend the list---rather than emphasizing the unusual case: ``` python try: self.items.extend(new_items) except AttributeError: self.items = list(new_items) ``` ### External links - 8. Errors and Exceptions in The Python Tutorial, docs.python.org - 8. Errors and Exceptions in The Python Tutorial for Python 2.4, docs.python.org - 6. Built-in Exceptions, docs.python.org
# Python Programming/Errors In python there are three types of errors; *syntax errors*, *logic errors* and *exceptions*. ## Syntax errors Syntax errors are the most basic type of error. They arise when the Python parser is unable to understand a line of code. Syntax errors are almost always fatal, i.e. there is almost never a way to successfully execute a piece of code containing syntax errors. Some syntax errors can be caught and handled, like eval(\"\"), but these are rare. In IDLE, it will highlight where the syntax error is. Most syntax errors are typos, incorrect indentation, or incorrect arguments. If you get this error, try looking at your code for any of these. ## Logic errors These are the most difficult type of error to find, because they will give unpredictable results and may crash your program.  A lot of different things can happen if you have a logic error. However these are very easy to fix as you can use a debugger, which will run through the program and fix any problems. A simple example of a logic error can be showcased below, the while loop will compile and run however, the loop will never finish and may crash Python: ``` python #Counting Sheep #Goal: Print number of sheep up until 101. sheep_count=1 while sheep_count<100: print("%i Sheep"%sheep_count) ``` Logic errors are only erroneous in the perspective of the programming goal one might have; in many cases Python is working as it was intended, just not as the user intended. The above while loop is functioning correctly as Python is intended to, but the exit the condition the user needs is missing. ## Exceptions Exceptions arise when the python parser knows what to do with a piece of code but is unable to perform the action. An example would be trying to access the internet with python without an internet connection; the python interpreter knows what to do with that command but is unable to perform it. ### Dealing with exceptions Unlike syntax errors, exceptions are not always fatal. Exceptions can be handled with the use of a `try` statement. Consider the following code to display the HTML of the website \'example.com\'. When the execution of the program reaches the try statement it will attempt to perform the indented code following, if for some reason there is an error (the computer is not connected to the internet or something) the python interpreter will jump to the indented code below the \'except:\' command. ``` python import urllib2 url = 'http://www.example.com' try: req = urllib2.Request(url) response = urllib2.urlopen(req) the_page = response.read() print(the_page) except: print("We have a problem.") ``` Another way to handle an error is to except a specific error. ``` python try: age = int(raw_input("Enter your age: ")) print("You must be {0} years old.".format(age)) except ValueError: print("Your age must be numeric.") ``` If the user enters a numeric value as his/her age, the output should look like this: Enter your age: 5 Your age must be 5 years old. However, if the user enters a non-numeric value as his/her age, a `ValueError` is thrown when trying to execute the `int()` method on a non-numeric string, and the code under the `except` clause is executed: Enter your age: five Your age must be numeric. You can also use a `try` block with a `while` loop to validate input: ``` python valid = False while valid == False: try: age = int(raw_input("Enter your age: ")) valid = True # This statement will only execute if the above statement executes without error. print("You must be {0} years old.".format(age)) except ValueError: print("Your age must be numeric.") ``` The program will prompt you for your age until you enter a valid age: Enter your age: five Your age must be numeric. Enter your age: abc10 Your age must be numeric. Enter your age: 15 You must be 15 years old. In certain other cases, it might be necessary to get more information about the exception and deal with it appropriately. In such situations the except as construct can be used. ``` python f=raw_input("enter the name of the file:") l=raw_input("enter the name of the link:") try: os.symlink(f,l) except OSError as e: print("an error occurred linking %s to %s: %s\n error no %d"%(f,l,e.args[1],e.args[0])) ``` enter the name of the file:file1.txt enter the name of the link:AlreadyExists.txt an error occurred linking file1.txt to AlreadyExists.txt: File exists error no 17 enter the name of the file:file1.txt enter the name of the link:/Cant/Write/Here/file1.txt an error occurred linking file1.txt to /Cant/Write/Here/file1.txt: Permission denied error no 13 pt:Python/Conceitos básicos/Erros e exceções
# Python Programming/Source Documentation and Comments Documentation is the process of leaving information about your code. The two mechanisms for doing this in Python are comments and documentation strings. ## Comments There will always be a time in which you have to return to your code. Perhaps it is to fix a bug, or to add a new feature. Regardless, looking at your own code after six months is almost as bad as looking at someone else\'s code. What one needs is a means to leave reminders to yourself as to what you were doing. For this purpose, you leave comments. Comments are little snippets of text embedded inside your code that are ignored by the Python interpreter. A comment is denoted by the hash character (#) and extends to the end of the line. For example: ``` python #!/usr/bin/env python # commentexample.py # Display the knights that come after Scene 24 print("The Knights Who Say Ni!") # print("I will never see the light of day!") ``` As you can see, you can also use comments to temporarily remove segments of your code, like the second print statement. ### Comment Guidelines The following guidelines are from PEP 8, written by Guido van Rossum. - General - Comments that contradict the code are worse than no comments. Always make a priority of keeping the comments up-to-date when the code changes! - Comments should be complete sentences. If a comment is a phrase or sentence, its first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of identifiers!). - If a comment is short, the period at the end can be omitted. Block comments generally consist of one or more paragraphs built out of complete sentences, and each sentence should end in a period. - You should use two spaces after a sentence-ending period. - When writing English, Strunk and White applies. - Python coders from non-English speaking countries: please write your comments in English, unless you are 120% sure that the code will never be read by people who don\'t speak your language. - Inline Comments - An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a \# and a single space. - Inline comments are unnecessary and in fact distracting if they state the obvious. Don\'t do this: ``` python x = x + 1 # Increment x ``` But sometimes, this is useful: ``` python x = x + 1 # Compensate for border ``` ## Documentation Strings But what if you just want to know how to use a function, class, or method? You could add comments before the function, but comments are inside the code, so you would have to pull up a text editor and view them that way. But you can\'t pull up comments from a C extension, so that is less than ideal. You could always write a separate text file with how to call the functions, but that would mean that you would have to remember to update that file. If only there was a mechanism for being able to embed the documentation and get at it easily\... Fortunately, Python has such a capability. Documentation strings (or docstrings) are used to create easily-accessible documentation. You can add a docstring to a function, class, or module by adding a string as the first indented statement. For example: ``` python #!/usr/bin/env python # docstringexample.py """Example of using documentation strings.""" class Knight: """ An example class. Call spam to get bacon. """ def spam(eggs="bacon"): """Prints the argument given.""" print(eggs) ``` The convention is to use triple-quoted strings, because it makes it easier to add more documentation spanning multiple lines. To access the documentation, you can use the `help` function inside a Python shell with the object you want help on, or you can use the `pydoc` command from your system\'s shell. If we were in the directory where docstringexample.py lives, one could enter `pydoc docstringexample` to get documentation on that module.
# Python Programming/Idioms Python is a strongly idiomatic language: there is generally a single optimal way of doing something (a programming idiom), rather than many ways: "There's more than one way to do it" is *not* a Python motto. This section starts with some general principles, then goes through the language, highlighting how to idiomatically use operations, data types, and modules in the standard library. ## Principles Use exceptions for error-checking, following EAFP (It\'s Easier to Ask Forgiveness than Permission) instead of LBYL (Look Before You Leap): put an action that may fail inside a `try...except` block. Use context managers for managing resources, like files. Use `finally` for ad hoc cleanup, but prefer to write a context manager to encapsulate this. Use properties, not getter/setter pairs. Use dictionaries for dynamic records, classes for static records (for simple classes, use collections.namedtuple): if a record always has the same fields, make this explicit in a class; if the fields may vary (be present or not), use a dictionary. Use `_` for throwaway variables, like discarding a return value when a tuple is returned, or to indicate that a parameter is being ignored (when required for an interface, say). You can use `*_, **__` to discard positional or keyword arguments passed to a function: these correspond to the usual `*args, **kwargs` parameters, but explicitly discarded. You can also use these in addition to positional or named parameters (following the ones you use), allowing you to use some and discard any excess ones. Use implicit True/False (truthy/falsy values), except when needing to distinguish between falsy values, like None, 0, and \[\], in which case use an explicit check like `is None` or `== 0`. Use the optional `else` clause after `try, for, while` not just `if`. ## Imports For readable and robust code, only import modules, not names (like functions or classes), as this creates a new (name) binding, which is not necessarily in sync with the existing binding.[^1] For example, given a module `m` which defines a function `f`, importing the function with `from m import f` means that `m.f` and `f` can differ if either is assigned to (creating a new binding). In practice, this is frequently ignored, particularly for small-scale code, as changing a module post-import is rare, so this is rarely a problem, and both classes and functions are imported from modules so they can be referred to without a prefix. However, for robust, large-scale code, this is an important rule, as it risks creating very subtle bugs. For robust code with low typing, one can use a renaming import to abbreviate a long module name: ``` python import module_with_very_long_name as vl vl.f() # easier than module_with_very_long_name.f, but still robust ``` Note that importing submodules (or subpackages) from a package using `from` is completely fine: ``` python from p import sm # completely fine sm.f() ``` ## Operations Swap values ``` python b, a = a, b ``` Attribute access on nullable value To access an attribute (esp. to call a method) on a value that might be an object, or might be `None`, use the boolean shortcircuiting of `and`: ``` python a and a.x a and a.f() ``` Particularly useful for regex matches: ``` python match and match.group(0) ``` in `in` in can be used for substring checking ## Data types ### All sequence types Indexing during iteration Use `enumerate()` if you need to keep track of iteration cycles over an iterable: ``` python for i, x in enumerate(l): # ... ``` Anti-idiom: ``` python for i in range(len(l)): x = l[i] # why did you go from list to numbers back to the list? # ... ``` Finding first matching element Python sequences do have an `index` method, but this returns the index of the first occurrence of a specific value in the sequence. To find the first occurrence of a value that satisfies a condition, instead, use `next` and a generator expression: ``` python try: x = next(i for i, n in enumerate(l) if n > 0) except StopIteration: print('No positive numbers') else: print('The index of the first positive number is', x) ``` If you need the value, not the index of its occurrence, you can get it directly through: ``` python try: x = next(n for n in l if n > 0) except StopIteration: print('No positive numbers') else: print('The first positive number is', x) ``` The reason for this construct is twofold: - Exceptions let you signal "no match found" (they solve the semipredicate problem): since you\'re returning a single value (not an index), this can\'t be returned in the value. - Generator expressions let you use an expression without needing a lambda or introducing new grammar. Truncating For mutable sequences, use `del`, instead of reassigning to a slice: ``` python del l[j:] del l[:i] ``` Anti-idiom: ``` python l = l[:j] l = l[i:] ``` The simplest reason is that `del` makes your intention clear: you\'re truncating. More subtly, slicing creates another reference to the same list (because lists are mutable), and then unreachable data can be garbage-collected, but generally this is done later. Deleting instead immediately modifies the list in-place (which is faster than creating a slice and then assigning it to the existing variable), and allows Python to immediately deallocate the deleted elements, instead of waiting for garbage collection. In some cases you *do* want 2 slices of the same list -- though this is rare in basic programming, other than iterating once over a slice in a `for` loop -- but it\'s rare that you\'ll want to make a slice of a whole list, then replace the original list variable with a slice (but not change the other slice!), as in the following funny-looking code: ``` python m = l l = l[i:j] # why not m = l[i:j] ? ``` Sorted list from an iterable You can create a sorted list directly from any iterable, without needing to first make a list and then sort it. These include sets and dictionaries (iterate on the keys): ``` python s = {1, 'a', ...} l = sorted(s) d = {'a': 1, ...} l = sorted(d) ``` ### Tuples Use tuples for constant sequences. This is rarely necessary (primarily when using as keys in a dictionary), but makes intention clear. ### Strings Substring Use `in` for substring checking. However, do *not* use `in` to check if a string is a single-character match, since it matches substrings and will return spurious matches -- instead use a tuple of valid values. For example, the following is wrong: ``` python def valid_sign(sign): return sign in '+-' # wrong, returns true for sign == '+-' ``` Instead, use a tuple: ``` python def valid_sign(sign): return sign in ('+', '-') ``` Building a string To make a long string incrementally, build a list and then join it with `''` -- or with newlines, if building a text file (don\'t forget the final newline in this case!). This is faster and clearer than appending to a string, which is often *slow.* (In principle can be $O(nk)$ in overall length of string and number of additions, which is $O(n^2)$ if pieces are of similar sizes.) However, there are some optimizations in some versions CPython that make simple string appending fast -- string appending in CPython 2.5+, and bytestring appending in CPython 3.0+ are fast, but for building Unicode strings (unicode in Python 2, string in Python 3), joining is faster. If doing extensive string manipulation, be aware of this and profile your code. See Performance Tips: String Concatenation and Concatenation Test Code for details. Don\'t do this: ``` python s = '' for x in l: # this makes a new string every iteration, because strings are immutable s += x ``` Instead: ``` python # ... # l.append(x) s = ''.join(l) ``` You can even use generator expressions, which are extremely efficient: ``` python s = ''.join(f(x) for x in l) ``` If you do want a mutable string-like object, you can use `StringIO`. - Efficient String Concatenation in Python -- old article (so benchmarks out of date), but gives overview of some techniques. ### Dictionaries To iterate through a dictionary, either keys, values, or both: ``` python # Iterate over keys for k in d: ... # Iterate over values, Python 3 for v in d.values(): ... # Iterate over values, Python 2 # In Python 2, dict.values() returns a copy for v in d.itervalues(): ... # Iterate over keys and values, Python 3 for k, v in d.items(): ... # Iterate over values, Python 2 # In Python 2, dict.items() returns a copy for k, v in d.iteritems(): ... ``` Anti-patterns: ``` python for k, _ in d.items(): # instead: for k in d: ... for _, v in d.items(): # instead: for v in d.values() ... ``` FIXME: - setdefault - usually better to use collections.defaultdict `dict.get` is useful, but using `dict.get` and then checking if it is `None` as a way of testing if the key is in the dictionary is an anti-idiom, as `None` is a potential value, and whether the key is in the dictionary can be checked directly. It\'s ok to use `get` and compare with `None` if this is _not_ a potential value, however. Simple: ``` python if 'k' in d: # ... d['k'] ``` Anti-idiom (unless `None` is not a potential value): ``` python v = d.get('k') if v is not None: # ... v ``` Dict from parallel sequences of keys and values Use `zip` as: `dict(zip(keys, values))` ## Modules ### re Match if found, else `None`: ``` python match = re.match(r, s) return match and match.group(0) ``` \...returns `None` if no match, and the match contents if there is one. ## References - "Idioms and Anti-Idioms in Python", Moshe Zadka ## Further reading - "PEP 20 \-- The Zen of Python", Tim Peters [^1]: "Idioms and Anti-Idioms in Python": from module import name1, name2
# Python Programming/Package management *pip* is the standard Python package manager, making it easy to download and install packages from the PyPI repository. pip seems to be part of Python distribution since Python 2.7.9 and 3.5.4. If you do not have pip, you can install it by downloading get-pip.py from bootstrap.pypa.io and running python get-pip.py. Other package managers are not covered in this chapter. Examples of pip use: - pip install xlrd - Installs xlrd package from the PyPI repository, or from another repository if customized to search in additional repositories. - pip install \--upgrade xlrd - Upgrades a package to the latest version. - pip install mypackage.whl - Installs the package from wheel file mypackage.whl. This is useful when for whatever reason installation from PyPI fails and you need to download the wheel file (.whl) of the package manually. - pip freeze - Lists installed packages and their versions. - pip show xlrd - Outputs information about an installed package (here xlrd), including version, author and license. - python -m pip install xlrd - Calls pip via python and -m option. Useful e.g. for installing packages for ../PyPy/ (a just-in-time compiler for Python), in which case you use pypy -m pip install xlrd. - pip \--version - Outputs the pip version. - pip install \--upgrade pip - Upgrades pip itself. *PyPI* is an online repository of Python packages, many of which are published under a rather permissive license such as MIT license or one of the BSD licenses. PyPI hosts both pure-Python packages and Python packages taking advantage of the C language. Installing pure-Python packages such as xlrd is usually seamless. As for C language packages, many of them have precompiled binaries for multiple operating systems, making the installation seamless as well. However, for a C language package that has only sources published, pip needs a working and properly set up compiler to successfully install the package. A *wheel file* is a package distribution. It can contain pure-Python code but also precompiled executable binaries if required. A single package can offer multiple wheels per different Python versions and operating systems. An example wheel file containing precompiled binaries is numpy-1.16.2-cp27-cp27m-win32.whl, for numpy package, available from pypi Download files section for the package. If you are using pip with no problems, you do not need to worry about wheel files. ## requirements.txt This file lists the application dependencies. It\'s equivalent to composer.json in PHP or package.json in JavaScript. File generation: `pip freeze > requirements.txt` Dependencies installation: `pip install -r requirements.txt` ## External links - pip - The Python Package Installer, pip.pypa.io - Installation in pip documentation, pip.pypa.io - How do I install pip on Windows?, stackoverflow.com - Installing Packages, packaging.python.org - Packaging Python Projects, packaging.python.org - The Python Package Index (PyPI), pypi.org - Over 10% of Python Packages on PyPI are Distributed Without Any License, 2018, snyk.io
# Python Programming/Python 2 vs. Python 3 Python 3 was created incompatible with Python 2. Support for Python 2.7 ended in 2020. One noticeable difference is that in Python 3, *print* is not a statement but rather a function, and therefore, invoking it requires placing brackets around its arguments. Differences with deeper impact include making all strings Unicode and introducing a bytes type, making all integers big integers, letting slash (/) denote a true division rather than per default integer division, etc.; for a compact overview, see Python wiki. Python 2 code can be made ready for a switch to Python 3 by importing features from \_\_future\_\_ module. For instance, *from \_\_future\_\_ import print_function* makes Python 2 behave as if it had Python 3 print function. Python 3 was first released in 2008. A list of Python packages ready for Python 3 is available from py3readiness.org. A survey conducted in 2018 by JetBrains and Python Software Foundation suggests significant adoption of Python 3 among Python users. ## External links - W:History of Python#Version 3, en.wikipedia.org - What's New In Python 3.0, docs.python.org - 28.11. \_\_future\_\_ --- Future statement definitions, docs.python.org - Porting Python 2 Code to Python 3, docs.python.org - Cheat Sheet: Writing Python 2-3 compatible code, python-future.org - Should I use Python 2 or Python 3 for my development activity?, wiki.python.org - Python3.0, wiki.python.org - Python 3 Readiness, pyreadiness.org - PEP 373 \-- Python 2.7 Release Schedule, legacy.python.org - Python Developers Survey 2018 Results, jetbrains.com (conducted with Python Software Foundation) - How we rolled out one of the largest Python 3 migrations ever, 2018, blogs.dropbox.com
# Python Programming/Decorators Duplicated code is recognized as bad practice in software for lots of reasons, not least of which is that it requires more work to maintain. If you have the same algorithm operating twice on different pieces of data you can put the algorithm in a function and pass in the data to avoid having to duplicate the code. However, sometimes you find cases where the code itself changes, but two or more places still have significant chunks of duplicated boilerplate code. A typical example might be logging: ``` python def multiply(a, b): result = a * b log("multiply has been called") return result def add(a, b): result = a + b log("add has been called") return result ``` In a case like this, it\'s not obvious how to factor out the duplication. We can follow our earlier pattern of moving the common code to a function, but calling the function with different data is not enough to produce the different behavior we want (add or multiply). Instead, we have to pass a *function* to the common function. This involves a function that operates on a function, known as a *higher-order function*. Decorator in Python is a syntax sugar for high-level function. Minimal example of property decorator: ``` python >>> class Foo(object): ... @property ... def bar(self): ... return 'baz' ... >>> F = Foo() >>> print(F.bar) baz ``` The above example is really just a syntax sugar for codes like this: ``` python >>> class Foo(object): ... def bar(self): ... return 'baz' ... bar = property(bar) ... >>> F = Foo() >>> print(F.bar) baz ``` Minimal Example of generic decorator: ``` python >>> def decorator(f): ... def called(*args, **kargs): ... print('A function is called somewhere') ... return f(*args, **kargs) ... return called ... >>> class Foo(object): ... @decorator ... def bar(self): ... return 'baz' ... >>> F = Foo() >>> print(F.bar()) A function is called somewhere baz ``` A good use for the decorators is to allow you to refactor your code so that common features can be moved into decorators. Consider for example, that you would like to trace all calls to some functions and print out the values of all the parameters of the functions for each invocation. Now you can implement this in a decorator as follows: ``` python #define the Trace class that will be #invoked using decorators class Trace(object): def __init__(self, f): self.f =f def __call__(self, *args, **kwargs): print("entering function " + self.f.__name__) i=0 for arg in args: print("arg {0}: {1}".format(i, arg)) i =i+1 return self.f(*args, **kwargs) ``` Then you can use the decorator on any function that you defined by: ``` python @Trace def sum(a, b): print "inside sum" return a + b ``` On running this code you would see output like ``` python >>> sum(3,2) entering function sum arg 0: 3 arg 1: 2 inside sum ``` Alternately, instead of creating the decorator as a class, you could have used a function as well. ``` python def Trace(f): def my_f(*args, **kwargs): print("entering " + f.__name__) result= f(*args, **kwargs) print("exiting " + f.__name__) return result my_f.__name = f.__name__ my_f.__doc__ = f.__doc__ return my_f #An example of the trace decorator @Trace def sum(a, b): print("inside sum") return a + b #if you run this you should see >>> sum(3,2) entering sum inside sum exiting sum 5 ``` Remember it is good practice to return the function or a sensible decorated replacement for the function so that decorators can be chained.
# Python Programming/Context Managers A basic issue in programming is resource management "wikilink"): a resource "wikilink") is anything in limited supply, notably file handles, network sockets, locks, etc., and a key problem is making sure these are *released* after they are *acquired.* If they are not released, you have a resource leak, and the system may slow down or crash. More generally, you may want cleanup actions to always be done, other than simply releasing resources. Python provides special syntax for this in the `with` statement, which automatically manages resources encapsulated within context manager types, or more generally performs startup and cleanup actions around a block of code. You should **always** use a `with` statement for resource management. There are many built-in context manager types, including the basic example of `File`, and it is easy to write your own. The code is not hard, but the concepts are slightly subtle, and it is easy to make mistakes. ## Basic resource management Basic resource management uses an explicit pair of `open()...close()` functions, as in basic file opening and closing. ***Don\'t do this,*** for the reasons we are about to explain: ``` python f = open(filename) # ... f.close() ``` The key problem with this simple code is that it fails if there is an early return, either due to a `return` statement or an exception, possibly raised by called code. To fix this, ensuring that the cleanup code is called when the block is exited, one uses a `try...finally` clause: ``` python f = open(filename) try: # ... finally: f.close() ``` However, this still requires manually releasing the resource, which might be forgotten, and the release code is distant from the acquisition code. The release can be done automatically by instead using `with`, which works because `File` is a context manager type: ``` python with open(filename) as f: # ... ``` This assigns the value of `open(filename)` to `f` (this point is subtle and varies between context managers), and then automatically releases the resource, in this case calling `f.close()`, when the block exits. ## Technical details Newer objects are *context managers* (formally context manager types: subtypes, as they implement the context manager interface, which consists of `__enter__()`, `__exit__()`), and thus can be used in `with` statements easily (see With Statement Context Managers). For older file-like objects that have a `close` method but not `__exit__()`, you can use the `@contextlib.closing` decorator. If you need to roll your own, this is very easy, particularly using the `@contextlib.contextmanager` decorator.[^1] Context managers work by calling `__enter__()` when the `with` context is entered, binding the return value to the target of `as`, and calling `__exit__()` when the context is exited. There\'s some subtlety about handling exceptions during exit, but you can ignore it for simple use. More subtly, `__init__()` is called when an object is created, but `__enter__()` is called when a `with` context is entered. The `__init__()`/`__enter__()` distinction is important to distinguish between single use, reusable and reentrant context managers. It\'s not a meaningful distinction for the common use case of instantiating an object in the `with` clause, as follows: ``` python with A() as a: ... ``` \...in which case any single use context manager is fine. However, in general it is a difference, notably when distinguishing a reusable context manager from the resource it is managing, as in here: ``` python a_cm = A() with a_cm as a: ... ``` Putting resource acquisition in `__enter__()` instead of `__init__()` gives a reusable context manager. Notably, `File()` objects do the initialization in `__init__()` and then just returns itself when entering a context, as in `def __enter__(): return self`. This is fine if you want the target of the `as` to be bound to an *object* (and allows you to use factories like `open` as the source of the `with` clause), but if you want it to be bound to something else, notably a *handle* (file name or file handle/file descriptor), you want to wrap the actual object in a separate context manager. For example: ``` python @contextmanager def FileName(*args, **kwargs): with File(*args, **kwargs) as f: yield f.name ``` For simple uses you don\'t need to do any `__init__()` code, and only need to pair `__enter__()`/`__exit__()`. For more complicated uses you can have reentrant context managers, but that\'s not necessary for simple use. ## Caveats ### `try...finally` Note that a `try...finally` clause *is* necessary with `@contextlib.contextmanager`, as this does not catch any exceptions raised after the `yield`, but is *not* necessary in `__exit__()`, which is called even if an exception is raised. ### Context, not scope The term *context* manager is carefully chosen, particularly in contrast to "scope". Local variables in Python have function scope, and thus the target of a `with` statement, if any, is still visible after the block has exited, though `__exit__()` has already been called on the context manager (the argument of the `with` statement), and thus is often not useful or valid. This is a technical point, but it\'s worth distinguishing the `with` statement context from the overall function scope. ### Generators Generators that hold or use resources are a bit tricky. Beware that creating generators within a `with` statement and then using them outside the block does *not* work, because generators have deferred evaluation, and thus when they are evaluated, the resource has already been released. This is most easily seen using a file, as in this generator expression to convert a file to a list of lines, stripping the end-of-line character: ``` python with open(filename) as f: lines = (line.rstrip('\n') for line in f) ``` When `lines` is then used -- evaluation can be forced with `list(lines)` -- this fails with `<samp>`{=html}ValueError: I/O operation on closed file.`</samp>`{=html} This is because the file is closed at the end of the `with` statement, but the lines are not read until the generator is evaluated. The simplest solution is to avoid generators, and instead use lists, such as list comprehensions. This is generally appropriate in this case (reading a file) since one wishes to minimize system calls and just read the file all at once (unless the file is very large): ``` python with open(filename) as f: lines = [line.rstrip('\n') for line in f] ``` In case that one does wish to use a resource in a generator, the resource must be held within the generator, as in this generator function: ``` python def stripped_lines(filename): with open(filename) as f: for line in f: yield line.rstrip('\n') ``` As the nesting makes clear, the file is kept open while iterating through it. To release the resource, the generator must be explicitly closed, using `generator.close()``,` just as with other objects that hold resources (this is the dispose pattern). This can in turn be automated by making the generator into a context manager, using `@contextlib.closing,` as: ``` python from contextlib import closing with closing(stripped_lines(filename)) as lines: # ... ``` ### Not RAII is an alternative form of resource management, particularly used in C++. In RAII, resources are acquired during object construction, and released during object destruction. In Python the analogous functions are `__init__()` and `__del__()` (finalizer), but RAII does *not* work in Python, and releasing resources in `__del__()` does *not* work. This is because there is no guarantee that `__del__()` will be called: it\'s just for memory manager use, not for resource handling. In more detail, Python object construction is two-phase, consisting of (memory) allocation in `__new__()` and (attribute) initialization in `__init__()`. Python is garbage-collected via reference counting, with objects being finalized (not destructed) by `__del__()`. However, finalization is non-deterministic (objects have non-deterministic lifetimes), and the finalizer may be called much later or not at all, particularly if the program crashes. Thus using `__del__()` for resource management will generally leak resources. It is possible to use finalizers for resource management, but the resulting code is implementation-dependent (generally working in CPython but not other implementations, such as PyPy) and fragile to version changes. Even if this is done, it requires great care to ensure references drop to zero in all circumstances, including: exceptions, which contain references in tracebacks if caught or if running interactively; and references in global variables, which last until program termination. Prior to Python 3.4, finalizers on objects in cycles were also a serious problem, but this is no longer a problem; however, finalization of objects in cycles is not done in a deterministic order. ## References - Context Manager Types - With Statement Context Managers ## External links - Get With the Program as Contextmanager - PyMOTW (Module of the Week): contextlib - Markus Gattol: Context Manager [^1]: Nils von Barth's answer to "how to delete dir created by python tempfile.mkdtemp", *StackOverflow*
# Python Programming/Reflection A Python script can find out about the type, class, attributes and methods of an object. This is referred to as **reflection** or **introspection**. See also ../Metaclasses/. Reflection-enabling functions include type(), isinstance(), callable(), dir() and getattr(). ## Type The type method enables to find out about the type of an object. The following tests return True: - type(3) is int - type(3.0) is float - type(10\*\*10) is long \# Python 2 - type(1 + 1j) is complex - type(\'Hello\') is str - type(\[1, 2\]) is list - type(\[1, \[2, \'Hello\'\]\]) is list - type({\'city\': \'Paris\'}) is dict - type((1,2)) is tuple - type(set()) is set - type(frozenset()) is frozenset - ------------------------------------------------------------------------ - type(3).\_\_name\_\_ == \"int\" - type(\'Hello\').\_\_name\_\_ == \"str\" - ------------------------------------------------------------------------ - import types, re, Tkinter \# For the following examples - type(re) is types.ModuleType - type(re.sub) is types.FunctionType - type(Tkinter.Frame) is types.ClassType - type(Tkinter.Frame).\_\_name\_\_ == \"classobj\" - type(Tkinter.Frame()).\_\_name\_\_ == \"instance\" - type(re.compile(\'myregex\')).\_\_name\_\_ == \"SRE_Pattern\" - type(type(3)) is types.TypeType The type function disregards class inheritance: \"type(3) is object\" yields False while \"isinstance(3, object)\" yields True. Links: - 2. Built-in Functions \# type, python.org - 8.15. types --- Names for built-in types, python.org ## Isinstance Determines whether an object is an instance of a type or class. The following tests return True: - isinstance(3, int) - isinstance(\[1, 2\], list) - isinstance(3, object) - isinstance(\[1, 2\], object) - import Tkinter; isinstance(Tkinter.Frame(), Tkinter.Frame) - import Tkinter; Tkinter.Frame().\_\_class\_\_.\_\_name\_\_ == \"Frame\" Note that isinstance provides a weaker condition than a comparison using #Type. Function isinstance and a user-defined class: ``` python class Plant: pass # Dummy class class Tree(Plant): pass # Dummy class derived from Plant tree = Tree() # A new instance of Tree class print(isinstance(tree, Tree)) # True print(isinstance(tree, Plant)) # True print(isinstance(tree, object)) # True print(type(tree) is Tree) # True print(type(tree).__name__ == "instance") # False print(tree.__class__.__name__ == "Tree") # True ``` Links: - Built-in Functions \# isinstance, python.org - isinstance() considered harmful, canonical.org ## Issubclass Determines whether a class is a subclass of another class. Pertains to classes, not their instances. ``` python class Plant: pass # Dummy class class Tree(Plant): pass # Dummy class derived from Plant tree = Tree() # A new instance of Tree class print(issubclass(Tree, Plant)) # True print(issubclass(Tree, object)) # False in Python 2 print(issubclass(int, object)) # True print(issubclass(bool, int)) # True print(issubclass(int, int)) # True print(issubclass(tree, Plant)) # Error - tree is not a class ``` Links: - Built-in Functions \# issubclass, python.org ## Duck typing Duck typing provides an indirect means of reflection. It is a technique consisting in using an object as if it was of the requested type, while catching exceptions resulting from the object not supporting some of the features of the class or type. Links: - Glossary \# duck-typing, python.org ## Callable For an object, determines whether it can be called. A class can be made callable by providing a \_\_call\_\_() method. Examples: - callable(2) - Returns False. Ditto for callable(\"Hello\") and callable(\[1, 2\]). - callable(\[1,2\].pop) - Returns True, as pop without \"()\" returns a function object. - callable(\[1,2\].pop()) - Returns False, as \[1,2\].pop() returns 2 rather than a function object. Links: - Built-in Functions \# callable, python.org ## Dir Returns the list of names of attributes of an object, which includes methods. Is somewhat heuristic and possibly incomplete, as per python.org. Examples: - dir(3) - dir(\"Hello\") - dir(\[1, 2\]) - import re; dir(re) - Lists names of functions and other objects available in the re module for regular expressions. Links: - Built-in Functions \# dir, python.org ## Getattr Returns the value of an attribute of an object, given the attribute name passed as a string. An example: - getattr(3, \"imag\") The list of attributes of an object can be obtained using #Dir. Links: - Built-in Functions \# getattr, python.org ## Keywords A list of Python keywords can be obtained from Python: ``` python import keyword pykeywords = keyword.kwlist print(keyword.iskeyword("if")) # True print(keyword.iskeyword("True")) # False ``` Links: - 32.6. keyword --- Testing for Python keywords, python.org ## Built-ins A list of Python built-in objects and functions can be obtained from Python: ``` python print(dir(__builtins__)) # Output the list print(type(__builtins__.list)) # = <type 'type'> print(type(__builtins__.open)) # = <type 'builtin_function_or_method'> print(list is __builtins__.list) # True print(open is __builtins__.open) # True ``` Links: - 28.3. \_\_builtin\_\_ --- Built-in objects, python.org - Built-in Functions \# dir, python.org ## External links - 2. Built-in Functions, docs.python.org - How to determine the variable type in Python?, stackoverflow.com - Differences between isinstance() and type() in python, stackoverflow.com - W:Reflection (computer_programming)#Python#Python "wikilink"), Wikipedia - W:Type introspection#Python, Wikipedia
# Python Programming/Metaclasses In Python, classes are themselves objects. Just as other objects are instances of a particular class, classes themselves are instances of a metaclass. ### Python3 The Pep 3115 defines the changes to python 3 metaclasses. In python3 you have a method \_\_prepare\_\_ that is called in the metaclass to create a dictionary or other class to store the class members.[^1] Then there is the \_\_new\_\_ method that is called to create new instances of that class. [^2] ### The type Metaclass The metaclass for all standard Python types is the \"type\" object. ``` python >>> type(object) <type 'type'> >>> type(int) <type 'type'> >>> type(list) <type 'type'> ``` Just like list, int and object, \"type\" is itself a normal Python object, and is itself an instance of a class. In this case, it is in fact an instance of itself. ``` python >>> type(type) <type 'type'> ``` It can be instantiated to create new class objects similarly to the class factory example above by passing the name of the new class, the base classes to inherit from, and a dictionary defining the namespace to use. For instance, the code: ``` python >>> class MyClass(BaseClass): ... attribute = 42 ``` Could also be written as: ``` python >>> MyClass = type("MyClass", (BaseClass,), {'attribute' : 42}) ``` ### Metaclasses It is possible to create a class with a different metaclass than type by setting the metaclass keyword argument when defining the class. When this is done, the class, and its subclass will be created using your custom metaclass. For example ``` python class CustomMetaclass(type): def __init__(cls, name, bases, dct): print("Creating class %s using CustomMetaclass" % name) super(CustomMetaclass, cls).__init__(name, bases, dct) class BaseClass(metaclass=CustomMetaclass): pass class Subclass1(BaseClass): pass ``` This will print `Creating class BaseClass using CustomMetaclass`\ `Creating class Subclass1 using CustomMetaclass` By creating a custom metaclass in this way, it is possible to change how the class is constructed. This allows you to add or remove attributes and methods, register creation of classes and subclasses creation and various other manipulations when the class is created. ### More resources - Wikipedia article on Aspect Oriented Programming - Unifying types and classes in Python 2.2 - O\'Reilly Article on Python Metaclasses ### References [^1]: <http://www.python.org/dev/peps/pep-3115/> [^2]: <http://eli.thegreenplace.net/2011/08/14/python-metaclasses-by-example/>
# Python Programming/Performance Since Python is an interpreted language in its most commonly used CPython implementation, it is many times slower in a variety of tasks than the most commonly used compiled non-managed languages such as C and C++; for some tasks, it is more than 100 times slower. CPython seems to be on par with Perl, another interpreted language, slower on some tasks, faster on other tasks. Performance can be measured using benchmarks. Benchmarks are often far from representative of the real-world usage and have to be taken with a grain of salt. Some benchmarks are outright wrong in that non-idiomatic code is used for a language, yielding avoidably low performance for the language. ../PyPy/ is a just-in-time (JIT) compiler that often runs faster than CPython. Another compiler that can lead to greater speeds is Numba, which works for a subset of Python. Yet another compiler is ../Cython/, not to be confused with CPython. ## External links - Python 3 versus C gcc fastest programs, benchmarksgame-team.pages.debian.net - Python 3 versus Java fastest programs, benchmarksgame-team.pages.debian.net - Python 3 versus Go fastest programs, benchmarksgame-team.pages.debian.net - Perl vs Python 3 - Which programs are fastest?, benchmarksgame-team.pages.debian.net - Python speed center, speed.python.org - pypy speed center, speed.pypy.org - Python Interpreters Benchmarks, pybenchmarks.org - Performance of Python runtimes on a non-numeric scientific code by Riccardo Murri, arxiv.org - How To Make Python Run As Fast As Julia by Jean Francois Puget, ibm.com
# Python Programming/PyPy PyPy is a Python interpreter containing a just-in-time compiler. Python programs can usually be run by PyPy without modification but for availability of 3rd party modules since a module made for CPython, the normal Python interpreter, does not automatically work with PyPy. Furthermore, some Python programs can run into trouble because of PyPy\'s different strategy of when to free up allocated objects including file handles. The speed-up brought by PyPy compared to CPython depends on the nature of the task. For some computationally heavy tasks, the speed-up factor can reach as high as 50. PyPy speed center reports the geometric average speed-up factor as 7.6, calculated from a set of benchmarks. PyPy is available both for Python 2 and Python 3, but the version for Python 3 is slower; the above speed statements pertain to Python 2. Interactive use of PyPy is possible: you can type \"pypy\" into a command line, and start interacting with it just like with CPython. The outputs from PyPy are not guaranteed to be exactly the same as from CPython. For instance, PyPy can yield items from a set in an order different from that of CPython since the item order in a set is arbitrary and not guaranteed to the same between different Python implementations; for verification, you can compare the results of {1,2}.pop(). Dictionaries have an arbitrary key order as well. Floating point results may be slightly different between PyPy and CPython in some setups as long as PyPy is built with SSE2 instruction set enabled and CPython is not. See also ../Performance/. ## External links - PyPy, pypy.org - PyPy\'s Speed Center, speed.pypy.org - PyPy, en.wikipedia.org
# Python Programming/Cython Cython (not to be confused with CPython) is a compiler of Python-like source code to the C language, from which it is compiled by a C compiler to binary executable. The objective is a significant speedup compared to interpreting the Python code in CPython, the standard interpreter. Cython is usually used to create extension modules for Python. The source code language compilable by Cython is a near superset of Python. You can install Cython using *pip install Cython*. However, in order for Cython to work, you will need a working C compiler. On Linux, you usually have one; on Windows, you can install and use Microsoft Visual C++ compiler or MinGW. Beyond the normal Python, Cython-compilable Python source can contain C-like declarations of variable types, leading to speedups of the compiled code. Cython-compilable Python source code files conventionally use extension pyx. The compiled extension module still needs CPython (the normal Python interpreter) to run, and can call other Python modules, including pure Python modules. This is because, where required, Cython compiles to C code that uses the CPython API to achieve general Python-like behavior. ## External links - Official website, cython.org - Basic Tutorial, docs.cython.org - Cython, pypi.org - cython, github.com - Cython, en.wikipedia.org - Python Interpreters Benchmarks, pybenchmarks.org
# Python Programming/Command-line one-liners Python can run one-liners from an operating system command line using option -c: - python -c \"print(3.0/2)\" - Calculates and outputs the result. - python -c \"import math;print(math.sin(1))\" - Imports a module required and outputs sine value. - python -c \"for i in range(1,11):print(i)\" - Uses a loop to output numbers from 1 to 10. - python -c \"for i in range(1,11):for j in range(1,11): print(i,j)\" - Does not work; two loops in a line are an invalid syntax. - python -c \"for i, j in ((i,j) for i in range (1,11) for j in range(1,11)): print(i, j)\" - Outputs pairs using two analogues of loop within a comprehension. - echo hey \| python -c \"import sys,re;\[sys.stdout.write(line) for line in sys.stdin if re.search(\'he.\', line)\]\" - Acts as grep: outputs each line of the input containing a substring matching a regular expression. Not a Python one-liner strength. - echo hallo \| python -c \"import sys,re;\[sys.stdout.write(re.sub(\'h\[au\]llo\', \'hello\', line)) for line in sys.stdin\]\" - Acts as sed: for each line of the input, performs a regex replacement and outputs the results. Again, not a Python one-liner strength. - python -m calendar - Outputs a year\'s calendar using calendar module. - python -c \"import playsound as p;p.playsound(r\'C:\\WINDOWS\\Media\\notify.wav\')\" - On Windows, plays notification sound. Requires installation of playsound module. The module works across platforms; what is Windows specific above is the file path. ## External links - Powerful Python One-Liners, wiki.python.org
# Python Programming/Tips and Tricks There are many tips and tricks you can learn in Python: ## Strings - Triple quotes are an easy way to define a string with both single and double quotes. - String concatenation is *expensive*. Use percent formatting and str.join() for concatenation: (but don\'t worry about this unless your resulting string is more than 500-1000 characters long) [^1] ``` python print "Spam" + " eggs" + " and" + " spam" # DON'T DO THIS print " ".join(["Spam","eggs","and","spam"]) # Much faster/more # common Python idiom print "%s %s %s %s" % ("Spam", "eggs", "and", "spam") # Also a pythonic way of # doing it - very fast ``` ## Optimized C modules Several modules have optimized versions written in C, which provide an almost-identical interface and are frequently *much* faster or more memory-efficient than the pure Python implementations. Module behavior generally does differ in some respects, often minor, and thus C versions are frequently used. This is primarily a Python 2.x feature, which has been largely removed in Python 3, with modules automatically using optimized implementations if available.[^2] However, the `cProfile`/`profile` pair still exists (as of Python 3.4). ### importing The C version of a module named `module` or `Module` is called `cModule`, and frequently imported using `import...as` to strip off the prefix, as: ``` python import cPickle as pickle ``` For compatibility, one can try to import the C version and fall back to the Python version if the C version is not available; in this case using `import...as` is *required,* so the code does not depend on which module was imported: ``` python try: import cPickle as pickle except ImportError: import pickle ``` ### Examples Notable examples include: - (Python 2.x) `cPickle` for `pickle`, up to 1000× faster. - (Python 2.x) `cStringIO` for `StringIO`, replaced by `io.StringIO` in Python 3 - `cProfile` for `profile` -- the Python `profile` adds significant overhead, and thus `cProfile` is recommended for most use. - (not needed in Python 3.3+) `cElementTree` for `ElementTree`, 15--20 times faster and uses 2--5 times less memory;[^3] not needed in Python 3.3+, which automatically uses a fast implementation if possible. ## List comprehension and generators - List comprehension and generator expressions are very useful for working with small, compact loops. Additionally, it is faster than a normal for-loop. ``` python directory = os.listdir(os.getcwd()) # Gets a list of files in the # directory the program runs from filesInDir = [item for item in directory] # Normal For Loop rules apply, you # can add "if condition" to make a # more narrow search. ``` - List comprehension and generator expression can be used to work with two (or more) lists with zip or itertools.izip ``` python [a - b for (a,b) in zip((1,2,3), (1,2,3))] # will return [0, 0, 0] ``` ## Data type choice Choosing the correct data type can be critical to the performance of an application. For example, say you have 2 lists: ``` python list1 = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}] list2 = [{'e': 5, 'f': 6}, {'g': 7, 'h': 8}, {'i': 9, 'j': 10}] ``` and you want to find the entries common to both lists. You could iterate over one list, checking for common items in the other: ``` python common = [] for entry in list1: if entry in list2: common.append(entry) ``` For such small lists, this will work fine, but for larger lists, for example if each contains thousands of entries, the following will be more efficient, and produces the same result: ``` python set1 = set([tuple(entry.items()) for entry in list1]) set2 = set([tuple(entry.items()) for entry in list2]) common = set1.intersection(set2) common = [dict(entry) for entry in common] ``` Sets are optimized for speed in such functions. Dictionaries themselves cannot be used as members of a set as they are mutable, but tuples can. If one needs to do set operations on a list of dictionaries, one can convert the items to tuples and the list to a set, perform the operation, then convert back. This is often much faster than trying to replicate set operations using string functions. ## Other - Decorators can be used for handling common concerns like logging, db access, etc. - While Python has no built-in function to flatten a list you can use a recursive function to do the job quickly. ``` python def flatten(seq, list = None): """flatten(seq, list = None) -> list Return a flat version of the iterator `seq` appended to `list` """ if list == None: list = [] try: # Can `seq` be iterated over? for item in seq: # If so then iterate over `seq` flatten(item, list) # and make the same check on each item. except TypeError: # If seq isn't iterable list.append(seq) # append it to the new list. return list ``` - To stop a Python script from closing right after you launch one independently, add this code: ``` python print 'Hit Enter to exit' raw_input() ``` - Python already has a GUI built in: Tkinter, based on Tcl\'s Tk. More are available, such as PyQt4, pygtk3, and wxPython. ```{=html} <!-- --> ``` - Ternary Operators: ``` python [on_true] if [expression] else [on_false] x, y = 50, 25 small = x if x < y else y ``` - Booleans as indexes: ``` python b = 1==1 name = "I am %s" % ["John","Doe"][b] #returns I am Doe ``` ## References [^1]: [^2]: What's New In Python 3.0, Guido van Rossum [^3]: \"The cElementTree Module\", January 30, 2005, Fredrik Lundh
# Python Programming/Standard Library The Python Standard Library is a collection of script modules accessible to a Python program to simplify the programming process and removing the need to rewrite commonly used commands. They can be used by \'calling/importing\' them at the beginning of a script. A list of the Standard Library modules can be found at <http://www.python.org/doc/>. The following are among the most important: - time - sys - os - math - random - pickle - urllib - re - cgi - socket pt:Python/Bibliotecas padrão
# Python Programming/Regular Expression Python includes a module for working with regular expressions on strings. For more information about writing regular expressions and syntax not specific to Python, see the regular expressions wikibook. Python\'s regular expression syntax is similar to Perl\'s To start using regular expressions in your Python scripts, import the \"re\" module: ``` python import re ``` ## Overview Regular expression functions in Python at a glance: ``` python import re if re.search("l+","Hello"): print(1) # Substring match suffices if not re.match("ell.","Hello"): print(2) # The beginning of the string has to match if re.match(".el","Hello"): print(3) if re.match("he..o","Hello",re.I): print(4) # Case-insensitive match print(re.sub("l+", "l", "Hello")) # Prints "Helo"; replacement AKA substitution print(re.sub(r"(.*)\1", r"\1", "HeyHey")) # Prints "Hey"; backreference print(re.sub("EY", "ey", "HEy", flags=re.I))# Prints "Hey"; case-insensitive sub print(re.sub(r"(?i)EY", r"ey", "HEy")) # Prints "Hey"; case-insensitive sub for match in re.findall("l+.", "Hello Dolly"): print(match) # Prints "llo" and then "lly" for match in re.findall("e(l+.)", "Hello Dolly"): print(match) # Prints "llo"; match picks group 1 for match in re.findall("(l+)(.)", "Hello Dolly"): print(match[0], match[1]) # The groups end up as items in a tuple match = re.match("(Hello|Hi) (Tom|Thom)","Hello Tom Bombadil") if match: # Equivalent to if match is not None print(match.group(0)) # Prints the whole match disregarding groups print(match.group(1) + match.group(2)) # Prints "HelloTom" ``` ## Matching and searching One of the most common uses for regular expressions is extracting a part of a string or testing for the existence of a pattern in a string. Python offers several functions to do this. The match and search functions do mostly the same thing, except that the match function will only return a result if the pattern matches at the beginning of the string being searched, while search will find a match anywhere in the string. ``` python >>> import re >>> foo = re.compile(r'foo(.{,5})bar', re.I+re.S) >>> st1 = 'Foo, Bar, Baz' >>> st2 = '2. foo is bar' >>> search1 = foo.search(st1) >>> search2 = foo.search(st2) >>> match1 = foo.match(st1) >>> match2 = foo.match(st2) ``` In this example, match2 will be `None`, because the string `st2` does not start with the given pattern. The other 3 results will be Match objects (see below). You can also match and search without compiling a regexp: ``` python >>> search3 = re.search('oo.*ba', st1, re.I) ``` Here we use the search function of the re module, rather than of the pattern object. For most cases, its best to compile the expression first. Not all of the re module functions support the flags argument and if the expression is used more than once, compiling first is more efficient and leads to cleaner looking code. The compiled pattern object functions also have parameters for starting and ending the search, to search in a substring of the given string. In the first example in this section, `match2` returns no result because the pattern does not start at the beginning of the string, but if we do: ``` python >>> match3 = foo.match(st2, 3) ``` it works, because we tell it to start searching at character number 3 in the string. What if we want to search for multiple instances of the pattern? Then we have two options. We can use the start and end position parameters of the search and match function in a loop, getting the position to start at from the previous match object (see below) or we can use the findall and finditer functions. The findall function returns a list of matching strings, useful for simple searching. For anything slightly complex, the finditer function should be used. This returns an iterator object, that when used in a loop, yields Match objects. For example: ``` python >>> str3 = 'foo, Bar Foo. BAR FoO: bar' >>> foo.findall(str3) [', ', '. ', ': '] >>> for match in foo.finditer(str3): ... match.group(1) ... ', ' '. ' ': ' ``` If you\'re going to be iterating over the results of the search, using the finditer function is almost always a better choice. ### Match objects Match objects are returned by the search and match functions, and include information about the pattern match. The group function returns a string corresponding to a capture group (part of a regexp wrapped in `()`) of the expression, or if no group number is given, the entire match. Using the `search1` variable we defined above: ``` python >>> search1.group() 'Foo, Bar' >>> search1.group(1) ', ' ``` Capture groups can also be given string names using a special syntax and referred to by `matchobj.group('name')`. For simple expressions this is unnecessary, but for more complex expressions it can be very useful. You can also get the position of a match or a group in a string, using the start and end functions: ``` python >>> search1.start() 0 >>> search1.end() 8 >>> search1.start(1) 3 >>> search1.end(1) 5 ``` This returns the start and end locations of the entire match, and the start and end of the first (and in this case only) capture group, respectively. ## Replacing Another use for regular expressions is replacing text in a string. To do this in Python, use the sub function. sub takes up to 3 arguments: The text to replace with, the text to replace in, and, optionally, the maximum number of substitutions to make. Unlike the matching and searching functions, sub returns a string, consisting of the given text with the substitution(s) made. ``` python >>> import re >>> mystring = 'This string has a q in it' >>> pattern = re.compile(r'(a[n]? )(\w) ') >>> newstring = pattern.sub(r"\1'\2' ", mystring) >>> newstring "This string has a 'q' in it" ``` This takes any single alphanumeric character (\\w in regular expression syntax) preceded by \"a\" or \"an\" and wraps in in single quotes. The `\1` and `\2` in the replacement string are backreferences to the 2 capture groups in the expression; these would be group(1) and group(2) on a Match object from a search. The subn function is similar to sub, except it returns a tuple, consisting of the result string and the number of replacements made. Using the string and expression from before: ``` python >>> subresult = pattern.subn(r"\1'\2' ", mystring) >>> subresult ("This string has a 'q' in it", 1) ``` Replacing without constructing and compiling a pattern object: ``` python >>> result = re.sub(r"b.*d","z","abccde") >>> result 'aze' ``` ## Splitting The split function splits a string based on a given regular expression: ``` python >>> import re >>> mystring = '1. First part 2. Second part 3. Third part' >>> re.split(r'\d\.', mystring) ['', ' First part ', ' Second part ', ' Third part'] ``` ## Escaping The escape function escapes all non-alphanumeric characters in a string. This is useful if you need to take an unknown string that may contain regexp metacharacters like `(` and `.` and create a regular expression from it. ``` python >>> re.escape(r'This text (and this) must be escaped with a "\" to use in a regexp.') 'This\\ text\\ \\(and\\ this\\)\\ must\\ be\\ escaped\\ with\\ a\\ \\"\\\\\\"\\ to\\ use\\ in\\ a\\ regexp\\.' ``` ## Flags The different flags use with regular expressions: Abbreviation Full name Description -------------- ----------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- `re.I` `re.IGNORECASE` Makes the regexp case-insensitive `re.L` `re.LOCALE` Makes the behavior of some special sequences (`\w, \W, \b, \B, \s, \S`) dependent on the current locale `re.M` `re.MULTILINE` Makes the `^` and `$` characters match at the beginning and end of each line, rather than just the beginning and end of the string `re.S` `re.DOTALL` Makes the `.` character match every character *including* newlines. `re.U` `re.UNICODE` Makes `\w, \W, \b, \B, \d, \D, \s, \S` dependent on Unicode character properties `re.X` `re.VERBOSE` Ignores whitespace except when in a character class or preceded by an non-escaped backslash, and ignores `#` (except when in a character class or preceded by an non-escaped backslash) and everything after it to the end of a line, so it can be used as a comment. This allows for cleaner-looking regexps. ## Pattern objects If you\'re going to be using the same regexp more than once in a program, or if you just want to keep the regexps separated somehow, you should create a pattern object, and refer to it later when searching/replacing. To create a pattern object, use the compile function. ``` python import re foo = re.compile(r'foo(.{,5})bar', re.I+re.S) ``` The first argument is the pattern, which matches the string \"foo\", followed by up to 5 of any character, then the string \"bar\", storing the middle characters to a group, which will be discussed later. The second, optional, argument is the flag or flags to modify the regexp\'s behavior. The flags themselves are simply variables referring to an integer used by the regular expression engine. In other languages, these would be constants, but Python does not have constants. Some of the regular expression functions do not support adding flags as a parameter when defining the pattern directly in the function, if you need any of the flags, it is best to use the compile function to create a pattern object. The `r` preceding the expression string indicates that it should be treated as a raw string. This should normally be used when writing regexps, so that backslashes are interpreted literally rather than having to be escaped. ## External links - re --- Regular expression operations, docs.python.org - Python Programming/RegEx, wikiversity.org fr:Programmation Python/Regex
# Python Programming/External commands The traditional way of executing external commands is using os.system(): ``` python import os os.system("dir") os.system("echo Hello") exitCode = os.system("echotypo") ``` The modern way, since Python 2.4, is using subprocess module: ``` python subprocess.call(["echo", "Hello"]) exitCode = subprocess.call(["dir", "nonexistent"]) ``` The traditional way of executing external commands and reading their output is via popen2 module: ``` python import popen2 readStream, writeStream, errorStream = popen2.popen3("dir") # allLines = readStream.readlines() for line in readStream: print(line.rstrip()) readStream.close() writeStream.close() errorStream.close() ``` The modern way, since Python 2.4, is using subprocess module: ``` python import subprocess process = subprocess.Popen(["echo","Hello"], stdout=subprocess.PIPE) for line in process.stdout: print(line.rstrip()) ``` Keywords: system commands, shell commands, processes, backtick, pipe. ## External links - 17.1. subprocess --- Subprocess management, python.org, since Python 2.4 - 15.1. os --- Miscellaneous operating system interfaces, python.org - 17.5. popen2 --- Subprocesses with accessible I/O streams, python.org, deprecated since Python 2.6
# Python Programming/XML Tools ## Introduction Python includes several modules for manipulating xml. ## xml.sax.handler Python Doc ``` python import xml.sax.handler as saxhandler import xml.sax as saxparser class MyReport: def __init__(self): self.Y = 1 class MyCH(saxhandler.ContentHandler): def __init__(self, report): self.X = 1 self.report = report def startDocument(self): print('startDocument') def startElement(self, name, attrs): print('Element:', name) report = MyReport() #for future use ch = MyCH(report) xml = """\ <collection> <comic title=\"Sandman\" number='62'> <writer>Neil Gaiman</writer> <penciller pages='1-9,18-24'>Glyn Dillon</penciller> <penciller pages="10-17">Charles Vess</penciller> </comic> </collection> """ print(xml) saxparser.parseString(xml, ch) ``` ## xml.dom.minidom An example of doing RSS feed parsing with DOM ``` python from xml.dom import minidom as dom import urllib2 def fetchPage(url): a = urllib2.urlopen(url) return ''.join(a.readlines()) def extract(page): a = dom.parseString(page) item = a.getElementsByTagName('item') for i in item: if i.hasChildNodes(): t = i.getElementsByTagName('title')[0].firstChild.wholeText l = i.getElementsByTagName('link')[0].firstChild.wholeText d = i.getElementsByTagName('description')[0].firstChild.wholeText print(t, l, d) if __name__=='__main__': page = fetchPage("http://rss.slashdot.org/Slashdot/slashdot") extract(page) ``` XML document provided by pyxml documentation.
# Python Programming/Email Python includes several modules in the standard library for working with emails and email servers. ## Sending mail Sending mail is done with Python\'s `smtplib` using an SMTP (Simple Mail Transfer Protocol) server. Actual usage varies depending on complexity of the email and settings of the email server, the instructions here are based on sending email through Google\'s Gmail. The first step is to create an SMTP object, each object is used for connection with one server. ``` python import smtplib server = smtplib.SMTP('smtp.gmail.com', 587) ``` The first argument is the server\'s hostname, the second is the port. The port used varies depending on the server. Next, we need to do a few steps to set up the proper connection for sending mail. ``` python server.ehlo() server.starttls() server.ehlo() ``` These steps may not be necessary depending on the server you connect to. ehlo() is used for ESMTP servers, for non-ESMTP servers, use helo() instead. See Wikipedia\'s article about the SMTP protocol for more information about this. The starttls() function starts Transport Layer Security mode, which is required by Gmail. Other mail systems may not use this, or it may not be available. Next, log in to the server: ``` python server.login("youremailusername", "password") ``` Then, send the mail: ``` python msg = "\nHello!" # The /n separates the message from the headers (which we ignore for this example) server.sendmail("you@gmail.com", "target@example.com", msg) ``` Note that this is a rather crude example, it doesn\'t include a subject, or any other headers. For that, one should use the `email` package. ## The `email` package Python\'s email package contains many classes and functions for composing and parsing email messages, this section only covers a small subset useful for sending emails. We start by importing only the classes we need, this also saves us from having to use the full module name later. ``` python from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart ``` Then we compose some of the basic message headers: ``` python fromaddr = "you@gmail.com" toaddr = "target@example.com" msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "Python email" ``` Next, we attach the body of the email to the MIME message: ``` python body = "Python test mail" msg.attach(MIMEText(body, 'plain')) ``` For sending the mail, we have to convert the object to a string, and then use the same procedure as above to send using the SMTP server.. ``` python import smtplib server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo() server.login("youremailusername", "password") text = msg.as_string() server.sendmail(fromaddr, toaddr, text) ``` If we look at the text, we can see it has added all the necessary headers and structure necessary for a MIME formatted email. See MIME for more details on the standard:
# Python Programming/Threading Threading in python is used to run multiple threads (tasks, function calls) at the same time. Note that this does not mean that they are executed on different CPUs. Python threads will NOT make your program faster if it already uses 100 % CPU time. In that case, you probably want to look into parallel programming. If you are interested in parallel programming with python, please see here. Python threads are used in cases where the execution of a task involves some waiting. One example would be interaction with a service hosted on another computer, such as a webserver. Threading allows python to execute other code while waiting; this is easily simulated with the sleep function. ## Examples ### A Minimal Example with Function Call Make a thread that prints numbers from 1-10 and waits a second between each print: ``` python import threading import time def loop1_10(): for i in range(1, 11): time.sleep(1) print(i) threading.Thread(target=loop1_10).start() ``` ### A Minimal Example with Object ``` python #!/usr/bin/env python import threading import time class MyThread(threading.Thread): def run(self): # Default called function with mythread.start() print("{} started!".format(self.getName())) # "Thread-x started!" time.sleep(1) # Pretend to work for a second print("{} finished!".format(self.getName())) # "Thread-x finished!" def main(): for x in range(4): # Four times... mythread = MyThread(name = "Thread-{}".format(x)) # ...Instantiate a thread and pass a unique ID to it mythread.start() # ...Start the thread, run method will be invoked time.sleep(.9) # ...Wait 0.9 seconds before starting another if __name__ == '__main__': main() ``` The output looks like this: `Thread-0 started!`\ `Thread-1 started!`\ `Thread-0 finished!`\ `Thread-2 started!`\ `Thread-1 finished!`\ `Thread-3 started!`\ `Thread-2 finished!`\ `Thread-3 finished!` fr:Programmation Python/Les threads
# Python Programming/Sockets ## HTTP Client Make a very simple HTTP client ``` python import socket s = socket.socket() s.connect(('localhost', 80)) s.send('GET / HTTP/1.1\nHost:localhost\n\n') s.recv(40000) # receive 40000 bytes ``` ## NTP/Sockets Connecting to and reading an NTP time server, returning the time as follows `ntpps       picoseconds portion of time`\ `ntps        seconds portion of time`\ `ntpms       milliseconds portion of time`\ `ntpt        64-bit ntp time, seconds in upper 32-bits, picoseconds in lower 32-bits`
# Python Programming/GUI Programming There are various GUI toolkits usable from Python. Very productive are true GUI-builders, where the programmer can arrange the GUI window and other components such as database by using the mouse only in an intuitive fashion like in Windows Delphi 2.0. Very little typing is required. For python, only Boa Constructor follows this paradigm. WXglade and Qt-designer, monkey studio etc. come somewhat near but remain incomplete. Disadvantages with the following kits described below are: - Difficult deployment - the apps won\'t run on a particular GNU-Linux installation without major additional work - breakage - apps won\'t work due to bit-rot. ## Tkinter Tkinter is a Python wrapper for Tcl/Tk providing a cross-platform GUI toolkit. On Windows, it comes bundled with Python; on other operating systems, it can be installed. The set of available widgets is smaller than in some other toolkits, but since Tkinter widgets are extensible, many of the missing compound widgets can be created using the extensibility, such as combo box and scrolling pane. A minimal example: ``` python from Tkinter import * root = Tk() frame = Frame(root) frame.pack() label = Label(frame, text="Hey there.") label.pack() quitButton = Button(frame, text="Quit", command=frame.quit) quitButton.pack() root.mainloop() ``` Main chapter: ../Tkinter/. Links: - 24.1. Tkinter --- Python interface to Tcl/Tk, python.org - Tkinter 8.5 reference: a GUI for Python, infohost.nmt.edu; the same as pdf - An Introduction to Tkinter, effbot.org ## PyGTK *See also book PyGTK For GUI Programming* PyGTK provides a convenient wrapper for the GTK+ library for use in Python programs, taking care of many of the boring details such as managing memory and type casting. The bare GTK+ toolkit runs on Linux, Windows, and Mac OS X (port in progress), but the more extensive features --- when combined with PyORBit and gnome-python --- require a GNOME install, and can be used to write full featured GNOME applications. Home Page ## PyQt PyQt is a wrapper around the cross-platform Qt C++ toolkit. It has many widgets and support classes supporting SQL, OpenGL, SVG, XML, and advanced graphics capabilities. A PyQt hello world example: ``` python from PyQt4.QtCore import * from PyQt4.QtGui import * class App(QApplication): def __init__(self, argv): super(App, self).__init__(argv) self.msg = QLabel("Hello, World!") self.msg.show() if __name__ == "__main__": import sys app = App(sys.argv) sys.exit(app.exec_()) ``` PyQt is a set of bindings for the cross-platform Qt application framework. PyQt v4 supports Qt4 and PyQt v3 supports Qt3 and earlier. ## wxPython Bindings for the cross platform toolkit wxWidgets. WxWidgets is available on Windows, Macintosh, and Unix/Linux. ``` python import wx class test(wx.App): def __init__(self): wx.App.__init__(self, redirect=False) def OnInit(self): frame = wx.Frame(None, -1, "Test", pos=(50,50), size=(100,40), style=wx.DEFAULT_FRAME_STYLE) button = wx.Button(frame, -1, "Hello World!", (20, 20)) self.frame = frame self.frame.Show() return True if __name__ == '__main__': app = test() app.MainLoop() ``` - wxPython ## Dabo Dabo is a full 3-tier application framework. Its UI layer wraps wxPython, and greatly simplifies the syntax. ``` python import dabo dabo.ui.loadUI("wx") class TestForm(dabo.ui.dForm): def afterInit(self): self.Caption = "Test" self.Position = (50, 50) self.Size = (100, 40) self.btn = dabo.ui.dButton(self, Caption="Hello World", OnHit=self.onButtonClick) self.Sizer.append(self.btn, halign="center", border=20) def onButtonClick(self, evt): dabo.ui.info("Hello World!") if __name__ == '__main__': app = dabo.ui.dApp() app.MainFormClass = TestForm app.start() ``` - Dabo ## pyFltk pyFltk is a Python wrapper for the FLTK, a lightweight cross-platform GUI toolkit. It is very simple to learn and allows for compact user interfaces. The \"Hello World\" example in pyFltk looks like: ``` python from fltk import * window = Fl_Window(100, 100, 200, 90) button = Fl_Button(9,20,180,50) button.label("Hello World") window.end() window.show() Fl.run() ``` ## Other Toolkits - PyKDE - Part of the kdebindings package, it provides a python wrapper for the KDE libraries. - PyXPCOM provides a wrapper around the Mozilla XPCOM component architecture, thereby enabling the use of standalone XUL applications in Python. The XUL toolkit has traditionally been wrapped up in various other parts of XPCOM, but with the advent of libxul and XULRunner this should become more feasible. These days, nobody uses PyXPCOM for very good reasons: PyXPCOM gives one dead links and outdated incompatible firefox extensions. ## External links - Graphic User Interface FAQ, python.org - An excerpt from Chapter 20: GUI Development, from Python Programming on Win32, onlamp.com, by Mark Hammond, Andy Robinson; covers Tkinter, PythonWin and wxPython - Google Ngram Viewer: Tkinter, wxPython, wxWidgets, PyGTK, PyQt fr:Programmation Python/L\'interface graphique pt:Python/Programação com GUI
# Python Programming/Tkinter Tkinter is a Python wrapper for Tcl/Tk providing a cross-platform GUI toolkit. On Windows, it comes bundled with Python; on other operating systems, it can be installed. The set of available widgets is smaller than in some other toolkits, but since Tkinter widgets are extensible, many of the missing compound widgets can be created using the extensibility, such as combo box and scrolling pane. IDLE, Python\'s Integrated Development and Learning Environment, is written using Tkinter and is often distributed with Python. You can learn about features of Tkinter by playing around with menus and dialogs of IDLE. For instance, Options \> Configure IDLE\... dialog shows a broad variety of GUI elements including tabbed interface. You can learn about programming using Tkinter by studying IDLE source code, which, on Windows, is available e.g. in C:\\Program Files\\Python27\\Lib\\idlelib. *Python 3:* The examples on this page are for Python 2. In Python 3, what was previously module Tkinter is tkinter, what was tkMessageBox is messagebox, etc. ## Minimal example A minimal example: ``` python from Tkinter import * root = Tk() frame = Frame(root) frame.pack() label = Label(frame, text="Hey there.") label.pack() quitButton = Button(frame, text="Quit", command=frame.quit) quitButton.pack() root.mainloop() ``` A minimal example made more compact - later references to GUI items not required: ``` python from Tkinter import * root = Tk() frame = Frame(root) frame.pack() Label(frame, text="Hey there.").pack() Button(frame, text="Quit", command=frame.quit).pack() root.mainloop() ``` A minimal example creating an application class derived from Frame: ``` python from Tkinter import * class App(Frame): def __init__(self, master): Frame.__init__(self) self.label = Label(master, text="Hey there.") self.label.pack() self.quitButton = Button(master, text="Quit", command=self.quit) self.quitButton.pack() if __name__ == '__main__': root = Tk() app = App(root) root.mainloop() ``` ## Message boxes Simple message boxes can be created using tkMessageBox as follows: ``` python import Tkinter, tkMessageBox Tkinter.Tk().withdraw() # Workaround: Hide the window answer = tkMessageBox.askokcancel("Confirmation", "File not saved. Discard?") answer = tkMessageBox.askyesno("Confirmation", "Do you really want to delete the file?") # Above, "OK" and "Yes" yield True, and "Cancel" and "No" yield False tkMessageBox.showwarning("Warning", "Timeout has elapsed.") tkMessageBox.showwarning("Warning", "Timeout has elapsed.", icon=tkMessageBox.ERROR) tkMessageBox.showerror("Warning", "Timeout has elapsed.") ``` Links: - The tkMessageBox dialogs module, infohost.nmt.edu - Standard Dialogs, effbot.org ## File dialog File dialogs can be created as follows: ``` python import Tkinter, tkFileDialog Tkinter.Tk().withdraw() # Workaround: Hide the window filename1 = tkFileDialog.askopenfilename() filename2 = tkFileDialog.askopenfilename(initialdir=r"C:\Users") filename3 = tkFileDialog.asksaveasfilename() filename4 = tkFileDialog.asksaveasfilename(initialdir=r"C:\Users") if filename1 <> "": for line in open(filename1): # Dummy reading of the file dummy = line.rstrip() ``` Links: - The tkFileDialog module, infohost.nmt.edu - File Dialogs, effbot.org - tkFileDialog, tkinter.unpythonic.net ## Radio button A radio button can be used to create a simple choice dialog with multiple options: ``` python from Tkinter import * master = Tk() choices = [("Apple", "a"), ("Orange", "o"), ("Pear", "p")] defaultChoice = "a" userchoice = StringVar() userchoice.set(defaultChoice) def cancelAction(): userchoice.set("");master.quit() Label(master, text="Choose a fruit:").pack() for text, key in choices: Radiobutton(master, text=text, variable=userchoice, value=key).pack(anchor=W) Button(master, text="OK", command=master.quit).pack(side=LEFT, ipadx=10) Button(master, text="Cancel", command=cancelAction).pack(side=RIGHT, ipadx=10) mainloop() if userchoice.get() <>"": print userchoice.get() # "a", or "o", or "p" else: print "Choice canceled." ``` An alternative to radio button that immediately reacts to button press: ``` python from Tkinter import * import os buttons = [("Users", r"C:\Users"), ("Windows", r"C:\Windows"), ("Program Files", r"C:\Program Files")] master = Tk() def open(filePath): def openInner(): os.chdir(filePath) # Cross platform #os.system('start "" "'+filePath+'') # Windows master.quit() return openInner Label(master, text="Choose a fruit:").pack() for buttonLabel, filePath in buttons: Button(master, text=buttonLabel, command=open(filePath)).pack(anchor=W) mainloop() ``` Links: - The Radiobutton widget, infohost.nmt.edu - The Tkinter Radiobutton Widget, effbot.org ## List box A list box can be used to create a simple multiple-choice dialog: ``` python from Tkinter import * master = Tk() choices = ["Apple", "Orange", "Pear"] canceled = BooleanVar() def cancelAction(): canceled.set(True); master.quit() Label(master, text="Choose a fruit:").pack() listbox = Listbox(master, selectmode=EXTENDED) # Multiple options can be chosen for text in choices: listbox.insert(END, text) listbox.pack() Button(master, text="OK", command=master.quit).pack(side=LEFT, ipadx=10) Button(master, text="Cancel", command=cancelAction).pack(side=RIGHT, ipadx=10) mainloop() if not canceled.get(): print listbox.curselection() # A tuple of choice indices starting with 0 # The above is a tuple even if selectmode=SINGLE if "0" in listbox.curselection(): print "Apple chosen." if "1" in listbox.curselection(): print "Orange chosen." if "2" in listbox.curselection(): print "Pear chosen." else: print "Choice canceled." ``` Links: - The Listbox widget, infohost.nmt.edu - The Tkinter Listbox Widget, effbot.org - TKinter Listbox example (Python recipe), code.activestate.com ## Checkbox Checkbox or check button can be created as follows: ``` python from Tkinter import * root = Tk() checkbuttonState = IntVar() Checkbutton(root, text="Recursive", variable=checkbuttonState).pack() mainloop() print checkbuttonState.get() # 1 = checked; 0 = unchecked ``` Links: - The Checkbutton widget, infohost.nmt.edu - The Tkinter Checkbutton Widget, effbot.org ## Entry Entry widget, a single-line text input field, can be used as follows: ``` python from Tkinter import * root = Tk() Label(text="Enter your first name:").pack() entryContent = StringVar() Entry(root, textvariable=entryContent).pack() mainloop() print entryContent.get() ``` Links: - The Entry widget, infohost.nmt.edu - The Tkinter Entry Widget, effbot.org ## Menu Menus can be created as follows: ``` python from Tkinter import * root = Tk() def mycommand(): print "Chosen." menubar = Menu(root) menu1 = Menu(menubar, tearoff=0) menu1.add_command(label="New", command=mycommand) menu1.add_command(label="Clone", command=mycommand) menu1.add_separator() menu1.add_command(label="Exit", command=root.quit) menubar.add_cascade(label="Project", menu=menu1) menu2 = Menu(menubar, tearoff=0) menu2.add_command(label="Oval", command=mycommand) menu2.add_command(label="Rectangle", command=mycommand) menubar.add_cascade(label="Shapes", menu=menu2) root.config(menu=menubar) mainloop() ``` Links: - The Menu widget, infohost.nmt.edu - The Tkinter Menu Widget, effbot.org ## LabelFrame A frame around other elements can be created using LabelFrame widget as follows: ``` python from Tkinter import * root = Tk() Label(text="Bus").pack() frame = LabelFrame(root, text="Fruits") # text is optional frame.pack() Label(frame, text="Apple").pack() Label(frame, text="Orange").pack() mainloop() ``` Links: - The LabelFrame widget, infohost.nmt.edu - Tkinter LabelFrame Widget, effbot.org ## Message Message is like Label but ready to wrap across multiple lines. An example: ``` python from Tkinter import * root = Tk() Message(text="Lazy brown fox jumped. " * 5, width=100).pack() # width is optional mainloop() ``` Links: - The Message widget, infohost.nmt.edu - The Tkinter Message Widget, effbot.org ## Option menu Drop-down list, in Tkinter option menu, can be created as follows: ``` python from Tkinter import * root = Tk() options = ["Apple", "Orange", "Pear"] selectedOption = StringVar() selectedOption.set("Apple") # Default OptionMenu(root, selectedOption, *options).pack() mainloop() print selectedOption.get() # The text in the options list ``` Links: - The OptionMenu widget, infohost.nmt.edu - The Tkinter OptionMenu Widget, effbot.org ## Text Text widget is a more complex one, allowing editing of both plain and formatted text, including multiple fonts. Example to be added. Links: - The Text widget, infohost.nmt.edu - The Tkinter Text Widget, effbot.org ## Tcl/Tk version The Windows installer for Python 2.3 ships with Tcl/Tk 8.4.3. You can find out about the version: ``` python import Tkinter print Tkinter.TclVersion # Up to 8.5 print Tkinter.TkVersion # Up to 8.5 ``` Links: - What\'s new in Python 2.3, python.org ## Related books - Tcl Programming/Tk ## External links - 24.1. Tkinter --- Python interface to Tcl/Tk, python.org - Tkinter 8.5 reference: a GUI for Python, infohost.nmt.edu; the same as pdf - An Introduction to Tkinter, effbot.org - Tkinter Summary, staff.washington.edu - TkInter, wiki.python.org - GUI Tk « Python, java2s.com, many examples
# Python Programming/CGI interface The Common Gateway Interface (CGI) allows to execute some Python programs on an HTTP server. ## Installation By default, open a .py file in HTTP returns its content. In order to make the server compile and execute the source code, it must be placed in a directory including an *.htaccess* file, with the lines[^1]: `AddHandler cgi-script .py`\ `Options +ExecCGI` Attention: on the Unix-like servers the files aren\'t executable by default, so this must be set with the command: *chmod +x \*.py*. ## Examples The module `cgitb` is used for debugging: ``` python #!C:\Program Files (x86)\Python\python.exe # -*- coding: UTF-8 -*- print "Content-type: text/html; charset=utf-8\n\n" print "<html><head><title>Local directory</title></head><body>" import cgitb cgitb.enable() import os print "The CGI file is located into:" print os.path.dirname(__file__) print "</body></html>" ``` The usage of a form needs an `import cgi`[^2]. For a MySQL database, its `import MySQLdb`[^3]. The following file is called *CGI_MySQL.py*, and uses the both modules: ``` python #!C:\Program Files (x86)\Python\python.exe # -*- coding: UTF-8 -*- print "Content-type: text/html; charset=utf-8\n\n" print "<html><head><title>DB CGI</title></head><body>" print "<h1>MySQL extraction</h1>" print "<ul>" import cgitb cgitb.enable() import cgi, MySQLdb form = cgi.FieldStorage() if form.getvalue('name') == None: print "<h2>Research a name</h2>" print ''' <form action="CGI_MySQL.py" method="post"> <input type="text" name="name" /> <input type="submit"></form> ''' else: print "<h2>Result</h2>" print "List for " + form.getvalue('name') + " :" connection = MySQLdb.connect(user='login1', passwd='passwd1', db='base1') cursor = connection.cursor() cursor.execute("SELECT page_title FROM page WHERE name ='"+form.getvalue('name')+"'") for row in cursor.fetchall(): print "<li>%s</li>" % row[0] connection.close() print "</ul>" print "</body></html>" ``` ## References ```{=html} <references/> ``` fr:Programmation Python/L\'interface CGI [^1]: [^2]: <http://fr.openclassrooms.com/informatique/cours/apercu-de-la-cgi-avec-python> [^3]: <https://pypi.python.org/pypi/MySQL-python/1.2.5>
# Python Programming/Internet The urllib module which is bundled with python can be used for web interaction. This module provides a file-like interface for web urls. ## Getting page text as a string An example of reading the contents of a webpage ``` python import urllib.request as urllib pageText = urllib.urlopen("http://www.spam.org/eggs.html").read() print(pageText) ``` Processing page text line by line: ``` python import urllib.request as urllib for line in urllib.urlopen("https://en.wikibooks.org/wiki/Python_Programming/Internet"): print(line) ``` Get and post methods can be used, too. ``` python import urllib.request as urllib params = urllib.urlencode({"plato":1, "socrates":10, "sophokles":4, "arkhimedes":11}) # Using GET method pageText = urllib.urlopen("http://international-philosophy.com/greece?%s" % params).read() print(pageText) # Using POST method pageText = urllib.urlopen("http://international-philosophy.com/greece", params).read() print(pageText) ``` ## Downloading files To save the content of a page on the internet directly to a file, you can read() it and save it as a string to a file object ``` python import urllib2 data = urllib2.urlopen("http://upload.wikimedia.org/wikibooks/en/9/91/Python_Programming.pdf", "pythonbook.pdf").read() # not recommended as if you are downloading 1gb+ file, will store all data in ram. file = open('Python_Programming.pdf','wb') file.write(data) file.close() ``` This will download the file from here and save it to a file \"pythonbook.pdf\" on your hard drive. ## Other functions The urllib module includes other functions that may be helpful when writing programs that use the internet: ``` python >>> plain_text = "This isn't suitable for putting in a URL" >>> print(urllib.quote(plain_text)) This%20isn%27t%20suitable%20for%20putting%20in%20a%20URL >>> print(urllib.quote_plus(plain_text)) This+isn%27t+suitable+for+putting+in+a+URL ``` The urlencode function, described above converts a dictionary of key-value pairs into a query string to pass to a URL, the quote and quote_plus functions encode normal strings. The quote_plus function uses plus signs for spaces, for use in submitting data for form fields. The unquote and unquote_plus functions do the reverse, converting urlencoded text to plain text. ## Email With Python, MIME compatible emails can be sent. This requires an installed SMTP server. ``` python import smtplib from email.mime.text import MIMEText msg = MIMEText( """Hi there, This is a test email message. Greetings""") me = 'sender@example.com' you = 'receiver@example.com' msg['Subject'] = 'Hello!' msg['From'] = me msg['To'] = you s = smtplib.SMTP() s.connect() s.sendmail(me, [you], msg.as_string()) s.quit() ``` This sends the sample message from \'sender@example.com\' to \'receiver@example.com\'. ## External links - urllib.request, docs.python.org - HOWTO Fetch Internet Resources Using The urllib Package, docs.python.org - urllib2 for Python 2, docs.python.org - HOWTO Fetch Internet Resources Using urllib2 --- Python 2.7, docs.python.org
# Python Programming/Networks ## Sockets Python can also communicate via sockets. ### Connecting to a server This simple Python program will fetch a 4096 byte HTTP response from Google: ``` python import socket, sys sock = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) sock.connect ( ( "google.com", 80 ) ) sock.send('GET / HTTP/1.1\r\n') sock.send('User-agent: Mozilla/5.0 (wikibooks test)\r\n\r\n') print(sock.recv(4096)) ``` ## High-level interfaces Most Python developers will prefer to use a high-level interface over using sockets, such as Twisted and urllib2.
# Python Programming/Math For basic math including addition, subtraction, multiplication and the like, see ../Basic Math/ and ../Operators/ chapters. For quick reference, the built-in Python math operators include addition (+), subtraction (-), multiplication (\*), division (/), floor division (//), modulo (%), and exponentiation (\*\*). The built-in Python math functions include rounding (round()), absolute value (abs()), minimum (min()), maximum (max()), division with a remainder (divmod()), and exponentiation (pow()). Sign function can be created as \"sign = lambda n: 1 if n \> 0 else -1 if n \< 0 else 0\". ## Math A range of mathematical functions is available from math module of the standard library: ``` python import math v1 = math.sin(10) # sine v2 = math.cos(10) # cosine v3 = math.tan(10) # tangent v4 = math.asin(10) # arc sine v5 = math.acos(10) # arc cosine v6 = math.atan(10) # arc tangent v7 = math.sinh(10) # hyperbolic sine v8 = math.cosh(10) # hyperbolic cosine v9 = math.tanh(10) # hyperbolic tangent vA = math.pow(2, 4) # 2 raised to 4 vB = math.exp(4) # e ^ 4 vC = math.sqrt(10) # square root vD = math.pow(5, 1/3.0) # cubic root of 5 vE = math.log(3) # ln; natural logarithm vF = math.log(100, 10) # base 10 vG = math.ceil(2.3) # ceiling vH = math.floor(2.7) # floor vI = math.pi vJ = math.e ``` ## Example code using in-built operators This code was made to replicate the log function in a calculator ``` python3 import time base_number = input("[A]input base number: ") new_number = 0 result = input("[end number]input result ") exponent = 0 while int(new_number) != int(result): exponent += float("0.0000001") new_number = int(base_number)**float(exponent) print(new_number) else: print("") print("The exponent or X is " + str(exponent)) time.sleep(200) ``` ## Cmath The cmath module provides similar functions like the math module but for complex numbers, and then some. ## Random Pseudo-random generators are available from the random module: ``` python import random v1 = random.random() # Uniformly distributed random float >= 0.0 and < 1.0. v2 = random.random()*10 # Uniformly distributed random float >= 0.0 and < 10.0 v3 = random.randint(0,9) # Uniformly distributed random int >= 0 and <=9 li=[1, 2, 3]; random.shuffle(li); print(li) # Randomly shuffled list ``` ## Decimal The decimal module enables decimal floating point arithmethic, avoiding certain artifacts of the usual underlying binary representation of floating point numbers that are unintuitive to humans. ``` python import decimal plainFloat = 1/3.0 v1 = plainFloat # 0.3333333333333333 decFloat = decimal.Decimal("0.33333333333333333333333333333333333333") v2 = decFloat # Decimal('0.33333333333333333333333333333333333333') decFloat2 = decimal.Decimal(plainFloat) v3 = decFloat2 # Decimal('0.333333333333333314829616256247390992939472198486328125') ``` ## Fractions The fractions module provides fraction arithmetic via Fraction class. Compared to floating point numbers representing fractions, Fraction fractions do not lose precision. ``` python from fractions import Fraction oneThird = Fraction(1, 3) floatOneThird = 1/3.0 v1 = Fraction(0.25) # 1/4 v2 = Fraction(floatOneThird) # 6004799503160661/18014398509481984 v3 = Fraction(1, 3) * Fraction(2, 5) # 2/15 ``` ## Statistics The statistics module, available since Python 3.4, provides some basic statistical functions. It only provides basics; it does not replace full-fledged 3rd party libraries such as numpy. For Python 2.7, the statistics module can be installed from pypi. ``` python import statistics as stats v1 = stats.mean([1, 2, 3, 100]) # 26.5 v2 = stats.median([1, 2, 3, 100]) # 2.5 v3 = stats.mode([1, 1, 2, 3]) # 1 v4 = stats.pstdev([1, 1, 2, 3]) # 0.82915...; population standard deviation v5 = stats.pvariance([1, 1, 2, 3]) # 0.6875; population variance ``` ## External links - 2. Built-in Functions, python.org - 9. Numeric and Mathematical Modules, python.org - 9.2. math --- Mathematical functions, python.org - 9.3. cmath --- Mathematical functions for complex numbers, python.org - 9.4. decimal --- Decimal fixed point and floating point arithmetic, python.org - 9.5. fractions --- Rational numbers, python.org - 9.6. random --- Generate pseudo-random numbers, python.org - 9.7. itertools --- Functions creating iterators for efficient looping, python.org - 9.7. statistics --- Mathematical statistics functions, python.org
# Python Programming/Database Programming Python has support for working with databases via a simple API. Modules included with Python include modules for SQLite and Berkeley DB. Modules for MySQL , PostgreSQL , FirebirdSQL and others are available as third-party modules. The latter have to be downloaded and installed before use. The package MySQLdb can be installed, for example, using the debian package \"python-mysqldb\". ## DBMS Specifics ### MySQL An Example with MySQL would look like this: ``` python import MySQLdb db = MySQLdb.connect("host machine", "dbuser", "password", "dbname") cursor = db.cursor() query = """SELECT * FROM sampletable""" lines = cursor.execute(query) data = cursor.fetchall() db.close() ``` On the first line, the Module `MySQLdb` is imported. Then a connection to the database is set up and on line 4, we save the actual SQL statement to be executed in the variable `query`. On line 5 we execute the query and on line 6 we fetch all the data. After the execution of this piece of code, `lines` contains the number of lines fetched (e.g. the number of rows in the table `sampletable`). The variable `data` contains all the actual data, e.g. the content of `sampletable`. In the end, the connection to the database would be closed again. If the number of lines are large, it is better to use `row = cursor.fetchone()` and process the rows individually: ``` python #first 5 lines are the same as above while True: row = cursor.fetchone() if row == None: break #do something with this row of data db.close() ``` Obviously, some kind of data processing has to be used on row, otherwise the data will not be stored. The result of the `fetchone()` command is a Tuple. In order to make the initialization of the connection easier, a configuration file can be used: ``` python import MySQLdb db = MySQLdb.connect(read_default_file="~/.my.cnf") ... ``` Here, the file .my.cnf in the home directory contains the necessary configuration information for MySQL. ### Sqlite An example with sqlite is very similar to the one above and the cursor provides many of the same functionalities. ``` python import sqlite3 db = sqlite3.connect("/path/to/file") cursor = db.cursor() query = """SELECT * FROM sampletable""" lines = cursor.execute(query) data = cursor.fetchall() db.close() ``` When writing to the db, one has to remember to call db.commit(), otherwise the changes are not saved: ``` python import sqlite3 db = sqlite3.connect("/path/to/file") cursor = db.cursor() query = """INSERT INTO sampletable (value1, value2) VALUES (1,'test')""" cursor.execute(query) db.commit() db.close() ``` ### Postgres ``` python import psycopg2 conn = psycopg2.connect("dbname=test") cursor = conn.cursor() cursor.execute("select * from test"); for i in cursor.next(): print(i) conn.close() ``` ### Firebird ``` python import firebirdsql conn = firebirdsql.connect(dsn='localhost/3050:/var/lib/firebird/2.5/test.fdb', user='alice', password='wonderland') cur = conn.cursor() cur.execute("select * from baz") for c in cur.fetchall(): print(c) conn.close() ``` ## General Principles ### Parameter Quoting You will frequently need to substitute dynamic data into a query string. **It is important to ensure this is done correctly.** ``` python # Do not do this! result = db.execute("SELECT name FROM employees WHERE location = '" + location + "'") ``` This example is **wrong**, because it doesn't correctly deal with special characters, like apostrophes, in the string being substituted. If your code has to deal with potentially hostile users (like on a public-facing Web server), this could leave you open to an **SQL injection attack**. For simple cases, use the automatic parameter substitution provided by the `execute` method, e.g. ``` python result = db.execute("SELECT name FROM employees WHERE location = ?", [location]) ``` The DBMS interface itself will automatically convert the values you pass into the correct SQL syntax. For more complex cases, the DBMS module should provide a quoting function that you can explicitly call. For example, MySQLdb provides the `escape_string` method, while APSW (for SQLite3) provides `format_sql_value`. This is necessary where the query structure takes a more dynamic form: ``` python criteria = [("company", company)] # list of tuples (fieldname, value) if department != None : criteria.append(("department", department)) # ... append other optional criteria as appropriate ... result = db.execute( "SELECT name FROM employees WHERE " + " and ".join( "%s = %s" % (criterion[0], MySQLdb.escape_string(criterion[1])) for criterion in criteria ) ) ``` This will dynamically construct queries like "select name from employees where company = \'*some company*\'" or "select name from employees where company = \'*some company*\' and department = \'*some department*\'", depending on which fields have been filled in by the user. ### Use Iterators Python iterators are a natural fit for the problem of iterating over lots of database records. Here is an example of a function that performs a database query and returns an iterator for the results, instead of returning them all at once. It relies on the fact that, in APSW (the Python 3 interface library for SQLite), the `cursor.execute` method itself returns an iterator for the result records. The result is that you can write very concise code for doing complex database queries in Python. ``` python def db_iter(db, cmd, mapfn = lambda x : x) : "executes cmd on a new cursor from connection db and yields the results in turn." cu = db.cursor() result = cu.execute(cmd) while True: yield mapfn(next(result)) ``` Example uses of this function: ``` python for artist, publisher in db_iter( db = db, cmd = "SELECT artist, publisher FROM artists WHERE location = %s" % apsw.format_sql_value(location) ): print(artist, publisher) ``` and ``` python for location in db_iter( db = db, cmd = "SELECT DISTINCT location FROM artists", mapfn = lambda x : x[0] ): print(location) ``` In the first example, since `db_iter` returns a tuple for each record, this can be directly assigned to individual variables for the record fields. In the second example, the tuple has only one element, so a custom `mapfn` is used to extract this element and return it instead of the tuple. ### Never Use "SELECT \*" in a Script Database table definitions are frequently subject to change. As application requirements evolve, fields and even entire tables are often added, or sometimes removed. Consider a statement like ``` python result = db.execute("select * from employees") ``` You may happen to know that the `employees` table currently contains, say, 4 fields. But tomorrow someone may add a fifth field. Did you remember to update your code to deal with this? If not, it's liable to crash. Or even worse, produce an incorrect result! Better to always list the **specific** fields you're interested in, no matter how many there are: ``` python result = db.execute("select name, address, department, location from employees") ``` That way, any extra fields added will simply be ignored. And if any of the named fields are removed, the code will at least fail with a runtime error, which is a good reminder that you forgot to update it! ### Looping on Field Breaks Consider the following scenario: your sales company database has a table of employees, and also a table of sales made by each employee. You want to loop over these sale entries, and produce some per-employee statistics. A naïve approach might be: - Query the database to get a list of employees - For each employee, do a database query to get the list of sales for each employee. If you have a lot of employees, then the first query may produce a large list, and the second step will involve a correspondingly large number of database queries. In fact, the entire processing loop can run off a *single database query*, using the standard SQL construct called a `join`. Here is what an example of such a loop could look like: ``` python rows = db_iter \ ( db = db, cmd = "select employees.name, sales.amount, sales.date from" " employees left join sales on employees.id = sales.employee_id" " order by employees.name, sales.date" ) prev_employee_name = None while True: row = next(rows, None) if row != None : employee_name, amount, date = row if row == None or employee_name != prev_employee_name : if prev_employee_name != None : # done stats for this employee report(prev_employee_name, employee_stats) if row == None : break # start stats for a new employee prev_employee_name = employee_name employee_stats = {"total_sales" : 0, "number_of_sales" : 0} if date != None : employee_stats["earliest_sale"] = date # another row of stats for this employee if amount != None : employee_stats["total_sales"] += amount employee_stats["number_of_sales"] += 1 if date != None : employee_stats["latest_sale"] = date ``` Here the statistics are quite simple: earliest and latest sale, and number and total amount of sales, and could be computed directly within the SQL query. But the same loop could compute more complex statistics (like standard deviation) that cannot be represented directly within a simple SQL query. Note how the statistics for each employee are written out under either of two conditions: - The employee name of the next record is different from the previous one - The end of the query results has been reached. Both conditions are tested with `row == None or employee_name != prev_employee_name`; after writing out the employee statistics, a separate check for the second condition `row == None` is used to terminate the loop. If the loop doesn't terminate, then processing is initialized for the new employee. Note also the use of a `left join` in this case: if an employee has had no sales, then the join will return a single row for that employee, with SQL `null` values (represented by `None` in Python) for the fields from the `sales` table. This is why we need checks for such `None` values before processing those fields. Alternatively, we could have used an `inner join`, which would have returned *no* results for an employee with no sales. Whether you want to omit such an employee from your report, or include them with totals of zero, is really up to your application. ## See Also - Python Programming/Database Programming ## External links - APSW module, code.google.com --- SQLite3 for Python 2.*x* and 3.*x* - SQLite documentation - Psycopg2 (PostgreSQL module - newer), initd.org - PyGreSQL (PostgreSQL module - older), pygresql.org - MySQL module, sourceforge.net - FirebirdSQL module, github.com
# Python Programming/numpy is a numeric library for python. ## Installation It\'s provided with the main Linux distribution, however it can be installed through the Debian package *python-numpy*. On Windows, it can be downloaded on <http://sourceforge.net/projects/numpy/files/>. Then, once the .zip unpacked, the installation is done by entering into the console: `python setup.py install` In case of error: - *ImportError "No Module named Setuptools"*, save the file <https://bootstrap.pypa.io/ez_setup.py> into the Python folder, and install it with: `python ez_setup.py install`. - *Microsoft Visual C++ 9.0 is required*, download it on <https://www.microsoft.com/en-us/download/details.aspx?id=44266> ## Histogram ``` python import numpy mydata = [numpy.random.normal(0,1) for i in range(10000) ] h, n = numpy.histogram( mydata , 100, (-5,5) ) ``` {{\...}} ## See also - <http://numpy.scipy.org/> - <http://docs.scipy.org/doc/numpy/reference/> - Research using FOSS
# Python Programming/Game Programming in Python ### 3D Game Programming #### 3D Game Engine with a Python binding - Irrlicht Engine1 (Python binding website: 2 ) Both are very good free open source C++ 3D game Engine with a Python binding. - CrystalSpace is a free cross-platform software development kit for real-time 3D graphics, with particular focus on games. Crystal Space is accessible from Python in two ways: (1) as a Crystal Space plugin module in which C++ code can call upon Python code, and in which Python code can call upon Crystal Space; (2) as a pure Python module named 'cspace' which one can 'import' from within Python programs. To use the first option, load the 'cspython' plugin as you would load any other Crystal Space plugin, and interact with it via the SCF 'iScript' interface .The second approach allows you to write Crystal Space applications entirely in Python, without any C++ coding. CS Wiki #### 3D Game Engines written for Python Engines designed for Python from scratch. - Blender is an impressive 3D tool with a fully integrated 3D graphics creation suite allowing modeling, animation, rendering, post-production, real-time interactive 3D and game creation and playback with cross-platform compatibility. The 3D game engine uses an embedded python interpreter to make 3D games. - Panda3D is a 3D game engine. It\'s a library written in C++ with Python bindings. Panda3D is designed in order to support a short learning curve and rapid development. This software is available for free download with source code under the BSD License. The development was started by \[Disney\]. Now there are many projects made with Panda3D, such as Disney\'s Pirate\'s of the Caribbean Online, ToonTown, Building Virtual World, Shell Games and many others. Panda3D supports several features: Procedural Geometry, Animated Texture, Render to texture, Track motion, fog, particle system, and many others. - Crystal-space Is a 3D game engine, with a Python bindings, named \*Crystal, view Wikipedia page of \*CrystalSpace. ### 2D Game Programming - Pygame is a cross platform Python library which wraps SDL. It provides many features like Sprite groups and sound/image loading and easy changing of an objects position. It also provides the programmer access to key and mouse events. A full tutorial can be found in the free book \"Making Games with Python & Pygame\". - Phil\'s Pygame Utilities (PGU) is a collection of tools and libraries that enhance Pygame. Tools include a tile editor and a level editor (tile, isometric, hexagonal). GUI enhancements include full featured GUI, HTML rendering, document layout, and text rendering. The libraries include a sprite and tile engine (tile, isometric, hexagonal), a state engine, a timer, and a high score system. (Beta with last update March, 2007. APIs to be deprecated and isometric and hexagonal support is currently Alpha and subject to change.) \[Update 27/02/08 Author indicates he is not currently actively developing this library and anyone that is willing to develop their own scrolling isometric library offering can use the existing code in PGU to get them started.\] - Pyglet is a cross-platform windowing and multimedia library for Python with no external dependencies or installation requirements. Pyglet provides an object-oriented programming interface for developing games and other visually-rich applications for Windows, Mac OS X and Linux. Pyglet allows programs to open multiple windows on multiple screens, draw in those windows with OpenGL, and play back audio and video in most formats. Unlike similar libraries available, pyglet has no external dependencies (such as SDL) and is written entirely in Python. Pyglet is available under a BSD-Style license. - Kivy Kivy is a library for developing multi-touch applications. It is completely cross-platform (Linux/OSX/Win & Android with OpenGL ES2). It comes with native support for many multi-touch input devices, a growing library of multi-touch aware widgets and hardware accelerated OpenGL drawing. Kivy is designed to let you focus on building custom and highly interactive applications as quickly and easily as possible. - Rabbyt A fast Sprite "wikilink") library for Python with game development in mind. With Rabbyt Anims, even old graphics cards can produce very fast animations of 2,400 or more sprites handling position, rotation, scaling, and color simultaneously. ### See Also - 10 Lessons Learned- How To Build a Game In A Week From Scratch With No Budget
# Python Programming/PyQt4 **WARNING: The examples on this page are a mixture of PyQt3 and PyQt4 - use with caution!** This tutorial aims to provide a hands-on guide to learn the basics of building a small Qt4 application in Python. To follow this tutorial, you should have basic Python knowledge. However, knowledge of Qt4 is not necessary. I\'m using Linux in these examples and am assuming you already have a working installation of Python and PyQt4. To test this, open a Python shell (by typing \'Python\' in a console to start the interactive interpreter) and type: `>>> import PyQt4` If no error message appears, you should be ready to go. The examples in this tutorial as easy as possible, showing useful ways to write and structure your program. It is important that you read the source code of the example files, most of the explanations are in the code. The best way to get comfortable with PyQt is play around with the examples and try to change things. ## Hello, world! Let\'s start easy: popping up a window and displaying something. The following small program will pop up a window showing \"Hello, world!\". ``` python #!/usr/bin/env python import sys from PyQt4 import Qt # We instantiate a QApplication passing the arguments of the script to it: a = Qt.QApplication(sys.argv) # Add a basic widget to this application: # The first argument is the text we want this QWidget to show, the second # one is the parent widget. Since Our "hello" is the only thing we use (the # so-called "MainWidget", it does not have a parent. hello = Qt.QLabel("Hello, World") # ... and that it should be shown. hello.show() # Now we can start it. a.exec_() ``` About 7 lines of code, and that\'s about as easy as it can get. ## A Button Let\'s add some interaction! We\'ll replace the label saying \"Hello, World!\" with a button and assign an action to it. This assignment is done by connecting a **signal**, an event which is sent out when the button is pushed, to a **slot**, which is an action, normally a function that is run in the case of that event. ``` python #!/usr/bin/env python import sys from PyQt4 import Qt a = Qt.QApplication(sys.argv) # Our function to call when the button is clicked def sayHello(): print ("Hello, World!") # Instantiate the button hellobutton = Qt.QPushButton("Say 'Hello world!'") # And connect the action "sayHello" to the event "button has been clicked" hellobutton.clicked.connect(sayHello) # The rest is known already... #a.setMainWidget(hellobutton) hellobutton.show() a.exec_() ``` You can imagine that coding this way is not scalable nor the way you\'ll want to continue working. So let\'s make that stuff pythonic, adding structure and actually using object-orientation in it. We create our own application class, derived from a QApplication and put the customization of the application into its methods: One method to build up the widgets and a slot which contains the code that\'s executed when a signal is received. ``` python #!/usr/bin/env python import sys from PyQt4 import Qt class HelloApplication(Qt.QApplication): def __init__(self, args): """ In the constructor we're doing everything to get our application started, which is basically constructing a basic QApplication by its __init__ method, then adding our widgets and finally starting the exec_loop.""" Qt.QApplication.__init__(self, args) self.addWidgets() def addWidgets(self): """ In this method, we're adding widgets and connecting signals from these widgets to methods of our class, the so-called "slots" """ self.hellobutton = Qt.QPushButton("Say 'Hello world!'") self.hellobutton.clicked.connect(self.slotSayHello) self.hellobutton.show() def slotSayHello(self): """ This is an example slot, a method that gets called when a signal is emitted """ print ("Hello, World!") # Only actually do something if this script is run standalone, so we can test our # application, but we're also able to import this program without actually running # any code. if __name__ == "__main__": app = HelloApplication(sys.argv) app.exec_() ``` ## GUI Coding \... so we want to use Qt3 Designer for creating our GUI. In the picture, you can see a simple GUI, with in green letters the names of the widgets. What we are going to do is We compile the .ui file from Qt designer into a python class We subclass that class and use it as our mainWidget This way, we\'re able to change the user interface afterwards from Qt designer, without having it messing around in the code we added. `pyuic4 testapp_ui.ui -o testapp_ui.py` makes a Python file from it which we can work with. The way our program works can be described like this: We fill in the lineedit Clicking the add button will be connected to a method that reads the text from the lineedit, makes a listviewitem out of it and adds that to our listview. Clicking the deletebutton will delete the currently selected item from the listview. Here\'s the heavily commented code (only works in PyQt3): ``` python #!/usr/bin/env python from testapp_ui import TestAppUI from qt import * import sys class HelloApplication(QApplication): def __init__(self, args): """ In the constructor we're doing everything to get our application started, which is basically constructing a basic QApplication by its __init__ method, then adding our widgets and finally starting the exec_loop.""" QApplication.__init__(self, args) # We pass None since it's the top-level widget, we could in fact leave # that one out, but this way it's easier to add more dialogs or widgets. self.maindialog = TestApp(None) self.setMainWidget(self.maindialog) self.maindialog.show() self.exec_loop() class TestApp(TestAppUI): def __init__(self, parent): # Run the parent constructor and connect the slots to methods. TestAppUI.__init__(self, parent) self._connectSlots() # The listview is initially empty, so the deletebutton will have no effect, # we grey it out. self.deletebutton.setEnabled(False) def _connectSlots(self): # Connect our two methods to SIGNALS the GUI emits. self.addbutton.clicked.connect(self._slotAddClicked) self.deletebutton.clicked.connect(self._slotDeleteClicked) def _slotAddClicked(self): # Read the text from the lineedit, text = self.lineedit.text() # if the lineedit is not empty, if len(text): # insert a new listviewitem ... lvi = QListViewItem(self.listview) # with the text from the lineedit and ... lvi.setText(0,text) # clear the lineedit. self.lineedit.clear() # The deletebutton might be disabled, since we're sure that there's now # at least one item in it, we enable it. self.deletebutton.setEnabled(True) def _slotDeleteClicked(self): # Remove the currently selected item from the listview. self.listview.takeItem(self.listview.currentItem()) # Check if the list is empty - if yes, disable the deletebutton. if self.listview.childCount() == 0: self.deletebutton.setEnabled(False) if __name__ == "__main__": app = HelloApplication(sys.argv) ``` also this code is useful and it works on PyQt4 and it has many useful options ``` python #!/usr/bin/env python # Copyright (c) 2008-10 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 2 of the License, or # version 3 of the License, or (at your option) any later version. It is # provided for educational purposes and is distributed in the hope that # it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See # the GNU General Public License for more details. # # # Versions # # 1.0.1 Fixed bug reported by Brian Downing where paths that contained # spaces were not handled correctly. # 1.0.2 Fixed bug reported by Ben Thompson that if the UIC program # fails, no problem was reported; I try to report one now. # 1.1.0 Added Remember path option; if checked the program starts with # the last used path, otherwise with the current directory, unless # overridden on the command line # 1.1.1 Changed default path on Windows to match PyQt 4.4 # 1.2.1 Changed import style + bug fixes # 1.2.2 Added stderr to error message output as per Michael Jackson's # suggestion # 1.2.3 Tried to make the paths work on Mac OS X # 1.2.4 Added more options # 1.2.5 Use "new-style" connections (src.signal.connect(target.slot) instead of # src.connect(src, SIGNAL("signal()"), target.slot)) and improve PEP-8 # compliance from __future__ import division from __future__ import print_function from __future__ import unicode_literals from future_builtins import * import os import platform import stat import sys from PyQt4.QtCore import * from PyQt4.QtGui import * __version__ = "1.2.5" Windows = sys.platform.lower().startswith(("win", "microsoft")) class OptionsForm(QDialog): def __init__(self, parent=None): super(OptionsForm, self).__init__(parent) settings = QSettings() if sys.platform.startswith("darwin"): pyuic4Label = QLabel("pyuic4 (pyuic.py)") else: pyuic4Label = QLabel("pyuic4") self.pyuic4Label = QLabel(settings.value("pyuic4", QVariant(PYUIC4)).toString()) self.pyuic4Label.setFrameStyle(QFrame.StyledPanel| QFrame.Sunken) pyuic4Button = QPushButton("py&uic4...") pyrcc4Label = QLabel("pyrcc4") self.pyrcc4Label = QLabel(settings.value("pyrcc4", QVariant(PYRCC4)).toString()) self.pyrcc4Label.setFrameStyle(QFrame.StyledPanel| QFrame.Sunken) pyrcc4Button = QPushButton("p&yrcc4...") pylupdate4Label = QLabel("pylupdate4") self.pylupdate4Label = QLabel(settings.value("pylupdate4", QVariant(PYLUPDATE4)).toString()) self.pylupdate4Label.setFrameStyle(QFrame.StyledPanel| QFrame.Sunken) pylupdate4Button = QPushButton("&pylupdate4...") lreleaseLabel = QLabel("lrelease") self.lreleaseLabel = QLabel(settings.value("lrelease", QVariant("lrelease")).toString()) self.lreleaseLabel.setFrameStyle(QFrame.StyledPanel| QFrame.Sunken) lreleaseButton = QPushButton("&lrelease...") toolPathGroupBox = QGroupBox("Tool Paths") pathsLayout = QGridLayout() pathsLayout.addWidget(pyuic4Label, 0, 0) pathsLayout.addWidget(self.pyuic4Label, 0, 1) pathsLayout.addWidget(pyuic4Button, 0, 2) pathsLayout.addWidget(pyrcc4Label, 1, 0) pathsLayout.addWidget(self.pyrcc4Label, 1, 1) pathsLayout.addWidget(pyrcc4Button, 1, 2) pathsLayout.addWidget(pylupdate4Label, 2, 0) pathsLayout.addWidget(self.pylupdate4Label, 2, 1) pathsLayout.addWidget(pylupdate4Button, 2, 2) pathsLayout.addWidget(lreleaseLabel, 3, 0) pathsLayout.addWidget(self.lreleaseLabel, 3, 1) pathsLayout.addWidget(lreleaseButton, 3, 2) toolPathGroupBox.setLayout(pathsLayout) resourceModuleNamesGroupBox = QGroupBox( "Resource Module Names") qrcFiles = bool(int(settings.value("qrc_resources", "1").toString())) self.qrcRadioButton = QRadioButton("&qrc_file.py") self.qrcRadioButton.setChecked(qrcFiles) self.rcRadioButton = QRadioButton("file_&rc.py") self.rcRadioButton.setChecked(not qrcFiles) radioLayout = QHBoxLayout() radioLayout.addWidget(self.qrcRadioButton) radioLayout.addWidget(self.rcRadioButton) resourceModuleNamesGroupBox.setLayout(radioLayout) self.pyuic4xCheckBox = QCheckBox("Run pyuic4 with -&x " " to make forms stand-alone runable") x = bool(int(settings.value("pyuic4x", "0").toString())) self.pyuic4xCheckBox.setChecked(x) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok| QDialogButtonBox.Cancel) layout = QVBoxLayout() layout.addWidget(toolPathGroupBox) layout.addWidget(resourceModuleNamesGroupBox) layout.addWidget(self.pyuic4xCheckBox) layout.addWidget(buttonBox) self.setLayout(layout) pyuic4Button.clicked.connect(lambda: self.setPath("pyuic4")) pyrcc4Button.clicked.connect(lambda: self.setPath("pyrcc4")) pylupdate4Button.clicked.connect(lambda: self.setPath("pylupdate4")) lreleaseButton.clicked.connect(lambda: self.setPath("lrelease")) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) self.setWindowTitle("Make PyQt - Options") def accept(self): settings = QSettings() settings.setValue("pyuic4", QVariant(self.pyuic4Label.text())) settings.setValue("pyrcc4", QVariant(self.pyrcc4Label.text())) settings.setValue("pylupdate4", QVariant(self.pylupdate4Label.text())) settings.setValue("lrelease", QVariant(self.lreleaseLabel.text())) settings.setValue("qrc_resources", "1" if self.qrcRadioButton.isChecked() else "0") settings.setValue("pyuic4x", "1" if self.pyuic4xCheckBox.isChecked() else "0") QDialog.accept(self) def setPath(self, tool): if tool == "pyuic4": label = self.pyuic4Label elif tool == "pyrcc4": label = self.pyrcc4Label elif tool == "pylupdate4": label = self.pylupdate4Label elif tool == "lrelease": label = self.lreleaseLabel path = QFileDialog.getOpenFileName(self, "Make PyQt - Set Tool Path", label.text()) if path: label.setText(QDir.toNativeSeparators(path)) class Form(QMainWindow): def __init__(self): super(Form, self).__init__() pathLabel = QLabel("Path:") settings = QSettings() rememberPath = settings.value("rememberpath", QVariant(True if Windows else False)).toBool() if rememberPath: path = (unicode(settings.value("path").toString()) or os.getcwd()) else: path = (sys.argv[1] if len(sys.argv) > 1 and QFile.exists(sys.argv[1]) else os.getcwd()) self.pathLabel = QLabel(path) self.pathLabel.setFrameStyle(QFrame.StyledPanel| QFrame.Sunken) self.pathLabel.setToolTip("The relative path; all actions will " "take place here,<br>and in this path's subdirectories " "if the Recurse checkbox is checked") self.pathButton = QPushButton("&Path...") self.pathButton.setToolTip(self.pathLabel.toolTip().replace( "The", "Sets the")) self.recurseCheckBox = QCheckBox("&Recurse") self.recurseCheckBox.setToolTip("Clean or build all the files " "in the path directory,<br>and all its subdirectories, " "as deep as they go.") self.transCheckBox = QCheckBox("&Translate") self.transCheckBox.setToolTip("Runs <b>pylupdate4</b> on all " "<tt>.py</tt> and <tt>.pyw</tt> files in conjunction " "with each <tt>.ts</tt> file.<br>Then runs " "<b>lrelease</b> on all <tt>.ts</tt> files to produce " "corresponding <tt>.qm</tt> files.<br>The " "<tt>.ts</tt> files must have been created initially by " "running <b>pylupdate4</b><br>directly on a <tt>.py</tt> " "or <tt>.pyw</tt> file using the <tt>-ts</tt> option.") self.debugCheckBox = QCheckBox("&Dry Run") self.debugCheckBox.setToolTip("Shows the actions that would " "take place but does not do them.") self.logBrowser = QTextBrowser() self.logBrowser.setLineWrapMode(QTextEdit.NoWrap) self.buttonBox = QDialogButtonBox() menu = QMenu(self) optionsAction = menu.addAction("&Options...") self.rememberPathAction = menu.addAction("&Remember path") self.rememberPathAction.setCheckable(True) self.rememberPathAction.setChecked(rememberPath) aboutAction = menu.addAction("&About") moreButton = self.buttonBox.addButton("&More", QDialogButtonBox.ActionRole) moreButton.setMenu(menu) moreButton.setToolTip("Use <b>More-&gt;Tool paths</b> to set the " "paths to the tools if they are not found by default") self.buildButton = self.buttonBox.addButton("&Build", QDialogButtonBox.ActionRole) self.buildButton.setToolTip("Runs <b>pyuic4</b> on all " "<tt>.ui</tt> " "files and <b>pyrcc4</b> on all <tt>.qrc</tt> files " "that are out-of-date.<br>Also runs <b>pylupdate4</b> " "and <b>lrelease</b> if the Translate checkbox is " "checked.") self.cleanButton = self.buttonBox.addButton("&Clean", QDialogButtonBox.ActionRole) self.cleanButton.setToolTip("Deletes all <tt>.py</tt> files that " "were generated from <tt>.ui</tt> and <tt>.qrc</tt> " "files,<br>i.e., all files matching <tt>qrc_*.py</tt>, " "<tt>*_rc.py</tt> and <tt>ui_*.py.") quitButton = self.buttonBox.addButton("&Quit", QDialogButtonBox.RejectRole) topLayout = QHBoxLayout() topLayout.addWidget(pathLabel) topLayout.addWidget(self.pathLabel, 1) topLayout.addWidget(self.pathButton) bottomLayout = QHBoxLayout() bottomLayout.addWidget(self.recurseCheckBox) bottomLayout.addWidget(self.transCheckBox) bottomLayout.addWidget(self.debugCheckBox) bottomLayout.addStretch() bottomLayout.addWidget(self.buttonBox) layout = QVBoxLayout() layout.addLayout(topLayout) layout.addWidget(self.logBrowser) layout.addLayout(bottomLayout) widget = QWidget() widget.setLayout(layout) self.setCentralWidget(widget) aboutAction.triggered.connect(self.about) optionsAction.triggered.connect(self.setOptions) self.pathButton.clicked.connect(self.setPath) self.buildButton.clicked.connect(self.build) self.cleanButton.clicked.connect(self.clean) quitButton.clicked.connect(self.close) self.setWindowTitle("Make PyQt") def closeEvent(self, event): settings = QSettings() settings.setValue("rememberpath", QVariant(self.rememberPathAction.isChecked())) settings.setValue("path", QVariant(self.pathLabel.text())) event.accept() def about(self): QMessageBox.about(self, "About Make PyQt", """<b>Make PyQt</b> v {0} <p>Copyright &copy; 2007-10 Qtrac Ltd. All rights reserved. <p>This application can be used to build PyQt applications. It runs pyuic4, pyrcc4, pylupdate4, and lrelease as required, although pylupdate4 must be run directly to create the initial .ts files. <p>Python {1} - Qt {2} - PyQt {3} on {4}""".format( __version__, platform.python_version(), QT_VERSION_STR, PYQT_VERSION_STR, platform.system())) def setPath(self): path = QFileDialog.getExistingDirectory(self, "Make PyQt - Set Path", self.pathLabel.text()) if path: self.pathLabel.setText(QDir.toNativeSeparators(path)) def setOptions(self): dlg = OptionsForm(self) dlg.exec_() def build(self): self.updateUi(False) self.logBrowser.clear() recurse = self.recurseCheckBox.isChecked() path = unicode(self.pathLabel.text()) self._apply(recurse, self._build, path) if self.transCheckBox.isChecked(): self._apply(recurse, self._translate, path) self.updateUi(True) def clean(self): self.updateUi(False) self.logBrowser.clear() recurse = self.recurseCheckBox.isChecked() path = unicode(self.pathLabel.text()) self._apply(recurse, self._clean, path) self.updateUi(True) def updateUi(self, enable): for widget in (self.buildButton, self.cleanButton, self.pathButton, self.recurseCheckBox, self.transCheckBox, self.debugCheckBox): widget.setEnabled(enable) if not enable: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) else: QApplication.restoreOverrideCursor() self.buildButton.setFocus() def _apply(self, recurse, function, path): if not recurse: function(path) else: for root, dirs, files in os.walk(path): for dir in sorted(dirs): function(os.path.join(root, dir)) def _make_error_message(self, command, process): err = "" ba = process.readAllStandardError() if not ba.isEmpty(): err = ": " + str(QString(ba)) return "<span style="color:red;">FAILED: %s%s</span>" % (command, err) def _build(self, path): settings = QSettings() pyuic4 = unicode(settings.value("pyuic4", QVariant(PYUIC4)).toString()) pyrcc4 = unicode(settings.value("pyrcc4", QVariant(PYRCC4)).toString()) prefix = unicode(self.pathLabel.text()) pyuic4x = bool(int(settings.value("pyuic4x", "0").toString())) if not prefix.endswith(os.sep): prefix += os.sep failed = 0 process = QProcess() for name in os.listdir(path): source = os.path.join(path, name) target = None if source.endswith(".ui"): target = os.path.join(path, "ui_" + name.replace(".ui", ".py")) command = pyuic4 elif source.endswith(".qrc"): if bool(int(settings.value("qrc_resources", "1").toString())): target = os.path.join(path, "qrc_" + name.replace(".qrc", ".py")) else: target = os.path.join(path, name.replace(".qrc", "_rc.py")) command = pyrcc4 if target is not None: if not os.access(target, os.F_OK) or ( os.stat(source)[stat.ST_MTIME] > os.stat(target)[stat.ST_MTIME]): args = ["-o", target, source] if command == PYUIC4 and pyuic4x: args.insert(0, "-x") if (sys.platform.startswith("darwin") and command == PYUIC4): command = sys.executable args = [PYUIC4] + args msg = ("converted <span style="color:darkblue;">" + source + "</span> to <span style="color:blue;">" + target + "</span>") if self.debugCheckBox.isChecked(): msg = "<span style="color:green;"># " + msg + "</span>" else: process.start(command, args) if (not process.waitForFinished(2 * 60 * 1000) or not QFile.exists(target)): msg = self._make_error_message(command, process) failed += 1 self.logBrowser.append(msg.replace(prefix, "")) else: self.logBrowser.append("<span style="color:green;">" "# {0} is up-to-date</span>".format( source.replace(prefix, ""))) QApplication.processEvents() if failed: QMessageBox.information(self, "Make PyQt - Failures", "Try manually setting the paths to the tools " "using <b>More-&gt;Options</b>") def _clean(self, path): prefix = unicode(self.pathLabel.text()) if not prefix.endswith(os.sep): prefix += os.sep deletelist = [] for name in os.listdir(path): target = os.path.join(path, name) source = None if (target.endswith(".py") or target.endswith(".pyc") or target.endswith(".pyo")): if name.startswith("ui_") and not name[-1] in "oc": source = os.path.join(path, name[3:-3] + ".ui") elif name.startswith("qrc_"): if target[-1] in "oc": source = os.path.join(path, name[4:-4] + ".qrc") else: source = os.path.join(path, name[4:-3] + ".qrc") elif name.endswith(("_rc.py", "_rc.pyo", "_rc.pyc")): if target[-1] in "oc": source = os.path.join(path, name[:-7] + ".qrc") else: source = os.path.join(path, name[:-6] + ".qrc") elif target[-1] in "oc": source = target[:-1] if source is not None: if os.access(source, os.F_OK): if self.debugCheckBox.isChecked(): self.logBrowser.append("<span style="color:green;">" "# delete {0}</span>".format( target.replace(prefix, ""))) else: deletelist.append(target) else: self.logBrowser.append("<span style="color:darkred;">" "will not remove " "'{0}' since `{1}' not found</span>" .format(target.replace(prefix, ""), source.replace(prefix, ""))) if not self.debugCheckBox.isChecked(): for target in deletelist: self.logBrowser.append("deleted " "<span style="color:red;">{0}</span>".format( target.replace(prefix, ""))) os.remove(target) QApplication.processEvents() def _translate(self, path): prefix = unicode(self.pathLabel.text()) if not prefix.endswith(os.sep): prefix += os.sep files = [] tsfiles = [] for name in os.listdir(path): if name.endswith((".py", ".pyw")): files.append(os.path.join(path, name)) elif name.endswith(".ts"): tsfiles.append(os.path.join(path, name)) if not tsfiles: return settings = QSettings() pylupdate4 = unicode(settings.value("pylupdate4", QVariant(PYLUPDATE4)).toString()) lrelease = unicode(settings.value("lrelease", QVariant(LRELEASE)).toString()) process = QProcess() failed = 0 for ts in tsfiles: qm = ts[:-3] + ".qm" command1 = pylupdate4 args1 = files + ["-ts", ts] command2 = lrelease args2 = ["-silent", ts, "-qm", qm] msg = "updated <span style="color:blue;">{0}</span>".format( ts.replace(prefix, "")) if self.debugCheckBox.isChecked(): msg = "<span style="color:green;"># {0}</span>".format(msg) else: process.start(command1, args1) if not process.waitForFinished(2 * 60 * 1000): msg = self._make_error_message(command1, process) failed += 1 self.logBrowser.append(msg) msg = "generated <span style="color:blue;">{0}</span>".format( qm.replace(prefix, "")) if self.debugCheckBox.isChecked(): msg = "<span style="color:green;"># {0}</span>".format(msg) else: process.start(command2, args2) if not process.waitForFinished(2 * 60 * 1000): msg = self._make_error_message(command2, process) failed += 1 self.logBrowser.append(msg) QApplication.processEvents() if failed: QMessageBox.information(self, "Make PyQt - Failures", "Try manually setting the paths to the tools " "using <b>More-&gt;Options</b>") app = QApplication(sys.argv) PATH = unicode(app.applicationDirPath()) if Windows: PATH = os.path.join(os.path.dirname(sys.executable), "Lib/site-packages/PyQt4") if os.access(os.path.join(PATH, "bin"), os.R_OK): PATH = os.path.join(PATH, "bin") if sys.platform.startswith("darwin"): i = PATH.find("Resources") if i > -1: PATH = PATH[:i] + "bin" PYUIC4 = os.path.join(PATH, "pyuic4") if sys.platform.startswith("darwin"): PYUIC4 = os.path.dirname(sys.executable) i = PYUIC4.find("Resources") if i > -1: PYUIC4 = PYUIC4[:i] + "Lib/python2.6/site-packages/PyQt4/uic/pyuic.py" PYRCC4 = os.path.join(PATH, "pyrcc4") PYLUPDATE4 = os.path.join(PATH, "pylupdate4") LRELEASE = "lrelease" if Windows: PYUIC4 = PYUIC4.replace("/", "\\") + ".bat" PYRCC4 = PYRCC4.replace("/", "\\") + ".exe" PYLUPDATE4 = PYLUPDATE4.replace("/", "\\") + ".exe" app.setOrganizationName("Qtrac Ltd.") app.setOrganizationDomain("qtrac.eu") app.setApplicationName("Make PyQt") if len(sys.argv) > 1 and sys.argv[1] == "-c": settings = QSettings() settings.setValue("pyuic4", QVariant(PYUIC4)) settings.setValue("pyrcc4", QVariant(PYRCC4)) settings.setValue("pylupdate4", QVariant(PYLUPDATE4)) settings.setValue("lrelease", QVariant(LRELEASE)) form = Form() form.show() app.exec_() ``` ## Useful to Know Creating the GUI in Qt Designer not only makes creating the GUI easier, but it\'s also a great learning tool. You can test what a widget looks like, see what\'s available in Qt, and have a look at properties you might want to use. The C++ API documentation is also a very useful (read: necessary) tool when working with PyQt. The API translation is straightforward, and after a little experience, you\'ll find the developers API docs one of the tools you really need. When working from KDE, konqueror\'s default shortcut is qt:\[widgetname\], so \[alt\]+\[F2\], \"qt:qbutton directly takes you to the right API documentation page. Trolltech\'s doc section has much more documentation which you might want to have a look at. The first 3 examples in this tutorial have been created using PyQt4, the last one uses syntax that only works with PyQt3. Note: The previous version of this page (applicable to pyqt3) is/was available at <http://vizzzion.org/?id=pyqt>. This document is published under the GNU Free Documentation License. fr:PyQt
# Python Programming/Dbus In Linux, **Dbus** is a way for processes to communicate with each other. For example, programs like Pidgin instant messenger allow other programs to find out or change the user\'s status (Available, Away, etc). Another example is the network-manager service that publishes which internet connection is active. Programs that sometimes connect to the internet can then pick the best time to download updates to the system. ## Buses Messages are sent along buses. Services attach themselves to these buses, and allow clients to pass messages to and from them. There are two main buses, the **system bus** and **session bus**. Services on the system bus affect the whole system, such as providing information about the network or disk drives. Services on the session bus provide access to programs running on the desktop, like Pidgin. ``` python import dbus sys_bus = dbus.SystemBus() ``` ## Objects and interfaces Services attached to a bus can be contacted using their **well-known name**. While this could be any string, the format is normally that of a reverse domain name: an example for a spreadsheet program called \"CalcProgram\" from \"My Corp Inc.\" could be \"com.mycorp.CalcProgram\". Services publish objects using slash-separated paths (this is similar to webpages). Someone on dbus can request an object if they know this path. The object passed back is not a full object: it just refers to the service\'s copy of the object. It is called a **proxy object**. ``` python proxy_for_cell_a2 = sys_bus.get_object('com.mycorp.CalcProgram', '/spreadsheet1/cells/a2') ``` Before the proxy object can be used, we need to specify what type of object it is. We do this by creating an interface object. ``` python cell_a2 = dbus.Interface(proxy_for_cell_a2, 'com.mycorp.CalcProgram.SpreadsheetCell') ``` Whatever methods are set up for this type of object can be called: ``` python cell_a2.getContents() ``` Name Example Description ------------------------- ---------------------------------------- --------------------------------------------- service well known name com.mycorp.CalcProgram Identifies the application path of an object /spreadsheet1/cells/a2 Identifies an object published by a service interface com.mycorp.CalcProgram.SpreadsheetCell Identifies what type of object we expect ## dbus-python examples These examples have been tested with dbus-python 0.83.0. Older library versions may not have the same interface. Calling an interface\'s methods / Listing HAL Devices: ``` python import dbus bus = dbus.SystemBus() hal_manager_object = bus.get_object('org.freedesktop.Hal', '/org/freedesktop/Hal/Manager') hal_manager_interface = dbus.Interface(hal_manager_object, 'org.freedesktop.Hal.Manager') # calling method upon interface print hal_manager_interface.GetAllDevices() # accessing a method through 'get_dbus_method' through proxy object by specifying interface method = hal_manager_object.get_dbus_method('GetAllDevices', 'org.freedesktop.Hal.Manager') print(method()) # calling method upon proxy object by specifying the interface to use print( hal_manager_object.GetAllDevices(dbus_interface='org.freedesktop.Hal.Manager')) ``` Introspecting an object: ``` python import dbus bus = dbus.SystemBus() hal_manager_object = bus.get_object( 'org.freedesktop.Hal', # service '/org/freedesktop/Hal/Manager' # published object ) introspection_interface = dbus.Interface( hal_manager_object, dbus.INTROSPECTABLE_IFACE, ) # Introspectable interfaces define a property 'Introspect' that # will return an XML string that describes the object's interface interface = introspection_interface.Introspect() print(interface) ``` Avahi: ``` python import dbus sys_bus = dbus.SystemBus() # get an object called / in org.freedesktop.Avahi to talk to raw_server = sys_bus.get_object('org.freedesktop.Avahi', '/') # objects support interfaces. get the org.freedesktop.Avahi.Server interface to our org.freedesktop.Avahi object. server = dbus.Interface(raw_server, 'org.freedesktop.Avahi.Server') # The so-called documentation is at /usr/share/avahi/introspection/Server.introspect print(server) print(server.GetVersionString()) print(server.GetHostName()) ``` ## pydbus examples These examples have been tested with pydbus 0.2 and 0.3. Calling an interface\'s methods / Listing systemd units: ``` python from pydbus import SystemBus bus = SystemBus() systemd = bus.get( '.systemd1' # service name - names starting with . automatically get org.freedesktop prepended. # no object path - it'll be set to the service name transformed to the path format (/org/freedesktop/systemd1) ) for unit in systemd.ListUnits()[0]: print(unit) ``` Introspecting an object: ``` python from pydbus import SystemBus bus = SystemBus() systemd = bus.get('.systemd1') # Introspectable interfaces define a property 'Introspect' that # will return an XML string that describes the object's interface print(systemd.Introspect()[0]) # Introspection data is automatically converted to Python's help system data help(systemd) ``` Avahi: ``` python from pydbus import SystemBus bus = SystemBus() # get an object called / in org.freedesktop.Avahi to talk to avahi = bus.get('.Avahi', '/') # See the object's API help(avahi) print(avahi.GetVersionString()) print(avahi.GetHostName()) ``` ## References - dbus-python tutorial, dbus.freedesktop.org, Simon McVittie, 2006-06-14 - pydbus README.rst, github.com - DbusExamples, wiki.python.org - D-Bus Howto, developer.pidgin.im - Rough notes: Python and D-Bus, archived version, A.M. Kuchling, 2007, originally at www.amk.ca
# Python Programming/matplotlib matplotlib is a Python library that allows Python to be used like Matlab, visualizing data on the fly. It is able to create plots, histograms, power spectra, bar charts, errorcharts, scatterplots, etc. It can be used from normal Python and also from iPython. Examples: Plot a data series that represents the square function: ``` py from matplotlib import pyplot as plt data = [x * x for x in range(20)] plt.plot(data) plt.show() ``` Plot a data series that represents the square function but in reverse order, by providing not only the series of the y-axis values but also the series of x-axis values: ``` py from matplotlib import pyplot as plt datax = range(20) datax.reverse() datay = [x * x for x in range(20)] plt.plot(datax, datay) plt.show() ``` Plot the square function, setting the limits for the y-axis: ``` py from matplotlib import pyplot as plt data = [x * x for x in range(20)] plt.ylim(-500, 500) # Set limits of y-axis plt.plot(data) plt.show() ``` ## Links - matplotlib, matplotlib.org - Pyplot tutorial, matplotlib.org
# Python Programming/Sorted Container Types Python does not provide modules for *sorted* set and dictionary data types as part of its standard library. This is a concious decision on the part of Guido van Rossum, et al. to preserve \"one obvious way to do it.\" Instead, Python delegates this task to third-party libraries that are available on the Python Package Index. These libraries use various techniques to maintain list, dict, and set types in sorted order. Maintaining order using a specialized data structure can avoid very slow behavior (quadratic run-time) in the naive approach of editing and constantly re-sorting. Third-party modules supporting sorted containers: - SortedContainers - Pure-Python implementation that is fast-as-C implementations. Implements sorted list, dict, and set. Testing includes 100% code coverage and hours of stress. Documentation includes full API reference, performance comparison, and contributing/development guidelines. License: Apache2. - rbtree - Provides a fast, C-implementation for sorted dict and set data types. Based on a red-black tree implementation. - treap - Provides a sorted dict data type. Uses a treap for implementation and improves performance using Cython. - bintrees - Provides several tree-based implementations for dict and set data types. Fastest implementations are based on AVL and Red-Black trees. Implemented in C. Extends the conventional API to provide set operations for dict data types. - banyan - Provides a fast, C-implementation for dict and set data types. - skiplistcollections - Pure-Python implementation based on skip-lists providing a limited API for dict and set data types. - blist - Provides sorted list, dict and set data types based on the \"blist\" data type, a B-tree implementation. Implemented in Python and C. ## External links - SortedContainers, pypi.python.org - rbtree, pypi.python.org - treap, pypi.python.org - bintrees, pypi.python.org - Banyan, pypi.python.org - skiplistcollections, pypi.python.org - blist, pypi.python.org
# Python Programming/Excel Python has multiple 3rd party libraries for reading and writing Microsoft Excel spreadsheet files, including .xls and .xlsx. For working with .xls files, there is *xlrd* for reading and *xlwt* for writing. For working with .xlsx files, there is *xlrd* for reading, *openpyxl* for reading and writing, and *XlsxWriter* and *PyExcelerate* for writing. To interact with the Excel application and create Python-based add-ins: *xlwings*, *xlOil*, *PyXLL* (commercial). ## xlrd Supports reading .xls Excel files. Support for .xlsx files was removed in xlrd version 2.0.0 from Dec 2020 due to security concerns, but is still available in xlrd version 1.2.0 from Dec 2018. License: BSD. Example: ``` Python import xlrd workbook = xlrd.open_workbook("MySpreadsheet.xls") #for sheet in workbook.sheets(): # Loads all the sheets, unlike workbook.sheet_names() for sheetName in workbook.sheet_names(): # Sheet iteration by name print("Sheet name:", sheetName) sheet = workbook.sheet_by_name(sheetName) for rowno in range(sheet.nrows): for colno in range(sheet.ncols): cell = sheet.cell(rowno, colno) print(str(cell.value)) # Output as a string if cell.ctype == xlrd.XL_CELL_DATE: dateTuple = xlrd.xldate_as_tuple(cell.value, workbook.datemode) print(dateTuple) # E.g. (2017, 1, 1, 0, 0, 0) mydate = xlrd.xldate.xldate_as_datetime(cell.value, workbook.datemode) print(mydate) # In xlrd 0.9.3 print() for sheetno in range(workbook.nsheets): # Sheet iteration by index sheet = workbook.sheet_by_index(sheetno) print("Sheet name:", sheet.name) for notekey in sheet.cell_note_map: # In xlrd 0.7.2 print("Note AKA comment text:", sheet.cell_note_map[notekey].text) print(xlrd.formula.colname(1)) # Column name such as A or AD, here 'B' ``` Links: - xlrd, pypi.python.org - xlrd 1.2.0, pypi.python.org - xlrd documentation, readthedocs.io - xlrd API documentation, readthedocs.io - Python: xlrd discerning dates from floats, stackoverflow.com - xlrd.biffh.XLRDError: Excel xlsx file; not supported, 11 Dec 2020, stackoverflow.com - xlrd 2 released, 11 Dec 2020, groups.google.com ## xlwt Supports writing .xls files. License: BSD. Links: - xlwt, pypi.python.org - xlwt documentation, readthedocs.io ## openpyxl Supports reading and writing .xlsx Excel files. Does not support .xls files. License: MIT. Reading a workbook: ``` python from openpyxl import load_workbook workbook = load_workbook("MyNewWorkbook.xlsx") for worksheet in workbook.worksheets: print("==%s==" % worksheet.title) for row in worksheet: # For each cell in each row for cell in row: print(cell.row, cell.column, cell.value) # E.g. 1 A Value for cell in worksheet["A"]: # For each cell in column A print(cell.value) print(worksheet["A1"].value) # A single cell print(worksheet.cell(column=1, row=1).value) # A1 value as well ``` Creating a new workbook: ``` python from openpyxl import Workbook workbook = Workbook() worksheet = workbook.worksheets[0] worksheet['A1'] = 'String value' worksheet['A2'] = 42 # Numerical value worksheet.cell(row=3, column=1).value = "New A3 Value" workbook.save("MyNewWorkbook.xlsx") # Overrides if it exists ``` Changing an existing workbook: ``` python from openpyxl import load_workbook workbook_name = 'MyWorkbook.xlsx' workbook = load_workbook(workbook_name) worksheet = workbook.worksheets[0] worksheet['A1'] = "String value" workbook.save(workbook_name) ``` Links: - openpyxl, pypi.org - openpyxl - A Python library to read/write Excel 2010 xlsx/xlsm files, readthedocs.io ## XlsxWriter Supports writing of .xlsx files. License: BSD. Links: - XlsxWriter, pypi.org - Creating Excel files with Python and XlsxWriter, readthedocs.io ## PyExcelerate Supports writing .xlsx files. License: BSD. Links: - PyExcelerate, pypi.org ## xlutils Supports various operations and queries on .xls files; depends on xlrd and xlwt. License: MIT. Links: - xlutils, pypi.org ## xlOil Supports creation of Python-based Excel add-ins. Requires Python 3.6 or later; requires Excel 2010 or later installed. Supports: global and local scope worksheet functions, ribbon customisation, custom task panes, RTD/async functions, *numpy*, *matplotlib*, *pandas*, *jupyter*. Low overhead function calls due to use of the Excel\'s C-API and embedded in-process Python Examples: Create a function to add one day to a date: ``` Python import datetime as dt @xloil.func def pyTestDate(x: dt.datetime) -> dt.datetime:     return x + dt.timedelta(days=1) ``` Create a function which give a live ticking clock in an cell (uses RTD): ``` python @xloil.func async def pyTestAsyncGen(secs): while True: await asyncio.sleep(secs) yield datetime.datetime.now() ``` Links: - xlOil, pypi.org - xloil, readthedocs.io ## pywin32 Supports access to Windows applications via Windows Component Object Model (COM). Thus, on Windows, if Excel is installed, PyWin32 lets you call it from Python and let it do various things. You can install PyWin32 by downloading a .exe installer from SourceForge, where it is currently hosted. Links: - 3.4.1. PyWin32, docs.python.org - pywin32, pypi.org - Python for Windows Extensions files, sourceforge.net - Python Excel Mini Cookbook, pythonexcels.com ## External links - Working with Excel Files in Python, python-excel.org \-- has links to source code repositories (GitHub, etc.) for the packages
# Python Programming/MS Word Microsoft Word documents of the .docx format can be created or changed using python-docx 3rd party module. The .doc format can be worked with on Windows using PyWin32 via COM interface, provided Word is installed. An example: ``` Python import win32com.client wordapp = win32com.client.gencache.EnsureDispatch("Word.Application") # wordapp.Visible = False worddoc = wordapp.Documents.Open(r"C:\MyFile.doc") wdFormatHTML = 8 worddoc.SaveAs(r"C:\MyFile.html", FileFormat=wdFormatHTML) worddoc.ActiveWindow.Close() # wordapp.Application.Quit(-1) - No need to quit; Word quits when its last window is closed ``` ## External links - python-docx, pypi.python.org - python-docx, readthedocs.io
# Python Programming/Extending with C Python modules can be written in pure Python but they can also be written in the C language. The following shows how to extend Python with C. ## Using the Python/C API ### A minimal example To illustrate the mechanics, we will create a minimal extension module containing a single function that outputs \"Hello\" followed by the name passed in as the first parameter. We will first create the C source code, placing it to **hellomodule.c**: ``` c #include <Python.h> static PyObject* say_hello(PyObject* self, PyObject* args) { const char* name; if (!PyArg_ParseTuple(args, "s", &name)) return NULL; printf("Hello %s!\n", name); Py_RETURN_NONE; } static PyMethodDef HelloMethods[] = { {"say_hello", say_hello, METH_VARARGS, "Greet somebody."}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC inithello(void) { (void) Py_InitModule("hello", HelloMethods); } ``` Then we will need a setup file, **setup.py**: ``` python from distutils.core import setup, Extension module1 = Extension('hello', sources = ['hellomodule.c']) setup (name = 'PackageName', version = '1.0', description = 'This is a demo package', ext_modules = [module1]) ``` Then we can build the module using a procedure whose details depends on the operating system and the compiler suite. #### Building with GCC for Linux Before our module can be compiled, you must install the Python development headers if you have not already. On Debian and Debian-based systems such as Ubuntu, these can be installed with the following command: ``` bash $ sudo apt install python-dev ``` On openSUSE, the required package is called `python-devel` and can be installed with `zypper`: ``` bash $ sudo zypper install python-devel ``` Now that `Python.h` is available, we can compile the module source code we created in the previous section as follows: ``` bash $ python setup.py build ``` The will compile the module to a file called `hello.so` in `build/lib.linux-i686-`*`x`*`.`*`y`*. #### Building with GCC for Microsoft Windows Microsoft Windows users can use MinGW to compile the extension module from the command line. Assuming `gcc` is in the path, you can build the extension as follows: `python setup.py build -cmingw32` The above will produce file `hello.pyd`, a Python Dynamic Module, similar to a DLL. The file will land in `build\lib.win32-`*`x`*`.`*`y`*. An alternate way of building the module in Windows is to build a DLL. (This method does not need an extension module file). From `cmd.exe`, type: `gcc -c  hellomodule.c -I/Python`*`XY`*`/include`\ `gcc -shared hellomodule.o -L/Python`*`XY`*`/libs -lpython`*`XY`*` -o hello.dll` where *XY* represents the version of Python, such as \"24\" for version 2.4. #### Building using Microsoft Visual C++ With VC8, distutils is broken. Therefore, we will use cl.exe from a command prompt instead: `cl /LD hellomodule.c /Ic:\Python24\include c:\Python24\libs\python24.lib /link/out:hello.dll` #### Using the extension module Change to the subdirectory where the file hello.so resides. In an interactive Python session you can use the module as follows. `>>> import hello`\ `>>> hello.say_hello("World")`\ `Hello World!` ### A module for calculating Fibonacci numbers In this section, we present a module for Fibonacci numbers, thereby expanding on the minimal example above. Compared to the minimal example, what is worth noting is the use of \"i\" in PyArg_ParseTuple() and Py_BuildValue(). The C source code in (fibmodule.c): ``` c #include <Python.h> int _fib(int n) { if (n < 2) return n; else return _fib(n-1) + _fib(n-2); } static PyObject* fib(PyObject* self, PyObject* args) { int n; if (!PyArg_ParseTuple(args, "i", &n)) return NULL; return Py_BuildValue("i", _fib(n)); } static PyMethodDef FibMethods[] = { {"fib", fib, METH_VARARGS, "Calculate the Fibonacci numbers."}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initfib(void) { (void) Py_InitModule("fib", FibMethods); } ``` The build script (setup.py): ``` python from distutils.core import setup, Extension module1 = Extension('fib', sources = ['fibmodule.c']) setup (name = 'PackageName', version = '1.0', description = 'This is a demo package', ext_modules = [module1]) ``` Usage: `>>> import fib`\ `>>> fib.fib(10)`\ `55` ## Using SWIG SWIG is a tool that helps a variety of scripting and programming languages call C and C++ code. SWIG makes creation of C language modules much more straightforward. To use SWIG, you need to get it up and running first. You can install it on an Ubuntu system as follows: `$ sudo apt-get install swig`\ `$ sudo apt-get install python-dev` To get SWIG for Windows, you can use binaries available from the SWIG download page. Once you have SWIG, you need to create the module source file and the module interface file: hellomodule.c: ``` c #include <stdio.h> void say_hello(const char* name) { printf("Hello %s!\n", name); } ``` hello.i: ``` c %module hello extern void say_hello(const char* name); ``` Then we let SWIG do its work: `swig -python hello.i` The above produces files hello.py and hello_wrap.c. The next step is compiling; substitute /usr/include/python2.4/ with the correct path to Python.h for your setup: `gcc -fpic -c hellomodule.c hello_wrap.c -I/usr/include/python2.4/` As the last step, we do the linking: `gcc -shared hellomodule.o hello_wrap.o -o _hello.so -lpython` The module is used as follows: `>>> import hello`\ `>>> hello.say_hello("World")`\ `Hello World!` ## External links - Extending and Embedding the Python Interpreter, python.org - Python/C API Reference Manual, python.org - SWIG, swig.org - Download SWIG, swig.org
# Python Programming/Extending with C++ There are different ways to extend Python with C and C++ code: - In plain C, using Python.h - Using Swig - Using Boost.Python, optionally with Py++ preprocessing - Using pybind11 - Using ../Cython/. This page describes Boost.Python. Before the emergence of Cython, it was the most comfortable way of writing C++ extension modules. Boost.Python comes bundled with the Boost C++ Libraries. To install it on an Ubuntu system, you might need to run the following commands `$ sudo apt-get install libboost-python-dev `\ `$ sudo apt-get install python-dev` ## A Hello World Example ### The C++ source code (hellomodule.cpp) ``` cpp #include <iostream> using namespace std; void say_hello(const char* name) { cout << "Hello " << name << "!\n"; } #include <boost/python/module.hpp> #include <boost/python/def.hpp> using namespace boost::python; BOOST_PYTHON_MODULE(hello) { def("say_hello", say_hello); } ``` ### setup.py ``` python #!/usr/bin/env python from distutils.core import setup from distutils.extension import Extension setup(name="PackageName", ext_modules=[ Extension("hello", ["hellomodule.cpp"], libraries = ["boost_python"]) ]) ``` Now we can build our module with `python setup.py build` The module \`hello.so\` will end up in e.g \`build/lib.linux-i686-2.4\`. ### Using the extension module Change to the subdirectory where the file \`hello.so\` resides. In an interactive python session you can use the module as follows. `>>> import hello`\ `>>> hello.say_hello("World")`\ `Hello World!` ## An example with CGAL Some, but not all, functions of the CGAL library already have Python bindings. Here an example is provided for a case without such a binding and how it might be implemented. The example is taken from the CGAL Documentation. ``` Cpp // test.cpp using namespace std; /* PYTHON */ #include <boost/python.hpp> #include <boost/python/module.hpp> #include <boost/python/def.hpp> namespace python = boost::python; /* CGAL */ #include <CGAL/Cartesian.h> #include <CGAL/Range_segment_tree_traits.h> #include <CGAL/Range_tree_k.h> typedef CGAL::Cartesian<double> K; typedef CGAL::Range_tree_map_traits_2<K, char> Traits; typedef CGAL::Range_tree_2<Traits> Range_tree_2_type; typedef Traits::Key Key; typedef Traits::Interval Interval; Range_tree_2_type *Range_tree_2 = new Range_tree_2_type; void create_tree() { typedef Traits::Key Key; typedef Traits::Interval Interval; std::vector<Key> InputList, OutputList; InputList.push_back(Key(K::Point_2(8,5.1), 'a')); InputList.push_back(Key(K::Point_2(1.0,1.1), 'b')); InputList.push_back(Key(K::Point_2(3,2.1), 'c')); Range_tree_2->make_tree(InputList.begin(),InputList.end()); Interval win(Interval(K::Point_2(1,2.1),K::Point_2(8.1,8.2))); std::cout << "\n Window Query:\n"; Range_tree_2->window_query(win, std::back_inserter(OutputList)); std::vector<Key>::iterator current=OutputList.begin(); while(current!=OutputList.end()){ std::cout << " " << (*current).first.x() << "," << (*current).first.y() << ":" << (*current).second << std::endl; current++; } std::cout << "\n Done\n"; } void initcreate_tree() {;} using namespace boost::python; BOOST_PYTHON_MODULE(test) { def("create_tree", create_tree, ""); } ``` ``` Cpp // setup.py #!/usr/bin/env python from distutils.core import setup from distutils.extension import Extension setup(name="PackageName", ext_modules=[ Extension("test", ["test.cpp"], libraries = ["boost_python"]) ]) ``` We then compile and run the module as follows: `$ python setup.py build`\ `$ cd build/lib*`\ `$ python`\ `>>> import test`\ `>>> test.create_tree()`\ `Window Query:`\ ` 3,2.1:c`\ ` 8,5.1:a`\ `Done`\ `>>>` ## Handling Python objects and errors One can also handle more complex data, e.g. Python objects like lists. The attributes are accessed with the extract function executed on the objects \"attr\" function output. We can also throw errors by telling the library that an error has occurred and returning. In the following case, we have written a C++ function called \"afunction\" which we want to call. The function takes an integer N and a vector of length N as input, we have to convert the python list to a vector of strings before calling the function. ``` Cpp #include <vector> using namespace std; void _afunction_wrapper(int N, boost::python::list mapping) { int mapping_length = boost::python::extract<int>(mapping.attr("__len__")()); //Do Error checking, the mapping needs to be at least as long as N if (mapping_length < N) { PyErr_SetString(PyExc_ValueError, "The string mapping must be at least of length N"); boost::python::throw_error_already_set(); return; } vector<string> mystrings(mapping_length); for (int i=0; i<mapping_length; i++) { mystrings[i] = boost::python::extract<char const *>(mapping[i]); } //now call our C++ function _afunction(N, mystrings); } using namespace boost::python; BOOST_PYTHON_MODULE(c_afunction) { def("afunction", _afunction_wrapper); } ``` ## External links - Boost.Python, boost.org - pybind11, pypi.org
# Python Programming/Extending with Pyrex Pyrex is a compiler of Python-like source code to the C language, intended to make it relatively easy for Python programmers to write fast Python extension modules without having to learn the C language. ../Cython/ is an actively developed derivative of Pyrex. Pyrex is no longer actively developed, the last stable release being from 2010. Links: - Pyrex - a Language for Writing Python Extension Modules, cosc.canterbury.ac.nz - Pyrex (programming language) "wikilink"), en.wikipedia.org
# Python Programming/Extending with ctypes ctypes1 is a foreign function interface module for Python (included with Python 2.5 and above), which allows you to load in dynamic libraries and call C functions. This is not technically extending Python, but it serves one of the primary reasons for extending Python: to interface with external C code. ## Basics A library is loaded using the `ctypes.CDLL` function. After you load the library, the functions inside the library are already usable as regular Python calls. For example, if we wanted to forego the standard Python print statement and use the standard C library function, `printf`, you would use this: ``` python from ctypes import * libName = 'libc.so' # If you're on a UNIX-based system libName = 'msvcrt.dll' # If you're on Windows libc = CDLL(libName) libc.printf("Hello, World!\n") ``` Of course, you must use the libName line that matches your operating system, and delete the other. If all goes well, you should see the infamous Hello World string at your console. ## Getting Return Values ctypes assumes, by default, that any given function\'s return type is a signed integer of native size. Sometimes you don\'t want the function to return anything, and other times, you want the function to return other types. Every ctypes function has an attribute called `restype`. When you assign a ctypes class to `restype`, it automatically casts the function\'s return value to that type. ### Common Types ctypes name C type Python type Notes ------------- -------------------- ------------- ----------------- None void None the None object c_bool C99 \_Bool bool c_byte signed char int c_char signed char str length of one c_char_p char \* str c_double double float c_float float float c_int signed int int c_long signed long long c_longlong signed long long long c_short signed short long c_ubyte unsigned char int c_uint unsigned int int c_ulong unsigned long long c_ulonglong unsigned long long long c_ushort unsigned short int c_void_p void \* int c_wchar wchar_t unicode length of one c_wchar_p wchar_t \* unicode
# Python Programming/Extending with Perl It is possible to call Perl functions and modules in Python. One way to do that is the PyPerl Module. It is not developed actively any more and for it to work in newer versions, one has to use this version and apply the patches. ``` python import perl perl.eval( "use lib './' ") perl.require( 'Module::ModuleName' ) obj = perl.callm("new", 'Module::ModuleName' ) obj[ '_attr1' ] = 9 obj[ '_attr2' ] = 42 obj.fxn1() ``` It is thus possible to handle Perl objects, change their attributes and call their methods. ## See also - <http://wiki.python.org/moin/IntegratingPythonWithOtherLanguages#Perl>
# Python Programming/Popularity The popularity of a programming language is one factor that people consider when choosing a language for a task or a project. Beware that even a good programming language can be unpopular. The popularity of Python can be determined with the help of various indices, which are not identical to the real popularity in the real world. While the statistics are linked from the external links section below, it is advisable that you use them with a grain of salt. Python is the main scripting language used by Google, per Google Python Style Guide. Python is embedded in various software packages to support their extensibility and automation, including Gimp and Inkscape; see also Wikipedia\'s W:Python (programming_language)#Uses#Uses "wikilink") and W:List of Python software#Embedded as a scripting language. ## External links - Tiobe index, tiobe.com - PYPL PopularitY of Programming Languages, pypl.github.io - RedMonk rankings, redmonk.com, combines Stack Overflow data with GitHub data - The 2015 Top Ten Programming Languages, spectrum.ieee.org, 2015 - W:Measuring programming language popularity - W:Programming languages used in most popular websites - W:Python (programming_language) "wikilink") - W:List of Python software - Google Python Style Guide, google.github.io - Python Success Stories, python.org - Organizations using Python, wiki.python.org
# Python Programming/Links Web resources: Python.org: - The Python.org documents section - Current Python 2.x documentation - Current Python 3.x documentation - Python Wiki at python.org - Python IDEs Online books: - Dive into Python by Mark Pilgrim, a free book published under GNU Free Documentation License, with around 100 000 words - Text Processing in Python, a book by David Mertz, published by Addison Wesley - Introduction to Python Programming with NCLab, a book available as a single PDF, with around 44 000 words - Invent Your Own Computer Games with Python - A complete eBook for total beginners available for free under a Creative Commons license. - Making Games with Python & Pygame - A Creative Commons-licensed book that covers the Pygame library. - Hacking Secret Ciphers with Python - A Creative Commons-licensed book for complete beginners with a focus on cryptography. Various: - Python Programming Tutorials \-- a list of Python tutorials - ActiveState Python Cookbook \-- a collection of Python recipes - Dev Shed\'s Python Tutorials \-- a collection of Python articles - Python Tutorials at awaretek.com - Python 101 \-- Introduction to Python by Dave Kuhlman, around 9000 words - Category:Python, rosettacode.org
# Python Programming/Library Modules This is a list of python modules in the standard library as of Python 3.6. - \_\_future\_\_: Future statement definitions - \_\_main\_\_: The environment where the top-level script is run. - \_dummy_thread: Drop-in replacement for the \_thread module. - \_thread: Low-level threading API. - abc: Abstract base classes according to PEP 3119. - aifc: Read and write audio files in AIFF or AIFC format. - argparse: Command-line option and argument parsing library. - array: Space efficient arrays of uniformly typed numeric values. - ast: Abstract Syntax Tree classes and manipulation. - asynchat: Support for asynchronous command/response protocols. - asyncio: Asynchronous I/O, event loop, coroutines and tasks. - asyncore: A base class for developing asynchronous socket handling services. - atexit: Register and execute cleanup functions. - audioop: Manipulate raw audio data. - base64: RFC 3548: Base16, Base32, Base64 Data Encodings; Base85 and Ascii85 - bdb: Debugger framework. - binascii: Tools for converting between binary and various ASCII-encoded binary representations. - binhex: Encode and decode files in binhex4 format. - bisect: Array bisection algorithms for binary searching. - builtins: The module that provides the built-in namespace. - bz2: Interfaces for bzip2 compression and decompression. - calendar: Functions for working with calendars, including some emulation of the Unix cal program. - cgi: Helpers for running Python scripts via the Common Gateway Interface. - cgitb: Configurable traceback handler for CGI scripts. - chunk: Module to read IFF chunks. - cmath: Mathematical functions for complex numbers. - cmd: Build line-oriented command interpreters. - code: Facilities to implement read-eval-print loops. - codecs: Encode and decode data and streams. - codeop: Compile (possibly incomplete) Python code. - collections: Container datatypes - colorsys: Conversion functions between RGB and other color systems. - compileall: Tools for byte-compiling all Python source files in a directory tree. - concurrent: - configparser: Configuration file parser. - contextlib: Utilities for with-statement contexts. - copy: Shallow and deep copy operations. - copyreg: Register pickle support functions. - cProfile - crypt (Unix): The crypt() function used to check Unix passwords. - csv: Write and read tabular data to and from delimited files. - ctypes: A foreign function library for Python. - curses (Unix): An interface to the curses library, providing portable terminal handling. - datetime: Basic date and time types. - dbm: Interfaces to various Unix \"database\" formats. - decimal: Implementation of the General Decimal Arithmetic Specification. - difflib: Helpers for computing differences between objects. - dis: Disassembler for Python bytecode. - distutils: Support for building and installing Python modules into an existing Python installation. - doctest: Test pieces of code within docstrings. - dummy_threading: Drop-in replacement for the threading module. - email: Package supporting the parsing, manipulating, and generating email messages. - encodings: - ensurepip: Bootstrapping the \"pip\" installer into an existing Python installation or virtual environment. - enum: Implementation of an enumeration class. - errno: Standard errno system symbols. - faulthandler: Dump the Python traceback. - fcntl (Unix): The fcntl() and ioctl() system calls. - filecmp: Compare files efficiently. - fileinput: Loop over standard input or a list of files. - fnmatch: Unix shell style filename pattern matching. - formatter: Deprecated: Generic output formatter and device interface. - fpectl (Unix): Provide control for floating point exception handling. - fractions: Rational numbers. - ftplib: FTP protocol client (requires sockets). - functools: Higher-order functions and operations on callable objects. - gc: Interface to the cycle-detecting garbage collector. - getopt: Portable parser for command line options; support both short and long option names. - getpass: Portable reading of passwords and retrieval of the userid. - gettext: Multilingual internationalization services. - glob: Unix shell style pathname pattern expansion. - grp (Unix): The group database (getgrnam() and friends). - gzip: Interfaces for gzip compression and decompression using file objects. - hashlib: Secure hash and message digest algorithms. - heapq: Heap queue algorithm (a.k.a. priority queue). - hmac: Keyed-Hashing for Message Authentication (HMAC) implementation - html: Helpers for manipulating HTML. - http: HTTP status codes and messages - imaplib: IMAP4 protocol client (requires sockets). - imghdr: Determine the type of image contained in a file or byte stream. - imp: Deprecated: Access the implementation of the import statement. - importlib: The implementation of the import machinery. - inspect: Extract information and source code from live objects. - io: Core tools for working with streams. - ipaddress: IPv4/IPv6 manipulation library. - itertools: Functions creating iterators for efficient looping. - json: Encode and decode the JSON format. - keyword: Test whether a string is a keyword in Python. - lib2to3: the 2to3 library - linecache: This module provides random access to individual lines from text files. - locale: Internationalization services. - logging: Flexible event logging system for applications. - lzma: A Python wrapper for the liblzma compression library. - macpath: Mac OS 9 path manipulation functions. - mailbox: Manipulate mailboxes in various formats - mailcap: Mailcap file handling. - marshal: Convert Python objects to streams of bytes and back (with different constraints). - math: Mathematical functions (sin() etc.). - mimetypes: Mapping of filename extensions to MIME types. - mmap: Interface to memory-mapped files for Unix and Windows. - modulefinder: Find modules used by a script. - msilib (Windows): Creation of Microsoft Installer files, and CAB files. - msvcrt (Windows): Miscellaneous useful routines from the MS VC++ runtime. - multiprocessing: Process-based parallelism. - netrc: Loading of .netrc files. - nis (Unix): Interface to Sun\'s NIS (Yellow Pages) library. - nntplib: NNTP protocol client (requires sockets). - numbers: Numeric abstract base classes (Complex, Real, Integral, etc.). - operator: Functions corresponding to the standard operators. - optparse: Deprecated: Command-line option parsing library. - os: Miscellaneous operating system interfaces. - ossaudiodev (Linux, FreeBSD): Access to OSS-compatible audio devices. - parser: Access parse trees for Python source code. - pathlib: Object-oriented filesystem paths - pdb: The Python debugger for interactive interpreters. - pickle: Convert Python objects to streams of bytes and back. - pickletools: Contains extensive comments about the pickle protocols and pickle-machine opcodes, as well as some useful functions. - pipes (Unix): A Python interface to Unix shell pipelines. - pkgutil: Utilities for the import system. - platform: Retrieves as much platform identifying data as possible. - plistlib: Generate and parse Mac OS X plist files. - poplib: POP3 protocol client (requires sockets). - posix (Unix): The most common POSIX system calls (normally used via module os). - pprint: Data pretty printer. - profile: Python source profiler. - pstats: Statistics object for use with the profiler. - pty (Linux): Pseudo-Terminal Handling for Linux. - pwd (Unix): The password database (getpwnam() and friends). - py_compile: Generate byte-code files from Python source files. - pyclbr: Supports information extraction for a Python class browser. - pydoc: Documentation generator and online help system. - queue: A synchronized queue class. - quopri: Encode and decode files using the MIME quoted-printable encoding. - random: Generate pseudo-random numbers with various common distributions. - re: Regular expression operations. - readline (Unix): GNU readline support for Python. - reprlib: Alternate repr() implementation with size limits. - resource (Unix): An interface to provide resource usage information on the current process. - rlcompleter: Python identifier completion, suitable for the GNU readline library. - runpy: Locate and run Python modules without importing them first. - sched: General purpose event scheduler. - secrets: Generate secure random numbers for managing secrets. - select: Wait for I/O completion on multiple streams. - selectors: High-level I/O multiplexing. - shelve: Python object persistence. - shlex: Simple lexical analysis for Unix shell-like languages. - shutil: High-level file operations, including copying. - signal: Set handlers for asynchronous events. - site: Module responsible for site-specific configuration. - smtpd: A SMTP server implementation in Python. - smtplib: SMTP protocol client (requires sockets). - sndhdr: Determine type of a sound file. - socket: Low-level networking interface. - socketserver: A framework for network servers. - spwd (Unix): The shadow password database (getspnam() and friends). - sqlite3: A DB-API 2.0 implementation using SQLite 3.x. - ssl: TLS/SSL wrapper for socket objects - stat: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat(). - statistics: mathematical statistics functions - string: Common string operations. - stringprep: String preparation, as per RFC 3453 - struct: Interpret bytes as packed binary data. - subprocess: Subprocess management. - sunau: Provide an interface to the Sun AU sound format. - symbol: Constants representing internal nodes of the parse tree. - symtable: Interface to the compiler\'s internal symbol tables. - sys: Access system-specific parameters and functions. - sysconfig: Python\'s configuration information - syslog (Unix): An interface to the Unix syslog library routines. - tabnanny: Tool for detecting white space related problems in Python source files in a directory tree. - tarfile: Read and write tar-format archive files. - telnetlib: Telnet client class. - tempfile: Generate temporary files and directories. - termios (Unix): POSIX style tty control. - test: Regression tests package containing the testing suite for Python. - textwrap: Text wrapping and filling - threading: Thread-based parallelism. - time: Time access and conversions. - timeit: Measure the execution time of small code snippets. - tkinter: Interface to Tcl/Tk for graphical user interfaces - token: Constants representing terminal nodes of the parse tree. - tokenize: Lexical scanner for Python source code. - trace: Trace or track Python statement execution. - traceback: Print or retrieve a stack traceback. - tracemalloc: Trace memory allocations. - tty (Unix): Utility functions that perform common terminal control operations. - turtle: An educational framework for simple graphics applications - turtledemo: A viewer for example turtle scripts - types: Names for built-in types. - typing: Support for type hints (see PEP 484). - unicodedata: Access the Unicode Database. - unittest: Unit testing framework for Python. - urllib: - uu: Encode and decode files in uuencode format. - uuid: UUID objects (universally unique identifiers) according to RFC 4122 - venv: Creation of virtual environments. - warnings: Issue warning messages and control their disposition. - wave: Provide an interface to the WAV sound format. - weakref: Support for weak references and weak dictionaries. - webbrowser: Easy-to-use controller for Web browsers. - winreg (Windows): Routines and objects for manipulating the Windows registry. - winsound (Windows): Access to the sound-playing machinery for Windows. - wsgiref: WSGI Utilities and Reference Implementation. - xdrlib: Encoders and decoders for the External Data Representation (XDR). - xml: Package containing XML processing modules - zipapp: Manage executable python zip archives - zipfile: Read and write ZIP-format archive files. - zipimport: support for importing Python modules from ZIP archives. - zlib: Low-level interface to compression and decompression routines compatible with gzip.
# Python Programming/Naming conventions There are various naming conventions used in Python programs. PEP 0008 specifies naming conventions for class names (e.g. GenericTree), package and module names (e.g. generictree and generic_tree), function and variable names (storestate or store_state; mixedCase is dispreferred), and more. Google Python Style Guide follows similar naming conventions. The above stands in contrast to Java naming convention (e.g. storeState for method names) and C# naming convention (e.g. StoreState for method names). In Python 2, the standard library contains multiple deviations from PEP 0008. For instance, Tkinter module is spelled as Tkinter with capital T; this was renamed to tkinter in Python 3. ## External links - Naming Conventions in PEP 0008: Style Guide for Python Code, python.org - Naming in Google Python Style Guide, google.github.io - pycodestyle - Python style guide checker, pypi.python.org - Modules to Rename in PEP 3108, python.org - W:Naming convention (programming) "wikilink")
# Ada Programming/All Chapters ------------------------------------------------------------------------ !Ada. Time-tested, safe and secure.{width="300"} \_\_NOEDITSECTION\_\_ \_\_TOC\_\_ # Preface # Basic Ada # Installing # Building # Control Statements # Type System # Integer types # Unsigned integer types # Enumerations # Floating point types # Fixed point types # Arrays # Records # Access types # Limited types # Strings # Subprograms # Packages # Input Output # Exceptions # Generics # Tasking # Object Orientation # New in Ada 2005 # Containers # Interfacing # Coding Standards # Tips # Common Errors # Algorithms # Chapter 1 # Chapter 6 # Knuth-Morris-Pratt pattern matcher # Binary Search # Function overloading # Mathematical calculations # Statements # Variables # Lexical elements # Keywords # Delimiters # Operators # Attributes # Pragmas # Libraries # Libraries: Standard # Libraries: Ada # Libraries: Interfaces # Libraries: System # Libraries: GNAT # Libraries: Multi-Purpose # Libraries: Container # Libraries: GUI # Libraries: Distributed Systems # Libraries: Databases # Libraries: Web # Libraries: Input Output # Platform Support # Platform: Linux # Platform: Windows # Platform: Virtual Machines # Portals # Tutorials # Web 2.0 All Chapters All Chapters
# Ada Programming/Installing Ada compilers are available from several vendors, on a variety of host and target platforms. The Ada Resource Association maintains a list of available compilers. Below is an alphabetical list of available compilers with additional comments. ## AdaMagic from SofCheck SofCheck used to produce an Ada 95 front-end that can be plugged into a code generating back-end to produce a full compiler. This front-end is offered for licensing to compiler vendors. Based on this front-end, SofCheck used to offer: - AdaMagic, an Ada-to-C/C++ translator - AppletMagic, an Ada-to-Java bytecode compiler SofCheck has merged with AdaCore under the AdaCore name, leaving no visible trace of AdaMagic offering on AdaCore website. However, MapuSoft is now licensed to resell AdaMagic. They renamed it to \"Ada-to-C/C++ changer\". New name sounds like fake. Almost no Ada developer heard of MapuSoft. MapuSoft is never seen making Ada libraries, commercial or FLOSS. They are never seen at Ada conferences. Yet this is a real stuff, a validated Ada compiler that knows lots of tricks required to work on top of C/C++ compilers. E.g. it contains a proven knowledge of handling integer overflow with a special \"-1\" case. Thanks to MapuSoft, AdaMagic really became available to developers. Get AppCOE, but not Win64 one, install it. In the MapuSoft/AppCOE_x32/Tools/Ada there will be AdaMagic. AdaMagic is known to support Win64, but AppCOE for Win64 is known to contain no AdaMagic at all. Using AdaMagic from command line is badly supported in AppCOE, but possible. Set up ADA_MAGIC environment variable, edit Tools/Ada/{linux\|windows}/SITE/rts_path to point to real path, edit SITE/config to get rid of unsupported C compiler keys, and compile via e.g. ``` bash adareg -key=`test_key | sed -e '/md5/!d;s/md5 = //'` Hello_World.adb adabgen -key=`test_key | sed -e '/md5/!d;s/md5 = //'` Hello_World ``` Commercial; proprietary. ## AdaMULTI from Green Hills Software Green Hills Software sells development environments for multiple languages and multiple targets (including DSPs), primarily to embedded software developers. Languages supported Ada 83, Ada 95, C, C++, Fortran ---------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- License for the run-time library Proprietary, royalty free. Native platforms GNU/Linux on i386, Microsoft Windows on i386, and Solaris on SPARC Cross platforms INTEGRITY, INTEGRITY-178B and velOSity from Green Hills; VxWorks from Wind River; several bare board targets, including x86, PowerPC, ARM, MIPS and ColdFire/68k. Safety-critical GMART and GSTART run-time libraries certified to DO-178B level A. Available from <http://www.ghs.com/> Support Commercial Add-ons included IDE, debugger, TimeMachine, integration with various version control systems, source browsers, other utilities GHS claims to make great efforts to ensure that their compilers produce the most efficient code and often cites the EEMBC benchmark results as evidence, since many of the results published by chip manufacturers use GHS compilers to show their silicon in the best light, although these benchmarks are not Ada specific. GHS has no publicly announced plans to support the two most recent Ada standards (2005 and 2012) but they do continue to actively market and develop their existing Ada products. ## DEC Ada from HP DEC Ada was an Ada 83 compiler for OpenVMS. While "DEC Ada" is probably the name most users know, the compiler has also been called "HP Ada", \"VAX Ada\", and \"Compaq Ada\". - Ada for OpenVMS Alpha Installation Guide (PDF) - Ada for OpenVMS VAX Installation Guide (PDF) ## GNAT, the GNU Ada Compiler from AdaCore and the Free Software Foundation GNAT is the free GNU Ada compiler, which is part of the GNU Compiler Collection. It is the only Ada compiler that supports all of the optional annexes of the language standard. The original authors formed the company AdaCore to offer professional support, consulting, training and custom development services. It is thus possible to obtain GNAT from many different sources, detailed below. GNAT is always licensed under the terms of the GNU General Public License. However, the run-time library uses either the GPL, or the GNAT Modified GPL, depending on where you obtain it. Several optional add-ons are available from various places: - ASIS, the Ada Semantic Interface Specification, is a library that allows Ada programs to examine and manipulate other Ada programs. - FLORIST is a library that provides a POSIX programming interface to the operating system. - GDB, the GNU Debugger, with Ada extensions. - GLADE implements Annex E, the Distributed Systems Annex. With it, one can write distributed programs in Ada, where partitions of the program running on different computers communicate over the network with one another and with shared objects. - GPS, the GNAT Programming Studio, is a full-featured integrated development environment, written in Ada. It allows you to code in Ada, C and C++. Many Free Software libraries are also available. ### GNAT GPL (or Community) Edition As of may 2022, AdaCore no longer supports GNAT GPL. It has been replaced with Alire, a package manager for Ada sources, which also provides toolchains. The following is no longer relevant for post May 2022 users. This is a source and binary release from AdaCore, intended for use by Free Software developers only. If you want to distribute your binary programs linked with the GPL run-time library, then you must do so under terms compatible with the GNU General Public License. As of GNAT GPL Edition 2013: Languages supported Ada 83, Ada 95, Ada 2005, Ada 2012, C, C++ ---------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- License for the run-time library pure GPL Native platforms GNU/Linux on x86_64; Microsoft Windows on i386; ; Mac OS X (Darwin, x86_64). Earlier releases have supported Solaris on SPARC, GNU/Linux on i386, Microsoft .NET on i386 Cross platforms AVR, hosted on Windows; Java VM, hosted on Windows; Mindstorms NXT, hosted on Windows; ARM, hosted on Windows and Linux; Compiler back-end GCC 4.9 Available from <https://www.adacore.com/download> Support None Add-ons included GDB, GPS in source and binary form; many more in source-only form. ### GNAT Modified GPL releases With these releases of GNAT, you can distribute your programs in binary form under licensing terms of your own choosing; you are not bound by the GPL. #### GNAT 3.15p This is the last public release of GNAT from AdaCore that uses the GNAT Modified General Public License. GNAT 3.15p has passed the Ada Conformity Assessment Test Suite (ACATS). It was released in October 2002. The binary distribution from AdaCore also contains an Ada-aware version of the GNU Debugger (GDB), and a graphical front-end to GDB called the GNU Visual Debugger (GVD). Languages supported Ada 83, Ada 95, C ---------------------------------- ---------------------------------------------------------------------------------------------------------------------------------- License for the run-time library GNAT-modified GPL Native platforms GNU/Linux on i386 (with glibc 2.1 or later), Microsoft Windows on i386, OS/2 2.0 or later on i386, Solaris 2.5 or later on SPARC Cross platforms none Compiler back-end GCC 2.8.1 Available from <ftp://ftp.cs.kuleuven.ac.be/pub/Ada-Belgium/mirrors/gnu-ada/3.15p/> Support None Add-ons included ASIS, Florist, GLADE, GDB, Gnatwin (on Windows only), GtkAda 1.2, GVD #### GNAT Pro GNAT Pro is the professional version of GNAT, offered as a subscription package by AdaCore. The package also includes professional consulting, training and maintenance services. AdaCore can provide custom versions of the compiler for native or cross development. For more information, see <http://www.adacore.com/>. Languages supported Ada 83, Ada 95, Ada 2005, Ada 2012, C, and optionally C++ ---------------------------------- -------------------------------------------------------------------------------------------------------- License for the run-time library GNAT-modified GPL Native platforms many, see <http://www.adacore.com/home/products/gnatpro/supported_platforms/> Cross platforms many, see <http://www.adacore.com/home/products/gnatpro/supported_platforms/>; even more on request Compiler back-end GCC 4.3 Available from <http://www.adacore.com/> by subscription (commercial) Support Commercial; customer-only bug database Add-ons included ASIS, Florist, GDB, GLADE, GPS, GtkAda, XML/Ada, and many more in source and, on request, binary form. #### GCC GNAT has been part of the Free Software Foundation\'s GCC since October 2001. The Free Software Foundation does not distribute binaries, only sources. Its licensing of the run-time library for Ada (and other languages) allows the development of proprietary software without necessarily imposing the terms of the GPL. Most GNU/Linux distributions and several distributions for other platforms include prebuilt binaries; see below. For technical reasons, we recommend against using the Ada compilers included in GCC 3.1, 3.2, 3.3 and 4.0. Instead, we recommend using GCC 3.4, 4.1 or later, or one of the releases from AdaCore (3.15p, GPL Edition or Pro). Since October 2003, AdaCore merge most of their changes from GNAT Pro into GCC during Stage 1; this happens once for each major release. Since GCC 3.4, AdaCore has gradually added support for revised language standards, first Ada 2005 and now Ada 2012. GCC version 4.4 switched to version 3 of the GNU General Public License and grants a Runtime Library Exception similar in spirit to the GNAT Modified General Public License used in all previous versions. This Runtime Library Exception applies to run-time libraries for all languages, not just Ada. As of GCC 4.7, released on 2012-03-22: Languages supported Ada 83, Ada 95, Ada 2005, parts of Ada 2012, C, C++, Fortran 95, Java, Objective-C, Objective-C++ (and others) ---------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------- License for the run-time library GPL version 3 with Runtime Library Exception Native platforms none (source only) Cross platforms none (source only) Compiler back-end GCC 4.7 Available from <http://gcc.gnu.org/> in source only form. Support Volunteer; public bug database Add-ons included none ### The GNU Ada Project The GNU Ada Project provides source and binary packages of various GNAT versions for several operating systems, and, importantly, the scripts used to create the packages. This may be helpful if you plan to port the compiler to another platform or create a cross-compiler; there are instructions for building your own GNAT compiler for GNU/Linux and Mac OS X users. Both GPL and GMGPL or GCC Runtime Library Exception versions of GNAT are available. Languages supported Ada 83, Ada 95, Ada 2005, C. `<small>`{=html}(Some distributions also support Ada 2012, Fortran 90, Java, Objective C and Objective C++)`</small>`{=html} ---------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------- License for the run-time library pure, GNAT-modified GPL, or GCC Runtime Library Exception Native platforms Fedora Core 4 and 5, MS-DOS, OS/2, Solaris 10, SuSE 10, Mac OS X, `<small>`{=html}(more?)`</small>`{=html} Cross platforms none Compiler back-end GCC 2.8.1, 3.4, 4.0, 4.1, 4.2, 4.3, 4.4, 4.5, 4.6 `<small>`{=html}(various binary packages)`</small>`{=html} Available from Sourceforge Support Volunteer; public bug database Add-ons included AdaBrowse, ASIS, Booch Components, Charles, GPS, GtkAda `<small>`{=html}(more?)`</small>`{=html} ### A# (A-Sharp, a.k.a. Ada for .NET) This compiler is historical as it has now been merged into GNAT GPL Edition and GNAT Pro. A# is a port of Ada to the .NET Platform. A# was originally developed at the Department of Computer Science at the United States Air Force Academy which distribute A# as a service to the Ada community under the terms of the GNU general public license. A# integrates well with Microsoft Visual Studio 2005, AdaGIDE and the RAPID open-source GUI Design tool. As of 2006-06-06: Languages supported Ada 83, Ada 95, C ---------------------------------- ------------------------------------------- License for the run-time library pure GPL Native platforms Microsoft .NET Cross platforms none Compiler back-end GCC 3.4 (GNAT GPL 2006 Edition?) Available from <http://sourceforge.net/projects/asharp/> Support None (but see GNAT Pro) Add-ons included none. ### GNAT for AVR microcontrollers Rolf Ebert and others provide a version of GNAT configured as a cross-compiler to various AVR microcontrollers, as well as an experimental Ada run-time library suitable for use on the microcontrollers. As of Version 1.1.0 (2010-02-25): Languages supported Ada 83, Ada 95, Ada 2005, C ---------------------------------- -------------------------------------------------------------- License for the run-time library GNAT-Modified GPL Host platforms GNU/Linux and Microsoft Windows on i386 Target platforms Various AVR 8-bit microcontrollers Compiler back-end GCC 4.7 Available from <http://avr-ada.sourceforge.net/> Support Volunteer; public bug database Add-ons included partial Ada run time system, AVR peripherals support library ### GNAT for LEON The Real-Time Research Group of the Technical University of Madrid (UPM, *Universidad Politécnica de Madrid*) wrote a Ravenscar-compliant real-time kernel for execution on LEON processors and a modified run-time library. They also provide a GNAT cross-compiler. As of version 2.0.1: Languages supported Ada 83, Ada 95, Ada 2005, C ---------------------------------- ---------------------------------------------------------- License for the run-time library pure GPL Native platforms none Cross platforms GNU/Linux on i686 to LEON2 bare boards Compiler back-end GCC 4.1 (GNAT GPL 2007 Edition) Available from <http://www.dit.upm.es/ork/> Support ? Add-ons included OpenRavenscar real-time kernel; minimal run-time library ### GNAT for Macintosh (Mac OS X) GNAT for Macintosh provides both FSF (GMGPL) and AdaCore (GPL) versions of GNAT with Xcode and Carbon "wikilink") integration and bindings. Note that this site was last updated for GCC 4.3 and Mac OS X Leopard (both PowerPC and Intel-based). Aside from the work on integration with Apple's Carbon graphical user interface and with Xcode 3.1 it may be preferable to see above. There is also support at MacPorts; the last update (at 25 Nov 2011) was for GCC 4.4.2. ### Prebuilt packages as part of larger distributions Many distributions contain prebuilt binaries of GCC or various public releases of GNAT from AdaCore. Quality varies widely between distributions. The list of distributions below is in alphabetical oder. *(Please keep it that way.)* #### AIDE (for Microsoft Windows) AIDE --- Ada Instant Development Environment is a complete one-click, just-works Ada distribution for Windows, consisting of GNAT, comprehensive documentation, tools and libraries. All are precompiled, and source code is also available. The installation procedure is particularly easy (just unzip to default c:\\aide and run). AIDE is intended for beginners and teachers, but can also be used by advanced users. Languages supported Ada 83, Ada 95, C ---------------------------------- ------------------------------------------- License for the run-time library GNAT-modified GPL Native platforms Microsoft Windows on i386 Cross platforms none Compiler back-end GCC 2.8.1 Available from <https://stef.genesix.org/aide/aide.html> Support stef@genesix.org Add-ons included ASIS, GDB, GPS, GtkAda, Texinfo (more?) #### Cygwin (for Microsoft Windows) Cygwin, the Linux-like environment for Windows, also contains a version of the GNAT compiler. The Cygwin version of GNAT is older than the MinGW version and does not support DLLs and Multi-Threading `<small>`{=html}(as of 11.2004)`</small>`{=html}. #### Debian (GNU/Linux and GNU/kFreeBSD) There is a Debian Policy for Ada which tries to make Debian the best Ada development *and deployment* platform. The development platform includes the compiler and many libraries, pre-packaged and integrated so as to be easy to use in any program. The deployment platform is the renowned *stable* distribution, which is suitable for mission-critical workloads and enjoys long life cycles, typically 3 to 4 years. Because Debian is a binary distribution, it is possible to deploy non-free, binary-only programs on it while enjoying all the benefits of a stable platform. Compiler choices are conservative for this reason, and the Policy mandates that all Ada programs and libraries be compiled with the same version of GNAT. This makes it possible to use all libraries in the same program. Debian separates run-time libraries from development packages, so that end users do not have to install the development system just to run a program. The GNU Ada compiler can be installed on a Debian system with this command: `aptitude install gnat` This will also give you a list of related packages, which are likely to be useful for an Ada programmer. Debian is unique in that it also allows programmers to use some of GNAT\'s internal components by means of two libraries: - libgnatvsn (licensed under GNAT-Modified GPL) and - libgnatprj (the project manager, licensed under pure GPL). Debian packages make use of these libraries. In the table below, the information about the future Debian 8.0 *Jessie* is accurate as of October 2014 and will change.   3.1 *Sarge* 4.0 *Etch* 5.0 *Lenny* 6.0 *Squeeze* 7.0 *Wheezy* 8.0 *Jessie* ---------------------------------- -------------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------ ---------------- ------------------------- ---------------- ----------------- Release date June 2005 April 2007 February 2009 February 2011 May 2013 April 2015 Languages supported Ada 83, Ada 95, C +Ada 2005, parts of Ada 2012, C, C++, Fortran 95, Java, Objective-C, Objective-C++ +Ada 2012 License for the run-time library GNAT-modified GPL (both ZCX and SJLJ versions starting from 5.0 *Lenny*) GPL version 3 with Run-time library exception Native platforms: 3.1 *Sarge* 4.0 *Etch* 5.0 *Lenny* 6.0 *Squeeze* 7.0 *Wheezy* 8.0 *Jessie* `alpha` yes yes `amd64` yes yes yes yes yes `armel` preliminary yes yes `armhf` yes yes `hppa` yes yes yes `hurd-i386` yes yes `i386` yes yes yes yes yes yes `ia64` yes yes yes yes `kfreebsd-amd64` yes yes yes `kfreebsd-i386` yes yes yes yes yes `mips` yes yes yes yes yes `mipsel` yes yes yes yes yes `powerpc` yes yes yes yes yes yes `ppc64` yes yes yes yes `s390` yes yes yes yes s390x `sparc` yes yes yes yes yes yes Cross platforms none Compiler back-end GCC 2.8.1 GCC 4.1 GCC 4.3 GCC 4.4 GCC 4.6 GCC 4.9 Available from <http://www.debian.org/> Support Volunteer; public bug database; paid support available from third parties; public mailing list Add-ons included 3.1 *Sarge* 4.0 *Etch* 5.0 *Lenny* 6.0 *Squeeze* 7.0 *Wheezy* 8.0 *Jessie* ada-reference-manual 1995 1995 1995 2005 2012 2012 AdaBindX 0.7.2 AdaBrowse 4.0.2 4.0.2 4.0.2 4.0.3 4.0.3 \- AdaCGI 1.6 1.6 1.6 1.6 1.6 1.6 AdaControl 1.6r8 1.9r4 1.12r3 1.12r3 1.16r11 APQ (with PostgreSQL) 3.0 3.2 3.2 AdaSockets 1.8.4.7 1.8.4.7 1.8.4.7 1.8.8 1.8.10 1.8.11 Ahven 1.2 1.7 2.1 2.4 Alog 0.1 0.3 0.4.1 \- anet 0.1 0.3.1 ASIS 3.15p 2005 2007 2008 2010 2014 AUnit 1.01 1.03 1.03 1.03 1.03 3.7.1 AWS 2.0 2.2 2.5 prerelease 2.7 2.10.2 3.2.0 Charles 2005-02-17 (superseded by Ada.Containers in gnat) Florist 3.15p 2006 2006 2009 2011 2014 GDB 5.3 6.4 6.8 7.0.1 7.4.1 7.7.1 GLADE 3.15p 2006 (superseded by PolyORB) GMPAda 0.0.20091124 0.0.20120331 0.0.20131223 GNADE 1.5.1 1.6.1 1.6.1 1.6.2 1.6.2 \- GNAT Checker 1999-05-19 (superseded by AdaControl) GPRBuild 1.3.0w 2011 2014 GPS 2.1 4.0.1 4.0.1 4.3 5.0 5.3 GtkAda 2.4 2.8.1 2.8.1 2.14.2 2.24.1 2.24.4 Log4Ada 1.0 1.2 1.2 Narval 1.10.2 OpenToken 3.0b 3.0b 3.0b 4.0b 4.0b 5.0a PC/SC Ada 0.6 0.7.1 0.7.2 PolyORB 2.6 prerelease 2.8 prerelease 2.11 prerelease PLPlot 5.9.0 5.9.5 5.9.5 5.10.0 Templates Parser 10.0+20060522 11.1 11.5 11.6 11.8 TextTools 2.0.3 2.0.3 2.0.5 2.0.6 2.1.0 XML/Ada 1.0 2.2 3.0 3.2 4.1 4.4 XML-EZ-out 1.06 1.06.1 1.06.1 The ADT plugin for Eclipse (see section ObjectAda from Aonix) can be used with GNAT as packaged for Debian Etch. Specify \"/usr\" as the toolchain path. #### DJGPP (for MS-DOS) DJGPP has GNAT as part of their GCC distribution. DJGPP is a port of a comprehensive collection of GNU utilities to MS-DOS with 32-bit extensions, and is actively supported (as of 1.2005). It includes the whole GCC compiler collection, that now includes Ada. See the DJGPP website for installation instructions. DJGPP programs run also in a DOS command box in Windows, as well as in native MS-DOS systems. #### FreeBSD and DragonFly FreeBSD\'s ports collection has an Ada framework with an expanding set of software packages. The Framework is currently built by FSF GCC 6.3.1, although FSF GCC 5.4 can optionally be used instead. The AdaCore GPL compilers are not present. There are several reasons for this, not the least of which is the addition maintenance of multiple compilers is significant. There are no non-GCC based Ada compilers represented in ports either. While FreeBSD does have a snapshot that goes with each release, the ports are updating in a rolling fashion continuously, and the vast majority of users prefer the \"head\" of ports which has the latest packages. Languages supported Ada 83, Ada 95, Ada 2005, Ada 2012, C, C++, ObjC, Fortran ---------------------------------- ---------------------------------------------------------------------------------------------------------- License for the run-time library GPLv3 with Runtime Library Exception v3 Native platforms FreeBSD i386, FreeBSD AMD64, FreeBSD ARM64, DragonFly x86-64 Cross platforms FreeBSD/DragonFly-\>Android (targets ARMv7 and x86), FreeBSD/DragonFly-\>FreeBSD/ARM64 (targets Aarch64) Compiler back-end GCC 6.3.1 Available from <http://www.freebsd.org>, <https://github.com/DragonFlyBSD/DPorts> Support Volunteer; public bug database There are two ways to install the software. The quickest and easiest way is to install prebuilt binaries using the command \"pkg install `<pkg name>`{=html}\". For example, to install the GNAT Programming Studio and all of its dependencies including the GNAT compiler, all you need is one command: `pkg install gps-ide` If a specific package is not available, or the user just prefers to build from source (this can take a long time), then a typical command would be: `cd /usr/ports/devel/gps && make install clean` As with the binary installation, if any dependencies are missing they will be built first, also from source. **Available software as of 8 February 2017** Directory Common Name version pkg name ------------------------------------- ------------------------------------------------------------ -------------------- ------------------------------ archivers/zip-ada Zip-Ada (Library) 52 zip-ada cad/ghdl GNU VHDL simulator 0.33 ghdl databases/adabase Thick bindings to Postgres, MySQL and SQLite 3.0 adabase databases/apq Ada95 database interface library 3.2.0 apq databases/apq-mysql APQ MySQL driver 3.2.0 apq-mysql databases/apq-odbc APQ ODBC driver 3.2.0 apq-odbc databases/apq-pgsql APQ PostgreSQL driver 3.2.0 apq-pgsql devel/ada-util Ada 2005 app utilities (Library) 1.8.0 ada-util devel/adaid UUID generation library 0.0.1 adaid devel/adabooch Ada95 Booch Components (Library) 2016-03-21 adabooch devel/adacurses AdaCurses (Binding) 2015-08-08 adacurses devel/afay AFlex and AYACC parser generators 041111 afay devel/ahven Ahven (Unit Test Library) 2.6 ahven devel/alog Stackable logging framework 0.5.2 alog devel/aunit Unit testing framework 2016 aunit devel/florist-gpl Florist (Posix Binding) 2016 florist-gpl devel/gnatcoll GNAT Component Collection 2016 gnatcoll devel/gnatpython GNATPython (python-based test framework) 2014-02-24 gnatpython devel/gprbuild GPRbuild (Multi-language build tool) 20160609 gprbuild devel/gps GNAT Programming Studio 2016 gps-ide devel/libspark2012 SPARK 2012 library source files 2012 libspark2012 devel/matreshka Matreshka (Info Systems Library) 0.7.0 matreshka devel/pcsc-ada PCSC library 0.7.3 pcsc-ada devel/pragmarcs PragmAda Reusable Components 20161207 pragmarcs devel/sdl_gnat GNAT SDL bindings (Thin) 2013 sdl_gnat devel/simple_components Simple Ada components 4.18 simple_components dns/ironsides Spark/Ada Ironsides DNS Server 2015-04-15 ironsides graphics/generic_image_decoder image decoder library 05 generic_image_decoder lang/adacontrol AdaControl (Construct detection tool) 1.17r3 adacontrol lang/asis Ada Semantic Interface Specification 2016 asis lang/gcc5-aux GNAT Ada compiler (FSF GCC) 5.4 (2016-06-03) gcc5-aux lang/gcc6-aux GNAT Ada compiler (FSF GCC) 6.3.1 (2017-02-02) gcc6-aux lang/gnat_util GNAT sources (helper Library) 2017-02-02 gnat_util lang/gnatcross-aarch64 FreeBSD/ARM64 cross-compiler, Aarch64 2017-02-02 (6.3.1) gnatcross-aarch64 lang/gnatcross-binutils-aarch64 GNU Binutils used by FreeBSD/ARM64 cross-compiler 2.27 gnatcross-binutils-aarch64 lang/gnatcross-sysroot-aarch64 FreeBSD/ARM64 sysroot 1 gnatcross-sysroot-aarch64 lang/gnatdroid-armv7 Android 5.0 cross-compiler, ARMv7 2017-02-02 (6.3.1) gnatdroid-armv7 lang/gnatdroid-binutils GNU Binutils used by Android cross-compiler 2.27 gnatdroid-binutils lang/gnatdroid-binutils-x86 GNU Binutils used by Android cross-compiler (x86) 2.27 gnatdroid-binutils-x86 lang/gnatdroid-sysroot Android API 4.0 to 6.0 sysroot 23 gnatdroid-sysroot lang/gnatdroid-sysroot-x86 Android API 4.4 to 6.0 sysroot (x86) 23 gnatdroid-sysroot-x86 lang/gnatdroid-x86 Android 5.0 cross-compiler, x86 2017-02-02 (6.3.1) gnatdroid-x86 lang/lua-ada Ada bindings for Lua 1.0 ada-lua math/plplot-ada PLplot Ada bindings 5.12.0 plplot-ada misc/excel-writer Excel output library 15 excel-writer misc/ini_file_manager Configuration file library 03 ini_file_manager net/adasockets IPv4 socket library 1.10 adasockets net/anet Network library (IPv4 and IPv6) 0.3.4 anet net/polyorb PolyORB (CORBA/SOAP/DSA middleware) 2.11.1 (2014) polyorb security/libadacrypt Cryptography Library (symm & asymm) 20151019 libadacrypt security/libsparkcrypto LibSparkCrypto (Cryptography Library) 0.1.1 libsparkcrypto shells/sparforte Shell and scripting language for mission-critical projects 2.0.2 spareforte textproc/adabrowse AdaBrowse (Ada95 HTML doc. generator) 4.0.3 adabrowse textproc/opentoken Ada Lex analyzer and parser 6.0b opentoken textproc/py-sphinxcontrib-adadomain Sphinx documentation generator for Ada 0.1 py27-sphinxcontrib-adadomain textproc/templates_parser AWS Template Parser library 17.0.0 templates_parser textproc/words Words (Latin/English dictionary) 1.97F words textproc/xml_ez_out XML output (Library) 1.06 xml_ez_out textproc/xmlada XML/Ada (Library) 17.0.0 xmlada www/aws Ada Web Server 17.0.1 aws www/aws-demos Ada Web Server demos 17.0.1 aws-demos x11-toolkits/gtkada GTK2/Ada (bindings) 2.24.4 gtkada x11-toolkits/gtkada3 GTK3/Ada (bindings) 3.14.2 gtkada3 #### Gentoo GNU/Linux The GNU Ada compiler can be installed on a Gentoo system using emerge: ` emerge dev-lang/gnat` In contrast to Debian, Gentoo is primarily a source distribution, so many packages are available only in source form, and require the user to recompile them (using emerge). Also in contrast to Debian, Gentoo supports several versions of GNAT in parallel on the same system. Be careful, because not all add-ons and libraries are available with all versions of GNAT. Languages supported Ada 83, Ada 95, Ada 2005, C (more?) ---------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------- License for the run-time library pure or GNAT-modified GPL (both available) Native platforms Gentoo GNU/Linux on amd64, powerpc and i386 Cross platforms none Compiler back-end GCC 3.4, 4.1 (various binary packages) Available from <http://www.gentoo.org/> (see other Gentoo dev-ada packages) Support Volunteer; public bug database Add-ons included AdaBindX, AdaBroker, AdaDoc, AdaOpenGL, AdaSockets, ASIS, AUnit, Booch Components, CBind, Charles, Florist, GLADE, GPS, GtkAda, XML/Ada #### Mandriva Linux The GNU Ada compiler can be installed on a Mandriva system with this command: `urpmi gnat` #### MinGW (for Microsoft Windows) MinGW --- Minimalist GNU for Windows contains a version of the GNAT compiler. The current version of MinGW (5.1.6) contains gcc-4.5.0. This includes a fully functional GNAT compiler. If the automatic downloader does not work correctly you can download the compiler directly: pick gcc-4.5.0-1 from MinGW/BaseSystem/GCC/Version4/ ##### old instructions The following list should help you with the installation. (I may have forgotten something --- but this is wiki, just add to the list) 1. Install `<var>`{=html}MinGW-3.1.0-1.exe`</var>`{=html} 1. extract `<var>`{=html}binutils-2.15.91-20040904-1.tar.gz`</var>`{=html} 2. extract `<var>`{=html}mingw-runtime-3.5.tar.gz`</var>`{=html} 3. extract `<var>`{=html}gcc-core-3.4.2-20040916-1.tar.gz`</var>`{=html} 4. extract `<var>`{=html}gcc-ada-3.4.2-20040916-1.tar.gz`</var>`{=html} 5. extract `<var>`{=html}gcc-g++-3.4.2-20040916-1.tar.gz (Optional)`</var>`{=html} 6. extract `<var>`{=html}gcc-g77-3.4.2-20040916-1.tar.gz (Optional)`</var>`{=html} 7. extract `<var>`{=html}gcc-java-3.4.2-20040916-1.tar.gz (Optional)`</var>`{=html} 8. extract `<var>`{=html}gcc-objc-3.4.2-20040916-1.tar.gz (Optional)`</var>`{=html} 9. extract `<var>`{=html}w32api-3.1.tar.gz`</var>`{=html} 2. Install `<var>`{=html}mingw32-make-3.80.0-3.exe (Optional)`</var>`{=html} 3. Install `<var>`{=html}gdb-5.2.1-1.exe (Optional)`</var>`{=html} 4. Install `<var>`{=html}MSYS-1.0.10.exe (Optional)`</var>`{=html} 5. Install `<var>`{=html}msysDTK-1.0.1.exe (Optional)`</var>`{=html} 1. extract `<var>`{=html}msys-automake-1.8.2.tar.bz2 (Optional)`</var>`{=html} 2. extract `<var>`{=html}msys-autoconf-2.59.tar.bz2 (Optional)`</var>`{=html} 3. extract `<var>`{=html}msys-libtool-1.5.tar.bz2 (Optional)`</var>`{=html} I have made good experience in using `<var>`{=html}D:\\MinGW`</var>`{=html} as target directory for all installations and extractions. Also noteworthy is that the Windows version for GNAT from Libre is also based on MinGW. In gcc-3.4.2-release_notes.txt from MinGW site reads: *please check that the files in the /lib/gcc/mingw32/3.4.2/adainclude and adalib directories are flagged as read-only. This attribute is necessary to prevent them from being deleted when using gnatclean to clean a project.* So be sure to do this. #### OpenCSW (for Solaris on SPARC and x86) OpenCSW has binary packages of GCC 3.4.6 and 4.6.2 with Ada support. The package names are gcc3ada and gcc4ada respectively. Languages supported Ada 83, Ada 95, parts of Ada 2005, C, C++, Fortran 95, Java, Objective-C, Objective-C++ ---------------------------------- ----------------------------------------------------------------------------------------- License for the run-time library GNAT-modified GPL Native platforms Oracle Solaris and OpenSolaris on SPARC and x86 Cross platforms none Compiler back-end GCC 3.4.6 and 4.6.2 (both available) Support ? Available from <http://www.opencsw.org/> Add-ons included none (?) #### pkgsrc: NetBSD, DragonFly, FreeBSD and Solaris The pkgsrc portable package file system has a small Ada framework. It is based on FSF GCC 5.4 currently and the FSF GCC 6.2 is available as well. The AdaCore GPL versions are not present, nor are non-GCC based compilers. The pkgsrc system is released in quarterly branches, which are normally recommended. However, a user could also choose the \"head\" which would the very latest package versions. The pkgsrc system supports 21 platforms, but for Ada this is potentially limited to 5 due to the bootstrap compiler requirement: NetBSD, DragonFly, SunOS (Solaris/Illumos), OpenBSD/MirBSD, and FreeBSD. Languages supported Ada 83, Ada 95, Ada 2005, Ada 2012, C, C++, ObjC, Fortran ---------------------------------- ------------------------------------------------------------------------------------------ License for the run-time library GPLv3 with Runtime Library Exception v3 Native platforms NetBSD i386 and amd64, DragonFly x86-64, FreeBSD i386 and amd64, Solaris i386 and x86_64 Cross platforms None Compiler back-end GCC 5.4 (GCC 4.9 and 6 available) Available from <http://www.pkgsrc.org>, status: <http://www.pkgsrc.se> Support Volunteer; public bug database There are two ways to install the software. The quickest and easiest way is to install prebuilt binaries using the command \"pkg_add `<pkg name>`{=html}\". For example, to install the GNAT Programming Studio and all of its dependencies including the GNAT compiler, all you need is one command: `pkg_add gps` If a specific package is not available, or the user just prefers to build from source (this can take a long time), then a typical command would be: `cd /usr/pkg/devel/gps && bmake install` As with the binary installation, if any dependencies are missing they will be built first, also from source. **Available software as of 14 December 2016** Directory Common Name version pkg name -------------------- ------------------------------------------ -------------------- -------------- cad/ghdl GNU VHDL simulator 0.32rc1 ghdl devel/florist Florist (Posix Binding) 2012 florist-gpl devel/gnatpython GNATPython (python-based test framework) 2011-09-12 gnatpython devel/gprbuild-aux GPRbuild (Multi-language build tool) 2016-06-09 gprbuild-aux lang/gcc-aux GNAT Ada compiler (FSF GCC) 4.9.2 (2014-10-23) gcc-aux lang/gcc5-aux GNAT Ada compiler (FSF GCC) 5.4.0 (2016-06-03) gcc5-aux lang/gcc6-aux GNAT Ada compiler (FSF GCC) 6.2.0 (2016-08-22) gcc6-aux textproc/xmlada XML/Ada (Library) 4.4.0 xmlada www/aws Ada Web Server 3.1.0.0 (w) aws www/aws-demos Ada Web Server demos 3.1.0.0 (w) aws-demos x11/gtkada GTK/Ada (bindings) 2.24.4 gtkada #### SuSE Linux All versions of SuSE Linux have a GNAT compiler included. SuSE versions 9.2 and higher also contains ASIS, Florist and GLADE libraries. The following two packages are needed: `gnat`\ `gnat-runtime` For SuSE version 12.1, the compiler is in the package ` gcc46-ada`\ ` libada46` For 64 bit system you will need the 32 bit compatibility packages as well: `gnat-32bit`\ `gnat-runtime-32bit` #### Ubuntu Ubuntu (and derivatives like Kubuntu, Xubuntu\...) is a Debian-based Linux distribution, thus the installation process described above "wikilink") can be used. Graphical package managers like Synaptic or Adept can also be employed to select the Ada packages. ## ICC from Irvine Compiler Corporation Irvine Compiler Corporation provides native and cross compilers for various platforms.1 The compiler and run-time system support development of certified, safety-critical software. Commercial, proprietary. No-cost evaluation is possible on request. Royalty-free redistribution of the run-time system is allowed. ## Janus/Ada 83 and 95 from RR Software RR Software offers native compilers for MS-DOS, Microsoft Windows and various Unix and Unix-like systems, and a library for Windows GUI programming called CLAW. There are academic, personal and professional editions, as well as support options. Janus/Ada 95 supports subset of Ada 2007 and Ada 2012 features. Commercial but relatively cheap; proprietary. ## MAXAda from Concurrent Concurrent offers MAXAda, an Ada 95 compiler for Linux/Xeon and PowerPC platforms, and Ada bindings to POSIX and X/Motif.2 Commercial, proprietary. ## ObjectAda from PTC (formerly Aonix/Atego) PTC offers ObjectAda native (Windows, some flavors of Unix, and Linux) and cross (PPC, Intel, VxWorks, and ERC32) compilers. Limited support of Ada 2012 is available. Commercial, proprietary. ## PowerAda from OC Systems OC Systems offers Ada compilers and bindings to POSIX and X-11: - PowerAda, an Ada 95 compiler for Linux and AIX, - LegacyAda/390, an Ada 83 compiler for IBM System 370 and 390 mainframes Commercial, proprietary. ## ApexAda from PTC (formerly IBM Rational) PTC ApexAda for native and embedded development. Commercial, proprietary. ## SCORE from DDC-I DDC-I offers its SCORE cross-compilers for embedded development. SCORE stands for Safety-Critical, Object-oriented, Real-time Embedded. Commercial, proprietary. ## TADS from Tartan Tartan offers the Tartan Ada Development System (TADS), with cross-compilers for some digital signal processors. Commercial, proprietary. ## XD Ada from DXC XD Ada is an Ada 83 cross-compiler for embedded development. Hosts include VAX, Alpha and Integrity Servers running OpenVMS. Targets include Motorola 68000 and MIL-STD-1750A processors. Commercial, proprietary. ## XGC Ada from XGC Software XGC compilers are GCC with custom run-time libraries suitable for avionics and space applications. The run-time kernels are very small and do not support exception propagation (i.e. you can handle an exception only in the subprogram that raised it). Commercial but some versions are also offered as free downloads. Free Software. Languages supported Ada 83, Ada 95, C ---------------------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- License for the run-time library GNAT-Modified GPL Native platforms none Cross platforms Hosts: sun-sparc-solaris, pc-linux2.\*; targets are bare boards with ERC32, MIL-STD-1750A, Motorola 68000 family or Intel 32-bit processors. PowerPC and Intel 80186 targets on request. Compiler back-end GCC 2.8.1 Available from <http://www.xgc.com/> Support Commercial Add-ons included Ravenscar-compliant run-time kernels, certified for avionics and space applications; gdb cross-debugger; target simulator. ## References ```{=html} <references/> ``` Programming}}\|Installing es:Programación en Ada/Instalación
# Ada Programming/Building Ada programs are usually easier to build than programs written in other languages like C or C++, which frequently require a makefile. This is because an Ada source file already specifies the dependencies of its source unit. See the **with** keyword for further details. Building an Ada program is not defined by the Reference Manual, so this process is absolutely dependent on the compiler. Usually the compiler kit includes a make tool which compiles a main program and all its dependencies, and links an executable file. ## Building with various compilers : *This list is incomplete. You can help Wikibooks by adding the build information for other compilers.* ### GNAT With GNAT, you can run this command: `gnat make `*`<your_unit_file>`{=html}* If the file contains a procedure, gnatmake will generate an executable file with the procedure as main program. Otherwise, e.g. a package, gnatmake will compile the unit and all its dependencies. #### GNAT command line gnatmake can be written as one word `gnatmake` or two words `gnat make`. For a full list of gnat commands just type `gnat` without any command options. The output will look something like this: `GNAT 3.4.3 Copyright 1996-2004 Free Software Foundation, Inc.`\ \ `List of available commands`\ \ `GNAT BIND               gnatbind`\ `GNAT CHOP               gnatchop`\ `GNAT CLEAN              gnatclean`\ `GNAT COMPILE            gnatmake -c -f -u`\ `GNAT ELIM               gnatelim`\ `GNAT FIND               gnatfind`\ `GNAT KRUNCH             gnatkr`\ `GNAT LINK               gnatlink`\ `GNAT LIST               gnatls`\ `GNAT MAKE               gnatmake`\ `GNAT NAME               gnatname`\ `GNAT PREPROCESS         gnatprep`\ `GNAT PRETTY             gnatpp`\ `GNAT STUB               gnatstub`\ `GNAT XREF               gnatxref`\ \ `Commands FIND, LIST, PRETTY, STUB and XREF accept project file switches -vPx, -Pprj and -Xnam=val` For further help on the option just type the command (one word or two words --- as you like) without any command options. #### GNAT IDE The GNAT toolchain comes with an IDE called GPS, included with recent releases of the GPL version of GNAT. GPS features a graphical user interface. Emacs includes (Ada Mode), and GNAT plugins for KDevelop and Vim "wikilink") (Ada Mode) are available. Vim Ada Mode is maintained by The GNU Ada project. #### GNAT with Xcode Apple\'s free (gratis) IDE, Xcode, uses the LLVM compiler with the Clang front-end, and does not support Ada: however, in Xcode 4.3 for OS X Lion and later versions, the command line tools (assembler, linker etc) which are required to use GNAT are an optional component of Xcode and must be specially installed. ### Rational APEX Rational APEX is a complete development environment comprising a language sensitive editor, compiler, debugger, coverage analyser, configuration management and much more. You normally work with APEX running a GUI. APEX has been built for the development of big programs. Therefore the basic entity of APEX is a *subsystem*, a directory with certain traits recognized by APEX. All Ada compilation units have to reside in subsystems. You can define an *export set*, i.e. the set of Ada units visible to other subsystems. However for a subsystem A to gain visibility to another subsystem B, A has to *import* B. After importing, A sees all units in B\'s export set. (This is much like the with-clauses, but here visibility means only potential visibility for Ada: units to be actually visible must be mentioned in a with-clause of course; units not in the export set cannot be used in with-clauses of Ada units in external subsystems.) Normally subsystems should be hierarchically ordered, i.e. form a directed graph. But for special uses, subsystems can also mutually import one another. For configuration management, a subsystem is decomposed in *views*, subdirectories of the subsystem. Views hold different development versions of the Ada units. So actually it\'s not subsystems which import other subsystems, rather subsystem views import views of other subsystems. (Of course, the closure of all imports must be consistent --- it cannot be the case that e.g. subsystem (A, view A1) imports subsystems (B, B1) and (C, C1), whereas (B, B1) imports (C, C2)). A view can be defined to be the development view. Other views then hold releases at different stages. Each Ada compilation unit has to reside in a file of its own. When compiling an Ada unit, the compiler follows the with-clauses. If a unit is not found within the subsystem holding the compile, the compiler searches the import list (only the direct imports are considered, not the closure). Units can be taken under version control. In each subsystem, a set of *histories* can be defined. An Ada unit can be taken under control in a history. If you want to edit it, you first have to check it out --- it gets a new version number. After the changes, you can check it in again, i.e. make the changes permanent (or you abandon your changes, i.e. go back to the previous version). You normally check out units in the development view only; check-outs in release views can be forbidden. You can select which version shall be the active one; normally it is the one latest checked in. You can even switch histories to get different development paths. e.g. different bodies of the same specification for different targets. ### ObjectAda ObjectAda is a set of tools for editing, compiling, navigating and debugging programs written in Ada. There are various editions of ObjectAda. With some editions you compile programs for the same platform and operating systems on which you run the tools. These are called native. With others, you can produce programs for different operating systems and platforms. One possible platform is the Java virtual machine. These remarks apply to the native Microsoft Windows edition. You can run the translation tools either from the IDE or from the command line. Whether you prefer to work from the IDE, or from the command line, a little bookkeeping is required. This is done by creating a project. Each project consists of a number of source files, and a number of settings like search paths for additional Ada libraries and other dependences. Each project also has at least one target. Typically, there is a debug target, and a release target. The names of the targets indicate their purpose. At one time you compile for debugging, typically during development, at other times you compile with different settings, for example when the program is ready for release. Some (all commercial?) editions of ObjectAda permit a Java (VM) target. ### DEC Ada for VMS DEC Ada is an Ada 83 compiler for VMS. While "DEC Ada" is probably the name most users know, the compiler is now called "HP Ada". It had previously been known also by names of \"VAX Ada\" and \"Compaq Ada\". DEC Ada uses a true library management system --- so the first thing you need to do is create and activate a library: `ACS Library Create [MyLibrary]`\ `ACS Set Library [MyLibrary]` When creating a library you already set some constraints like support for Long_Float or the available memory size. So carefully read `HELP ACS Library Create *` Then next step is to load your Ada sources into the library: `ACS Load [Source]*.ada` The sources don\'t need to be perfect at this stage but syntactically correct enough for the compiler to determine the packages declared and analyze the statements. Dec Ada allows you to have more than one package in one source file and you have any filename convention you like. The purpose of `ACS Load` is the creation of the dependency tree between the source files. Next you compile them: `ACS Compile *` Note that compile take the package name and not the filename. The wildcard `*` means *all packages loaded*. The compiler automatically determines the right order for the compilation so a make "wikilink") tool is not strictly needed. Last but not least you link your file into an `ACS Link /Executable=[Executables]Main.exe Main` On large systems you might want to break sources down into several libraries --- in which case you also need `ACS Merge /Keep *` to merge the content of the current library with the library higher up the hierarchy. The larger libraries should then be created with: `ACS Library Create /Large` This uses a different directory layout more suitable for large libraries. #### DEC Ada IDE Dec Ada comes without an IDE, however the DEC LSE as well as the Ada Mode of the Vim text editor "wikilink") support DEC Ada. ## Compiling our Demo Source Once you have downloaded our example programs you might wonder how to compile them. First you need to extract the sources. Use your favorite zip tool "wikilink") to achieve that. On extraction a directory with the same name as the filename is created. Beware: WinZip might also create a directory equaling the filename so Windows users need to be careful using the right option otherwise they end up with `<var style="color:OliveDrab4">`{=html}wikibook-ada-1_2\_0.src\\wikibook-ada-1_2\_0`</var>`{=html}. Once you extracted the files you will find all sources in `<var style="color:OliveDrab4">`{=html}wikibook-ada-1_2\_0/Source`</var>`{=html}. You could compile them right there. For your convenience we also provide ready made project files for the following IDEs (If you find a directory for an IDEs not named it might be in the making and not actually work). ### GNAT You will find multi-target GNAT Project files and a multi-make Makefile file in `<var style="color:OliveDrab4">`{=html}wikibook-ada-2_0\_0/GNAT`</var>`{=html}. For i686 Linux and Windows you can compile any demo using: `gnat make -P `*`project_file`* You can also open them inside the GPS with `gps -P `*`project_file`* For other target platform it is a bit more difficult since you need to tell the project files which target you want to create. The following options can be used: style (\"Debug\", \"Release\"): you can define if you like a debug or release version so you can compare how the options affect size and speed.\ os (\"Linux\", \"OS2\", \"Windows_NT\", \"VMS\") : choose your operating system. Since there is no Ada 2005 available for OS/2 don\'t expect all examples to compile.\ target (\"i686\", \"x86_64\", \"AXP\"): choose your CPU --- \"i686\" is any form of 32bit Intel or AMD CPU, \"x86_64\" is an 64 bit Intel or AMD CPU and if you have an \"AXP\" then you know it. Remember to type all options as they are shown. To compile a debug version on x86-64 Linux you type: `gnat make -P `*`project_file`*` -Xstyle=Debug -Xos=Linux -Xtarget=x86_64` As said in the beginning there is also a **makefile** available that will automatically determine the target used. So if you have a GNU make you can save yourself a lot of typing by using: `make `*`project`* or even use `make `*`all`* to make all examples in debug and release in one go. Each compile is stored inside its own directory which is created in the form of `<var style="color:OliveDrab4">`{=html}wikibook-ada-2_0\_0/GNAT/**OS**-**Target**-**Style**`</var>`{=html}. Empty directories are provided inside the archive. ### Rational APEX APEX uses the subsystem and view directory structure, so you will have to create those first and copy the source files into the view. After creating a view using the architecture model of your choice, use the menu option \"Compile -\> Maintenance -\> Import Text Files\". In the Import Text Files dialog, add \"wikibook-ada-2_0\_0/Source/\*.ad?\" to select the Ada source files from the directory you originally extracted to. Apex uses the file extensions .1.ada for specs and .2.ada for bodies --- don\'t worry, the import text files command will change these automatically. To link an example, select its main subprogram in the directory viewer and click the link button in the toolbar, or \"Compile -\> Link\" from the menu. Double-click the executable to run it. You can use the shift-key modifier to bypass the link or run dialog. ### ObjectAda #### ObjectAda command-line The following describes using the ObjectAda tools for Windows in a console window. Before you can use the ObjectAda tools from the command line, make sure the `PATH` environment variable lists the directory containing the ObjectAda tools. Something like `set path=%path%;P:\Programs\Aonix\ObjectAda\bin` A minimal ObjectAda project can have just one source file. like the Hello World program provided in To build an executable from this source file, follow these steps (assuming the current directory is a fresh one and contains the above mentioned source file): - Register your source files: `X:\some\directory> adareg hello_world_1.adb` This makes your sources known to the ObjectAda tools. Have a look at the file UNIT.MAP created by adareg in the current directory if you like seeing what is happening under the hood. - Compile the source file: `X:\some\directory> adacomp hello_world_1.adb`\ `Front end of hello_world_1.adb succeeded with no errors.` - Build the executable program: `X:\some\directory> adabuild hello_world_1`\ `ObjectAda Professional Edition Version 7.2.2: adabuild`\ `   Copyright (c) 1997-2002 Aonix.  All rights reserved.`\ `Linking...`\ `Link of hello completed successfully` Notice that you specify the name of the main unit as argument to `adabuild`, not the name of the source file. In this case, it is *Hello_World_1* as in ` Hello_World_1 ` More information about the tools can be found in the user guide *Using the command line interface*, installed with the ObjectAda tools. ## See also ### Wikibook - Ada Programming - Ada Programming/Installing ## External links - GNAT Online Documentation: - GNAT User\'s Guide - DEC Ada: - Developing Ada Products on OpenVMS (PDF) - DEC Ada --- Language Reference Manual (PDF) - DEC Ada --- Run-Time Reference (PDF) Programming}}\|Building
# Ada Programming/Environment environment for the development of Ada-language programs. Some useful ## Emacs Ada-Mode **Emacs** is an easily-customized highly-extensible text-editor. Emacs includes a module for Ada-language support as part of the Emacs standard distribution, called **\'Ada-mode**\'. Emacs is available for many Linux distributions as a binary or source package. Emacs is available as a binary installer for Windows, and is also available as an OS-agnostic source code package. The Ada-mode website includes a description of \'Ada-mode\' as well as installation and configuration instructions for different operating systems, including a guide to customizing Ada-mode to personal taste.[^1] A mailing list is available at the Ada-mode website for answering questions related to Ada development in Emacs. ## GNAT Studio **GNAT Studio** (formerly **GPS**, an acronym for the **GNAT Programming Studio**) is a fully-featured integrated development environment. It includes support for multiple platforms and languages, and modern programming tools including a language sensitive editor, graphical debugger, automatic code fixing, and support for version control systems. GPS is supported by AdaCore, and comes with a large amount of online documentation, including an online user guide and tutorial. AdaCore also maintains a port of the GUI toolkit GTK called GtkAda, which provides for the development of rich, GUI-based applications with Ada. ## PTC PTC\'s editions of ObjectAda include compilers and tools for various targets, a programmable debugger, a language sensitive editing environment, and also an Eclipse plugin. ApexAda continues the full lifecycle environment offered with this former Rational/IBM Ada. ## Ada support in mainstream Integrated Development Environments There are extensions for mainstream Integrated Development Environments supporting Ada with the GNAT compiler: GNATbench for Eclipse, Ada for VS Code, IntelliJ IDEA, and Ada for Netbeans. ## APSE (historical) **APSE** is short for **Ada Programming Support Environment**.[^2] APSE was a U.S. Military specification for developing a programming environment that would support the Ada programming language and Ada-related programming tools. ## References ```{=html} <references /> ``` ## See also ### Wikibook - Getting Started (from Ada Programming) - Ada Style Guide Programming}}\|Building [^1]: FSF download (download) [^2]: APSE (article on wikipedia).
# Ada Programming/Expressions ## Expressions The LRM defines an expression as `<q>`{=html}a formula that defines the computation or retrieval of a value.`</q>`{=html}.[^1] There are numerous forms of expression, ranging from primaries such as literals or names, to quantified expression. An expression is typically used in an assignment, or as part of a bigger expression. The value of an expression usually involves computation. However, some expressions\' values are determined at compile time; these are called *static* expressions. A so-called simple expression (which happens to be a *term*) is seen in `   Area := Length * Height;` The text `Length * Height` has the form of an expression, and is used on the right hand side of an assignment statement. Computing the value of the expression means multiplying the value named `Length` by the one named `Height`. Using the same expression as part of a bigger expression is demonstrated in the following example: `   `` Cost (Paint, Area => Length * Height) > 900 * Dollar `\ `     ...` The bigger expression starts with `Cost` and ends with `Dollar`. It features another form of expression, a *relation*, and places a function call and another multiplicative expression to the left and right, respectively, of the relation\'s relational operator `>`. The two are called *operands* and the result is a Boolean expression. ### Kinds of Expressions Among basic expressions are *literals*, for example, decimal (real), enumeration, string, and access value literals: `  2.5e+3`\ `  False`\ `  "и"`\ `  ` Involving many of those, one can write *aggregates* (a *primary*), `  (X => 0.0,`\ `   Y => 1.0,`\ `   Z => 0.0)` but arbitrarily complex sub-components are possible, too, creating an aggregate from component expressions, `  (Height => 1.89 * Meter,  `\ `   Age    => Guess (Picture => Images.Load (Suspects, "P2012-Aug.PNG"),`\ `                    Tiles   => Grid'(1 .. 3 => Scan, 4 => Skip)),`\ `   Name   => `` Nickname'("Herbert"))` `Age` is associated with the value of a nested *function call*. The actual parameter for `Tiles` has type name `Grid` qualify the array aggregate following it; the component `Name` is associated with an *allocator*. The well known 'mathematical' expressions have closely corresponding *simple expressions* in Ada syntax, for example `2.0*π*r`, or the *relation* `  Area = π*r**2` Other expressions test for *membership* in a range, or in a type: `  X `` 1 .. 10 | 12`\ `  Shape `` Polygon'Class` ### Conditional Expressions, Quantified Expressions New in Ada 2012, there are forms for making the value of an expression depend on the value of another expression, conditionally. They have a pair of parentheses around them and they start with a keyword, which clearly distinguishes them from other kinds of expression. For example: `  Area := (`` Is_Circular `` Pi * Radius**2 `` Length * Height);` In this example, the value of `Is_Circular` determines the part of the expression that is used for computing the value of the entire expression. A similar construct exists for and also one for . These kinds of expressions are frequently used in assertions, like in the conditions of contract based programming. ### References ```{=html} <references/> ``` [^1]:
# Ada Programming/Control ` `*`condition`*` `\ `    `*`statement`*`;`\ \ `    `*`other statement`*`;`\ ` ``;` ` `*`condition`*` `\ `    `*`statement`*`;`\ ` `*`condition`*` `\ `    `*`other statement`*`;`\ ` `*`condition`*` `\ `    `*`other statement`*`;`\ `...`\ \ `    `*`another statement`*`;`\ ` ``; ` ` ``;`\ `  ``;`\ `...`\ ` Degrees `` `` Float `` -273.15 .. Float'Last;`\ `...`\ `Temperature : Degrees;`\ `...`\ ` Temperature >= 40.0 `\ `    Put_Line ("Wow!");`\ `    Put_Line ("It's extremely hot");`\ ` Temperature >= 30.0 `\ `    Put_Line ("It's hot");`\ ` Temperature >= 20.0 `\ `    Put_Line ("It's warm");`\ ` Temperature >= 10.0 `\ `    Put_Line ("It's cool");`\ ` Temperature >= 0.0 `\ `    Put_Line ("It's cold");`\ \ `    Put_Line ("It's freezing");`\ ` ``; ` In Ada, conditional statements with more than one conditional do not use short-circuit evaluation by default. In order to mimic C/C++\'s short-circuit evaluation, use ` ` or ` ` between the conditions. ` X `\ `   `` 1 `\ \ `      Walk_The_Dog;`\ \ `   `` 5 `\ \ `      Launch_Nuke;`\ \ `   `` 8 | 10 `\ \ `      Sell_All_Stock;`\ \ `   `` `` `\ \ `      Self_Destruct;`\ \ ` ``;` The subtype of X must be a discrete type, i.e. an enumeration or integer type. In Ada, one advantage of the case statement is that the compiler will check the coverage of the choices, that is, all the values of the subtype of variable X must be present or a default branch must specify what to do in the remaining cases. For procedures: `;` For functions: ` Value;` `   `` Label;`\ \ `   Dont_Do_Something;`\ \ `Label`\ `   ...` ` Use_Return `\ \ `   Do_Something;`\ \ `   `` Test `\ `      ``;`\ `   `` ``;`\ \ `   Do_Something_Else;`\ \ `   ``;`\ ` Use_Return;` ` Use_Goto `\ \ `   Do_Something`\ `  `\ `   `` Test `\ `      `` Exit_Use_Goto`\ `   `` `\ \ `   Do_Something_Else`\ \ `Exit_Use_Goto`\ `   `\ ` Use_Goto` ` Use_If `\ \ `   Do_Something;`\ `  `\ `   `` `` Test `\ \ `      Do_Something_Else;`\ \ `   `` ``;`\ \ `   ``;`\ ` Use_If;` *`Endless_Loop`*` :`\ `   `\ \ `      Do_Something;`\ \ `   `` `` `*`Endless_Loop`*`;` The loop name (in this case, \"Endless_Loop\") is an optional feature of Ada. Naming loops is nice for readability but not strictly needed. Loop names are useful though if the program should jump out of an inner loop, see below. *`While_Loop`*` :`\ `   `` X <= 5 `\ \ `      X := Calculate_Something;`\ \ `   `` `` `*`While_Loop`*`;` *`Until_Loop`*` :`\ `   `\ \ `      X := Calculate_Something;`\ \ `      `` Until_Loop `` X > 5;`\ `   `` `` `*`Until_Loop`*`;` *`Exit_Loop`*` :`\ `   `\ \ `      X := Calculate_Something;`\ \ `      `` Exit_Loop `` X > 5;`\ \ `      Do_Something (X);`\ \ `   `` ``  `*`Exit_Loop`*`;` In Ada the **exit** condition can be combined with any other loop statement as well. You can also have more than one **exit** statement. You can also exit a named outer loop if you have several loops inside each other. *`For_Loop`*` :`\ `   `` I `` Integer `` 1 .. 10 `\ \ `      Do_Something (I)`\ \ `   `` `` `*`For_Loop`*`;` You don\'t have to declare both subtype and range as seen in the example. If you leave out the subtype then the compiler will determine it by context; if you leave out the range then the loop will iterate over every value of the subtype given. As always with Ada: when \"determine by context\" gives two or more possible options then an error will be displayed and then you have to name the type to be used. Ada will only do \"guess-works\" when it is safe to do so. The loop counter I is a constant implicitly declared and ceases to exist after the body of the loop. *`Array_Loop`*` :`\ `   `` I `` X'`` `\ \ `      X (I) := Get_Next_Element;`\ \ `   `` `` `*`Array_Loop`*`;` With X being an array. Note: This syntax is mostly used on arrays --- hence the name --- but will also work with other types when a full iteration is needed. #### Working example The following example shows how to iterate over every element of an integer type. \ \ ` ``;`\ \ ` Range_1 `\ `   `` Range_Type `` `` -5 .. 10;`\ \ `   `` T_IO `` ``;`\ `   `` I_IO `` ``  `` (Range_Type);`\ \ \ `   `` A `` Range_Type `\ `      I_IO.Put (Item  => A,`\ `                Width => 3,`\ `                Base  => 10);`\ \ `      `` A < Range_Type'Last `\ `         T_IO.Put (",");`\ `      `\ `         T_IO.New_Line;`\ `      `` ``;`\ `   `` ``;`\ ` Range_1;` ## See also ### Wikibook - Ada Programming ### Ada Reference Manual - - - - - - - Programming}}\|Control es:Programación en Ada/Sentencias y estructuras de control
# Ada Programming/Type System Ada\'s type system allows the programmer to construct powerful abstractions that represent the real world, and to provide valuable information to the compiler, so that the compiler can find many logic or design errors before they become bugs. It is at the heart of the language, and good Ada programmers learn to use it to great advantage. Four principles govern the type system: - **Type**: a way to categorize data. characters are types \'a\' through \'z\'. Integers are types that include 0,1,2\.... - **Strong typing**: types are incompatible with one another, so it is not possible to mix apples and oranges. The compiler will not guess that your apple is an orange. You must explicitly say my_fruit = fruit(my_apple). Strong typing reduces the amount of errors. This is because developers can really easily write a float into an integer variable without knowing. Now data you needed for your program to succeed has been lost in the conversion when the complier switched types. Ada gets mad and rejects the developer\'s dumb mistake by refusing to do the conversion unless explicitly told. - **Static typing**: type checked while compiling, this allows type errors to be found earlier. - **Abstraction**: types represent the real world or the problem at hand; not how the computer represents the data internally. There are ways to specify exactly how a type must be represented at the bit level, but we will defer that discussion to another chapter. An example of an abstraction is your car. You don\'t really know how it works you just know that bumbling hunk of metal moves. Nearly every technology you work with is abstracted layer to simplify the complex circuits that make it up - the same goes for software. You want abstraction because code in a class makes a lot more sense than a hundred if statements with no explanation when debugging - **Name equivalence**, as opposed to *structural equivalence* used in most other languages. Two types are compatible if and only if they have the same name; *not* if they just happen to have the same size or bit representation. You can thus declare two integer types with the same ranges that are totally incompatible, or two record types with exactly the same components, but which are incompatible. Types are incompatible with one another. However, each type can have any number of *subtypes*, which are compatible with their base type and may be compatible with one another. See below for examples of subtypes which are incompatible with one another. ## Predefined types There are several predefined types, but most programmers prefer to define their own, application-specific types. Nevertheless, these predefined types are very useful as interfaces between libraries developed independently. The predefined library, obviously, uses these types too. These types are predefined in the package: Integer: This type covers at least the range $-2^{15}+1$ .. $+2^{15}-1$ (RM ). The Standard also defines `Natural` and `Positive` subtypes of this type. Float: There is only a very weak implementation requirement on this type (RM ); most of the time you would define your own floating-point types, and specify your precision and range requirements.\ Duration: A fixed point type used for timing. It represents a period of time in seconds (RM ).\ Character : A special form of Enumerations. There are three predefined kinds of character types: 8-bit characters (called `Character`), 16-bit characters (called `Wide_Character`), and 32-bit characters (`Wide_Wide_Character`). `Character` has been present since the first version of the language (Ada 83), `Wide_Character` was added in Ada 95, while the type `Wide_Wide_Character` is available with Ada 2005.\ String: Three indefinite array types, of `Character`, `Wide_Character`, and `Wide_Wide_Character` respectively. The standard library contains packages for handling strings in three variants: fixed length (), with varying length below a certain upper bound (), and unbounded length (). Each of these packages has a `Wide_` and a `Wide_Wide_` variant.\ Boolean : A `Boolean` in Ada is an Enumeration of `False` and `True` with special semantics. Packages and predefine some types which are primarily useful for low-level programming and interfacing to hardware. System.Address : An address in memory.\ System.Storage_Elements.Storage_Offset : An offset, which can be added to an address to obtain a new address. You can also subtract one address from another to get the offset between them. Together, `Address`, `Storage_Offset` and their associated subprograms provide for address arithmetic.\ System.Storage_Elements.Storage_Count : A subtype of `Storage_Offset` which cannot be negative, and represents the memory size of a data structure (similar to C\'s `size_t`).\ System.Storage_Elements.Storage_Element : In most computers, this is a byte. Formally, it is the smallest unit of memory that has an address.\ System.Storage_Elements.Storage_Array : An array of `Storage_Element`s without any meaning, useful when doing raw memory access. ## The Type Hierarchy Types are organized hierarchically. A type inherits properties from types above it in the hierarchy. For example, all scalar types (integer, enumeration, modular, fixed-point and floating-point types) have operators \"\", \"\" and arithmetic operators defined for them, and all discrete types can serve as array indexes. !Ada type hierarchy{width="550"} Here is a broad overview of each category of types; please follow the links for detailed explanations. Inside parenthesis there are equivalences in C and Pascal for readers familiar with those languages. Signed Integers `<small>`{=html}(**int**, **INTEGER**)`</small>`{=html} : Signed Integers are defined via the range of values needed.\ Unsigned Integers `<small>`{=html}(**unsigned**, **CARDINAL**)`</small>`{=html} : Unsigned Integers are called Modular Types. Apart from being unsigned they also have wrap-around functionality.\ Enumerations `<small>`{=html}(**enum**, **char**, **bool**, **BOOLEAN**)`</small>`{=html} : Ada Enumeration types are a separate type family.\ Floating point `<small>`{=html}(**float**, **double**, **REAL**)`</small>`{=html} : Floating point types are defined by the digits needed, the relative error bound.\ Ordinary and Decimal Fixed Point `<small>`{=html}(**DECIMAL**)`</small>`{=html} : Fixed point types are defined by their delta, the absolute error bound.\ Arrays `<small>`{=html}( **\[ \]**, **ARRAY \[ \] OF**, **STRING** )`</small>`{=html} : Arrays with both compile-time and run-time determined size are supported.\ Record `<small>`{=html}(**struct**, **class**, **RECORD OF**)`</small>`{=html} : A **record** is a composite type that groups one or more fields.\ Access `<small>`{=html}(**\***, **\^**, **POINTER TO**)`</small>`{=html} : Ada\'s Access types may be more than just a simple memory address.\ Task & Protected `<small>`{=html}(similar to multithreading in C++)`</small>`{=html} : Task and Protected types allow the control of concurrency\ Interfaces `<small>`{=html}(similar to virtual methods in C++)`</small>`{=html} : New in Ada 2005, these types are similar to the Java interfaces. ### Classification of Types Ada\'s types can be classified as follows. **Specific vs. Class-wide** ` T `` ...  -- a specific type`\ `  T'Class      -- the corresponding class-wide type (exists only for tagged types)` `T'Class` and `T'Class'Class` are the same. Primitive operations with parameters of specific types are *non-dispatching*, those with parameters of class-wide types are *dispatching*. New types can be declared by *deriving* from specific types; primitive operations are *inherited* by derivation. You cannot derive from class-wide types. **Constrained vs. Unconstrained** ` I `` `` 1 .. 10;           -- constrained`\ ` AC `` `` (1 .. 10) `` ...  -- constrained` ` AU `` `` (I `` <>) `` ...          -- unconstrained`\ ` R (X: Discriminant [:= Default]) `` ...  -- unconstrained` By giving a *constraint* to an unconstrained subtype, a subtype or object becomes constrained: ` RC `` R (Value);  -- constrained subtype of R`\ `OC: R (Value);            -- constrained object of anonymous constrained subtype of R`\ `OU: R;                    -- unconstrained object` Declaring an unconstrained object is only possible if a default value is given in the type declaration above. The language does not specify how such objects are allocated. GNAT allocates the maximum size, so that size changes that might occur with discriminant changes present no problem. Another possibility is implicit dynamic allocation on the heap and re-allocation followed by a deallocation when the size changes. **Definite vs. Indefinite** ` I `` `` 1 .. 10;                     -- definite`\ ` RD (X: Discriminant := Default) `` ...  -- definite` ` T (<>) `` ...                    -- indefinite`\ ` AU `` `` (I `` <>) `` ...  -- indefinite`\ ` RI (X: Discriminant) `` ...      -- indefinite` Definite subtypes allow the declaration of objects without initial value, since objects of definite subtypes have constraints that are known at creation-time. Object declarations of indefinite subtypes need an initial value to supply a constraint; they are then constrained by the constraint delivered by the initial value. `OT: T  := Expr;                       -- some initial expression (object, function call, etc.)`\ `OA: AU := (3 => 10, 5 => 2, 4 => 4);  -- index range is now 3 .. 5`\ `OR: RI := Expr;                       -- again some initial expression as above` **Unconstrained vs. Indefinite** Note that unconstrained subtypes are not necessarily indefinite as can be seen above with RD: it is a definite unconstrained subtype. ## Concurrency Types The Ada language uses types for one more purpose in addition to classifying data + operations. The type system integrates concurrency (threading, parallelism). Programmers will use types for expressing the concurrent threads of control of their programs. The core pieces of this part of the type system, the **task** types and the **protected** types are explained in greater depth in a section on tasking. ## Limited Types Limiting a type means disallowing assignment. The "concurrency types" described above are always limited. Programmers can define their own types to be limited, too, like this: ` T `` `` …;` (The ellipsis stands for , or for a definition, see the corresponding subsection on this page.) A limited type also doesn\'t have an equality operator unless the programmer defines one. You can learn more in the limited types chapter. ## Defining new types and subtypes You can define a new type with the following syntax: ` T ``...` followed by the description of the type, as explained in detail in each category of type. Formally, the above declaration creates a type and its *first subtype* named `T`. The type itself, correctly called the \"type of T\", is anonymous; the RM refers to it as *`T`* (in italics), but often speaks sloppily about the type T. But this is an academic consideration; for most purposes, it is sufficient to think of `T` as a type. For scalar types, there is also a base type called `T'Base`, which encompasses all values of T. For signed integer types, the type of T comprises the (complete) set of mathematical integers. The base type is a certain hardware type, symmetric around zero (except for possibly one extra negative value), encompassing all values of T. As explained above, all types are incompatible; thus: ` Integer_1 `` `` 1 .. 10;`\ ` Integer_2 `` `` 1 .. 10;`\ `A : Integer_1 := 8;`\ `B : Integer_2 := A; ` is illegal, because `Integer_1` and `Integer_2` are different and incompatible types. It is this feature which allows the compiler to detect logic errors at compile time, such as adding a file descriptor to a number of bytes, or a length to a weight. The fact that the two types have the same range does not make them compatible: this is *name equivalence* in action, as opposed to structural equivalence. (Below, we will see how you can convert between incompatible types; there are strict rules for this.) ### Creating subtypes You can also create new subtypes of a given type, which will be compatible with each other, like this: ` Integer_1 `` `` 1 .. 10;`\ ` Integer_2 `` Integer_1      `` 7 .. 11;  `\ ` Integer_3 `` Integer_1'Base `` 7 .. 11;  `\ `A : Integer_1 := 8;`\ `B : Integer_3 := A; ` The declaration of `Integer_2` is bad because the constraint `7 .. 11` is not compatible with `Integer_1`; it raises `Constraint_Error` at subtype elaboration time. `Integer_1` and `Integer_3` are compatible because they are both subtypes of the same type, namely `Integer_1'Base`. It is not necessary that the subtype ranges overlap, or be included in one another. The compiler inserts a run-time range check when you assign A to B; if the value of A, at that point, happens to be outside the range of `Integer_3`, the program raises `Constraint_Error`. There are a few predefined subtypes which are very useful: ` Natural  `` Integer `` 0 .. Integer'Last;`\ ` Positive `` Integer `` 1 .. Integer'Last;` ### Derived types A derived type is a new, full-blown type created from an existing one. Like any other type, it is incompatible with its parent; however, it inherits the primitive operations defined for the parent type. ` Integer_1 `` `` 1 .. 10;`\ ` Integer_2 `` `` Integer_1 `` 2 .. 8;`\ `A : Integer_1 := 8;`\ `B : Integer_2 := A; ` Here both types are discrete; it is mandatory that the range of the derived type be included in the range of its parent. Contrast this with subtypes. The reason is that the derived type inherits the primitive operations defined for its parent, and these operations assume the range of the parent type. Here is an illustration of this feature: ` Derived_Types `\ \ `   `` Pak `\ `      `` Integer_1 `` `` 1 .. 10;`\ `      `` P (I: `` Integer_1); `\ `      `` Integer_2 `` `` Integer_1 `` 8 .. 10; `\ `      `\ `   `` Pak;`\ \ `   `` `` Pak `\ `      `\ `   `` Pak;`\ \ `   `` Pak;`\ `   A: Integer_1 := 4;`\ `   B: Integer_2 := 9;`\ \ \ \ `   P (B); `\ \ ` Derived_Types;` When we call `P (B)`, the parameter B is converted to `Integer_1`; this conversion of course passes since the set of acceptable values for the derived type (here, 8 .. 10) must be included in that of the parent type (1 .. 10). Then P is called with the converted parameter. Consider however a variant of the example above: ` Derived_Types `\ \ `  `` Pak `\ `    `` Integer_1 `` `` 1 .. 10;`\ `    `` P (I: `` Integer_1; J: `` Integer_1);`\ `    `` Integer_2 `` `` Integer_1 `` 8 .. 10;`\ `  `` Pak;`\ \ `  `` `` Pak `\ `    `` P (I: `` Integer_1; J: `` Integer_1) `\ `    `\ `      J := I - 1;`\ `    `` P;`\ `  `` Pak;`\ \ `  `` Pak;`\ \ `  A: Integer_1 := 4;  X: Integer_1;`\ `  B: Integer_2 := 8;  Y: Integer_2;`\ \ \ \ `  P (A, X);`\ `  P (B, Y);`\ \ ` Derived_Types;` When `P (B, Y)` is called, both parameters are converted to `Integer_1`. Thus the range check on J (7) in the body of P will pass. However on return parameter Y is converted back to `Integer_2` and the range check on Y will of course fail. With the above in mind, you will see why in the following program Constraint_Error will be called at run time, before `P` is even called. ` Derived_Types `\ \ `  `` Pak `\ `    `` Integer_1 `` `` 1 .. 10;`\ `    `` P (I: `` Integer_1; J: `` Integer_1);`\ `    `` Integer_2 `` `` Integer_1'Base `` 8 .. 12;`\ `  `` Pak;`\ \ `  `` `` Pak `\ `    `` P (I: `` Integer_1; J: `` Integer_1) `\ `    `\ `      J := I - 1;`\ `    `` P;`\ `  `` Pak;`\ \ `  `` Pak;`\ \ `  B: Integer_2 := 11;  Y: Integer_2;`\ \ \ \ `  P (B, Y);`\ \ ` Derived_Types;` ## Subtype categories Ada supports various categories of subtypes which have different abilities. Here is an overview in alphabetical order. ### Anonymous subtype A subtype which does not have a name assigned to it. Such a subtype is created with a variable declaration: `X : String (1 .. 10) := (`` => ' ');` Here, (1 .. 10) is the constraint. This variable declaration is equivalent to: ` Anonymous_String_Type `` String (1 .. 10);`\ \ `X : Anonymous_String_Type := (`` => ' ');` ### Base type In Ada, all types are anonymous and only subtypes may be named. For scalar types, there is a special subtype of the anonymous type, called the *base type*, which is nameable with the \' attribute. The base type comprises all values of the *first subtype*. Some examples: ` `` Int `` `` 0 .. 100;` The base type `Int'Base` is a hardware type selected by the compiler that comprises the values of `Int`. Thus it may have the range -2^7^ .. 2^7^-1 or -2^15^ .. 2^15^-1 or any other such type. ` `` Enum  `` (A, B, C, D);`\ ` `` Short `` `` Enum `` A .. C;` `Enum'Base` is the same as `Enum`, but `Short'Base` also holds the literal `D`. ### Constrained subtype A subtype of an indefinite subtype that adds constraints. The following example defines a 10 character string sub-type. ` `` String_10 `` String (1 .. 10);` You cannot partially constrain an unconstrained subtype: ` `` My_Array `` `` (Integer `` <>, Integer `` <>) `` Some_Type;`\ \ ` -- `` Constr `` My_Array (1 .. 10, Integer `` <>);  illegal`\ \ ` `` Constr `` My_Array (1 .. 10, -100 .. 200);` Constraints for all indices must be given, the result is necessarily a definite subtype. ### Definite subtype A definite subtype is a subtype whose size is known at compile-time. All subtypes which are not indefinite subtypes are, by definition, definite subtypes. Objects of definite subtypes may be declared without additional constraints. ### Indefinite subtype An **indefinite subtype** is a subtype whose size is not known at compile-time but is dynamically calculated at run-time. An indefinite subtype does not by itself provide enough information to create an object; an additional constraint or explicit initialization expression is necessary in order to calculate the actual size and therefore create the object. `X : String := "This is a string";` `X` is an object of the indefinite (sub)type `String`. Its constraint is derived implicitly from its initial value. `X` may change its value, but not its bounds. It should be noted that it is not necessary to initialize the object from a literal. You can also use a function. For example: `X : String := Ada.Command_Line.Argument (1);` This statement reads the first command-line argument and assigns it to `X`. A subtype of an indefinite subtype that does not add a constraint only introduces a new name for the original subtype (a kind of renaming under a different notion). ` `` My_String `` String;` `My_String` and `String` are interchangeable. ### Named subtype A subtype which has a name assigned to it. "First subtypes" are created with the keyword (remember that types are always anonymous, the name in a type declaration is the name of the first subtype), others with the keyword . For example: ` Count_To_Ten `` `` 1 .. 10;` `Count_to_Ten` is the first subtype of a suitable integer base type. However, if you would like to use this as an index constraint on `String`, the following declaration is illegal: ` Ten_Characters `` String (Count_to_Ten);` This is because `String` has `Positive` as its index, which is a subtype of `Integer` (these declarations are taken from package `Standard`): ` Positive `` Integer `` 1 .. Integer'Last;`\ \ ` String `` (Positive `` <>) `` Character;` So you have to use the following declarations: ` Count_To_Ten `` Integer `` 1 .. 10;`\ ` Ten_Characters `` String (Count_to_Ten);` Now `Ten_Characters` is the name of that subtype of `String` which is constrained to `Count_To_Ten`. You see that posing constraints on types versus subtypes has very different effects. ### Unconstrained subtype Any indefinite type is also an unconstrained subtype. However, unconstrainedness and indefiniteness are not the same. ` `` My_Enum `` (A, B, C);`\ ` `` My_Record (Discriminant: My_Enum) `` ...;`\ \ ` My_Object_A: My_Record (A);` This type is unconstrained and indefinite because you need to give an actual discriminant for object declarations; the object is constrained to this discriminant which may not change. When however a default is provided for the discriminant, the type is definite yet unconstrained; it allows to define both, constrained and unconstrained objects: ` `` My_Enum `` (A, B, C);`\ ` `` My_Record (Discriminant: My_Enum := A) `` ...;`\ \ ` My_Object_U: My_Record;      -- unconstrained object`\ ` My_Object_B: My_Record (B);  -- constrained to discriminant B like above` Here, My_Object_U is unconstrained; upon declaration, it has the discriminant A (the default) which however may change. ### Incompatible subtypes ` `` My_Integer `` `` -10 .. + 10;`\ ` `` My_Positive `` My_Integer `` + 1 .. + 10;`\ ` `` My_Negative `` My_Integer `` -10 .. -  1;` These subtypes are of course incompatible. Another example are subtypes of a discriminated record: ` `` My_Enum `` (A, B, C);`\ ` `` My_Record (Discriminant: My_Enum) `` ...;`\ ` `` My_A_Record `` My_Record (A);`\ ` `` My_C_Record `` My_Record (C);` Also these subtypes are incompatible. ## Qualified expressions In most cases, the compiler is able to infer the type of an expression; for example: ` Enum `` (A, B, C);`\ `E : Enum := A;` Here the compiler knows that `A` is a value of the type `Enum`. But consider: ` Bad `\ `   `` Enum_1 `` (A, B, C);`\ `   `` P (E : `` Enum_1) ``... `\ `   `` Enum_2 `` (A, X, Y, Z);`\ `   `` P (E : `` Enum_2) ``... `\ \ `   P (A); `\ ` Bad;` The compiler cannot choose between the two versions of `P`; both would be equally valid. To remove the ambiguity, you use a *qualified expression*: `   P (Enum_1'(A)); ` As seen in the following example, this syntax is often used when creating new objects. If you try to compile the example, it will fail with a compilation error since the compiler will determine that 256 is not in range of `Byte`. \ \ ` ``;`\ \ ` Convert_Evaluate_As `\ `   `` Byte     `` `` 2**8;`\ `   `` Byte_Ptr `` `` Byte;`\ \ `   `` T_IO `` ``;`\ `   `` M_IO `` `` `` (Byte);`\ \ `   A : `` Byte_Ptr := `` Byte'(256);`\ \ `   T_IO.Put ("A = ");`\ `   M_IO.Put (Item  => A.all,`\ `             Width =>  5,`\ `             Base  => 10);`\ ` Convert_Evaluate_As;` You should use qualified expression when getting a string literal\'s length. ``` ada "foo"'Length -- compilation error: prefix of attribute must be a name -- qualify expression to turn it into a name String'("foo" & "bar")'Length -- 6 ``` ## Type conversions Data do not always come in the format you need them. You must, then, face the task of converting them. As a true multi-purpose language with a special emphasis on \"mission critical\", \"system programming\" and \"safety\", Ada has several conversion techniques. The most difficult part is choosing the right one, so the following list is sorted in order of utility. You should try the first one first; the last technique is a last resort, to be used if all others fail. There are also a few related techniques that you might choose instead of actually converting the data. Since the most important aspect is not the result of a successful conversion, but how the system will react to an invalid conversion, all examples also demonstrate **faulty** conversions. ### Explicit type conversion An explicit type conversion looks much like a function call; it does not use the *tick* (apostrophe, \') like the qualified expression does. `Type_Name (`*`Expression`*`)` The compiler first checks that the conversion is legal, and if it is, it inserts a run-time check at the point of the conversion; hence the name *checked conversion*. If the conversion fails, the program raises Constraint_Error. Most compilers are very smart and optimise away the constraint checks; so, you need not worry about any performance penalty. Some compilers can also warn that a constraint check will always fail (and optimise the check with an unconditional raise). Explicit type conversions are legal: - between any two numeric types - between any two subtypes of the same type - between any two types derived from the same type (note special rules for tagged types) - between array types under certain conditions (see RM 4.6(24.2/2..24.7/2)) - and *nowhere else* (The rules become more complex with class-wide and anonymous access types.) `I: Integer := Integer (10);  `\ `J: Integer := 10;            `\ `K: Integer := Integer'(10);  `\ `                             ` This example illustrates explicit type conversions: \ \ ` ``;`\ \ ` Convert_Checked `\ `   `` Short `` `` -128 .. +127;`\ `   `` Byte  `` `` 256;`\ \ `   `` T_IO `` ``;`\ `   `` I_IO `` `` `` (Short);`\ `   `` M_IO `` `` `` (Byte);`\ \ `   A : Short := -1;`\ `   B : Byte;`\ \ `   B := Byte (A);  -- range check will lead to Constraint_Error`\ `   T_IO.Put ("A = ");`\ `   I_IO.Put (Item  =>  A,`\ `             Width =>  5,`\ `             Base  => 10);`\ `   T_IO.Put (", B = ");`\ `   M_IO.Put (Item  =>  B,`\ `             Width =>  5,`\ `             Base  => 10);`\ ` Convert_Checked;` Explicit conversions are possible between any two numeric types: integers, fixed-point and floating-point types. If one of the types involved is a fixed-point or floating-point type, the compiler not only checks for the range constraints (thus the code above will raise Constraint_Error), but also performs any loss of precision necessary. Example 1: the loss of precision causes the procedure to only ever print \"0\" or \"1\", since `P / 100` is an integer and is always zero or one. ` Ada.Text_IO;`\ ` Naive_Explicit_Conversion `\ `   `` Proportion `` `` 4 `` 0.0 .. 1.0;`\ `   `` Percentage `` `` 0 .. 100;`\ `   `` To_Proportion (P : `` Percentage) `` Proportion `\ `   `\ `      `` Proportion (P / 100);`\ `   `` To_Proportion;`\ \ `   Ada.Text_IO.Put_Line (Proportion'Image (To_Proportion (27)));`\ ` Naive_Explicit_Conversion;` Example 2: we use an intermediate floating-point type to guarantee the precision. ` Ada.Text_IO;`\ ` Explicit_Conversion `\ `   `` Proportion `` `` 4 `` 0.0 .. 1.0;`\ `   `` Percentage `` `` 0 .. 100;`\ `   `` To_Proportion (P : `` Percentage) `` Proportion `\ `      `` Prop `` `` 4 `` 0.0 .. 100.0;`\ `   `\ `      `` Proportion (Prop (P) / 100.0);`\ `   `` To_Proportion;`\ \ `   Ada.Text_IO.Put_Line (Proportion'Image (To_Proportion (27)));`\ ` Explicit_Conversion;` You might ask why you should convert between two subtypes of the same type. An example will illustrate this. ` String_10 `` String (1 .. 10);`\ `X: String := "A line long enough to make the example valid";`\ `Slice: `` String := String_10 (X (11 .. 20));` Here, `Slice` has bounds 1 and 10, whereas `X (11 .. 20)` has bounds 11 and 20. ### Change of Representation Type conversions can be used for packing and unpacking of records or arrays. ` Unpacked `` `\ `  `\ ` ``;`\ \ ` Packed `` `` Unpacked;`\ `  Packed `` `\ `  `\ ` ``;` `P: Packed;`\ `U: Unpacked;`\ \ `P := Packed (U);  `\ `U := Unpacked (P);  ` ### Checked conversion for non-numeric types The examples above all revolved around conversions between numeric types; it is possible to convert between any two numeric types in this way. But what happens between non-numeric types, e.g. between array types or record types? The answer is two-fold: - you can convert explicitly between a type and types derived from it, or between types derived from the same type, - and that\'s all. No other conversions are possible. Why would you want to derive a record type from another record type? Because of representation clauses. Here we enter the realm of low-level systems programming, which is not for the faint of heart, nor is it useful for desktop applications. So hold on tight, and let\'s dive in. Suppose you have a record type which uses the default, efficient representation. Now you want to write this record to a device, which uses a special record format. This special representation is more compact (uses fewer bits), but is grossly inefficient. You want to have a layered programming interface: the upper layer, intended for applications, uses the efficient representation. The lower layer is a device driver that accesses the hardware directly and uses the inefficient representation. ` Device_Driver `\ `   `` Size_Type `` `` 0 .. 64;`\ `   `` Register `` `\ `      A, B : Boolean;`\ `      Size : Size_Type;`\ `   `` ``;`\ \ `   `` Read (R : `` Register);`\ `   `` Write (R : `` Register);`\ ` Device_Driver;` The compiler chooses a default, efficient representation for `Register`. For example, on a 32-bit machine, it would probably use three 32-bit words, one for A, one for B and one for Size. This efficient representation is good for applications, but at one point we want to convert the entire record to just 8 bits, because that\'s what our hardware requires. ` `` Device_Driver `\ `   `` Hardware_Register `` `` Register; `\ `   `` Hardware_Register `` `\ `      A `` 0 `` 0 .. 0;`\ `      B `` 0 `` 1 .. 1;`\ `      Size `` 0 `` 2 .. 7;`\ `   `` ``;`\ \ `   `` Get `` Hardware_Register; `\ `   `` Put (H : `` Hardware_Register); `\ \ `   `` Read (R : `` Register) `\ `      H : Hardware_Register := Get;`\ `   `\ `      R := Register (H); `\ `   `` Read;`\ \ `   `` Write (R : `` Register) `\ `   `\ `      Put (Hardware_Register (R)); `\ `   `` Write;`\ ` Device_Driver;` In the above example, the package body declares a derived type with the inefficient, but compact representation, and converts to and from it. This illustrates that **type conversions can result in a change of representation**. ### View conversion, in object-oriented programming Within object-oriented programming you have to distinguish between *specific* types and *class-wide* types. With specific types, only conversions in the direction to the root are possible, which of course cannot fail. There are no conversions in the opposite direction `<small>`{=html}(where would you get the further components from?)`</small>`{=html}; *extension aggregates* have to be used instead. With the conversion itself, no components of the source object that are not present in the target object are lost, they are just hidden from visibility. Therefore, this kind of conversion is called a *view conversion* since it provides a view of the source object as an object of the target type (especially it does not change the object\'s tag). It is a common idiom in object oriented programming to rename the result of a view conversion. (A renaming declaration does not create a new object; it only gives a new name to something that already exists.) ` Parent_Type `` `` `\ `   ``<components>`{=html}`;`\ ` ``;`\ ` Child_Type `` `` Parent_Type `` `\ `   ``<further components>`{=html}`;`\ ` ``;`\ \ `Child_Instance : Child_Type;`\ `Parent_View    : Parent_Type `` Parent_Type (Child_Instance);`\ `Parent_Part    : Parent_Type := Parent_Type (Child_Instance);` `Parent_View` is not a new object, but another name for `Child_Instance` viewed as the parent, i.e. only the parent components are visible, the child-specific components are hidden. `Parent_Part`, however, is an object of the parent type, which of course has no storage for the child-specific components, so they are lost with the assignment. All types derived from a tagged type `T` form a tree rooted at `T`. The class-wide type `T'Class` can hold any object within this tree. With class-wide types, conversions in any direction are possible; there is a run-time tag check that raises `Constraint_Error` if the check fails. These conversions are also view conversions, no data is created or lost. `Object_1 : Parent_Type'`` := Parent_Type'`` (Child_Instance);`\ `Object_2 : Parent_Type'`` `` Parent_Type'`` (Child_Instance);` `Object_1` is a new object, a copy; `Object_2` is just a new name. Both objects are of the class-wide type. Conversions to any type within the given class are legal, but are tag-checked. `Success : Child_Type := Child_Type (Parent_Type'Class (Parent_View));`\ `Failure : Child_Type := Child_Type (Parent_Type'Class (Parent_Part));` The first conversion passes the tag check and both objects `Child_Instance` and `Success` are equal. The second conversion fails the tag check. `<small>`{=html}(Conversion assignments of this kind will rarely be used; dispatching will do this automatically, see object oriented programming.)`</small>`{=html} You can perform these checks yourself with membership tests: ` Parent_View `` Child_Type `` ...`\ ` Parent_View `` Child_Type'`` `` ...` There is also the package `Ada.Tags`. ### Address conversion Ada\'s access type is not just a memory location (a thin pointer). Depending on implementation and the access type used, the access might keep additional information (a fat pointer). For example GNAT keeps two memory addresses for each access to an indefinite object --- one for the data and one for the constraint informations `<small>`{=html}(, , \'\')`</small>`{=html}. If you want to convert an access to a simple memory location you can use the package . Note however that an address and a fat pointer cannot be converted reversibly into one another. The address of an array object is the address of its first component. Thus the bounds get lost in such a conversion. ` My_Array `` `` (Positive `` <>) `` Something;`\ `A: My_Array (50 .. 100);`\ \ `     A'`` = A(A'``)'` ### Unchecked conversion One of the great criticisms of Pascal was \"there is no escape\". The reason was that sometimes you have to convert the incompatible. For this purpose, Ada has the generic function *Unchecked_Conversion*: \ `   `` Source (<>) `` `` ``;`\ `   `` Target (<>) `` `` ``;`\ ` `` (S : Source) `` Target;` *`Unchecked_Conversion`* will bit-copy the source data and reinterpret them under the target type without any checks. It is **your** chore to make sure that the requirements on unchecked conversion as stated in RM are fulfilled; if not, the result is implementation dependent and may even lead to abnormal data. Use the \'Valid attribute after the conversion to check the validity of the data in problematic cases. A function call to (an instance of) `Unchecked_Conversion` will copy the source to the destination. The compiler may also do a conversion *in place* (every instance has the convention *Intrinsic*). To use `Unchecked_Conversion` you need to instantiate the generic. In the example below, you can see how this is done. When run, the example will output `A = -1, B = 255`. No error will be reported, but is this the result you expect? \ \ ` ``;`\ ` ``;`\ \ ` Convert_Unchecked `\ \ `   `` Short `` `` -128 .. +127;`\ `   `` Byte  `` `` 256;`\ \ `   `` T_IO `` ``;`\ `   `` I_IO `` `` `` (Short);`\ `   `` M_IO `` `` `` (Byte);`\ \ `   `` Convert `` `` `` (Source => Short,`\ `                                                     Target => Byte);`\ \ `   A : `` Short := -1;`\ `   B : Byte;`\ \ \ \ `   B := Convert (A);`\ `   T_IO.Put ("A = ");`\ `   I_IO.Put (Item  =>  A,`\ `             Width =>  5,`\ `             Base  => 10);`\ `   T_IO.Put (", B = ");`\ `   M_IO.Put (Item  =>  B,`\ `             Width =>  5,`\ `             Base  => 10);`\ \ ` Convert_Unchecked;` There is of course a range check in the assignment `B := Convert (A);`. Thus if `B` were defined as `B: Byte `` 0 .. 10;`, `Constraint_Error` would be raised. ### Overlays If the copying of the result of `Unchecked_Conversion` is too much waste in terms of performance, then you can try overlays, i.e. address mappings. By using overlays, both objects share the same memory location. If you assign a value to one, the other changes as well. The syntax is: ` Target'`` `` `*`expression`*`;`\ ` (Ada, Target);` where *expression* defines the address of the source object. While overlays might look more elegant than `Unchecked_Conversion`, you should be aware that they are even more dangerous and have even greater potential for doing something very wrong. For example if `Source'`` < Target'` and you assign a value to Target, you might inadvertently write into memory allocated to a different object. You have to take care also of implicit initializations of objects of the target type, since they would overwrite the actual value of the source object. The Import pragma with convention Ada can be used to prevent this, since it avoids the implicit initialization, RM . The example below does the same as the example from \"Unchecked Conversion\". \ \ ` ``;`\ \ ` Convert_Address_Mapping `\ `   `` Short `` `` -128 .. +127;`\ `   `` Byte  `` `` 256;`\ \ `   `` T_IO `` ``;`\ `   `` I_IO `` `` `` (Short);`\ `   `` M_IO `` `` `` (Byte);`\ \ `   A : `` Short;`\ `   B : `` Byte;`\ `  `\ `   `` B'`` `` A'``;`\ `  `` (Ada, B);`\ `  `\ \ `   A := -1;`\ `   T_IO.Put ("A = ");`\ `   I_IO.Put (Item  =>  A,`\ `             Width =>  5,`\ `             Base  => 10);`\ `   T_IO.Put (", B = ");`\ `   M_IO.Put (Item  =>  B,`\ `             Width =>  5,`\ `             Base  => 10);`\ ` Convert_Address_Mapping;` ### Export / Import Just for the record: There is still another method using the and pragmas. However, since this method completely undermines Ada\'s visibility and type concepts even more than overlays, it has no place here in this language introduction and is left to experts. ## Elaborated Discussion of Types for Signed Integer Types As explained before, a type declaration ` T `` `` 1 .. 10;` declares an anonymous type *`T`* and its first subtype `T` (please note the italicization). *`T`* encompasses the complete set of mathematical integers. Static expressions and named numbers make use of this fact. All numeric integer literals are of type `Universal_Integer`. They are converted to the appropriate specific type where needed. `Universal_Integer` itself has no operators. Some examples with static named numbers: ` S1: `` := Integer'`` + Integer'``;       `\ ` S2: `` := Long_Integer'`` + 1;             `\ ` S3: `` := S1 + S2;                           `\ ` S4: `` := Integer'`` + Long_Integer'``;  ` Static expressions are evaluated at compile-time on the appropriate types with no overflow checks, i.e. mathematically exact (only limited by computer store). The result is then implicitly converted to `Universal_Integer`. The literal 1 in `S2` is of type `Universal_Integer` and implicitly converted to `Long_Integer`. `S3` implicitly converts the summands to `root_integer`, performs the calculation and converts back to `Universal_Integer`. `S4` is illegal because it mixes two different types. You can however write this as ` S5: `` := Integer'Pos (Integer'``) + Long_Integer'Pos (Long_Integer'``);  ` where the Pos attributes convert the values to `Universal_Integer`, which are then further implicitly converted to `root_integer`, added and the result converted back to `Universal_Integer`. `root_integer` is the anonymous greatest integer type representable by the hardware. It has the range `System.Min_Integer .. System.Max_Integer`. All integer types are rooted at `root_integer`, i.e. derived from it. `Universal_Integer` can be viewed as `root_integer'Class`. During run-time, computations of course are performed with range checks and overflow checks on the appropriate subtype. Intermediate results may however exceed the range limits. Thus with `I, J, K` of the subtype `T` above, the following code will return the correct result: `I := 10;`\ `J :=  8;`\ `K := (I + J) - 12;`\ Real literals are of type `Universal_Real`, and similar rules as the ones above apply accordingly. ## Relations between types Types can be made from other types. Array types, for example, are made from two types, one for the arrays\' index and one for the arrays\' components. An array, then, expresses an association, namely that between one value of the index type and a value of the component type. ` `` Color `` (Red, Green, Blue);`\ ` `` Intensity `` `` 0 .. 255;`\ ` `\ ` `` Colored_Point `` `` (Color) `` Intensity;` The type `Color` is the index type and the type `Intensity` is the component type of the array type `Colored_Point`. See array. ## See also ### Wikibook - Ada Programming ### Ada Reference Manual - - - - - - - - System es:Programación en Ada/Tipos
# Ada Programming/Constants # Are Constants Constant? Variables and constants are declared like so: `X, Y: T := Some_Value;  -- Initialization optional`\ `C: `` T := Some_Value;` The initialization value for X and Y is evaluated separately for each one -- thus, if this is a function call, they may have different values. For the nomenclature: Ada calls variables and constants together \"objects\". Do not confuse this with the term \"objects\" used in OOP. It is good practice to declare local objects which do not change as constant. Silly question: What actually does \"constant\" mean? ` Swap (X, Y: `` T) `\ `  Temp: `` T := X;`\ \ `  X := Y;`\ `  Y := Temp;`\ ` Swap;` In the Swap example, the temporary copy of X certainly is constant -- we do not touch it. However (a triviality you'll say), it is not constant during construction nor during destruction at the end of Swap. Hold it! In the following, you will learn some astonishing facts about "constants" (objects with the keyword constant). ## First Doubts Let us sow first doubts about the constancy. Controlled types (RM 7.6) grant the programmer access to the process of construction, copy and destruction via the three operations Initialize, Adjust and Finalize. Given a controlled type T. `X: `` T := F;` After construction of X and its initialization with a copy of F, the operation Adjust is called with parameter mode in out for the constant object X. (Initialize is not called here because an initial value is given.) In Ada.\*\_IO (RM A.6-A.10), the file parameter of Create and Close has mode in out, of Read and Write (resp. Put and Get) it has in. But each of these operations does change the state of the file parameter. This reflects a design where the (internal) File object\'s \"state\" represents the open-ness of the File object, rather than the content of the (external) file. Agreed that this choice is debatable, but it is consistent across the I/O packages. The presumed implementation model implies a level of indirection, where the File parameter represents a reference, which is essentially \"null\" when the file is closed, and non-null when the file is open. Everything else is buried in some mysterious netherland whose state is not reflected in the mode of the File parameter. This is a symptom of any language that has pointer parameters whose mode has no effect on the ability to update the pointed-to object. So: **An object is not constant at least during construction and destruction.** But as you have seen with Ada.\*\_IO, a constant object can indeed change its state also during its lifetime. (An in parameter is like a constant within a subprogram.) **"The constant keyword means that the value never changes" -- this is a False statement for Ada** (the details are painful); it\'s true for elementary types and some others, but not for most composite types. You can find some interesting statements about this in Ada RM: RM 3.3(13/3, 25.1/3), 13.9.1(13/3). The corresponding terms are *immutably limited* and *inherently mutable*. ## Example Pointers `Pointer:`\ \ `  `` Rec `` `\ `    I: `` Integer;`\ `  `` ``;`\ `  Ob: `` Rec := (I => `` Integer'(42));`\ `  -- Ob.I is constant, but not Ob.I.all!`\ \ `  Ob.I.all := 53;`\ ` Pointer;` Here you will certainly agree with me that this is clear as daylight. But what about the case of an internal pointer accessing the whole object itself? `Reflexive:`\ \ `  `` Rec `` `` ``  -- immutably limited`\ `    -- Rosen technique (only possible on immutably limited types);`\ `    -- Ref is a variable view (Rec is aliased since it is limited).`\ `    Ref: `` Rec := Rec'Unchecked_Access;`\ `    I  : Integer;`\ `  `` ``;`\ `  Ob: `` Rec := (I => 42, Ref => <>);`\ \ `  Ob.I := 53;  -- illegal`\ `  Ob.Ref.I := 53;  -- erroneous until Ada 2005, legal for Ada 2012`\ ` Reflexive;` The object must be limited since copying would ruin the reference. Ada 2012 AARM 13.9.1(14.e/3): The Rosen trick (named after Jean Pierre Rosen) is no longer erroneous when the actual object is constant, but good practice. This applies to objects where there is necessarily a variable view at some point in the lifetime of the object which you can \"squirrel away\" for later use. This certainly does not happen \"by mistake\", the programmer does it on purpose. ` Controlled `\ `  `` Rec `` `` Ada.Finalization.Controlled `` `\ `    Ref: `` Rec;  -- variable view`\ `    I  : Integer;`\ `  `` ``;`\ `  `` `` Initialize (T: `` Rec);`\ `  `` `` Adjust     (T: `` Rec);`\ `  -- "in out" means they see a variable view of the object`\ `  -- (even if it's a constant)`\ ` Controlled;` You can use it like so: \ `  `` Create `` Controlled.Rec `` … `` Create;`\ `  Ob: `` Controlled.Rec := Create;`\ `  -- here, Adjust works on a constant on an assignment operation`\ \ `  Ob.Ref.I := 53;  -- Ob.I := 53;  illegal`\ `;` A copy of the return object Create is assigned to Ob, the object Create is finalized. Now the component Ref points to a no longer existing object. (Note the difference between *assignment statement* and *assignment operation*.) Adjust has to correct the wrong target. Create might look like this: ` Create `` Controlled.Rec `\ `  X: Controlled.Rec;  -- Initialize called`\ \ `  `` X;`\ ` Create;` The variable X is declared without an initial value, so Initialize is called. Create returns this self referencing object. This is the package body: ` `` Controlled `\ `  `` Initialize (T: `` Rec) `\ `  `\ `    T := (Ada.Finalization.Controlled `\ `          Ref => T'Unchecked_Access,`\ `          I   => 42);`\ `  `` Initialize;`\ `  `` Adjust (T: `` Rec) `\ `  `\ `    T.Ref := T'Unchecked_Access;`\ `  `` Adjust;`\ ` Controlled;` Initiallize is only called if no initial value is given in the object declaration. T is regarded as *aliased* so that the component Ref is a variable view of the object itself. ## Example Task and Protected Object Tasks are active objects, i.e. each task has its own thread of control: All tasks run concurrently. A task communicates with other tasks via rendezvous by calling one of its entries (roughly corresponding to a subprogram call). Since Ada is a block-oriented language, tasks may be defined as components of arrays and records, and these may be constants. ` `` TT `\ `  `` Set (I: Integer);`\ ` TT;`\ ` `` TT ``      -- local objects are not`\ `  I: Integer := 42;  -- considered part of constant`\ \ `  `` Set (I: Integer) `\ `    TT.I := I;`\ `  `` Set;`\ ` TT;`\ ` Rec `` `\ `  T: TT;  -- active object that changes state (even if "constant")`\ ` record;`\ `Ob: `` Rec := (T => <>);` `Ob.T.Set (53);  -- execution of an entry of a constant task` Protected objects are very similar to tasks. ` `` Prot `\ `  `` Set (I: Integer);`\ \ `  I: Integer := 42;  -- *`\ ` Prot;`\ ` `` Prot `\ `  `` Set (I: Integer) `\ `  `\ `    Prot.I := I;  -- Prot.I is *`\ `  `` Set;`\ ` Prot;`\ ` Rec `` `` `\ `  Ref: `` Rec := Rec'Unchecked_Access;  -- reflexive`\ `  P  : Prot;`\ ` ``;`\ `Ob: `` Rec := (`` => <>);` `Ob.P.Set (53);      -- illegal`\ `Ob.Ref.P.Set (53);  -- variable view required` ## Constants Are Like This If an object is declared "constant", the meaning is just twofold: - The object cannot be used in an assignment (if it is not yet limited). - The object can only be used as an in parameter. **In no case at all does it mean that the logical state of the object is immutable.** In fact, such a type should be _private_, which means _the client has no influence at all on what happens in the object's inside. The provider is responsible for the correct behavior._ *Immutably limited* and *controlled objects* are *inherently mutable*. # See also ## Wikibook - Ada Programming/Keywords/constant ## Ada Reference Manual - - Programming}}\|Constants es:Programación en Ada/Objetos
# Ada Programming/Representation clauses There are several forms to specify the representation of items. ## Attributes ` Day_Of_Month `` `` 1 .. 31;`\ `  Day_Of_Month'``      `` 8;  `\ `  Day_Of_Month'`` `` 1;  ` ## Records A record representation clause specifies the *Layout* aspect of a record. For any component, a *component clause* may be given specifying the location within the record object by its storage unit offset with respect to the address (called *Position*) and the bits occupied at this position (called *First_Bit* and *Last_Bit*): `Component_Name `` Position `` First_Bit .. Last_Bit;` These three expressions must be static, not negative and of any integer type; they have corresponding attributes **\'Position**, **\'First_Bit** and **\'Last_Bit**. Note that the bit range may extend well over storage unit boundaries. Components without a component clause are located at the compiler\'s choice. Example: ` Device_Register `` `\ `   Ready : Status_Flag;`\ `   Error : Error_Flag;`\ `   Data  : Unsigned_16;`\ ` ``;`\ \ `  Device_Register `` `\ `   Ready `` 0 ``  0 ..  0;`\ `   Error `` 0 ``  1 ..  1;`\ `   `\ `   Data  `` 0 `` 16 .. 31;`\ ` ``;` Alternatively with identical result: `  Device_Register `` `\ `   Ready `` 0 `` 0 ..  0;`\ `   Error `` 0 `` 1 ..  1;`\ `   `\ `   Data  `` 1 `` 0 .. 15;`\ ` ``;` The layout depends of course on whether the machine architecture is *little endian* or *big endian*. The corresponding attribute is called \'Bit_Order. For the Data component in the native bit order, **\'Position**, **\'First_Bit** and **\'Last_Bit** will in both cases return 1, 0 and 15. ### Biased Representation For certain components, a so-called *biased representation* may be possible. For the type T, the attribute \'Size will return 10, but since it has only eight values, three bits would suffice. This can be forced with the following specification: ` T `` `` 1000 .. 1007;` ` Rec `` `\ `   A: Integer `` 0 .. 1;`\ `   B: Boolean;`\ `   C: T;`\ ` ``;` ` Rec `` `\ `   B `` 0 `` 0 .. 1;`\ `   C `` 0 `` 4 .. 6;  `\ ` ``;` Note that no size clause is needed for type T. Thus, a *change of representation* is performed in either way when record components and stand-alone objects of type T are assigned to one another. Also note that for component `A` the compiler is free to choose any of the remaining bits of position 0, but may also use at position 1 as many bits as an integer requires in the given implementation. ## Enumerations An enumeration representation clause specifies the *Coding* aspect of an enumeration type with a named aggregate. ` Status_Flag ``  (Ready, Wait);`\ `  Status_Flag `` (Ready => 0, Wait => 1);  ` Another representation: `  Status_Flag `` (Ready => 0, Wait => 2#100#);` The expressions for the literals must be static and of any integer type. The values must not conflict with the order. ## The Aspect Pack The aspect Pack may be used for arrays and records. It specifies that for each component as many bits are used as the attribute \'Size applied to its subtype returns.
# Ada Programming/Strings Ada supports three different types of strings. Each string type is designed to solve a different problem. In addition, every string type is implemented for each available Characters type `<small>`{=html}(Character, Wide_Character, Wide_Wide_Character)`</small>`{=html} giving a complement of nine combinations. ## Fixed-length string handling Fixed-Length Strings (the predefined type String) are arrays of Character, and consequently of a fixed length. Since String is an indefinite subtype the length does not need to be known at compile time --- the length may well be calculated at run time. In the following example the length is calculated from command-line argument 1: `X : String := Ada.Command_Line.Argument (1);` However once the length has been calculated and the string has been created the length stays constant. Try the following program which shows a typical mistake: \ \ ` ``;`\ ` ``;`\ \ ` Show_Commandline_1 `\ \ `   `` T_IO `` ``;`\ `   `` CL   `` ``;`\ \ `   X : String := CL.Argument (1);`\ \ \ `   T_IO.Put ("Argument 1 = ");`\ `   T_IO.Put_Line (X);`\ \ `   X := CL.Argument (2);`\ \ `   T_IO.Put ("Argument 2 = ");`\ `   T_IO.Put_Line (X);`\ ` Show_Commandline_1;` The program will only work when the 1st and 2nd parameter have the same length. This is even true when the 2nd parameter is shorter. There is neither an automatic padding of shorter strings nor an automatic truncation of longer strings. Having said that, the package contains a set of procedures and functions for Fixed-Length String Handling which allows padding of shorter strings and truncation of longer strings. Try the following example to see how it works: ` ``;`\ ` ``;`\ ` ``;`\ \ ` Show_Commandline_2 `\ \ `   `` T_IO `` ``;`\ `   `` CL   `` ``;`\ `   `` S    `` ``;`\ `   `` SF   `` ``;`\ \ `   X : String := CL.Argument (1);`\ \ \ `   T_IO.Put ("Argument 1 = ");`\ `   T_IO.Put_Line (X);`\ \ `   SF.Move (`\ `     Source  => CL.Argument (2),`\ `     Target  => X,`\ `     Drop    => S.Right,`\ `     Justify => S.Left,`\ `     Pad     => S.Space);`\ \ `   T_IO.Put ("Argument 2 = ");`\ `   T_IO.Put_Line (X);`\ ` Show_Commandline_2;` ## Bounded-length string handling Bounded-Length Strings can be used when the maximum length of a string is known and/or restricted. This is often the case in database applications where only a limited number of characters can be stored. Like Fixed-Length Strings the maximum length does not need to be known at compile time --- it can also be calculated at runtime --- as the example below shows: \ \ ` ``;`\ ` ``;`\ ` ``;`\ \ ` Show_Commandline_3 `\ \ `   `` T_IO `` Ada.Text_IO;`\ `   `` CL   `` Ada.Command_Line;`\ \ `   `` Max_Length (`\ `      Value_1 : Integer;`\ `      Value_2 : Integer)`\ `   `\ `      Integer`\ `   `\ `      Retval : Integer;`\ `   `\ `      `` Value_1 > Value_2 `\ `         Retval := Value_1;`\ `      `\ `         Retval := Value_2;`\ `      `` ``;`\ `      `` Retval;`\ `   `` Max_Length;`\ \ `   `` Inline (Max_Length);`\ \ `   `` SB`\ `   `` `` Ada.Strings.Bounded.Generic_Bounded_Length (`\ `       Max => Max_Length (`\ `                  Value_1 => CL.Argument (1)'Length,`\ `                  Value_2 => CL.Argument (2)'Length));`\ \ `   X :  SB.Bounded_String`\ `     := SB.To_Bounded_String (CL.Argument (1));`\ \ \ `   T_IO.Put ("Argument 1 = ");`\ `   T_IO.Put_Line (SB.To_String (X));`\ \ `   X := SB.To_Bounded_String (CL.Argument (2));`\ \ `   T_IO.Put ("Argument 2 = ");`\ `   T_IO.Put_Line (SB.To_String (X));`\ ` Show_Commandline_3;` You should know that Bounded-Length Strings have some distinct disadvantages. Most noticeable is that each Bounded-Length String is a different type which makes converting them rather cumbersome. Also a Bounded-Length String type always allocates memory for the maximum permitted string length for the type. The memory allocation for a Bounded-Length String is equal to the maximum number of string \"characters\" plus an implementation dependent number containing the string length (each character can require allocation of more than one byte per character, depending on the underlying character type of the string, and the length number is 4 bytes long for the Windows GNAT Ada compiler v3.15p, for example). ## Unbounded-length string handling Last but not least there is the Unbounded-Length String. In fact: If you are not doing embedded or database programming this will be the string type you are going to use most often as it gives you the maximum amount of flexibility. As the name suggest the Unbounded-Length String can hold strings of almost any length --- limited only to the value of Integer\'Last or your available heap memory. This is because Unbounded_String type is implemented using dynamic memory allocation behind the scenes, providing lower efficiency but maximum flexibility. ` ``;`\ ` ``;`\ ` ``;`\ \ ` Show_Commandline_4 `\ \ `   `` T_IO `` Ada.Text_IO;`\ `   `` CL   `` Ada.Command_Line;`\ `   `` SU   `` Ada.Strings.Unbounded;`\ \ `   X :  SU.Unbounded_String `\ `     := SU.To_Unbounded_String (CL.Argument (1));`\ \ \ `   T_IO.Put ("Argument 1 = ");`\ `   T_IO.Put_Line (SU.To_String (X));`\ \ `   X := SU.To_Unbounded_String (CL.Argument (2));`\ \ `   T_IO.Put ("Argument 2 = ");`\ `   T_IO.Put_Line (SU.To_String (X));`\ ` Show_Commandline_4;` As you can see the Unbounded-Length String example is also the shortest `<small>`{=html}(disregarding the buggy first example)`</small>`{=html} --- this makes using Unbounded-Length Strings very appealing. ## See also ### Wikibook - Ada Programming ### Ada 95 Reference Manual - - - - - ### Ada 2005 Reference Manual - - - - - Programming}}\|Strings es:Programación en Ada/Tipos/Strings
# Ada Programming/Subprograms In Ada the subprograms are classified into two categories: procedures and functions. A procedures call is a statement and does not return any value, whereas a function returns a value and must therefore be a part of an expression. Subprogram parameters may have three modes. : The actual parameter value goes into the call and is not changed there; the formal parameter is a constant and allows only reading -- with a caveat, see Ada Programming/Constants. This is the default when no mode is given. The actual parameter can be an expression.\ : The actual parameter goes into the call and may be redefined. The formal parameter is a variable and can be read and written.\ : The actual parameter\'s value before the call is irrelevant, it will get a value in the call. The formal parameter can be read and written. (In Ada 83 parameters were write-only.) A parameter of any mode may also be explicitly . : The formal parameter is an access (a pointer) to some variable. (This is not a parameter mode from the reference manual point of view.) Note that parameter modes do not specify the parameter passing method. Their purpose is to document the data flow. The parameter passing method depends on the type of the parameter. A rule of thumb is that parameters fitting into a register are passed by copy, others are passed by reference. For certain types, there are special rules, for others the parameter passing mode is left to the compiler (which you can assume to do what is most sensible). Tagged types are always passed by reference. Explicitly parameters and parameters specify pass by reference. Unlike in the C class of programming languages, Ada subprogram calls cannot have empty parameters parentheses ` ` when there are no parameters. ## Procedures A procedure call in Ada constitutes a statement by itself. For example: ` A_Test ``A, B: `` Integer; C: `` Integer`` `\ \ `   C := A + B;`\ ` A_Test;` When the procedure is called with the statement `A_Test (5 + P, 48, Q);` the expressions 5 + P and 48 are evaluated (expressions are only allowed for in parameters), and then assigned to the formal parameters A and B, which behave like constants. Then, the value A + B is assigned to formal variable C, whose value will be assigned to the actual parameter Q when the procedure finishes. C, being an parameter, is an uninitialized variable before the first assignment. (Therefore in Ada 83, there existed the restriction that parameters are write-only. If you wanted to read the value written, you had to declare a local variable, do all calculations with it, and finally assign it to C before return. This was awkward and error prone so the restriction was removed in Ada 95.) Within a procedure, the return statement can be used without arguments to exit the procedure and return the control to the caller. For example, to solve an equation of the kind $ax^2 + bx + c = 0$: ` ``;`\ `  ``;`\ \ ` Quadratic_Equation`\ `   ``A, B, C :     Float;   `\ `    R1, R2  : `` Float;`\ `    Valid   : `` Boolean`\ \ `   Z : Float;`\ \ `   Z := B**2 - 4.0 * A * C;`\ `   `` Z < 0.0 `` A = 0.0 `\ `      Valid := False;  `\ `      R1    := 0.0;`\ `      R2    := 0.0;`\ `   `\ `      Valid := True;`\ `      R1    := (-B + Sqrt (Z)) / (2.0 * A);`\ `      R2    := (-B - Sqrt (Z)) / (2.0 * A);`\ `   `` ``;`\ ` Quadratic_Equation;` The function SQRT calculates the square root of non-negative values. If the roots are real, they are given back in R1 and R2, but if they are complex or the equation degenerates (A = 0), the execution of the procedure finishes after assigning to the Valid variable the False value, so that it is controlled after the call to the procedure. Notice that the parameters should be modified at least once, and that if a mode is not specified, it is implied . ## Functions A function is a subprogram that can be invoked as part of an expression. Until Ada 2005, functions can only take (the default) or parameters; the latter can be used as a work-around for the restriction that functions may not have parameters. Ada 2012 has removed this restriction. Here is an example of a function body: ` Minimum (A, B: Integer) `` Integer `\ \ `   `` A <= B `\ `      `` A;`\ `   `\ `      `` B;`\ `   `` ``;`\ ` Minimum;` (There is, by the way, also the attribute `Integer'Min`, see RM 3.5.) Or in Ada2012: ` Minimum (A, B: Integer) `` Integer `\ \ `   `` (`` A <= B `` A `` B);`\ ` Minimum;` or even shorter as an *expression function* ` Minimum (A, B: Integer) `` Integer `` (`` A <= B `` A `` B);` The formal parameters with mode behave as local constants whose values are provided by the corresponding actual parameters. The statement is used to indicate the value returned by the function call and to give back the control to the expression that called the function. The expression of the statement may be of arbitrary complexity and must be of the same type declared in the specification. If an incompatible type is used, the compiler gives an error. If the restrictions of a subtype are not fulfilled, e.g. a range, it raises a Constraint_Error exception. The body of the function can contain several statements and the execution of any of them will finish the function, returning control to the caller. If the flow of control within the function branches in several ways, it is necessary to make sure that each one of them is finished with a statement. If at run time the end of a function is reached without encountering a statement, the exception Program_Error is raised. Therefore, the body of a function must have at least one such statement. Every call to a function produces a new copy of any object declared within it. When the function finalizes, its objects disappear. Therefore, it is possible to call the function recursively. For example, consider this implementation of the factorial function: ` Factorial (N : Positive) `` Positive `\ \ `   `` N = 1 `\ `      `` 1;`\ `   `\ `      `` (N * Factorial (N - 1));`\ `   `` ``;`\ ` Factorial;` When evaluating the expression `Factorial (4);` the function will be called with parameter 4 and within the function it will try to evaluate the expression `Factorial (3)`, calling itself as a function, but in this case parameter N would be 3 (each call copies the parameters) and so on until N = 1 is evaluated which will finalize the recursion and then the expression will begin to be completed in the reverse order. A formal parameter of a function can be of any type, including vectors or records. Nevertheless, it cannot be an anonymous type, that is, its type must be declared before, for example: ` Float_Vector `` `` (Positive `` <>) `` Float;`\ \ ` Add_Components (V: Float_Vector) `` Float `\ `   Result : Float := 0.0;`\ \ `   `` I `` V'`` `\ `      Result := Result + V(I);`\ `   `` ``;`\ `   `` Result;`\ ` Add_Components;` In this example, the function can be used on a vector of arbitrary dimension. Therefore, there are no static bounds in the parameters passed to the functions. For example, it is possible to be used in the following way: `V4  : Float_Vector (1 .. 4) := (1.2, 3.4, 5.6, 7.8);`\ `Sum : Float;`\ \ `Sum := Add_Components (V4);` In the same way, a function can also return a type whose bounds are not known a priori. For example: ` Invert_Components (V : Float_Vector) `` Float_Vector `\ `   Result : Float_Vector(V'``);   `\ \ `   `` I `` V'`` `\ `      Result(I) := V (V'`` + V'`` - I);`\ `   `` ``;`\ `   `` Result;`\ ` Invert_Components; ` The variable Result has the same bounds as V, so the returned vector will always have the same dimension as the one passed as parameter. A value returned by a function can be used without assigning it to a variable, it can be referenced as an expression. For example, `Invert_Components (V4) (1)`, where the first element of the vector returned by the function would be obtained (in this case, the last element of V4, i.e. 7.8). ## Named parameters In subprogram calls, named parameter notation (i.e. the name of the formal parameter followed of the symbol and then the actual parameter) allows the rearrangement of the parameters in the call. For example: `Quadratic_Equation (Valid => OK, A => 1.0, B => 2.0, C => 3.0, R1 => P, R2 => Q);`\ `F := Factorial (N => (3 + I));` This is especially useful to make clear which parameter is which. `Phi := Arctan (A, B);`\ `Phi := Arctan (Y => A, X => B);` The first call (from Ada.Numerics.Elementary_Functions) is not very clear. One might easily confuse the parameters. The second call makes the meaning clear without any ambiguity. Another use is for calls with numeric literals: `Ada.Float_Text_IO.Put_Line (X, 3, 2, 0);  -- ?`\ `Ada.Float_Text_IO.Put_Line (X, Fore => 3, Aft => 2, Exp => 0);  -- OK` ## Default parameters On the other hand, formal parameters may have default values. They can, therefore, be omitted in the subprogram call. For example: ` By_Default_Example (A, B: `` Integer := 0);` can be called in these ways: `By_Default_Example (5, 7);      `\ `By_Default_Example (5);         `\ `By_Default_Example;             `\ `By_Default_Example (B => 3);    `\ `By_Default_Example (1, B => 2); ` In the first statement, a \"regular call\" is used (with positional association); the second also uses positional association but omits the second parameter to use the default; in the third statement, all parameters are by default; the fourth statement uses named association to omit the first parameter; finally, the fifth statement uses mixed association, here the positional parameters have to precede the named ones. Note that the default expression is evaluated once for each formal parameter that has no actual parameter. Thus, if in the above example a function would be used as defaults for A and B, the function would be evaluated once in case 2 and 4; twice in case 3, so A and B could have different values; in the others cases, it would not be evaluated. ## Renaming Subprograms may be renamed. The parameter and result profile for a renaming-as-declaration must be mode conformant. ` Solve`\ `  (A, B, C: ``  Float;`\ `   R1, R2 : `` Float;`\ `   Valid  : `` Boolean) `` Quadratic_Equation;` This may be especially comfortable for tagged types. ` Some_Package `\ `  `` Message_Type `` `` `` ``;`\ `  `` Print (Message: `` Message_Type);`\ ` Some_Package; ` ` Some_Package;`\ ` Main `\ `  Message: Some_Package.Message_Type;`\ `  `` Print `` Message.Print;  `\ `  ``<s>`{=html}`Method_Ref: `` `` := Print'``;``</s>`{=html}`  `\ `  `\ `  Some_Package.Print (Message);  `\ `  Message.Print;                 `\ `  Print;                         `\ `  ``<s>`{=html}`Method_Ref.``;``</s>`{=html}`                `\ `                                 `\ ` Main;` But note that `Message.Print'``;` is illegal, you have to use a renaming declaration as above. Since only mode conformance is required (and not full conformance as between specification and body), parameter names and default values may be changed with renamings: `P (X: ``Integer :=  0);`\ `R (A: ``Integer := -1) ``P;` ## See also ### Wikibook - Ada Programming - Ada Programming/Operators ### Ada 95 Reference Manual - - ### Ada 2005 Reference Manual - - ### Ada Quality and Style Guide - Programming}}\|Subprograms es:Programación en Ada/Subprogramas
# Ada Programming/Packages Ada encourages the division of code into separate modules called *packages*. Each package can contain any combination of items. Some of the benefits of using packages are: - package contents are placed in a separate namespace, preventing naming collisions, - implementation details of the package can be hidden from the programmer (information hiding), - object orientation requires defining a type and its primitive subprograms within a package, and - packages that are library units can be separately compiled. Some of the more common package usages are: - a group of related subprograms along with their shared data, with the data not visible outside the package, - one or more data types along with subprograms for manipulating those data types, and - a generic package that can be instantiated under varying conditions. The following is a quote from the current Ada Reference Manual ## Separate compilation Note: The following chapters deal with packages on *library level*. This is the most common use, since packages are the basic code structuring means in Ada. However, Ada being a block oriented language, packages can be declared at any level in any declarative region. In this case, the normal visibility rules apply, also for the package body. Package specifications and bodies on library level are compilation units, so can be separately compiled. Ada has nothing to say about how and where compilation units are stored. This is implementation dependent. (Most implementations indeed store compilation units in files of their own; name suffixes vary, GNAT uses `.ads` and `.adb`, APEX `.1.ada` and `.2.ada`.) The package body can itself be divided into multiple parts by specifying that subprogram implementations or bodies of nested packages are **separate**. These are then further compilation units. One of the biggest advantages of Ada over most other programming languages is its well-defined system of modularization and separate compilation. Even though Ada allows separate compilation, it maintains the strong type checking among the various compilations by enforcing rules of compilation order and compatibility checking. Ada compilers determine the compilation sequence; no make file is needed. Ada uses separate compilation (like Modula-2, Java and C#), and not independent compilation (as C/C++ does), in which the various parts are compiled with no knowledge of the other compilation units with which they will be combined. A note to C/C++ users: Yes, you can use the preprocessor to emulate separate compilation --- but it is only an emulation and the smallest mistake leads to very hard to find bugs. It is telling that all C/C++ successor languages including D have turned away from the independent compilation and the use of the preprocessor. So it\'s good to know that Ada has had separate compilation ever since Ada-83 and is probably the most sophisticated implementation around. ## Parts of a package A package generally consists of two parts, the specification and the body. A package specification can be further divided in two logical parts, the visible part and the private part. Only the visible part of the specification is mandatory. The private part of the specification is optional, and a package specification might not have a package body---the package body only exists to complete any *incomplete* items in the specification. Subprogram declarations are the most common *incomplete* items. There must not be a package body if there is no incomplete declaration, and there has to be a package body if there is some incomplete declaration in the specification. To understand the value of the three-way division, consider the case of a package that has already been released and is in use. A change to the visible part of the specification will require that the programmers of all using software verify that the change does not affect the using code. A change to the private part of the declaration will require that all using code be recompiled but no review is normally needed. Some changes to the private part can change the meaning of the client code however. An example is changing a private record type into a private access type. This change can be done with changes in the private part, but change the semantic meaning of assignment in the clients code. A change to the package body will only require that the file containing the package body be recompiled, because *nothing* outside of the package body can ever access anything within the package body (beyond the declarations in the specification part). A common usage of the three parts is to declare the existence of a type and some subprograms that operate on that type in the visible part, define the actual structure of the type (e.g. as a record) in the private part, and provide the code to implement the subprograms in the package body. ### The package specification --- the visible part The visible part of a package specification describes all the subprogram specifications, variables, types, constants etc. that are visible to anyone who wishes to use the package. ` Public_Only_Package `\ \ `  `` Range_10 `` `` 1 .. 10;`\ \ ` Public_Only_Package;` Since Range_10 is an integer type, there are a lot of operations declared implicitly in this package. ### The private part The private part of a package serves two purposes: - To complete the deferred definition of private types and constants. - To export entities only visible to the children of the package. ` Package_With_Private `\ `     `\ `   `` Private_Type `` ``;`\ \ \ \ `   `` Private_Type `` `` (1 .. 10) `` Integer;`\ \ ` Package_With_Private;` Since the type is private, clients cannot make any use of it as long as there are no operations defined in the visible part. ### The package body The package body defines the implementation of the package. All the subprograms defined in the specification have to be implemented in the body. New subprograms, types and objects can be defined in the body that are not visible to the users of the package. ` Package_With_Body `\ \ `   `` Basic_Record `` ``;`\ \ `   `` Set_A (This : `` `` Basic_Record;`\ `                    An_A : ``     Integer);`\ \ `   `` Get_A (This : Basic_Record) `` Integer;`\ \ \ \ `   `` Basic_Record `` `\ `      `` `\ `         A : Integer;`\ `      `` `` ;`\ \ `   ``  (Get_A);  -- not a standard Ada pragma`\ `   `` (Get_A);`\ `   `` (Set_A);`\ \ ` Package_With_Body;` ` `` Package_With_Body `\ \ `   `` Set_A (This : `` `` Basic_Record;`\ `                    An_A : ``     Integer) `\ `   `\ `      This.A := An_A;`\ `   `` Set_A;`\ \ `   `` Get_A (This : Basic_Record) `` Integer `\ `   `\ `      `` This.A;`\ `   `` Get_A;`\ \ ` Package_With_Body;` : Only available when using GNAT. ### Two Flavors of Package The packages above each define a type together with operations of the type. When the type\'s composition is placed in the private part of a package, the package then exports what is known to be an Abstract Data Type or ADT for short. Objects of the type are then constructed by calling one of the subprograms associated with the respective type. A different kind of package is the Abstract State Machine or ASM. A package will be modeling a single item of the problem domain, such as the motor of a car. If a program controls one car, there is typically just one motor, or *the* motor. The public part of the package specification only declares the operations of the module (of the motor, say), but no type. All data of the module are hidden in the body of the package where they act as state variables to be queried, or manipulated by the subprograms of the package. The initialization part sets the state variables to their initial values. ` Package_With_Body `\ \ `   `` Set_A ``An_A `` `` Integer`\ \ `   `` Get_A `` Integer`\ \ \ \ `   `` Pure_Function ``Get_A``—not a standard Ada pragma`\ \ ` Package_With_Body` ` `` Package_With_Body `\ \ `   The_A`` Integer`\ \ `   `` Set_A ``An_A `` `` Integer`` `\ `   `\ `      The_A `` An_A`\ `   `` Set_A`\ \ `   `` Get_A `` Integer `\ `   `\ `      `` The_A`\ `   `` Get_A`\ \ \ \ \ `   The_A `` 0`\ \ ` Package_With_Body` (A note on construction: The package initialization part after corresponds to a construction subprogram of an ADT package. However, as a state machine *is* an "object" already, "construction" is happening during package initialization. (Here it sets the state variable `The_A` to its initial value.) An ASM package can be viewed as a singleton.) ## Using packages To utilize a package it\'s needed to name it in a **with** clause, whereas to have direct visibility of that package it\'s needed to name it in a **use** clause. For C++ programmers, Ada\'s **with** clause is analogous to the C++ preprocessor\'s **#include** and Ada\'s **use** is similar to the **using namespace** statement in C++. In particular, **use** leads to the same namespace pollution problems as **using namespace** and thus should be used sparingly. Renaming can shorten long compound names to a manageable length, while the **use type** clause makes a type\'s operators visible. These features reduce the need for plain **use**. ### Standard with The standard with clause provides visibility for the public part of a unit to the following defined unit. The imported package can be used in any part of the defined unit, including the body when the clause is used in the specification. ### Private with ` `` Ada.Strings.Unbounded; `\ \ ` Private_With `\ \ `   `\ \ `   `` Basic_Record `` ``;`\ \ `   `` Set_A (This : `` `` Basic_Record;`\ `                    An_A : ``     String);`\ \ `   `` Get_A (This : Basic_Record) `` String;`\ \ \ `   `\ \ `   `` Unbounded `` Ada.Strings.Unbounded;`\ \ `   `` Basic_Record `` `\ `      `` `\ `         A : Unbounded.Unbounded_String;`\ `      `` ``;`\ \ `   ``  (Get_A);`\ `   `` (Get_A);`\ `   `` (Set_A);`\ \ ` Private_With;` ` `` Private_With `\ \ `   `\ \ `   `` Set_A (This : `` `` Basic_Record;`\ `                    An_A : ``     String)`\ `   `\ `   `\ `      This.A := Unbounded.To_Unbounded_String (An_A);`\ `   `` Set_A;`\ \ `   `` Get_A (This : Basic_Record) `` String `\ `   `\ `      `` Unbounded.To_String (This.A);`\ `   `` Get_A;`\ \ ` Private_With;` ### Limited with The limited with can be used to represent two mutually dependent type (or more) located in separate packages. ` `` Departments;`\ \ ` Employees `\ \ `   `` Employee `` `` ``;`\ \ `   `` Assign_Employee`\ `     (E : `` `` Employee;`\ `      D : `` Departments.Department'``);`\ \ `   `` Dept_Ptr `` `` `` Departments.Department'``;`\ \ `   `` Current_Department(E : `` Employee) `` Dept_Ptr;`\ `   ...`\ ` Employees;` ` `` Employees;`\ \ ` Departments `\ \ `   `` Department `` `` ``;`\ \ `   `` Choose_Manager`\ `     (Dept    : `` `` Department;`\ `      Manager : `` Employees.Employee'``);`\ `   ...`\ ` Departments;` ### Making operators visible Suppose you have a package Universe that defines some numeric type T. ` Universe`\ ` P `\ `  V`` Universe``T `` 10``0`\ \ `  V `` V `` 42``0``  `\ ` P` This program fragment is illegal since the operators implicitly defined in Universe are not directly visible. You have four choices to make the program legal. Use a use_package_clause. This makes **all declarations** in Universe directly visible (provided they are not hidden because of other homographs). ` Universe`\ `  Universe`\ ` P `\ `  V`` Universe``T `` 10``0`\ \ `  V `` V `` 42``0`\ ` P` Use renaming. This is error prone since if you rename many operators, cut and paste errors are probable. ` Universe`\ ` P `\ `  `` "*" ``Left`` Right`` Universe``T`` `` Universe``T `` Universe``"*"`\ `  `` "/" ``Left`` Right`` Universe``T`` `` Universe``T `` Universe``"*"``  `\ `  V`` Universe``T `` 10``0`\ \ `  V `` V `` 42``0`\ ` P` Use qualification. This is extremely ugly and unreadable. ` Universe`\ ` P `\ `  V`` Universe``T `` 10``0`\ \ `  V `` Universe``"*" ``V`` 42``0`\ ` P` Use the use_type_clause. This makes only the **operators** in Universe directly visible. ` Universe`\ ` P `\ `  V`` Universe``T `` 10``0`\ `  `` `` Universe``T`\ \ `  V `` V `` 42``0`\ ` P` There is a special beauty in the use_type_clause. Suppose you have a set of packages like so: ` Universe`\ ` Pack `\ `  `` T `` Universe``T`\ ` Pack` ` Pack`\ ` P `\ `  V`` Pack``T `` 10``0`\ \ `  V `` V `` 42``0``  `\ ` P` Now you\'ve got into trouble. Since Universe is not made visible, you cannot use a use_package_clause for Universe to make the operator directly visible, nor can you use qualification for the same reason. Also a use_package_clause for Pack does not help, since the operator is not defined in Pack. The effect of the above construct means that the operator is not nameable, i.e. it cannot be renamed in a renaming statement. Of course you can add Universe to the context clause, but this may be impossible due to some other reasons (e.g. coding standards); also adding the operators to Pack may be forbidden or not feasible. So what to do? The solution is simple. Use the use_type_clause for Pack.T and all is well! ` Pack`\ ` P `\ `  V`` Pack``T `` 10``0`\ `  `` `` Pack``T`\ \ `  V `` V `` 42``0`\ ` P` ## Package organisation ### Nested packages A nested package is a package declared inside a package. Like a normal package, it has a public part and a private part. From outside, items declared in a nested package N will have visibility as usual; the programmer may refer to these items using a full dotted name like `P.N.X`. (But not `P.M.Y`.) ` P `\ `   D`` Integer`\ \ `   `\ `   `` N `\ `      X`` Integer`\ `   `\ `      Foo`` Integer`\ `   `` N`\ \ `   E`` Integer`\ \ `   `\ `   `` M `\ `      Y`` Integer`\ `   `\ `      Bar`` Integer`\ `   `` M`\ \ ` P` Inside a package, declarations become visible as they are introduced, in textual order. That is, a nested package N that is declared *after* some other declaration D can refer to this declaration D. A declaration E following N can refer to items of N.[^1] But neither can "look ahead" and refer to any declaration that goes after them. For example, spec `N` above cannot refer to `M` in any way. In the following example, a type is derived in both of the two nested packages `Disks` and `Books`. Notice that the full declaration of parent type `Item` appears before the two nested packages. ` `` `` `\ \ ` Shelf `\ \ `   `` Elaborate_Body`\ \ `   `\ \ `   `` ID `` `` 1_000 `` 9_999`\ `   `` Item ``Identifier `` ID`` `` `` `` `` `` `\ `   `` Item_Ref `` `` `` Item`\ \ `   `` Next_ID `` ID`\ `   `\ \ \ `   `` Disks `\ \ `      `` Music `` `\ `         Jazz`\ `         Rock`\ `         Raga`\ `         Classic`\ `         Pop`\ `         Soul`\ \ `      `` Disk ``Style `` Music`` Identifier `` ID`` `` `` Item ``Identifier`\ `         `` `\ `            Artist `` Unbounded_String`\ `            Title  `` Unbounded_String`\ `         `` `\ \ `   `` Disks`\ \ \ `   `` Books `\ \ `      `` Literature `` `\ `         Play`\ `         Novel`\ `         Poem`\ `         Story`\ `         Text`\ `         Art`\ \ `      `` Book ``Kind `` Literature`` Identifier `` ID`` `` `` Item ``Identifier`\ `         `` `\ `            Authors `` Unbounded_String`\ `            Title   `` Unbounded_String`\ `            Year    `` Integer`\ `         `` `\ \ `   `` Books`\ \ `   `\ \ `   `` Put ``it`` Item_Ref`\ `   `` Get ``identifier `` ID`` `` Item_Ref`\ `   `` Search ``title `` String`` `` ID`\ \ \ \ `   `\ \ `   `` Boxes `\ `      `` Treasure``Identifier`` ID`` `` `` `\ `   `\ `      `` Treasure``Identifier`` ID`` `` `` Item``Identifier`` `` `` `\ `   `` Boxes`\ \ ` Shelf` A package may also be nested inside a subprogram. In fact, packages can be declared in any declarative part, including those of a block. ### Child packages Ada allows one to extend the functionality of a unit (package) with so-called children (child packages). With certain exceptions, all the functionality of the parent is available to a child. This means that all public and private declarations of the parent package are visible to all child packages. The above example, reworked as a hierarchy of packages, looks like this. Notice that the package is not needed by the top level package `Shelf`, hence its with clause doesn\'t appear here. (We have added a match function for searching a shelf, though): ` Shelf `\ \ `   `` Elaborate_Body`\ \ `   `` ID `` `` 1_000 `` 9_999`\ `   `` Item ``Identifier `` ID`` `` `` `` `` `` `\ `   `` Item_Ref `` `` `` Item`\ \ `   `` Next_ID `` ID`\ `   `\ \ `   `` match ``it `` Item`` Text `` String`` `` Boolean `` `\ `   `\ \ \ `   `\ \ `   `` Put ``it`` Item_Ref`\ `   `` Get ``identifier `` ID`` `` Item_Ref`\ `   `` Search ``title `` String`` `` ID`\ \ ` Shelf` The name of a child package consists of the parent unit\'s name followed by the child package\'s identifier, separated by a period (dot) \`\'. ` `` `` `\ \ ` Shelf``Books `\ \ `   `` Literature `` `\ `      Play`\ `      Novel`\ `      Poem`\ `      Story`\ `      Text`\ `      Art`\ \ `   `` Book ``Kind `` Literature`` Identifier `` ID`` `` `` Item ``Identifier`\ `      `` `\ `         Authors `` Unbounded_String`\ `         Title   `` Unbounded_String`\ `         Year    `` Integer`\ `      `` `\ \ `   `` match``it`` Book`` text`` String`` `` Boolean`\ \ ` Shelf``Books` `Book` has two components of type `Unbounded_String`, so appears in a with clause of the child package. This is unlike the nested packages case which requires that all units needed by any one of the nested packages be listed in the context clause of the enclosing package (see ). Child packages thus give better control over package dependences. With clauses are more local. The new child package `Shelf.Disks` looks similar. The `Boxes` package which was a nested package in the private part of the original `Shelf` package is moved to a private child package: ` `` Shelf``Boxes `\ `    `` Treasure``Identifier`` ID`` `` `` `\ \ `    `` Treasure``Identifier`` ID`` `` `` Item``Identifier`` `` `` `\ `    `` match``it`` Treasure`` text`` String`` `` Boolean`\ ` Shelf``Boxes` The privacy of the package means that it can only be used by equally private client units. These clients include private siblings and also the bodies of siblings (as bodies are never public). Child packages may be listed in context clauses just like normal packages. A of a child also \'withs\' the parent. ### Subunits A subunit is just a feature to move a body into a place of its own when otherwise the enclosing body will become too large. It can also be used for limiting the scope of context clauses. The subunits allow to physically divide a package into different compilation units without breaking the logical unity of the package. Usually each separated subunit goes to a different file allowing separate compilation of each subunit and independent version control history for each one. ` `` `` Pack `\ `   `` Proc `` `\ ` `` Pack`\ \ ` `` Some_Unit`\ ` `` ``Pack`\ ` `` Proc `\ ` `\ `   ...`\ ` `` Proc` ## Notes ```{=html} <references/> ``` ## See also ### Wikibook - Ada Programming ### Wikipedia - Module "wikilink") ### Ada 95 Reference Manual - ### Ada 2005 Reference Manual - Programming}}\|Packages Ada Programming}}/Unfinished module\|Packages es:Programación en Ada/Paquetes [^1]: For example, `E: Integer := D + N.X;`
# Ada Programming/Input Output ## Overview The standard Ada libraries provide several Input/Output facilities, each one adapted to specific needs. Namely, the language defines the following dedicated packages: - Text_IO - Sequential_IO - Direct_IO - Stream_IO The programmer must choose the adequate package depending on the application needs. For example, the following properties of the data handled by the application should be considered: - **Data contents**: plain text, or binary data? - **Accessing the data**: random access, or sequential access? - **Medium**: data file, console, network/data-bus? - **Data structure**: homogeneous file (sequence of the same data field), heterogeneous file (different data fields)? - **Data format**: adherence to an existing data format, or the application can freely choose a new one? For example, Stream_IO is very powerful and can handle complex data structures but can be heavier than other packages; Sequential_IO is lean and easy to use but cannot be used by applications requiring random data access; Text_IO can handle just textual data, but it is enough for handling the command-line console. The following table gives some advices for choosing the more adequate one: Data access Plain text Binary data ------------- --------------- --------------- Homogeneous Heterogeneous Sequential Text_IO Sequential_IO Random Stream_IO Direct_IO : **Simple heuristics for choosing an I/O package** So the most important lesson to learn is choosing the right one. This chapter will describe more in detail these standard packages, explaining how to use them effectively. Besides these Ada-defined packages for general I/O operations each Ada compiler usually has other implementation-defined Input-Output facilities, and there are also other external libraries for specialized I/O needs like XML processing or interfacing with databases. ## Text I/O Text I/O is probably the most used Input/Output package. All data inside the file are represented by human readable text. Text I/O provides support for line and page layout but the standard is free form text. ` `\ ` `\ ` Main `\ `  Str  `` String ``1 `` 80`\ `  Last `` Natural`\ \ `  Ada``Text_IO``Get_Line ``Str`` Last`\ `  Ada``Text_IO``Put_Line ``Str ``1 `` Last`\ This example copies text from standard input to standard output when all lines are shorter than 80 characters, the string length. See package Text I/O how to deal with longer lines. The package also contains several generic packages for converting numeric and enumeration types to character strings; there are child packages for handling Bounded and Unbounded strings, allowing the programmer to read and write different data types in the same file easily (there are ready-to-use instantiations of these generic packages for the Integer, Float, and Complex types). Finally, the same family of Ada.Text_IO packages (including the several children and instantiation packages) for the type Wide_Character and Wide_Wide_Character. It is worth noting that the family of Text_IO packages provide some automatic text processing. For example, the Get procedures for numeric and enumeration types ignore white space at the beginning of a line (Get_Line for String does not present this behavior), or adding line and page terminators when closing the file. This is thus adequate for applications handling simple textual data, but users requiring direct management of text (e.g. raw access to the character encoding) must consider other packages like Sequential_IO. ## Direct I/O Direct I/O is used for random access files which contain only elements of one specific type. With Direct_IO you can position the file pointer to any element of that type `<small>`{=html}(random access)`</small>`{=html}, however you can\'t freely choose the element type, the element type needs to be a definite subtype. ## Sequential I/O Direct I/O is used for random access files which contain only elements of one specific type. With Sequential_IO it is the other way round: you can choose between definite and indefinite element types but you have to read and write the elements one after the other. ## Stream I/O Stream I/O is the most powerful input/output package which Ada provides. Stream I/O allows you to mix objects from different element types in one sequential file. In order to read/write from/to a stream each type provides a \'Read and \'Write attribute as well as an \'Input and \'Output attribute. These attributes are automatically generated for each type you declare. The \'Read and \'Write attributes treat the elements as raw data. They are suitable for low level input/output as well as interfacing with other programming languages. The \'Input and \'Output attributes add additional control information to the file, like for example the \'First and \'Last attributes for an array. In object orientated programming you can also use the \'Class\'Input and \'Class\'Output attributes - they will store and recover the actual object type as well. Stream I/O is also the most flexible input/output package. All I/O attributes can be replaced with user defined functions or procedures using representation clauses and you can provide your own Stream I/O types using flexible object oriented techniques. ## See also ### Wikibook - Ada Programming - Ada Programming/Libraries/Ada.Direct_IO - Ada Programming/Libraries/Ada.Sequential_IO - Ada Programming/Libraries/Ada.Streams - Ada Programming/Libraries/Ada.Streams.Stream_IO - Ada Programming/Libraries/Ada.Text_IO.Text_Streams - Ada Programming/Libraries/Ada.Text_IO - Ada Programming/Libraries/Ada.Text_IO.Enumeration_IO (nested package) - Ada Programming/Libraries/Ada.Text_IO.Integer_IO (nested package) - Ada Programming/Libraries/Ada.Text_IO.Modular_IO (nested package) - Ada Programming/Libraries/Ada.Text_IO.Float_IO (nested package) - Ada Programming/Libraries/Ada.Text_IO.Fixed_IO (nested package) - Ada Programming/Libraries/Ada.Text_IO.Decimal_IO (nested package) - Ada Programming/Libraries/Ada.Text_IO.Bounded_IO - Ada Programming/Libraries/Ada.Text_IO.Unbounded_IO - Ada Programming/Libraries/Ada.Text_IO.Complex_IO (specialized needs annex) - Ada Programming/Libraries/Ada.Text_IO.Editing (specialized needs annex) - Ada Programming/Libraries/Ada.Integer_Text_IO - Ada Programming/Libraries/Ada.Float_Text_IO - Ada Programming/Libraries/Ada.Complex_Text_IO (specialized needs annex) - Ada Programming/Libraries/Ada.Storage_IO (not a general-purpose I/O package) - Ada Programming/Libraries/Ada.IO_Exceptions - Ada Programming/Libraries/Ada.Command_Line - Ada Programming/Libraries/Ada.Directories - Ada Programming/Libraries/Ada.Environment_Variables - Ada Programming/Libraries/GNAT.IO (implementation defined) - Ada Programming/Libraries/GNAT.IO_Aux (implementation defined) - Ada Programming/Libraries/GNAT.Calendar.Time_IO (implementation defined) - Ada Programming/Libraries/System.IO (implementation defined) - Ada Programming/Libraries - Ada Programming/Libraries/GUI - Ada Programming/Libraries/Web - Ada Programming/Libraries/Database - Ada Programming/Platform - Ada Programming/Platform/Linux - Ada Programming/Platform/Windows ### Ada Reference Manual - - - - - - - - ### Ada 95 Quality and Style Guide - - - - - - Programming}}\|InputOutput es:Programación en Ada/Entrada-salida
# Ada Programming/Exceptions ## Robustness *Robustness* is the ability of a system or system component to behave "reasonably" when it detects an anomaly, e.g.: - It receives invalid inputs. - Another system component (hardware or software) malfunctions. Take as example a telephone exchange control program. What should the control program do when a line fails? It is unacceptable simply to halt --- all calls will then fail. Better would be to abandon the current call (only), record that the line is out of service, and continue. Better still would be to try to reuse the line --- the fault might be transient. Robustness is desirable in all systems, but it is essential in systems on which human safety or welfare depends, e.g., hospital patient monitoring, aircraft fly-by-wire, nuclear power station control, etc. ## Modules, preconditions and postconditions A module may be specified in terms of its preconditions and postconditions. A *precondition* is a condition that the module's inputs are supposed to satisfy. A *postcondition* is a condition that the module's outputs are required to satisfy, provided that the precondition is satisfied. What should a module do if its precondition is not satisfied? - Halt? Even with diagnostic information, this is generally unacceptable. - Use a global result code? The result code can be set to indicate an anomaly. Subsequently it may be tested by a module that can effect error recovery. Problem: this induces tight coupling among the modules concerned. - Each module has its own result code? This is a parameter (or function result) that may be set to indicate an anomaly, and is tested by calling modules. Problems: (1) setting and testing result codes tends to swamp the normal-case logic and (2) the result codes are normally ignored. - Exception handling --- Ada's solution. A module detecting an anomaly raises an exception. The same, or another, module may handle that exception. The exception mechanism permits clean, modular handling of anomalous situations: - A unit (e.g., block or subprogram body) may raise an exception, to signal that an anomaly has been detected. The computation that raised the exception is abandoned (and can never be resumed, although it can be restarted). - A unit may propagate an exception that has been raised by itself (or propagated out of another unit it has called). - A unit may alternatively handle such an exception, allowing programmer-defined recovery from an anomalous situation. Exception handlers are segregated from normal-case code. ## Predefined exceptions The predefined exceptions are those defined in package . Every language-defined run-time error causes a predefined exception to be raised. Some examples are: - `Constraint_Error`, raised when a subtype's constraint is not satisfied - `Program_Error`, when a protected operation is called inside a protected object, e.g. - `Storage_Error`, raised by running out of storage - `Tasking_Error`, when a task cannot be activated because the operating system has not enough resources, e.g. Ex.1 `  Name : String (1 .. 10);`\ `  ...`\ `  Name := "Hamlet"; `\ `                    ` Ex.2 `  `\ `     P := `` Int_Node'(0, P);`\ `  `` ``; `\ `            ` Ex.3 Compare the following approaches: `  `` Compute_Sqrt (X    : ``  Float;`\ `                          Sqrt : `` Float;`\ `                          OK   : `` Boolean)`\ `  `\ `  `\ `     `` X >= 0 `\ `        OK := True;`\ `        `\ `        ...`\ `     `\ `        OK := False;`\ `     `` ``;`\ `  `` Compute_Sqrt;`\ `  `\ `  ...`\ `  `\ `  `` Triangle (A, B, C         : ``  Float;`\ `                      Area, Perimeter : `` Float;`\ `                      Exists          : `` Boolean)`\ `  `\ `     S  : `` Float := 0.5 * (A + B + C);`\ `     OK : Boolean;`\ `  `\ `     Compute_Sqrt (S * (S-A) * (S-B) * (S-C), Area, OK);`\ `     Perimeter := 2.0 * S;`\ `     Exists    := OK;`\ `  `` Triangle;` A negative argument to Compute_Sqrt causes OK to be set to False. Triangle uses it to determine its own status parameter value, and so on up the calling tree, *ad nauseam*. *versus* `  `` Sqrt (X : Float) `` Float `\ `  `\ `     `` X < 0.0 `\ `        `` Constraint_Error;`\ `     `` ``;`\ `     `\ `     ...`\ `  `` Sqrt;`\ `  `\ `  ...`\ `  `\ `  `` Triangle (A, B, C         : ``  Float;`\ `                      Area, Perimeter : `` Float)`\ `  `\ `     S: `` Float := 0.5 * (A + B + C);`\ `  `\ `     Area      := Sqrt (S * (S-A) * (S-B) * (S-C));`\ `     Perimeter := 2.0 * S;`\ `  `` Triangle;` A negative argument to Sqrt causes Constraint_Error to be explicitly raised inside Sqrt, and propagated out. Triangle simply propagates the exception (by not handling it). Alternatively, we can catch the error by using the type system: `  `` Pos_Float `` Float `` 0.0 .. Float'``;`\ `  `\ `  `` Sqrt (X : Pos_Float) `` Pos_Float `\ `  `\ `     `\ `     ...`\ `  `` Sqrt;` A negative argument to Sqrt now raises Constraint_Error at the point of call. Sqrt is never even entered. ## Input-output exceptions Some examples of exceptions raised by subprograms of the **predefined package** are: - `End_Error`, raised by Get, Skip_Line, etc., if end-of-file already reached. - `Data_Error`, raised by Get in Integer_IO, etc., if the input is not a literal of the expected type. - `Mode_Error`, raised by trying to read from an output file, or write to an input file, etc. - `Layout_Error`, raised by specifying an invalid data format in a text I/O operation Ex. 1 `  `\ `     A : Matrix (1 .. M, 1 .. N);`\ `  `\ `     `` I `` 1 .. M `\ `        `` J `` 1 .. N `\ `            `\ `               Get (A(I,J));`\ `            `\ `               `` Data_Error =>`\ `                  Put ("Ill-formed matrix element");`\ `                  A(I,J) := 0.0;`\ `            ``;`\ `         `` ``;`\ `     `` ``;`\ `  `\ `     `` End_Error =>`\ `        Put ("Matrix element(s) missing");`\ `  ``;` ## Exception declarations Exceptions are declared similarly to objects. Ex.1 declares two exceptions: `  Line_Failed, Line_Closed: ``;` However, exceptions are not objects. For example, recursive re-entry to a scope where an exception is declared does *not* create a new exception of the same name; instead the exception declared in the outer invocation is reused. Ex.2 `  `` Directory_Enquiries `\ \ `     `` Insert (New_Name   : `` Name;`\ `                       New_Number : `` Number);`\ \ `     `` Lookup (Given_Name  : ``  Name;`\ `                       Corr_Number : `` Number);`\ \ `     Name_Duplicated : ``;`\ `     Name_Absent     : ``;`\ `     Directory_Full  : ``;`\ \ `  `` Directory_Enquiries;` ## Exception handlers When an exception occurs, the normal flow of execution is abandoned and the exception is handed up the call sequence until a matching handler is found. Any declarative region (except a package specification) can have a handler. The handler names the exceptions it will handle. By moving up the call sequence, exceptions can become anonymous; in this case, they can only be handled with the handler. ` F `` Some_Type `\ `  ... -- declarations (1)`\ \ `  ... -- statements (2)`\ ` -- handlers start here (3)`\ `  `` Name_1 | Name_2 => ... -- The named exceptions are handled with these statements`\ `  `` `` => ...  -- any other exceptions (also anonymous ones) are handled here`\ ` F;` Exceptions raised in the declarative region itself (1) cannot be handled by handlers of this region (3); they can only be handled in outer scopes. Exceptions raised in the sequence of statements (2) can of course be handled at (3). The reason for this rule is so that the handler can assume that any items declared in the declarative region (1) are well defined and may be referenced. If the handler at (3) could handle exceptions raised at (1), it would be unknown which items existed and which ones didn\'t. ## Raising exceptions The **raise** statement explicitly raises a specified exception. Ex. 1 `  `` `` Directory_Enquiries `\ `  `\ `     `` Insert (New_Name   : `` Name;`\ `                       New_Number : `` Number)`\ `     `\ `        …`\ `     `\ `        …`\ `        `` New_Name = Old_Entry.A_Name `\ `           `` Name_Duplicated;`\ `        `` ``;`\ `        …`\ `        New_Entry :=  `` Dir_Node'(New_Name, New_Number,…);`\ `        …`\ `     `\ `        `` Storage_Error => `` Directory_Full;`\ `     `` Insert;`\ `     `\ `     `` Lookup (Given_Name  : ``  Name;`\ `                       Corr_Number : `` Number)`\ `     `\ `        …`\ `     `\ `        …`\ `        `` `` Found `\ `           `` Name_Absent;`\ `        `` ``;`\ `        …`\ `     `` Lookup;`\ `  `\ `  `` Directory_Enquiries;` ## Exception handling and propagation Exception handlers may be grouped at the end of a block, subprogram body, etc. A handler is any sequence of statements that may end: - by completing; - by executing a **return** statement; - by raising a different exception (**raise** e;); - by re-raising the same exception (**raise**;). Suppose that an exception *e* is raised in a sequence of statements *U* (a block, subprogram body, etc.). - If *U* contains a handler for *e*: that handler is executed, then control leaves *U*. - If *U* contains no handler for *e*: *e* is *propagated* out of *U*; in effect, *e* is raised at the \"point of call" of *U*. So the raising of an exception causes the sequence of statements responsible to be abandoned at the point of occurrence of the exception. It is not, and cannot be, resumed. Ex. 1 `  ...`\ `  `\ `     `` Line_Failed =>`\ `        `` `\ `           Log_Error;`\ `           Retransmit (Current_Packet);`\ `        `\ `           `` Line_Failed =>`\ `              Notify_Engineer; `\ `              Abandon_Call;`\ `        ``;`\ `  ...` ## Information about an exception occurrence Ada provides information about an exception in an object of type Exception_Occurrence, defined in along with subprograms taking this type as parameter: - Exception_Name: return the full exception name using the dot notation and in uppercase letters. For example, `Queue.Overflow`. - Exception_Message: return the exception message associated with the occurrence. - Exception_Information: return a string including the exception name and the associated exception message. For getting an exception occurrence object the following syntax is used: ` ``;  `` ``;`\ `...`\ \ `  `` Error: High_Pressure | High_Temperature =>`\ `    Put ("Exception: ");`\ `    Put_Line (Exception_Name (Error));`\ `    Put (Exception_Message (Error));`\ `  `` Error: `` =>`\ `    Put ("Unexpected exception: ");`\ `    Put_Line (Exception_Information(Error));`\ `;` The exception message content is implementation defined when it is not set by the user who raises the exception. It usually contains a reason for the exception and the raising location. The user can specify a message using the procedure Raise_Exception. \ `   Valve_Failure : ``;`\ \ `  ...`\ `  Raise_Exception (Valve_Failure'``, "Failure while opening");`\ `  ...`\ `  Raise_Exception (Valve_Failure'``, "Failure while closing");`\ `  ...`\ \ `  `` Fail: Valve_Failure =>`\ `    Put (Exception_Message (Fail));`\ `;` Starting with Ada 2005, a simpler syntax can be used to associate a string message with exception occurrence. `-- `\ \ `   Valve_Failure : ``;`\ \ `  ...`\ `  `` Valve_Failure `` "Failure while opening";`\ `  ...`\ `  `` Valve_Failure `` "Failure while closing";`\ `  ...`\ \ `  `` Fail: Valve_Failure =>`\ `    Put (Exception_Message (Fail));`\ `;` The package also provides subprograms for saving exception occurrences and re-raising them. ## See also ### Wikibook - Ada Programming ### Ada 95 Reference Manual - - ### Ada 2005 Reference Manual - - ### Ada Quality and Style Guide - **Chapter 4: Program Structure** - - ```{=html} <!-- --> ``` - **Chapter 5: Programming Practices** - - - - - ```{=html} <!-- --> ``` - **Chapter 7: Portability** - - - Programming}}\|Exceptions es:Programación en Ada/Excepciones
# Ada Programming/Generics ## Parametric polymorphism (generic units) The idea of code reuse arises from the necessity for constructing large software systems combining well-established building blocks. The reusability of code improves the productivity and the quality of software. The generic units are one of the ways in which the Ada language supports this characteristic. A generic unit is a subprogram or package that defines algorithms in terms of types and operations that are not defined until the user instantiates them. Note to C++ programmers: generic units are similar to C++ templates. For example, to define a procedure for swapping variables of any (non-limited) type: \ `  `` Element_T `` ``;  `\ ` Swap (X, Y : `` `` Element_T);` ` Swap (X, Y : `` `` Element_T) `\ `  Temporary : `` Element_T := X;`\ \ `  X := Y;`\ `  Y := Temporary;`\ ` Swap;` The `Swap` subprogram is said to be generic. The subprogram specification is preceded by the generic formal part consisting of the reserved word followed by a list of generic formal parameters which may be empty. The entities declared as generic are not directly usable, it is necessary to instantiate them. To be able to use `Swap`, it is necessary to create an instance for the wanted type. For example: ` Swap_Integers `` `` Swap (Integer);` Now the `Swap_Integers` procedure can be used for variables of type `Integer`. The generic procedure can be instantiated for all the needed types. It can be instantiated with different names or, if the same identifier is used in the instantiation, each declaration overloads the procedure: ` Instance_Swap `` `` Swap (Float);`\ ` Instance_Swap `` `` Swap (Day_T);`\ ` Instance_Swap `` `` Swap (Element_T => Stack_T);` Similarly, generic packages can be used, for example, to implement a stack of any kind of elements: \ `  Max: Positive; `\ `  `` Element_T `` ``;`\ ` Generic_Stack `\ `  `` Push (E: Element_T);`\ `  `` Pop return Element_T;`\ ` Generic_Stack;` ` `` Generic_Stack `\ `  Stack: `` (1 .. Max) `` Element_T;`\ `  Top  : Integer `` 0 .. Max := 0;  `\ `  `\ ` Generic_Stack;` A stack of a given size and type could be defined in this way: \ `  `` Float_100_Stack `` `` Generic_Stack (100, Float);`\ `  `` Float_100_Stack;`\ \ `  Push (45.8);`\ `  `\ `;` ## Generic parameters The generic unit declares *generic formal parameters*, which can be: - objects (of mode *in* or *in out* but never *out*) - types - subprograms - instances of another, designated, generic unit. When instantiating the generic, the programmer passes one *actual parameter* for each formal. Formal values and subprograms can have defaults, so passing an actual for them is optional. ### Generic formal objects Formal parameters of mode *in* accept any value, constant, or variable of the designated type. The actual is copied into the generic instance, and behaves as a constant inside the generic; this implies that the designated type cannot be limited. It is possible to specify a default value, like this: \ `   Object : `` Natural := 0;` For mode *in out*, the actual must be a variable. One limitation with generic formal objects is that they are never considered static, even if the actual happens to be static. If the object is a number, it cannot be used to create a new type. It can however be used to create a new derived type, or a subtype: \ `   Size : `` Natural := 0;`\ ` P `\ `   `` T1 `` `` Size; `\ `   `` T2 `` `` 1 .. Size; `\ `   `` T3 `` `` Integer `` 1 .. Size; `\ `   `` T4 `` Integer `` 1 .. Size; `\ ` P;` The reason why formal objects are nonstatic is to allow the compiler to emit the object code for the generic only once, and to have all instances share it, passing it the address of their actual object as a parameter. This bit of compiler technology is called *shared generics*. If formal objects were static, the compiler would have to emit one copy of the object code, with the object embedded in it, for each instance, potentially leading to an explosion in object code size (*code bloat*). (Note to C++ programmers: in C++, since formal objects can be static, the compiler cannot implement shared generics in the general case; it would have to examine the entire body of the generic before deciding whether or not to share its object code. In contrast, Ada generics are designed so that the compiler can instantiate a generic *without looking at its body*.) ### Generic formal types The syntax allows the programmer to specify which type categories are acceptable as actuals. As a rule of thumb: The syntax expresses how the generic sees the type, i.e. it assumes the worst, not how the creator of the instance sees the type. This is the syntax of RM : ` formal_type_declaration ::=`\ `   `` defining_identifier[discriminant_part] `` formal_type_definition;`\ ` `\ ` formal_type_definition ::= formal_private_type_definition`\ `                          | formal_derived_type_definition`\ `                          | formal_discrete_type_definition`\ `                          | formal_signed_integer_type_definition`\ `                          | formal_modular_type_definition`\ `                          | formal_floating_point_definition`\ `                          | formal_ordinary_fixed_point_definition`\ `                          | formal_decimal_fixed_point_definition`\ `                          | formal_array_type_definition`\ `                          | formal_access_type_definition`\ `                          | formal_interface_type_definition` This is quite complex, so some examples are given below. A type declared with the syntax ` T (<>)` denotes a type with *unknown discriminants*. This is the Ada vernacular for indefinite types, i.e. types for which objects cannot be declared without giving an initial expression. An example of such a type is one with a discriminant without default, another example is an unconstrained array type. Generic formal type Acceptable actual types -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ` T (<>) `` `` ``;` Any type at all. The actual type can be limited or not, indefinite or definite, but the *generic* treats it as limited and indefinite, i.e. does not assume that assignment is available for the type. ` T (<>) `` ``;` Any nonlimited type: the generic knows that it is possible to assign to variables of this type, but it is not possible to declare objects of this type without initial value. ` T `` ``;` Any nonlimited definite type: the generic knows that it is possible to assign to variables of this type and to declare objects without initial value. ` T (<>) `` `` `` `` ``;` Any tagged type, abstract or concrete, limited or not. ` T (<>) `` `` `` ``;` Any concrete tagged type, limited or not. ` T (<>) `` `` `` ``;` Any nonlimited tagged type, abstract or concrete. ` T (<>) `` `` ``;` Any nonlimited, concrete tagged type. ` T (<>) `` `` Parent;` Any type derived from `Parent`. The generic knows about `Parent`\'s operations, so can call them. Neither `T` nor `Parent` can be abstract. ` T (<>) `` `` `` Parent `` ``;` Any type, abstract or concrete, derived from `Parent`, where `Parent` is a tagged type, so calls to `T`\'s operations can dispatch dynamically. ` T (<>) `` `` Parent `` ``;` Any concrete type, derived from the tagged type `Parent`. ` T `` (<>);` Any discrete type: integer, modular, or enumeration. ` T `` `` <>;` Any signed integer type ` T `` `` <>;` Any modular type ` T `` `` <>;` Any (non-decimal) fixed point type ` T `` `` <> `` <>;` Any decimal fixed point type ` T `` `` <>;` Any floating point type `<code>`{=html} T (I) E; Any array type with index of type `I` and elements of type `E` (`I` and `E` could be formal parameters as well) ` T `` `` O;` Any access type pointing to objects of type `O` (`O` could be a formal parameter as well) In the body we can only use the operations predefined for the type category of the formal parameter. That is, the generic specification is a contract between the generic implementor and the client instantiating the generic unit. This is different to the parametric features of other languages, such as C++. It is possible to further restrict the set of acceptable actual types like so: Generic formal type Acceptable actual types ---------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------- ` T (<>) `\... Definite or indefinite types (loosely speaking: types with or without discriminants, but other forms of indefiniteness exist) ` T (D : DT) `\... Types with a discriminant of type DT (it is possible to specify several discriminants, too) ` T `\... Definite types (loosely speaking types without a discriminant or with a discriminant with default value) ### Generic formal subprograms It is possible to pass a subprogram as a parameter to a generic. The generic specifies a generic formal subprogram, complete with parameter list and return type (if the subprogram is a function). The actual must match this parameter profile. It is not necessary that the *names* of parameters match, though. Here is the specification of a generic subprogram that takes another subprogram as its parameter: \ `  `` Element_T `` ``;`\ `  `` `` "*" (X, Y: Element_T) `` Element_T;`\ ` Square (X : Element_T) `` Element_T;` And here is the body of the generic subprogram; it calls parameter as it would any other subprogram. ` Square (X: Element_T) `` Element_T `\ \ `  `` X * X;   `\ ` Square;` This generic function could be used, for example, with matrices, having defined the matrix product. ` Square;`\ ` Matrices;`\ ` Matrix_Example `\ `  `` Square_Matrix `` `` Square`\ `    (Element_T => Matrices.Matrix_T, "*" => Matrices.Product);`\ `  A : Matrices.Matrix_T := Matrices.Identity;`\ \ `  A := Square_Matrix (A);`\ ` Matrix_Example;` It is possible to specify a default with \"the box\" (` `), like this: \ `  `` Element_T `` ``;`\ `  `` `` "*" (X, Y: Element_T) `` Element_T `` <>;` This means that if, at the point of instantiation, a function \"\*\" exists for the actual type, and if it is directly visible, then it will be used by default as the actual subprogram. One of the main uses is passing needed operators. The following example shows this `<small>`{=html}(follow download links for full example)`</small>`{=html}: `  ` `  `\ `     `` Element_Type `` ``;`\ `     `*`...`*\ `     `` `` "<"`\ `       (Left  : `` Element_Type;`\ `        Right : `` Element_Type)`\ `        ``  Boolean`\ `     `` ``;`\ `  `` Search`\ `    (Elements : `` Array_Type;`\ `     Search   : `` Element_Type;`\ `     Found    : `` Boolean;`\ `     Index    : `` Index_Type'``)`\ `     `*`...`* ### Generic instances of other generic packages A generic formal can be a package; it must be an instance of a generic package, so that the generic knows the interface exported by the package: \ `   `` `` P `` `` Q (``);` This means that the actual must be an instance of the generic package Q. The box after Q means that we do not care which actual generic parameters were used to create the actual for P. It is possible to specify the exact parameters, or to specify that the defaults must be used, like this: \ `   `\ `   `` `` P1 `` `` Q (Param1 => X, Param2 => Y);`\ \ `   `\ `   `` `` P2 `` `` Q;`\ You can specify one default parameters, none or only some. Defaults are indicated with a box (\" =\> \<\> \"), and you can use \" others =\> \<\>\") to mean \"use defaults for all parameters not mentioned\". The actual package must, of course, match these constraints. The generic sees both the public part and the generic parameters of the actual package (Param1 and Param2 in the above example). This feature allows the programmer to pass arbitrarily complex types as parameters to a generic unit, while retaining complete type safety and encapsulation. *(example needed)* It is not possible for a package to list itself as a generic formal, so no generic recursion is possible. The following is illegal: ` A;`\ \ `   `` `` P `` `` A (``);`\ ` A; ` In fact, this is only a particular case of: ` A; `\ ` A;` which is also illegal, despite the fact that A is no longer generic. ## Instantiating generics To instantiate a generic unit, use the keyword **new**: ` Square_Matrix `` `` Square`\ `   (Element_T => Matrices.Matrix_T, "*" => Matrices.Product);` Notes of special interest to C++ programmers: - The generic formal types define *completely* which types are acceptable as actuals; therefore, the compiler can instantiate generics without looking at the body of the generic. - Each instance has a name and is different from all other instances. In particular, if a generic package declares a type, and you create two instances of the package, then you will get two different, incompatible types, even if the actual parameters are the same. - Ada requires that all instantiations be explicit. - It is not possible to create special-case instances of a generic (known as \"template specialisation\" in C++). As a consequence of the above, Ada does not permit template metaprogramming. However, this design has significant advantages: - the object code can be shared by all instances of a generic, unless of course the programmer has requested that subprograms be inlined; there is no danger of code bloat. - when reading programs written by other people, there are no hidden instantiations, and no special cases to worry about. Ada follows the Law of Least Astonishment. ## Advanced generics ### Generics and nesting A generic unit can be nested inside another unit, which itself may be generic. Even though no special rules apply (just the normal rules about generics and the rules about nested units), novices may be confused. It is important to understand the difference between a generic unit and *instances* of a generic unit. **Example 1**. A generic subprogram nested in a nongeneric package. ` Bag_Of_Strings `\ `   `` Bag `` ``;`\ `   `\ `      `` `` Operator (S : `` `` String);`\ `   `` Apply_To_All (B : `` `` Bag);`\ \ `   `\ ` Bag_Of_Strings;` To use **Apply_To_All**, you first define the procedure to be applied to each String in the Bag. Then, you instantiate **Apply_To_All**, and finally you call the instance. ` Bag_Of_Strings;`\ ` Example_1 `\ `   `` Capitalize (S : `` `` String) `` ``; `\ `   `` Capitalize_All `\ `      `` Bag_Of_Strings.Apply_To_All (Operator => Capitalize);`\ `   B : Bag_Of_Strings.Bag;`\ \ `   Capitalize_All (B);`\ ` Example_1;` **Example 2.** A generic subprogram nested in a generic package This is the same as above, except that now the Bag itself is generic: \ `   `` Element_Type (<>) `` ``;`\ ` Generic_Bag `\ `   `` Bag `` ``;`\ `   `\ `      `` `` Operator (S : `` `` Element_Type);`\ `   `` Apply_To_All (B : `` `` Bag);`\ \ `   `\ ` Generic_Bag;` As you can see, the generic formal subprogram **Operator** takes a parameter of the generic formal type **Element_Type**. This is okay: the nested generic sees everything that is in its enclosing unit. You cannot instantiate **Generic_Bag.Apply_To_All** directly, so you must first create an instance of **Generic_Bag**, say **Bag_Of_Strings**, and then instantiate **Bag_Of_Strings.Apply_To_All**. ` Generic_Bag;`\ ` Example_2 `\ `   `` Capitalize (S : `` `` String) `` ``; `\ `   `` Bag_Of_Strings `\ `      `` Generic_Bag (Element_Type => String);`\ `   `` Capitalize_All `\ `      `` Bag_Of_Strings.Apply_To_All (Operator => Capitalize);`\ `   B : Bag_Of_Strings.Bag;`\ \ `   Capitalize_All (B);`\ ` Example_2;` ### Generics and child units **Example 3**. A generic unit that is a child of a nongeneric unit. Each instance of the generic child is a child of the parent unit, and so it can see the parent\'s public and private parts. ` Bag_Of_Strings `\ `   `` Bag `` ``;`\ \ `   `\ ` Bag_Of_Strings; `\ \ \ `   `` `` Operator (S : `` `` String);`\ ` Bag_Of_Strings.Apply_To_All (B : `` `` Bag);` The differences between this and Example 1 are: - **Bag_Of_Strings.Apply_To_All** is compiled separately. In particular, **Bag_Of_Strings.Apply_To_All** might have been written by a different person who did not have access to the source text of **Bag_Of_Strings**. - Before you can use **Bag_Of_Strings.Apply_To_All**, you must **with** it explicitly; **with**ing the parent, **Bag_Of_Strings**, is not sufficient. - If you do not use **Bag_Of_Strings.Apply_To_All**, your program does not contain its object code. - Because **Bag_Of_Strings.Apply_To_All** is at the library level, it can declare controlled types; the nested package could not do that in Ada 95. In Ada 2005, one can declare controlled types at any level. ` Bag_Of_Strings.Apply_To_All; `\ ` Example_3 `\ `   `` Capitalize (S : `` `` String) `` ``; `\ `   `` Capitalize_All `\ `      `` Bag_Of_Strings.Apply_To_All (Operator => Capitalize);`\ `   B : Bag_Of_Strings.Bag;`\ \ `   Capitalize_All (B);`\ ` Example_3;` **Example 4**. A generic unit that is a child of a generic unit This is the same as Example 3, except that now the Bag is generic, too. \ `   `` Element_Type (<>) `` ``;`\ ` Generic_Bag `\ `   `` Bag `` ``;`\ \ `   `\ ` Generic_Bag;`\ \ \ `   `` `` Operator (S : `` `` Element_Type);`\ ` Generic_Bag.Apply_To_All (B : `` `` Bag);`\ \ ` Generic_Bag.Apply_To_All;`\ ` Example_4 `\ `   `` Capitalize (S : `` `` String) `` ``; `\ `   `` Bag_Of_Strings `\ `      `` Generic_Bag (Element_Type => String);`\ `   `` Capitalize_All `\ `      `` Bag_Of_Strings.Apply_To_All (Operator => Capitalize);`\ `   B : Bag_Of_Strings.Bag;`\ \ `   Capitalize_All (B);`\ ` Example_4;` **Example 5**. A parameterless generic child unit Children of a generic unit **must** be generic, no matter what. If you think about it, it is quite logical: a child unit sees the public and private parts of its parent, including the variables declared in the parent. If the parent is generic, which instance should the child see? The answer is that the child must be the child of only one instance of the parent, therefore the child must also be generic. \ `   `` Element_Type (<>) `` ``;`\ `   `` Hash_Type `` (<>);`\ `   `` `` Hash_Function (E : Element_Type) `` Hash_Type;`\ ` Generic_Hash_Map `\ `   `` Map `` ``;`\ \ `   `\ ` Generic_Hash_Map;` Suppose we want a child of a **Generic_Hash_Map** that can serialise the map to disk; for this it needs to sort the map by hash value. This is easy to do, because we know that **Hash_Type** is a discrete type, and so has a less-than operator. The child unit that does the serialisation does not need any additional generic parameters, but it must be generic nevertheless, so it can see its parent\'s generic parameters, public and private part. \ ` Generic_Hash_Map.Serializer `\ `    `` Dump (Item : `` Map; To_File : `` String);`\ `    `` Restore (Item : `` Map; From_File : `` String);`\ ` Generic_Hash_Map.Serializer;`\ To read and write a map to disk, you first create an instance of **Generic_Hash_Map**, for example **Map_Of_Unbounded_Strings**, and then an instance of **Map_Of_Unbounded_Strings.Serializer**: ` Ada.Strings.Unbounded;`\ ` Generic_Hash_Map.Serializer;`\ ` Example_5 `\ `   `` Ada.Strings.Unbounded;`\ `   `` Hash (S : `` Unbounded_String) `` Integer `` ``; `\ `   `` Map_Of_Unbounded_Strings `\ `      `` Generic_Hash_Map (Element_Type => Unbounded_String,`\ `                            Hash_Type => Integer,`\ `                            Hash_Function => Hash);`\ `   `` Serializer `\ `      `` Map_Of_Unbounded_Strings.Serializer;`\ `   M : Map_Of_Unbounded_Strings.Map;`\ \ `   Serializer.Restore (Item => M, From_File => "map.dat");`\ ` Example_5;` ## See also ### Wikibook - Ada Programming - Ada Programming/Object Orientation: tagged types provides other mean of polymorphism in Ada. ### Wikipedia - Generic programming ### Ada Reference Manual - Programming}}\|Generics es:Programación en Ada/Unidades genéricas
# Ada Programming/Tasking ## Tasks A *task unit* is a program unit that is obeyed concurrently with the rest of an Ada program. The corresponding activity, a new locus of control, is called a *task* in Ada terminology, and is similar to a *thread*, for example in Java Threads. The execution of the main program is also a task, the anonymous environment task. A task unit has both a declaration and a body, which is mandatory. A task body may be compiled separately as a subunit, but a task may not be a library unit, nor may it be generic. Every task depends on a *master*, which is the immediately surrounding declarative region - a block, a subprogram, another task, or a package. The execution of a master does not complete until all its dependent tasks have terminated. The environment task is the master of all other tasks; it terminates only when all other tasks have terminated. Task units are similar to packages in that a task declaration defines entities exported from the task, whereas its body contains local declarations and statements of the task. A single task is declared as follows: `  `` Single `\ `     `*`declarations of exported identifiers`*\ `  `` Single;`\ `  ...`\ `  `` `` Single `\ `    `*`local declarations and statements`*\ `  `` Single;` A task declaration can be simplified, if nothing is exported, thus: `  `` No_Exports;` Ex. 1 `  `` Housekeeping `\ `  `\ `     `` Check_CPU;`\ `     `` Backup_Disk;`\ `  `\ `     `` `` Check_CPU `\ `        ...`\ `     `` Check_CPU;`\ `  `\ `     `` `` Backup_Disk `\ `        ...`\ `     `` Backup_Disk;`\ `     `\ `  `` `\ `     ``;`\ `     `\ `  `` Housekeeping;` It is possible to declare task types, thus allowing task units to be created dynamically, and incorporated in data structures: `  `` `` T `\ `     ...`\ `  `` T;`\ `  ...`\ `  Task_1, Task_2 : T;`\ `  ...`\ `  `` `` T `\ `     ...`\ `  `` T;` Task types are **limited**, i.e. they are restricted in the same way as limited types, so assignment and comparison are not allowed. ### Rendezvous The only entities that a task may export are entries. An **entry** looks much like a procedure. It has an identifier and may have **in**, **out** or **in out** parameters. Ada supports communication from task to task by means of the *entry call*. Information passes between tasks through the actual parameters of the entry call. We can encapsulate data structures within tasks and operate on them by means of entry calls, in a way analogous to the use of packages for encapsulating variables. The main difference is that an entry is executed by the called task, not the calling task, which is suspended until the call completes. If the called task is not ready to service a call on an entry, the calling task waits in a (FIFO) queue associated with the entry. This interaction between calling task and called task is known as a *rendezvous*. The calling task requests rendezvous with a specific named task by calling one of its entries. A task accepts rendezvous with any caller of a specific entry by executing an **accept** statement for the entry. If no caller is waiting, it is held up. Thus entry call and accept statement behave symmetrically. (To be honest, optimized object code may reduce the number of context switches below the number implied by this poor description.) There is, however, a big difference between a procedure and an entry. A procedure has exactly one body that is executed when called. There is no such relation between an entry and a corresponding accept statement. An entry may have more than one accept statement, and the code executed may be different each time. In fact, there even need not be an accept statement at all. (Calling such an entry leads to deadlock of the caller if not timed, of course.) Ex. 2 The following task type implements a single-slot buffer, i.e. an encapsulated variable that can have values inserted and removed in strict alternation. Note that the buffer task has no need of state variables to implement the buffer protocol: the alternation of insertion and removal operations is directly enforced by the control structure in the body of Encapsulated_Buffer_Task_Type which is, as is typical, a **loop**. `  `` `` Encapsulated_Buffer_Task_Type `\ `     `` Insert (An_Item : ``  Item);`\ `     `` Remove (An_Item : `` Item);`\ `  `` Encapsulated_Buffer_Task_Type;`\ `  ...`\ `  Buffer_Pool : `` (0 .. 15) `` Encapsulated_Buffer_Task_Type;`\ `  This_Item   : Item;`\ `  ...`\ `  `` `` Encapsulated_Buffer_Task_Type `\ `     Datum : Item;`\ `  `\ `     `\ `        `` Insert (An_Item : ``  Item) `\ `           Datum := An_Item;`\ `        `` Insert;`\ `        `` Remove (An_Item : `` Item) `\ `           An_Item := Datum;`\ `        `` Remove;`\ `     `` ``;`\ `  `` Encapsulated_Buffer_Task_Type;`\ `  ...`\ `  Buffer_Pool(1).Remove (This_Item);`\ `  Buffer_Pool(2).Insert (This_Item);` ### Selective Wait To avoid being held up when it could be doing productive work, a server task often needs the freedom to accept a call on any one of a number of alternative entries. It does this by means of the *selective wait* statement, which allows a task to wait for a call on any of two or more entries. If only one of the alternatives in a selective wait statement has a pending entry call, then that one is accepted. If two or more alternatives have calls pending, the implementation is free to accept any one of them. For example, it could choose one at random. This introduces *bounded non-determinism* into the program. A sound Ada program should not depend on a particular method being used to choose between pending entry calls. (However, there are facilities to influence the method used, when that is necessary.) Ex. 3 `  `` `` Encapsulated_Variable_Task_Type `\ `     `` Store (An_Item : ``  Item);`\ `     `` Fetch (An_Item : `` Item);`\ `  `` Encapsulated_Variable_Task_Type;`\ `  ...`\ `  `` `` Encapsulated_Variable_Task_Type `\ `     Datum : Item;`\ `  `\ `     `` Store (An_Item : `` Item) `\ `        Datum := An_Item;`\ `     `` Store;`\ `     `\ `        ``   `\ `           `` Store (An_Item : `` Item) `\ `              Datum := An_Item;`\ `           `` Store;`\ `        `\ `           `` Fetch (An_Item : `` Item) `\ `              An_Item := Datum;`\ `           `` Fetch;`\ `        `` ``;`\ `     `` ``;`\ `  `` Encapsulated_Variable_Task_Type;` `  x, y : Encapsulated_Variable_Task_Type;` creates two variables of type Encapsulated_Variable_Task_Type. They can be used thus: `  it : Item;`\ `  ...`\ `  x.Store(Some_Expression);`\ `  ...`\ `  x.Fetch (it);`\ `  y.Store (it);` Again, note that the control structure of the body ensures that an Encapsulated_Variable_Task_Type must be given an initial value by a first Store operation before any Fetch operation can be accepted. ### Guards Depending on circumstances, a server task may not be able to accept calls for some of the entries that have accept alternatives in a selective wait statement. The acceptance of any alternative can be made conditional by using a *guard*, which is *Boolean* precondition for acceptance. This makes it easy to write monitor-like server tasks, with no need for an explicit signaling mechanism, nor for mutual exclusion. An alternative with a True guard is said to be *open*. It is an error if no alternative is open when the selective wait statement is executed, and this raises the Program_Error exception. Ex. 4 `  `` Cyclic_Buffer_Task_Type `\ `     `` Insert (An_Item : ``  Item);`\ `     `` Remove (An_Item : `` Item);`\ `  `` Cyclic_Buffer_Task_Type;`\ `  ...`\ `  `` `` Cyclic_Buffer_Task_Type `\ `     Q_Size : `` := 100;`\ `     `` Q_Range `` Positive `` 1 .. Q_Size;`\ `     Length : Natural `` 0 .. Q_Size := 0;`\ `     Head, Tail : Q_Range := 1;`\ `     Data : `` (Q_Range) `` Item;`\ `  `\ `     `\ `        `\ `           `` Length < Q_Size =>`\ `              `` Insert (An_Item : ``  Item) `\ `                 Data(Tail) := An_Item;`\ `              `` Insert;`\ `              Tail := Tail `` Q_Size + 1;`\ `              Length := Length + 1;`\ `        `\ `           `` Length > 0 =>`\ `              `` Remove (An_Item : `` Item) `\ `                 An_Item := Data(Head);`\ `              `` Remove;`\ `              Head := Head `` Q_Size + 1;`\ `              Length := Length - 1;`\ `        `` ``;`\ `     `` ``;`\ `  `` Cyclic_Buffer_Task_Type;` ## Protected types Tasks allow for encapsulation and safe usage of variable data without the need for any explicit mutual exclusion and signaling mechanisms. Ex. 4 shows how easy it is to write server tasks that safely manage locally-declared data on behalf of multiple clients. There is no need for mutual exclusion of access to the managed data, *because it is never accessed concurrently*. However, the overhead of creating a task merely to serve up some data may be excessive. For such applications, Ada 95 provides **protected** modules, based on the well-known computer science concept of a *monitor "wikilink")*. A protected module encapsulates a data structure and exports subprograms that operate on it under automatic mutual exclusion. It also provides automatic, implicit signaling of conditions between client tasks. Again, a protected module can be either a single protected object or a protected type, allowing many protected objects to be created. A protected module can export only procedures, functions and entries, and its body may contain only the bodies of procedures, functions and entries. The protected data is declared after **private** in its specification, but is accessible only within the protected module\'s body. Protected procedures and entries may read and/or write its encapsulated data, and automatically exclude each other. Protected functions may only read the encapsulated data, so that multiple protected function calls can be concurrently executed in the same protected object, with complete safety; but protected procedure calls and entry calls exclude protected function calls, and vice versa. Exported entries and subprograms of a protected object are executed by its calling task, as a protected object has no independent locus of control. (To be honest, optimized object code may reduce the number of context switches below the number implied by this naive description.) Similar to a task entry which optionally has a *guard*, a protected entry must have a *barrier* to control admission. This provides automatic signaling, and ensures that when a protected entry call is accepted, its barrier condition is True, so that a barrier provides a reliable precondition for the entry body. A barrier can statically be true, then the entry is always open. Ex. 5 The following is a simple protected type analogous to the Encapsulated_Buffer task in Ex. 2. `  `` `` Protected_Buffer_Type `\ `     `` Insert (An_Item : ``  Item);`\ `     `` Remove (An_Item : `` Item);`\ `  `\ `     Buffer : Item;`\ `     Empty  : Boolean := True;`\ `  `` Protected_Buffer_Type;`\ `  ...`\ `  `` `` Protected_Buffer_Type `\ `     `` Insert (An_Item : ``  Item)`\ `        `` Empty `\ `     `\ `        Buffer := An_Item;`\ `        Empty := False;`\ `     `` Insert;`\ `     `` Remove (An_Item : `` Item)`\ `        `` `` Empty `\ `     `\ `        An_Item := Buffer;`\ `        Empty := True;`\ `     `` Remove;`\ `  `` Protected_Buffer_Type;` Note how the barriers, using the state variable Empty, ensure that messages are alternately inserted and removed, and that no attempt can be made to take data from an empty buffer. All this is achieved without explicit signaling or mutual exclusion constructs, whether in the calling task or in the protected type itself. The notation for calling a protected entry or procedure is exactly the same as that for calling a task entry. This makes it easy to replace one implementation of the abstract type by the other, the calling code being unaffected. Ex. 6 The following task type implements Dijkstra\'s semaphore ADT, with FIFO scheduling of resumed processes. The algorithm will accept calls to both Wait and Signal, so long as the semaphore invariant would not be violated. When that circumstance approaches, calls to Wait are ignored for the time being. `  `` `` Semaphore_Task_Type `\ `     `` Initialize (N : `` Natural);`\ `     `` Wait;`\ `     `` Signal;`\ `  `` Semaphore_Task_Type;`\ `  ...`\ `  `` `` Semaphore_Task_Type `\ `     Count : Natural;`\ `  `\ `     `` Initialize (N : `` Natural) `\ `        Count := N;`\ `     `` Initialize;`\ `     `\ `        `\ `           `` Count > 0 =>`\ `               `` Wait `\ `                  Count := Count - 1;`\ `               `` Wait;`\ `        `\ `               `` Signal;`\ `               Count := Count + 1;`\ `        `` ``;`\ `     `` ``;`\ `  `` Semaphore_Task_Type;` This task could be used as follows: `  nr_Full, nr_Free : Semaphore_Task_Type;`\ `  ...`\ `  nr_Full.Initialize (0); nr_Free.Initialize (nr_Slots);`\ `  ...`\ `  nr_Free.Wait; nr_Full.Signal;` Alternatively, semaphore functionality can be provided by a protected object, with major efficiency gains. Ex. 7 The Initialize and Signal operations of this protected type are unconditional, so they are implemented as protected procedures, but the Wait operation must be guarded and is therefore implemented as an entry. `  `` `` Semaphore_Protected_Type `\ `     `` Initialize (N : `` Natural);`\ `     `` Wait;`\ `     `` Signal;`\ `  `\ `     Count : Natural := 0;`\ `  `` Semaphore_Protected_Type;`\ `  ...`\ `  `` `` Semaphore_Protected_Type `\ `     `` Initialize (N : `` Natural) `\ `     `\ `        Count := N;`\ `     `` Initialize;`\ `     `` Wait`\ `        `` Count > 0 `\ `     `\ `        Count := Count - 1;`\ `     `` Wait;`\ `     `` Signal `\ `     `\ `        Count := Count + 1;`\ `     `` Signal;`\ `  `` Semaphore_Protected_Type;` Unlike the task type above, this does not ensure that Initialize is called before Wait or Signal, and Count is given a default initial value instead. Restoring this defensive feature of the task version is left as an exercise for the reader. ## Entry families Sometimes we need a group of related entries. Entry *families*, indexed by a *discrete type*, meet this need. Ex. 8 This task provides a pool of several buffers. `  `` Buffer_Id `` Integer `` 1 .. nr_Bufs;`\ `  ...`\ `  `` Buffer_Pool_Task `\ `     `` Insert (Buffer_Id) (An_Item : `` Item);`\ `     `` Remove (Buffer_Id) (An_Item : `` Item);`\ `  `` Buffer_Pool_Task;`\ `  ...`\ `  `` `` Buffer_Pool_Task `\ `     Data   : `` (Buffer_Id) `` Item;`\ `     Filled : `` (Buffer_Id) `` Boolean  := (others => False);`\ `  `\ `    `\ `      `` I `` Data'`` `\ `        `\ `          `` `` Filled(I) =>`\ `             `` Insert (I) (An_Item : `` Item) `\ `                Data(I) := An_Item;`\ `             `` Insert;`\ `             Filled(I) := True;`\ `        `\ `          `` Filled(I) =>`\ `             `` Remove (I) (An_Item : `` Item) `\ `                    An_Item := Data(I);`\ `             `` Remove;`\ `             Filled(I) := False;`\ `        `\ `          ``; `\ `        `` ``;`\ `      `` ``;`\ `    `` ``;   `\ `  `` Buffer_Pool_Task;`\ `  ...`\ `  Buffer_Pool_Task.Remove(K)(This_Item);` Note that the busy wait is necessary here to prevent the task from being suspended on some buffer when there was no call pending for it, because such suspension would delay serving requests for all the other buffers (perhaps indefinitely). ## Termination Server tasks often contain infinite loops to allow them to service an arbitrary number of calls in succession. But control cannot leave a task\'s master until the task terminates, so we need a way for a server to know when it should terminate. This is done by a *terminate alternative* in a selective wait. Ex. 9 `  `` `` Terminating_Buffer_Task_Type `\ `     `` Insert (An_Item : ``  Item);`\ `     `` Remove (An_Item : `` Item);`\ `  `` Terminating_Buffer_Task_Type;`\ `  ...`\ `  `` `` Terminating_Buffer_Task_Type `\ `     Datum : Item;`\ `  `\ `     `\ `        `\ `           `` Insert (An_Item : ``  Item) `\ `              Datum := An_Item;`\ `           `` Insert;`\ `        `\ `           ``;`\ `        `` ``;`\ `        `\ `           `` Remove (An_Item : `` Item) `\ `              An_Item := Datum;`\ `           `` Remove;`\ `        `\ `           ``;`\ `        `` ``;`\ `     `` ``;`\ `  `` Terminating_Buffer_Task_Type;` The task terminates when: 1. at least one terminate alternative is open, and 2. there are no pending calls to its entries, and 3. all other tasks of the same master are in the same state (or already terminated), and 4. the task\'s master has completed (i.e. has run out of statements to execute). Conditions (1) and (2) ensure that the task is in a fit state to stop. Conditions (3) and (4) ensure that stopping cannot have an adverse effect on the rest of the program, because no further calls that might change its state are possible. ## Timeout A task may need to avoid being held up by calling to a slow server. A *timed entry call* lets a client specify a maximum delay before achieving rendezvous, failing which the attempted entry call is withdrawn and an alternative sequence of statements is executed. Ex. 10 `  `` Password_Server `\ `     `` Check (User, Pass : `` String; Valid : `` Boolean);`\ `     `` Set (User, Pass : ``  String);`\ `  `` Password_Server;`\ `  ...`\ `  User_Name, Password : String (1 .. 8);`\ `  ...`\ `  Put ("Please give your new password:");`\ `  Get_Line (Password);`\ `  `\ `     Password_Server.Set (User_Name, Password);`\ `     Put_Line ("Done");`\ `  `\ `     `` 10.0;`\ `     Put_Line ("The system is busy now, please try again later.");`\ `  `` ``;` To time out the *functionality* provided by a task, two distinct entries are needed: one to pass in arguments, and one to collect the result. Timing out on rendezvous with the latter achieves the desired effect. Ex. 11 `  `` Process_Data `\ `     `` Input (D  : ``  Datum);`\ `     `` Output (D  : `` Datum);`\ `  `` Process_Data;`\ `  `\ `  Input_Data, Output_Data : Datum;`\ `  `\ `  `\ `     `*`collect`*` Input_Data `*`from sensors`*`;`\ `     Process_Data.Input (Input_Data);`\ `     `\ `        Process_Data.Output (Output_Data);`\ `        `*`pass`*` Output_Data `*`to display task`*`;`\ `     `\ `        `` 0.1;`\ `        Log_Error ("Processing did not complete quickly enough.");`\ `     `` ``;`\ `  `` ``;` Symmetrically, a delay alternative in a selective wait statement allows a server task to withdraw an offer to accept calls after a maximum delay in achieving rendezvous with any client. Ex. 12 `  `` Resource_Lender `\ `     `` Get_Loan (Period : `` Duration);`\ `     `` Give_Back;`\ `  `` Resource_Lender;`\ `  ...`\ `  `` `` Resource_Lender `\ `     Period_Of_Loan : Duration;`\ `  `\ `     `\ `        `\ `           `` Get_Loan (Period : `` Duration) `\ `              Period_Of_Loan := Period;`\ `           `` Get_Loan;`\ `           `\ `              `` Give_Back;`\ `           `\ `              `` Period_Of_Loan;`\ `              Log_Error ("Borrower did not give up loan soon enough.");`\ `           `` ``;`\ `        `\ `           ``;`\ `        `` ``;`\ `     `` ``;`\ `  `` Resource_Lender;` ## Conditional entry calls An entry call can be made conditional, so that it is withdrawn if the rendezvous is not immediately achieved. This uses the select statement notation with an **else** part. Thus the constructs `  `\ `    Callee.Rendezvous;`\ `  `\ `    Do_something_else;`\ `  `` ``;` and `  `\ `    Callee.Rendezvous;`\ `  `\ `    `` 0.0;`\ `    Do_something_else;`\ `  `` ``;` seem to be conceptually equivalent. However, the attempt to start the rendezvous may take some time, especially if the callee is on another processor, so the *delay 0.0;* may expire although the callee would be able to accept the rendezvous, whereas the *else* construct is safe. ## Requeue statements A requeue statement allows an accept statement or entry body to be completed while redirecting it to a different or the same entry queue, even to one of another task. The called entry has to share the same parameter list or be parameter-less. The caller of the original entry is not aware of the requeue and the entry call continues although now to possibly another entry of another task. The requeue statement should normally be used to quickly check some precondition for the work proper. If these are fulfilled, the work proper is delegated to another task, hence the caller should nearly immediately be requeued. Thus requeuing may have an effect on timed entry calls. To be a bit more specific, say the timed entry call is to T1.E1, the requeue within T1.E1 to T2.E2: ` `` T1 `\ `  ...`\ `  `` E1 `\ `    ...  `\ `    `` T2``E2``  `\ `  `` E1`\ `  ...`\ ` T1` Let Delta_T be the timeout of the timed entry call to T1.E1. There are now several possibilities: 1\. Delta_T expires before T1.E1 is accepted.`</br>`{=html} : The entry call is aborted, i.e. taken out of the queue. 2\. Delta_T expires after T1.E1 is accepted.`</br>`{=html} : T1.E1 has finished (its check of preconditions) and T2.E2 is to be accepted.`</br>`{=html} : For the caller, who is unaware of the requeue, the entry call is still executing; it is completed only with the completion T2.E2. Thus, although the original entry call may be postponed for a long time while T2.E2 is waiting to be accepted, the call is executing from the caller\'s point of view. To avoid this behaviour, a call may be *requeued with abort*. This changes case 2 above: 2.a The call is requeued to T2.E2 before Delta_T expires. : 2.a.1. T2.E2 is accepted before expiration, the call continues until T2.E2 is completed. ```{=html} <!-- --> ``` : 2.a.2. Delta_T expires before T2.E2 is accepted: The entry call is aborted, i.e. taken out of the queue of T2.E2. 2.b The call is requeued to T2.E2 after the expiration of Delta_T. : 2.b.1. T2.E2 is immediately available (i.e. there is no requeue), T2.E2 continues to completion. ```{=html} <!-- --> ``` : 2.b.2. T2.E2 is queued: The entry call is aborted, i.e. taken out of the queue of T2.E2. In short, for a requeue with abort, the entry call to T1.E1 is completed in cases 1, 2.a.1 and 2.b.1; it is aborted in 2.a.2 and 2.b.2. So what is the difference between these three entries? ` `` E1 `\ `    ...  `\ `    `` T2``E2 `` ``  `\ `  `` E1`\ \ `  `` E2 `\ `    ...  `\ `    T2``E2``  `\ `  `` E2`\ \ `  `` E3 `\ `    ...  `\ `  `` E3`\ `  T2``E2``  ` E1 has just been discussed. After the requeue, its enclosing task is free for other work, while the caller is still suspended until its call is completed or aborted. E2 also delegates, however via an entry call. Thus E2 completes only with the completion of T2.E2. E3 first frees the caller, then delegates to T2.E2, i.e. the entry call is completed with E3. ## Scheduling FIFO, priority, priority inversion avoidance, \... to be completed. ## Interfaces and polymorphism Tasks and protected types can also implement interfaces. ` Printable `` `` ``;`\ \ ` Input (D  : ``  Printable);`\ \ \ ` Process_Data `` `` Printable `\ `   `` Input  (D  : ``  Datum);`\ `   `` Output (D  : `` Datum);`\ ` Process_Data;` To allow delegation necessary to the polymorphism, the interface **Printable** shall be defined in its own package. It is then possible to define different **task type** implementing the **Printable** interface and use these implemetations polymorphically: ` `` printable_package; `` printable_package;  `\ ` `` Printer `\ `    `` `` Print_Red  `` `` Printable `` ``;`\ `    `` `` Print_Blue `` `` Printable `` ``;`\ ` `\ `    `` `` Print_Red `\ `    `\ `       Ada.Text_IO.Put_Line ("Printing in Red");`\ `    `` Print_Red;`\ ` `\ `    `` `` Print_Blue `\ `    `\ `       Ada.Text_IO.Put_Line ("Printing in Blue");`\ `    `` Print_Blue;`\ ` `\ `    printer_task : `` Printable'Class;`\ ` `\ `    printer_task := `` Print_Red;`\ `    printer_task := `` Print_Blue;  `\ ` `` Printer;` This feature is also called **synchronized interfaces**. ## Restrictions and Profiles Ada tasking has too many features for some applications. Therefore there exist restrictions and profiles for certain, mostly safety or security critical applications. Restrictions and profiles are defined via pragmas. A restriction forbids the use of certain features, for instance the restriction No_Abort_Statements forbids the use of the abort statement. A profile (do not confuse with parameter profiles for subprograms) combines a set of restrictions. See ## See also ### Wikibook - Ada Programming - Ada Programming/Libraries/Ada.Storage IO - Ada Programming/Libraries/Ada.Task_Identification - Ada Programming/Libraries/Ada.Task_Attributes ### Ada Reference Manual #### Ada 95 - #### Ada 2005 - - ## Ada Quality and Style Guide - **Chapter 4: Program Structure** - - - Chapter 6: Concurrency es:Programación en Ada/Tareas
# Ada Programming/Object Orientation ## Object orientation in Ada Object oriented programming consists in building the software in terms of \"objects\". An \"object\" contains data and has a behavior. The data, normally, consists in constants and variables as seen in the rest of this book but could also, conceivably, reside outside the program entirely, i.e. on disk or on the network. The behavior consists in subprograms that operate on the data. What makes Object Orientation unique, compared to procedural programming, is not a single feature but the combination of several features: - *encapsulation*, i.e. the ability to separate the implementation of an object from its interface; this in turn separates \"clients\" of the object, who can only use the object in certain predefined ways, from the internals of the object, which have no knowledge of the outside clients. ```{=html} <!-- --> ``` - *inheritance*, the ability for one type of objects to inherit the data and behavior (subprograms) of another, without necessarily needing to break encapsulation; ```{=html} <!-- --> ``` - *type extension*, the ability for an object to add new data components and new subprograms on top of the inherited ones and to *replace* some inherited subprograms with its own versions; this is called *overriding*. ```{=html} <!-- --> ``` - *polymorphism*, the ability for a \"client\" to use the services of an object without knowing the exact type of the object, i.e. in an abstract way. Indeed at run time, the actual objects can have different types from one invocation to the next. It is possible to do object-oriented programming in any language, even assembly. However, type extension and polymorphism are very difficult to get right without language support. In Ada, each of these concepts has a matching construct; this is why Ada supports object-oriented programming directly. - Packages provide encapsulation; - Derived types provide inheritance; - Record extensions, described below, provide for type extension; - Class-wide types, also described below, provide for polymorphism. Ada has had encapsulation and derived types since the first version (MIL-STD-1815 in 1980), which led some to qualify the language as \"object-oriented\" in a very narrow sense. Record extensions and class-wide types were added in Ada 95. Ada 2005 further adds interfaces. The rest of this chapter covers these aspects. ### The simplest object: the Singleton ` Directory `\ `  `` Present (Name_Pattern: String) `` Boolean;`\ `  `\ `     `` Visit (Full_Name, Phone_Number, Address: String;`\ `                           Stop: `` Boolean);`\ `  `` Iterate (Name_Pattern: String);`\ ` Directory;` The Directory is an object consisting of data (the telephone numbers and addresses, presumably held in an external file or database) and behavior (it can look an entry up and traverse all the entries matching a Name_Pattern, calling Visit on each). A simple package provides for encapsulation (the inner workings of the directory are hidden) and a pair of subprograms provide the behavior. This pattern is appropriate when only one object of a certain type must exist; there is, therefore, no need for type extension or polymorphism. ### Primitive operations In Ada, methods are usually referred to by the technical term *primitive subprograms of a tagged type* or the equivalent term *primitive operations of a tagged type*. The primitive operations of a type are those that are always available wherever the type is used. For the tagged types that are used in object oriented programming, they also can be inherited by and overridden by derived types, and can be dynamically dispatched. Primitive operations of a type need to be declared immediately within the same package as the type (not within a nested package nor a child package). For tagged types, new primitive operations and overrides of inherited primitive operations are further required to be declared before the *freezing point* of the type. Any subprograms declared after the freezing point will not be considered primitive, and therefore cannot be inherited and are not dynamically dispatched. Freezing points are discussed in more detail below, but the simple practice of declaring all primitive operations immediately following the initial type declaration will ensure that those subprograms are indeed recognized as primitive. Primitive operations of type T need to have at least one parameter of type `T` or of type `access T`. While most object-oriented languages automatically provide a `this` or `self` pointer, Ada requires that you explicitly declare a formal parameter to receive the current object. That typically will be the first parameter in the list, which enables the `object.subprogram` call syntax (available since Ada 2005), but it may be at any parameter position. Tagged types are always passed by reference; the parameter passing method has nothing to do with the parameter modes `in` and `out`, which describe the dataflow. The parameter passing method is identical for `T` and `access T`. For tagged types, no other directly dispatchable types can be used in the parameter list because Ada doesn\'t offer multiple dispatching. The following example is illegal. ` P `\ `   `` A `` `` ``;`\ `   `` B `` `` ``;`\ `   `` Proc (This: B; That: A); `\ ` P;` When additional dispatchable objects need to be passed in, the parameter list should declare them using their class-wide types, `T'Class`. For example: ` P `\ `   `` A `` `` ``;`\ `   `` B `` `` ``;`\ `   `` Proc (This: B; That: A'Class); `\ ` P;` Note, however, that this does not limit the number of parameters of the same tagged type. For example, the following definition is legal. ` P `\ `   `` A `` `` ``;`\ `   `` Proc (This, That: A); `\ ` P;` Primitive operations of tagged types are dispatching operations. Whether a call to such a primitive operation is in effect dispatching or statically bound, depends on the context (see below). Note that in a dispatching call both actual parameters of the last example must have the same tag (i.e. the same type); Constraint_Error will be called if the tag check fails. ### Derived types Type derivation has been part of Ada since the very start. ` P `\ `  `` T ``;`\ `  `` Create (Data: Boolean) `` T;  `\ `  `` Work (Object : `` T);        `\ `  `` Work (Pointer: `` T);        `\ `  `` Acc_T `` T;`\ `  `` Proc (Pointer: Acc_T);           `\ \ `  `` T `\ `    Data: Boolean;`\ `  ``;`\ ` P;` The above example creates a type T that contains data (here just a Boolean but it could be anything) and behavior consisting of some subprograms. It also demonstrates encapsulation by placing the details of the type T in the private part of the package. The primitive operations of T are the function Create, the overloaded procedures Work, and the predefined \"=\" operator; Proc is not primitive, since it has an *access type* on T as parameter --- don\'t confuse this with an *access parameter*, as used in the second procedure Work. When deriving from T, the primitive operations are inherited. ` P;`\ ` Q `\ `  `` Derived `` P.T;`\ ` Q;` The type Q.Derived has the same data *and the same behavior* as P.T; it inherits both the data *and the subprograms*. Thus it is possible to write: ` Q;`\ ` Main `\ `  Object: Q.Derived := Q.Create (Data => False);`\ \ `  Q.Work (Object);`\ ` Main;` Inherited operations may be overridden and new operations added, but the rules (Ada 83) unfortunaltely are somewhat different from the rules for tagged types (Ada 95). Admittedly, the reasons for writing this may seem obscure. The purpose of this kind of code is to have objects of types P.T and Q.Derived, which are not compatible: `Ob1: P.T;`\ `Ob2: Q.Derived;` `Ob1 := Ob2;              -- illegal`\ `Ob1 := P.T (Ob2);        -- but convertible`\ `Ob2 := Q.Derived (Ob1);  -- in both directions` This feature is not used very often (it\'s used e.g. for declaring types reflecting physical dimensions) but I present it here to introduce the next step: type extension. ### Type extensions Type extensions are an Ada 95 amendment. A tagged type provides support for dynamic polymorphism and type extension. A tagged type bears a hidden tag that identifies the type at run-time. Apart from the tag, a tagged record is like any other record, so it can contain arbitrary data. ` Person `\ `   `` Object `` `\ `     `\ `         Name   : String (1 .. 10);`\ `         Gender : Gender_Type;`\ `     `` ``;`\ `   `` Put (O : Object);`\ ` Person;` As you can see, a `Person.Object` is an *object* in the sense that it has data and behavior (the procedure `Put`). However, this object does not hide its data; any program unit that has a ` Person` clause can read and write the data in a Person.Object directly. This breaks encapsulation and also illustrates that Ada completely separates the concepts of *encapsulation* and *type*. Here is a version of Person.Object that encapsulates its data: ` Person `\ `   `` Object `` ``;`\ `   `` Put (O : Object);`\ \ `   `` Object `` `\ `     `\ `         Name   : String (1 .. 10);`\ `         Gender : Gender_Type;`\ `     `` ``;`\ ` Person;` Because the type Person.Object is tagged, it is possible to create a record extension, which is a derived type with additional data. ` Person;`\ ` Programmer `\ `   `` Object `` `` Person.Object ``;`\ \ `   `` Object `` `` Person.Object `\ `     `\ `        Skilled_In : Language_List;`\ `     `` ``;`\ ` Programmer;` The type `Programmer.Object` inherits the data and behavior, i.e. the type\'s primitive operations, from `Person.Object`; it is thus possible to write: ` Programmer;`\ ` Main `\ `   Me : Programmer.Object;`\ \ `   Programmer.Put (Me);`\ `   Me.Put; `\ ` Main;` So the declaration of the type `Programmer.Object`, as a record extension of `Person.Object`, implicitly declares a ` Put` that applies to a `Programmer.Object`. Like in the case of untagged types, objects of type Person and Programmer are convertible. However, where untagged objects are convertible in either direction, conversion of tagged types only works in the direction to the root. (Conversion away from the root would have to add components out of the blue.) Such a conversion is called a *view conversion*, because components are not lost, they only become invisible. Extension aggregates have to be used if you go away from the root. ### Overriding Now that we have introduced tagged types, record extensions and primitive operations, it becomes possible to understand overriding. In the examples above, we introduced a type `Person.Object` with a primitive operation called `Put`. Here is the body of the package: ` Ada.Text_IO;`\ ` Person `\ `   `` Put (O : Object) `\ `   `\ `      Ada.Text_IO.Put (O.Name);`\ `      Ada.Text_IO.Put (" is a ");`\ `      Ada.Text_IO.Put_Line (Gender_Type'Image (O.Gender));`\ `   `` Put;`\ ` Person;` As you can see, this simple operation prints both data components of the record type to standard output. Now, remember that the record extension `Programmer.Object` has an additional data member. If we write: ` Programmer;`\ ` Main `\ `   Me : Programmer.Object;`\ \ `   Programmer.Put (Me);`\ `   Me.Put; `\ ` Main;` then the program will call the inherited primitive operation `Put`, which will print the name and gender *but not the additional data*. In order to provide this extra behavior, we must *override* the inherited procedure `Put` like this: ` Person;`\ ` Programmer `\ `   `` Object `` `` Person.Object ``;`\ `   `` `\ `   `` Put (O : Object);`\ \ `   `` Object `` `` Person.Object `\ `     `\ `        Skilled_In : Language_List;`\ `     `` ``;`\ ` Programmer;` ` Programmer `\ `   `` Put (O : Object) `\ `   `\ `      Person.Put (Person.Object (O)); `\ `      Put (O.Skilled_In); `\ `   `` Put;`\ ` Programmer;` `Programmer.Put` *overrides* `Person.Put`; in other words it *replaces* it completely. Since the intent is to extend the behavior rather than replace it, `Programmer.Put` calls `Person.Put` as part of its behavior. It does this by converting its parameter from the type `Programmer.Object` to its ancestor type `Person.Object`. This construct is a *view conversion*; contrary to a normal type conversion, it does *not* create a new object and does *not* incur any run-time cost (and indeed, if the operand of such *view conversion* was actually a variable, the result can be used when an out parameter is required (eg. procedure call)). Of course, it is optional that an overriding operation call its ancestor; there are cases where the intent is indeed to replace, not extend, the inherited behavior. (Note that also for untagged types, overriding of inherited operations is possible. The reason why it\'s discussed here is that derivation of untagged types is done rather seldom.) ### Polymorphism, class-wide programming and dynamic dispatching The full power of object orientation is realized by polymorphism, class-wide programming and dynamic dispatching, which are different words for the same, single concept. To explain this concept, let us extend the example from the previous sections, where we declared a base tagged type `Person.Object` with a primitive operation `Put` and a record extension `Programmer.Object` with additional data and an overriding primitive operation `Put`. Now, let us imagine a collection of persons. In the collection, some of the persons are programmers. We want to traverse the collection and call `Put` on each person. When the person under consideration is a programmer, we want to call `Programmer.Put`; when the person is not a programmer, we want to call `Person.Put`. This, in essence, is polymorphism, class-wide programming and dynamic dispatching. With Ada\'s strong typing, ordinary calls cannot be dynamically dispatched; a call to an operation on a declared type must always be statically bound to go to the operation defined for that specific type. Dynamic dispatching (known as simply *dispatching* in Ada parlance) is provided through separate *class-wide types* that are polymorphic. Each tagged type, such as `Person.Object`, has a corresponding *class of types* which is the set of types comprising the type `Person.Object` itself and all types that extend `Person.Object`. In our example, this class consists of two types: - `Person.Object` - `Programmer.Object` Ada 95 defines the `Person.Object'Class` attribute to denote the corresponding class-wide type. In other words: \ `   Someone : Person.Object'Class := ...; `\ \ `   Someone.Put; `\ `;` The declaration of Someone denotes an object that may be of *either* type, `Person.Object` or `Programmer.Object`. Consequently, the call to the primitive operation `Put` dispatches dynamically to either `Person.Put` or `Programmer.Put`. The only problem is that, since we don\'t know whether Someone is a programmer or not, we don\'t know how many data components Someone has, either, and therefore we don\'t know how many bytes Someone takes in memory. For this reason, the class-wide type `Person.Object'Class` is *indefinite*. It is impossible to declare an object of this type without giving some constraint. It is, however, possible to: - declare an object of a class-wide with an initial value (as above). The object is then constrained by its initial value. - declare an *access value* to such an object (because the access value has a known size); - pass objects of a class-wide type as parameters to subprograms - assign an object of a specific type (in particular, the result of a function call) to a variable of a class-wide type. With this knowledge, we can now build a polymorphic collection of persons; in this example we will quite simply create an array of access values to persons: ` Person;`\ ` Main `\ `   `` Person_Access `` Person.Object'Class;`\ `   `` Array_Of_Persons  `` (Positive `` <>) of Person_Access;`\ \ `   `` Read_From_Disk `` Array_Of_Persons ``;`\ \ `   Everyone : `` Array_Of_Persons := Read_From_Disk;`\ ` `\ `   `` K `` Everyone'Range `\ `      Everyone (K).``.Put; `\ `   ``;`\ ` Main;` The above procedure achieves our desired goal: it traverses the array of Persons and calls the procedure `Put` that is appropriate for each person. #### Advanced topic: How dynamic dispatching works You don\'t need to know how dynamic dispatching works in order to use it effectively but, in case you are curious, here is an explanation. The first component of each object in memory is the *tag*; this is why objects are of a *tagged* type rather than plain records. The tag really is an access value to a table; there is one table for each specific type. The table contains access values to each primitive operation of the type. In our example, since there are two types `Person.Object` and `Programmer.Object`, there are two tables, each containing a single access value. The table for `Person.Object` contains an access value to `Person.Put` and the table for `Programmer.Object` contains an access value to `Programmer.Put`. When you compile your program, the compiler constructs both tables and places them in the program executable code. Each time the program creates a new object of a specific type, it automatically sets its tag to point to the appropriate table. Each time the program performs a *dispatching call* of a primitive operation, the compiler inserts object code that: - dereferences the tag to find the table of primitive operations for the specific type of the object at hand - dereferences the access value to the primitive operation - calls the primitive operation. Conversely, when the program performs a call where the parameter is a view conversion to an ancestor type, the compiler performs these two dereferences at compile time rather than run time: such a call is *statically bound*; the compiler emits code that directly calls the primitive operation of the ancestor type specified in the view conversion. #### Redispatching Dispatching is controlled by the (hidden) tag of the object. So what happens when a primitive operation `Op1` calls another primitive operation `Op2` on the same object? ` `` Root `` `` ``;`\ ` `` Op1 (This: Root);`\ ` `` Op2 (This: Root);`\ \ ` `` Derived `` `` Root `` ``;`\ ` -- Derived inherits Op1`\ ` `` `` Op2 (This: Derived);`\ \ ` `` Op1 (This: Root) `\ ` `\ `   ...`\ `   Op2 (This);               -- not redispatching`\ `   Op2 (Root'Class (This));  -- redispatching`\ `   This.Op2;                 -- not redispatching (new syntax since Ada 2005)`\ `   (Root'Class (This)).Op2;  -- redispatching (new syntax since Ada 2005)`\ `   ...`\ ` `` Op1;`\ \ ` D: Derived;`\ ` C: Root'Class := D;`\ \ ` Op1 (D);  -- statically bound call`\ ` Op1 (C);  -- dispatching call`\ ` D.Op1;    -- statically bound call (new syntax since Ada 2005)`\ ` C.Op1;    -- dispatching call (new syntax since Ada 2005)` In this fragment, `Op1` is not overridden, whereas `Op2` is overridden. The body of `Op1` calls `Op2`, so which `Op2` will be called if `Op1` is called for an object of type `Derived`? The basic rules of dispatching still apply. Calls to `Op2` will be dispatched when called using an object of a class-wide type. The formal parameter lists for the operations specify the type of `This` to be a specific type, not class-wide. In fact, that parameter *must* be a specific type so that the operation will be dispatched for objects of that type, and to allow the operation\'s code to access any additional data items associated with that type. If you want redispatching, you must state that explicitly by converting the parameter of the specific type to the class-wide type again. (Remember: view conversions never lose components, they just hide them. A conversion to a class-wide type can unhide them again.) The first call `Op1 (D)` (statically bound, i.e., not dispatching) executes the inherited `Op1` --- and within `Op1`, the first call to `Op2` is also statically bound (there is no redispatching) because parameter `This` is a view conversion to specific type `Root`. However, the second call is dispatching because the parameter `This` is converted to the class-wide type. That call dispatches to the overriding `Op2`. Because the conventional `This.Op2` call is *not* dispatching, the call will be to `Root.Op2` even though the object itself is of type `Derived` and the `Op2` operation is overridden. *This is very different from how other OO languages behave.* In other OO languages, a method is either dispatching or not. In Ada, an operation is either *available* for dispatching or not. Whether or not dispatching is actually *used* for a given call depends on the way that the object\'s type is specified at that call point. For programmers accustomed to other OO languages, it can come as quite a surprise that calls from a dispatchable operation to other operations on the same object are, by default, *not* (dynamically) dispatched. The default of not redispatching is not an issue if all of the operations have been overridden, because they all will be operating on the expected type of object. However, it has ramifications when writing code for types that might be extended by another type sometime in the future. It\'s possible that the new type will not work as intended if it doesn\'t override all of the primitive operations that call other primitive operations. The safest policy is to use a class-wide conversion of the object to force dispatching of calls. One way to accomplish that is to define a class-wide constant in each dispatched method: ` `` Op2 (This: Derived) `\ `   This_Class: `` Root'Class := This;`\ ` ` `This` is needed to access data items and to make any non-dispatching calls. `This_Class` is needed to make dispatching calls. Less commonly encountered and perhaps less surprising, calls from a non-dispatchable (class-wide) routine for a tagged type to other routines on the same object are, by default, dispatched: ` `` Root `` `` ``;`\ ` `` Op1 (This: Root'Class);`\ ` `` Op2 (This: Root);`\ \ ` `` Derived `` `` Root `` ``;`\ ` -- Derived does `**`not`**` inherit Op1, rather Op1 is applicable to Derived.`\ ` `` `` Op2 (This: Derived);`\ \ ` `` Op1 (This: Root'Class) `\ ` `\ `   ...`\ `   Op2 (This);               -- dispatching`\ `   Op2 (Root (This));        -- static call`\ `   This.Op2;                 -- dispatching (new syntax since Ada 2005)`\ `   (Root (This)).Op2;        -- static call (new syntax since Ada 2005)`\ `   ...`\ ` `` Op1;`\ \ ` D: Derived;`\ ` C: Root'Class := D;`\ \ ` Op1 (D);  -- static call`\ ` Op1 (C);  -- static call`\ ` D.Op1;    -- static call (new syntax since Ada 2005)`\ ` C.Op1;    -- static call (new syntax since Ada 2005)` Note that calls on `Op1` are always static, since `Op1` is *not* inherited. Its parameter type is class-wide, so the operation is *applicable* to all types derived from Root. (Op2 has an entry for each type derived from `Root` in the dispatch table. There is no such dispatch table for `Op1`; rather there is only one such operation for all types in the class.) Normal calls *from* `Op1` are dispatched because the declared type of `This` is class-wide. The default to dispatching usually isn\'t bothersome because class-wide operations are typically used to perform a script involving calls to one or more dispatched operations. #### Run-time type identification Run-time type identification allows the program to (indirectly or directly) query the tag of an object at run time to determine which type the object belongs to. This feature, obviously, makes sense only in the context of polymorphism and dynamic dispatching, so works only on tagged types. You can determine whether an object belongs to a certain class of types, or to a specific type, by means of the membership test , like this: ` Base    `` `` ``;`\ ` Derived `` `` Base    `` ``;`\ ` Leaf    `` `` Derived `` ``;`\ \ `...`\ ` Explicit_Dispatch (This : `` Base'Class) `\ \ `   `` This `` Leaf `` ... ``;`\ `   `` This `` Derived'Class `` ... ``;`\ ` Explicit_Dispatch;` Thanks to the strong typing rules of Ada, run-time type identification is in fact rarely needed; the distinction between class-wide and specific types usually allows the programmer to ensure objects are of the appropriate type without resorting to this feature. Additionally, the reference manual defines `package Ada.Tags` (RM 3.9(6/2)), attribute `'Tag` (RM 3.9(16,18)), and `function Ada.Tags.Generic_Dispatching_Constructor` (RM 3.9(18.2/2)), which enable direct manipulation with tags. ### Creating Objects The Language Reference Manual\'s section on states when an object is created, and destroyed again. This subsection illustrates how objects are created. The LRM section starts, For example, assume a typical hierarchy of object oriented types: a top-level type `Person`, a `Programmer` type derived from `Person`, and possibly more kinds of persons. Each person has a name; assume `Person` objects to have a `Name` component. Likewise, each `Person` has a `Gender` component. The `Programmer` type inherits the components and the operations of the `Person` type, so `Programmer` objects have a `Name` and a `Gender` component, too. `Programmer` objects may have additional components specific to programmers. Objects of a tagged type are created the same way as objects of any type. The second LRM sentence says, for example, that an object will be created when you declare a variable or a constant of a type. For the tagged type `Person`, \ `   P`` Person`\ \ `   Text_IO``Put_Line``"The name is " `` P``Name`\ Nothing special so far. Just like any ordinary variable declaration this O-O one is elaborated. The result of elaboration is an object named `P` of type `Person`. However, `P` has only default name and gender value components. These are likely not useful ones. One way of giving initial values to the object\'s components is to assign an aggregate. \ `   P`` Person `` ``Name `` "Scorsese"`` Gender `` Male`\ \ `   Text_IO``Put_Line``"The name is " `` P``Name`\ The parenthesized expression after := is called an *aggregate* (). Another way to create an object that is mentioned in the LRM paragraph is to call a function. An object will be created as the return value of a function call. Therefore, instead of using an aggregate of initial values, we might call a function returning an object. Introducing proper O-O information hiding, we change the package containing the `Person` type so that `Person` becomes a private type. To enable clients of the package to construct `Person` objects we declare a function that returns them. (The function may do some interesting construction work on the objects. For instance, the aggregate above will most probably raise the exception Constraint_Error depending on the name string supplied; the function can mangle the name so that it matches the declaration of the component.) We also declare a function that returns the name of `Person` objects. ` Persons `\ \ `   `` Person `` `` `\ \ `   `` Make ``Name`` String`` Sex`` Gender_Type`` `` Person`\ \ `   `` Name ``P`` Person`` `` String`\ \ \ `   `` Person `` `\ `      `\ `         Name   `` String ``1 `` 10`\ `         Gender `` Gender_Type`\ `      `` `\ \ ` Persons` Calling the `Make` function results in an object which can be used for initialization. Since the `Person` type is **private** we can no longer refer to the `Name` component of `P`. But there is a corresponding function `Name` declared with type `Person` making it a socalled primitive operation. (The component and the function in this example are both named `Name` However, we can choose a different name for either if we want.) \ `   P`` Person `` Make ``Name `` "Orwell"`` Sex `` Male`\ \ `   Text_IO``Put_Line``"The name is " `` Name``P`\ Objects can be copied into another. The target object is first destroyed. Then the component values of the source object are assigned to the corresponding components of the target object. In the following example, the default initialized `P` gets a copy of one of the objects created by the `Make` calls. \ `   P`` Person`\ \ `   `` 2001 `` 1984 `\ `      P `` Make ``Name `` "Kubrick"`` Sex `` Male`\ `   `\ `      P `` Make ``Name `` "Orwell"`` Sex `` Male`\ `   `` `\ \ `   Text_IO``Put_Line``"The name is " `` Name``P`\ So far, there is no mention of the `Programmer` type derived from `Person`. There is no polymorphism yet, and likewise initialization does not yet mention inheritance. Before dealing with `Programmer` objects and their initialization a few words about class-wide types are in order. ### More details on primitive operations Remember what we said before about \"Primitive Operations\". Primitive operations are: - subprograms taking a parameter of the tagged type; - functions returning an object of the tagged type; - subprograms taking a parameter of an *anonymous access type* to the tagged type; - In Ada 2005 only, functions returning an *anonymous access type* to the tagged type; Additionally, primitive operations must be declared before the type is *frozen* (the concept of freezing will be explained later): Examples: ` X `\ `   `` Object `` `` `` ``;`\ \ `   `` Primitive_1 (This : ``     Object);`\ `   `` Primitive_2 (That :    `` Object);`\ `   `` Primitive_3 (Me   : `` `` Object);`\ `   `` Primitive_4 (Them : `` Object);`\ `   ``  Primitive_5 `` Object;`\ `   ``  Primitive_6 (Everyone : Boolean) `` `` Object;`\ ` X;` All of these subprograms are primitive operations. A primitive operation can also take parameters of the same or other types; also, the controlling operand does not have to be the first parameter: ` X `\ `   `` Object `` `` `` ``;`\ \ `   `` Primitive_1 (This : `` Object; Number : `` Integer);`\ `   `` Primitive_2 (You  : `` Boolean; That : `` Object);`\ `   `` Primitive_3 (Me, Her : `` `` Object);`\ ` X;` The definition of primitive operations specifically excludes named access types and class-wide types as well as operations not defined immediately in the same declarative region. Counter-examples: ` X `\ `   `` Object `` `` `` ``;`\ `   `` Object_Access `` `` Object;`\ `   `` Object_Class_Access `` `` Object'Class;`\ \ `   `` Not_Primitive_1 (This : ``     Object'Class);`\ `   `` Not_Primitive_2 (This : `` `` Object_Access);`\ `   `` Not_Primitive_3 (This :    `` Object_Class_Access);`\ `   ``  Not_Primitive_4 `` Object'Class;`\ \ `   `` Inner `\ `       `` Not_Primitive_5 (This : `` Object);`\ `   `` Inner;`\ ` X;` #### Advanced topic: Freezing rules Freezing rules (ARM 13.14) are perhaps the most complex part of the Ada language definition; this is because the standard tries to describe freezing as unambiguously as possible. Also, that part of the language definition deals with freezing of all entities, including complicated situations like generics and objects reached by dereferencing access values. You can, however, get an intuitive understanding of freezing of tagged types if you understand how dynamic dispatching works. In that section, we saw that the compiler emits a table of primitive operations for each tagged type. The point in the program text where this happens is the point where the tagged type is *frozen*, i.e. the point where the table becomes complete. After the type is frozen, no more primitive operations can be added to it. This point is the earliest of: - the end of the package spec where the tagged type is declared - the appearance of the first type derived from the tagged type Example: ` X `\ \ `  `` Object `` `` `` ``;`\ `  `` Primitive_1 (This: `` Object);`\ \ `  -- this declaration freezes Object`\ `  `` Derived `` `` Object `` `` ``;`\ \ `  -- illegal: declared after Object is frozen`\ `  `` Primitive_2 (This: `` Object);`\ \ ` X;` Intuitively: at the point where Derived is declared, the compiler starts a new table of primitive operations for the derived type. This new table, initially, is equal to the table of the primitive operations of the parent type, `Object`. Hence, `Object` must freeze. - the declaration of a variable of the tagged type Example: ` X `\ \ `  `` Object `` `` `` ``;`\ `  `` Primitive_1 (This: `` Object);`\ \ `  V: Object;  -- this declaration freezes Object`\ \ `  -- illegal: Primitive operation declared after Object is frozen`\ `  `` Primitive_2 (This: `` Object);`\ \ ` X;` Intuitively: after the declaration of `V`, it is possible to call any of the primitive operations of the type on `V`. Therefore, the list of primitive operations must be known and complete, i.e. frozen. - The completion (*not* the declaration, if any) of a constant of the tagged type: ` X `\ \ `  `` Object `` `` `` ``;`\ `  `` Primitive_1 (This: `` Object);`\ \ `  -- this declaration does NOT freeze Object`\ `  Deferred_Constant: `` Object;`\ \ `  `` Primitive_2 (This : `` Object); -- OK`\ \ \ \ `  -- only the completion freezes Object`\ `  Deferred_Constant: `` Object := (`` ``);`\ \ `  -- illegal: declared after Object is frozen`\ `  `` Primitive_3 (This: `` Object);`\ \ ` `` X;` ### New features of Ada 2005 Ada 2005 adds overriding indicators, allows anonymous access types in more places and offers the object.method notation. #### Overriding indicators The new keyword can be used to indicate whether an operation overrides an inherited subprogram or not. Its use is optional because of upward-compatibility with Ada 95. For example: ` X `\ `    `` Object `` `` `` ``;`\ \ `   ``  Primitive `` `` Object; `\ \ `   `` Derived_Object `` `` Object `` `` ``;`\ \ `   `` `\ `   `` Primitive (This : `` Derived_Object); `\ \ `   `\ `   ``  Primitive `` Derived_Object;`\ ` X;` The compiler will check the desired behaviour. This is a good programming practice because it avoids some nasty bugs like not overriding an inherited subprogram because the programmer spelt the identifier incorrectly, or because a new parameter is added later in the parent type. It can also be used with abstract operations, with renamings, or when instantiating a generic subprogram: ` `\ ` Primitive_X (This : `` Object) `` ``;`\ \ \ `  Primitive_Y `` Object `` Some_Other_Subprogram;`\ \ ` `\ ` Primitive_Z (This : `` Object)`\ `      `` `` Generic_Procedure (Element => Integer);` #### Object.Method notation We have already seen this notation: ` X `\ `   `` Object `` `` `` ``;`\ \ `   `` Primitive (This: `` Object; That: `` Boolean);`\ ` X;` ` X;`\ ` Main `\ `   Obj : X.Object;`\ \ `   Obj.Primitive (That => True); `\ ` Main;` This notation is only available for primitive operations where the controlling parameter is the *first* parameter. ### Abstract types A tagged type can also be abstract (and thus can have abstract operations): ` X `\ \ `   `` Object `` `` `` …;`\ \ `   `` One_Class_Member      (This : ``     Object);`\ `   `` Another_Class_Member  (This : `` `` Object);`\ `   ``  Abstract_Class_Member `` Object  `` ``;`\ \ ` X;` An abstract operation cannot have any body, so derived types are forced to override it (unless those derived types are also abstract). See next section about interfaces for more information about this. The difference with a non-abstract tagged type is that you cannot declare any variable of this type. However, you can declare an access to it, and use it as a parameter of a class-wide operation. ### Multiple Inheritance via Interfaces Interfaces allow for a limited form of multiple inheritance (taken from Java). On a semantic level they are similar to an \"abstract tagged null record\" as they may have primitive operations but cannot hold any data and thus these operations cannot have a body, they are either declared or . *Abstract* means the operation has to be overridden, *null* means the default implementation is a null body, i.e. one that does nothing. An interface is declared with: ` Printable `\ `   `` Object `` ``;`\ `   `` Class_Member_1 (This : ``     Object) `` ``;`\ `   `` Class_Member_2 (This :    `` Object) `` ``;`\ ` Printable;` You implement an by adding it to a concrete *class*: ` Person;`\ ` Programmer `\ `   `` Object `` `` Person.Object`\ `                  `` Printable.Object`\ `   `\ `      `\ `         Skilled_In : Language_List;`\ `      `` ``;`\ `   `\ `   `` Class_Member_1   (This : `` Object);`\ `   `` `\ `   `` New_Class_Member (This : Object; That : String);`\ ` Programmer;` As usual, all inherited abstract operations must be overridden although *null subprograms* ones need not. Such a type may implement a list of interfaces (called the *progenitors*), but can have only one *parent*. The parent may be a concrete type or also an interface. ` Derived `` `` Parent `` Progenitor_1 `` Progenitor_2 ... `` ...;` ### Multiple Inheritance via Mix-in Ada supports multiple inheritance of *interfaces* (see above), but only single inheritance of *implementation*. This means that a tagged type can *implement* multiple interfaces but can only *extend* a single ancestor tagged type. This can be problematic if you want to add behavior to a type that already extends another type; for example, suppose you have ` Base ``;`\ ` Derived `` Base ``;` and you want to make `Derived` controlled, i.e. add the behavior that `Derived` controls its initialization, assignment and finalization. Alas you cannot write: ` Derived `` Base `` ``.Controlled ``; ` since for historical reasons does not define interfaces `Controlled` and `Limited_Controlled`, but abstract types. If your base type is not limited, there is no good solution for this; you have to go back to the root of the class and make it controlled. (The reason will become obvious presently.) For limited types however, another solutions is the use of a mix-in: ` Base ``;`\ ` Derived;`\ \ ` Controlled_Mix_In (Enclosing: `` Derived) `\ `  `` ``.Limited_Controlled ``;`\ \ ` Initialize (This: `` Controlled_Mix_In);`\ ` Finalize   (This: `` Controlled_Mix_In);`\ \ ` Derived `` Base `\ `  Mix_In: Controlled_Mix_In (Enclosing => Derived'Access); `\ `  `\ `;` This special kind of mix-in is an object with an access discriminant that references its enclosing object (also known as *Rosen trick*). In the declaration of the `Derived` type, we initialize this discriminant with a special syntax: `Derived'Access` really refers to an access value to the *current instance* of type `Derived`. Thus the access discriminant allows the mix-in to see its enclosing object and all its components; therefore it can initialize and finalize its enclosing object: ` Initialize (This: `` Controlled_Mix_In) `\ `  Enclosing: Derived `` This.Enclosing.``;`\ \ `  `\ ` Initialize;` and similarly for `Finalize`. The reason why this does not work for non-limited types is the self-referentiality via the discriminant. Imagine you have two variables of such a non-limited type and assign one to the other: `X := Y;` In an assignment statement, `Adjust` is called only *after* `Finalize` of the target `X` and so cannot provide the new value of the discriminant. Thus `X.Mixin_In.Enclosing` will inevitably reference `Y`. Now let\'s further extend our hierarchy: ` Further `` Derived ``;`\ \ ` Initialize (This: `` Further);`\ ` Finalize   (This: `` Further);` Oops, this does not work because there are no corresponding procedures for `Derived`, yet -- so let\'s quickly add them. ` Base ``;`\ ` Derived;`\ \ ` Controlled_Mix_In (Enclosing: `` Derived) `\ `  `` ``.Limited_Controlled ``;`\ \ ` Initialize (This: `` Controlled_Mix_In);`\ ` Finalize   (This: `` Controlled_Mix_In);`\ \ ` Derived `` Base `\ `  Mix_In: Controlled_Mix_In (Enclosing => Derived'Access);  `\ `  `\ `;`\ \ ` Initialize (This: `` Derived);  `\ ` Finalize   (This: `` Derived);`\ \ ` Further `` Derived ``;` ` Initialize (This: `` Further);`\ ` Finalize   (This: `` Further);` We have of course to write `not overriding` for the procedures on `Derived` because there is indeed nothing they could override. The bodies are ` Initialize (This: `` Derived) `\ \ `  `\ ` Initialize;` ` Initialize (This: `` Controlled_Mix_In) `\ `  Enclosing: Derived `` This.Enclosing.``;`\ \ `  Initialize (Enclosing);`\ ` Initialize;` To our dismay, we have to learn that `Initialize/Finalize` for objects of type `Further` will not be called, instead those for the parent `Derived`. Why? \ `  X: Further;  -- Initialize (Derived (X)) is called here`\ \ `  ``;`\ `;  -- Finalize (Derived (X)) is called here` The reason is that the mix-in defines the local object `Enclosing` to be of type `Derived` in the renames-statement above. To cure this, we have necessarily to use the dreaded redispatch (shown in different but equivalent notations): ` Initialize (This: `` Controlled_Mix_In) `\ `  Enclosing: Derived `` This.Enclosing.``;`\ \ `  Initialize (Derived'Class (Enclosing));`\ ` Initialize;` ` Finalize (This: `` Controlled_Mix_In) `\ `  Enclosing: Derived'Class `` Derived'Class (This.Enclosing.``);`\ \ `  Enclosing.Finalize;`\ ` Finalize;` \ `  X: Further;  -- Initialize (X) is called here`\ \ `  ``;`\ `;  -- Finalize (X) is called here` Alternatively (and presumably better still) is to write ` Controlled_Mix_In (Enclosing: `` Derived'Class) `\ `  `` ``.Limited_Controlled ``;` Then we automatically get redispatch and can omit the type conversions on `Enclosing`. ## Class names Both the class package and the class record need a name. In theory they may have the same name, but in practice this leads to nasty `<small>`{=html}(because of unintuitive error messages)`</small>`{=html} name clashes when you use the clause. So over time three de facto naming standards have been commonly used. ### Classes/Class The package is named by a plural noun and the record is named by the corresponding singular form. ` Persons `\ \ `   `` Person `` `\ `      `\ `         Name   : String (1 .. 10);`\ `         Gender : Gender_Type;`\ `      `` ``;`\ \ ` Persons;` This convention is the usually used in Ada\'s built-in libraries. Disadvantage: Some \"multiples\" are tricky to spell, especially for those of us who aren\'t native English speakers. ### Class/Object The package is named after the class, the record is just named Object. ` Person `\ \ `   `` Object `` `\ `      `\ `         Name   : String (1 .. 10);`\ `         Gender : Gender_Type;`\ `      `` ``;`\ \ ` Person;` Most UML and IDL code generators use this technique. Disadvantage: You can\'t use the clause on more than one such class packages at any one time. However you can always use the \"type\" instead of the package. ### Class/Class_Type The package is named after the class, the record is postfixed with *\_Type*. ` Person `\ \ `   `` Person_Type `` `\ `      `\ `         Name   : String (1 .. 10);`\ `         Gender : Gender_Type;`\ `      `` ``;`\ \ ` Person;` Disadvantage: lots of ugly \"\_Type\" postfixes. ## Object-Oriented Ada for C++ programmers In C++, the construct ``` c++ struct C { virtual void v(); void w(); static void u(); }; ``` is strictly equivalent to the following in Ada: ` P `\ `  `` C ``;`\ `  `` V (This : `` C);        `\ `  `` W (This : `` C'Class);  `\ `  `` U;`\ ` P;` In C++, member functions implicitly take a parameter `this` which is of type `C*`. In Ada, all parameters are explicit. As a consequence, the fact that `u()` does *not* take a parameter is implicit in C++ but explicit in Ada. In C++, `this` is a pointer. In Ada, the explicit `This` parameter does not have to be a pointer; all parameters of a tagged type are implicitly passed by reference anyway. ### Static dispatching In C++, function calls dispatch statically in the following cases: - the target of the call is an object type - the member function is non-virtual For example: ``` c++ C object; object.v(); object.w(); ``` both dispatch statically. In particular, the static dispatch for v() may be confusing; this is because object is neither a pointer nor a reference. Ada behaves exactly the same in this respect, except that Ada calls this *static binding* rather than *dispatching*: \ `   Object : P.C;`\ \ `   Object.V; `\ `   Object.W; `\ `;` ### Dynamic dispatching In C++, a function call dispatches dynamically if the two following conditions are met simultaneously: - the target of the call is a pointer or a reference - the member function is virtual. For example: ``` c++ C* object; object->v(); // dynamic dispatch object->w(); // static, non-virtual member function object->u(); // illegal: static member function C::u(); // static dispatch ``` In Ada, a primitive subprogram call dispatches (dynamically) if and only if: - the target object is of a class-wide type; Note: In Ada vernacular, the term *dispatching* always means *dynamic*. For example: \ `   Object : P.C'Class := ...;`\ \ `   P.V (Object); `\ `   P.W (Object); `\ `   P.U; `\ `;` As can be seen *there is no need for access types or pointers* to do dispatching in Ada. In Ada, *tagged types are always passed by-reference to subprograms* without the need for explicit access values. Also note that in C++, the class serves as: - the unit of encapsulation (Ada uses packages and visibility for this) - the type, like in Ada. As a consequence, you call C::u() in C++ because u() is encapsulated in C, but P.U in Ada since U is encapsulated in the *package* P, not the *type* C. ### Class-wide and specific types The most confusing part for C++ programmers is the concept of a \"class-wide type\". To help you understand: - pointers and references in C++ are really, implicitly, class-wide; - object types in C++ are really specific; - C++ provides no way to declare the equivalent of: ` C_Specific_Access `` C;` - C++ provides no way to declare the equivalent of: ` C_Specific_Access_One `` C;`\ ` C_Specific_Access_Two `` C;` which, in Ada, are two different, *incompatible* types, possibly allocating their memory from different storage pools! - In Ada, you do *not* need access values for dynamic dispatching. - In Ada, you use access values for dynamic memory management (only) and class-wide types for dynamic dispatching (only). - In C++, you use pointers and references both for dynamic memory management and for dynamic dispatching. - In Ada, class-wide types are explicit (with `'Class`). - In C++, class-wide types are implicit (with `*` or `&`). ### Constructors in C++, a special syntax declares a constructor: ``` c++ class C { C(/* optional parameters */); // constructor }; ``` A constructor cannot be virtual. A class can have as many constructors, differentiated by their parameters, as necessary. Ada does not have such constructors. Perhaps they were not deemed necessary since in Ada, any function that returns an object of the tagged type can serve as a kind of constructor. This is however not the same as a real constructor like the C++ one; this difference is most striking in cases of derivation trees (see Finalization below). The Ada constructor subprograms do not have to have a special name and there can be as many constructors as necessary; each function can take parameters as appropriate. ` P `\ `  `` T is `` ``;`\ `  `` Make                 `` T;  -- constructor`\ `  `` To_T (From: Integer) `` T;  -- another constructor`\ `  `` Make (This: `` T);            -- not a constructor`\ \ `  ...`\ ` P;` If an Ada constructor function is also a primitive operation (as in the example above), it becomes abstract upon derivation and has to be overridden if the derived type is not itself abstract. If you do not want this, declare such functions in a nested scope. In C++, one idiom is the *copy constructor* and its cousin the *assignment operator*: ``` c++ class C { C(const C& that); // copies "that" into "this" C& operator= (const C& right); // assigns "right" to "this", which is "left" }; ``` This copy constructor is invoked implicitly on initialization, e.g. ``` c++ C a = b; // calls the copy constructor C c; a = c; // calls the assignment operator ``` Ada provides a similar functionality by means of *controlled types*. A controlled type is one that extends the predefined type `.Controlled`: ` ``;`\ ` P `\ `  `` T `` `` ``.Controlled `` ``;`\ `  `` Make `` T;  -- constructor`\ \ `  `` T `` ... `` ``;`\ `  `` `` Initialize (This: `` `` T);`\ `  `` `` Adjust     (This: `` `` T); -- copy constructor`\ ` P;` Note that Initialize is not a constructor; it resembles the C++ constructor in some way, but is also very different. Suppose you have a type T1 derived from T with an appropriate overriding of Initialize. A real constructor (like the C++ one) would automatically first construct the parent components (T), then the child components. In Ada, this is not automatic. In order to mimic this in Ada, we have to write: ` Initialize (This: `` `` T1) `\ \ `  Initialize (T (This));  -- Don't forget this part!`\ `  ...  -- handle the new components here`\ ` Initialize;` The compiler inserts a call to Initialize after each object of type T is allocated when no initial value is given. It also inserts a call to Adjust after each assignment to the object. Thus, the declarations: `A: T;`\ `B: T := X;` will: - allocate memory for A - call Initialize (A) - allocate memory for B - copy the contents of X to B - call Adjust (B) Initialize (B) will not be called because of the explicit initialization. So, the equivalent of a copy constructor is an overriding of Adjust. If you would like to provide this functionality to a type that extends another, non-controlled type, see \"Multiple Inheritance\". ### Destructors In C++, a destructor is a member function with only the implicit `this` parameter: ``` c++ class C { virtual ~C(); // destructor } ``` While a constructor *cannot* be virtual, a destructor *must* be virtual if the class is to be used with dynamic dispatch (has virtual methods or derives from a class with virtual methods). C++ classes do not use dynamic dispatch by default, so it can catch some programmers out and wreak havoc in their programs by simply forgetting the keyword `virtual`. In Ada, the equivalent functionality is again provided by controlled types, by overriding the procedure Finalize: ` ``;`\ ` P `\ `   `` T `` `` ``.Controlled `` ``;`\ `   `` Make `` T;  -- constructor`\ \ `   `` T `` ... `` ``;`\ `   `` `` Finalize (This: `` `` T);  -- destructor`\ ` P;` Because Finalize is a primitive operation, it is automatically \"virtual\"; you cannot, in Ada, forget to make a destructor virtual. ### Encapsulation: public, private and protected members In C++, the unit of encapsulation is the class; in Ada, the unit of encapsulation is the package. This has consequences on how an Ada programmer places the various components of an object type. ``` c++ class C { public: int a; void public_proc(); protected: int b; int protected_func(); private: bool c; void private_proc(); }; ``` A way to mimic this C++ class in Ada is to define a hierarchy of types, where the base type is the public part, which must be abstract so that no stand-alone objects of this base type can be defined. It looks like so: ` `` ``;`\ \ ` CPP `\ \ `  `` Public_Part `` `` `` ``  -- no objects of this type`\ `    A: Integer;`\ `  `` ``;`\ \ `  `` Public_Proc (This: `` `` Public_Part);`\ \ `  `` Complete_Type `` `` Public_Part `` ``;`\ \ `  -- procedure Public_Proc (This: in out Complete_Type);  -- inherited, implicitly defined`\ \ `  -- visible for children`\ \ `  `` Private_Part;  -- declaration stub`\ `  `` Private_Part_Pointer `` `` Private_Part;`\ \ `  `` Private_Component `` `` ``.Controlled `` `\ `    P: Private_Part_Pointer;`\ `  `` record;`\ \ `  `` `` Initialize (X: `` `` Private_Component);`\ `  `` `` Adjust     (X: `` `` Private_Component);`\ `  `` `` Finalize   (X: `` `` Private_Component);`\ \ `  `` Complete_Type `` `` Public_Part `` `\ `    B: Integer;`\ `    P: Private_Component;  -- must be controlled to avoid storage leaks`\ `  `` ``;`\ \ `  `` `` `` Protected_Proc (This: Complete_Type);`\ \ ` CPP;` The private part is defined as a stub only, its completion is hidden in the body. In order to make it a component of the complete type, we have to use a pointer since the size of the component is still unknown (the size of a pointer is known to the compiler). With pointers, unfortunately, we incur the danger of memory leaks, so we have to make the private component controlled. For a little test, this is the body, where the subprogram bodies are provided with identifying prints: ` Ada.Unchecked_Deallocation;`\ ` Ada.Text_IO;`\ \ ` `` CPP `\ \ `  `` Public_Proc (This: `` `` Public_Part) ``  -- primitive`\ `  `\ `    Ada.Text_IO.Put_Line ("Public_Proc" & Integer'Image (This.A));`\ `  `` Public_Proc;`\ \ `  `` Private_Part `` ``  -- complete declaration`\ `    C: Boolean;`\ `  `` ``;`\ \ `  `` `` Initialize (X: `` `` Private_Component) `\ `  `\ `    X.P := new Private_Part'(C => True);`\ `    Ada.Text_IO.Put_Line ("Initialize " & Boolean'Image (X.P.C));`\ `  `` Initialize;`\ \ `  `` `` (X: `` `` Private_Component) `\ `  `\ `    Ada.Text_IO.Put_Line ("Adjust " & Boolean'Image (X.P.C));`\ `    X.P := new Private_Part'(C => X.P.C);  -- deep copy`\ `  `` Adjust;`\ \ `  `` `` Finalize (X: `` `` Private_Component) `\ `    `` Free `` `` Ada.Unchecked_Deallocation (Private_Part, Private_Part_Pointer);`\ `  `\ `    Ada.Text_IO.Put_Line ("Finalize " & Boolean'Image (X.P.C));`\ `    Free (X.P);`\ `  `` Finalize;`\ \ `  `` Private_Proc (This: `` `` Complete_Type) ``  -- not primitive`\ `  `\ `    Ada.Text_IO.Put_Line ("Private_Proc" & Integer'Image (This.A) & Integer'Image (This.B) & ' ' & Boolean'Image (This.P.P.C));`\ `  `` Private_Proc;`\ \ `  `` `` `` Protected_Proc (This: Complete_Type) ``  -- primitive`\ `    X: Complete_Type := This;`\ `  `\ `    Ada.Text_IO.Put_Line ("Protected_Proc" & Integer'Image (This.A) & Integer'Image (This.B));`\ `    Private_Proc (X);`\ `  `` Protected_Proc;`\ \ ` CPP;` We see that, due to the construction, the private procedure is not a primitive operation. Let\'s define a child class so that the protected operation can be reached: ` CPP.Child `\ ` `\ `  `` Do_It (X: Complete_Type);  -- not primitive`\ \ ` CPP.Child;` A child can look inside the private part of the parent and thus can see the protected procedure: ` Ada.Text_IO;`\ \ ` `` CPP.Child `\ \ `  `` Do_It (X: Complete_Type) `\ `  `\ `    Ada.Text_IO.Put_Line ("Do_It" & Integer'Image (X.A) & Integer'Image (X.B));`\ `    Protected_Proc (X);`\ `  `` Do_It;`\ \ ` CPP.Child;` This is a simple test program, its output is shown below. ` CPP.Child;`\ `  CPP.Child, CPP;`\ \ ` Test_CPP `\ \ `  X, Y: Complete_Type;`\ \ \ \ `  X.A := +1;`\ `  Y.A := -1;`\ \ `  Public_Proc (X);  Do_It (X);`\ `  Public_Proc (Y);  Do_It (Y);`\ \ `  X := Y;`\ \ `  Public_Proc (X);  Do_It (X);`\ \ ` Test_CPP;` This is the commented output of the test program: `Initialize TRUE                     Test_CPP: Initialize X`\ `Initialize TRUE                                      and Y`\ `Public_Proc 1                       |  Public_Proc (X):  A=1`\ `Do_It 1-1073746208                  |  Do_It (X):        B uninitialized`\ `Adjust TRUE                         |  |  Protected_Proc (X): Adjust local copy X of This`\ `Protected_Proc 1-1073746208         |  |  |`\ `Private_Proc 1-1073746208 TRUE      |  |  |  Private_Proc on local copy of This`\ `Finalize TRUE                       |  |  Protected_Proc (X): Finalize local copy X`\ `Public_Proc-1                       |  ditto for Y`\ `Do_It-1 65536                       |  |`\ `Adjust TRUE                         |  |`\ `Protected_Proc-1 65536              |  |`\ `Private_Proc-1 65536 TRUE           |  |`\ `Finalize TRUE                       |  |`\ `Finalize TRUE                       |  Assignment: Finalize target X.P.C`\ `Adjust TRUE                         |  |           Adjust: deep copy`\ `Public_Proc-1                       |  again for X, i.e. copy of Y`\ `Do_It-1 65536                       |  |`\ `Adjust TRUE                         |  |`\ `Protected_Proc-1 65536              |  |`\ `Private_Proc-1 65536 TRUE           |  |`\ `Finalize TRUE                       |  |`\ `Finalize TRUE                       Finalize Y`\ `Finalize TRUE                            and X` You see that a direct translation of the C++ behaviour into Ada is difficult, if feasible at all. Methinks, the primitive Ada subprograms corresponds more to virtual C++ methods (in the example, they are not). Each language has its own idiosyncrasies which have to be taken into account, so that attempts to directly translate code from one into the other may not be the best approach. ### De-encapsulation: friends and stream input-output In C++, a friend function or class can see all members of the class it is a friend of. Friends break encapsulation and are therefore to be discouraged. In Ada, since packages and not classes are the unit of encapsulation, a \"friend\" subprogram is simply one that is declared in the same package as the tagged type. In C++, stream input and output are the particular case where friends are usually necessary: ``` c++ #include <iostream> class C { public: C(); friend ostream& operator<<(ostream& output, C& arg); private: int a, b; bool c; }; #include <iostream> int main() { C object; cout << object; return 0; }; ``` Ada does not need this construct because it defines stream input and output operations by default: The default implementation of the `Input`, `Output`, `Read` and `Write` attributes may be overridden (shown for `Write` as an example). The overriding must occur before the type is frozen, i.e. (in the case of this example) in the package specification. ` `` Ada``Streams``  `\ ` P `\ `   `` C `` `` `\ \ `   `` C `` `` `\ `      A`` B `` Integer`\ `      C `` Boolean`\ `   `` `\ `   `` My_Write ``Stream `` `` `` `` Ada``Streams``Root_Stream_Type`\ `                       Item   `` `` C`\ `   `` C`` `` My_Write``  `\ ` P` By default, the `Write` attribute sends the components to the stream in the same order as given in the declaration, i.e. A, B then C, so we change the order. ` `` P `\ `   `` My_Write ``Stream `` `` `` `` Ada``Streams``Root_Stream_Type`\ `                       Item `` `` C`` `\ `   `\ `      `\ `      Boolean`` ``Stream`` Item``C``  `\ `      Integer`` ``Stream`` Item``B``  `\ `      Integer`` ``Stream`` Item``A``  `\ `   `` My_Write`\ ` P` Now `P.C'Write` calls the overridden version of the package. ` `` Ada``Text_IO``Text_Streams`\ ` `` P`\ ` `` Main `\ `    Object `` P``C`\ ` `\ `    P``C`` ``Ada``Text_IO``Text_Streams``Stream ``Ada``Text_IO``Standard_Output`\ `               Object`\ ` `` Main` Note that the stream IO attributes are not primitive operations of the tagged type; this is also the case in C++ where the friend operators are not, in fact, member functions of the type. ### Terminology Ada C++ ---------------------------------------- ------------------------------------------------------------------------------------------------------------------ Package class (as a unit of encapsulation) Tagged type class (of objects) (as a type) (*not* pointer or reference, which are class-wide) Primitive operation virtual member function Tag pointer to the virtual table Class (of types) a tree of classes, rooted by a base class and including all the (recursively-)derived classes of that base class Class-wide type \- Class-wide operation static member function Access value to a specific tagged type \- Access value to a class-wide type pointer or reference to a class ## See also ### Wikibook - Ada Programming - Ada Programming/Types/record - record - interface - tagged ### Wikipedia - Object-oriented programming ### Ada Reference Manual #### Ada 95 - - - - - - #### Ada 2005 - - - - - - - ### Ada Quality and Style Guide - es:Programación en Ada/Tipos etiquetados
# Ada Programming/Contract Based Programming ## Contract Based Programming in Ada 2012 Among the additions to Ada 2012, a number of aspects follow the common theme of 'formal' contracts on types and subprograms. The formality here is referring to symbolic logic integrated with existing features of Ada. Contracts endow the language with expressive features similar to those of Eiffel\'s Design by Contract™, SPARK, or those connected with LSP. Since specifying contracts involves several parts of the Ada language, also since obeying contracts on the part of the compiler does so, too, the topic of contracts is addressed in several parts of the language reference. A comprehensive, more focused view, is a subject of the latest edition of the Ada Rationale.[^1] Parts of the contracts can be about statically known properties of the program, while others would be checked only at run-time. In the first case, the formal parts of the contract may be analyzed not just by the Ada compiler, but also by proof tools. The assurance resulting from the analysis can be that certain undesirable properties will be absent from the program. For example, the program might then be known to not raise exceptions. This overview will only outline syntax and variants by example while referring to existing wikibook entries and other resources for explanations of contracts in general. ### Preconditions and Postconditions of Subprograms Considering functions, for example, their specification gives the type of the return value as part of the parameter profile. One way of informing about the specifics of the return value of the function is to give a mathematical (in style) expression of the result, which is thus guaranteed by this clause of the contract. A contract may also specify conditions that say what must be true of objects entering the computation in order for the function to produce its result. In contracts, the return value is named *function_name*`'Result`. `  `` Sum (A, B : Number) `` Number`\ `  `\ `    Post => (`\ `               A <= 0.0 `` B >= 0.0`\ `             `\ `               Sum'Result = A + B);` An alternative mode of expression emphasizes the pre-requisites, `  `` Sum (A, B : Number) `` Number`\ `  `\ `    Pre  => A <= 0.0 and B >= 0.0,`\ `    Post => Sum'Result = A + B;` The first example leaves unsaid what happens when the condition evaluates to False. By default, when an assertion fails, and if the current Assertion_Policy is Check, Assertion_Error is raised. (The current amendment process of Ada is considering "raise expressions" (8652/0117): should the condition not be True, these permit raising a specific exception as an part, with a corresponding specific message instead of defaulting as just outlined.) The second example expressly obliges, in `Pre`, the caller to ensure that both `A` and `B` will have the specified properties of being `Number`s and of being no greater than 0.0 and no less than 0.0, respectively. This way the `Pre` aspect is stating that in case the condition is False, the function cannot fulfill its contractual obligation as given in `Post`. ### Assertions About Types And Subtypes Ada types may be declared to have a type invariant. This kind of predicate applies to private types. Hence, its expression may only refer to other publicly visible features of the type. The type\'s name here denotes the current instance of the type. `  `` Stack `` `\ `      `` Type_Invariant => Count(Stack) >= 0;` As detailed in , invariants may also be given for a derivation class of types, using aspect name `Type_Invariant'Class`, to apply to all types in a hierarchy. A predicate may also be given when declaring a subtype. In this case, the expression (of a boolean type) states properties of the subtype (see for details) and its truth would be checked at certain points. When a predicate should be tested by the compiler, its aspect is named `Static_Predicate`, and `Dynamic_Predicate` otherwise. Roughly, then, checks are performed when a type conversion takes place, or when a parameter is passed, or when an object is created. When deriving subtypes, the predicate that applies is the conjunction of the predicates on the subtypes involved. ### Assertion Policies The language reference manual extends the `Assert` pragma and its associated `Assertion_Policy` to also cover aspects of contract based programming in . Each 'section' of a contract, such as `Pre`, can be turned on and off for checking. This is done by specifying the desired Assertion_Policy, as locally or as globally as is desired. The following line turns checks on for aspect mark `Pre`: `  `` Assertion_Policy (Pre => Check);` Implementations of Ada are free to provide more policy identifiers than the two defined by the language, `Check` and `Ignore`. A setting that affects all possible assertion aspects at the same time omits giving aspect marks. `  `` Assertion_Policy (Check);` ## References [^1]: Ada Rationale, Contracts and Aspects
# Ada Programming/Ada 2005 This is an overview of the major features that are available in **Ada 2005**, the version of the Ada standard that was accepted by ISO in January 2007 (to differentiate it from its predecessors Ada 83 and Ada 95, the informal name Ada 2005 is generally agreed on). For the rationale and a more detailed (and very technical) description, see the Amendment to the Ada Reference Manual following the links to the last version of every Ada Issue document (AI). Although the standard is now published, not all compilers will be able to handle it. Many of these additions are already implemented by the following Free Software compilers: - GNAT GPL Edition - GCC 4.1 - GNAT Pro 6.0.2 (the AdaCore supported version) is a complete implementation. After downloading and installing any of them, remember to use the `-gnat05` switch when compiling Ada 2005 code. Note that Ada 2005 is the default mode in GNAT GPL 2007 Edition. ## Language features ### Character set Not only does Ada 2005 now support a new 32-bit character type --- called `Wide_Wide_Character` --- but the source code itself may be of this extended character set as well. Thus Russians and Indians, for example, will be able to use their native language in identifiers and comments. And mathematicians will rejoice: The whole Greek and fractur character sets are available for identifiers. For example, Ada.Numerics will be extended with a new constant: `π : `` := Pi;` This is not a new idea --- GNAT always had the `-gnati`*`c`* compiler option to specify the character set 1. But now this idea has become standard, so all Ada compilers will need to support Unicode 4.0 for identifiers --- as the new standard requires. See also: - - ### Interfaces Interfaces allow for a limited form of multiple inheritance similar to Java and C#. You find a full description here: Ada Programming/OO. See also: - - ### Union In addition to Ada\'s safe variant record an unchecked C style union is now available. You can find a full description here: Ada Programming/Types/record#Union. See also: - - ### With The with statement got a massive upgrade. First there is the new limited with which allows two packages to *with* each other. Then there is private with to make a package only visible inside the private part of the specification. See also: - - ### Access types #### Not null access An access type definition can specify that the access type can never be null. See Ada Programming/Types/access#Null exclusions. See also: #### Anonymous access The possible uses of anonymous access types are extended. They are allowed virtually in every type or object definition, including access to subprogram parameters. Anonymous access types may point to constant objects as well. Also, they could be declared to be not null. With the addition of the following operations in package , it is possible to test the equality of anonymous access types. `   `` "=" (Left, Right : `*`universal_access`*`) `` Boolean;`\ `   `` "/="(Left, Right : `*`universal_access`*`) `` Boolean;` See Ada Programming/Types/access#Anonymous access. See also: - - - ## Language library ### Containers A major addition to the language library is the generic packages for containers. If you are familiar with the C++ STL, you will likely feel very much at home using . One thing, though: Ada is a block structured language. Many ideas of how to use the STL employ this feature of the language. For example, local subprograms can be supplied to iteration schemes. The original Ada Issue text has now been transformed into . If you know how to write Ada programs, and have a need for vectors, lists, sets, or maps (tables), please have a look at the mentioned above. There is an *!example* section in the text explaining the use of the containers in some detail. Matthew Heaney provides a number of demonstration programs with his reference implementation of AI-302 () which you can find at tigris. In Ada Programming/Containers you will find a demo using containers. **Historical side note**: The C++ STL draws upon the work of David R. Musser and Alexander A. Stepanov. For some of their studies of generic programming, they had been using Ada 83. The Stepanov Papers Collection has a few publications available. ### Scan Filesystem Directories and Environment Variables See also: - - ### Numerics Besides the new constant of package (see Character Set above), the most important addition are the packages to operate with vectors and matrices. See also: - - (Related note on Ada programming tools: AI-388 contains an interesting assessment of how compiler writers are bound to perpetuate the lack of handling of international characters in programming support tools for now. As an author of Ada programs, be aware that your tools provider or Ada consultant could recommend that the program text be 7bit ASCII only.) ## Real-Time and High Integrity Systems See also: - - - - - ### Ravenscar profile See also: - - - - ### New scheduling policies See also: - - - ### Dynamic priorities for protected objects See also: ## Summary of what\'s new ### New keywords Added 3 keywords (72 total) - - - ### New pragmas Added 11 pragmas: - - - - - - - - - - - ### New attributes Added 7 attributes: - - - - - - - ### New packages - Assertions: - ```{=html} <!-- --> ``` - Container library: - - - - `<small>`{=html}(generic procedure)`</small>`{=html} - `<small>`{=html}(generic procedure)`</small>`{=html} - - - - - - - - - - ```{=html} <!-- --> ``` - Vector and matrix manipulation: - - - - ```{=html} <!-- --> ``` - General OS facilities: - - - ```{=html} <!-- --> ``` - String hashing: - `<small>`{=html}(generic function)`</small>`{=html} - `<small>`{=html}(generic function)`</small>`{=html} - `<small>`{=html}(generic function)`</small>`{=html} - `<small>`{=html}(generic function)`</small>`{=html} - `<small>`{=html}(generic function)`</small>`{=html} - `<small>`{=html}(generic function)`</small>`{=html} - `<small>`{=html}(generic function)`</small>`{=html} - `<small>`{=html}(generic function)`</small>`{=html} - `<small>`{=html}(generic function)`</small>`{=html} - `<small>`{=html}(generic function)`</small>`{=html} - `<small>`{=html}(generic function)`</small>`{=html} - `<small>`{=html}(generic function)`</small>`{=html} ```{=html} <!-- --> ``` - Time operations: - - - ```{=html} <!-- --> ``` - Tagged types: - `<small>`{=html}(generic function)`</small>`{=html} ```{=html} <!-- --> ``` - Text packages: - - - - - - - ```{=html} <!-- --> ``` - `Wide_Wide_Character` packages: - - - - - - - - - - - ```{=html} <!-- --> ``` - Execution-time clocks: - - - ```{=html} <!-- --> ``` - Dispatching: - - - ```{=html} <!-- --> ``` - Timing events: - ```{=html} <!-- --> ``` - Task termination procedures: - ## See also ### Wikibook - Ada Programming/Ada 83 - Ada Programming/Ada 95 - Ada Programming/Ada 2012 - Ada Programming/Object Orientation - Ada Programming/Types/access - Ada Programming/Keywords - Ada Programming/Keywords/and - Ada Programming/Keywords/interface - Ada Programming/Attributes - Ada Programming/Pragmas - Ada Programming/Pragmas/Restrictions - Ada Programming/Libraries/Ada.Containers - Ada Programming/Libraries/Ada.Directories ### Pages in the category Ada 2005 - Ada Programming}}/Ada 2005 feature ## External links ### Papers and presentations - Ada 2005: Putting it all together (SIGAda 2004 presentation) - GNAT and Ada 2005 (SIGAda 2004 paper) - An invitation to Ada 2005, and the presentation of this paper at Ada-Europe 2004 ### Rationale - *Rationale for Ada 2005* by John Barnes "wikilink"): 1. Introduction 2. Object Oriented Model 3. Access Types 4. Structure and Visibility 5. Tasking and Real-Time 6. Exceptions, Generics, Etc. 7. Predefined Library 8. Containers 9. Epilogue : : References : Index Available as a single document for printing. ### Language Requirements - *Instructions to the Ada Rapporteur Group from SC22/WG9 for Preparation of the Amendment to ISO/IEC 8652* (10 October 2002), and a presentation of this document at SIGAda 2002 ### Ada Reference Manual - **Ada Reference Manual**, ISO/IEC 8652:1995(E) with COR.1:2001 and AMD.1:2007 - **Annotated Ada Reference Manual**, ISO/IEC 8652:1995(E) with COR.1:2001 and AMD.1:2007 (colored diffs) - List of Ada Amendment drafts ### Ada Issues - Amendment 200Y - - - - - - - - - - - - - - - - - - - - - - - - - - 2005 Ada Programming}}/Ada 2005\| \*Ada 2005 Ada Programming}}/Ada 2005 feature\| \*Ada 2005
# Ada Programming/Ada 2012 This is an overview of the major features that are available in **Ada 2012**, the most recent version of the Ada standard. ## Summary of what\'s new ### New syntax Added 4 forms of expressions: - conditional expressions - case expressions - quantified expressions - expression functions These additional expressions originated with new support for contract based programming. ### New keywords Added 1 keyword (73 total) - ### New pragmas Added 5 pragmas: - - - - - Note that all these pragmas except born obsolescent, and it is recommended to use them as aspects instead. ### New aspects Aspect specifications is a new feature of Ada 2012. While some aspect identifiers are completely new, others were present in previous versions of the language as aspect-related pragmas or attribute-definition clauses. Note that for these pragmas, in some cases the old pragma identifiers are marked as obsolescent, while in other cases the usage of the pragma is still the recommended approach. Added 18 aspects: - - (also added as an obsolescent pragma) - - - - - (also added as an obsolescent pragma) - - - (also added as an obsolescent pragma) - (also added as an obsolescent pragma) - - - - - - - Aspect specifications already present in previous versions of the language as pragmas: - - (pragma now obsolescent) - (pragma now obsolescent) - (pragma now obsolescent) - (pragma now obsolescent) - (pragma now obsolescent) - - (pragma now obsolescent) - - - (pragma now obsolescent) - (pragma now obsolescent) - (pragma now obsolescent) - (pragma now obsolescent) - - (pragma now obsolescent) - - (pragma now obsolescent) - - (pragma now obsolescent) - - (pragma now obsolescent) - - - - (pragma now obsolescent) - (pragma now obsolescent) - (pragma now obsolescent) - (pragma now obsolescent) Aspect specifications already present in previous versions of the language as attribute definition clauses: - - - - - - - - - - - - - ### New attributes Added 5 attributes: - - - - - ### New packages - Multiprocessing: - - ```{=html} <!-- --> ``` - Real-time: - ```{=html} <!-- --> ``` - OS facilities: - ```{=html} <!-- --> ``` - Iterators: - ```{=html} <!-- --> ``` - Text handling: - - - ```{=html} <!-- --> ``` - Container library: - - - - - - - - - - - - - - - ## See also ### Wikibook - Ada Programming/Ada 83 - Ada Programming/Ada 95 - Ada Programming/Ada 2005 ### Pages in the category Ada 2012 - Ada Programming}}/Ada 2012 feature ## External links - www.ada2012.org, website maintained by the Ada Resource Association. - Ada Answers: Ada 2012 - ISO/IEC JTC1/SC22/WG9 N498 (2009). *Instructions to the Ada Rapporteur Group from SC22/WG9 for Preparation of Amendment 2 to ISO/IEC 8652* ### Papers and presentations - Towards Ada 2012: an interim report from the Ada Rapporteur Group, by Ed Schonberg (2010-06-17) - HD Video: *An introduction to Ada 2012*, presentation by Ed Schonberg (1h 02 min, 2012-10-16) ### Rationale - *Ada 2012 Rationale*, by John Barnes "wikilink") - Introduction - Chapter 1: Contracts and Aspects - Chapter 2: Expressions - Chapter 3: Structure and Visibility - Chapter 4: Tasking and Real-Time - Chapter 5: Iterators, Pools, etc. - Chapter 6: Containers - Epilogue - Predefined Library ### Ada Reference Manual - **Ada Reference Manual**, ISO/IEC 8652:2012(E) --- Language and Standard Libraries - ISO/IEC 8652:2012 --- Information technology --- Programming languages --- Ada (2012-12-10), same contents as the above link. - **Annotated Ada Reference Manual**, ISO/IEC 8652:2012(E) --- Language and Standard Libraries (colored diffs) - List of Ada Amendment drafts ### Ada Issues - Ada 2005 Issues - - - ### Implementations - Implementation of Ada 2012 Features in GNAT compiler ### Press releases - Ada 2012 Language Standard Approved by ISO, by Ada Resource Association & Ada-Europe (2012-12-18) PDF - Ada 2012 Language Standard Submitted to ISO, by Ada Resource Association & Ada-Europe (2012-06-12) PDF 2012 Ada Programming}}/Ada 2012\| \*Ada 2012 Ada Programming}}/Ada 2012 feature\|
# Ada Programming/Containers What follows is a simple demo of some of the container types. It does not cover everything, but should get you started. #### First Example: Maps The program below prints greetings to the world in a number of human languages. The greetings are stored in a table, or hashed map. The map associates every greeting (a value) with a language code (a key). That is, you can use language codes as keys to find greeting values in the table. The elements in the map are constant strings of international characters, or really, pointers to such constant strings. A package `Regional` is used to set up both the language IDs and an instance of . ` ` ` ``;  `` Ada.Containers;`\ \ ` Regional `\ \ `   `` Language_ID `` (DE, EL, EN, ES, FR, NL);`\ `   `\ \ `   `` Hello_Text `` `` `` Wide_String;`\ `   `\ \ \ `   `` ID_Hashed (id: Language_ID) `` Hash_Type;`\ `   `\ \ `   `` Phrases `` `` Ada.Containers.Hashed_Maps`\ `     (Key_Type => Language_ID,`\ `      Element_Type => Hello_Text,`\ `      Hash => ID_Hashed,`\ `      Equivalent_Keys => "=");`\ \ ` Regional;` Here is the program, details will be explained later. ` Regional; `` Regional;`\ ` ``; `` Ada;`\ \ ` Hello_World_Extended `\ \ `   `\ \ `   greetings: Phrases.Map;`\ `   `\ \ ` `\ \ `   Phrases.Insert(greetings,`\ `                  Key => EN,`\ `                  New_Item => `` Wide_String'("Hello, World!"));`\ \ `   `\ `   greetings.Insert(DE, `` Wide_String'("Hallo, Welt!"));`\ `   greetings.Insert(NL, `` Wide_String'("Hallo, Wereld!"));`\ `   greetings.Insert(ES, `` Wide_String'("¡Hola mundo!")); `\ `   greetings.Insert(FR, `` Wide_String'("Bonjour, Monde!"));`\ `   greetings.Insert(EL, `` Wide_String'("Γεια σου κόσμε"));`\ \ `   `\ `      `` Phrases;`\ \ `      speaker: Cursor := First(greetings);`\ `   `\ `      `` Has_Element(speaker) `\ `         Wide_Text_IO.Put_Line( Element(speaker).`` );`\ `         Next(speaker);`\ `      `` ``;`\ `   ``;`\ \ ` Hello_World_Extended;` The first of the `Insert` statements is written in an Ada 95 style: `  Phrases.Insert(greetings,`\ `                 Key => EN,`\ `                 New_Item => `` Wide_String'("Hello, World!"));` The next insertions use so called distinguished receiver notation which you can use in Ada 2005. (It\'s O-O parlance. While the Insert call involves all of: a Container object (greetings), a Key object (EN), and a New_Item object ( Wide_String\'(\"Hello, World!\")), the Container object is distinguished from the others in that the Insert call provides it (and only it) with the other objects. In this case the Container object will be modified by the call, using arguments named Key and New_Item for the modification.) `  greetings.Insert(ES, `` Wide_String'("¡Hola mundo!"));` After the table is set up, the program goes on to print all the greetings contained in the table. It does so employing a cursor that runs along the elements in the table in some order. The typical scheme is to obtain a cursor, here using `First`, and then to iterate the following calls: 1. `Has_Element`, for checking whether the cursor is at an element 2. `Element`, to get the element and 3. `Next`, to move the cursor to another element When there is no more element left, the cursor will have the special value `No_Element`. Actually, this is an iteration scheme that can be used with all containers in child packages of . #### A slight variation: picking an element The next program shows how to pick a value from the map, given a key. Actually, you will provide the key. The program is like the previous one, except that it doesn\'t just print all the elements in the map, but picks one based on a Language_ID value that it reads from standard input. ` Regional; `` Regional;`\ ` Ada.Wide_Text_IO; `` Ada;`\ \ ` Hello_World_Pick `\ \ `  ... as before ...`\ \ ` `\ `     `` Phrases;`\ ` `\ `     `` Lang_IO `` `` Wide_Text_IO.Enumeration_IO(Language_ID);`\ `     lang: Language_ID;`\ `  `\ `     Lang_IO.Get(lang);`\ `     Wide_Text_IO.Put_Line( greetings.Element(lang).`` );`\ `  ``;`\ ` `\ ` Hello_World_Pick;` This time the `Element` function consumes a Key (lang) not a Cursor. Actually, it consumes two values, the other value being `greetings`, in distinguished receiver notation. #### Second Example: Vectors and Maps Let\'s take bean counting literally. Red beans, green beans, and white beans. (Yes, white beans really do exist.) Your job will be to collect a number of beans, weigh them, and then determine the average weight of red, green, and white beans, respectively. Here is one approach. Again, we need a package, this time for storing vegetable related information. Introducing the `Beans` package (the Grams type doesn\'t belong in a vegetable package, but it\'s there to keep things simple): ` `\ \ ` Beans `\ \ `   `` Bean_Color `` ``R`` G`` W`\ `   `\ \ `   `` Grams `` `` 0``01 `` 7`\ `   `\ `   `\ \ `   `` Bean `\ `   `\ `      `\ `         kind`` Bean_Color`\ `         weight`` Grams`\ `      `` `\ \ `   `` Bean_Count `` Positive `` 1 `` 1_000`\ `   `\ \ `   `` Bean_Vecs `` `` Ada``Containers``Vectors`\ `     ``Element_Type => Bean`\ `      Index_Type => Bean_Count`\ \ ` Beans` The `Vectors` instance offers a data structure similar to an array that can change its size at run time. It is called `Vector`. Each bean that is read will be appended to a `Bean_Vecs.Vector` object. The following program first calls `read_input` to fill a buffer with beans. Next, it calls a function that computes the average weight of beans having the same color. This function: ` Beans``   `` Beans`\ \ ` average_weight`\ `  ``buffer`` Bean_Vecs``Vector`` desired_color`` Bean_Color`` `` Grams`\ ``{{Ada/comment | scan `buffer` for all beans that have `desired_color`. Compute the}}``{=mediawiki}\ ``{{Ada/comment | mean of their `.weight` components}}``{=mediawiki} Then the average value is printed for beans of each color and the program stops. ` Beans`\ ` average_weight`\ ` `\ \ ` bean_counting `\ `   `` Beans`` Ada`\ \ `   buffer`` Bean_Vecs``Vector`\ \ `   `` read_input``buf`` `` `` Bean_Vecs``Vector`` `` `\ `   ```{{Ada/comment | collect information from a series of bean measurements into `buf`}}``{=mediawiki}\ \ \ ` `\ \ `   read_input``buffer`\ \ `   `\ `   ```{{Ada/comment | For every bean color in `Bean_Color`, the function `average_weight`}}``{=mediawiki}\ `   ```{{Ada/comment | will scan `buffer` once, and accumulate statistical data from}}``{=mediawiki}\ `   `\ \ `   `` kind `` Bean_Color `\ `      Wide_Text_IO``Put_Line`\ `        ``Bean_Color``Wide_Image``kind`` `\ `         " ø =" `` Grams``Wide_Image`` average_weight``buffer`` kind`` `\ `   `` `\ \ ` bean_counting` All container operations take place in function `average_weight`. To find the mean weight of beans of the same color, the function is looking at all beans in order. If a bean has the right color, `average_weight` adds its weight to the total weight, and increases the number of beans counted by 1. The computation visits all beans. The iteration that is necessary for going from one bean to the next and then performing the above steps is best left to the `Iterate` procedure which is part of all container packages. To do so, wrap the above steps inside some procedure and pass this procedure to `Iterate`. The effect is that `Iterate` calls your procedure for each element in the vector, passing a cursor value to your procedure, one for each element. Having the container machinery do the iteration can also be faster than moving and checking the cursor yourself, as was done in the `Hello_World_Extended` example. ` Beans``  `` Beans``Bean_Vecs`\ \ ` average_weight`\ `  ``buffer`` Bean_Vecs``Vector`` desired_color`` Bean_Color`` `` Grams`\ \ `   total`` Grams := 0``0`\ `   ```{{Ada/-- | weight of all beans in `buffer` having `desired_color`}}``{=mediawiki}\ \ `   number`` Natural := 0`\ `   ```{{Ada/-- | number of beans in `buffer` having `desired_color`}}``{=mediawiki}\ \ `   `` accumulate``c`` Cursor`` `\ `      ```{{Ada/-- | if the element at `c` has the `desired_color`, measure it}}``{=mediawiki}\ `   `\ `      `` Element``c``kind = desired_color `\ `         number := number `` 1`\ `         total := total `` Element``c``weight`\ `      `` `\ `   `` accumulate`\ \ ` `\ \ `   Iterate``buffer`` accumulate``Access`\ \ `   `` number `` 0 `\ `      `` total `` number`\ `   `\ `      `` 0``0`\ `   `` `\ \ ` average_weight` This approach is straightforward. However, imagine larger vectors. `average_weight` will visit all elements repeatedly for each color. If there are M colors and N beans, `average_weight` will be called M \* N times, and with each new color, N more calls are necessary. A possible alternative is to collect all information about a bean once it is visited. However, this will likely need more variables, and you will have to find a way to return more than one result (one average for each color), etc. Try it! A different approach might be better. One is to copy beans of different colors to separate vector objects. (Remembering Cinderella.) Then `average_weight` must visit each element only one time. The following procedure does this, using a new type from `Beans`, called `Bean_Pots`. `   ...`\ `   `` Bean_Pots `` ``Bean_Color`` `` Bean_Vecs``Vector`\ `   ...` Note how this plain array associates colors with Vectors. The procedure for getting the beans into the right bowls uses the bean color as array index for finding the right bowl (vector). ` gather_into_pots``buffer`` Bean_Vecs``Vector`` pots`` `` `` Bean_Pots`` `\ `   `` Bean_Vecs`\ \ `   `` put_into_right_pot``c`` Cursor`` `\ `      ```{{Ada/comment | select the proper bowl for the bean at `c` and «append»}}``{=mediawiki}\ `      `\ `   `\ `      Append``pots``Element``c``kind`` Element``c`\ `   `` put_into_right_pot`\ \ `  `\ `   Iterate``buffer`` put_into_right_pot``Access`\ ` gather_into_pots` Everything is in place now. ` Beans`\ ` average_weight`\ ` gather_into_pots`\ ` Ada``Wide_Text_IO`\ \ ` bean_counting `\ `   `` Beans`` Ada`\ \ `   buffer`` Bean_Vecs``Vector`\ `   bowls`` Bean_Pots`\ \ `   `` read_input``buf`` `` `` Bean_Vecs``Vector`` `` `\ `   ```{{Ada/-- | collect information from a series of bean measurements into `buf`}}``{=mediawiki}\ \ \ ` `\ \ `   read_input``buffer`\ \ `   `\ `   `\ `   `\ \ `   gather_into_pots``buffer`` bowls`\ \ `   `` color `` Bean_Color `\ `      Wide_Text_IO``Put_Line`\ `        ``Bean_Color``Wide_Image``color`\ `         & " ø ="`\ `         & Grams``Wide_Image``average_weight``bowls``color`` color`\ `   `` `\ \ ` bean_counting` As a side effect of having chosen one vector per color, we can determine the number of beans in each vector by calling the `Length` function. But `average_weight`, too, computes the number of elements in the vector. Hence, a summing function might replace `average_weight` here. #### All In Just One Map! The following program first calls `read_input` to fill a buffer with beans. Then, information about these beans is stored in a table, mapping bean properties to numbers of occurrence. The processing that starts at `Iterate` uses chained procedure calls typical of the iteration mechanism. The Beans package in this example instantiates another generic library unit, . Where the require a hashing function, require a comparison function. We provide one, `"<"`, which sorts beans first by color, then by weight. It will automatically be associated with the corresponding generic formal function, as its name, `"<"`, matches that of the generic formal function, `"<"`. `   ...`\ `   `` "<"``a`` b`` Bean`` `` Boolean`\ `   `\ \ `   `` Bean_Statistics`\ `     `\ `     `\ `   `` `` Ada``Containers``Ordered_Maps`\ `     ``Element_Type => Natural`\ `      Key_Type => Bean`\ `   ...` Where the previous examples have ed subprograms, this variation on `bean_counting` packs them all as local subprograms. ` Beans`\ ` Ada``Wide_Text_IO`\ \ ` bean_counting `\ `   `` Beans`` Ada`\ \ `   buffer`` Bean_Vecs``Vector`\ `   stats_cw`` Bean_Statistics``Map`\ `   `\ `   `\ \ `   `` read_input``buf`` `` `` Bean_Vecs``Vector`` `` `\ `   ```{{Ada/-- | collect information from a series of bean measurements into `buf`}}``{=mediawiki}\ \ `   `` add_bean_info``specimen`` `` Bean`\ `   ```{{Ada/-- | insert bean `specimen` as a key into the `stats_cw` table unless}}``{=mediawiki}\ `   `\ `   `\ \ `   `` add_bean_info``specimen`` `` Bean`` `\ \ `      `` one_more``b`` `` Bean`` n`` `` `` Natural`` `\ `       `\ `      `\ `         n := n `` 1`\ `      `` one_more`\ \ `      c `` Bean_Statistics``Cursor`\ `      inserted`` Boolean`\ `   `\ `      stats_cw``Insert``specimen`` 0`` c`` inserted`\ `      Bean_Statistics``Update_Element``c`` one_more``Access`\ `   `` add_bean_info`\ \ ` `\ \ `   read_input``buffer`\ \ `   ```{{Ada/-- | next, for all beans in the vector `buffer` just filled, store}}``{=mediawiki}\ `   ```{{Ada/-- | information about each bean in the `stats_cw` table.}}``{=mediawiki}\ \ `   `\ `      `` Bean_Vecs`\ \ `      `` count_bean``c`` Cursor`` `\ `      `\ `         add_bean_info``Element``c`\ `      `` count_bean`\ `   `\ `      Iterate``buffer`` count_bean``Access`\ `   `\ \ `   `\ `   `\ `   ```{{Ada/-- | The `First`, and `Ceiling` functions will find cursors}}``{=mediawiki}\ `   `\ \ \ `   `\ `      `` Bean_Statistics`\ \ `      `\ \ `      q_sum`` Grams`\ `      q_count`` Natural`\ \ `      `` q_stats``lo`` hi`` Cursor`\ `      ```{{Ada/-- | `q_stats` will update the `q_sum` and `q_count` globals with}}``{=mediawiki}\ `      ```{{Ada/-- | the sum of the key weights and their number, respectively. `lo`}}``{=mediawiki}\ `      ```{{Ada/-- | (included) and `hi` (excluded) mark the interval of keys}}``{=mediawiki}\ `      `\ \ `      `` q_stats``lo`` hi`` Cursor`` `\ `         k`` Cursor := lo`\ `      `\ `         q_count := 0`` q_sum := 0``0`\ `         `\ `            `` `` k = hi`\ `            q_count := q_count `` Element``k`\ `            q_sum := q_sum `` Key``k``weight `` Element``k`\ `            Next``k`\ `         `` `\ `      `` q_stats`\ \ \ `      `\ `      `` assert`` Is_Empty``stats_cw`` "container is empty"`\ \ `      lower`` upper`` Cursor := First``stats_cw`\ `      `\ `      `\ \ `   `\ \ `      `\ \ `      Wide_Text_IO``Put_Line``"Summary:"`\ \ `      `` color `` Bean_Color `\ `         lower := upper`\ `         `` color = Bean_Color``Last `\ `            upper := No_Element`\ `         `\ `            upper := Ceiling``stats_cw`` Bean``Bean_Color``Succ``color`` 0``0`\ `         `` `\ \ `         q_stats``lower`` upper`\ \ `         `` q_count `` 0 `\ `            Wide_Text_IO``Put_Line`\ `              ``Bean_Color``Wide_Image``color`` & " group:" &`\ `               "  ø =" & Grams``Wide_Image``q_sum `` q_count`` &`\ `               ", # =" & Natural``Wide_Image``q_count`` &`\ `               ", Σ =" & Grams``Wide_Image``q_sum`\ `         `` `\ `      `` `\ `   `\ \ ` bean_counting` Like in the greetings example, you can pick values from the table. This time the values tell the number of occurrences of beans with certain properties. The `stats_cw` table is ordered by key, that is by bean properties. Given particular properties, you can use the `Floor` and `Ceiling` functions to approximate the bean in the table that most closely matches the desired properties. It is now easy to print a histogram showing the frequency with which each kind of bean has occurred. If N is the number of beans of a kind, then print N characters on a line, or draw a graphical bar of length N, etc. A histogram showing the number of beans per color can be drawn after computing the sum of beans of this color, using groups like in the previous example. You can delete beans of a color from the table using the same technique. Finally, think of marshalling the beans in order starting at the least frequently occurring kind. That is, construct a vector appending first beans that have occurred just once, followed by beans that have occurred twice, if any, and so on. Starting from the table is possible, but be sure to have a look at the sorting functions of . ## See also ### Wikibook - Ada Programming - Ada Programming/Libraries/Ada.Containers ### Ada 2005 Reference Manual - Programming}}\|Containers
# Ada Programming/Interfacing ## Interfacing Ada is one of the few languages where interfacing is part of the language standard. The programmer can interface with other programming languages, or with the hardware. ## Other programming languages The language standard defines the interfaces for C, Cobol and Fortran. Of course any implementation might define further interfaces --- GNAT for example defines an interface to C++. Interfacing with other languages is actually provided by pragma Export, Import and Convention. ### Interfacing with C The package Interfaces.C is used to define C types. C function wrappers should be used to encapsulate types and functions on the C side. This way the code is portable and foward-compatible. This is similar to the way of interfacing with C in Java\'s JNI. Wrappers should be used for: - Translating typedefs defined in C includes to types defined in Interfaces.C; - Using macros and exposing macro values to the Ada side; - Using variable parameter list functions; - Defining multiple function wrappers for a function that takes weakly typed parameters such as a function that takes a char_array or a null pointer; - Using getters and setters for C structs that depend on operating system version or other compile-type aspect; - Using pointer arithmetic; - Keeping Ada source memory-safe. #### Example ` Interfaces.C;`\ ` System;`\ ` Ada.Text_IO;`\ \ ` Main `\ `   `` W32_Open_File_Dialog`\ `   `\ `      `` C `` Interfaces.C;`\ `      `` C;`\ `      `\ `      `` OPENFILENAME `` `` System.Address;`\ `      `` Window_Type `` `` System.Address;`\ `      `\ `      `` GetOpenFileName (p : OPENFILENAME) `` C.int;`\ `      `` Import (C, GetOpenFileName, "ada_getopenfilename");`\ `      `\ `      `` Allocate `` OPENFILENAME `\ `        Import => True,`\ `        Convention => C,`\ `        External_Name => "ofn_allocate";`\ `      `\ `      `` Set_Struct_Size (X : OPENFILENAME) `\ `        Import => True,`\ `        Convention => C,`\ `        External_Name => "ofn_set_struct_size";`\ `      `\ `      `` Set_Owner (X : OPENFILENAME; Owner : Window_Type) `\ `        Import => True,`\ `        Convention => C,`\ `        External_Name => "ofn_set_owner";`\ `      `\ `      `` Set_File (X : OPENFILENAME; File : char_array; Length : C.int) `\ `        Import => True,`\ `        Convention => C,`\ `        External_Name => "ofn_set_file";`\ `      `\ `      `` Set_Filter (X : OPENFILENAME; Filter : char_array);`\ `      `` Import (C, Set_Filter, "ofn_set_filter");`\ `      `\ `      `` Set_Filter_Index (X : OPENFILENAME; N : C.int) `\ `        Import => True,`\ `        Convention => C,`\ `        External_Name => "ofn_set_filter_index";`\ `      `\ `      `` Get_File (X : OPENFILENAME) `` System.Address;`\ `      `` Import (C, Get_File, "ofn_get_file");`\ `      `\ `      `` Get_File_Length (X : OPENFILENAME) `` C.size_t;`\ `      `` Import (C, Get_File_Length, "ofn_get_file_length");`\ `      `\ `      `` Free (X : OPENFILENAME) `\ `        Import => True,`\ `        Convention => C,`\ `        External_Name => "ofn_free";`\ `      `\ `      OFN : OPENFILENAME;`\ `      Ret : C.int;`\ `      File : `` C.char_array := "test.txt" & C.nul;`\ `      Filter : `` C.char_array := "All" & C.nul & "*.*" & C.nul & C.nul & C.nul;`\ `   `\ `      OFN := Allocate;`\ `      Set_Struct_Size (OFN);`\ `      Set_Owner (OFN, Window_Type (System.Null_Address));`\ `      Set_File (OFN, File, 256);`\ `      Set_Filter (OFN, Filter);`\ `      Set_Filter_Index (OFN, 0);`\ `      Ret := GetOpenFileName (OFN);`\ `      `` Ret = 0 `\ `         Free (OFN);`\ `         Ada.Text_IO.Put_Line ("No file selected.");`\ `         return;`\ `      `` ``;`\ `      `\ `         Selected_File_Address : System.Address := Get_File (OFN);`\ `         Selected_File_Length : C.size_t := Get_File_Length (OFN);`\ `         Selected_File : char_array (1 .. Selected_File_Length + 1);`\ `         `` Selected_File'Address `` Selected_File_Address;`\ `      `\ `         Ada.Text_IO.Put_Line (To_Ada (Selected_File, Trim_Nul => True));`\ `      ``;`\ `      Free (OFN);`\ `   `` W32_Open_File_Dialog;`\ \ `   W32_Open_File_Dialog;`\ ` Main;` ``` c #include <windows.h> #include <stdlib.h> OPENFILENAME *ofn_allocate() { OPENFILENAME *ofn; ofn = (OPENFILENAME *) malloc(sizeof(OPENFILENAME)); if (ofn == NULL) return NULL; memset(ofn, 0, sizeof(OPENFILENAME)); return ofn; } void ofn_set_struct_size(OPENFILENAME *ofn) { ofn->lStructSize = sizeof(OPENFILENAME); } void ofn_set_owner(OPENFILENAME *ofn, void *owner) { ofn->hwndOwner = (HWND) owner; } void ofn_set_file(OPENFILENAME *ofn, char *file, int length) { if (ofn->lpstrFile) free(ofn->lpstrFile); ofn->lpstrFile = (char *)malloc (length); if (ofn->lpstrFile == NULL) { ofn->nMaxFile = 0; return; } strncpy(ofn->lpstrFile, file, length); ofn->nMaxFile = length; } void ofn_set_filter(OPENFILENAME *ofn, char *filter) { ofn->lpstrFilter = filter; } void ofn_set_filter_index(OPENFILENAME *ofn, int n) { ofn->nFilterIndex = n; } void ofn_free(OPENFILENAME *ofn) { if (ofn->lpstrFile) free(ofn->lpstrFile); free(ofn); } int ada_getopenfilename(OPENFILENAME *ofn) { return (int) GetOpenFileNameA(ofn); } char *ofn_get_file(OPENFILENAME *ofn) { return ofn->lpstrFile; } size_t ofn_get_file_length(OPENFILENAME *ofn) { return (size_t) lstrlen (ofn->lpstrFile); } ``` The following project file (getopenfilename.gpr) shows how to link to comdlg32.dll: project Getopenfilename is for Languages use ("Ada", "C"); for Source_Dirs use ("src"); for Object_Dir use "obj"; for Main use ("main.adb"); package Linker is for Default_Switches ("ada") use ("-lComdlg32"); end Linker; end Getopenfilename; ## Hardware devices Embedded programmers usually have to write device drivers. Ada provides extensive support for interfacing with hardware, like using representation clauses to specify the exact representation of types used by the hardware, or standard interrupt handling for writing Interrupt service routines. ## See also ### Wikibook - Ada Programming - Ada Programming/Libraries/Interfaces ### Ada Reference Manual - - ### Ada 95 Rationale - ### Ada Quality and Style Guide - Programming}}\|Interfacing Ada Programming}}/Unfinished module\|Interfacing
# Ada Programming/Coding standards ## Introduction Each project should follow a specific coding standard to ease readability and maintenance of the source code, and reduce the insertion of errors. Depending on the requirements of the project, a set of guidelines can help to achieve the desired level of performance, portability, code complexity\... There are many ASIS tools that can be used to check automatically the adherence of Ada source code to the guidelines. ## Tools - AdaControl (Rules) - gnatcheck - GNAT Pretty-Printer - The GNAT Metric Tool gnatmetric ## Coding guidelines - *Ada Quality & Style Guide: Guidelines for Professional Programmers* - ISO/IEC TR 15942:2000, *Guide for the use of the Ada programming language in high integrity systems.zip)*, First edition (2000-03-01). ISO Freely Available Standards - - - (PDF) ## See also ### Other wikibooks - Ada Style Guide ### Wikibook - Ada Programming ### Ada Quality and Style Guide - ## External links - Introduction to Coding Standards Programming}}\|Coding standards
# Ada Programming/Tips ## Full declaration of a type can be deferred to the unit\'s body Often, you\'ll want to make changes to the internals of a private type. This, in turn, will require the algorithms that act on it to be modified. If the type is completed in the unit specification, it is a pain to edit and recompile both files, even with an IDE, but it\'s something some programmers learn to live with. It turns out you don\'t have to. Nonchalantly mentioned in the ARM, and generally skipped over in tutorials, is the fact that private types can be completed in the unit\'s body itself, making them much closer to the relevant code, and saving a recompile of the specification, as well as every unit depending on it. This may seem like a small thing, and, for small projects, it is. However, if you have one of those uncooperative types that requires dozens of tweaks, or if your dependence graph has much depth, the time and annoyance saved add up quickly. Also, this construction is very useful when coding a shared library, because it permits to change the implementation of the type while still providing a compatible ABI. Code sample: ` Private_And_Body `\ \ `  `` Private_Type `` `` ``;`\ \ `  `\ \ \ `  `` Body_Type;   `\ `  `` Private_Type `` `` Body_Type;`\ ` Private_And_Body;` The type in the public part is an access to the hidden type. This has the drawback that memory management has to be provided by the package implementation. That is the reason why `Private_Type` is a limited type, the client will not be allowed to copy the access values, in order to prevent dangling references. Normally, the full type definition has to be given in the specification because the compiler has to know how much place to allocate to objects in order to produce code using this type. And the astute reader will note that also in this case the full type definition is given for Private_Type: it is an access to some other (albeit incomplete) type, and the size of an access value is known. This is why the full type definition of Body_Type can be moved to the body. The construction centering around `Private_Type` is sometimes called an opaque pointer. ## Lambda calculus through generics Suppose you\'ve decided to roll your own set "wikilink") type. You can add things to it, remove things from it, and you want to let a user apply some arbitrary function to all of its members. But the scoping rules seem to conspire against you, forcing nearly everything to be global. The mental stumbling block is that most examples given of generics are packages, and the Set package is already generic. In this case, the solution is to make the Apply_To_All procedure generic as well; that is, to nest the generics. Generic procedures inside packages exist in a strange scoping limbo, where anything in scope at the instantiation can be used by the instantiation, and anything normally in scope at the formal can be accessed by the formal. The end result is that the relevant scoping roadblocks no longer apply. It isn\'t the full lambda calculus, just one of the most useful parts. \ `  `` Element `` ``;`\ ` Sets `\ `  `` Set `` ``;`\ `   `*`[..]`*\ `  `\ `    `` `` Apply_To_One (The_Element : `` `` Element);`\ `  `` Apply_To_All (The_Set : `` `` Set);`\ ` Sets;` For a view of Functional Programming in Ada see.[^1] ## Compiler Messages Different compilers can diagnose different things differently, or the same thing using different messages, etc.. Having two compilers at hand can be useful. `selected component`: When a source program contains a construct such as `Foo.Bar`, you may see messages saying something like «selected component \"Bar\"» or maybe like «selected component \"Foo\"». The phrases may seem confusing, because one refers to `Foo`, while the other refers to `Bar`. But they are both right. The reason is that `selected_component` is an item from Ada\'s grammar (). It denotes all of: a prefix, a dot, and a selector_name. In the `Foo.Bar` example these correspond to `Foo`, \'`.`\', and `Bar`. Look for more grammar words in the compiler messages, e.g. «prefix», and associate them with identifiers quoted in the messages. ```{=html} <!-- --> ``` : For example, if you submit the following code to the compiler, ` `*`Pak`*\ ` Foo `\ `   `` T `` `` `*`Pak`*`Bar``  `\ ` Foo` : the compiler may print a diagnostic message about a prefixed component: `Foo`\'s author thought that `Pak` denotes a package, but actually it is the name of a *generic* package. (Which needs to be instantiated first; and then the *instance* name is a suitable prefix.) ## Universal integers All integer literals and also some attributes like `'Length` are of the anonymous type *universal_integer*, which comprises the infinite set of mathematical integers. Named numbers are of this type and are evaluated exactly (no overflow except for machine storage limitations), e.g. ` Very_Big: `` := 10**1_000_000 - 1;` Since *universal_integer* has no operators, its values are converted in this example to *root_integer*, another anonymous type, the calcuation is performed and the result again converted back in *universal_integer*. Generally values of *universal_integer* are implicitly converted to the appropriate type when used in some expression. So the expression ` A` is fine; the value of `A` is interpreted as a modular integer since can only be applied to modular integers (of course a context is needed to decide which modular integer type is meant). This feature can lead to pitfalls. Consider `   `` Ran_6 `` `` 1 `` 6`\ `   `` Mod_6 `` `` 6` and then `   `\ `   `` A`` `` Ran_6 ``  `\ `      …`\ \ `   `\ `   `` `` A`` `` Ran_6 ``  `\ `      …`\ `   `\ `   `` (`` A``) `` Ran_6 ``  `\ `      …`\ \ `   `\ `   `` A`` `` 1 `` 6 ``  `\ `      …`\ \ `   `\ `   `` `` A`` `` 1 `` 6 ``  `\ `      …`\ \ `   `\ `   `` A`` `` Mod_6 ``  `\ `      …`\ \ `   `\ `   `` `` A`` `` Mod_6 ``  `\ `      …` : The second conditional cannot be compiled because the expressions to the left of is incompatible to the type at the right. Note that has precedence over . It does not negate the entire membership test but only `A`. ```{=html} <!-- --> ``` : The fourth conditional fails in various ways. ```{=html} <!-- --> ``` : The sixth conditional might be fine because turns `A` into a modular value which is OK if the value is covered by modular type `Mod_6`. ```{=html} <!-- --> ``` : GNAT GPL 2009 gives these diagnoses respectively: `error: incompatible types`\ `error: operand of not must be enclosed in parentheses`\ `warning: not expression should be parenthesized here` : A way to *avoid* these problems is to use ` ` for the membership test (which, btw., is the language-intended form), `   `` A`` `` `` Ran_6 ``  `\ `      …` : See - , - ), and - , - , - Membership Tests ## I/O ### Text_IO Issues A canonical method of reading a sequence of lines from a text file uses the standard procedure .*Get_Line*. When the end of input is reached, *Get_Line* will fail, and exception *End_Error* is raised. Some programs will use another function from to prevent this and test for *End_of_File*. However, this isn\'t always the best choice, as has been explained for example in a Get_Line news group discussion on comp.lang.ada. A working solution uses an exception handler instead: `  `\ `     The_Line`` String``1``100`\ `     Last`` Natural`\ `  `\ `     `\ `        Text_IO``Get_Line``The_Line`` Last`\ `        `\ `     `` `\ `  `\ `     `` Text_IO``End_Error `\ `        `\ `  ` The function End_of_File RM A.10.1(34) works fine as long as the file follows the canonical form of text files presumed by Ada, which is always the case when the file has been written by . This canonical form requires an End_of_Line marker followed by an End_of_Page marker at the very end before the End_of_File. If the file was produced by another any other means, it will generally not have this canonical form, so a test for End_of_File will fail. That\'s why the exception End_Error has to be used in those cases (which always works). ## Quirks Using GNAT on Windows, calls to subprograms from might need special attention. (For example, the `Real_Time.Clock` function might seem to return values indicating that no time has passed between two invocations when certainly some time has passed.) The cause is reported to be a missing initialization of the run-time support when no other real-time features are present in the program.[^2] As a provisional fix, it is suggested to insert ` 0``0` before any use of `Real_Time` services. ### Stack Size With some implementations, notably GNAT, knowledge of stack size manipulation will be to your advantage. Executables produced with GNAT tools and standard settings can hit the stack size limit. If so, the operating system might allow setting higher limits. Using GNU/Linux and the Bash command shell, try `$ ulimit -s [some number]` The current value is printed when only `-s` is given to *ulimit*. ## References ```{=html} <references/> ``` ## See also ### Wikibook - Ada Programming - Ada Programming/Errors ### Ada Reference Manual - [^1]: Functional Programming in\...Ada?, by Chris Okasaki [^2]: Usenet article forwards this information from AdaCore.
# Ada Programming/Errors Some language features are often misunderstood, resulting in common programming errors, performance degradation and portability problems. The following incorrect usages of the Ada language are often seen in code written by Ada beginners. ## pragma Atomic & Volatile ## pragma Pack ## \'Bit_Order attribute ## \'Size attribute ## See also ### Wikibook - Ada Programming - Ada Programming/Tips ## References ```{=html} <references/> ``` Programming}}\|Errors Ada Programming}}/Common errors
# Ada Programming/Error handling ## Error handling techniques This chapter describes various error handling techniques. First the technique is described, then its use is shown with an example function and a call to that function. We use the √ function which should report an error condition when called with a negative parameter. To be specific: Exceptions is the Ada way to go. ### Return code ` Error_Handling_1 `\ \ `  `` Square_Root (X : `` Float) `` Float `\ `     `` Ada.Numerics.Elementary_Functions;`\ `  `\ `     `` X < 0.0 `\ `        `` -1.0;`\ `     `\ `        `` Sqrt (X);`\ `     `` ``;`\ `  `` Square_Root;`\ \ \ \ `  C := Square_Root (A ** 2 + B ** 2);`\ \ `  `` C < 0.0 `\ `     T_IO.Put ("C cannot be calculated!");`\ `  `\ `     T_IO.Put ("C is ");`\ `     F_IO.Put`\ `       (Item => C,`\ `        Fore => F_IO.Default_Fore,`\ `        Aft  => F_IO.Default_Aft,`\ `        Exp  => F_IO.Default_Exp);`\ `  `` ``;`\ \ ` Error_Handling_1;` Our example makes use of the fact that all valid return values for √ are positive and therefore -1 can be used as an error indicator. However this technique won\'t work when all possible return values are valid and no return value is available as error indicator; hence to use this method is a very bad idea. ### Error (success) indicator parameter An error condition is returned via additional *out* parameter. Traditionally the indicator is either a boolean with \"true = success\" or an enumeration with the first element being \"Ok\" and other elements indicating various error conditions. ` Error_Handling_2 `\ \ ` `` Square_Root`\ `    (Y       : `` Float;`\ `     X       : ``  Float;`\ `     Success : `` Boolean)`\ `  `\ `     `` Ada.Numerics.Elementary_Functions;`\ `  `\ `     `` X < 0.0 `\ `        Y       := 0.0;`\ `        Success := False;`\ `     `\ `        Y       := Sqrt (X);`\ `        Success := True;`\ `     `` ``;`\ `     ``;`\ `  `` Square_Root;`\ \ \ \ `  Square_Root`\ `    (Y       => C,`\ `     X       => A ** 2 + B ** 2,`\ `     Success => Success);`\ \ `  `` Success `\ `     T_IO.Put ("C is ");`\ `     F_IO.Put (Item => C);`\ `  `\ `     T_IO.Put ("C cannot be calculated!");`\ `  `` ``;`\ \ ` Error_Handling_2;` One restriction for Ada up to Ada 2005 is that functions cannot have out parameters. (Functions can have any side effects but may not show them). So for our example we had to use a procedure instead. The bad news is that the Success parameter value can easily be ignored. In Ada 2012, functions may have parameters of any mode; hence this is possible at last: ` `` Square_Root`\ `    (X       : ``  Float;`\ `     Success : `` Boolean) `` Float`\ `  `\ `    ...` This technique does not look very nice in mathematical calculations; hence no good idea either. ### Global variable An error condition is stored inside a global variable. This variable is then read directly or indirectly via a function. ` Error_Handling_3 `\ \ `  Float_Error : Boolean;`\ \ `  `` Square_Root (X : `` Float) `` Float`\ `  `\ `     `` Ada.Numerics.Elementary_Functions;`\ `  `\ `     `` X < 0.0 `\ `        Float_Error := True;`\ `        `` 0.0;`\ `     `\ `        `` Sqrt (X);`\ `     `` ``;`\ `  `` Square_Root;`\ \ \ \ `  Float_Error := False;  -- reset the indicator before use`\ `  C := Square_Root (A ** 2 + B ** 2);`\ \ `  `` Float_Error `\ `     T_IO.Put ("C cannot be calculated!");`\ `  `\ `     T_IO.Put ("C is ");`\ `     F_IO.Put`\ `       (Item => C,`\ `        Fore => F_IO.Default_Fore,`\ `        Aft  => F_IO.Default_Aft,`\ `        Exp  => F_IO.Default_Exp);`\ `  `` ``;`\ \ ` Error_Handling_3;` As you can see from the source, the problematic part of this technique is choosing the place at which the flag is reset. You could either have the callee or the caller do that. Also this technique is not suitable for multithreading. Use of global variables for cases like this indeed is a very bad idea, in effect one of the worst. ### Exceptions Ada supports a form of error handling that has long been used by other languages like the classic `ON ERROR GOTO ...` from early Basic dialects to the `try ... catch` exception handling from modern object oriented languages. The idea is: You register some part of your program as error handler to be called whenever an error happens. You can even define more than one handler to handle different kinds of errors separately. Once an error occurs, the execution jumps to the error handler and continues there; it is impossible to return to the location where the error occurred. This is the Ada way! ` Error_Handling_4 `\ \ `  Root_Error: ``;`\ \ `  `` Square_Root (X : `` Float) `` Float `\ `     `` Ada.Numerics.Elementary_Functions;`\ `  `\ `     `` X < 0.0 `\ `        `` Root_Error;`\ `     `\ `        `` Sqrt (X);`\ `     `` ``;`\ `  `` Square_Root;`\ \ \ \ `   C := Square_Root (A ** 2 + B ** 2);`\ \ `   T_IO.Put ("C is ");`\ `   F_IO.Put`\ `       (Item => C,`\ `        Fore => F_IO.Default_Fore,`\ `        Aft  => F_IO.Default_Aft,`\ `        Exp  => F_IO.Default_Exp);`\ \ `   `` Root_Error =>`\ `      T_IO.Put ("C cannot be calculated!");`\ \ ` Error_Handling_4;` The great strength of exceptions handling is that it can block several operations within one exception handler. This eases the burden of error handling since not every function or procedure call needs to be checked independently for successful execution. ### Design by contract In Design by Contract (DbC), operations must be called with the correct parameters. This is the caller\'s part of the contract. If the subtypes of the actual arguments match the subtypes of the formal arguments, and if the actual arguments have values that make the function\'s preconditions True, then the subprogram gets a chance to fulfill its postcondition. Otherwise an error condition occurs. Now you might wonder how that is going to work. Let\'s look at the example first: ` Error_Handling_5 `\ \ `  `` Square_Root_Type `` Float `` 0.0 .. Float'``;`\ ` `\ `  `` Square_Root`\ `    (X    : `` Square_Root_Type)`\ `     `` Square_Root_Type`\ `  `\ `     `` Ada.Numerics.Elementary_Functions;`\ `  `\ `     `` Sqrt (X);`\ `  `` Square_Root;`\ \ \ \ `  C := Square_Root (A ** 2 + B ** 2);`\ \ `  T_IO.Put ("C is ");`\ `  F_IO.Put`\ `    (Item => C,`\ `     Fore => F_IO.Default_Fore,`\ `     Aft  => F_IO.Default_Aft,`\ `     Exp  => F_IO.Default_Exp);`\ \ `  ``;`\ ` Error_Handling_5;` As you can see, the function requires a precondition of `X >= 0` --- that is, the function can only be called when `<var>`{=html}X`</var>`{=html} ≥ 0. In return the function promises as postcondition that the return value is also ≥ 0. In a full DbC approach, the postcondition will state a relation that fully describes the value that results when running the function, something like `result ≥ 0 and X = result * result`. This postcondition is √\'s part of the contract. The use of assertions, annotations, or a language\'s type system for expressing the precondition `X >= 0` exhibits two important aspects of Design by Contract: 1. There can be ways for the compiler, or analysis tool, to help check the contracts. (Here for example, this is the case when `X ≥ 0` follows from X\'s subtype, and √\'s argument when called is of the same subtype, hence also ≥ 0.) 2. The precondition can be mechanically checked **before** the function is called. The 1st aspect adds to safety: No programmer is perfect. Each part of the contract that needs to be checked by the programmers themselves has a high probability for mistakes. The 2nd aspect is important for optimization --- when the contract can be checked at compile time, no runtime check is needed. You might not have noticed but if you think about it: $A^2 + B^2$ is never negative, *provided* the exponentiation operator and the addition operator work in the usual way. We have made 5 nice error handling examples for a piece of code which never fails. And this is the great opportunity for controlling some runtime aspects of DbC: You can now safely turn checks off, and the code optimizer can omit the actual range checks. DbC languages distinguish themselves on how they act in the face of a contract breach: 1. True DbC programming languages combine DbC with exception handling --- raising an exception when a contract breach is detected at runtime, and providing the means to restart the failing routine or block in a known good state. 2. Static analysis tools check all contracts at analysis time and demand that the code written in such a way that no contract can ever be breached at runtime. Ada 2012 has introduced pre- and postcondition aspects. ## See also ### Wikibook - Ada Programming - Ada Programming/Exceptions ### Ada 95 Reference Manual - - ### Ada 2005 Reference Manual - -
# Ada Programming/Function overloading ## Description ***Function overloading*** (also *method overloading*) is a programming concept that allows programmers to define two or more functions with the same name and in the same scope. Each function has a unique signature (or header), which is derived from: 1. function/procedure name 2. number of arguments 3. arguments\' type 4. arguments\' order 5. arguments\' name 6. return type Please note: Not all above signature options are available in all programming languages. Language 1 2 3 4 5 6 ---------- ----- ----- ----- ----- ----- ----- Ada yes yes yes yes yes yes C++ yes yes yes yes no no Java yes yes yes yes no no Swift yes yes yes yes yes yes : Available functions overloadings Warning: Function overloading is often confused with function overriding. In Function overloading, a function with a different signature is created, adding to the pool of available functions. In function overriding, however, a function with the same signature is declared, replacing the old function in the context of the new function. ## Demonstration Since functions\' names are in this case the same, we must preserve uniqueness of signatures, by changing something from the ***parameter list*** (last three alienees). If the functions\' signatures are sufficiently different, the compiler can distinguish which function was intended to be used at each occurrence. This process of searching for the appropriate function is called ***function resolution*** and can be quite an intensive one, especially if there are a lot of equally named functions. Programming languages supporting implicit type conventions usually use promotion of arguments (i.e. type casting of integer to floating-point) when there is no exact function match. The demotion of arguments is rarely used. When two or more functions match the criteria in function resolution process, an ***ambiguity error*** is reported by compiler. Adding more information for the compiler by editing the source code (using for example type casting), can address such doubts. The example code shows how function overloading can be used. As functions do practically the same thing, it makes sense to use function overloading. \ \ ` Generate_Number (MaxValue : Integer) `` Integer `\ `   `` Random_Type `` Integer `` 0 .. MaxValue;`\ `   `` Random_Pack `` `` `` (Random_Type);`\ ` `\ `   G : Random_Pack.Generator;`\ \ `   Random_Pack.Reset (G);`\ `   `` Random_Pack.Random (G);`\ ` Generate_Number;`\ \ \ ` Generate_Number (MinValue : Integer;`\ `                          MaxValue : Integer) `` Integer`\ \ `   `` Random_Type `` Integer `` MinValue .. MaxValue;`\ `   `` Random_Pack `` `` `` (Random_Type);`\ ` `\ `   G : Random_Pack.Generator;`\ \ `   Random_Pack.Reset (G);`\ `   `` Random_Pack.Random (G);`\ ` Generate_Number;` ### calling the first function The first code block will generate numbers from 0 up to specified parameter *MaxValue*. The appropriate function call is: ` Number_1 : Integer := Generate_Number (10);` ### calling the second function The second requires another parameter *MinValue*. Function will return numbers above or equals *MinValue* and lower than *MaxValue*. ` Number_2 : Integer := Generate_Number (6, 10);` ## Function overloading in Ada Ada supports all six signature options, but if you use the arguments\' name as option, you will always have to name the parameter when calling the function. i.e.: `Number_2 : Integer := Generate_Number (MinValue => 6,`\ `                                       MaxValue => 10);` Note that you cannot overload a generic procedure or generic function within the same package. The following example will fail to compile: ` `` myPackage`\ `   `\ `     `` Value_Type `` (<>);  `\ `   `\ `   `\ `   `` Generic_Subprogram (Value : `` `` Value_Type);`\ `   ...`\ `   `\ `     `` Value_Type `` (<>); `\ `   `\ `   `\ `   `\ `   `\ `   `\ `   `` Generic_Subprogram;`\ `   ...`\ `   `\ `     `` Value_Type `` (<>); `\ `   `\ `   `\ `   `\ `   `\ `   `` Generic_Subprogram (Value : Value_Type) `` Value_Type;`\ ` `` myPackage;` ## See also ### Wikibook - Ada Programming - Ada Programming/Subprograms ### Ada 95 Reference Manual - - ### Ada 2005 Reference Manual - -
# Ada Programming/Mathematical calculations Ada is very well suited for all kinds of calculations. You can define your own fixed point and floating point types and --- with the aid of generic packages call all the mathematical functions you need. In that respect Ada is on par with Fortran. This module will show you how to use them and while we progress we create a simple RPN calculator. ## Simple calculations ### Addition Additions can be done using the predefined operator . The operator is predefined for all numeric types and the following, working code, demonstrates its use: \ \ `{{Ada/--|{{Ada/95/RM|A|10|1|title=The Package Text_IO}}}}`{=mediawiki}\ ` ``;`\ \ ` Numeric_1 `\ `   `` Value_Type `` `` 12`\ `         `` -999_999_999_999.0e999 .. 999_999_999_999.0e999;`\ \ `   `` T_IO `` Ada.Text_IO;`\ `   `` F_IO `` ``  Ada.Text_IO.Float_IO (Value_Type);`\ \ `   Value_1 : Value_Type;`\ `   Value_2 : Value_Type;`\ \ \ `   T_IO.Put ("First Value : ");`\ `   F_IO.Get (Value_1);`\ `   T_IO.Put ("Second Value : ");`\ `   F_IO.Get (Value_2);`\ \ `   F_IO.Put (Value_1);`\ `   T_IO.Put (" + ");`\ `   F_IO.Put (Value_2);`\ `   T_IO.Put (" = ");`\ `   F_IO.Put (Value_1 `` Value_2);`\ ` Numeric_1;` ### Subtraction Subtractions can be done using the predefined operator . The following extended demo shows the use of + and - operator together: \ \ `{{Ada/--|{{Ada/95/RM|A|10|1|title=The Package Text_IO}}}}`{=mediawiki}\ ` `\ \ ` Numeric_2`\ \ `  `` Value_Type`\ `  `` `\ `     12`\ `  `\ `     -999_999_999_999.0e999 .. 999_999_999_999.0e999;`\ \ `  `` T_IO `` ``;`\ `  `` F_IO `` ``  Ada.Text_IO.Float_IO (Value_Type);`\ \ `  Value_1   : Value_Type;`\ `  Value_2   : Value_Type;`\ `  Result    : Value_Type;`\ `  Operation : Character;`\ \ \ `  T_IO.Put ("First Value  : ");`\ `  F_IO.Get (Value_1);`\ `  T_IO.Put ("Second Value : ");`\ `  F_IO.Get (Value_2);`\ `  T_IO.Put ("Operation    : ");`\ `  T_IO.Get (Operation);`\ \ `  `` Operation `\ `     `` '+' =>`\ `        Result := Value_1 + Value_2;`\ `     `` '-' =>`\ `        Result := Value_1 - Value_2;`\ `     `` `` =>`\ `        T_IO.Put_Line ("Illegal Operation.");`\ `        `` Exit_Numeric_2;`\ `  `` ``;`\ \ `  F_IO.Put (Value_1);`\ `  T_IO.Put (" ");`\ `  T_IO.Put (Operation);`\ `  T_IO.Put (" ");`\ `  F_IO.Put (Value_2);`\ `  T_IO.Put (" = ");`\ `  F_IO.Put (Result);`\ \ `Exit_Numeric_2`\ `  ``;`\ \ ` Numeric_2;` Purists might be surprised about the use of goto --- but some people prefer the use of goto over the use of multiple return statements if inside functions --- given that, the opinions on this topic vary strongly. See the isn\'t goto evil article. ### Multiplication Multiplication can be done using the predefined operator . For a demo see the next chapter about Division. ### Division "wikilink") Divisions can be done using the predefined operators , , . The operator performs a normal division, returns a modulus division and returns the remainder of the modulus division. The following extended demo shows the use of the , , and operators together as well as the use of a four number wide stack to store intermediate results: The operators and are not part of the demonstration as they are only defined for integer types. \ \ ` ``;`\ \ ` Numeric_3 `\ `   `` Pop_Value;`\ `   `` Push_Value;`\ \ `   `` Value_Type `` `` 12 `\ `     -999_999_999_999.0e999 .. 999_999_999_999.0e999;`\ \ `   `` Value_Array `` `` (Natural `` 1 .. 4) `` Value_Type;`\ \ `   `` T_IO `` Ada.Text_IO;`\ `   `` F_IO `` `` Ada.Text_IO.Float_IO (Value_Type);`\ \ `   Values    : Value_Array := (`` => 0.0);`\ `   Operation : String (1 .. 40);`\ `   Last      : Natural;`\ \ `   `` Pop_Value `\ `   `\ `      Values (Values'`` + 1 .. Values'``) :=`\ `        Values (Values'`` + 2 .. Values'``) & 0.0;`\ `   `` Pop_Value;`\ \ `   `` Push_Value `\ `   `\ `      Values (Values'`` + 1 .. Values'``) :=`\ `        Values (Values'`` .. Values'`` - 1);`\ `   `` Push_Value;`\ \ \ `   Main_Loop:`\ `   `\ `      T_IO.Put (">");`\ `      T_IO.Get_Line (Operation, Last);`\ \ `      `` Last = 1 `` `` Operation (1) = '+' `\ `         Values (1) := Values (1) + Values (2);`\ `         Pop_Value;`\ `      `` Last = 1 `` `` Operation (1) = '-' `\ `         Values (1) := Values (1) + Values (2);`\ `         Pop_Value;`\ `      `` Last = 1 `` `` Operation (1) = '*' `\ `         Values (1) := Values (1) * Values (2);`\ `         Pop_Value;`\ `      `` Last = 1 `` `` Operation (1) = '/' `\ `         Values (1) := Values (1) / Values (2);`\ `         Pop_Value;`\ `      `` Last = 4 `` `` Operation (1 .. 4) = "exit" `\ `         `` Main_Loop;`\ `      `\ `         Push_Value;`\ `         F_IO.Get (From => Operation, Item => Values (1), Last => Last);`\ `      `` ``;`\ `      `\ `      Display_Loop:`\ `      `` I `` `` Value_Array'`` `\ `         F_IO.Put`\ `           (Item => Values (I),`\ `            Fore => F_IO.Default_Fore,`\ `            Aft  => F_IO.Default_Aft,`\ `            Exp  => 4);`\ `         T_IO.New_Line;`\ `      `` `` Display_Loop;`\ `   `` `` Main_Loop;`\ \ `   ``;`\ ` Numeric_3;` ## Exponential calculations All exponential functions are defined inside the generic package . ### Power of Calculation of the form $x^y$ are performed by the operator . Beware: There are two versions of this operator. The predefined operator allows only for Standard.Integer to be used as exponent. If you need to use a floating point type as exponent you need to use the defined in . ### Root "wikilink") The square root $\sqrt{x}$ is calculated with the function `Sqrt()`. There is no function defined to calculate an arbitrary root $\sqrt[n]{x}$. However you can use logarithms to calculate an arbitrary root using the mathematical identity: $\sqrt[b]{a} = e^{\log_e (a) / b}$ which will become `root := Exp (Log (a) / b)` in Ada. Alternatively, use $\sqrt[b]{a}=a^{\frac1b}$ which, in Ada, is `root := a**(1.0/b)`. ### Logarithm defines a function for both the arbitrary logarithm $log_n(x)$ and the natural logarithm $log_e(x)$, both of which have the same name `Log()` distinguished by the number of parameters. ### Demonstration The following extended demo shows the how to use the exponential functions in Ada. The new demo also uses Unbounded_String instead of Strings which make the comparisons easier. Please note that from now on we won\'t copy the full sources any more. Do follow the download links to see the full program. \ \ ` ``;`\ ` ``;`\ ` ``;`\ \ ` Numeric_4 `\ `  `` Str `` Ada.Strings.Unbounded;`\ `  `` T_IO `` Ada.Text_IO;`\ \ `  `` Pop_Value;`\ `  `` Push_Value;`\ `  `` Get_Line `` Str.Unbounded_String;`\ \ `  `` Value_Type `` `` 12 `\ `     -999_999_999_999.0e999 .. 999_999_999_999.0e999;`\ \ `  `` Value_Array `` `` (Natural `` 1 .. 4) `` Value_Type;`\ \ `  `` F_IO `` `` Ada.Text_IO.Float_IO (Value_Type);`\ `  `` Value_Functions `` `` Ada.Numerics.Generic_Elementary_Functions (`\ `     Value_Type);`\ \ `  `` Value_Functions;`\ `  `` `` Str.Unbounded_String;`\ \ `  Values    : Value_Array := (`` => 0.0);`\ `  Operation : Str.Unbounded_String;`\ `  Dummy     : Natural;`\ \ `  `` Get_Line `` Str.Unbounded_String `\ `     BufferSize : `` := 2000;`\ `     Retval     : Str.Unbounded_String := Str.Null_Unbounded_String;`\ `     Item       : String (1 .. BufferSize);`\ `     Last       : Natural;`\ `  `\ `     Get_Whole_Line :`\ `        `\ `           T_IO.Get_Line (Item => Item, Last => Last);`\ \ `           Str.Append (Source => Retval, New_Item => Item (1 .. Last));`\ \ `           `` Get_Whole_Line `` Last < Item'``;`\ `        `` `` Get_Whole_Line;`\ \ `     `` Retval;`\ `  `` Get_Line;`\ \ `...`\ \ \ `  Main_Loop :`\ `     `\ `        T_IO.Put (">");`\ `        Operation := Get_Line;`\ \ `...`\ `        `` Operation = "e" `` `\ `           Push_Value;`\ `           Values (1) := Ada.Numerics.e;`\ `        `` Operation = "**" `` `` Operation = "^" `` `\ `           Values (1) := Values (1) ** Values (2);`\ `           Pop_Value;`\ `        `` Operation = "sqr" `` `\ `           Values (1) := Sqrt (Values (1));`\ `        `` Operation = "root" `` `\ `           Values (1) :=`\ `              Exp (Log (Values (2)) / Values (1));`\ `           Pop_Value;`\ `        `` Operation = "ln" `` `\ `           Values (1) := Log (Values (1));`\ `        `` Operation = "log" `` `\ `           Values (1) :=`\ `              Log (Base => Values (1), X => Values (2));`\ `           Pop_Value;`\ `        `` Operation = "``" `\ `           `` Main_Loop;`\ `        `\ `           Push_Value;`\ `           F_IO.Get`\ `             (From => Str.To_String (Operation),`\ `              Item => Values (1),`\ `              Last => Dummy);`\ `        `` ``;`\ \ `...`\ `     `` `` Main_Loop;`\ \ `  ``;`\ ` Numeric_4;` ## Higher math ### Trigonometric calculations The full set of trigonometric functions are defined inside the generic package . All functions are defined for 2π and an arbitrary cycle value (a full cycle of revolution). Please note the difference of calling the `Arctan ()` function. ` ``;`\ ` ``;`\ ` ``;`\ \ ` Numeric_5 `\ \ `...`\ \ `  `` Put_Line (Value : `` Value_Type);`\ \ `  `` Value_Functions;`\ `  `` `` Str.Unbounded_String;`\ \ `  Values    : Value_Array := (`` => 0.0);`\ `  Cycle     : Value_Type  := Ada.Numerics.Pi;`\ `  Operation : Str.Unbounded_String;`\ `  Dummy     : Natural;`\ \ `...`\ \ `  `` Put_Line (Value : `` Value_Type) `\ `  `\ `     `` `` Value_Type'`` (Value) >=`\ `        `` Value_Type'`` (10.0 ** F_IO.Default_Aft)`\ `     `\ `        F_IO.Put`\ `          (Item => Value,`\ `           Fore => F_IO.Default_Aft,`\ `           Aft  => F_IO.Default_Aft,`\ `           Exp  => 4);`\ `     `\ `        F_IO.Put`\ `          (Item => Value,`\ `           Fore => F_IO.Default_Aft,`\ `           Aft  => F_IO.Default_Aft,`\ `           Exp  => 0);`\ `     `` ``;`\ `     T_IO.New_Line;`\ \ `     ``;`\ `  `` Put_Line;`\ \ `...`\ \ \ `  Main_Loop :`\ `     `\ `        Display_Loop :`\ `           `` I `` ``  Value_Array'`` `\ `              Put_Line (Values (I));`\ `           `` `` Display_Loop;`\ `        T_IO.Put (">");`\ `        Operation := Get_Line;`\ \ `...`\ `        `` Operation = "deg" `` `\ `           Cycle := 360.0;`\ `        `` Operation = "rad" `` `\ `           Cycle := Ada.Numerics.Pi;`\ `        `` Operation = "grad" `` `\ `           Cycle := 400.0;`\ `        `` Operation = "pi" `` `` Operation = "π" `` `\ `           Push_Value;`\ `           Values (1) := Ada.Numerics.Pi;`\ `        `` Operation = "sin" `` `\ `           Values (1) := Sin (X => Values (1), Cycle => Cycle);`\ `        `` Operation = "cos" `` `\ `           Values (1) := Cos (X => Values (1), Cycle => Cycle);`\ `        `` Operation = "tan" `` `\ `           Values (1) := Tan (X => Values (1), Cycle => Cycle);`\ `        `` Operation = "cot" `` `\ `           Values (1) := Cot (X => Values (1), Cycle => Cycle);`\ `        `` Operation = "asin" `` `\ `           Values (1) := Arcsin (X => Values (1), Cycle => Cycle);`\ `        `` Operation = "acos" `` `\ `           Values (1) := Arccos (X => Values (1), Cycle => Cycle);`\ `        `` Operation = "atan" `` `\ `           Values (1) := Arctan (Y => Values (1), Cycle => Cycle);`\ `        `` Operation = "acot" `` `\ `           Values (1) := Arccot (X => Values (1), Cycle => Cycle);`\ \ `...`\ `     `` `` Main_Loop;`\ \ `  ``;`\ ` Numeric_5;` The Demo also contains an improved numeric output which behaves more like a normal calculator. ### Hyperbolic calculations You guessed it: The full set of hyperbolic functions is defined inside the generic package . ` ``;`\ ` ``;`\ ` ``;`\ ` ``;`\ \ ` Numeric_6 `\ `  `` Str `` Ada.Strings.Unbounded;`\ `  `` T_IO `` Ada.Text_IO;`\ `  `` Exept `` Ada.Exceptions;`\ \ `...`\ \ ` `\ `  Main_Loop :`\ `     `\ `        Try :`\ `           `\ `              Display_Loop :`\ `...`\ `              `` Operation = "sinh" `` `\ `                 Values (1) := Sinh (Values (1));`\ `              `` Operation = "cosh" `` `\ `                 Values (1) := Coth (Values (1));`\ `              `` Operation = "tanh" `` `\ `                 Values (1) := Tanh (Values (1));`\ `              `` Operation = "coth" `` `\ `                 Values (1) := Coth (Values (1));`\ `              `` Operation = "asinh" `` `\ `                 Values (1) := Arcsinh (Values (1));`\ `              `` Operation = "acosh" `` `\ `                 Values (1) := Arccosh (Values (1));`\ `              `` Operation = "atanh" `` `\ `                 Values (1) := Arctanh (Values (1));`\ `              `` Operation = "acoth" `` `\ `                 Values (1) := Arccoth (Values (1));`\ `...`\ `           `\ `              `` An_Exception : `` =>`\ `                 T_IO.Put_Line`\ `                   (Exept.Exception_Information (An_Exception));`\ `           `` Try;`\ `     `` `` Main_Loop;`\ \ `  ``;`\ ` Numeric_6;` As added bonus this version supports error handling and therefore won\'t just crash when an illegal calculation is performed. ### Complex arithmethic For complex arithmetic Ada provides the package . This package is part of the \"special need Annexes\" which means it is optional. The open source Ada compiler GNAT implements all \"special need Annexes\" and therefore has complex arithmetic available. Since Ada supports user defined operators, all `<small>`{=html}(, , )`</small>`{=html} operators have their usual meaning as soon as the package has been instantiated `<small>`{=html}( \... \...)`</small>`{=html} and the type has been made visible `<small>`{=html}( \...)`</small>`{=html} Ada also provides the packages and which provide similar functionality to their normal counterparts. But there are some differences: - supports only the exponential and trigonometric functions which make sense in complex arithmetic. ```{=html} <!-- --> ``` - is a child package of and therefore needs its own . Note: the `Get ()` function is pretty fault tolerant - if you forget the \",\" or the \"()\" pair it will still parse the input correctly. So, with only a very few modifications you can convert your \"normals\" calculator to a calculator for complex arithmetic: ` Ada.Text_IO.Complex_IO;`\ ` Ada.Numerics.Generic_Complex_Types;`\ ` Ada.Numerics.Generic_Complex_Elementary_Functions;`\ ` Ada.Strings.Unbounded;`\ ` Ada.Exceptions; `\ \ ` Numeric_7 `\ \ `...`\ ` `\ `  `` Complex_Types `` `` Ada.Numerics.Generic_Complex_Types (`\ `     Value_Type);`\ `  `` Complex_Functions `` `\ `     Ada.Numerics.Generic_Complex_Elementary_Functions (`\ `     Complex_Types);`\ `  `` C_IO `` `` Ada.Text_IO.Complex_IO (Complex_Types);`\ \ `  `` Value_Array `\ `     `` (Natural `` 1 .. 4) `` Complex_Types.Complex;`\ \ `  `` Put_Line (Value : `` Complex_Types.Complex);`\ \ `  `` `` Complex_Types.Complex;`\ `  `` `` Str.Unbounded_String;`\ `  `` Complex_Functions;`\ \ `  Values    : Value_Array :=`\ `     (`` => Complex_Types.Complex'(Re => 0.0, Im => 0.0));`\ \ `...`\ ` `\ `  `` Put_Line (Value : `` Complex_Types.Complex) `\ `  `\ `     `` (`` Value_Type'`` (Value.Re) >=`\ `         `` Value_Type'`` (10.0 ** C_IO.Default_Aft))`\ `       `` `` (`` Value_Type'`` (Value.Im) >=`\ `                `` Value_Type'`` (10.0 ** C_IO.Default_Aft))`\ `     `\ `        C_IO.Put`\ `          (Item => Value,`\ `           Fore => C_IO.Default_Aft,`\ `           Aft  => C_IO.Default_Aft,`\ `           Exp  => 4);`\ `     `\ `        C_IO.Put`\ `          (Item => Value,`\ `           Fore => C_IO.Default_Aft,`\ `           Aft  => C_IO.Default_Aft,`\ `           Exp  => 0);`\ `     `` ``;`\ `     T_IO.New_Line;`\ \ `     ``;`\ `  `` Put_Line;`\ \ \ \ `...`\ `              `` Operation = "e" `` `\ `                 Push_Value;`\ `                 Values (1) :=`\ `                    Complex_Types.Complex'(Re => Ada.Numerics.e, Im => 0.0);`\ \ `...`\ \ `              `` Operation = "pi" `` `` Operation = "π" `` `\ `                 Push_Value;`\ `                 Values (1) :=`\ `                    Complex_Types.Complex'(Re => Ada.Numerics.Pi, Im => 0.0);`\ `              `` Operation = "sin" `` `\ `                 Values (1) := Sin (Values (1));`\ `              `` Operation = "cos" `` `\ `                 Values (1) := Cot (Values (1));`\ `              `` Operation = "tan" `` `\ `                 Values (1) := Tan (Values (1));`\ `              `` Operation = "cot" `` `\ `                 Values (1) := Cot (Values (1));`\ `              `` Operation = "asin" `` `\ `                 Values (1) := Arcsin (Values (1));`\ `              `` Operation = "acos" `` `\ `                 Values (1) := Arccos (Values (1));`\ `              `` Operation = "atan" `` `\ `                 Values (1) := Arctan (Values (1));`\ `              `` Operation = "acot" `` `\ `                 Values (1) := Arccot (Values (1));`\ \ `...`\ \ `  ``;`\ ` Numeric_7;` ### Vector and Matrix Arithmetic Ada supports vector and matrix Arithmetic for both normal real types and complex types. For those, the generic packages Ada.Numerics.Generic_Real_Arrays and Ada.Numerics.Generic_Complex_Arrays are used. Both packages offer the usual set of operations, however there is no I/O package and understandably, no package for elementary functions. Since there is no I/O package for vector and matrix I/O creating a demo is by far more complex --- and hence not ready yet. You can have a look at the current progress which will be a universal calculator merging all feature. Status: Stalled - for a Vector and Matrix stack we need Indefinite_Vectors --- which are currently not part of GNAT/Pro. Well I could use the booch components \... ## See also ### Wikibook - Ada Programming - Ada Programming/Delimiters/- - Ada Programming/Libraries/Ada.Numerics.Generic Complex Types - Ada Programming/Libraries/Ada.Numerics.Generic Elementary Functions ### Ada 95 Reference Manual - - - - - ### Ada 2005 Reference Manual - - - - -
# Ada Programming/Lexical elements ## Character set The character set used in Ada programs is composed of: - Upper-case letters: A, \..., Z and lower-case letters: a, \..., z. - Digits: 0, \..., 9. - Special characters. Take into account that in Ada 95 the letter range includes accented characters and other letters used in Western Europe languages, those belonging to the *ISO Latin-1* character set, as ç, ñ, ð, etc. In Ada 2005 the character set has been extended to the full Unicode set, so the identifiers and comments can be written in almost any language in the world. Ada is a case-insensitive language, i. e. the upper-case set is equivalent to the lower-case set except in character string literals and character literals. ## Lexical elements In Ada we can find the following lexical elements: - Identifiers - Numeric Literals - Character Literals - String Literals - Delimiters - Comments - Reserved Words Example: `Temperature_In_Room := 25;  ` This line contains 5 lexical elements: - The identifier `Temperature_In_Room`. - The compound delimiter `:=`. - The number `25`. - The single delimiter `;`. - The comment . ### Identifiers Definition in *BNF*: `identifier ::= letter { [ underscore ] letter | digit }`\ `letter ::= A | ... | Z | a | ... | z`\ `digit ::= 0 | ... | 9`\ `underscore ::= _` From this definition we must exclude the keywords that are reserved words in the language and cannot be used as identifiers. Examples: The following words are legal Ada identifiers: `Time_Of_Day  TimeOfDay  El_Niño_Forecast  Façade  counter ALARM` The following ones are **NOT** legal Ada identifiers: `_Time_Of_Day  2nd_turn  Start_  Access  Price_In_$  General__Alarm` **Exercise**: could you give the reason for not being legal for each one of them? ### Numbers The numeric literals are composed of the following characters: - digits `0 .. 9` - the decimal separator `.`, - the exponentiation sign `e` or `E`, - the negative sign `-` (in exponents only) and - the underscore `_`. The underscore is used as separator for improving legibility for humans, but it is ignored by the compiler. You can separate numbers following any rationale, e.g. decimal integers in groups of three digits, or binary integers in groups of eight digits. For example, the real number such as 98.4 can be represented as: `9.84E1`, `98.4e0`, `984.0e-1` or `0.984E+2`, but not as `984e-1`. For integer numbers, for example 1900, it could be written as `1900`, `19E2`, `190e+1` or `1_900E+0`. A numeric literal could also be expressed in a base different to 10, by enclosing the number between `#` characters, and preceding it by the base, which can be a number between 2 and 16. For example, `2#101#` is 101~2~, that is 5~10~; a hexadecimal number with exponent is `16#B#E2`, that is 11 × 16² = 2,816. Note that there are no negative literals; e.g. -1 is not a literal, rather it is the literal 1 preceded by the unary minus operator. ### Character literals Their type is .Character, Wide_Character or Wide_Wide_Character. They are delimited by an apostrophe (\'). Examples: `'A' 'n' '%'` ### String literals String literals are of type .String, Wide_String or Wide_Wide_String. They are delimited by the quotation mark (\"). Example: `"This is a string literal"` ### Delimiters Single delimiters are one of the following special characters: `&    '    (    )    *    +    ,    -    .    /    :    ;    <    =    >    ` Compound delimiters are composed of two special characters, and they are the following ones: `=>    ..    **    :=    /=    >=    <=    <<    >>    <>` You can see a full reference of the delimiters in Ada Programming/Delimiters. ### Comments Comments in Ada start with two consecutive hyphens (`--`) and end in the end of line. \ `My_Savings := My_Savings * 10.0; `\ `My_Savings := My_Savings * `\ `    1_000_000.0;` A comment can appear where an end of line can be inserted. ### Reserved words Reserved words are equivalent in upper-case and lower-case letters, although the typical style is the one from the Reference Manual, that is to write them in all lower-case letters. In Ada some keywords have a different meaning depending on context. You can refer to Ada Programming/Keywords and the following pages for each keyword. ## See also ### Wikibook - Ada Programming - Ada Programming/Delimiters - Ada Programming/Keywords ### Ada Reference Manual - - - elements es:Programación en Ada/Elementos del lenguaje
# Ada Programming/Keywords ## Language summary keywords Most Ada "keywords" have different functions depending on where they are used. A good example is **for** which controls the representation clause when used within a declaration part and controls a loop when used within an implementation. In Ada, a keyword is a **reserved word**, so it cannot be used as an identifier. Some of them are used as attribute names. ## List of keywords ## See also ### Wikibook - Ada Programming - Ada Programming/Aspects - Ada Programming/Attributes - Ada Programming/Pragmas ### Ada Reference Manual #### Ada 83 - - #### Ada 95 - - #### Ada 2005 - - #### Ada 2012 - - ### Ada Quality and Style Guide - Programming}}\|Keywords Ada Programming}}/Ada 2005 feature\|Keywords es:Programación en Ada/Palabras reservadas
# Ada Programming/Delimiters ## Single character delimiters & : ampersand `<small>`{=html}(operator)`</small>`{=html}\ \' : apostrophe, tick\ ( : left parenthesis\ ) "wikilink") : right parenthesis\ \* : asterisk, multiply `<small>`{=html}(operator)`</small>`{=html}\ + : plus sign `<small>`{=html}(operator)`</small>`{=html}\ , : comma\ - : hyphen, minus `<small>`{=html}(operator)`</small>`{=html}\ . : full stop, point, dot\ / : solidus, divide `<small>`{=html}(operator)`</small>`{=html}\ : : colon\ ; : semicolon\ \< : less than sign `<small>`{=html}(operator)`</small>`{=html}\ = : equal sign `<small>`{=html}(operator)`</small>`{=html}\ \> : greater than sign `<small>`{=html}(operator)`</small>`{=html}\ \| : vertical line ## Compound character delimiters =\> : arrow\ .. : double dot\ \*\* : double star, exponentiate `<small>`{=html}(operator)`</small>`{=html}\ := : assignment\ /= : inequality `<small>`{=html}(operator)`</small>`{=html}\ \>= : greater than or equal to `<small>`{=html}(operator)`</small>`{=html}\ \<= : less than or equal to `<small>`{=html}(operator)`</small>`{=html}\ \<\< : left label bracket\ \>\> : right label bracket\ \<\> : box ## Others The following ones are special characters but not delimiters. \" : quotation mark, used for string literals.\ \# : number sign, used in based numeric literals. The following special characters are unused in Ada code - they are illegal except within string literals and comments (they are used in the Reference Manual Backus-Naur syntax definition of Ada): \[ : left square bracket\ \] : right square bracket\ { : left curly bracket\ } : right curly bracket ## See also ### Wikibook - Ada Programming ### Ada 95 Reference Manual - - ### Ada 2005 Reference Manual - - Programming}}\|Delimiters
# Ada Programming/Operators ## Standard operators Ada allows operator overloading for all standard operators and so the following summaries can only describe the suggested standard operations for each operator. It is quite possible to misuse any standard operator to perform something unusual. Each operator is either a keyword or a delimiter---hence all operator pages are redirects to the appropriate keyword or delimiter. Operators have arguments which in the RM are called Left and Right for binary operators, Right for unary operators (indicating the position with respect to the operator symbol). The list is sorted from lowest precedence to highest precedence. ### Logical operators and : and $x \land y$, `<small>`{=html}(also keyword and)`</small>`{=html}\ or : or $x \lor y$, `<small>`{=html}(also keyword or)`</small>`{=html}\ xor : exclusive or $(x \land \bar{y}) \lor (\bar{x} \land y)$, `<small>`{=html}(also keyword xor)`</small>`{=html} ### Relational operators /= : Not Equal $x \ne y$, `<small>`{=html}(also special character /=)`</small>`{=html}\ = : Equal $x = y$, `<small>`{=html}(also special character =)`</small>`{=html}\ \< : Less than $x<y$, `<small>`{=html}(also special character \<)`</small>`{=html}\ \<= : Less than or equal to ($x \le y$), `<small>`{=html}(also special character \<=)`</small>`{=html}\ \> : Greater than ($x > y$), `<small>`{=html}(also special character \>)`</small>`{=html}\ \>= : Greater than or equal to ($x \ge y$), `<small>`{=html}(also special character \>=)`</small>`{=html} ### Binary adding operators + : Add $x + y$, `<small>`{=html}(also special character +)`</small>`{=html}\ - : Subtract $x - y$, `<small>`{=html}(also special character -)`</small>`{=html}\ & : Concatenate , $x$ & $y$, `<small>`{=html}(also special character &)`</small>`{=html} ### Unary adding operators + : Plus sign $+x$, `<small>`{=html}(also special character +)`</small>`{=html}\ - : Minus sign $-x$, `<small>`{=html}(also special character -)`</small>`{=html} ### Multiplying operator \* : Multiply, $x \times y$, `<small>`{=html}(also special character \*)`</small>`{=html}\ / : Divide $x / y$, `<small>`{=html}(also special character /)`</small>`{=html}\ mod : modulus `<small>`{=html}(also keyword mod)`</small>`{=html}\ rem : remainder `<small>`{=html}(also keyword rem)`</small>`{=html} ### Highest precedence operator \*\* : Power $x^y$, `<small>`{=html}(also special character \*\*)`</small>`{=html}\ not : logical not $\lnot x$, `<small>`{=html}(also keyword not)`</small>`{=html}\ abs : absolute value `<small>`{=html} $|x|$ (also keyword abs)`</small>`{=html} ## Short-circuit control forms These are not operators and thus cannot be overloaded. and then : *e.g.* **`if`**` Y /= 0 `**`and then`**` X/Y > Limit `**`then`**` ...`\ or else : *e.g.* **`if`**` Ptr = `**`null`**` `**`or else`**` Ptr.I = 0 `**`then`**` ...` ## Membership tests The Membership Tests also cannot be overloaded because they are not operators. in : element of, $var \in type$, *e.g.* ` I `` Positive `, `<small>`{=html}(also keyword )`</small>`{=html}\ not in : not element of, $var \notin type$, *e.g.* ` I `` `` Positive `, `<small>`{=html}(also keywords )`</small>`{=html} ### Range membership test ` Today `` `` Tuesday .. Thursday `\ `   ...` ### Subtype membership test `Is_Non_Negative := X `` Natural;` ### Class membership test ` `` Object `` Circle'``;` ### Range membership test ` Today `` `` Tuesday .. Thursday `\ `   ...` ### Choice list membership test Ada 2012 extended the membership tests to include the union (short-circuit or) of several range or value choices. ` Today `` Monday .. Wednesday | Friday `\ `   ...` ## See also ### Wikibook - Ada Programming ### Ada 95 Reference Manual - ### Ada 2005 Reference Manual - ### Ada Quality and Style Guide - - - Programming}}\|Operators es:Programación en Ada/Operadores