Conditionals and loops
Very often through the course of a program you'll need it to take different actions depending on some condition maybe finding the terminating condition of an algorithm, or responding to user input. The conditional statement in Python uses the if keyword. Every statement that starts a new block of code must be terminated with a colon. Indented code following the if statement will only be executed if the condition evaluates to True. As soon as your code is dedented, execution continues normally....
In many places it wont matter whether you pass in a sequence or an iterator In
Assigning to members of a list uses the same syntax. gt gt gt a 1, 2, 3, 4 gt gt gt a 0 ' a' gt gt gt a 'a', 2, 3, 4 gt gt gt a -1 'b' Deleting members uses the del keyword. Because you can modify a list by changing members or adding and removing members, it is a mutable datatype. The list has a close cousin that's immutable the tuple. TUPLES The tuple is a container object similar to a list. Tuples can be indexed in the same way as lists but, because they're immutable, you can't assign to...
Listing A function to compile and save or return assemblies from source code
from System.Environment import CurrentDirectory from System.IO import Path, Directory from Microsoft.CSharp import CSharpCodeProvider from Microsoft.VisualBasic import VBCodeProvider def Generate code, name, references None, outputDir None, inMemory False, csharp True params Compiler.CompilerParameters Configure the path c t . _ to save assembly outputDir Directory.GetCurrentDirectory asmPath Path.Combine outputDir, name '.dll' params.OutputAssembly asmPath params.GeneratelnMemory False else...
Using the interactive interpreter
When you download IronPython,33 you have two choices. You can download and install the msi installer IronPython 2 only , which includes the Python 2.5 standard library. Alternately, you can download and unpack the binary distribution that comes as a zip file. Whichever route you take, you'll have two executables, ipy.exe and ipyw.exe, which are the equivalents of the Python executables python.exe and pythonw.exe. Both are used to launch Python scripts ipy.exe launches them with a console...
Expressions functions and Python types
The simplest example of this is to use IronPython to evaluate individual expressions. IronPython makes a great calculator 21 So far, whenever we have executed Python code from a string we have passed in the enumeration member SourceCodeKind.Statements. This member has a sister, SourceCodeKind.Expression, that allows us to evaluate an expression and return an object. It is used in this snippet of C to evaluate a simple mathematical expression string code 2 3 5 ScriptSource source 21 You can see...
Python datatypes
Python boasts a rich set of built-in datatypes that you can use without importing any modules. Most of these, with the exception of the set that we introduce shortly, have syntax for including them within your code. To understand the examples in this book or to write Python yourself, you're going to need to recognize them. Table 2.1 contains a guide to all the basic datatypes and their syntaxes. Table 2.1 The built-in datatypes and their syntaxes Table 2.1 The built-in datatypes and their...
The essence of this concept is that valid uses of an object should be
Duck typing can be extremely useful. If you have an API that takes a mapping type object and sets or fetches entries from the object, you can pass in any object that implements the mapping protocol. Protocols are a dynamically typed versions of interfaces. They allow you to create data structures as classes, implementing custom behavior when data is set or fetched. You can also provide additional methods to access or modify the data beyond simple access. Listing 4.1 is an example class that...
Listing Using the dialog created in Visual Studio with IronPython
clr.AddReference 'RenameTabDialog' from RenameTabDialog import RenameTabDialogBase 10 IronPython uses reflection to discover members. Marking them as protected or private only makes them less convenient to access it doesn't truly hide them from the determined programmer. 11 If you subclass a .NET class, protected members are public, so you can still access them from outside the class. You can't access protected members on a non-Python subclass. from System.Windows.Forms import DialogResult...
A new language for NET 1
An introduction to IronPython Python and dynamic languages on .NET The IronPython interactive interpreter Live object introspection with help and dir The .NET framework was launched in 2000 and has since become a popular platform for object-oriented programming. Its heart and soul is the Common Language Runtime CLR , which is a powerful system including a just-in-time compiler, built-in memory management, and security features. Fortunately, you can write .NET programs that take advantage of...
Dynamic attribute access 1
Python attribute access uses straightforward syntax, shared with other imperative languages like Java and C . Through properties, you can control what happens when individual attributes are fetched or set but, with Python, you can provide access to arbitrary attributes through the_getattr_method. 8 This page in the Python documentation lists among other things the protocol methods for rich comparison 9 See the following article on rich comparison in CPython and IronPython, which also shows a...
A Delegates
A delegate is a type that represents a reference to a method. Delegates are essentially the same as Python function references a delegate that has been created from an instance carries a reference back to that instance in the same way as a bound method reference. Delegate definitions look like this delegate int IntegerFunction int a, int b This creates an IntegerFunction type that accepts two integers and returns an integer. In addition to creating delegates from method references, you can...
The builtin Python functions and modules
If we have a collection of objects created from Python code and we want to add them up, we have several choices of how to do it. We could set them in an execution scope with names and evaluate an expression that adds them up, or we could use Object-Operations.Add in a loop. We have a third choice as well Python has a perfectly good built-in function for adding things up sum. Python has a wide range of useful built-in functions, and in IronPython they are implemented as static methods on...
Listing Postback event handlers in MultiDoc Editor
def pageLink_Click sender, event self.currentPage sender.Text def editButton_Click sender, event self.editing True def cancelButton_Click sender, event self.editing False throw away any changes that have been made self.document getDocument def saveButton_Click sender, event saveDocument self.document self.editing False def pageTitleTextBox_TextChanged sender, event selectedPage getPage self.document, self.currentPage selectedPage.title self.currentPage pageTitleTextBox.Text def...
Regression tests
Unit tests are for testing components of your code, usually individual classes or functions. The elements under test should be testable in isolation from other parts this isn't always possible, but you have ways of handling these unavoidable dependencies within your tests. Dependencies that need to be managed include cases where your tests need to access external resources like databases or the filesystem. Functional tests are higher-level tests that drive your application from the outside....
Remove pages OK and Cancel dialog box
When the user asks to perform an irreversible action, such as removing a tab page, it's normal to ask for confirmation of the action. You're undoubtedly familiar with the standard Windows OK Cancel dialog box, which gives the user the choice of whether to continue with the action or to abort. This is actually our old friend the system message box. In case you've forgotten, the most useful overload of Show is as follows The two strings are the text and caption body and title of the message box....
A switch
Some situations that would require an if-elif-else construct or a dictionary lookup in Python can be done more cleanly in C using a switch statement. WeaponSelection weapon switch target.Type weapon WeaponSelection.FistsOfDoom break weapon WeaponSelection.Stomp break case TargetType.FluffyKitten case TargetType.FluffyBunny weapon WeaponSelection.MarshmallowCannon break case default weapon WeaponSelection.InconvenienceRay The case labels must be constants, and each case has to end with a...
Listing Trying to insert multiple people by constructing SQL strings
gt gt gt people 'James Nesbitt', Sydney 'Big Dawg' Colston, . . . 'Helena Bonham Carter' gt gt gt insert_statement insert into person name values ' s' gt gt gt for p in people . . . command.CommandText insert_statement p command.ExecuteNonQuery Traceback most recent call last File , line unknown, in Initialize 365 File Npgsql, line unknown, in ExecuteNonQuery File Npgsql, line unknown, in ExecuteCommand File Npgsql, line unknown, in CheckErrors EnvironmentError ERROR 42601 syntax error at or...
A Operator overloading
Operator overloading enables you to define how instances of your class should behave when they're used in expressions. For example, if you want to be able to add instances together, you can define operator public static operator Magnitude a, Magnitude b return Magnitude a.size b.size These operator overrides work in much the same way as the magic methods in Python such as _add__, _mul_, or _eq_ . Operator members must be declared as public static, and they can be for unary operators like as...
Providing modules and assemblies for the engine
Adding references to assemblies is done with the LoadAssembly method on the ScriptRuntime. This takes an actual assembly object, so we need to use the System. Reflection API to obtain it. We can use this to overcome another minor limitation when embedding IronPython. ipy.exe adds references to mscorlib.dll and System.dll the core assemblies containing the System namespace for us. This means that import System, or variants, can be executed without explicitly having to add references to these...
Functional testing Jpw
Functional tests, or acceptance tests, are high-level tests of an application from the outside. As much as possible, they should interact with the application in the same way the user does. Where unit tests test the components of your application, functional tests test the interaction of those components they'll often pick up on bugs or problems that unit tests miss. Functional tests can be more than just useful tests, though. In the Extreme Programming XP tradition you know a methodology has...
The SaveFileDialog
The SaveFileDialog presents the user with an explorer window so that a filename can be selected to save a file with. The dialog box is shown modally it blocks the application until the user has selected a file. To use this dialog box, you need to configure the filter, which determines which file types are shown in the explorer, and the title. You may also want to configure which directory the browser opens in and if any initial filename is to appear there. As with other controls you've used,...
Handling exceptions and the system message box
We've already covered handling exceptions in Python now you get a chance to use it. If saving a file fails, for whatever reason, you want to catch the exception and inform the user of the problem. This is a good example of where the creators of IronPython have done an excellent job of making the boundary between the .NET and the Python world seamless. The exception raised by .NET for this kind of error is an IOException. IronPython converts this into a Python exception. The corresponding Python...
Object introspection with dir and help
It's possible when programming to occasionally forget what properties and methods are available on an object. The interpreter is a great place to try things out, and two commands are particularly useful. dir object will give you a list of all the attributes available on an object. It returns a list of strings, so you can filter it or do anything else you might do with a list. The following code snippet looks for all the interfaces in the System.Collections namespace by building a list and then...
DataAdapters and DataSets
The data provider classes provide functionality that will enable you to do anything you might need to with your database. However, for some uses they are inconvenient. DataReaders provide a read-only, forward-only stream of data if you want to do complex processing that requires looking at data a number of times or navigating from parent records to child records, you'll need to perform multiple queries or store the information in some kind of data structure. While this data structure could be a...
doctest PyFIT
doctest is included in the Python standard library. Unfortunately it doesn't yet work with IronPython because sys.settrace isn't implemented. I Michael haven't tried the others with IronPython because unittest neatly fits the test-first pattern I prefer for development. It may be worth exploring some of these possibilities to see if you prefer them. 1 Also known as acceptance, integration, or black-box tests. 3 For a much more complete reference on a bewildering array of Python testing tools,...
Creating a REST web service
So far in the book we've concentrated on creating fairly self-contained applications most data storage has been in the form of text or XML files. For a lot of tasks this can be sufficient, but often the data your application will be manipulating lives somewhere else maybe in a relational database or behind a web service. One application I Christian worked on was part of a flight-planning system weather maps and forecasts that the application needed were managed by another system accessible...
Editing MultiDocs 1
Let's extend the Viewer into an application that will enable you to update the MultiDoc file, as well as looking at it. What do you need to add to the interface to support this The simplest way is to add an Edit button to the page display area on the right side of the page. When the users click the Edit button, the page title and page contents are swapped out with text boxes, allowing them to edit the values. The Edit button is replaced with a Cancel button and a Save button. Clicking either...
Listing Configuring the Button and CheckBox in the login panel
from System.Windows import Thickness, HorizontalAlignment from System.Windows.Controls import Button, StackPanel, CheckBox button Button button.Content ' Login ' button.FontSize 16 button.Margin Thickness 5, 5, 5, 5 stretch HorizontalAlignment.Stretch button.HorizontalAlignment stretch remember_me CheckBox lt - Create the CheckBox remember_me.IsChecked True lt -, remember_me .Margin Thickness 5, 5, 5, 5 I Check it remember_me.Content 'Remember' The textbox for the username is a straightforward...
The FormBorderStyle enumeration
So far, you've been configuring the humble label. The label has another property inherited from Control the BorderStyle. It isn't normal to configure a border on a label. It makes more sense to configure this on a Form, using the FormBorderStyle property instead. Unsurprisingly, BorderStyle and FormBorderStyle configure the style of border that Windows Forms draws controls with. You might want to change the border style on a panel containing a group of controls to make it stand out within a...
A Operators
There's a large overlap between the operators in Python and C . Table A.1 lists those that are different in C Table A.1 Differences between C and Python operators Table A.1 Differences between C and Python operators The equivalent of Python's not operator. Adds or subtracts 1 from a value. These are unusual from a Python perspective, because they both yield a value and mutate the operand, which can be confusing. Increment and decrement can be prefix or postfix if prefix, the increment decrement...
Writing a class library for IronPython 1
Writing code in C or VB.NET or Boo or F or any of the wealth of .NET languages that exist now and using it from IronPython is straightforward. Improving performance is not the only reason to use an alternative language in fact, my experience has been that IronPython is usually fast enough. It may be that you are writing a .NET class library and simply want to know how to make it as usable as possible from IronPython as well as other languages. Alternatively, you may be using C to access...
Listing Handlers for the document element
def onStartDocument self, lineNumber, attributes self.document Document self.fileName def onEndDocument self, lineNumber self.document.pages self.pages Both handles are simple. When you start reading the document or, encounter the document start tag , you create a new document with the right filename. By the time you encounter the document end tag, you should have read all the pages, and onEndDocument should attach the pages to the document. XmlDocumentReader can then complete and read return...
Get the length of the title
length WindowUtils.GetWindowTextLength hWnd sb StringBuilder length 1 WindowUtils .GetWindowText hWnd, sb, sb.Capacity lt 1- Finally get the title You can see from figure 14.4 that all this actually works This technique works fine where we can expose the functionality we need with a thin wrapper and then use it directly in Python. It doesn't work so well where we want IronPytfion 2.0 Beta 2.0.0.2000 on .NET 2.0.50727.1434 Copyright c Microsoft Corporation. AIL rights reserved, from...
Listing A thin wrapper that exports functions from Userdll in C
using System.Runtime.InteropServices public static extern bool IsWindowVisible IntPtr hWnd DllImport user32.dll public static extern IntPtr GetTopWindow IntPtr hWnd DllImport user32.dll public static extern IntPtr GetWindow IntPtr hWnd, uint wCmd DllImport user32.dll, SetLastError true, CharSet CharSet.Auto public static extern int GetWindowTextLength IntPtr hWnd DllImport user32.dll, SetLastError true, CharSet CharSet.Auto public static extern int GetWindowText IntPtr hWnd, Out StringBuilder...
XPS documents and flow content 1
XML Paper Specification XPS is a combination of a document markup language, which is a subset of XAML, and code support for viewing and printing documents. Although you won't read this in the Microsoft documentation, many see XPS as Microsoft's answer to Adobe's Portable Document Format PDF for creating print-ready documents. Fortunately, that debate is irrelevant to us because the classes that provide XPS support are a fantastic way of incorporating documents within WPF applications. One use...
Listing ShowDialog function displaying RenameTabDialog and returning result
dialog RenameTabDialog name, rename result dialog.ShowDialog dialog.Close return dialog. textBox. Text lt 1- Sets Return When ShowDialog is called, it displays the dialog. The elegant result can be seen in figure 6.4 note the padding around the buttons If the user selects OK or hits the Enter key , then the function returns the text from the text box otherwise, it returns None. Inspecting the controls after the dialog has returned is one way of retrieving the values the user has selected on the...
WebClient and changing data
Under the hood, WebClient caches requests for us. If we fetch the same URL later, even from a new instance, the same data will be returned instead of a new request being made. This is a problem if the data you want changes. In the Silverlight Twitter client we solved this by adding a digit to the end of the URL sent to the proxy. The digit is incremented with every request so that WebClient sees a different URL every time. Because we are putting the action, username, and password as parameters...
WPF in action 1
Although WPF doesn't have as many controls as Windows Forms, it includes standard controls such as check boxes, drop-down lists, and radio buttons. It also includes a range of new controls, both for advanced layout and entirely new user interface components. WPF also covers a wide range of areas beyond traditional user interfaces, including document support and 3D drawing. Even though it doesn't have all the controls that Windows Forms does, it still does an awful lot. It's extremely useful for...
Document observers 1
The model classes should remain loosely coupled to the view and controllers a substantial part of the Model-View-Controller pattern , so you can't give the document the responsibility for telling the tab controller to update the view. Now that OpenCommand can create new documents, we want the following to happen 1 OpenCommand to load and set the document on the main form 2 The save commands to update with the new document 3 The tab controller to update with the new document 4 The tab controller...
Higher order functions
Functions that take functions as arguments or return functions are called higher order functions. Functions that work with functions can be extremely useful. They allow you to separate out parts of a program more easily for example, a higher order function might provide a traversal of a data structure, where the function you pass in decides what to do for each item. This technique is highly reminiscent of the strategy pattern from Design Patterns Elements of Reusable Object-Oriented Software...
Calling unmanaged code with the Pinvoke attribute
The inability to use .NET attributes is an annoying hole in the IronPython .NET integration. Fortunately it is almost always easy to overcome by writing a small amount of C and either subclassing or wrapping from Python. One important attribute is DllImport,6 which is also known as P Invoke Platform Invoke , used for calling into unmanaged code.7 If you need to interact with native 6 This attribute is documented at dllimportattribute.aspx. 7 The FePy project does contain an experimental library...
A for loop
The C for loop has three parts in addition to the loop body An initialization clause, which sets up variables before the loop begins A condition that is tested before each execution of the loop body An iteration clause, which is executed after each execution of the loop body for int i 0 i lt 10 i total i After execution, total will have the value 45 the sum of 0 to 9 , because it stops when i equals 1. Each of the three control clauses is optional, and each clause can consist of multiple...
Listing The XML manifest file for an IronPython application
0 07 deployment 0 06 xaml lt Deployment.Parts gt lt -- Add additional assemblies here -- gt lt AssemblyPart Source Microsoft.Scripting. dll gt lt AssemblyPart gt lt AssemblyPart Source IronPython.dll gt lt AssemblyPart Source IronPython.Modules. dll gt lt AssemblyPart Source dll gt lt AssemblyPart Source gt lt Deployment.Parts gt lt Deployment gt Requiring XML manifest files may seem like unnecessary overhead for dynamic applications, but they serve a very serious purpose making Silverlight...
Protocols instead of interfaces 1
Interfaces are used in C to specify behavior of objects. For example, if a class implements the IDisposable interface, then you can provide a Dispose method to release resources used by your objects. .NET has a whole host of interfaces, and you can create new ones. If a class implements an interface, it provides a static target for the compiler to call whenever an operation provided by that interface is used in your code. NOTE C does have one example of duck typing enumeration with the...
Metaprogramming 1
Metaprogramming is the programming language or runtime assisting with the writing or modification of your program. The classic example is runtime code generation. In Python and IronPython, this is supported through the exec statement and built-in compile eval functions. Python source code is text, so generating code using string manipulation and then executing it is relatively easy. But, code generation has to be relatively deterministic your code that generates the strings is going to be...
A Using directive
In C code, you have access to any classes in the current assembly or referenced assemblies. Classes in the current namespace can be referred to directly. To refer to classes in other namespaces, you can use fully qualified class names in your code, but that's very verbose. The alternative is to add a using directive to the top of the file using EvilGenius.Minions Then occurrences of the unadorned class name GiantRobot in the code refer to EvilGenius.Minions.GiantRobot. In the case of a name...
Listing Methods to create menu strip and submenus
menuStrip MenuStrip lt - Main menu strip fileMenu self.createMenuItem 'iFile ' lt 1- Creates File menu saveKeys Keys.Control Keys.S saveMenuItem self.createMenuItem 'iSave ', handler lambda sender, event self.saveCommand.execute , keys saveKeys lt Creates Save menu item saveAsKeys Keys.Control Keys.Shift Keys.S saveAsMenuItem self.createMenuItem 'S amp ave As ', lambda sender, event self.saveAsCommand.execute , keys saveAsKeys lt Creates Save As menu item fileMenu.DropDownItems .Add...
The view layer creating a user interface
The specification says that the user edits documents using an interface with multiple tabs, one tab per page. The Windows Forms control for presenting a multitabbed interface is the TabControl, a container control. Individual pages within the Tab-Control are represented with TabPage controls. Let's create a form with a TabControl in it to establish the base of the view layer of the application you'll build on this as you add new features. The TabControl will form the main component in the...
M
OS X 87, 361 magenta 104 magic attributes 443 magic methods 49, 83, 184, 433 Mailman 21 main, unittest function 160 maintainablity 81 makedirs 28 makeSuite 164 managed code 6 Managed JScript 17, 331, 394 ManagedThreadId 350 ManagementClass 254 ManagementEventwatcher 251 ManagementObjectSearcher 251 ManagementQuery 251 ManagementScope 257 manual tests 157 ManualResetEvent 178 mapping 38 mapping protocol 82, 185, 435 Marc, the PowerShell Guy 267 Margin 222, 234, 336 Martelli, Alex 83, 173 mask...
A data model
To keep MultiDoc easy to maintain, you should define standard ways of accessing and changing the document. This will be useful for saving documents, loading new documents, switching between individual pages in the document, and so on. The documents in our example are intended to contain multiple pages a logical data model would be a document containing pages, with both the document and the pages represented in classes. Pages are stored sequentially, so it makes sense to make the document a...



