Python port from GSF to CSL contributed by Geertjan Wielenga and Ralph Benjamin Ruijs.
Imported code from https://github.com/GeertjanWielenga/Python4NetBeans/commit/4975789946aee1758476f53e99e04fca82d6ad6a
1.1 --- a/python.console/src/org/netbeans/modules/python/console/PythonConsoleAction.java Sun Jan 04 13:11:53 2015 -0600
1.2 +++ b/python.console/src/org/netbeans/modules/python/console/PythonConsoleAction.java Sun Feb 01 15:02:07 2015 -0800
1.3 @@ -1,7 +1,3 @@
1.4 -/*
1.5 - * To change this template, choose Tools | Templates
1.6 - * and open the template in the editor.
1.7 - */
1.8 package org.netbeans.modules.python.console;
1.9
1.10 import java.awt.event.ActionEvent;
2.1 --- a/python.core/src/org/netbeans/modules/python/api/PythonPlatformManager.java Sun Jan 04 13:11:53 2015 -0600
2.2 +++ b/python.core/src/org/netbeans/modules/python/api/PythonPlatformManager.java Sun Feb 01 15:02:07 2015 -0800
2.3 @@ -19,6 +19,7 @@
2.4 import java.util.List;
2.5 import java.util.Map;
2.6 import java.util.Properties;
2.7 +import java.util.concurrent.ExecutionException;
2.8 import java.util.concurrent.Future;
2.9 import java.util.logging.Level;
2.10 import java.util.logging.Logger;
2.11 @@ -67,7 +68,8 @@
2.12 private PythonPlatform getBundledPlatform() {
2.13 PythonPlatform platform = new PythonPlatform(PLATFORM_ID_DEFAULT);
2.14
2.15 - File jythonInstall = InstalledFileLocator.getDefault().locate("jython-2.5.1", "org.jython", false); // NOI18N
2.16 + File jythonInstall = new File("C:\\jython2.5.1"); // NOI18N
2.17 +// File jythonInstall = InstalledFileLocator.getDefault().locate("jython-2.5.1", "org.jython", false); // NOI18N
2.18 if (!jythonInstall.exists()) {
2.19 return null;
2.20 }
2.21 @@ -396,7 +398,11 @@
2.22 }catch(PythonException ex){
2.23 Exceptions.printStackTrace(ex);
2.24 throw ex;
2.25 - }catch(Exception ex){
2.26 + }catch(InterruptedException ex){
2.27 + Exceptions.printStackTrace(ex);
2.28 + } catch (ExecutionException ex) {
2.29 + Exceptions.printStackTrace(ex);
2.30 + } catch (IOException ex) {
2.31 Exceptions.printStackTrace(ex);
2.32 }
2.33 return platform;
3.1 --- a/python.debugger/nbproject/project.xml Sun Jan 04 13:11:53 2015 -0600
3.2 +++ b/python.debugger/nbproject/project.xml Sun Feb 01 15:02:07 2015 -0800
3.3 @@ -24,6 +24,14 @@
3.4 </run-dependency>
3.5 </dependency>
3.6 <dependency>
3.7 + <code-name-base>org.netbeans.modules.editor.document</code-name-base>
3.8 + <build-prerequisite/>
3.9 + <compile-dependency/>
3.10 + <run-dependency>
3.11 + <specification-version>1.3</specification-version>
3.12 + </run-dependency>
3.13 + </dependency>
3.14 + <dependency>
3.15 <code-name-base>org.netbeans.modules.editor.lib</code-name-base>
3.16 <build-prerequisite/>
3.17 <compile-dependency/>
3.18 @@ -140,14 +148,6 @@
3.19 </run-dependency>
3.20 </dependency>
3.21 <dependency>
3.22 - <code-name-base>org.openide.util.ui</code-name-base>
3.23 - <build-prerequisite/>
3.24 - <compile-dependency/>
3.25 - <run-dependency>
3.26 - <specification-version>9.3</specification-version>
3.27 - </run-dependency>
3.28 - </dependency>
3.29 - <dependency>
3.30 <code-name-base>org.openide.util</code-name-base>
3.31 <build-prerequisite/>
3.32 <compile-dependency/>
3.33 @@ -164,6 +164,14 @@
3.34 </run-dependency>
3.35 </dependency>
3.36 <dependency>
3.37 + <code-name-base>org.openide.util.ui</code-name-base>
3.38 + <build-prerequisite/>
3.39 + <compile-dependency/>
3.40 + <run-dependency>
3.41 + <specification-version>9.3</specification-version>
3.42 + </run-dependency>
3.43 + </dependency>
3.44 + <dependency>
3.45 <code-name-base>org.openide.windows</code-name-base>
3.46 <build-prerequisite/>
3.47 <compile-dependency/>
3.48 @@ -189,6 +197,8 @@
3.49 <public-packages>
3.50 <package>org.netbeans.modules.python.debugger</package>
3.51 <package>org.netbeans.modules.python.debugger.actions</package>
3.52 + <package>org.netbeans.modules.python.debugger.backend</package>
3.53 + <package>org.netbeans.modules.python.debugger.spi</package>
3.54 </public-packages>
3.55 </data>
3.56 </configuration>
4.1 --- a/python.debugger/src/org/netbeans/modules/python/debugger/gui/WatchPanel.java Sun Jan 04 13:11:53 2015 -0600
4.2 +++ b/python.debugger/src/org/netbeans/modules/python/debugger/gui/WatchPanel.java Sun Feb 01 15:02:07 2015 -0800
4.3 @@ -77,6 +77,7 @@
4.4 import java.io.IOException;
4.5 import javax.swing.text.StyledDocument;
4.6 import org.netbeans.editor.EditorUI;
4.7 +import org.netbeans.modules.python.api.PythonMIMEResolver;
4.8 import org.openide.ErrorManager;
4.9 import org.openide.cookies.EditorCookie;
4.10 import org.openide.text.NbDocument;
4.11 @@ -99,7 +100,7 @@
4.12 }
4.13
4.14 public static void setupContext(final JEditorPane editorPane, final ActionListener contextSetUp) {
4.15 - EditorKit kit = CloneableEditorSupport.getEditorKit("text/x-python");
4.16 + EditorKit kit = CloneableEditorSupport.getEditorKit(PythonMIMEResolver.PYTHON_MIME_TYPE);
4.17 editorPane.setEditorKit(kit);
4.18 DebuggerEngine en = DebuggerManager.getDebuggerManager ().getCurrentEngine();
4.19 if (EventQueue.isDispatchThread() && en != null) {
5.1 --- a/python.debugger/src/org/netbeans/modules/python/debugger/resources/python/nbpythondebug/jpydaemon.py Sun Jan 04 13:11:53 2015 -0600
5.2 +++ b/python.debugger/src/org/netbeans/modules/python/debugger/resources/python/nbpythondebug/jpydaemon.py Sun Feb 01 15:02:07 2015 -0800
5.3 @@ -1483,9 +1483,8 @@
5.4 self.cmd = FREEZE
5.5 elif ( string.upper(verb) == "BP-"):
5.6 self.cmd = CLEAR_BP
5.7 - file , optarg = _utils.nextArg(arg)
5.8 - line , optarg = _utils.nextArg(optarg)
5.9 - self.clear_break( file, int(line) )
5.10 + arg , optarg = _utils.nextArg(arg) # split BP arguments
5.11 + self.clear_break( arg , int(optarg) )
5.12 self.cmd = FREEZE
5.13 elif ( string.upper(verb) == "KILL"):
5.14 self.cmd = QUIT
6.1 --- a/python.editor/build-python.xml Sun Jan 04 13:11:53 2015 -0600
6.2 +++ b/python.editor/build-python.xml Sun Feb 01 15:02:07 2015 -0800
6.3 @@ -87,7 +87,8 @@
6.4 </subant>
6.5 </target>
6.6
6.7 - <target name="everything" depends="gsf,python"/>
6.8 +<!-- <target name="everything" depends="gsf,python"/>-->
6.9 + <target name="everything" depends="python"/>
6.10
6.11 <target name="clean">
6.12 <ant dir="${nbroot}/nbbuild" target="init"/>
7.1 --- a/python.editor/build.xml Sun Jan 04 13:11:53 2015 -0600
7.2 +++ b/python.editor/build.xml Sun Feb 01 15:02:07 2015 -0800
7.3 @@ -6,12 +6,12 @@
7.4 <description>Builds, tests, and runs the project org.netbeans.modules.python.editor.</description>
7.5 <import file="../../nbbuild/templates/projectized.xml"/>
7.6
7.7 - <target name="jar" depends="init,compile,jar-prep" unless="is.jar.uptodate">
7.8 +<!-- <target name="jar" depends="init,compile,jar-prep" unless="is.jar.uptodate">
7.9 <taskdef name="gsfjar" classname="org.netbeans.modules.gsf.GsfJar" classpath="${nb_all}/contrib/gsf.api/anttask/gsfanttask.jar:${nbantext.jar}"/>
7.10 <gsfjar jarfile="${cluster}/${module.jar}" compress="${build.package.compress}" index="${build.package.index}" manifest="${manifest.mf}" stamp="${cluster}/.lastModified">
7.11 <fileset dir="${build.classes.dir}"/>
7.12 </gsfjar>
7.13 - </target>
7.14 + </target>-->
7.15
7.16 <target name="files-init" depends="projectized-common.files-init">
7.17 <!-- Override module.files definition performed by parent, used for NBMs etc. -->
8.1 --- a/python.editor/nbproject/project.xml Sun Jan 04 13:11:53 2015 -0600
8.2 +++ b/python.editor/nbproject/project.xml Sun Feb 01 15:02:07 2015 -0800
8.3 @@ -15,6 +15,51 @@
8.4 </run-dependency>
8.5 </dependency>
8.6 <dependency>
8.7 + <code-name-base>org.netbeans.api.annotations.common</code-name-base>
8.8 + <build-prerequisite/>
8.9 + <compile-dependency/>
8.10 + <run-dependency>
8.11 + <release-version>1</release-version>
8.12 + <specification-version>1.25</specification-version>
8.13 + </run-dependency>
8.14 + </dependency>
8.15 + <dependency>
8.16 + <code-name-base>org.netbeans.api.java.classpath</code-name-base>
8.17 + <build-prerequisite/>
8.18 + <compile-dependency/>
8.19 + <run-dependency>
8.20 + <release-version>1</release-version>
8.21 + <specification-version>1.48</specification-version>
8.22 + </run-dependency>
8.23 + </dependency>
8.24 + <dependency>
8.25 + <code-name-base>org.netbeans.core.multiview</code-name-base>
8.26 + <build-prerequisite/>
8.27 + <compile-dependency/>
8.28 + <run-dependency>
8.29 + <release-version>1</release-version>
8.30 + <specification-version>1.42</specification-version>
8.31 + </run-dependency>
8.32 + </dependency>
8.33 + <dependency>
8.34 + <code-name-base>org.netbeans.modules.csl.api</code-name-base>
8.35 + <build-prerequisite/>
8.36 + <compile-dependency/>
8.37 + <run-dependency>
8.38 + <release-version>2</release-version>
8.39 + <specification-version>2.49</specification-version>
8.40 + </run-dependency>
8.41 + </dependency>
8.42 + <dependency>
8.43 + <code-name-base>org.netbeans.modules.editor.bracesmatching</code-name-base>
8.44 + <build-prerequisite/>
8.45 + <compile-dependency/>
8.46 + <run-dependency>
8.47 + <release-version>0</release-version>
8.48 + <specification-version>1.36</specification-version>
8.49 + </run-dependency>
8.50 + </dependency>
8.51 + <dependency>
8.52 <code-name-base>org.netbeans.modules.editor.codetemplates</code-name-base>
8.53 <build-prerequisite/>
8.54 <compile-dependency/>
8.55 @@ -33,6 +78,14 @@
8.56 </run-dependency>
8.57 </dependency>
8.58 <dependency>
8.59 + <code-name-base>org.netbeans.modules.editor.document</code-name-base>
8.60 + <build-prerequisite/>
8.61 + <compile-dependency/>
8.62 + <run-dependency>
8.63 + <specification-version>1.0</specification-version>
8.64 + </run-dependency>
8.65 + </dependency>
8.66 + <dependency>
8.67 <code-name-base>org.netbeans.modules.editor.indent</code-name-base>
8.68 <build-prerequisite/>
8.69 <compile-dependency/>
8.70 @@ -60,14 +113,6 @@
8.71 </run-dependency>
8.72 </dependency>
8.73 <dependency>
8.74 - <code-name-base>org.netbeans.modules.editor.document</code-name-base>
8.75 - <build-prerequisite/>
8.76 - <compile-dependency/>
8.77 - <run-dependency>
8.78 - <specification-version>1.0</specification-version>
8.79 - </run-dependency>
8.80 - </dependency>
8.81 - <dependency>
8.82 <code-name-base>org.netbeans.modules.editor.mimelookup</code-name-base>
8.83 <build-prerequisite/>
8.84 <compile-dependency/>
8.85 @@ -166,6 +211,23 @@
8.86 </run-dependency>
8.87 </dependency>
8.88 <dependency>
8.89 + <code-name-base>org.netbeans.modules.parsing.api</code-name-base>
8.90 + <build-prerequisite/>
8.91 + <compile-dependency/>
8.92 + <run-dependency>
8.93 + <release-version>1</release-version>
8.94 + <specification-version>9.3</specification-version>
8.95 + </run-dependency>
8.96 + </dependency>
8.97 + <dependency>
8.98 + <code-name-base>org.netbeans.modules.parsing.indexing</code-name-base>
8.99 + <build-prerequisite/>
8.100 + <compile-dependency/>
8.101 + <run-dependency>
8.102 + <specification-version>9.3</specification-version>
8.103 + </run-dependency>
8.104 + </dependency>
8.105 + <dependency>
8.106 <code-name-base>org.netbeans.modules.projectapi</code-name-base>
8.107 <build-prerequisite/>
8.108 <compile-dependency/>
8.109 @@ -201,6 +263,14 @@
8.110 </run-dependency>
8.111 </dependency>
8.112 <dependency>
8.113 + <code-name-base>org.netbeans.modules.python.source</code-name-base>
8.114 + <build-prerequisite/>
8.115 + <compile-dependency/>
8.116 + <run-dependency>
8.117 + <specification-version>1.0</specification-version>
8.118 + </run-dependency>
8.119 + </dependency>
8.120 + <dependency>
8.121 <code-name-base>org.netbeans.modules.queries</code-name-base>
8.122 <build-prerequisite/>
8.123 <compile-dependency/>
8.124 @@ -274,14 +344,6 @@
8.125 </run-dependency>
8.126 </dependency>
8.127 <dependency>
8.128 - <code-name-base>org.openide.util.ui</code-name-base>
8.129 - <build-prerequisite/>
8.130 - <compile-dependency/>
8.131 - <run-dependency>
8.132 - <specification-version>9.3</specification-version>
8.133 - </run-dependency>
8.134 - </dependency>
8.135 - <dependency>
8.136 <code-name-base>org.openide.util</code-name-base>
8.137 <build-prerequisite/>
8.138 <compile-dependency/>
8.139 @@ -298,6 +360,14 @@
8.140 </run-dependency>
8.141 </dependency>
8.142 <dependency>
8.143 + <code-name-base>org.openide.util.ui</code-name-base>
8.144 + <build-prerequisite/>
8.145 + <compile-dependency/>
8.146 + <run-dependency>
8.147 + <specification-version>9.3</specification-version>
8.148 + </run-dependency>
8.149 + </dependency>
8.150 + <dependency>
8.151 <code-name-base>org.openide.windows</code-name-base>
8.152 <build-prerequisite/>
8.153 <compile-dependency/>
8.154 @@ -306,64 +376,6 @@
8.155 </run-dependency>
8.156 </dependency>
8.157 </module-dependencies>
8.158 - <test-dependencies>
8.159 - <test-type>
8.160 - <name>unit</name>
8.161 - <test-dependency>
8.162 - <code-name-base>org.netbeans.libs.junit4</code-name-base>
8.163 - <compile-dependency/>
8.164 - </test-dependency>
8.165 - <test-dependency>
8.166 - <code-name-base>org.netbeans.modules.editor.lib</code-name-base>
8.167 - <compile-dependency/>
8.168 - </test-dependency>
8.169 - <test-dependency>
8.170 - <code-name-base>org.netbeans.modules.editor.mimelookup</code-name-base>
8.171 - <recursive/>
8.172 - <compile-dependency/>
8.173 - <test/>
8.174 - </test-dependency>
8.175 - <test-dependency>
8.176 - <code-name-base>org.netbeans.modules.editor.mimelookup.impl</code-name-base>
8.177 - </test-dependency>
8.178 - <test-dependency>
8.179 - <code-name-base>org.netbeans.modules.editor.util</code-name-base>
8.180 - <recursive/>
8.181 - <compile-dependency/>
8.182 - </test-dependency>
8.183 - <test-dependency>
8.184 - <code-name-base>org.netbeans.modules.gsf</code-name-base>
8.185 - <recursive/>
8.186 - <compile-dependency/>
8.187 - <test/>
8.188 - </test-dependency>
8.189 - <test-dependency>
8.190 - <code-name-base>org.netbeans.modules.lexer</code-name-base>
8.191 - <compile-dependency/>
8.192 - <test/>
8.193 - </test-dependency>
8.194 - <test-dependency>
8.195 - <code-name-base>org.netbeans.modules.masterfs</code-name-base>
8.196 - </test-dependency>
8.197 - <test-dependency>
8.198 - <code-name-base>org.netbeans.modules.nbjunit</code-name-base>
8.199 - <recursive/>
8.200 - <compile-dependency/>
8.201 - </test-dependency>
8.202 - <test-dependency>
8.203 - <code-name-base>org.netbeans.modules.python.editor</code-name-base>
8.204 - <recursive/>
8.205 - <compile-dependency/>
8.206 - </test-dependency>
8.207 - <test-dependency>
8.208 - <code-name-base>org.netbeans.modules.python.project</code-name-base>
8.209 - <compile-dependency/>
8.210 - </test-dependency>
8.211 - <test-dependency>
8.212 - <code-name-base>org.openide.util</code-name-base>
8.213 - </test-dependency>
8.214 - </test-type>
8.215 - </test-dependencies>
8.216 <friend-packages>
8.217 <friend>org.netbeans.modules.python.project</friend>
8.218 <friend>org.netbeans.modules.python.testrunner</friend>
9.1 --- a/python.editor/src/org/netbeans/modules/python/actions/RunPyAction.java Sun Jan 04 13:11:53 2015 -0600
9.2 +++ b/python.editor/src/org/netbeans/modules/python/actions/RunPyAction.java Sun Feb 01 15:02:07 2015 -0800
9.3 @@ -5,14 +5,12 @@
9.4 package org.netbeans.modules.python.actions;
9.5
9.6 import java.io.File;
9.7 -import java.util.Properties;
9.8 import org.netbeans.modules.python.api.PythonExecution;
9.9 -import org.netbeans.modules.python.api.PythonOptions;
9.10 import org.netbeans.modules.python.api.PythonPlatform;
9.11 import org.netbeans.modules.python.api.PythonPlatformManager;
9.12 -import org.netbeans.modules.python.editor.lexer.PythonTokenId;
9.13 import org.netbeans.api.project.Project;
9.14 import org.netbeans.api.project.ui.OpenProjects;
9.15 +import org.netbeans.modules.python.api.PythonMIMEResolver;
9.16 import org.openide.filesystems.FileObject;
9.17 import org.openide.filesystems.FileUtil;
9.18 import org.openide.loaders.DataObject;
9.19 @@ -25,7 +23,7 @@
9.20 protected void performAction(Node[] activatedNodes) {
9.21 //listProperties();
9.22 DataObject gdo = activatedNodes[0].getLookup().lookup(DataObject.class);
9.23 - if (gdo.getPrimaryFile().getMIMEType().equals(PythonTokenId.PYTHON_MIME_TYPE)) {
9.24 + if (gdo.getPrimaryFile().getMIMEType().equals(PythonMIMEResolver.PYTHON_MIME_TYPE)) {
9.25
9.26 String path = gdo.getPrimaryFile().getParent().getPath();
9.27 //int pos = path.lastIndexOf("/");
9.28 @@ -67,7 +65,7 @@
9.29 boolean results = false; //super.enable(activatedNodes);
9.30 if (activatedNodes.length > 0) {
9.31 DataObject gdo = activatedNodes[0].getLookup().lookup(DataObject.class);
9.32 - results = gdo.getPrimaryFile().getMIMEType().equals(PythonTokenId.PYTHON_MIME_TYPE);
9.33 + results = gdo.getPrimaryFile().getMIMEType().equals(PythonMIMEResolver.PYTHON_MIME_TYPE);
9.34 }
9.35 return results;
9.36 }
10.1 --- a/python.editor/src/org/netbeans/modules/python/editor/Bundle.properties Sun Jan 04 13:11:53 2015 -0600
10.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/Bundle.properties Sun Feb 01 15:02:07 2015 -0800
10.3 @@ -18,6 +18,8 @@
10.4 PythonLib=Python Library
10.5 In=in
10.6
10.7 +ChooseDecl=Go To Declaration
10.8 +
10.9 CTL_Hints_DisplayName=Hints
10.10 CTL_Hints_ToolTip=Hints And Warnings for Python Code
10.11 UnsafeIdentifierName=Only a-z, A-Z, digits and underscore are safe in Python names
11.1 --- a/python.editor/src/org/netbeans/modules/python/editor/DedentAction.java Sun Jan 04 13:11:53 2015 -0600
11.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/DedentAction.java Sun Feb 01 15:02:07 2015 -0800
11.3 @@ -48,8 +48,8 @@
11.4 import org.netbeans.editor.BaseDocument;
11.5 import org.netbeans.editor.Utilities;
11.6 import org.netbeans.lib.editor.util.swing.DocumentUtilities;
11.7 +import org.netbeans.modules.csl.spi.GsfUtilities;
11.8 import org.netbeans.modules.editor.indent.api.IndentUtils;
11.9 -import org.netbeans.modules.gsf.spi.GsfUtilities;
11.10 import org.openide.util.Exceptions;
11.11
11.12 /**
12.1 --- a/python.editor/src/org/netbeans/modules/python/editor/GoToSuperTypeAction.java Sun Jan 04 13:11:53 2015 -0600
12.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/GoToSuperTypeAction.java Sun Feb 01 15:02:07 2015 -0800
12.3 @@ -43,14 +43,27 @@
12.4 */
12.5 package org.netbeans.modules.python.editor;
12.6
12.7 +import java.awt.Component;
12.8 +import java.awt.Cursor;
12.9 +import java.awt.Image;
12.10 import java.awt.Point;
12.11 import java.awt.Rectangle;
12.12 import java.awt.Toolkit;
12.13 import java.awt.event.ActionEvent;
12.14 -import java.io.IOException;
12.15 +import java.awt.event.FocusEvent;
12.16 +import java.awt.event.FocusListener;
12.17 +import java.awt.event.KeyEvent;
12.18 +import java.awt.event.MouseEvent;
12.19 import java.util.ArrayList;
12.20 +import java.util.Collection;
12.21 import java.util.Collections;
12.22 import java.util.List;
12.23 +import javax.swing.DefaultListCellRenderer;
12.24 +import javax.swing.DefaultListModel;
12.25 +import javax.swing.ImageIcon;
12.26 +import javax.swing.JList;
12.27 +import javax.swing.JPanel;
12.28 +import javax.swing.ListModel;
12.29 import javax.swing.SwingUtilities;
12.30 import javax.swing.text.BadLocationException;
12.31 import javax.swing.text.Document;
12.32 @@ -58,19 +71,24 @@
12.33 import org.netbeans.api.editor.EditorRegistry;
12.34 import org.netbeans.editor.BaseAction;
12.35 import org.netbeans.editor.BaseDocument;
12.36 -import org.netbeans.modules.gsf.GsfHtmlFormatter;
12.37 -import org.netbeans.modules.gsf.api.CancellableTask;
12.38 -import org.netbeans.modules.gsf.api.CompilationInfo;
12.39 -import org.netbeans.modules.gsf.api.DeclarationFinder.AlternativeLocation;
12.40 -import org.netbeans.modules.gsf.api.DeclarationFinder.DeclarationLocation;
12.41 -import org.netbeans.modules.gsf.api.SourceModel;
12.42 -import org.netbeans.modules.gsf.api.SourceModelFactory;
12.43 -import org.netbeans.modules.gsf.spi.GsfUtilities;
12.44 -import org.netbeans.modules.gsfret.editor.hyperlink.DeclarationPopup;
12.45 -import org.netbeans.modules.gsfret.editor.hyperlink.GoToSupport;
12.46 -import org.netbeans.modules.gsfret.editor.hyperlink.PopupUtil;
12.47 +import org.netbeans.modules.csl.api.DeclarationFinder.AlternativeLocation;
12.48 +import org.netbeans.modules.csl.api.DeclarationFinder.DeclarationLocation;
12.49 +import org.netbeans.modules.csl.api.ElementHandle;
12.50 +import org.netbeans.modules.csl.api.ElementKind;
12.51 +import org.netbeans.modules.csl.api.HtmlFormatter;
12.52 +import org.netbeans.modules.csl.api.Modifier;
12.53 +import org.netbeans.modules.csl.api.UiUtils;
12.54 +import org.netbeans.modules.csl.spi.GsfUtilities;
12.55 +import org.netbeans.modules.parsing.api.ParserManager;
12.56 +import org.netbeans.modules.parsing.api.ResultIterator;
12.57 +import org.netbeans.modules.parsing.api.Source;
12.58 +import org.netbeans.modules.parsing.api.UserTask;
12.59 +import org.netbeans.modules.parsing.spi.ParseException;
12.60 +import org.netbeans.modules.python.editor.imports.PopupUtil;
12.61 +import org.openide.awt.StatusDisplayer;
12.62 import org.openide.filesystems.FileObject;
12.63 import org.openide.util.Exceptions;
12.64 +import org.openide.util.ImageUtilities;
12.65 import org.openide.util.NbBundle;
12.66
12.67 /**
12.68 @@ -109,21 +127,20 @@
12.69 // Move imports that I think may be unused to the end - or just comment them out?
12.70
12.71 // For imports: Gather imports from everywhere... move others into the same section
12.72 - CompilationInfo info = null;
12.73 + PythonParserResult info = null;
12.74
12.75 - SourceModel model = SourceModelFactory.getInstance().getModel(fo);
12.76 - if (model != null) {
12.77 - final CompilationInfo[] infoHolder = new CompilationInfo[1];
12.78 + Source source = Source.create(fo);
12.79 + if (source != null) {
12.80 + final PythonParserResult[] infoHolder = new PythonParserResult[1];
12.81 try {
12.82 - model.runUserActionTask(new CancellableTask<CompilationInfo>() {
12.83 - public void cancel() {
12.84 + ParserManager.parse(Collections.singleton(source), new UserTask() {
12.85 +
12.86 + @Override
12.87 + public void run(ResultIterator resultIterator) throws Exception {
12.88 + infoHolder[0] = (PythonParserResult) resultIterator.getParserResult();
12.89 }
12.90 -
12.91 - public void run(CompilationInfo info) throws Exception {
12.92 - infoHolder[0] = info;
12.93 - }
12.94 - }, false);
12.95 - } catch (IOException ex) {
12.96 + });
12.97 + } catch (ParseException ex) {
12.98 Exceptions.printStackTrace(ex);
12.99 }
12.100 info = infoHolder[0];
12.101 @@ -186,7 +203,7 @@
12.102 Point point = new Point(rectangle.x, rectangle.y + rectangle.height);
12.103 SwingUtilities.convertPointToScreen(point, target);
12.104
12.105 - String caption = NbBundle.getMessage(GoToSupport.class, "ChooseDecl");
12.106 + String caption = NbBundle.getMessage(GoToSuperTypeAction.class, "ChooseDecl");
12.107 PopupUtil.showPopup(new DeclarationPopup(caption, alternatives), caption, point.x, point.y, true, 0);
12.108
12.109 return true;
12.110 @@ -213,4 +230,439 @@
12.111
12.112 return null;
12.113 }
12.114 +
12.115 + /**
12.116 + * Copied from csl.api.core.
12.117 + */
12.118 + private static class GsfHtmlFormatter extends HtmlFormatter {
12.119 + protected boolean isDeprecated;
12.120 + protected boolean isParameter;
12.121 + protected boolean isType;
12.122 + protected boolean isName;
12.123 + protected boolean isEmphasis;
12.124 +
12.125 + protected StringBuilder sb = new StringBuilder();
12.126 +
12.127 + public GsfHtmlFormatter() {
12.128 + }
12.129 +
12.130 + public void reset() {
12.131 + textLength = 0;
12.132 + sb.setLength(0);
12.133 + }
12.134 +
12.135 + public void appendHtml(String html) {
12.136 + sb.append(html);
12.137 + // Not sure what to do about maxLength here... but presumably
12.138 + }
12.139 +
12.140 + public void appendText(String text, int fromInclusive, int toExclusive) {
12.141 + for (int i = fromInclusive; i < toExclusive; i++) {
12.142 + if (textLength >= maxLength) {
12.143 + if (textLength == maxLength) {
12.144 + sb.append("...");
12.145 + textLength += 3;
12.146 + }
12.147 + break;
12.148 + }
12.149 + char c = text.charAt(i);
12.150 +
12.151 + switch (c) {
12.152 + case '<':
12.153 + sb.append("<"); // NOI18N
12.154 +
12.155 + break;
12.156 +
12.157 + case '>': // Only ]]> is dangerous
12.158 + if ((i > 1) && (text.charAt(i - 2) == ']') && (text.charAt(i - 1) == ']')) {
12.159 + sb.append(">"); // NOI18N
12.160 + } else {
12.161 + sb.append(c);
12.162 + }
12.163 + break;
12.164 +
12.165 + case '&':
12.166 + sb.append("&"); // NOI18N
12.167 +
12.168 + break;
12.169 +
12.170 + default:
12.171 + sb.append(c);
12.172 + }
12.173 +
12.174 + textLength++;
12.175 + }
12.176 + }
12.177 +
12.178 + public void name(ElementKind kind, boolean start) {
12.179 + assert start != isName;
12.180 + isName = start;
12.181 +
12.182 + if (isName) {
12.183 + sb.append("<b>");
12.184 + } else {
12.185 + sb.append("</b>");
12.186 + }
12.187 + }
12.188 +
12.189 + public void parameters(boolean start) {
12.190 + assert start != isParameter;
12.191 + isParameter = start;
12.192 +
12.193 + if (isParameter) {
12.194 + sb.append("<font color=\"#808080\">");
12.195 + } else {
12.196 + sb.append("</font>");
12.197 + }
12.198 + }
12.199 +
12.200 + @Override
12.201 + public void active(boolean start) {
12.202 + emphasis(start);
12.203 + }
12.204 +
12.205 + public void type(boolean start) {
12.206 + assert start != isType;
12.207 + isType = start;
12.208 +
12.209 + if (isType) {
12.210 + sb.append("<font color=\"#808080\">");
12.211 + } else {
12.212 + sb.append("</font>");
12.213 + }
12.214 + }
12.215 +
12.216 + public void deprecated(boolean start) {
12.217 + assert start != isDeprecated;
12.218 + isDeprecated = start;
12.219 +
12.220 + if (isDeprecated) {
12.221 + sb.append("<s>");
12.222 + } else {
12.223 + sb.append("</s>");
12.224 + }
12.225 + }
12.226 +
12.227 + public String getText() {
12.228 + assert !isParameter && !isDeprecated && !isName && !isType;
12.229 +
12.230 + return sb.toString();
12.231 + }
12.232 +
12.233 + public void emphasis(boolean start) {
12.234 + assert start != isEmphasis;
12.235 + isEmphasis = start;
12.236 +
12.237 + if (isEmphasis) {
12.238 + sb.append("<b>");
12.239 + } else {
12.240 + sb.append("</b>");
12.241 + }
12.242 + }
12.243 + }
12.244 + private static class DeclarationPopup extends JPanel implements FocusListener {
12.245 +
12.246 + private String caption;
12.247 + private List<AlternativeLocation> declarations;
12.248 +
12.249 + /** Creates new form DeclarationPopup */
12.250 + public DeclarationPopup(String caption, List<AlternativeLocation> declarations) {
12.251 + this.caption = caption;
12.252 + this.declarations = declarations;
12.253 +
12.254 + initComponents();
12.255 +
12.256 + jList1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
12.257 +
12.258 + addFocusListener(this);
12.259 + }
12.260 +
12.261 + /** This method is called from within the constructor to
12.262 + * initialize the form.
12.263 + * WARNING: Do NOT modify this code. The content of this method is
12.264 + * always regenerated by the Form Editor.
12.265 + */
12.266 + // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
12.267 + private void initComponents() {
12.268 + java.awt.GridBagConstraints gridBagConstraints;
12.269 +
12.270 + jLabel1 = new javax.swing.JLabel();
12.271 + jScrollPane1 = new javax.swing.JScrollPane();
12.272 + jList1 = new javax.swing.JList();
12.273 +
12.274 + setFocusCycleRoot(true);
12.275 + setLayout(new java.awt.GridBagLayout());
12.276 +
12.277 + jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
12.278 + jLabel1.setText(caption
12.279 + );
12.280 + jLabel1.setFocusable(false);
12.281 + gridBagConstraints = new java.awt.GridBagConstraints();
12.282 + gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
12.283 + add(jLabel1, gridBagConstraints);
12.284 +
12.285 + jList1.setModel(createListModel());
12.286 + jList1.setCellRenderer(new RendererImpl());
12.287 + jList1.setSelectedIndex(0);
12.288 + jList1.setVisibleRowCount(declarations.size()
12.289 + );
12.290 + jList1.addKeyListener(new java.awt.event.KeyAdapter() {
12.291 + public void keyPressed(java.awt.event.KeyEvent evt) {
12.292 + jList1KeyPressed(evt);
12.293 + }
12.294 + });
12.295 + jList1.addMouseListener(new java.awt.event.MouseAdapter() {
12.296 + public void mouseClicked(java.awt.event.MouseEvent evt) {
12.297 + jList1MouseClicked(evt);
12.298 + }
12.299 + });
12.300 + jScrollPane1.setViewportView(jList1);
12.301 +
12.302 + gridBagConstraints = new java.awt.GridBagConstraints();
12.303 + gridBagConstraints.gridx = 0;
12.304 + gridBagConstraints.gridy = 1;
12.305 + gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
12.306 + gridBagConstraints.weightx = 1.0;
12.307 + gridBagConstraints.weighty = 1.0;
12.308 + add(jScrollPane1, gridBagConstraints);
12.309 + }// </editor-fold>
12.310 +
12.311 + private void jList1MouseClicked(java.awt.event.MouseEvent evt) {
12.312 + // TODO add your handling code here:
12.313 + if (evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() == 1) {
12.314 + openSelected();
12.315 + }
12.316 + }
12.317 +
12.318 + private void jList1KeyPressed(java.awt.event.KeyEvent evt) {
12.319 + // TODO add your handling code here:
12.320 + if (evt.getKeyCode() == KeyEvent.VK_ENTER && evt.getModifiers() == 0) {
12.321 + openSelected();
12.322 + }
12.323 + }
12.324 +
12.325 +
12.326 + // Variables declaration - do not modify
12.327 + private javax.swing.JLabel jLabel1;
12.328 + private javax.swing.JList jList1;
12.329 + private javax.swing.JScrollPane jScrollPane1;
12.330 + // End of variables declaration
12.331 +
12.332 + private void openSelected() {
12.333 + AlternativeLocation desc = (AlternativeLocation) jList1.getSelectedValue();
12.334 +
12.335 + if (desc != null) {
12.336 + DeclarationLocation location = desc.getLocation();
12.337 + if (location == DeclarationLocation.NONE) {
12.338 + StatusDisplayer.getDefault().setStatusText(NbBundle.getMessage(DeclarationPopup.class, "InvalidLoc"));
12.339 + Toolkit.getDefaultToolkit().beep();
12.340 + } else {
12.341 + String invalid = location.getInvalidMessage();
12.342 + if (invalid != null) {
12.343 + // TODO - show in the editor as an error instead?
12.344 + StatusDisplayer.getDefault().setStatusText(invalid);
12.345 + Toolkit.getDefaultToolkit().beep();
12.346 + } else {
12.347 + FileObject fileObject = location.getFileObject();
12.348 + if (fileObject != null) {
12.349 + UiUtils.open(fileObject,location.getOffset());
12.350 + } else {
12.351 + Toolkit.getDefaultToolkit().beep();
12.352 + }
12.353 + }
12.354 + }
12.355 + }
12.356 +
12.357 + PopupUtil.hidePopup();
12.358 + }
12.359 +
12.360 + private ListModel createListModel() {
12.361 + DefaultListModel dlm = new DefaultListModel();
12.362 +
12.363 + for (AlternativeLocation el: declarations) {
12.364 + dlm.addElement(el);
12.365 + }
12.366 +
12.367 + return dlm;
12.368 + }
12.369 +
12.370 + private static class RendererImpl extends DefaultListCellRenderer {
12.371 + @Override
12.372 + public Component getListCellRendererComponent(
12.373 + JList list,
12.374 + Object value,
12.375 + int index,
12.376 + boolean isSelected,
12.377 + boolean cellHasFocus) {
12.378 + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
12.379 +
12.380 + if (value instanceof AlternativeLocation) {
12.381 + AlternativeLocation desc = (AlternativeLocation) value;
12.382 + ElementHandle e = desc.getElement();
12.383 + ImageIcon icon = Icons.getElementIcon(e.getKind(), e.getModifiers());
12.384 + setIcon(icon);
12.385 +
12.386 + GsfHtmlFormatter formatter = new GsfHtmlFormatter();
12.387 + String s = desc.getDisplayHtml(formatter);
12.388 + setText("<html>"+s);
12.389 + }
12.390 +
12.391 + return c;
12.392 + }
12.393 + }
12.394 +
12.395 + public void focusGained(FocusEvent arg0) {
12.396 + jList1.requestFocus();
12.397 + jList1.requestFocusInWindow();
12.398 + }
12.399 +
12.400 + public void focusLost(FocusEvent arg0) {
12.401 + }
12.402 +
12.403 + }
12.404 + private static class Icons {
12.405 + private static final String ICON_BASE = "org/netbeans/modules/csl/source/resources/icons/";
12.406 + private static final String GIF_EXTENSION = ".gif";
12.407 + private static final String PNG_EXTENSION = ".png";
12.408 + private static final String WAIT = ICON_BASE + "wait" + PNG_EXTENSION;
12.409 + //private static final Map<String, Icon> icons = new HashMap<String, Icon>();
12.410 +
12.411 + /** Creates a new instance of Icons */
12.412 + private Icons() {
12.413 + }
12.414 +
12.415 + // public static Icon getBusyIcon() {
12.416 + // Image img = Utilities.loadImage(WAIT);
12.417 + //
12.418 + // if (img == null) {
12.419 + // return null;
12.420 + // } else {
12.421 + // return new ImageIcon(img);
12.422 + // }
12.423 + // }
12.424 + //
12.425 + // public static Icon getMethodIcon() {
12.426 + // // TODO - consider modifiers
12.427 + // Image img =
12.428 + // Utilities.loadImage(ICON_BASE + "method" + "Public" + PNG_EXTENSION);
12.429 + //
12.430 + // if (img == null) {
12.431 + // return null;
12.432 + // } else {
12.433 + // return new ImageIcon(img);
12.434 + // }
12.435 + // }
12.436 + //
12.437 + // public static Icon getFieldIcon() {
12.438 + // // TODO - consider modifiers
12.439 + // Image img =
12.440 + // Utilities.loadImage(ICON_BASE + "field" + "Public" + PNG_EXTENSION);
12.441 + //
12.442 + // if (img == null) {
12.443 + // return null;
12.444 + // } else {
12.445 + // return new ImageIcon(img);
12.446 + // }
12.447 + // }
12.448 + //
12.449 + // public static Icon getClassIcon() {
12.450 + // Image img = Utilities.loadImage(ICON_BASE + "class" + PNG_EXTENSION);
12.451 + //
12.452 + // if (img == null) {
12.453 + // return null;
12.454 + // } else {
12.455 + // return new ImageIcon(img);
12.456 + // }
12.457 + // }
12.458 + //
12.459 + // public static Icon getModuleIcon() {
12.460 + // Image img =
12.461 + // Utilities.loadImage(ICON_BASE + "package" + GIF_EXTENSION);
12.462 + //
12.463 + // if (img == null) {
12.464 + // return null;
12.465 + // } else {
12.466 + // return new ImageIcon(img);
12.467 + // }
12.468 + // }
12.469 +
12.470 + public static ImageIcon getElementIcon( ElementKind elementKind, Collection<Modifier> modifiers ) {
12.471 +
12.472 + if ( modifiers == null ) {
12.473 + modifiers = Collections.<Modifier>emptyList();
12.474 + }
12.475 +
12.476 + Image img = null;
12.477 +
12.478 + switch( elementKind ) {
12.479 + case FILE:
12.480 + img = ImageUtilities.loadImage( ICON_BASE + "emptyfile-icon" + PNG_EXTENSION );
12.481 + break;
12.482 + case ERROR:
12.483 + img = ImageUtilities.loadImage( ICON_BASE + "error-glyph" + GIF_EXTENSION );
12.484 + break;
12.485 + case PACKAGE:
12.486 + case MODULE:
12.487 + img = ImageUtilities.loadImage( ICON_BASE + "package" + GIF_EXTENSION );
12.488 + break;
12.489 + case TEST:
12.490 + img = ImageUtilities.loadImage( ICON_BASE + "test" + PNG_EXTENSION );
12.491 + break;
12.492 + case CLASS:
12.493 + case INTERFACE:
12.494 + img = ImageUtilities.loadImage( ICON_BASE + "class" + PNG_EXTENSION );
12.495 + break;
12.496 + case TAG:
12.497 + img = ImageUtilities.loadImage( ICON_BASE + "html_element" + PNG_EXTENSION );
12.498 + break;
12.499 + case RULE:
12.500 + img = ImageUtilities.loadImage( ICON_BASE + "rule" + PNG_EXTENSION );
12.501 + break;
12.502 + case VARIABLE:
12.503 + case PROPERTY:
12.504 + case GLOBAL:
12.505 + case ATTRIBUTE:
12.506 + case FIELD:
12.507 + img = ImageUtilities.loadImage( getIconName( ICON_BASE + "field", PNG_EXTENSION, modifiers ) );
12.508 + break;
12.509 + case PARAMETER:
12.510 + case CONSTANT:
12.511 + img = ImageUtilities.loadImage(ICON_BASE + "constant" + PNG_EXTENSION );
12.512 + break;
12.513 + case CONSTRUCTOR:
12.514 + img = ImageUtilities.loadImage( getIconName( ICON_BASE + "constructor", PNG_EXTENSION, modifiers ) );
12.515 + break;
12.516 + case METHOD:
12.517 + img = ImageUtilities.loadImage( getIconName( ICON_BASE + "method", PNG_EXTENSION, modifiers ) );
12.518 + break;
12.519 + case DB:
12.520 + img = ImageUtilities.loadImage(ICON_BASE + "database" + GIF_EXTENSION);
12.521 + break;
12.522 + default:
12.523 + img = null;
12.524 + }
12.525 +
12.526 + return img == null ? null : new ImageIcon (img);
12.527 + }
12.528 +
12.529 + // Private Methods ---------------------------------------------------------
12.530 + private static String getIconName(String typeName, String extension, Collection<Modifier> modifiers) {
12.531 +
12.532 + StringBuffer fileName = new StringBuffer( typeName );
12.533 +
12.534 + if (modifiers.contains(Modifier.STATIC)) {
12.535 + fileName.append( "Static" );
12.536 + }
12.537 + if (modifiers.contains(Modifier.PROTECTED)) {
12.538 + return fileName.append( "Protected" ).append( extension ).toString();
12.539 + }
12.540 + if (modifiers.contains(Modifier.PRIVATE)) {
12.541 + return fileName.append( "Private" ).append( extension ).toString();
12.542 + }
12.543 + // Assume it's public
12.544 + return fileName.append( "Public" ).append( extension ).toString();
12.545 + //return fileName.append( "Package" ).append( extension ).toString();
12.546 + //return fileName.append(extension).toString();
12.547 + }
12.548 + }
12.549 }
13.1 --- a/python.editor/src/org/netbeans/modules/python/editor/IndentAction.java Sun Jan 04 13:11:53 2015 -0600
13.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/IndentAction.java Sun Feb 01 15:02:07 2015 -0800
13.3 @@ -48,8 +48,8 @@
13.4 import org.netbeans.editor.BaseKit;
13.5 import org.netbeans.editor.Utilities;
13.6 import org.netbeans.lib.editor.util.swing.DocumentUtilities;
13.7 +import org.netbeans.modules.csl.spi.GsfUtilities;
13.8 import org.netbeans.modules.editor.indent.api.IndentUtils;
13.9 -import org.netbeans.modules.gsf.spi.GsfUtilities;
13.10 import org.openide.util.Exceptions;
13.11
13.12 /**
14.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonAstTreeNode.java Sun Jan 04 13:11:53 2015 -0600
14.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonAstTreeNode.java Sun Feb 01 15:02:07 2015 -0800
14.3 @@ -30,19 +30,17 @@
14.4 */
14.5 package org.netbeans.modules.python.editor;
14.6
14.7 -import java.io.CharConversionException;
14.8 -import java.util.ArrayList;
14.9 -import java.util.Collections;
14.10 -import java.util.Enumeration;
14.11 -import java.util.List;
14.12 -import javax.swing.tree.TreeNode;
14.13 -import org.netbeans.modules.gsf.api.ParserResult.AstTreeNode;
14.14 -import org.openide.util.Exceptions;
14.15 -import org.openide.xml.XMLUtil;
14.16 -import org.python.antlr.PythonTree;
14.17 -import org.python.antlr.Visitor;
14.18 -import org.python.antlr.ast.Name;
14.19 -
14.20 +//import java.io.CharConversionException;
14.21 +//import java.util.ArrayList;
14.22 +//import java.util.Collections;
14.23 +//import java.util.Enumeration;
14.24 +//import java.util.List;
14.25 +//import org.openide.util.Exceptions;
14.26 +//import org.openide.xml.XMLUtil;
14.27 +//import org.python.antlr.PythonTree;
14.28 +//import org.python.antlr.Visitor;
14.29 +//import org.python.antlr.ast.Name;
14.30 +/* Unused?
14.31 class PythonAstTreeNode implements AstTreeNode {
14.32 private List<PythonAstTreeNode> children;
14.33 private final PythonTree node;
14.34 @@ -179,3 +177,4 @@
14.35 return null;
14.36 }
14.37 }
14.38 +*/
14.39 \ No newline at end of file
15.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonAstUtils.java Sun Jan 04 13:11:53 2015 -0600
15.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonAstUtils.java Sun Feb 01 15:02:07 2015 -0800
15.3 @@ -30,7 +30,6 @@
15.4 */
15.5 package org.netbeans.modules.python.editor;
15.6
15.7 -import java.io.IOException;
15.8 import java.util.ArrayList;
15.9 import java.util.Collections;
15.10 import java.util.HashSet;
15.11 @@ -48,17 +47,19 @@
15.12 import org.netbeans.editor.BaseDocument;
15.13 import org.netbeans.editor.Finder;
15.14 import org.netbeans.editor.FinderFactory;
15.15 +import org.netbeans.modules.csl.api.ElementKind;
15.16 +import org.netbeans.modules.csl.api.OffsetRange;
15.17 +import org.netbeans.modules.csl.api.StructureItem;
15.18 +import org.netbeans.modules.csl.spi.GsfUtilities;
15.19 +import org.netbeans.modules.csl.spi.ParserResult;
15.20 +import org.netbeans.modules.parsing.api.ParserManager;
15.21 +import org.netbeans.modules.parsing.api.ResultIterator;
15.22 +import org.netbeans.modules.parsing.api.Source;
15.23 +import org.netbeans.modules.parsing.api.UserTask;
15.24 +import org.netbeans.modules.parsing.spi.ParseException;
15.25 import org.netbeans.modules.python.editor.elements.IndexedElement;
15.26 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
15.27 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
15.28 -import org.netbeans.modules.gsf.api.CancellableTask;
15.29 -import org.netbeans.modules.gsf.api.CompilationInfo;
15.30 -import org.netbeans.modules.gsf.api.ElementKind;
15.31 -import org.netbeans.modules.gsf.api.OffsetRange;
15.32 -import org.netbeans.modules.gsf.api.ParserResult;
15.33 -import org.netbeans.modules.gsf.api.SourceModel;
15.34 -import org.netbeans.modules.gsf.api.SourceModelFactory;
15.35 -import org.netbeans.modules.gsf.api.TranslatedSource;
15.36 import org.netbeans.modules.python.editor.lexer.PythonCommentTokenId;
15.37 import org.netbeans.modules.python.editor.scopes.ScopeInfo;
15.38 import org.netbeans.modules.python.editor.scopes.SymbolTable;
15.39 @@ -92,62 +93,38 @@
15.40 // This is just a utility class, no instances expected so private constructor
15.41 }
15.42
15.43 - public static int getAstOffset(CompilationInfo info, int lexOffset) {
15.44 - ParserResult result = info.getEmbeddedResult(PythonTokenId.PYTHON_MIME_TYPE, 0);
15.45 + public static int getAstOffset(ParserResult result, int lexOffset) {
15.46 if (result != null) {
15.47 - TranslatedSource ts = result.getTranslatedSource();
15.48 - if (ts != null) {
15.49 - return ts.getAstOffset(lexOffset);
15.50 - }
15.51 + return result.getSnapshot().getEmbeddedOffset(lexOffset);
15.52 }
15.53
15.54 return lexOffset;
15.55 }
15.56
15.57 - public static OffsetRange getAstOffsets(CompilationInfo info, OffsetRange lexicalRange) {
15.58 - ParserResult result = info.getEmbeddedResult(PythonTokenId.PYTHON_MIME_TYPE, 0);
15.59 + public static OffsetRange getAstOffsets(ParserResult result, OffsetRange lexicalRange) {
15.60 if (result != null) {
15.61 - TranslatedSource ts = result.getTranslatedSource();
15.62 - if (ts != null) {
15.63 - int rangeStart = lexicalRange.getStart();
15.64 - int start = ts.getAstOffset(rangeStart);
15.65 - if (start == rangeStart) {
15.66 - return lexicalRange;
15.67 - } else if (start == -1) {
15.68 - return OffsetRange.NONE;
15.69 - } else {
15.70 - // Assumes the translated range maintains size
15.71 - return new OffsetRange(start, start + lexicalRange.getLength());
15.72 - }
15.73 + int rangeStart = lexicalRange.getStart();
15.74 + int start = result.getSnapshot().getEmbeddedOffset(rangeStart);
15.75 + if (start == rangeStart) {
15.76 + return lexicalRange;
15.77 + } else if (start == -1) {
15.78 + return OffsetRange.NONE;
15.79 + } else {
15.80 + // Assumes the translated range maintains size
15.81 + return new OffsetRange(start, start + lexicalRange.getLength());
15.82 }
15.83 }
15.84 return lexicalRange;
15.85 }
15.86
15.87 - public static PythonTree getRoot(CompilationInfo info) {
15.88 - return getRoot(info, PythonTokenId.PYTHON_MIME_TYPE);
15.89 - }
15.90 -
15.91 - public static PythonParserResult getParseResult(CompilationInfo info) {
15.92 - ParserResult result = info.getEmbeddedResult(PythonTokenId.PYTHON_MIME_TYPE, 0);
15.93 -
15.94 - if (result == null) {
15.95 + public static PythonParserResult getParseResult(ParserResult result) {
15.96 + if(result == null || !(result instanceof PythonParserResult)) {
15.97 return null;
15.98 } else {
15.99 return ((PythonParserResult)result);
15.100 }
15.101 }
15.102
15.103 - public static PythonTree getRoot(CompilationInfo info, String mimeType) {
15.104 - ParserResult result = info.getEmbeddedResult(mimeType, 0);
15.105 -
15.106 - if (result == null) {
15.107 - return null;
15.108 - }
15.109 -
15.110 - return getRoot(result);
15.111 - }
15.112 -
15.113 public static PythonTree getRoot(ParserResult r) {
15.114 assert r instanceof PythonParserResult;
15.115
15.116 @@ -160,7 +137,7 @@
15.117 * Return a range that matches the given node's source buffer range
15.118 */
15.119 @SuppressWarnings("unchecked")
15.120 - public static OffsetRange getNameRange(CompilationInfo info, PythonTree node) {
15.121 + public static OffsetRange getNameRange(PythonParserResult info, PythonTree node) {
15.122 // final int type = node.getType();
15.123 // switch (type) {
15.124 // case Token.FUNCTION: {
15.125 @@ -218,7 +195,7 @@
15.126 // but if you have additional comments etc. that won't work right, so
15.127 // in this case, go and look at the actual document
15.128 if (info != null) {
15.129 - BaseDocument doc = (BaseDocument)info.getDocument();
15.130 + BaseDocument doc = GsfUtilities.getDocument(info.getSnapshot().getSource().getFileObject(), false);
15.131 if (doc != null) {
15.132 int lexOffset = PythonLexerUtils.getLexerOffset(info, defStart);
15.133 int limitOffset = PythonLexerUtils.getLexerOffset(info, def.getCharStopIndex());
15.134 @@ -592,36 +569,33 @@
15.135 return null;
15.136 }
15.137
15.138 - public static PythonTree getForeignNode(final IndexedElement o, CompilationInfo[] compilationInfoRet) {
15.139 + public static PythonTree getForeignNode(final IndexedElement o, PythonParserResult[] parserResultRet) {
15.140 FileObject fo = o.getFileObject();
15.141
15.142 if (fo == null) {
15.143 return null;
15.144 }
15.145 -
15.146 - SourceModel model = SourceModelFactory.getInstance().getModel(fo);
15.147 - if (model == null) {
15.148 +
15.149 + Source source = Source.create(fo);
15.150 + if(source == null) {
15.151 return null;
15.152 }
15.153 - final CompilationInfo[] infoHolder = new CompilationInfo[1];
15.154 + final PythonParserResult[] resultHolder = new PythonParserResult[1];
15.155 try {
15.156 - model.runUserActionTask(new CancellableTask<CompilationInfo>() {
15.157 - public void cancel() {
15.158 + ParserManager.parse(Collections.singleton(source), new UserTask() {
15.159 +
15.160 + @Override
15.161 + public void run(ResultIterator resultIterator) throws Exception {
15.162 + resultHolder[0] = (PythonParserResult) resultIterator.getParserResult();
15.163 }
15.164 -
15.165 - public void run(CompilationInfo info) throws Exception {
15.166 - infoHolder[0] = info;
15.167 - }
15.168 - //}, true);
15.169 - }, false); // XXX REMOVE THIS REMOVE THIS REMOVE THIS!
15.170 - } catch (IOException ex) {
15.171 + });
15.172 + } catch (ParseException ex) {
15.173 Exceptions.printStackTrace(ex);
15.174 - return null;
15.175 }
15.176
15.177 - CompilationInfo info = infoHolder[0];
15.178 - if (compilationInfoRet != null) {
15.179 - compilationInfoRet[0] = info;
15.180 + PythonParserResult info = resultHolder[0];
15.181 + if (parserResultRet != null) {
15.182 + parserResultRet[0] = info;
15.183 }
15.184 PythonParserResult result = getParseResult(info);
15.185 if (result == null) {
15.186 @@ -667,7 +641,7 @@
15.187 // }
15.188
15.189 ElementKind kind = o.getKind();
15.190 - List<PythonStructureItem> items = result.getStructure().getElements();
15.191 + List<PythonStructureItem> items = PythonStructureScanner.analyze(info).getElements();
15.192 if (items != null) {
15.193 return find(items, signature, kind);
15.194 } else {
15.195 @@ -675,21 +649,20 @@
15.196 }
15.197 }
15.198
15.199 - private static PythonTree find(List<PythonStructureItem> items, String signature, ElementKind kind) {
15.200 - for (PythonStructureItem item : items) {
15.201 + private static PythonTree find(List<? extends StructureItem> items, String signature, ElementKind kind) {
15.202 + for (StructureItem item : items) {
15.203 ElementKind childKind = item.getKind();
15.204 if (childKind == kind &&
15.205 - signature.equals(item.getSignature())) {
15.206 - return item.getNode();
15.207 + item instanceof PythonStructureItem &&
15.208 + signature.equals(((PythonStructureItem)item).getSignature())) {
15.209 + return ((PythonStructureItem)item).getNode();
15.210 }
15.211 - if (childKind == ElementKind.CLASS && signature.indexOf(item.getName()) != -1) {
15.212 + if (childKind == ElementKind.CLASS && signature.contains(item.getName())) {
15.213 @SuppressWarnings("unchecked")
15.214 - List<PythonStructureItem> children = (List<PythonStructureItem>)item.getNestedItems();
15.215 - if (children != null) {
15.216 - PythonTree result = find(children, signature, kind);
15.217 - if (result != null) {
15.218 - return result;
15.219 - }
15.220 + List<? extends StructureItem> children = item.getNestedItems();
15.221 + PythonTree result = find(children, signature, kind);
15.222 + if (result != null) {
15.223 + return result;
15.224 }
15.225 }
15.226 }
15.227 @@ -697,7 +670,7 @@
15.228 return null;
15.229 }
15.230
15.231 - public static Set<OffsetRange> getAllOffsets(CompilationInfo info, AstPath path, int lexOffset, String name, boolean abortOnFree) {
15.232 + public static Set<OffsetRange> getAllOffsets(PythonParserResult info, AstPath path, int lexOffset, String name, boolean abortOnFree) {
15.233 if (path == null) {
15.234 path = AstPath.get(PythonAstUtils.getRoot(info), lexOffset);
15.235 }
15.236 @@ -708,7 +681,7 @@
15.237 return null;
15.238 }
15.239 Set<OffsetRange> offsets = new HashSet<OffsetRange>();
15.240 - Document doc = info.getDocument();
15.241 + Document doc = GsfUtilities.getDocument(info.getSnapshot().getSource().getFileObject(), false);
15.242 if (doc == null) {
15.243 return Collections.emptySet();
15.244 }
15.245 @@ -787,7 +760,7 @@
15.246 }
15.247 }
15.248
15.249 - public static Set<OffsetRange> getLocalVarOffsets(CompilationInfo info, int lexOffset) {
15.250 + public static Set<OffsetRange> getLocalVarOffsets(PythonParserResult info, int lexOffset) {
15.251 int astOffset = getAstOffset(info, lexOffset);
15.252 if (astOffset != -1) {
15.253 PythonTree root = getRoot(info);
15.254 @@ -806,7 +779,7 @@
15.255 return Collections.emptySet();
15.256 }
15.257
15.258 - public static Set<OffsetRange> getLocalVarOffsets(CompilationInfo info, PythonTree scope, String name) {
15.259 + public static Set<OffsetRange> getLocalVarOffsets(PythonParserResult info, PythonTree scope, String name) {
15.260 LocalVarVisitor visitor = new LocalVarVisitor(info, name, false, true);
15.261 try {
15.262 visitor.visit(scope);
15.263 @@ -817,7 +790,7 @@
15.264 }
15.265 }
15.266
15.267 - public static List<Name> getLocalVarNodes(CompilationInfo info, PythonTree scope, String name) {
15.268 + public static List<Name> getLocalVarNodes(PythonParserResult info, PythonTree scope, String name) {
15.269 LocalVarVisitor visitor = new LocalVarVisitor(info, name, true, false);
15.270 try {
15.271 visitor.visit(scope);
15.272 @@ -828,7 +801,7 @@
15.273 }
15.274 }
15.275
15.276 - public static List<Name> getLocalVarAssignNodes(CompilationInfo info, PythonTree scope, String name) {
15.277 + public static List<Name> getLocalVarAssignNodes(PythonParserResult info, PythonTree scope, String name) {
15.278 LocalVarAssignVisitor visitor = new LocalVarAssignVisitor(info, name, true, false);
15.279 try {
15.280 visitor.visit(scope);
15.281 @@ -843,12 +816,12 @@
15.282 private List<Name> vars = new ArrayList<Name>();
15.283 private Set<OffsetRange> offsets = new HashSet<OffsetRange>();
15.284 private String name;
15.285 - private CompilationInfo info;
15.286 + private PythonParserResult info;
15.287 private boolean collectNames;
15.288 private boolean collectOffsets;
15.289 private PythonTree parent;
15.290
15.291 - private LocalVarVisitor(CompilationInfo info, String name, boolean collectNames, boolean collectOffsets) {
15.292 + private LocalVarVisitor(PythonParserResult info, String name, boolean collectNames, boolean collectOffsets) {
15.293 this.info = info;
15.294 this.name = name;
15.295 this.collectNames = collectNames;
15.296 @@ -899,12 +872,12 @@
15.297 private List<Name> vars = new ArrayList<Name>();
15.298 private Set<OffsetRange> offsets = new HashSet<OffsetRange>();
15.299 private String name;
15.300 - private CompilationInfo info;
15.301 + private PythonParserResult info;
15.302 private boolean collectNames;
15.303 private boolean collectOffsets;
15.304 private PythonTree parent;
15.305
15.306 - private LocalVarAssignVisitor(CompilationInfo info, String name, boolean collectNames, boolean collectOffsets) {
15.307 + private LocalVarAssignVisitor(PythonParserResult info, String name, boolean collectNames, boolean collectOffsets) {
15.308 this.info = info;
15.309 this.name = name;
15.310 this.collectNames = collectNames;
16.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
16.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonBracesMatcherFactory.java Sun Feb 01 15:02:07 2015 -0800
16.3 @@ -0,0 +1,52 @@
16.4 +/*
16.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
16.6 + *
16.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
16.8 + *
16.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
16.10 + * Other names may be trademarks of their respective owners.
16.11 + *
16.12 + * The contents of this file are subject to the terms of either the GNU
16.13 + * General Public License Version 2 only ("GPL") or the Common
16.14 + * Development and Distribution License("CDDL") (collectively, the
16.15 + * "License"). You may not use this file except in compliance with the
16.16 + * License. You can obtain a copy of the License at
16.17 + * http://www.netbeans.org/cddl-gplv2.html
16.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16.19 + * specific language governing permissions and limitations under the
16.20 + * License. When distributing the software, include this License Header
16.21 + * Notice in each file and include the License file at
16.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
16.23 + * particular file as subject to the "Classpath" exception as provided
16.24 + * by Oracle in the GPL Version 2 section of the License file that
16.25 + * accompanied this code. If applicable, add the following below the
16.26 + * License Header, with the fields enclosed by brackets [] replaced by
16.27 + * your own identifying information:
16.28 + * "Portions Copyrighted [year] [name of copyright owner]"
16.29 + *
16.30 + * Contributor(s):
16.31 + *
16.32 + * Portions Copyrighted 2007 Sun Microsystems, Inc.
16.33 + */
16.34 +package org.netbeans.modules.python.editor;
16.35 +
16.36 +import org.netbeans.api.editor.mimelookup.MimeRegistration;
16.37 +import org.netbeans.modules.python.api.PythonMIMEResolver;
16.38 +import org.netbeans.spi.editor.bracesmatching.BracesMatcher;
16.39 +import org.netbeans.spi.editor.bracesmatching.BracesMatcherFactory;
16.40 +import org.netbeans.spi.editor.bracesmatching.MatcherContext;
16.41 +import org.netbeans.spi.editor.bracesmatching.support.BracesMatcherSupport;
16.42 +
16.43 +/**
16.44 + *
16.45 + * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
16.46 + */
16.47 +@MimeRegistration(mimeType = PythonMIMEResolver.PYTHON_MIME_TYPE, service = BracesMatcherFactory.class)
16.48 +public class PythonBracesMatcherFactory implements BracesMatcherFactory {
16.49 +
16.50 + @Override
16.51 + public BracesMatcher createMatcher(MatcherContext mc) {
16.52 + return BracesMatcherSupport.defaultMatcher(mc, -1, -1);
16.53 + }
16.54 +
16.55 +}
17.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonCodeCompleter.java Sun Jan 04 13:11:53 2015 -0600
17.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonCodeCompleter.java Sun Feb 01 15:02:07 2015 -0800
17.3 @@ -45,7 +45,6 @@
17.4 import javax.swing.text.JTextComponent;
17.5 import org.netbeans.api.editor.EditorRegistry;
17.6 import org.netbeans.api.editor.completion.Completion;
17.7 -import org.netbeans.modules.gsf.api.Index;
17.8 import org.netbeans.modules.python.editor.elements.Element;
17.9 import org.netbeans.modules.python.editor.elements.IndexedElement;
17.10 import org.netbeans.modules.python.editor.elements.IndexedMethod;
17.11 @@ -58,23 +57,23 @@
17.12 import org.netbeans.api.lexer.TokenSequence;
17.13 import org.netbeans.editor.BaseDocument;
17.14 import org.netbeans.editor.Utilities;
17.15 +import org.netbeans.modules.csl.api.CodeCompletionContext;
17.16 +import org.netbeans.modules.csl.api.CodeCompletionHandler;
17.17 +import org.netbeans.modules.csl.api.CodeCompletionResult;
17.18 +import org.netbeans.modules.csl.api.CompletionProposal;
17.19 +import org.netbeans.modules.csl.api.ElementHandle;
17.20 +import org.netbeans.modules.csl.api.ElementKind;
17.21 +import org.netbeans.modules.csl.api.HtmlFormatter;
17.22 +import org.netbeans.modules.csl.api.Modifier;
17.23 +import org.netbeans.modules.csl.api.OffsetRange;
17.24 +import org.netbeans.modules.csl.api.ParameterInfo;
17.25 +import org.netbeans.modules.csl.spi.DefaultCompletionProposal;
17.26 +import org.netbeans.modules.csl.spi.DefaultCompletionResult;
17.27 +import org.netbeans.modules.csl.spi.GsfUtilities;
17.28 +import org.netbeans.modules.csl.spi.ParserResult;
17.29 import org.netbeans.modules.editor.indent.api.IndentUtils;
17.30 -import org.netbeans.modules.gsf.api.CodeCompletionContext;
17.31 -import org.netbeans.modules.gsf.api.CodeCompletionHandler;
17.32 -import org.netbeans.modules.gsf.api.CodeCompletionResult;
17.33 -import org.netbeans.modules.gsf.api.CompilationInfo;
17.34 -import org.netbeans.modules.gsf.api.CompletionProposal;
17.35 -import org.netbeans.modules.gsf.api.ElementHandle;
17.36 -import org.netbeans.modules.gsf.api.ElementKind;
17.37 -import org.netbeans.modules.gsf.api.HtmlFormatter;
17.38 -import org.netbeans.modules.gsf.api.Modifier;
17.39 -import org.netbeans.modules.gsf.api.NameKind;
17.40 -import org.netbeans.modules.gsf.api.OffsetRange;
17.41 -import org.netbeans.modules.gsf.api.ParameterInfo;
17.42 -import org.netbeans.modules.gsf.api.SourceModelFactory;
17.43 -import org.netbeans.modules.gsf.spi.DefaultCompletionProposal;
17.44 -import org.netbeans.modules.gsf.spi.DefaultCompletionResult;
17.45 -import org.netbeans.modules.gsf.spi.GsfUtilities;
17.46 +import org.netbeans.modules.parsing.spi.indexing.support.QuerySupport;
17.47 +import org.netbeans.modules.python.api.PythonMIMEResolver;
17.48 import org.netbeans.modules.python.editor.PythonParser.Sanitize;
17.49 import org.netbeans.modules.python.editor.elements.IndexedPackage;
17.50 import org.netbeans.modules.python.editor.imports.ImportManager;
17.51 @@ -83,7 +82,6 @@
17.52 import org.netbeans.modules.python.editor.options.CodeStyle;
17.53 import org.netbeans.modules.python.editor.scopes.SymbolTable;
17.54 import org.openide.filesystems.FileObject;
17.55 -import org.openide.filesystems.FileStateInvalidException;
17.56 import org.openide.util.Exceptions;
17.57 import org.openide.util.ImageUtilities;
17.58 import org.openide.util.NbBundle;
17.59 @@ -130,23 +128,13 @@
17.60 "\\xhh", "Character with hex value hh",};
17.61
17.62 public CodeCompletionResult complete(CodeCompletionContext context) {
17.63 - CompilationInfo info = context.getInfo();
17.64 + ParserResult result = context.getParserResult();
17.65 int lexOffset = context.getCaretOffset();
17.66 String prefix = context.getPrefix();
17.67 - NameKind kind = context.getNameKind();
17.68 QueryType queryType = context.getQueryType();
17.69 this.caseSensitive = context.isCaseSensitive();
17.70
17.71 - // Temporary: case insensitive matches don't work very well for JavaScript
17.72 - if (kind == NameKind.CASE_INSENSITIVE_PREFIX) {
17.73 - kind = NameKind.PREFIX;
17.74 - }
17.75 -
17.76 - if (prefix == null) {
17.77 - prefix = "";
17.78 - }
17.79 -
17.80 - final Document document = info.getDocument();
17.81 + final Document document = result.getSnapshot().getSource().getDocument(false);
17.82 if (document == null) {
17.83 return CodeCompletionResult.NONE;
17.84 }
17.85 @@ -155,16 +143,16 @@
17.86 List<CompletionProposal> proposals = new ArrayList<CompletionProposal>();
17.87 DefaultCompletionResult completionResult = new PythonCompletionResult(context, proposals);
17.88
17.89 - PythonParserResult parseResult = PythonAstUtils.getParseResult(info);
17.90 + PythonParserResult parseResult = PythonAstUtils.getParseResult(result);
17.91 doc.readLock(); // Read-lock due to Token hierarchy use
17.92 try {
17.93 PythonTree root = parseResult != null ? parseResult.getRoot() : null;
17.94 - final int astOffset = PythonAstUtils.getAstOffset(info, lexOffset);
17.95 + final int astOffset = PythonAstUtils.getAstOffset(result, lexOffset);
17.96 if (astOffset == -1) {
17.97 return CodeCompletionResult.NONE;
17.98 }
17.99 final TokenHierarchy<Document> th = TokenHierarchy.get(document);
17.100 - final FileObject fileObject = info.getFileObject();
17.101 + final FileObject fileObject = result.getSnapshot().getSource().getFileObject();
17.102 //Call call = Call.getCallType(doc, th, lexOffset);
17.103
17.104 // Carry completion context around since this logic is split across lots of methods
17.105 @@ -175,22 +163,19 @@
17.106 request.result = parseResult;
17.107 request.lexOffset = lexOffset;
17.108 request.astOffset = astOffset;
17.109 - request.index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE));
17.110 + request.index = PythonIndex.get(fileObject);
17.111 request.doc = doc;
17.112 - request.info = info;
17.113 + if(prefix == null) {
17.114 + prefix = "";
17.115 + }
17.116 request.prefix = prefix;
17.117 request.th = th;
17.118 - request.kind = kind;
17.119 + request.kind = context.isPrefixMatch()?QuerySupport.Kind.PREFIX:QuerySupport.Kind.EXACT;
17.120 request.queryType = queryType;
17.121 request.fileObject = fileObject;
17.122 - request.anchor = lexOffset - prefix.length();
17.123 + request.anchor = lexOffset - request.prefix.length();
17.124 //request.call = call;
17.125 -
17.126 - try {
17.127 - request.searchUrl = request.fileObject.getURL().toExternalForm();
17.128 - } catch (FileStateInvalidException ex) {
17.129 - Exceptions.printStackTrace(ex);
17.130 - }
17.131 + request.searchUrl = request.fileObject.toURL().toExternalForm();
17.132 if (request.searchUrl == null) {
17.133 request.searchUrl = "";
17.134 }
17.135 @@ -284,7 +269,7 @@
17.136 // function, so I have to account for that.
17.137 FunctionDef def = (FunctionDef)path.leaf();
17.138 OffsetRange astRange = PythonAstUtils.getRange(def);
17.139 - OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(info, astRange);
17.140 + OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(parseResult, astRange);
17.141 if (lexRange != OffsetRange.NONE) {
17.142 OffsetRange narrowed = PythonLexerUtils.narrow(doc, lexRange, true);
17.143 if (!narrowed.containsInclusive(lexOffset)) {
17.144 @@ -360,7 +345,7 @@
17.145 return completionResult;
17.146 }
17.147
17.148 - public String document(CompilationInfo info, ElementHandle element) {
17.149 + public String document(ParserResult info, ElementHandle element) {
17.150 if (element instanceof CommentElement) {
17.151 // Text is packaged as the name
17.152 String rst = element.getName();
17.153 @@ -405,75 +390,72 @@
17.154 if (last != null) {
17.155 FileObject fo = GsfUtilities.findFileObject(last);
17.156 if (fo != null) {
17.157 - Index gsfIndex = SourceModelFactory.getInstance().getIndex(fo, PythonTokenId.PYTHON_MIME_TYPE);
17.158 - if (gsfIndex != null) {
17.159 - PythonIndex index = PythonIndex.get(gsfIndex, fo);
17.160 - boolean isMember = link.startsWith("meth:") || link.startsWith("attr:");
17.161 - if (isMember || link.startsWith("func:") || link.startsWith("data:")) { // NOI18N
17.162 - String name = link.substring(link.indexOf(':') + 1);
17.163 - int paren = name.indexOf('(');
17.164 - if (paren != -1) {
17.165 - name = name.substring(0, paren);
17.166 + PythonIndex index = PythonIndex.get(fo);
17.167 + boolean isMember = link.startsWith("meth:") || link.startsWith("attr:");
17.168 + if (isMember || link.startsWith("func:") || link.startsWith("data:")) { // NOI18N
17.169 + String name = link.substring(link.indexOf(':') + 1);
17.170 + int paren = name.indexOf('(');
17.171 + if (paren != -1) {
17.172 + name = name.substring(0, paren);
17.173 + }
17.174 + int dot = name.indexOf('.');
17.175 + String cls = null;
17.176 + if (dot != -1) {
17.177 + cls = name.substring(0, dot);
17.178 + name = name.substring(dot + 1);
17.179 + }
17.180 + Set<IndexedElement> elements;
17.181 + if (isMember) {
17.182 + elements = index.getAllMembers(name, QuerySupport.Kind.EXACT, null, false);
17.183 + } else {
17.184 + elements = index.getAllElements(name, QuerySupport.Kind.EXACT, null, false);
17.185 + }
17.186 + if (elements.size() == 0) {
17.187 + if (isMember) {
17.188 + elements = index.getAllElements(name, QuerySupport.Kind.EXACT, null, false);
17.189 + } else {
17.190 + elements = index.getAllMembers(name, QuerySupport.Kind.EXACT, null, false);
17.191 }
17.192 - int dot = name.indexOf('.');
17.193 - String cls = null;
17.194 - if (dot != -1) {
17.195 - cls = name.substring(0, dot);
17.196 - name = name.substring(dot + 1);
17.197 - }
17.198 - Set<IndexedElement> elements;
17.199 - if (isMember) {
17.200 - elements = index.getAllMembers(name, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, null, false);
17.201 - } else {
17.202 - elements = index.getAllElements(name, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, null, false);
17.203 - }
17.204 - if (elements.size() == 0) {
17.205 - if (isMember) {
17.206 - elements = index.getAllElements(name, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, null, false);
17.207 - } else {
17.208 - elements = index.getAllMembers(name, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, null, false);
17.209 + }
17.210 + if (elements.size() > 0) {
17.211 + if (cls != null && cls.length() > 0) {
17.212 + for (IndexedElement element : elements) {
17.213 + if (element.getIn() != null && element.getIn().equals(cls)) {
17.214 + return element;
17.215 + }
17.216 }
17.217 }
17.218 - if (elements.size() > 0) {
17.219 - if (cls != null && cls.length() > 0) {
17.220 - for (IndexedElement element : elements) {
17.221 - if (element.getIn() != null && element.getIn().equals(cls)) {
17.222 - return element;
17.223 - }
17.224 + // Pick the same one as the original element, if any
17.225 + if (originalHandle instanceof IndexedElement) {
17.226 + String oldUrl = ((IndexedElement)originalHandle).getFilenameUrl();
17.227 + for (IndexedElement element : elements) {
17.228 + if (oldUrl.equals(element.getFilenameUrl())) {
17.229 + return element;
17.230 }
17.231 }
17.232 - // Pick the same one as the original element, if any
17.233 - if (originalHandle instanceof IndexedElement) {
17.234 - String oldUrl = ((IndexedElement)originalHandle).getFilenameUrl();
17.235 - for (IndexedElement element : elements) {
17.236 - if (oldUrl.equals(element.getFilenameUrl())) {
17.237 - return element;
17.238 - }
17.239 + }
17.240 + return elements.iterator().next();
17.241 + }
17.242 + } else if (link.startsWith("class:") || link.startsWith("exc:")) { // NOI18N
17.243 + String name = link.substring(link.indexOf(':') + 1);
17.244 + int paren = name.indexOf('(');
17.245 + if (paren != -1) {
17.246 + name = name.substring(0, paren);
17.247 + }
17.248 + Set<IndexedElement> classes = index.getClasses(name, QuerySupport.Kind.EXACT, null, false);
17.249 + if (classes.size() > 0) {
17.250 + // Pick the same one as the original element, if any
17.251 + if (originalHandle instanceof IndexedElement) {
17.252 + String oldUrl = ((IndexedElement)originalHandle).getFilenameUrl();
17.253 + for (IndexedElement cls : classes) {
17.254 + if (oldUrl.equals(cls.getFilenameUrl())) {
17.255 + return cls;
17.256 }
17.257 }
17.258 - return elements.iterator().next();
17.259 }
17.260 - } else if (link.startsWith("class:") || link.startsWith("exc:")) { // NOI18N
17.261 - String name = link.substring(link.indexOf(':') + 1);
17.262 - int paren = name.indexOf('(');
17.263 - if (paren != -1) {
17.264 - name = name.substring(0, paren);
17.265 - }
17.266 - Set<IndexedElement> classes = index.getClasses(name, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, null, false);
17.267 - if (classes.size() > 0) {
17.268 - // Pick the same one as the original element, if any
17.269 - if (originalHandle instanceof IndexedElement) {
17.270 - String oldUrl = ((IndexedElement)originalHandle).getFilenameUrl();
17.271 - for (IndexedElement cls : classes) {
17.272 - if (oldUrl.equals(cls.getFilenameUrl())) {
17.273 - return cls;
17.274 - }
17.275 - }
17.276 - }
17.277 - return classes.iterator().next();
17.278 - }
17.279 - } // TODO: Attributes
17.280 - }
17.281 + return classes.iterator().next();
17.282 + }
17.283 + } // TODO: Attributes
17.284 }
17.285 }
17.286
17.287 @@ -481,9 +463,9 @@
17.288 }
17.289
17.290 @SuppressWarnings("unchecked")
17.291 - public String getPrefix(CompilationInfo info, int lexOffset, boolean upToOffset) {
17.292 + public String getPrefix(ParserResult info, int lexOffset, boolean upToOffset) {
17.293 try {
17.294 - BaseDocument doc = (BaseDocument)info.getDocument();
17.295 + BaseDocument doc = (BaseDocument)info.getSnapshot().getSource().getDocument(false);
17.296 if (doc == null) {
17.297 return null;
17.298 }
17.299 @@ -585,7 +567,7 @@
17.300 return QueryType.NONE;
17.301 }
17.302
17.303 - public String resolveTemplateVariable(String variable, CompilationInfo info, int caretOffset, String name, Map parameters) {
17.304 + public String resolveTemplateVariable(String variable, ParserResult info, int caretOffset, String name, Map parameters) {
17.305 PythonParserResult parseResult = PythonAstUtils.getParseResult(info);
17.306 if (parseResult != null) {
17.307 // HACK: The caret offset we're passed in is bogus. It -isn't- the code template
17.308 @@ -604,7 +586,7 @@
17.309 }
17.310
17.311 if ("initialindent".equals(variable)) { // NOI18N
17.312 - Document doc = info.getDocument();
17.313 + Document doc = info.getSnapshot().getSource().getDocument(false);
17.314 try {
17.315 int lineStart = IndentUtils.lineStartOffset(doc, Math.min(caretOffset, doc.getLength()));
17.316 int initial = IndentUtils.lineIndent(doc, lineStart);
17.317 @@ -614,23 +596,25 @@
17.318 return null;
17.319 }
17.320 } else if ("indent".equals(variable)) { // NOI18N
17.321 - Document doc = info.getDocument();
17.322 + Document doc = info.getSnapshot().getSource().getDocument(false);
17.323 return IndentUtils.createIndentString(doc, IndentUtils.indentLevelSize(doc));
17.324 }
17.325 return null;
17.326 }
17.327
17.328 - public Set<String> getApplicableTemplates(CompilationInfo info, int selectionBegin, int selectionEnd) {
17.329 + @Override
17.330 + public Set<String> getApplicableTemplates(Document info, int selectionBegin, int selectionEnd) {
17.331 return Collections.emptySet();
17.332 }
17.333
17.334 - public ParameterInfo parameters(CompilationInfo info, int lexOffset,
17.335 + @Override
17.336 + public ParameterInfo parameters(ParserResult info, int lexOffset,
17.337 CompletionProposal proposal) {
17.338 IndexedMethod[] methodHolder = new IndexedMethod[1];
17.339 int[] paramIndexHolder = new int[1];
17.340 int[] anchorOffsetHolder = new int[1];
17.341 int astOffset = PythonAstUtils.getAstOffset(info, lexOffset);
17.342 - if (!computeMethodCall(info, lexOffset, astOffset,
17.343 + if (!computeMethodCall((PythonParserResult) info, lexOffset, astOffset,
17.344 methodHolder, paramIndexHolder, anchorOffsetHolder, null)) {
17.345
17.346 return ParameterInfo.NONE;
17.347 @@ -642,7 +626,7 @@
17.348 }
17.349 int index = paramIndexHolder[0];
17.350 int astAnchorOffset = anchorOffsetHolder[0];
17.351 - int anchorOffset = PythonLexerUtils.getLexerOffset(info, astAnchorOffset);
17.352 + int anchorOffset = PythonLexerUtils.getLexerOffset((PythonParserResult) info, astAnchorOffset);
17.353
17.354 // TODO: Make sure the caret offset is inside the arguments portion
17.355 // (parameter hints shouldn't work on the method call name itself
17.356 @@ -676,8 +660,7 @@
17.357 PythonIndex index = request.index;
17.358 String className = classDef.getInternalName();
17.359 String prefix = request.prefix;
17.360 - NameKind kind = request.kind;
17.361 - Set<IndexedElement> methods = index.getInheritedElements(className, prefix, kind);
17.362 + Set<IndexedElement> methods = index.getInheritedElements(className, prefix, request.kind);
17.363
17.364 String searchUrl = request.searchUrl;
17.365 for (IndexedElement element : methods) {
17.366 @@ -821,7 +804,7 @@
17.367
17.368 // User defined and library classes
17.369 PythonIndex index = request.index;
17.370 - Set<IndexedElement> elements = index.getClasses(prefix, request.kind, PythonIndex.ALL_SCOPE, request.result, false);
17.371 + Set<IndexedElement> elements = index.getClasses(prefix, request.kind, request.result, false);
17.372 for (IndexedElement element : elements) {
17.373 if (element.isNoDoc()) {
17.374 continue;
17.375 @@ -857,7 +840,7 @@
17.376
17.377 String prefix = request.prefix;
17.378 int lexOffset = request.lexOffset;
17.379 - NameKind kind = request.kind;
17.380 + QuerySupport.Kind kind = request.kind;
17.381
17.382 TokenSequence<? extends PythonTokenId> ts = PythonLexerUtils.getPositionedSequence(request.doc, lexOffset);
17.383 if (ts == null) {
17.384 @@ -907,7 +890,7 @@
17.385 } else {
17.386 prefix = library;
17.387 }
17.388 - if (kind == NameKind.PREFIX || kind == NameKind.CASE_INSENSITIVE_PREFIX) {
17.389 + if (kind == QuerySupport.Kind.PREFIX || kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX) {
17.390 anchor = libraryStart;
17.391 int length = lexOffset - libraryStart;
17.392 if (length >= 0 && length < prefix.length()) {
17.393 @@ -989,7 +972,7 @@
17.394 }
17.395 }
17.396 Set<IndexedElement> symbols = index.getImportedElements(prefix, request.kind,
17.397 - PythonIndex.ALL_SCOPE, Collections.<String>singleton(library), null);
17.398 + Collections.<String>singleton(library), null);
17.399 for (IndexedElement symbol : symbols) {
17.400 if (!symbol.isPublic()) {
17.401 continue;
17.402 @@ -1046,7 +1029,7 @@
17.403
17.404 return true;
17.405 } else if (id == PythonTokenId.RAISE || id == PythonTokenId.EXCEPT) {
17.406 - Set<IndexedElement> classes = index.getExceptions(prefix, kind, PythonIndex.ALL_SCOPE);
17.407 + Set<IndexedElement> classes = index.getExceptions(prefix, kind);
17.408 for (IndexedElement clz : classes) {
17.409 if (clz.isNoDoc()) {
17.410 continue;
17.411 @@ -1094,9 +1077,9 @@
17.412 }
17.413
17.414 private boolean completeLocal(List<CompletionProposal> proposals, CompletionRequest request) {
17.415 - CompilationInfo info = request.info;
17.416 + PythonParserResult info = request.result;
17.417 String prefix = request.prefix;
17.418 - NameKind kind = request.kind;
17.419 + QuerySupport.Kind kind = request.kind;
17.420 org.netbeans.modules.python.editor.lexer.Call call = request.call;
17.421
17.422 // Only call local and inherited methods if we don't have an LHS, such as Foo::
17.423 @@ -1205,7 +1188,7 @@
17.424 TokenHierarchy<Document> th = request.th;
17.425 BaseDocument doc = request.doc;
17.426 AstPath path = request.path;
17.427 - NameKind kind = request.kind;
17.428 + QuerySupport.Kind kind = request.kind;
17.429 FileObject fileObject = request.fileObject;
17.430 PythonTree node = request.node;
17.431
17.432 @@ -1242,7 +1225,7 @@
17.433 if (method != null) {
17.434 // TODO - if the lhs is "foo.bar." I need to split this
17.435 // up and do it a bit more cleverly
17.436 - PythonTypeAnalyzer analyzer = new PythonTypeAnalyzer(request.info, index, method, node, astOffset, lexOffset, fileObject);
17.437 + PythonTypeAnalyzer analyzer = new PythonTypeAnalyzer(request.result, index, method, node, astOffset, lexOffset, fileObject);
17.438 type = analyzer.getType(lhs);
17.439
17.440 if (type == null) {
17.441 @@ -1384,10 +1367,10 @@
17.442 moduleName = lhs;
17.443 }
17.444 if (moduleCompletion) {
17.445 - Set<IndexedElement> modules = index.getModules(moduleName, NameKind.EXACT_NAME);
17.446 + Set<IndexedElement> modules = index.getModules(moduleName, QuerySupport.Kind.EXACT);
17.447 if (modules.size() > 0) {
17.448 Set<IndexedElement> symbols = index.getImportedElements(prefix, request.kind,
17.449 - PythonIndex.ALL_SCOPE, Collections.<String>singleton(moduleName), null);
17.450 + Collections.<String>singleton(moduleName), null);
17.451 if (symbols.size() > 0) {
17.452 if (elements != null && elements.size() > 0) {
17.453 symbols.addAll(elements);
17.454 @@ -1426,7 +1409,7 @@
17.455 // Try just the method call (e.g. across all classes). This is ignoring the
17.456 // left hand side because we can't resolve it.
17.457 if ((elements.isEmpty())) {
17.458 - elements = index.getAllMembers(prefix, kind, PythonIndex.ALL_SCOPE, request.result, false);
17.459 + elements = index.getAllMembers(prefix, kind, request.result, false);
17.460
17.461 if (addSpecifyTypeItem) {
17.462 // Add a special code completion item to TELL us the type
17.463 @@ -1460,10 +1443,10 @@
17.464 private boolean completeClasses(List<CompletionProposal> proposals, CompletionRequest request) {
17.465 PythonIndex index = request.index;
17.466 String prefix = request.prefix;
17.467 - NameKind kind = request.kind;
17.468 + QuerySupport.Kind kind = request.kind;
17.469 String searchUrl = request.searchUrl;
17.470
17.471 - Set<IndexedElement> classes = index.getClasses(prefix, kind, PythonIndex.ALL_SCOPE, request.result, false);
17.472 + Set<IndexedElement> classes = index.getClasses(prefix, kind, request.result, false);
17.473 for (IndexedElement clz : classes) {
17.474 if (clz.isNoDoc()) {
17.475 continue;
17.476 @@ -1484,11 +1467,11 @@
17.477 private boolean completeMethods(List<CompletionProposal> proposals, CompletionRequest request) {
17.478 PythonIndex index = request.index;
17.479 String prefix = request.prefix;
17.480 - NameKind kind = request.kind;
17.481 + QuerySupport.Kind kind = request.kind;
17.482
17.483 - Set<IndexedElement> elements = index.getAllElements(prefix, kind, PythonIndex.ALL_SCOPE, request.result, false);
17.484 + Set<IndexedElement> elements = index.getAllElements(prefix, kind, request.result, false);
17.485 if (request.call.getLhs() != null || elements.size() == 0) {
17.486 - Set<IndexedElement> members = index.getAllMembers(prefix, kind, PythonIndex.ALL_SCOPE, request.result, false);
17.487 + Set<IndexedElement> members = index.getAllMembers(prefix, kind, request.result, false);
17.488 if (members.size() > 0) {
17.489 elements.addAll(members);
17.490 }
17.491 @@ -1514,10 +1497,10 @@
17.492 private boolean completeDecorators(List<CompletionProposal> proposals, CompletionRequest request) throws BadLocationException {
17.493 PythonIndex index = request.index;
17.494 String prefix = request.prefix;
17.495 - NameKind kind = request.kind;
17.496 + QuerySupport.Kind kind = request.kind;
17.497
17.498 boolean found = false;
17.499 - Set<IndexedElement> elements = index.getAllElements(prefix, kind, PythonIndex.ALL_SCOPE, request.result, false);
17.500 + Set<IndexedElement> elements = index.getAllElements(prefix, kind, request.result, false);
17.501 for (IndexedElement element : elements) {
17.502 if (element.isNoDoc()) {
17.503 continue;
17.504 @@ -1598,7 +1581,7 @@
17.505 Set<IndexedMethod>[] alternatesHolder = new Set[1];
17.506 int[] paramIndexHolder = new int[1];
17.507 int[] anchorOffsetHolder = new int[1];
17.508 - CompilationInfo info = request.info;
17.509 + PythonParserResult info = request.result;
17.510 int lexOffset = request.lexOffset;
17.511 int astOffset = request.astOffset;
17.512
17.513 @@ -1642,7 +1625,7 @@
17.514 * The argument index is returned in parameterIndexHolder[0] and the method being
17.515 * called in methodHolder[0].
17.516 */
17.517 - static boolean computeMethodCall(CompilationInfo info, int lexOffset, int astOffset,
17.518 + static boolean computeMethodCall(PythonParserResult info, int lexOffset, int astOffset,
17.519 IndexedMethod[] methodHolder, int[] parameterIndexHolder, int[] anchorOffsetHolder,
17.520 Set<IndexedMethod>[] alternativesHolder) {
17.521 try {
17.522 @@ -1662,7 +1645,7 @@
17.523 int originalAstOffset = astOffset;
17.524
17.525 // Adjust offset to the left
17.526 - BaseDocument doc = (BaseDocument)info.getDocument();
17.527 + BaseDocument doc = (BaseDocument) info.getSnapshot().getSource().getDocument(false);
17.528 if (doc == null) {
17.529 return false;
17.530 }
17.531 @@ -1778,7 +1761,7 @@
17.532 callMethod = null;
17.533 return false;
17.534 } else if (targetMethod == null) {
17.535 - targetMethod = new PythonDeclarationFinder().findMethodDeclaration(info, call, path,
17.536 + targetMethod = new PythonDeclarationFinder().findMethodDeclaration((PythonParserResult) info, call, path,
17.537 alternativesHolder);
17.538 if (targetMethod == null) {
17.539 return false;
17.540 @@ -1826,7 +1809,6 @@
17.541 private static class CompletionRequest {
17.542 private DefaultCompletionResult completionResult;
17.543 private TokenHierarchy<Document> th;
17.544 - private CompilationInfo info;
17.545 private AstPath path;
17.546 private PythonTree node;
17.547 private PythonTree root;
17.548 @@ -1836,7 +1818,7 @@
17.549 private BaseDocument doc;
17.550 private String prefix;
17.551 private PythonIndex index;
17.552 - private NameKind kind;
17.553 + private QuerySupport.Kind kind;
17.554 private PythonParserResult result;
17.555 private QueryType queryType;
17.556 private FileObject fileObject;
17.557 @@ -2280,6 +2262,11 @@
17.558 anchor = request.anchor;
17.559 }
17.560
17.561 + @Override
17.562 + public OffsetRange getOffsetRange(ParserResult pr) {
17.563 + return null;
17.564 + }
17.565 +
17.566 void setHandle(ElementHandle handle) {
17.567 this.handle = handle;
17.568 }
17.569 @@ -2376,7 +2363,7 @@
17.570 }
17.571
17.572 public String getMimeType() {
17.573 - return PythonTokenId.PYTHON_MIME_TYPE;
17.574 + return PythonMIMEResolver.PYTHON_MIME_TYPE;
17.575 }
17.576
17.577 public String getIn() {
17.578 @@ -2407,6 +2394,11 @@
17.579 this.lexOffset = lexOffset;
17.580 }
17.581
17.582 + @Override
17.583 + public OffsetRange getOffsetRange(ParserResult pr) {
17.584 + return null;
17.585 + }
17.586 +
17.587 public String getVariableName() {
17.588 return call.getLhs();
17.589 }
17.590 @@ -2471,7 +2463,7 @@
17.591 }
17.592
17.593 public String getMimeType() {
17.594 - return PythonTokenId.PYTHON_MIME_TYPE;
17.595 + return PythonMIMEResolver.PYTHON_MIME_TYPE;
17.596 }
17.597
17.598 public String getIn() {
17.599 @@ -2581,19 +2573,19 @@
17.600 boolean packageImport = !cs.preferSymbolImports();
17.601 // TODO - if you're already applying this import on a LHS for an imported
17.602 // symbol, handle that
17.603 - new ImportManager(context.getInfo()).ensureImported(module, symbol, packageImport, false, false);
17.604 + new ImportManager((PythonParserResult) context.getParserResult()).ensureImported(module, symbol, packageImport, false, false);
17.605
17.606 } else if (call == null || call.getLhs() == null) {
17.607 if (pythonItem.getElement() instanceof IndexedElement) {
17.608 CodeStyle cs = CodeStyle.getDefault(pythonItem.request.doc);
17.609
17.610 final IndexedElement elem = (IndexedElement)pythonItem.getElement();
17.611 - FileObject requestFile = context.getInfo().getFileObject();
17.612 + FileObject requestFile = context.getParserResult().getSnapshot().getSource().getFileObject();
17.613 FileObject elementFile = elem.getFileObject();
17.614 if (elementFile != requestFile) {
17.615 String module = elem.getModule();
17.616 if (requestFile != null) {
17.617 - String searchModule = PythonUtils.getModuleName(requestFile, null);
17.618 + String searchModule = PythonUtils.getModuleName(requestFile);
17.619 if (searchModule.equals(module)) {
17.620 return;
17.621 }
17.622 @@ -2603,7 +2595,7 @@
17.623 boolean packageImport = !cs.preferSymbolImports();
17.624 // TODO - if you're already applying this import on a LHS for an imported
17.625 // symbol, handle that
17.626 - new ImportManager(context.getInfo()).ensureImported(module, symbol, packageImport, false, false);
17.627 + new ImportManager((PythonParserResult) context.getParserResult()).ensureImported(module, symbol, packageImport, false, false);
17.628 }
17.629 }
17.630 }
18.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonDeclarationFinder.java Sun Jan 04 13:11:53 2015 -0600
18.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonDeclarationFinder.java Sun Feb 01 15:02:07 2015 -0800
18.3 @@ -38,8 +38,6 @@
18.4 import java.util.Set;
18.5 import javax.swing.text.BadLocationException;
18.6 import javax.swing.text.Document;
18.7 -import org.netbeans.modules.gsf.api.Index;
18.8 -import org.netbeans.modules.gsf.api.SourceModelFactory;
18.9 import org.netbeans.modules.python.editor.elements.IndexedElement;
18.10 import org.netbeans.modules.python.editor.elements.IndexedMethod;
18.11 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
18.12 @@ -51,12 +49,14 @@
18.13 import org.netbeans.api.lexer.TokenSequence;
18.14 import org.netbeans.editor.BaseDocument;
18.15 import org.netbeans.editor.Utilities;
18.16 -import org.netbeans.modules.gsf.api.CompilationInfo;
18.17 -import org.netbeans.modules.gsf.api.DeclarationFinder;
18.18 -import org.netbeans.modules.gsf.api.ElementHandle;
18.19 -import org.netbeans.modules.gsf.api.HtmlFormatter;
18.20 -import org.netbeans.modules.gsf.api.NameKind;
18.21 -import org.netbeans.modules.gsf.api.OffsetRange;
18.22 +import org.netbeans.modules.csl.api.DeclarationFinder;
18.23 +import org.netbeans.modules.csl.api.DeclarationFinder.AlternativeLocation;
18.24 +import org.netbeans.modules.csl.api.DeclarationFinder.DeclarationLocation;
18.25 +import org.netbeans.modules.csl.api.ElementHandle;
18.26 +import org.netbeans.modules.csl.api.HtmlFormatter;
18.27 +import org.netbeans.modules.csl.api.OffsetRange;
18.28 +import org.netbeans.modules.csl.spi.ParserResult;
18.29 +import org.netbeans.modules.parsing.spi.indexing.support.QuerySupport;
18.30 import org.netbeans.modules.python.editor.lexer.PythonLexer;
18.31 import org.netbeans.modules.python.editor.scopes.SymbolTable;
18.32 import org.netbeans.modules.python.editor.scopes.SymInfo;
18.33 @@ -157,7 +157,7 @@
18.34 return OffsetRange.NONE;
18.35 }
18.36
18.37 - private DeclarationLocation findImport(CompilationInfo info, int lexOffset, BaseDocument doc) {
18.38 + private DeclarationLocation findImport(PythonParserResult info, int lexOffset, BaseDocument doc) {
18.39 TokenSequence<? extends PythonTokenId> ts = PythonLexerUtils.getPositionedSequence(doc, lexOffset);
18.40 if (ts == null) {
18.41 return DeclarationLocation.NONE;
18.42 @@ -253,21 +253,21 @@
18.43 return DeclarationLocation.NONE;
18.44 }
18.45
18.46 - private DeclarationLocation findImport(CompilationInfo info, String moduleName, String symbol) {
18.47 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE));
18.48 + private DeclarationLocation findImport(PythonParserResult info, String moduleName, String symbol) {
18.49 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
18.50
18.51 Set<IndexedElement> elements = null;
18.52
18.53 if (moduleName != null && symbol != null) {
18.54 - elements = index.getImportedElements(symbol, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, Collections.<String>singleton(moduleName), null);
18.55 + elements = index.getImportedElements(symbol, QuerySupport.Kind.EXACT, Collections.<String>singleton(moduleName), null);
18.56 }
18.57
18.58 if (symbol != null && (elements == null || elements.size() == 0)) {
18.59 - elements = index.getInheritedElements(null, symbol, NameKind.EXACT_NAME);
18.60 + elements = index.getInheritedElements(null, symbol, QuerySupport.Kind.EXACT);
18.61 }
18.62
18.63 if (elements == null || elements.size() == 0) {
18.64 - elements = index.getModules(moduleName, NameKind.EXACT_NAME);
18.65 + elements = index.getModules(moduleName, QuerySupport.Kind.EXACT);
18.66 }
18.67
18.68 if (elements != null && elements.size() > 0) {
18.69 @@ -316,7 +316,7 @@
18.70 }
18.71
18.72 @SuppressWarnings("empty-statement")
18.73 - private DeclarationLocation findUrl(CompilationInfo info, Document doc, int lexOffset) {
18.74 + private DeclarationLocation findUrl(PythonParserResult info, Document doc, int lexOffset) {
18.75 TokenSequence<?> ts = PythonLexerUtils.getPythonSequence((BaseDocument)doc, lexOffset);
18.76
18.77 if (ts == null) {
18.78 @@ -367,9 +367,10 @@
18.79 return DeclarationLocation.NONE;
18.80 }
18.81
18.82 - public DeclarationLocation findDeclaration(CompilationInfo info, int lexOffset) {
18.83 + @Override
18.84 + public DeclarationLocation findDeclaration(ParserResult info, int lexOffset) {
18.85
18.86 - final Document document = info.getDocument();
18.87 + final Document document = info.getSnapshot().getSource().getDocument(false);
18.88 if (document == null) {
18.89 return DeclarationLocation.NONE;
18.90 }
18.91 @@ -393,12 +394,12 @@
18.92 }
18.93
18.94 // See if it's an import
18.95 - DeclarationLocation imp = findImport(info, lexOffset, doc);
18.96 + DeclarationLocation imp = findImport(parseResult, lexOffset, doc);
18.97 if (imp != DeclarationLocation.NONE) {
18.98 return imp;
18.99 }
18.100
18.101 - DeclarationLocation url = findUrl(info, doc, lexOffset);
18.102 + DeclarationLocation url = findUrl(parseResult, doc, lexOffset);
18.103 if (url != DeclarationLocation.NONE) {
18.104 return url;
18.105 }
18.106 @@ -406,6 +407,8 @@
18.107 final TokenHierarchy<Document> th = TokenHierarchy.get(document);
18.108 org.netbeans.modules.python.editor.lexer.Call call =
18.109 org.netbeans.modules.python.editor.lexer.Call.getCallType(doc, th, lexOffset);
18.110 +
18.111 + FileObject fileObject = info.getSnapshot().getSource().getFileObject();
18.112
18.113 // Search for local variables
18.114 if (root != null && call.getLhs() == null) {
18.115 @@ -418,13 +421,13 @@
18.116 SymInfo sym = symbolTable.findDeclaration(scope, name, true);
18.117 if (sym != null) {
18.118 if (sym.isFree()) {
18.119 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE));
18.120 + PythonIndex index = PythonIndex.get(fileObject);
18.121
18.122 List<Import> imports = symbolTable.getImports();
18.123 List<ImportFrom> importsFrom = symbolTable.getImportsFrom();
18.124 - Set<IndexedElement> elements = index.getImportedElements(name, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, imports, importsFrom);
18.125 + Set<IndexedElement> elements = index.getImportedElements(name, QuerySupport.Kind.EXACT, parseResult, imports, importsFrom);
18.126 if (elements != null && elements.size() > 0) {
18.127 - return getDeclaration(info, null /*name*/, elements,
18.128 + return getDeclaration(parseResult, null /*name*/, elements,
18.129 path, node, index, astOffset, lexOffset);
18.130 }
18.131 // Must be defined by one of the imported symbols
18.132 @@ -443,7 +446,7 @@
18.133 break;
18.134 } else if (at.getInternalName().equals(name)) {
18.135 // We found our library - just show it
18.136 - return findImport(info, name, null);
18.137 + return findImport(parseResult, name, null);
18.138 }
18.139 }
18.140 }
18.141 @@ -457,7 +460,7 @@
18.142 break;
18.143 } else if (at.getInternalName().equals(name)) {
18.144 // We found our library - just show it
18.145 - return findImport(info, impNode.getInternalModule(), name);
18.146 + return findImport(parseResult, impNode.getInternalModule(), name);
18.147 }
18.148 }
18.149 }
18.150 @@ -465,22 +468,22 @@
18.151 }
18.152
18.153 if (sym.isUnresolved()) {
18.154 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE));
18.155 + PythonIndex index = PythonIndex.get(fileObject);
18.156
18.157 List<Import> imports = symbolTable.getImports();
18.158 List<ImportFrom> importsFrom = symbolTable.getImportsFrom();
18.159 - Set<IndexedElement> elements = index.getImportedElements(name, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, imports, importsFrom);
18.160 + Set<IndexedElement> elements = index.getImportedElements(name, QuerySupport.Kind.EXACT, parseResult, imports, importsFrom);
18.161 if (elements != null && elements.size() > 0) {
18.162 - return getDeclaration(info, null /*name*/, elements,
18.163 + return getDeclaration(parseResult, null /*name*/, elements,
18.164 path, node, index, astOffset, lexOffset);
18.165 }
18.166 } else {
18.167 OffsetRange astRange = PythonAstUtils.getNameRange(null, declNode);
18.168 - int lexerOffset = PythonLexerUtils.getLexerOffset(info, astRange.getStart());
18.169 + int lexerOffset = PythonLexerUtils.getLexerOffset(parseResult, astRange.getStart());
18.170 if (lexerOffset == -1) {
18.171 lexerOffset = 0;
18.172 }
18.173 - return new DeclarationLocation(info.getFileObject(), lexerOffset);
18.174 + return new DeclarationLocation(fileObject, lexerOffset);
18.175 }
18.176 }
18.177 }
18.178 @@ -510,11 +513,11 @@
18.179 }
18.180
18.181 if (name != null) {
18.182 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE));
18.183 + PythonIndex index = PythonIndex.get(fileObject);
18.184 // Add methods in the class (without an FQN)
18.185 - Set<IndexedElement> elements = index.getInheritedElements(type, name, NameKind.EXACT_NAME);
18.186 + Set<IndexedElement> elements = index.getInheritedElements(type, name, QuerySupport.Kind.EXACT);
18.187 if (elements != null && elements.size() > 0) {
18.188 - return getDeclaration(info, null /*name*/, elements,
18.189 + return getDeclaration(parseResult, null /*name*/, elements,
18.190 path, node, index, astOffset, lexOffset);
18.191 }
18.192 }
18.193 @@ -530,32 +533,32 @@
18.194 }
18.195 }
18.196 if (prefix != null) {
18.197 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE));
18.198 + PythonIndex index = PythonIndex.get(fileObject);
18.199
18.200 Set<? extends IndexedElement> elements = null;
18.201 if (prefix.length() > 0 && Character.isUpperCase(prefix.charAt(0))) {
18.202 - elements = index.getClasses(prefix, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, parseResult, true);
18.203 + elements = index.getClasses(prefix, QuerySupport.Kind.EXACT, parseResult, true);
18.204 }
18.205
18.206 if (elements == null || elements.size() == 0) {
18.207 elements = index.getAllElements(prefix,
18.208 - NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, parseResult, true);
18.209 + QuerySupport.Kind.EXACT, parseResult, true);
18.210 }
18.211
18.212 if (elements == null || elements.size() == 0) {
18.213 elements = index.getAllMembers(prefix,
18.214 - NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, parseResult, true);
18.215 + QuerySupport.Kind.EXACT, parseResult, true);
18.216 }
18.217
18.218 if (elements != null && elements.size() > 0) {
18.219 - return getDeclaration(info, null /*name*/, elements,
18.220 + return getDeclaration(parseResult, null /*name*/, elements,
18.221 path, node, index, astOffset, lexOffset);
18.222 }
18.223
18.224 // TODO - classes
18.225 //WORKING HERE
18.226 // if (elements == null || elements.size() == 0) {
18.227 -// elements = index.getClasses(prefix, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, parseResult, true);
18.228 +// elements = index.getClasses(prefix, QuerySupport.Kind.EXACT, PythonIndex.ALL_SCOPE, parseResult, true);
18.229 // }
18.230 // if (elements != null && elements.size() > 0) {
18.231 // String name = null; // unused!
18.232 @@ -570,9 +573,9 @@
18.233 return DeclarationLocation.NONE;
18.234 }
18.235
18.236 - private DeclarationLocation getDeclaration(CompilationInfo info, String name, Set<? extends IndexedElement> methods,
18.237 + private DeclarationLocation getDeclaration(PythonParserResult info, String name, Set<? extends IndexedElement> methods,
18.238 AstPath path, PythonTree closest, PythonIndex index, int astOffset, int lexOffset) {
18.239 - BaseDocument doc = (BaseDocument)info.getDocument();
18.240 + BaseDocument doc = (BaseDocument)info.getSnapshot().getSource().getDocument(false);
18.241 if (doc == null) {
18.242 return DeclarationLocation.NONE;
18.243 }
18.244 @@ -584,8 +587,8 @@
18.245 return getDeclarationLocation(info, candidate, methods);
18.246 }
18.247
18.248 - private DeclarationLocation getDeclarationLocation(CompilationInfo info, IndexedElement candidate, Set<? extends IndexedElement> methods) {
18.249 - BaseDocument doc = (BaseDocument)info.getDocument();
18.250 + private DeclarationLocation getDeclarationLocation(PythonParserResult info, IndexedElement candidate, Set<? extends IndexedElement> methods) {
18.251 + BaseDocument doc = (BaseDocument)info.getSnapshot().getSource().getDocument(false);
18.252 if (doc == null) {
18.253 return DeclarationLocation.NONE;
18.254 }
18.255 @@ -632,7 +635,7 @@
18.256 return DeclarationLocation.NONE;
18.257 }
18.258
18.259 - private IndexedElement findBestMatch(CompilationInfo info, String name, Set<? extends IndexedElement> methodSet,
18.260 + private IndexedElement findBestMatch(PythonParserResult info, String name, Set<? extends IndexedElement> methodSet,
18.261 BaseDocument doc, int astOffset, int lexOffset, AstPath path, PythonTree call, PythonIndex index) {
18.262 // Make sure that the best fit method actually has a corresponding valid source location
18.263 // and parse tree
18.264 @@ -665,7 +668,7 @@
18.265 return null;
18.266 }
18.267
18.268 - private IndexedElement findBestMatchHelper(CompilationInfo info, String name, Set<IndexedElement> elements,
18.269 + private IndexedElement findBestMatchHelper(PythonParserResult info, String name, Set<IndexedElement> elements,
18.270 BaseDocument doc, int astOffset, int lexOffset, AstPath path, PythonTree callNode, PythonIndex index) {
18.271
18.272 Set<IndexedElement> candidates = new HashSet<IndexedElement>();
18.273 @@ -677,25 +680,21 @@
18.274 }
18.275
18.276 // 1. Prefer matches in the current file
18.277 - try {
18.278 - String searchUrl = info.getFileObject().getURL().toExternalForm();
18.279 - candidates = new HashSet<IndexedElement>();
18.280 + String searchUrl = info.getSnapshot().getSource().getFileObject().toURL().toExternalForm();
18.281 + candidates = new HashSet<IndexedElement>();
18.282
18.283 - for (IndexedElement element : elements) {
18.284 - String url = element.getFilenameUrl();
18.285 + for (IndexedElement element : elements) {
18.286 + String url = element.getFilenameUrl();
18.287
18.288 - if (url.equals(searchUrl)) {
18.289 - candidates.add(element);
18.290 - }
18.291 + if (url.equals(searchUrl)) {
18.292 + candidates.add(element);
18.293 }
18.294 + }
18.295
18.296 - if (candidates.size() == 1) {
18.297 - return candidates.iterator().next();
18.298 - } else if (!candidates.isEmpty()) {
18.299 - elements = candidates;
18.300 - }
18.301 - } catch (FileStateInvalidException ex) {
18.302 - Exceptions.printStackTrace(ex);
18.303 + if (candidates.size() == 1) {
18.304 + return candidates.iterator().next();
18.305 + } else if (!candidates.isEmpty()) {
18.306 + elements = candidates;
18.307 }
18.308
18.309
18.310 @@ -772,7 +771,7 @@
18.311 return elements.iterator().next();
18.312 }
18.313
18.314 - public DeclarationLocation getSuperImplementations(CompilationInfo info, int lexOffset) {
18.315 + public DeclarationLocation getSuperImplementations(PythonParserResult info, int lexOffset) {
18.316 // Figure out if we're on a method, and if so, locate the nearest
18.317 // method it is overriding.
18.318 // Otherwise, if we're on a class (anywhere, not just definition),
18.319 @@ -799,7 +798,7 @@
18.320 }
18.321
18.322 Set<IndexedElement> elements = null;
18.323 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE));
18.324 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
18.325 if (findClass) {
18.326 elements = index.getSuperClasses(name);
18.327 } else {
18.328 @@ -828,9 +827,9 @@
18.329 return DeclarationLocation.NONE;
18.330 }
18.331
18.332 - public IndexedMethod findMethodDeclaration(CompilationInfo info, org.python.antlr.ast.Call call, AstPath path, Set<IndexedMethod>[] alternativesHolder) {
18.333 + public IndexedMethod findMethodDeclaration(PythonParserResult info, org.python.antlr.ast.Call call, AstPath path, Set<IndexedMethod>[] alternativesHolder) {
18.334 PythonParserResult parseResult = PythonAstUtils.getParseResult(info);
18.335 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE));
18.336 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
18.337 Set<IndexedElement> functions = null;
18.338
18.339 // TODO - do more accurate lookup of types here!
18.340 @@ -844,9 +843,9 @@
18.341
18.342 if (call.getInternalFunc() instanceof Attribute) {
18.343 // Method/member access
18.344 - functions = index.getAllMembers(callName, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, parseResult, false);
18.345 + functions = index.getAllMembers(callName, QuerySupport.Kind.EXACT, parseResult, false);
18.346 } else {
18.347 - functions = index.getAllElements(callName, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, parseResult, false);
18.348 + functions = index.getAllElements(callName, QuerySupport.Kind.EXACT, parseResult, false);
18.349 }
18.350
18.351 if (functions != null && functions.size() > 0) {
18.352 @@ -860,7 +859,7 @@
18.353 int astOffset = call.getCharStartIndex();
18.354 int lexOffset = PythonLexerUtils.getLexerOffset(info, astOffset);
18.355 IndexedElement candidate =
18.356 - findBestMatch(info, callName, eligible, (BaseDocument)info.getDocument(),
18.357 + findBestMatch(info, callName, eligible, (BaseDocument)info.getSnapshot().getSource().getDocument(false),
18.358 astOffset, lexOffset, path, call, index);
18.359 assert candidate instanceof IndexedMethod; // Filtered into earlier already
18.360 return (IndexedMethod)candidate;
18.361 @@ -882,16 +881,11 @@
18.362 return DeclarationLocation.NONE;
18.363 }
18.364
18.365 - Index gsfIndex = SourceModelFactory.getInstance().getIndex(fileInProject, PythonTokenId.PYTHON_MIME_TYPE);
18.366 - if (gsfIndex == null) {
18.367 - return DeclarationLocation.NONE;
18.368 - }
18.369 -
18.370 String className = testString.substring(0, methodIndex);
18.371 String methodName = testString.substring(methodIndex+1);
18.372
18.373 - PythonIndex index = PythonIndex.get(gsfIndex, fileInProject);
18.374 - Set<IndexedElement> elements = index.getAllMembers(methodName, NameKind.EXACT_NAME, PythonIndex.SOURCE_SCOPE, null, true);
18.375 + PythonIndex index = PythonIndex.get(fileInProject);
18.376 + Set<IndexedElement> elements = index.getAllMembers(methodName, QuerySupport.Kind.EXACT, null, true);
18.377 // Look for one that matches our class name
18.378 if (elements.size() > 0) {
18.379 IndexedElement candidate = null;
19.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonFormatter.java Sun Jan 04 13:11:53 2015 -0600
19.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonFormatter.java Sun Feb 01 15:02:07 2015 -0800
19.3 @@ -58,15 +58,14 @@
19.4 import org.netbeans.api.lexer.TokenUtilities;
19.5 import org.netbeans.editor.BaseDocument;
19.6 import org.netbeans.editor.Utilities;
19.7 +import org.netbeans.modules.csl.api.EditList;
19.8 +import org.netbeans.modules.csl.api.Formatter;
19.9 +import org.netbeans.modules.csl.spi.GsfUtilities;
19.10 +import org.netbeans.modules.csl.spi.ParserResult;
19.11 import org.netbeans.modules.editor.indent.api.IndentUtils;
19.12 import org.netbeans.modules.editor.indent.spi.Context;
19.13 -import org.netbeans.modules.gsf.api.CompilationInfo;
19.14 -import org.netbeans.modules.gsf.api.EditList;
19.15 -import org.netbeans.modules.gsf.api.Formatter;
19.16 -import org.netbeans.modules.gsf.spi.GsfUtilities;
19.17 import org.netbeans.modules.python.editor.imports.ImportManager;
19.18 import org.netbeans.modules.python.editor.options.CodeStyle;
19.19 -import org.netbeans.napi.gsfret.source.SourceUtils;
19.20 import org.openide.util.Exceptions;
19.21
19.22 /**
19.23 @@ -98,7 +97,8 @@
19.24 this.codeStyle = codeStyle;
19.25 }
19.26
19.27 - public void reformat(Context context, CompilationInfo compilationInfo) {
19.28 + @Override
19.29 + public void reformat(Context context, ParserResult compilationInfo) {
19.30
19.31 // No AST pretty printing yet
19.32 // I should offer to go and do space insert/removal around commas, parentheses, etc.
19.33 @@ -107,10 +107,10 @@
19.34 int startOffset = context.startOffset();
19.35 int endOffset = context.endOffset();
19.36
19.37 - reformat(context, document, startOffset, endOffset, compilationInfo);
19.38 + reformat(context, document, startOffset, endOffset, (PythonParserResult) compilationInfo);
19.39 }
19.40
19.41 - public void reformat(final Context context, Document document, int startOffset, int endOffset, CompilationInfo info) {
19.42 + public void reformat(final Context context, Document document, int startOffset, int endOffset, PythonParserResult info) {
19.43 if (codeStyle == null) {
19.44 codeStyle = CodeStyle.getDefault(context.document());
19.45 }
19.46 @@ -127,9 +127,9 @@
19.47 }
19.48
19.49 public boolean needsParserResult() {
19.50 - if (SourceUtils.isScanInProgress()) {
19.51 - return false;
19.52 - }
19.53 +// if (SourceUtils.isScanInProgress()) {
19.54 +// return false;
19.55 +// }
19.56
19.57 // If we're going to format imports, then yes, we need the parser result
19.58 JTextComponent target = EditorRegistry.lastFocusedComponent();
19.59 @@ -425,7 +425,7 @@
19.60 return Utilities.getRowFirstNonWhite(doc, offset) == offset;
19.61 }
19.62
19.63 - private void cleanup(Document document, CompilationInfo info, int startOffset, int endOffset) {
19.64 + private void cleanup(Document document, PythonParserResult info, int startOffset, int endOffset) {
19.65 BaseDocument doc = (BaseDocument)document;
19.66 final EditList edits = new EditList(doc);
19.67 try {
20.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonHintOptions.java Sun Jan 04 13:11:53 2015 -0600
20.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonHintOptions.java Sun Feb 01 15:02:07 2015 -0800
20.3 @@ -30,9 +30,10 @@
20.4 */
20.5 package org.netbeans.modules.python.editor;
20.6
20.7 +import org.netbeans.modules.csl.api.HintsProvider;
20.8 +import org.netbeans.modules.csl.api.HintsProvider.HintsManager;
20.9 +import org.netbeans.modules.python.api.PythonMIMEResolver;
20.10 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
20.11 -import org.netbeans.modules.gsf.api.HintsProvider;
20.12 -import org.netbeans.modules.gsf.api.HintsProvider.HintsManager;
20.13 import org.netbeans.spi.options.AdvancedOption;
20.14 import org.netbeans.spi.options.OptionsPanelController;
20.15 import org.openide.util.NbBundle;
20.16 @@ -43,17 +44,20 @@
20.17 public class PythonHintOptions extends AdvancedOption {
20.18 OptionsPanelController panelController;
20.19
20.20 + @Override
20.21 public String getDisplayName() {
20.22 return NbBundle.getMessage(PythonHintOptions.class, "CTL_Hints_DisplayName"); // NOI18N
20.23 }
20.24
20.25 + @Override
20.26 public String getTooltip() {
20.27 return NbBundle.getMessage(PythonHintOptions.class, "CTL_Hints_ToolTip"); // NOI18N
20.28 }
20.29
20.30 + @Override
20.31 public synchronized OptionsPanelController create() {
20.32 if (panelController == null) {
20.33 - HintsManager manager = HintsProvider.Factory.getManager(PythonTokenId.PYTHON_MIME_TYPE);
20.34 + HintsManager manager = HintsProvider.HintsManager.getManagerForMimeType(PythonMIMEResolver.PYTHON_MIME_TYPE);
20.35 assert manager != null;
20.36 panelController = manager.getOptionsController();
20.37 }
21.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonIndex.java Sun Jan 04 13:11:53 2015 -0600
21.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonIndex.java Sun Feb 01 15:02:07 2015 -0800
21.3 @@ -36,6 +36,7 @@
21.4 import java.net.URL;
21.5 import java.util.ArrayList;
21.6 import java.util.Arrays;
21.7 +import java.util.Collection;
21.8 import java.util.Collections;
21.9 import java.util.EnumSet;
21.10 import java.util.HashMap;
21.11 @@ -44,12 +45,20 @@
21.12 import java.util.List;
21.13 import java.util.Map;
21.14 import java.util.Set;
21.15 +import java.util.WeakHashMap;
21.16 +import java.util.logging.Level;
21.17 +import java.util.logging.Logger;
21.18 +import org.netbeans.api.project.Project;
21.19 +import org.netbeans.modules.csl.api.ElementKind;
21.20 +import org.netbeans.modules.parsing.spi.indexing.PathRecognizer;
21.21 +import org.netbeans.modules.parsing.spi.indexing.support.IndexResult;
21.22 +import org.netbeans.modules.parsing.spi.indexing.support.QuerySupport;
21.23 +import static org.netbeans.modules.parsing.spi.indexing.support.QuerySupport.Kind.CAMEL_CASE;
21.24 +import static org.netbeans.modules.parsing.spi.indexing.support.QuerySupport.Kind.CASE_INSENSITIVE_PREFIX;
21.25 +import static org.netbeans.modules.parsing.spi.indexing.support.QuerySupport.Kind.CASE_INSENSITIVE_REGEXP;
21.26 +import static org.netbeans.modules.parsing.spi.indexing.support.QuerySupport.Kind.PREFIX;
21.27 +import static org.netbeans.modules.parsing.spi.indexing.support.QuerySupport.Kind.REGEXP;
21.28 import org.netbeans.modules.python.editor.elements.IndexedElement;
21.29 -import org.netbeans.modules.gsf.api.ElementKind;
21.30 -import org.netbeans.modules.gsf.api.Index;
21.31 -import org.netbeans.modules.gsf.api.Index.SearchResult;
21.32 -import org.netbeans.modules.gsf.api.Index.SearchScope;
21.33 -import org.netbeans.modules.gsf.api.NameKind;
21.34 import org.netbeans.modules.python.api.PythonPlatform;
21.35 import org.netbeans.modules.python.api.PythonPlatformManager;
21.36 import org.netbeans.modules.python.editor.elements.IndexedPackage;
21.37 @@ -59,6 +68,7 @@
21.38 import org.openide.filesystems.URLMapper;
21.39 import org.openide.modules.InstalledFileLocator;
21.40 import org.openide.util.Exceptions;
21.41 +import org.openide.util.Lookup;
21.42 import org.python.antlr.ast.Import;
21.43 import org.python.antlr.ast.ImportFrom;
21.44 import org.python.antlr.ast.alias;
21.45 @@ -69,19 +79,24 @@
21.46 * @author Tor Norbye
21.47 */
21.48 public class PythonIndex {
21.49 - public static final Set<SearchScope> ALL_SCOPE = EnumSet.allOf(SearchScope.class);
21.50 - public static final Set<SearchScope> SOURCE_SCOPE = EnumSet.of(SearchScope.SOURCE);
21.51 +// public static final Set<SearchScope> ALL_SCOPE = EnumSet.allOf(SearchScope.class);
21.52 +// public static final Set<SearchScope> SOURCE_SCOPE = EnumSet.of(SearchScope.SOURCE);
21.53 static final String CLUSTER_URL = "cluster:"; // NOI18N
21.54 static final String PYTHONHOME_URL = "python:"; // NOI18N
21.55 private static final String STUB_MISSING = "stub_missing"; // NOI18N
21.56 - private final Index index;
21.57 - private final FileObject context;
21.58
21.59 // The "functions" module is always imported by the interpreter, and ditto
21.60 // for exceptions, constants, etc.
21.61 public static Set<String> BUILTIN_MODULES = new HashSet<String>();
21.62
21.63
21.64 + private static final Logger LOG = Logger.getLogger(PythonIndex.class.getName());
21.65 + public static final String OBJECT = "object"; // NOI18N
21.66 + static Map<String, Set<String>> wildcardImports = new HashMap<String, Set<String>>();
21.67 + static Set<String> systemModules;
21.68 + // TODO - make weak?
21.69 + static Set<String> availableClasses;
21.70 + private static String clusterUrl = null;
21.71 static {
21.72 //BUILTIN_MODULES.add("objects"); // NOI18N -- just links to the others
21.73 BUILTIN_MODULES.add("stdtypes"); // NOI18N
21.74 @@ -91,25 +106,179 @@
21.75 BUILTIN_MODULES.add("constants"); // NOI18N
21.76 }
21.77
21.78 - /** Creates a new instance of PythonIndex */
21.79 - private PythonIndex(Index index, FileObject context) {
21.80 - this.index = index;
21.81 - this.context = context;
21.82 + public static PythonIndex get(Collection<FileObject> roots) {
21.83 + // XXX no cache - is it needed?
21.84 + LOG.log(Level.FINE, "PythonIndex for roots: {0}", roots); //NOI18N
21.85 + return new PythonIndex(QuerySupportFactory.get(roots), false);
21.86 + }
21.87 +
21.88 + public static PythonIndex get(Project project) {
21.89 + Set<String> sourceIds = new HashSet<String>();
21.90 + Set<String> libraryIds = new HashSet<String>();
21.91 + Collection<? extends PathRecognizer> lookupAll = Lookup.getDefault().lookupAll(PathRecognizer.class);
21.92 + for (PathRecognizer pathRecognizer : lookupAll) {
21.93 + Set<String> source = pathRecognizer.getSourcePathIds();
21.94 + if (source != null) {
21.95 + sourceIds.addAll(source);
21.96 + }
21.97 + Set<String> library = pathRecognizer.getLibraryPathIds();
21.98 + if (library != null) {
21.99 + libraryIds.addAll(library);
21.100 + }
21.101 + }
21.102 +
21.103 + final Collection<FileObject> findRoots = QuerySupport.findRoots(project,
21.104 + sourceIds,
21.105 + libraryIds,
21.106 + Collections.<String>emptySet());
21.107 + return PythonIndex.get(findRoots);
21.108 + }
21.109 +
21.110 + private static final WeakHashMap<FileObject, PythonIndex> INDEX_CACHE = new WeakHashMap<FileObject, PythonIndex>();
21.111 + public static PythonIndex get(FileObject fo) {
21.112 + PythonIndex index = INDEX_CACHE.get(fo);
21.113 + if (index == null) {
21.114 + LOG.log(Level.FINE, "Creating PythonIndex for FileObject: {0}", fo); //NOI18N
21.115 + index = new PythonIndex(QuerySupportFactory.get(fo), true);
21.116 + INDEX_CACHE.put(fo, index);
21.117 + }
21.118 + return index;
21.119 }
21.120
21.121 - public static PythonIndex get(Index index) {
21.122 - return new PythonIndex(index, null);
21.123 + public static boolean isBuiltinModule(String module) {
21.124 + return BUILTIN_MODULES.contains(module) || STUB_MISSING.equals(module);
21.125 }
21.126
21.127 - public static PythonIndex get(Index index, FileObject context) {
21.128 - return new PythonIndex(index, context);
21.129 + // For testing only
21.130 + public static void setClusterUrl(String url) {
21.131 + clusterUrl = url;
21.132 }
21.133
21.134 - private boolean search(String key, String name, NameKind kind, Set<SearchResult> result,
21.135 - Set<SearchScope> scope, Set<String> terms) {
21.136 + static String getPreindexUrl(String url) {
21.137 + // TODO - look up the correct platform to use!
21.138 + final PythonPlatformManager manager = PythonPlatformManager.getInstance();
21.139 + final String platformName = manager.getDefaultPlatform();
21.140 + PythonPlatform platform = manager.getPlatform(platformName);
21.141 + if (platform != null) {
21.142 + String s = platform.getHomeUrl();
21.143 + if (s != null) {
21.144 + if (url.startsWith(s)) {
21.145 + url = PYTHONHOME_URL + url.substring(s.length());
21.146 + return url;
21.147 + }
21.148 + }
21.149 + }
21.150 +
21.151 + String s = getClusterUrl();
21.152 +
21.153 + if (url.startsWith(s)) {
21.154 + return CLUSTER_URL + url.substring(s.length());
21.155 + }
21.156 +
21.157 + if (url.startsWith("jar:file:")) { // NOI18N
21.158 + String sub = url.substring(4);
21.159 + if (sub.startsWith(s)) {
21.160 + return CLUSTER_URL + sub.substring(s.length());
21.161 + }
21.162 + }
21.163 +
21.164 + return url;
21.165 + }
21.166 +
21.167 +/** Get the FileObject corresponding to a URL returned from the index */
21.168 + public static FileObject getFileObject(String url) {
21.169 + return getFileObject(url, null);
21.170 + }
21.171 +
21.172 + public static FileObject getFileObject(String url, FileObject context) {
21.173 try {
21.174 - index.search(key, name, kind, scope, result, terms);
21.175 + if (url.startsWith(PYTHONHOME_URL)) {
21.176 + Iterator<String> it = null;
21.177 +
21.178 + // TODO - look up the right platform for the given project
21.179 + //if (context != null) {
21.180 + // Project project = FileOwnerQuery.getOwner(context);
21.181 + // if (project != null) {
21.182 + // PythonPlatform platform = PythonPlatform.platformFor(project);
21.183 + // if (platform != null) {
21.184 + // it = Collections.singleton(platform).iterator();
21.185 + // }
21.186 + // }
21.187 + //}
21.188 +
21.189 + PythonPlatformManager manager = PythonPlatformManager.getInstance();
21.190 + if (it == null) {
21.191 + it = manager.getPlatformList().iterator();
21.192 + }
21.193 + while (it.hasNext()) {
21.194 + String name = it.next();
21.195 + PythonPlatform platform = manager.getPlatform(name);
21.196 + if (platform != null) {
21.197 + String u = platform.getHomeUrl();
21.198 + if (u != null) {
21.199 + try {
21.200 + u = u + url.substring(PYTHONHOME_URL.length());
21.201 + FileObject fo = URLMapper.findFileObject(new URL(u));
21.202 + if (fo != null) {
21.203 + return fo;
21.204 + }
21.205 + } catch (MalformedURLException mue) {
21.206 + Exceptions.printStackTrace(mue);
21.207 + }
21.208 + }
21.209 + }
21.210 + }
21.211 +
21.212 + return null;
21.213 + } else if (url.startsWith(CLUSTER_URL)) {
21.214 + url = getClusterUrl() + url.substring(CLUSTER_URL.length()); // NOI18N
21.215 + if (url.indexOf(".egg!/") != -1) { // NOI18N
21.216 + url = "jar:" + url; // NOI18N
21.217 + }
21.218 + }
21.219 +
21.220 + return URLMapper.findFileObject(new URL(url));
21.221 + } catch (IOException ex) {
21.222 + Exceptions.printStackTrace(ex);
21.223 + }
21.224 +
21.225 + return null;
21.226 + }
21.227 +
21.228 + static String getClusterUrl() {
21.229 + if (clusterUrl == null) {
21.230 + File f =
21.231 + InstalledFileLocator.getDefault().locate("modules/org-netbeans-modules-python-editor.jar", null, false); // NOI18N
21.232 +
21.233 + if (f == null) {
21.234 + throw new RuntimeException("Can't find cluster");
21.235 + }
21.236 +
21.237 + f = new File(f.getParentFile().getParentFile().getAbsolutePath());
21.238 +
21.239 + try {
21.240 + f = f.getCanonicalFile();
21.241 + clusterUrl = f.toURI().toURL().toExternalForm();
21.242 + } catch (IOException ioe) {
21.243 + Exceptions.printStackTrace(ioe);
21.244 + }
21.245 + }
21.246
21.247 + return clusterUrl;
21.248 + }
21.249 +
21.250 + private final QuerySupport index;
21.251 + private final boolean updateCache;
21.252 +
21.253 + /** Creates a new instance of PythonIndex */
21.254 + private PythonIndex(QuerySupport index, boolean updateCache) {
21.255 + this.index = index;
21.256 + this.updateCache = updateCache;
21.257 + }
21.258 +
21.259 + private boolean search(String fieldName, String fieldValue, QuerySupport.Kind kind, Set<? super IndexResult> result, final String... fieldsToLoad) {
21.260 + try {
21.261 + result.addAll(index.query(fieldName, fieldValue, kind, fieldsToLoad));
21.262 return true;
21.263 } catch (IOException ioe) {
21.264 Exceptions.printStackTrace(ioe);
21.265 @@ -120,8 +289,8 @@
21.266 }
21.267 }
21.268
21.269 - public Set<IndexedElement> getModules(String name, final NameKind kind) {
21.270 - final Set<SearchResult> result = new HashSet<SearchResult>();
21.271 + public Set<IndexedElement> getModules(String name, final QuerySupport.Kind kind) {
21.272 + final Set<IndexResult> result = new HashSet<IndexResult>();
21.273
21.274 // if (!isValid()) {
21.275 // LOGGER.fine(String.format("LuceneIndex[%s] is invalid!\n", this.toString()));
21.276 @@ -130,32 +299,30 @@
21.277
21.278 // TODO - handle case insensitive searches etc?
21.279 String field = PythonIndexer.FIELD_MODULE_NAME;
21.280 - Set<String> terms = new HashSet<String>(5);
21.281 - terms.add(PythonIndexer.FIELD_MODULE_ATTR_NAME);
21.282 - terms.add(PythonIndexer.FIELD_MODULE_NAME);
21.283
21.284 - search(field, name, kind, result, ALL_SCOPE, terms);
21.285 + search(field, name, kind, result, PythonIndexer.FIELD_MODULE_ATTR_NAME, PythonIndexer.FIELD_MODULE_NAME);
21.286
21.287 final Set<IndexedElement> modules = new HashSet<IndexedElement>();
21.288
21.289 - for (SearchResult map : result) {
21.290 - String url = map.getPersistentUrl();
21.291 + for (IndexResult map : result) {
21.292 + URL url = map.getUrl();
21.293 if (url == null) {
21.294 continue;
21.295 }
21.296 + String path = url.toExternalForm();
21.297 String module = map.getValue(PythonIndexer.FIELD_MODULE_NAME);
21.298 if (STUB_MISSING.equals(module)) {
21.299 continue;
21.300 }
21.301
21.302 - IndexedElement element = new IndexedElement(module, ElementKind.MODULE, url, null, null, null);
21.303 + IndexedElement element = new IndexedElement(module, ElementKind.MODULE, path, null, null, null);
21.304
21.305 String attrs = map.getValue(PythonIndexer.FIELD_MODULE_ATTR_NAME);
21.306 if (attrs != null && attrs.indexOf('D') != -1) {
21.307 element.setFlags(IndexedElement.DEPRECATED);
21.308 }
21.309
21.310 - String rhs = url.substring(url.lastIndexOf('/') + 1);
21.311 + String rhs = path.substring(path.lastIndexOf('/') + 1);
21.312 element.setRhs(rhs);
21.313 modules.add(element);
21.314 }
21.315 @@ -163,15 +330,15 @@
21.316 return modules;
21.317 }
21.318
21.319 - public Set<IndexedPackage> getPackages(String name, final NameKind kind) {
21.320 - final Set<SearchResult> result = new HashSet<SearchResult>();
21.321 + public Set<IndexedPackage> getPackages(String name, final QuerySupport.Kind kind) {
21.322 + final Set<IndexResult> result = new HashSet<IndexResult>();
21.323
21.324 String field = PythonIndexer.FIELD_MODULE_NAME;
21.325 - search(field, name, kind, result, ALL_SCOPE, Collections.singleton(PythonIndexer.FIELD_MODULE_NAME));
21.326 + search(field, name, kind, result, PythonIndexer.FIELD_MODULE_NAME);
21.327
21.328 final Set<IndexedPackage> packages = new HashSet<IndexedPackage>();
21.329
21.330 - for (SearchResult map : result) {
21.331 + for (IndexResult map : result) {
21.332 String module = map.getValue(PythonIndexer.FIELD_MODULE_NAME);
21.333
21.334 String pkgName = null;
21.335 @@ -199,7 +366,7 @@
21.336 }
21.337
21.338 if (pkgName != null) {
21.339 - String url = map.getPersistentUrl();
21.340 + String url = map.getUrl().toExternalForm();
21.341 IndexedPackage element = new IndexedPackage(pkgName, pkg, url, nextNextDot != -1);
21.342 element.setRhs("");
21.343 packages.add(element);
21.344 @@ -208,10 +375,9 @@
21.345
21.346 return packages;
21.347 }
21.348 -
21.349 - public Set<IndexedElement> getClasses(String name, final NameKind kind, Set<SearchScope> scope,
21.350 - PythonParserResult context, boolean includeDuplicates) {
21.351 - final Set<SearchResult> result = new HashSet<SearchResult>();
21.352 +
21.353 + public Set<IndexedElement> getClasses(String name, final QuerySupport.Kind kind, PythonParserResult context, boolean includeDuplicates) {
21.354 + final Set<IndexResult> result = new HashSet<IndexResult>();
21.355
21.356 // if (!isValid()) {
21.357 // LOGGER.fine(String.format("LuceneIndex[%s] is invalid!\n", this.toString()));
21.358 @@ -220,42 +386,37 @@
21.359 String field;
21.360
21.361 switch (kind) {
21.362 - case EXACT_NAME:
21.363 - case PREFIX:
21.364 - case CAMEL_CASE:
21.365 - case REGEXP:
21.366 - field = PythonIndexer.FIELD_CLASS_NAME;
21.367 -
21.368 - break;
21.369 -
21.370 - case CASE_INSENSITIVE_PREFIX:
21.371 - case CASE_INSENSITIVE_REGEXP:
21.372 - field = PythonIndexer.FIELD_CASE_INSENSITIVE_CLASS_NAME;
21.373 -
21.374 - break;
21.375 -
21.376 - default:
21.377 - throw new UnsupportedOperationException(kind.toString());
21.378 + case EXACT:
21.379 + case PREFIX:
21.380 + case CAMEL_CASE:
21.381 + case REGEXP:
21.382 + field = PythonIndexer.FIELD_CLASS_NAME;
21.383 +
21.384 + break;
21.385 +
21.386 + case CASE_INSENSITIVE_PREFIX:
21.387 + case CASE_INSENSITIVE_REGEXP:
21.388 + field = PythonIndexer.FIELD_CASE_INSENSITIVE_CLASS_NAME;
21.389 +
21.390 + break;
21.391 +
21.392 + default:
21.393 + throw new UnsupportedOperationException(kind.toString());
21.394 }
21.395
21.396 - Set<String> terms = new HashSet<String>(5);
21.397 - terms.add(PythonIndexer.FIELD_IN);
21.398 - terms.add(PythonIndexer.FIELD_CLASS_ATTR_NAME);
21.399 - terms.add(PythonIndexer.FIELD_CLASS_NAME);
21.400 -
21.401 - search(field, name, kind, result, scope, terms);
21.402 + search(field, name, kind, result, PythonIndexer.FIELD_IN, PythonIndexer.FIELD_CLASS_ATTR_NAME, PythonIndexer.FIELD_CLASS_NAME);
21.403
21.404 Set<String> uniqueClasses = includeDuplicates ? null : new HashSet<String>();
21.405
21.406 final Set<IndexedElement> classes = new HashSet<IndexedElement>();
21.407
21.408 - for (SearchResult map : result) {
21.409 + for (IndexResult map : result) {
21.410 String clz = map.getValue(PythonIndexer.FIELD_CLASS_NAME);
21.411 if (clz == null) {
21.412 // A module without classes
21.413 continue;
21.414 }
21.415 - String url = map.getPersistentUrl();
21.416 + String url = map.getUrl().toExternalForm();
21.417 String module = map.getValue(PythonIndexer.FIELD_IN);
21.418 boolean isBuiltin = isBuiltinModule(module);
21.419
21.420 @@ -290,7 +451,7 @@
21.421 // * @todo Use arglist arity comparison to reject methods that are not overrides...
21.422 // */
21.423 // public IndexedMethod getOverridingMethod(String className, String methodName) {
21.424 -// Set<IndexedElement> methods = getInheritedElements(className, methodName, NameKind.EXACT_NAME);
21.425 +// Set<IndexedElement> methods = getInheritedElements(className, methodName, QuerySupport.Kind.EXACT);
21.426 //
21.427 // // TODO - this is only returning ONE match, not the most distant one. I really need to
21.428 // // produce a PythonIndex method for this which can walk in there and do a decent job!
21.429 @@ -308,7 +469,7 @@
21.430 // }
21.431 /** Get the super implementation of the given method */
21.432 public Set<IndexedElement> getOverridingMethods(String className, String function) {
21.433 - Set<IndexedElement> methods = getInheritedElements(className, function, NameKind.EXACT_NAME, true);
21.434 + Set<IndexedElement> methods = getInheritedElements(className, function, QuerySupport.Kind.EXACT, true);
21.435
21.436 // TODO - remove all methods that are in the same file
21.437 if (methods.size() > 0) {
21.438 @@ -339,16 +500,12 @@
21.439
21.440 /** Get the super class of the given class */
21.441 public Set<IndexedElement> getSuperClasses(String className) {
21.442 - final Set<SearchResult> result = new HashSet<SearchResult>();
21.443 - Set<String> terms = new HashSet<String>(5);
21.444 -// terms.add(PythonIndexer.FIELD_IN);
21.445 - terms.add(PythonIndexer.FIELD_EXTENDS_NAME);
21.446 - terms.add(PythonIndexer.FIELD_CLASS_NAME);
21.447 + final Set<IndexResult> result = new HashSet<IndexResult>();
21.448
21.449 - search(PythonIndexer.FIELD_CLASS_NAME, className, NameKind.EXACT_NAME, result, ALL_SCOPE, terms);
21.450 + search(PythonIndexer.FIELD_CLASS_NAME, className, QuerySupport.Kind.EXACT, result, PythonIndexer.FIELD_EXTENDS_NAME, PythonIndexer.FIELD_CLASS_NAME);
21.451
21.452 Set<String> classNames = new HashSet<String>();
21.453 - for (SearchResult map : result) {
21.454 + for (IndexResult map : result) {
21.455 String[] extendsClasses = map.getValues(PythonIndexer.FIELD_EXTENDS_NAME);
21.456 if (extendsClasses != null && extendsClasses.length > 0) {
21.457 for (String clzName : extendsClasses) {
21.458 @@ -357,18 +514,16 @@
21.459 }
21.460 }
21.461
21.462 - terms = new HashSet<String>(5);
21.463 - terms.add(PythonIndexer.FIELD_IN);
21.464 - terms.add(PythonIndexer.FIELD_CLASS_NAME);
21.465 + String[] terms = { PythonIndexer.FIELD_IN, PythonIndexer.FIELD_CLASS_NAME };
21.466
21.467 Set<IndexedElement> superClasses = new HashSet<IndexedElement>();
21.468
21.469 for (String superClz : classNames) {
21.470 result.clear();
21.471 - search(PythonIndexer.FIELD_CLASS_NAME, superClz, NameKind.EXACT_NAME, result, ALL_SCOPE, terms);
21.472 - for (SearchResult map : result) {
21.473 + search(PythonIndexer.FIELD_CLASS_NAME, superClz, QuerySupport.Kind.EXACT, result, terms);
21.474 + for (IndexResult map : result) {
21.475 assert superClz.equals(map.getValue(PythonIndexer.FIELD_CLASS_NAME));
21.476 - String url = map.getPersistentUrl();
21.477 + String url = map.getUrl().toExternalForm();
21.478 String module = map.getValue(PythonIndexer.FIELD_IN);
21.479 IndexedElement clz = new IndexedElement(superClz, ElementKind.CLASS, url, module, null, null);
21.480 superClasses.add(clz);
21.481 @@ -381,15 +536,15 @@
21.482 /**
21.483 * Get the set of inherited (through super classes and mixins) for the given fully qualified class name.
21.484 * @param classFqn FQN: module1::module2::moduleN::class
21.485 - * @param prefix If kind is NameKind.PREFIX/CASE_INSENSITIVE_PREFIX, a prefix to filter methods by. Else,
21.486 - * if kind is NameKind.EXACT_NAME filter methods by the exact name.
21.487 + * @param prefix If kind is QuerySupport.Kind.PREFIX/CASE_INSENSITIVE_PREFIX, a prefix to filter methods by. Else,
21.488 + * if kind is QuerySupport.Kind.EXACT filter methods by the exact name.
21.489 * @param kind Whether the prefix field should be taken as a prefix or a whole name
21.490 */
21.491 - public Set<IndexedElement> getInheritedElements(String classFqn, String prefix, NameKind kind) {
21.492 + public Set<IndexedElement> getInheritedElements(String classFqn, String prefix, QuerySupport.Kind kind) {
21.493 return getInheritedElements(classFqn, prefix, kind, false);
21.494 }
21.495
21.496 - public Set<IndexedElement> getInheritedElements(String classFqn, String prefix, NameKind kind, boolean includeOverrides) {
21.497 + public Set<IndexedElement> getInheritedElements(String classFqn, String prefix, QuerySupport.Kind kind, boolean includeOverrides) {
21.498 boolean haveRedirected = false;
21.499
21.500 if (classFqn == null) {
21.501 @@ -421,15 +576,11 @@
21.502 return elements;
21.503 }
21.504
21.505 - public static final String OBJECT = "object"; // NOI18N
21.506 -
21.507 /** Return whether the specific class referenced (classFqn) was found or not. This is
21.508 * not the same as returning whether any classes were added since it may add
21.509 * additional methods from parents (Object/Class).
21.510 */
21.511 - private boolean addMethodsFromClass(String prefix, NameKind kind, String classFqn,
21.512 - Set<IndexedElement> elements, Set<String> seenSignatures, Set<String> scannedClasses,
21.513 - boolean haveRedirected, boolean inheriting, boolean includeOverrides, int depth) {
21.514 + private boolean addMethodsFromClass(String prefix, QuerySupport.Kind kind, String classFqn, Set<IndexedElement> elements, Set<String> seenSignatures, Set<String> scannedClasses, boolean haveRedirected, boolean inheriting, boolean includeOverrides, int depth) {
21.515 // Prevent problems with circular includes or redundant includes
21.516 if (scannedClasses.contains(classFqn)) {
21.517 return false;
21.518 @@ -439,16 +590,15 @@
21.519
21.520 String searchField = PythonIndexer.FIELD_CLASS_NAME;
21.521
21.522 - Set<SearchResult> result = new HashSet<SearchResult>();
21.523 + Set<IndexResult> result = new HashSet<IndexResult>();
21.524
21.525 - Set<String> terms = new HashSet<String>(5);
21.526 - terms.add(PythonIndexer.FIELD_IN);
21.527 - terms.add(PythonIndexer.FIELD_EXTENDS_NAME);
21.528 - terms.add(PythonIndexer.FIELD_MEMBER);
21.529 - terms.add(PythonIndexer.FIELD_CLASS_NAME);
21.530 -
21.531 -
21.532 - search(searchField, classFqn, NameKind.EXACT_NAME, result, ALL_SCOPE, terms);
21.533 + String[] terms = {PythonIndexer.FIELD_IN,
21.534 + PythonIndexer.FIELD_EXTENDS_NAME,
21.535 + PythonIndexer.FIELD_MEMBER,
21.536 + PythonIndexer.FIELD_CLASS_NAME};
21.537 +
21.538 +
21.539 + search(searchField, classFqn, QuerySupport.Kind.EXACT, result, terms);
21.540
21.541 boolean foundIt = result.size() > 0;
21.542
21.543 @@ -467,10 +617,10 @@
21.544 }
21.545 int prefixLength = prefix.length();
21.546
21.547 - for (SearchResult map : result) {
21.548 + for (IndexResult map : result) {
21.549 assert map != null;
21.550
21.551 - String url = map.getPersistentUrl();
21.552 + String url = map.getUrl().toExternalForm();
21.553 String clz = map.getValue(PythonIndexer.FIELD_CLASS_NAME);
21.554 String module = map.getValue(PythonIndexer.FIELD_IN);
21.555
21.556 @@ -493,16 +643,16 @@
21.557 // Prevent duplicates when method is redefined
21.558 if (includeOverrides || !seenSignatures.contains(signature)) {
21.559 if (signature.startsWith(prefix)) {
21.560 - if (kind == NameKind.EXACT_NAME) {
21.561 + if (kind == QuerySupport.Kind.EXACT) {
21.562 if (signature.charAt(prefixLength) != ';') {
21.563 continue;
21.564 }
21.565 - } else if (kind == NameKind.CASE_INSENSITIVE_PREFIX && !signature.regionMatches(true, 0, prefix, 0, prefix.length())) {
21.566 + } else if (kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX && !signature.regionMatches(true, 0, prefix, 0, prefix.length())) {
21.567 continue;
21.568 } else {
21.569 // REGEXP, CAMELCASE filtering etc. not supported here
21.570 - assert (kind == NameKind.PREFIX) ||
21.571 - (kind == NameKind.CASE_INSENSITIVE_PREFIX);
21.572 + assert (kind == QuerySupport.Kind.PREFIX) ||
21.573 + (kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX);
21.574 }
21.575
21.576 if (!includeOverrides) {
21.577 @@ -558,36 +708,31 @@
21.578
21.579 return foundIt;
21.580 }
21.581 -
21.582 - public Set<IndexedElement> getAllMembers(String name, NameKind kind, Set<SearchScope> scope,
21.583 - PythonParserResult context, boolean includeDuplicates) {
21.584 - final Set<SearchResult> result = new HashSet<SearchResult>();
21.585 +
21.586 +
21.587 + public Set<IndexedElement> getAllMembers(String name, QuerySupport.Kind kind, PythonParserResult context, boolean includeDuplicates) {
21.588 + final Set<IndexResult> result = new HashSet<IndexResult>();
21.589 // TODO - handle case sensitivity better...
21.590 String field = PythonIndexer.FIELD_MEMBER;
21.591 - NameKind originalKind = kind;
21.592 - if (kind == NameKind.EXACT_NAME) {
21.593 + QuerySupport.Kind originalKind = kind;
21.594 + if (kind == QuerySupport.Kind.EXACT) {
21.595 // I can't do exact searches on methods because the method
21.596 // entries include signatures etc. So turn this into a prefix
21.597 // search and then compare chopped off signatures with the name
21.598 - kind = NameKind.PREFIX;
21.599 + kind = QuerySupport.Kind.PREFIX;
21.600 }
21.601
21.602 String searchUrl = null;
21.603 if (context != null) {
21.604 - try {
21.605 - searchUrl = context.getFile().getFileObject().getURL().toExternalForm();
21.606 - } catch (FileStateInvalidException ex) {
21.607 - Exceptions.printStackTrace(ex);
21.608 - }
21.609 + searchUrl = context.getSnapshot().getSource().getFileObject().toURL().toExternalForm();
21.610 }
21.611
21.612 - Set<String> terms = new HashSet<String>(5);
21.613 - terms.add(PythonIndexer.FIELD_IN);
21.614 - terms.add(PythonIndexer.FIELD_EXTENDS_NAME);
21.615 - terms.add(PythonIndexer.FIELD_MEMBER);
21.616 - terms.add(PythonIndexer.FIELD_CLASS_NAME);
21.617 + String[] terms = {PythonIndexer.FIELD_IN,
21.618 + PythonIndexer.FIELD_EXTENDS_NAME,
21.619 + PythonIndexer.FIELD_MEMBER,
21.620 + PythonIndexer.FIELD_CLASS_NAME};
21.621
21.622 - search(field, name, kind, result, scope, terms);
21.623 + search(field, name, kind, result, terms);
21.624
21.625 // Set<String> uniqueClasses = null;
21.626 // if (includeDuplicates) {
21.627 @@ -599,25 +744,25 @@
21.628 final Set<IndexedElement> members = new HashSet<IndexedElement>();
21.629 int nameLength = name.length();
21.630
21.631 - for (SearchResult map : result) {
21.632 + for (IndexResult map : result) {
21.633 String[] signatures = map.getValues(PythonIndexer.FIELD_MEMBER);
21.634 if (signatures != null && signatures.length > 0) {
21.635 - String url = map.getPersistentUrl();
21.636 + String url = map.getUrl().toExternalForm();
21.637 String clz = map.getValue(PythonIndexer.FIELD_CLASS_NAME);
21.638 String module = map.getValue(PythonIndexer.FIELD_IN);
21.639 boolean inherited = searchUrl == null || !searchUrl.equals(url);
21.640
21.641 for (String signature : signatures) {
21.642 - if (originalKind == NameKind.EXACT_NAME) {
21.643 + if (originalKind == QuerySupport.Kind.EXACT) {
21.644 if (signature.charAt(nameLength) != ';') {
21.645 continue;
21.646 }
21.647 - } else if (originalKind == NameKind.CASE_INSENSITIVE_PREFIX && !signature.regionMatches(true, 0, name, 0, name.length())) {
21.648 + } else if (originalKind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX && !signature.regionMatches(true, 0, name, 0, name.length())) {
21.649 continue;
21.650 } else {
21.651 // REGEXP, CAMELCASE filtering etc. not supported here
21.652 - assert (originalKind == NameKind.PREFIX) ||
21.653 - (originalKind == NameKind.CASE_INSENSITIVE_PREFIX);
21.654 + assert (originalKind == QuerySupport.Kind.PREFIX) ||
21.655 + (originalKind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX);
21.656 }
21.657
21.658 IndexedElement element = IndexedElement.create(signature, module, url, clz);
21.659 @@ -629,56 +774,50 @@
21.660
21.661 return members;
21.662 }
21.663 -
21.664 - public Set<IndexedElement> getAllElements(String name, NameKind kind, Set<SearchScope> scope,
21.665 - PythonParserResult context, boolean includeDuplicates) {
21.666 - final Set<SearchResult> result = new HashSet<SearchResult>();
21.667 +
21.668 + public Set<IndexedElement> getAllElements(String name, QuerySupport.Kind kind, PythonParserResult context, boolean includeDuplicates) {
21.669 + final Set<IndexResult> result = new HashSet<IndexResult>();
21.670 // TODO - handle case sensitivity better...
21.671 String field = PythonIndexer.FIELD_ITEM;
21.672 - NameKind originalKind = kind;
21.673 - if (kind == NameKind.EXACT_NAME) {
21.674 + QuerySupport.Kind originalKind = kind;
21.675 + if (kind == QuerySupport.Kind.EXACT) {
21.676 // I can't do exact searches on methods because the method
21.677 // entries include signatures etc. So turn this into a prefix
21.678 // search and then compare chopped off signatures with the name
21.679 - kind = NameKind.PREFIX;
21.680 + kind = QuerySupport.Kind.PREFIX;
21.681 }
21.682
21.683 String searchUrl = null;
21.684 if (context != null) {
21.685 - try {
21.686 - searchUrl = context.getFile().getFileObject().getURL().toExternalForm();
21.687 - } catch (FileStateInvalidException ex) {
21.688 - Exceptions.printStackTrace(ex);
21.689 - }
21.690 + searchUrl = context.getSnapshot().getSource().getFileObject().toURL().toExternalForm();
21.691 }
21.692
21.693 - Set<String> terms = new HashSet<String>(5);
21.694 - terms.add(PythonIndexer.FIELD_ITEM);
21.695 - terms.add(PythonIndexer.FIELD_MODULE_NAME);
21.696 + String[] terms = { PythonIndexer.FIELD_ITEM,
21.697 + PythonIndexer.FIELD_MODULE_NAME };
21.698
21.699 - search(field, name, kind, result, scope, terms);
21.700 + search(field, name, kind, result, terms);
21.701
21.702 final Set<IndexedElement> elements = new HashSet<IndexedElement>();
21.703 int nameLength = name.length();
21.704
21.705 - for (SearchResult map : result) {
21.706 + for (IndexResult map : result) {
21.707 String[] signatures = map.getValues(PythonIndexer.FIELD_ITEM);
21.708 if (signatures != null && signatures.length > 0) {
21.709 - String url = map.getPersistentUrl();
21.710 + String url = map.getUrl().toExternalForm();
21.711 String module = map.getValue(PythonIndexer.FIELD_MODULE_NAME);
21.712 boolean inherited = searchUrl == null || !searchUrl.equals(url);
21.713
21.714 for (String signature : signatures) {
21.715 - if (originalKind == NameKind.EXACT_NAME) {
21.716 + if (originalKind == QuerySupport.Kind.EXACT) {
21.717 if (signature.charAt(nameLength) != ';') {
21.718 continue;
21.719 }
21.720 - } else if (originalKind == NameKind.CASE_INSENSITIVE_PREFIX && !signature.regionMatches(true, 0, name, 0, name.length())) {
21.721 + } else if (originalKind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX && !signature.regionMatches(true, 0, name, 0, name.length())) {
21.722 continue;
21.723 } else {
21.724 // REGEXP, CAMELCASE filtering etc. not supported here
21.725 - assert (originalKind == NameKind.PREFIX) ||
21.726 - (originalKind == NameKind.CASE_INSENSITIVE_PREFIX);
21.727 + assert (originalKind == QuerySupport.Kind.PREFIX) ||
21.728 + (originalKind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX);
21.729 }
21.730
21.731 IndexedElement element = IndexedElement.create(signature, module, url, null);
21.732 @@ -704,20 +843,19 @@
21.733
21.734 Set<String> symbols = new HashSet<String>(250);
21.735
21.736 - Set<String> terms = new HashSet<String>(5);
21.737 - terms.add(PythonIndexer.FIELD_MODULE_NAME);
21.738 - terms.add(PythonIndexer.FIELD_ITEM);
21.739 + String[] terms = { PythonIndexer.FIELD_MODULE_NAME,
21.740 + PythonIndexer.FIELD_ITEM };
21.741
21.742 // Look up all symbols
21.743 for (String module : modules) {
21.744 - final Set<SearchResult> result = new HashSet<SearchResult>();
21.745 + final Set<IndexResult> result = new HashSet<IndexResult>();
21.746 // TODO - handle case sensitivity better...
21.747 String field = PythonIndexer.FIELD_MODULE_NAME;
21.748 - NameKind kind = NameKind.EXACT_NAME;
21.749 + QuerySupport.Kind kind = QuerySupport.Kind.EXACT;
21.750
21.751 - search(field, module, kind, result, ALL_SCOPE, terms);
21.752 + search(field, module, kind, result, terms);
21.753
21.754 - for (SearchResult map : result) {
21.755 + for (IndexResult map : result) {
21.756 String[] signatures = map.getValues(PythonIndexer.FIELD_ITEM);
21.757 if (signatures != null) {
21.758 for (String signature : signatures) {
21.759 @@ -798,17 +936,13 @@
21.760 return symbols;
21.761 }
21.762
21.763 - public static boolean isBuiltinModule(String module) {
21.764 - return BUILTIN_MODULES.contains(module) || STUB_MISSING.equals(module);
21.765 - }
21.766 -
21.767 @SuppressWarnings("unchecked")
21.768 public Set<String> getImportsFor(String ident, boolean includeSymbol) {
21.769 Set<String> modules = new HashSet<String>(10);
21.770
21.771 - final Set<SearchResult> result = new HashSet<SearchResult>();
21.772 - search(PythonIndexer.FIELD_MODULE_NAME, ident, NameKind.EXACT_NAME, result, ALL_SCOPE, Collections.singleton(PythonIndexer.FIELD_MODULE_NAME));
21.773 - for (SearchResult map : result) {
21.774 + final Set<IndexResult> result = new HashSet<IndexResult>();
21.775 + search(PythonIndexer.FIELD_MODULE_NAME, ident, QuerySupport.Kind.EXACT, result, PythonIndexer.FIELD_MODULE_NAME);
21.776 + for (IndexResult map : result) {
21.777 String module = map.getValue(PythonIndexer.FIELD_MODULE_NAME);
21.778 if (module != null) {
21.779 // TODO - record more information about this, such as the FQN
21.780 @@ -819,18 +953,17 @@
21.781
21.782 // TODO - handle case sensitivity better...
21.783 String field = PythonIndexer.FIELD_ITEM;
21.784 - NameKind kind = NameKind.PREFIX; // We're storing encoded signatures so not exact matches
21.785 + QuerySupport.Kind kind = QuerySupport.Kind.PREFIX; // We're storing encoded signatures so not exact matches
21.786
21.787 - Set<String> terms = new HashSet<String>(5);
21.788 - terms.add(PythonIndexer.FIELD_ITEM);
21.789 - terms.add(PythonIndexer.FIELD_MODULE_NAME);
21.790 + String[] terms = { PythonIndexer.FIELD_ITEM,
21.791 + PythonIndexer.FIELD_MODULE_NAME };
21.792
21.793 result.clear();
21.794 - search(field, ident, kind, result, ALL_SCOPE, terms);
21.795 + search(field, ident, kind, result, terms);
21.796 String match = ident + ";";
21.797
21.798 MapSearch:
21.799 - for (SearchResult map : result) {
21.800 + for (IndexResult map : result) {
21.801 String module = map.getValue(PythonIndexer.FIELD_MODULE_NAME);
21.802 if (module == null) {
21.803 continue;
21.804 @@ -883,13 +1016,12 @@
21.805
21.806 return modules;
21.807 }
21.808 -
21.809 - public Set<IndexedElement> getImportedElements(String prefix, NameKind kind, Set<SearchScope> scope,
21.810 - List<Import> imports, List<ImportFrom> importsFrom) {
21.811 +
21.812 + public Set<IndexedElement> getImportedElements(String prefix, QuerySupport.Kind kind, PythonParserResult context, List<Import> imports, List<ImportFrom> importsFrom) {
21.813 // TODO - separate methods from variables?? E.g. if you have method Foo() and class Foo
21.814 // coming from different places
21.815 -
21.816 -
21.817 +
21.818 +
21.819 // Set<String> imported = new HashSet<String>();
21.820 //
21.821 Set<IndexedElement> elements = new HashSet<IndexedElement>();
21.822 @@ -934,7 +1066,7 @@
21.823 // // Create variable items for the locally imported symbols
21.824 // for (String name : imported) {
21.825 // if (name.startsWith(prefix)) {
21.826 -// if (kind == NameKind.EXACT_NAME) {
21.827 +// if (kind == QuerySupport.Kind.EXACT) {
21.828 // // Ensure that the method is not longer than the prefix
21.829 // if ((name.length() > prefix.length()) &&
21.830 // (name.charAt(prefix.length()) != '(') &&
21.831 @@ -943,8 +1075,8 @@
21.832 // }
21.833 // } else {
21.834 // // REGEXP, CAMELCASE filtering etc. not supported here
21.835 -// assert (kind == NameKind.PREFIX) ||
21.836 -// (kind == NameKind.CASE_INSENSITIVE_PREFIX);
21.837 +// assert (kind == QuerySupport.Kind.PREFIX) ||
21.838 +// (kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX);
21.839 // }
21.840 // String url = null;
21.841 // ElementKind elementKind = ElementKind.VARIABLE;
21.842 @@ -962,18 +1094,16 @@
21.843 // Always include the current file as imported
21.844 String moduleName = null;
21.845 if (context != null) {
21.846 - moduleName = context.getName();
21.847 + moduleName = PythonUtils.getModuleName(context.getSnapshot().getSource().getFileObject());
21.848 modules.add(moduleName);
21.849 }
21.850
21.851 modules.addAll(BUILTIN_MODULES);
21.852
21.853 - addImportedElements(prefix, kind, scope, modules, elements, null);
21.854 + addImportedElements(prefix, kind, modules, elements, null);
21.855
21.856 return elements;
21.857 }
21.858 - static Map<String, Set<String>> wildcardImports = new HashMap<String, Set<String>>();
21.859 -
21.860 public Set<String> getImportedFromWildcards(List<ImportFrom> importsFrom) {
21.861 Set<String> symbols = new HashSet<String>(100);
21.862
21.863 @@ -992,9 +1122,7 @@
21.864 }
21.865 }
21.866
21.867 - Set<String> terms = new HashSet<String>(5);
21.868 - terms.add(PythonIndexer.FIELD_ITEM);
21.869 - terms.add(PythonIndexer.FIELD_MODULE_NAME);
21.870 + String[] terms = { PythonIndexer.FIELD_ITEM, PythonIndexer.FIELD_MODULE_NAME };
21.871
21.872 // Look up all symbols
21.873 for (String module : modules) {
21.874 @@ -1012,12 +1140,12 @@
21.875 }
21.876
21.877
21.878 - final Set<SearchResult> result = new HashSet<SearchResult>();
21.879 + final Set<IndexResult> result = new HashSet<IndexResult>();
21.880 // TODO - handle case sensitivity better...
21.881
21.882 - search(PythonIndexer.FIELD_MODULE_NAME, module, NameKind.EXACT_NAME, result, ALL_SCOPE, terms);
21.883 + search(PythonIndexer.FIELD_MODULE_NAME, module, QuerySupport.Kind.EXACT, result, terms);
21.884
21.885 - for (SearchResult map : result) {
21.886 + for (IndexResult map : result) {
21.887 String[] items = map.getValues(PythonIndexer.FIELD_ITEM);
21.888 if (items != null) {
21.889 for (String signature : items) {
21.890 @@ -1044,35 +1172,32 @@
21.891
21.892 return symbols;
21.893 }
21.894 -
21.895 - public Set<IndexedElement> getImportedElements(String prefix, NameKind kind, Set<SearchScope> scope,
21.896 - Set<String> modules, Set<String> systemModuleHolder) {
21.897 +
21.898 + public Set<IndexedElement> getImportedElements(String prefix, QuerySupport.Kind kind, Set<String> modules, Set<String> systemModuleHolder) {
21.899 Set<IndexedElement> elements = new HashSet<IndexedElement>();
21.900
21.901 - addImportedElements(prefix, kind, scope, modules, elements, systemModuleHolder);
21.902 + addImportedElements(prefix, kind, modules, elements, systemModuleHolder);
21.903
21.904 return elements;
21.905 }
21.906 - static Set<String> systemModules;
21.907
21.908 public boolean isSystemModule(String module) {
21.909 if (systemModules == null) {
21.910 systemModules = new HashSet<String>(800); // measured: 623
21.911 - Set<String> terms = new HashSet<String>(5);
21.912 - terms.add(PythonIndexer.FIELD_MODULE_ATTR_NAME);
21.913 - terms.add(PythonIndexer.FIELD_MODULE_NAME);
21.914 - final Set<SearchResult> result = new HashSet<SearchResult>();
21.915 + String[] terms = { PythonIndexer.FIELD_MODULE_ATTR_NAME,
21.916 + PythonIndexer.FIELD_MODULE_NAME };
21.917 + final Set<IndexResult> result = new HashSet<IndexResult>();
21.918
21.919 // This doesn't work because the attrs field isn't searchable:
21.920 - //search(PythonIndexer.FIELD_MODULE_ATTR_NAME, "S", NameKind.PREFIX, result, ALL_SCOPE, terms);
21.921 - //for (SearchResult map : result) {
21.922 + //search(PythonIndexer.FIELD_MODULE_ATTR_NAME, "S", QuerySupport.Kind.PREFIX, result, ALL_SCOPE, terms);
21.923 + //for (IndexResult map : result) {
21.924 // assert map.getValue(PythonIndexer.FIELD_MODULE_ATTR_NAME).indexOf("S") != -1;
21.925 // systemModules.add(map.getValue(PythonIndexer.FIELD_MODULE_NAME));
21.926 //}
21.927
21.928 - search(PythonIndexer.FIELD_MODULE_NAME, "", NameKind.PREFIX, result, ALL_SCOPE, terms);
21.929 + search(PythonIndexer.FIELD_MODULE_NAME, "", QuerySupport.Kind.PREFIX, result, terms);
21.930
21.931 - for (SearchResult map : result) {
21.932 + for (IndexResult map : result) {
21.933 String attrs = map.getValue(PythonIndexer.FIELD_MODULE_ATTR_NAME);
21.934 if (attrs != null && attrs.indexOf('S') != -1) {
21.935 String mod = map.getValue(PythonIndexer.FIELD_MODULE_NAME);
21.936 @@ -1084,19 +1209,14 @@
21.937 return systemModules.contains(module);
21.938 }
21.939
21.940 - // TODO - make weak?
21.941 - static Set<String> availableClasses;
21.942 -
21.943 public boolean isLowercaseClassName(String clz) {
21.944 if (availableClasses == null) {
21.945 availableClasses = new HashSet<String>(300); // measured: 193
21.946 - Set<String> terms = new HashSet<String>(5);
21.947 - terms.add(PythonIndexer.FIELD_CLASS_NAME);
21.948 - final Set<SearchResult> result = new HashSet<SearchResult>();
21.949 + final Set<IndexResult> result = new HashSet<IndexResult>();
21.950
21.951 - search(PythonIndexer.FIELD_CLASS_NAME, "", NameKind.PREFIX, result, ALL_SCOPE, terms);
21.952 + search(PythonIndexer.FIELD_CLASS_NAME, "", QuerySupport.Kind.PREFIX, result, PythonIndexer.FIELD_CLASS_NAME);
21.953
21.954 - for (SearchResult map : result) {
21.955 + for (IndexResult map : result) {
21.956 String c = map.getValue(PythonIndexer.FIELD_CLASS_NAME);
21.957 if (c != null && !Character.isUpperCase(c.charAt(0))) {
21.958 availableClasses.add(c);
21.959 @@ -1106,28 +1226,26 @@
21.960
21.961 return availableClasses.contains(clz);
21.962 }
21.963 -
21.964 - public void addImportedElements(String prefix, NameKind kind, Set<SearchScope> scope,
21.965 - Set<String> modules, Set<IndexedElement> elements, Set<String> systemModuleHolder) {
21.966 -
21.967 - Set<String> terms = new HashSet<String>(5);
21.968 - terms.add(PythonIndexer.FIELD_ITEM);
21.969 - terms.add(PythonIndexer.FIELD_MODULE_ATTR_NAME);
21.970 - terms.add(PythonIndexer.FIELD_MODULE_NAME);
21.971 +
21.972 + public void addImportedElements(String prefix, QuerySupport.Kind kind, Set<String> modules, Set<IndexedElement> elements, Set<String> systemModuleHolder) {
21.973 +
21.974 + String[] terms = { PythonIndexer.FIELD_ITEM,
21.975 + PythonIndexer.FIELD_MODULE_ATTR_NAME,
21.976 + PythonIndexer.FIELD_MODULE_NAME };
21.977
21.978 // Look up all symbols
21.979 for (String module : modules) {
21.980 boolean isBuiltin = isBuiltinModule(module);
21.981 boolean isSystem = isBuiltin;
21.982
21.983 - final Set<SearchResult> result = new HashSet<SearchResult>();
21.984 + final Set<IndexResult> result = new HashSet<IndexResult>();
21.985 // TODO - handle case sensitivity better...
21.986
21.987 - search(PythonIndexer.FIELD_MODULE_NAME, module, NameKind.EXACT_NAME, result, scope, terms);
21.988 + search(PythonIndexer.FIELD_MODULE_NAME, module, QuerySupport.Kind.EXACT, result, terms);
21.989 int prefixLength = prefix.length();
21.990
21.991 - for (SearchResult map : result) {
21.992 - String url = map.getPersistentUrl();
21.993 + for (IndexResult map : result) {
21.994 + String url = map.getUrl().toExternalForm();
21.995 String[] items = map.getValues(PythonIndexer.FIELD_ITEM);
21.996 if (items != null) {
21.997 String attrs = map.getValue(PythonIndexer.FIELD_MODULE_ATTR_NAME);
21.998 @@ -1136,16 +1254,16 @@
21.999 }
21.1000 for (String signature : items) {
21.1001 if (signature.startsWith(prefix)) {
21.1002 - if (kind == NameKind.EXACT_NAME) {
21.1003 + if (kind == QuerySupport.Kind.EXACT) {
21.1004 if (signature.charAt(prefixLength) != ';') {
21.1005 continue;
21.1006 }
21.1007 - } else if (kind == NameKind.CASE_INSENSITIVE_PREFIX && !signature.regionMatches(true, 0, prefix, 0, prefix.length())) {
21.1008 + } else if (kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX && !signature.regionMatches(true, 0, prefix, 0, prefix.length())) {
21.1009 continue;
21.1010 } else {
21.1011 // REGEXP, CAMELCASE filtering etc. not supported here
21.1012 - assert (kind == NameKind.PREFIX) ||
21.1013 - (kind == NameKind.CASE_INSENSITIVE_PREFIX);
21.1014 + assert (kind == QuerySupport.Kind.PREFIX) ||
21.1015 + (kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX);
21.1016 }
21.1017
21.1018 IndexedElement element = IndexedElement.create(signature, module, url, null);
21.1019 @@ -1170,17 +1288,16 @@
21.1020 }
21.1021 }
21.1022
21.1023 - public Set<IndexedElement> getExceptions(String prefix, NameKind kind, Set<SearchScope> scope) {
21.1024 - final Set<SearchResult> result = new HashSet<SearchResult>();
21.1025 - Set<String> terms = new HashSet<String>();
21.1026 - terms.add(PythonIndexer.FIELD_EXTENDS_NAME);
21.1027 - terms.add(PythonIndexer.FIELD_CLASS_NAME);
21.1028 - terms.add(PythonIndexer.FIELD_CLASS_ATTR_NAME);
21.1029 - terms.add(PythonIndexer.FIELD_IN);
21.1030 - search(PythonIndexer.FIELD_EXTENDS_NAME, "", NameKind.PREFIX, result, scope, terms); // NOI18N
21.1031 + public Set<IndexedElement> getExceptions(String prefix, QuerySupport.Kind kind) {
21.1032 + final Set<IndexResult> result = new HashSet<IndexResult>();
21.1033 + String[] terms = { PythonIndexer.FIELD_EXTENDS_NAME,
21.1034 + PythonIndexer.FIELD_CLASS_NAME,
21.1035 + PythonIndexer.FIELD_CLASS_ATTR_NAME,
21.1036 + PythonIndexer.FIELD_IN };
21.1037 + search(PythonIndexer.FIELD_EXTENDS_NAME, "", QuerySupport.Kind.PREFIX, result, terms); // NOI18N
21.1038 Map<String, String> extendsMap = new HashMap<String, String>(100);
21.1039 // First iteration: Compute inheritance hierarchy
21.1040 - for (SearchResult map : result) {
21.1041 + for (IndexResult map : result) {
21.1042
21.1043 String superClass = map.getValue(PythonIndexer.FIELD_EXTENDS_NAME);
21.1044 if (superClass != null) {
21.1045 @@ -1231,21 +1348,21 @@
21.1046
21.1047 // Next add elements for all the exceptions
21.1048 final Set<IndexedElement> classes = new HashSet<IndexedElement>();
21.1049 - for (SearchResult map : result) {
21.1050 + for (IndexResult map : result) {
21.1051 String clz = map.getValue(PythonIndexer.FIELD_CLASS_NAME);
21.1052 if (clz == null || !exceptionClasses.contains(clz)) {
21.1053 continue;
21.1054 }
21.1055
21.1056 - if ((kind == NameKind.PREFIX) && !clz.startsWith(prefix)) {
21.1057 + if ((kind == QuerySupport.Kind.PREFIX) && !clz.startsWith(prefix)) {
21.1058 continue;
21.1059 - } else if (kind == NameKind.CASE_INSENSITIVE_PREFIX && !clz.regionMatches(true, 0, prefix, 0, prefix.length())) {
21.1060 + } else if (kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX && !clz.regionMatches(true, 0, prefix, 0, prefix.length())) {
21.1061 continue;
21.1062 - } else if (kind == NameKind.EXACT_NAME && !clz.equals(prefix)) {
21.1063 + } else if (kind == QuerySupport.Kind.EXACT && !clz.equals(prefix)) {
21.1064 continue;
21.1065 }
21.1066
21.1067 - String url = map.getPersistentUrl();
21.1068 + String url = map.getUrl().toExternalForm();
21.1069 String module = map.getValue(PythonIndexer.FIELD_IN);
21.1070 IndexedElement element = new IndexedElement(clz, ElementKind.CLASS, url, module, null, null);
21.1071 String attrs = map.getValue(PythonIndexer.FIELD_CLASS_ATTR_NAME);
21.1072 @@ -1299,9 +1416,8 @@
21.1073
21.1074 return classes;
21.1075 }
21.1076 -
21.1077 - private boolean addSubclasses(String classFqn,
21.1078 - Set<IndexedElement> classes, Set<String> seenClasses, Set<String> scannedClasses, boolean directOnly) {
21.1079 +
21.1080 + private boolean addSubclasses(String classFqn, Set<IndexedElement> classes, Set<String> seenClasses, Set<String> scannedClasses, boolean directOnly) {
21.1081 // Prevent problems with circular includes or redundant includes
21.1082 if (scannedClasses.contains(classFqn)) {
21.1083 return false;
21.1084 @@ -1311,15 +1427,14 @@
21.1085
21.1086 String searchField = PythonIndexer.FIELD_EXTENDS_NAME;
21.1087
21.1088 - Set<SearchResult> result = new HashSet<SearchResult>();
21.1089 + Set<IndexResult> result = new HashSet<IndexResult>();
21.1090
21.1091 - Set<String> terms = new HashSet<String>(5);
21.1092 - terms.add(PythonIndexer.FIELD_IN);
21.1093 - terms.add(PythonIndexer.FIELD_EXTENDS_NAME);
21.1094 - terms.add(PythonIndexer.FIELD_CLASS_ATTR_NAME);
21.1095 - terms.add(PythonIndexer.FIELD_CLASS_NAME);
21.1096 + String[] terms = { PythonIndexer.FIELD_IN,
21.1097 + PythonIndexer.FIELD_EXTENDS_NAME,
21.1098 + PythonIndexer.FIELD_CLASS_ATTR_NAME,
21.1099 + PythonIndexer.FIELD_CLASS_NAME };
21.1100
21.1101 - search(searchField, classFqn, NameKind.EXACT_NAME, result, ALL_SCOPE, terms);
21.1102 + search(searchField, classFqn, QuerySupport.Kind.EXACT, result, terms);
21.1103
21.1104 boolean foundIt = result.size() > 0;
21.1105
21.1106 @@ -1328,10 +1443,10 @@
21.1107 return foundIt;
21.1108 }
21.1109
21.1110 - for (SearchResult map : result) {
21.1111 + for (IndexResult map : result) {
21.1112 String className = map.getValue(PythonIndexer.FIELD_CLASS_NAME);
21.1113 if (className != null && !seenClasses.contains(className)) {
21.1114 - String url = map.getPersistentUrl();
21.1115 + String url = map.getUrl().toExternalForm();
21.1116 String module = map.getValue(PythonIndexer.FIELD_IN);
21.1117 IndexedElement clz = new IndexedElement(className, ElementKind.CLASS, url, module, null, null);
21.1118 String attrs = map.getValue(PythonIndexer.FIELD_CLASS_ATTR_NAME);
21.1119 @@ -1351,123 +1466,4 @@
21.1120
21.1121 return foundIt;
21.1122 }
21.1123 - private static String clusterUrl = null;
21.1124 -
21.1125 - // For testing only
21.1126 - public static void setClusterUrl(String url) {
21.1127 - clusterUrl = url;
21.1128 - }
21.1129 -
21.1130 - static String getPreindexUrl(String url) {
21.1131 - // TODO - look up the correct platform to use!
21.1132 - final PythonPlatformManager manager = PythonPlatformManager.getInstance();
21.1133 - final String platformName = manager.getDefaultPlatform();
21.1134 - PythonPlatform platform = manager.getPlatform(platformName);
21.1135 - if (platform != null) {
21.1136 - String s = platform.getHomeUrl();
21.1137 - if (s != null) {
21.1138 - if (url.startsWith(s)) {
21.1139 - url = PYTHONHOME_URL + url.substring(s.length());
21.1140 - return url;
21.1141 - }
21.1142 - }
21.1143 - }
21.1144 -
21.1145 - String s = getClusterUrl();
21.1146 -
21.1147 - if (url.startsWith(s)) {
21.1148 - return CLUSTER_URL + url.substring(s.length());
21.1149 - }
21.1150 -
21.1151 - if (url.startsWith("jar:file:")) { // NOI18N
21.1152 - String sub = url.substring(4);
21.1153 - if (sub.startsWith(s)) {
21.1154 - return CLUSTER_URL + sub.substring(s.length());
21.1155 - }
21.1156 - }
21.1157 -
21.1158 - return url;
21.1159 - }
21.1160 -
21.1161 - /** Get the FileObject corresponding to a URL returned from the index */
21.1162 - public static FileObject getFileObject(String url) {
21.1163 - return getFileObject(url, null);
21.1164 - }
21.1165 -
21.1166 - public static FileObject getFileObject(String url, FileObject context) {
21.1167 - try {
21.1168 - if (url.startsWith(PYTHONHOME_URL)) {
21.1169 - Iterator<String> it = null;
21.1170 -
21.1171 - // TODO - look up the right platform for the given project
21.1172 - //if (context != null) {
21.1173 - // Project project = FileOwnerQuery.getOwner(context);
21.1174 - // if (project != null) {
21.1175 - // PythonPlatform platform = PythonPlatform.platformFor(project);
21.1176 - // if (platform != null) {
21.1177 - // it = Collections.singleton(platform).iterator();
21.1178 - // }
21.1179 - // }
21.1180 - //}
21.1181 -
21.1182 - PythonPlatformManager manager = PythonPlatformManager.getInstance();
21.1183 - if (it == null) {
21.1184 - it = manager.getPlatformList().iterator();
21.1185 - }
21.1186 - while (it.hasNext()) {
21.1187 - String name = it.next();
21.1188 - PythonPlatform platform = manager.getPlatform(name);
21.1189 - if (platform != null) {
21.1190 - String u = platform.getHomeUrl();
21.1191 - if (u != null) {
21.1192 - try {
21.1193 - u = u + url.substring(PYTHONHOME_URL.length());
21.1194 - FileObject fo = URLMapper.findFileObject(new URL(u));
21.1195 - if (fo != null) {
21.1196 - return fo;
21.1197 - }
21.1198 - } catch (MalformedURLException mue) {
21.1199 - Exceptions.printStackTrace(mue);
21.1200 - }
21.1201 - }
21.1202 - }
21.1203 - }
21.1204 -
21.1205 - return null;
21.1206 - } else if (url.startsWith(CLUSTER_URL)) {
21.1207 - url = getClusterUrl() + url.substring(CLUSTER_URL.length()); // NOI18N
21.1208 - if (url.indexOf(".egg!/") != -1) { // NOI18N
21.1209 - url = "jar:" + url; // NOI18N
21.1210 - }
21.1211 - }
21.1212 -
21.1213 - return URLMapper.findFileObject(new URL(url));
21.1214 - } catch (IOException ex) {
21.1215 - Exceptions.printStackTrace(ex);
21.1216 - }
21.1217 -
21.1218 - return null;
21.1219 - }
21.1220 -
21.1221 - static String getClusterUrl() {
21.1222 - if (clusterUrl == null) {
21.1223 - File f =
21.1224 - InstalledFileLocator.getDefault().locate("modules/org-netbeans-modules-python-editor.jar", null, false); // NOI18N
21.1225 -
21.1226 - if (f == null) {
21.1227 - throw new RuntimeException("Can't find cluster");
21.1228 - }
21.1229 -
21.1230 - f = new File(f.getParentFile().getParentFile().getAbsolutePath());
21.1231 -
21.1232 - try {
21.1233 - f = f.getCanonicalFile();
21.1234 - clusterUrl = f.toURI().toURL().toExternalForm();
21.1235 - } catch (IOException ioe) {
21.1236 - Exceptions.printStackTrace(ioe);
21.1237 - }
21.1238 - }
21.1239 -
21.1240 - return clusterUrl;
21.1241 - }
21.1242 }
22.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonIndexSearcher.java Sun Jan 04 13:11:53 2015 -0600
22.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonIndexSearcher.java Sun Feb 01 15:02:07 2015 -0800
22.3 @@ -31,7 +31,6 @@
22.4 package org.netbeans.modules.python.editor;
22.5
22.6 import java.awt.Toolkit;
22.7 -import java.util.EnumSet;
22.8 import java.util.HashSet;
22.9 import java.util.Set;
22.10 import java.util.logging.Logger;
22.11 @@ -42,13 +41,12 @@
22.12 import org.netbeans.api.project.Project;
22.13 import org.netbeans.api.project.ProjectInformation;
22.14 import org.netbeans.api.project.ProjectUtils;
22.15 -import org.netbeans.modules.gsf.api.CompilationInfo;
22.16 -import org.netbeans.modules.gsf.api.ElementHandle;
22.17 -import org.netbeans.modules.gsf.api.Index;
22.18 -import org.netbeans.modules.gsf.api.Index.SearchScope;
22.19 -import org.netbeans.modules.gsf.api.IndexSearcher;
22.20 -import org.netbeans.modules.gsf.api.NameKind;
22.21 -import org.netbeans.modules.gsf.spi.GsfUtilities;
22.22 +import org.netbeans.modules.csl.api.ElementHandle;
22.23 +import org.netbeans.modules.csl.api.IndexSearcher;
22.24 +import org.netbeans.modules.csl.api.IndexSearcher.Descriptor;
22.25 +import org.netbeans.modules.csl.api.IndexSearcher.Helper;
22.26 +import org.netbeans.modules.csl.spi.GsfUtilities;
22.27 +import org.netbeans.modules.parsing.spi.indexing.support.QuerySupport;
22.28 import org.openide.filesystems.FileObject;
22.29 import org.openide.util.ImageUtilities;
22.30 import org.python.antlr.PythonTree;
22.31 @@ -58,18 +56,20 @@
22.32 * @author Tor Norbye
22.33 */
22.34 public class PythonIndexSearcher implements IndexSearcher {
22.35 - public Set<? extends Descriptor> getTypes(Index gsfIndex, String textForQuery, NameKind kind, EnumSet<SearchScope> scope, Helper helper) {
22.36 - PythonIndex index = PythonIndex.get(gsfIndex);
22.37 +
22.38 + @Override
22.39 + public Set<? extends Descriptor> getTypes(Project prjct, String textForQuery, QuerySupport.Kind kind, Helper helper) {
22.40 + PythonIndex index = PythonIndex.get(prjct);
22.41 Set<PythonSymbol> result = new HashSet<PythonSymbol>();
22.42 Set<? extends IndexedElement> elements;
22.43
22.44 // TODO - do some filtering if you use ./#
22.45 // int dot = textForQuery.lastIndexOf('.');
22.46 - // if (dot != -1 && (kind == NameKind.PREFIX || kind == NameKind.CASE_INSENSITIVE_PREFIX)) {
22.47 + // if (dot != -1 && (kind == QuerySupport.Kind.PREFIX || kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX)) {
22.48 // String prefix = textForQuery.substring(dot+1);
22.49 // String in = textForQuery.substring(0, dot);
22.50
22.51 - elements = index.getClasses(textForQuery, kind, scope, null, true);
22.52 + elements = index.getClasses(textForQuery, kind, null, true);
22.53 for (IndexedElement element : elements) {
22.54 result.add(new PythonSymbol(element, helper));
22.55 }
22.56 @@ -77,22 +77,23 @@
22.57 return result;
22.58 }
22.59
22.60 - public Set<? extends Descriptor> getSymbols(Index gsfIndex, String textForQuery, NameKind kind, EnumSet<SearchScope> scope, Helper helper) {
22.61 - PythonIndex index = PythonIndex.get(gsfIndex);
22.62 + @Override
22.63 + public Set<? extends Descriptor> getSymbols(Project prjct, String textForQuery, QuerySupport.Kind kind, Helper helper) {
22.64 + PythonIndex index = PythonIndex.get(prjct);
22.65 Set<PythonSymbol> result = new HashSet<PythonSymbol>();
22.66 Set<? extends IndexedElement> elements;
22.67
22.68 // TODO - do some filtering if you use ./#
22.69 // int dot = textForQuery.lastIndexOf('.');
22.70 - // if (dot != -1 && (kind == NameKind.PREFIX || kind == NameKind.CASE_INSENSITIVE_PREFIX)) {
22.71 + // if (dot != -1 && (kind == QuerySupport.Kind.PREFIX || kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX)) {
22.72 // String prefix = textForQuery.substring(dot+1);
22.73 // String in = textForQuery.substring(0, dot);
22.74
22.75 - elements = index.getAllMembers(textForQuery, kind, scope, null, true);
22.76 + elements = index.getAllMembers(textForQuery, kind, null, true);
22.77 for (IndexedElement element : elements) {
22.78 result.add(new PythonSymbol(element, helper));
22.79 }
22.80 - elements = index.getClasses(textForQuery, kind, scope, null, true);
22.81 + elements = index.getClasses(textForQuery, kind, null, true);
22.82 for (IndexedElement element : elements) {
22.83 result.add(new PythonSymbol(element, helper));
22.84 }
22.85 @@ -187,12 +188,12 @@
22.86
22.87 @Override
22.88 public void open() {
22.89 - CompilationInfo[] infoRet = new CompilationInfo[1];
22.90 - PythonTree node = PythonAstUtils.getForeignNode(element, infoRet);
22.91 + PythonParserResult[] parserResultRet = new PythonParserResult[1];
22.92 + PythonTree node = PythonAstUtils.getForeignNode(element, parserResultRet);
22.93
22.94 if (node != null) {
22.95 int astOffset = PythonAstUtils.getRange(node).getStart();
22.96 - int lexOffset = PythonLexerUtils.getLexerOffset(infoRet[0], astOffset);
22.97 + int lexOffset = PythonLexerUtils.getLexerOffset(parserResultRet[0], astOffset);
22.98 if (lexOffset == -1) {
22.99 lexOffset = 0;
22.100 }
23.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonIndexer.java Sun Jan 04 13:11:53 2015 -0600
23.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonIndexer.java Sun Feb 01 15:02:07 2015 -0800
23.3 @@ -39,20 +39,21 @@
23.4 import java.util.HashMap;
23.5 import java.util.List;
23.6 import java.util.Map;
23.7 +import java.util.logging.Level;
23.8 +import java.util.logging.Logger;
23.9 import java.util.regex.Matcher;
23.10 import java.util.regex.Pattern;
23.11 import javax.swing.text.BadLocationException;
23.12 import org.netbeans.editor.BaseDocument;
23.13 -import org.netbeans.modules.gsf.api.IndexDocument;
23.14 -import org.netbeans.modules.gsf.api.IndexDocumentFactory;
23.15 -import org.netbeans.modules.gsf.api.Indexer;
23.16 -import org.netbeans.modules.gsf.api.Parser.Job;
23.17 -import org.netbeans.modules.gsf.api.ParserFile;
23.18 -import org.netbeans.modules.gsf.api.ParserResult;
23.19 -import org.netbeans.modules.gsf.api.SourceFileReader;
23.20 -import org.netbeans.modules.gsf.spi.DefaultParseListener;
23.21 -import org.netbeans.modules.gsf.spi.DefaultParserFile;
23.22 -import org.netbeans.modules.gsf.spi.GsfUtilities;
23.23 +import org.netbeans.modules.csl.spi.GsfUtilities;
23.24 +import org.netbeans.modules.csl.spi.ParserResult;
23.25 +import org.netbeans.modules.parsing.api.Snapshot;
23.26 +import org.netbeans.modules.parsing.spi.Parser;
23.27 +import org.netbeans.modules.parsing.spi.indexing.Context;
23.28 +import org.netbeans.modules.parsing.spi.indexing.EmbeddingIndexer;
23.29 +import org.netbeans.modules.parsing.spi.indexing.Indexable;
23.30 +import org.netbeans.modules.parsing.spi.indexing.support.IndexDocument;
23.31 +import org.netbeans.modules.parsing.spi.indexing.support.IndexingSupport;
23.32 import org.netbeans.modules.python.api.PythonPlatform;
23.33 import org.netbeans.modules.python.api.PythonPlatformManager;
23.34 import org.netbeans.modules.python.editor.elements.IndexedElement;
23.35 @@ -90,7 +91,9 @@
23.36 * Here I need to pick up all 3 signatures!
23.37 * @author Tor Norbye
23.38 */
23.39 -public class PythonIndexer implements Indexer {
23.40 +public class PythonIndexer extends EmbeddingIndexer {
23.41 + public static final String NAME = "PythonIndexer";
23.42 + public static final int VERSION = 1;
23.43 public static boolean PREINDEXING = Boolean.getBoolean("gsf.preindexing"); // NOI18N
23.44 public static final String FIELD_MEMBER = "member"; //NOI18N
23.45 public static final String FIELD_MODULE_NAME = "module"; //NOI18N
23.46 @@ -104,13 +107,35 @@
23.47 private FileObject prevParent;
23.48 private boolean prevResult;
23.49
23.50 - public boolean isIndexable(ParserFile file) {
23.51 - String extension = file.getExtension();
23.52 + public static boolean isIndexable(Indexable indexable, Snapshot snapshot) {
23.53 + FileObject fo = snapshot.getSource().getFileObject();
23.54 + String extension = fo.getExt();
23.55 + if ("py".equals(extension)) { // NOI18N
23.56 + return true;
23.57 + }
23.58 +
23.59 + if ("rst".equals(extension)) { // NOI18N
23.60 + // Index restructured text if it looks like it contains Python library
23.61 + // definitions
23.62 + return true;
23.63 + }
23.64 +
23.65 + if ("egg".equals(extension)) { // NOI18N
23.66 + return true;
23.67 + }
23.68 +
23.69 + return false;
23.70 + }
23.71 +
23.72 +
23.73 + public boolean isIndexable(Snapshot file) {
23.74 + FileObject fo = file.getSource().getFileObject();
23.75 + String extension = fo.getExt();
23.76 if ("py".equals(extension)) { // NOI18N
23.77
23.78 // Skip "test" folders under lib... Lots of weird files there
23.79 // and we don't want to pollute the index with them
23.80 - File parent = file.getFile().getParentFile();
23.81 + FileObject parent = fo.getParent();
23.82
23.83 if (parent != null && parent.getName().equals("test")) { // NOI18N
23.84 // Make sure it's really a lib folder, we want to include the
23.85 @@ -118,10 +143,6 @@
23.86
23.87 // Avoid double-indexing files that have multiple versions - e.g. foo.js and foo-min.js
23.88 // or foo.uncompressed
23.89 - FileObject fo = file.getFileObject();
23.90 - if (fo == null) {
23.91 - return true;
23.92 - }
23.93 FileObject parentFo = fo.getParent();
23.94 if (prevParent == parentFo) {
23.95 return prevResult;
23.96 @@ -159,22 +180,36 @@
23.97 return false;
23.98 }
23.99
23.100 - public List<IndexDocument> index(ParserResult result, IndexDocumentFactory factory) throws IOException {
23.101 + @Override
23.102 + protected void index(Indexable indexable, Parser.Result result, Context context) {
23.103 PythonParserResult parseResult = (PythonParserResult)result;
23.104 if (parseResult == null) {
23.105 - return Collections.emptyList();
23.106 + return;
23.107 }
23.108 - String extension = result.getFile().getNameExt();
23.109 +
23.110 + IndexingSupport support;
23.111 + try {
23.112 + support = IndexingSupport.getInstance(context);
23.113 + } catch (IOException ioe) {
23.114 + LOG.log(Level.WARNING, null, ioe);
23.115 + return;
23.116 + }
23.117 +
23.118 + support.removeDocuments(indexable);
23.119 +
23.120 + FileObject fileObject = result.getSnapshot().getSource().getFileObject();
23.121 + String extension = fileObject.getNameExt();
23.122
23.123 if (extension.endsWith(".rst")) { // NOI18N
23.124 - return scanRst(result.getFile().getFileObject(), factory, null);
23.125 + scanRst(fileObject, indexable, support, null);
23.126 } else if (extension.endsWith(".egg")) { // NOI18N
23.127 - return scanEgg(result, factory);
23.128 + scanEgg(fileObject, indexable, parseResult, support);
23.129 } else {
23.130 // Normal python file
23.131 - return new IndexTask(parseResult, factory).scan();
23.132 + new IndexTask(parseResult, support).scan();
23.133 }
23.134 }
23.135 + private static final Logger LOG = Logger.getLogger(PythonIndexer.class.getName());
23.136
23.137 public boolean acceptQueryPath(String url) {
23.138 return url.indexOf("jsstubs") == -1; // NOI18N
23.139 @@ -224,20 +259,20 @@
23.140
23.141 private static class IndexTask {
23.142 private PythonParserResult result;
23.143 - private ParserFile file;
23.144 - private IndexDocumentFactory factory;
23.145 + private FileObject file;
23.146 + private IndexingSupport support;
23.147 private List<IndexDocument> documents = new ArrayList<IndexDocument>();
23.148 private String url;
23.149 private String module;
23.150 private SymbolTable symbolTable;
23.151 private String overrideUrl;
23.152
23.153 - private IndexTask(PythonParserResult result, IndexDocumentFactory factory) {
23.154 + private IndexTask(PythonParserResult result, IndexingSupport support) {
23.155 this.result = result;
23.156 - this.file = result.getFile();
23.157 - this.factory = factory;
23.158 + this.file = result.getSnapshot().getSource().getFileObject();
23.159 + this.support = support;
23.160
23.161 - module = PythonUtils.getModuleName(null, file);
23.162 + module = PythonUtils.getModuleName(file);
23.163 //PythonTree root = PythonAstUtils.getRoot(result);
23.164 //if (root instanceof Module) {
23.165 // Str moduleDoc = PythonAstUtils.getDocumentationNode(root);
23.166 @@ -247,24 +282,18 @@
23.167 //}
23.168 }
23.169
23.170 - private IndexTask(PythonParserResult result, IndexDocumentFactory factory, String overrideUrl) {
23.171 - this(result, factory);
23.172 + private IndexTask(PythonParserResult result, IndexingSupport support, String overrideUrl) {
23.173 + this(result, support);
23.174 this.overrideUrl = overrideUrl;
23.175 }
23.176
23.177 public List<IndexDocument> scan() {
23.178 - FileObject fileObject = file.getFileObject();
23.179 - try {
23.180 - url = fileObject.getURL().toExternalForm();
23.181 -
23.182 - // Make relative URLs for urls in the libraries
23.183 - url = PythonIndex.getPreindexUrl(url);
23.184 - } catch (IOException ioe) {
23.185 - Exceptions.printStackTrace(ioe);
23.186 - }
23.187 + url = file.toURL().toExternalForm();
23.188 + // Make relative URLs for urls in the libraries
23.189 + url = PythonIndex.getPreindexUrl(url);
23.190
23.191 IndexDocument doc = createDocument();
23.192 - doc.addPair(FIELD_MODULE_NAME, module, true);
23.193 + doc.addPair(FIELD_MODULE_NAME, module, true, true);
23.194
23.195 String moduleAttrs = null;
23.196 if (url.startsWith(PythonIndex.CLUSTER_URL) || url.startsWith(PythonIndex.PYTHONHOME_URL)) {
23.197 @@ -283,7 +312,7 @@
23.198 }
23.199 }
23.200 if (moduleAttrs != null) {
23.201 - doc.addPair(FIELD_MODULE_ATTR_NAME, moduleAttrs, false); // NOI18N
23.202 + doc.addPair(FIELD_MODULE_ATTR_NAME, moduleAttrs, false, true);
23.203 }
23.204
23.205 PythonTree root = PythonAstUtils.getRoot(result);
23.206 @@ -306,7 +335,7 @@
23.207 StringBuilder sig = new StringBuilder();
23.208 sig.append(name);
23.209 appendFlags(sig, 'C', sym, 0);
23.210 - doc.addPair(FIELD_ITEM, sig.toString(), true);
23.211 + doc.addPair(FIELD_ITEM, sig.toString(), true, true);
23.212
23.213 if (sym.node instanceof ClassDef) {
23.214 assert sym.node instanceof ClassDef : sym.node;
23.215 @@ -323,24 +352,24 @@
23.216 assert sym.node instanceof FunctionDef : sym.node;
23.217 FunctionDef def = (FunctionDef)sym.node;
23.218 String sig = computeFunctionSig(name, def, sym);
23.219 - doc.addPair(FIELD_ITEM, sig, true);
23.220 + doc.addPair(FIELD_ITEM, sig, true, true);
23.221 } else if (sym.isImported()) {
23.222 if (!"*".equals(name)) { // NOI18N
23.223 StringBuilder sig = new StringBuilder();
23.224 sig.append(name);
23.225 appendFlags(sig, 'I', sym, 0);
23.226 - doc.addPair(FIELD_ITEM, sig.toString(), true);
23.227 + doc.addPair(FIELD_ITEM, sig.toString(), true, true);
23.228 }
23.229 } else if (sym.isGeneratorExp()) {
23.230 StringBuilder sig = new StringBuilder();
23.231 sig.append(name);
23.232 appendFlags(sig, 'G', sym, 0);
23.233 - doc.addPair(FIELD_ITEM, sig.toString(), true);
23.234 + doc.addPair(FIELD_ITEM, sig.toString(), true, true);
23.235 } else if (sym.isData()) {
23.236 StringBuilder sig = new StringBuilder();
23.237 sig.append(name);
23.238 appendFlags(sig, 'D', sym, 0);
23.239 - doc.addPair(FIELD_ITEM, sig.toString(), true);
23.240 + doc.addPair(FIELD_ITEM, sig.toString(), true, true);
23.241 } else {
23.242 // XXX what the heck is this??
23.243 }
23.244 @@ -351,7 +380,7 @@
23.245
23.246 private void indexClass(String className, SymInfo classSym, ClassDef clz) {
23.247 IndexDocument classDocument = createDocument();
23.248 - classDocument.addPair(FIELD_IN, module, true);
23.249 + classDocument.addPair(FIELD_IN, module, true, true);
23.250
23.251 // Superclass
23.252 List<expr> bases = clz.getInternalBases();
23.253 @@ -359,18 +388,18 @@
23.254 for (expr base : bases) {
23.255 String extendsName = PythonAstUtils.getExprName(base);
23.256 if (extendsName != null) {
23.257 - classDocument.addPair(FIELD_EXTENDS_NAME, extendsName, true);
23.258 + classDocument.addPair(FIELD_EXTENDS_NAME, extendsName, true, true);
23.259 }
23.260 }
23.261 }
23.262
23.263 - classDocument.addPair(FIELD_CLASS_NAME, className, true);
23.264 + classDocument.addPair(FIELD_CLASS_NAME, className, true, true);
23.265
23.266 if (classSym.isPrivate()) {
23.267 // TODO - store Documented, Deprecated, DocOnly, etc.
23.268 - classDocument.addPair(FIELD_CLASS_ATTR_NAME, IndexedElement.encode(IndexedElement.PRIVATE), false);
23.269 + classDocument.addPair(FIELD_CLASS_ATTR_NAME, IndexedElement.encode(IndexedElement.PRIVATE), false, true);
23.270 }
23.271 - classDocument.addPair(FIELD_CASE_INSENSITIVE_CLASS_NAME, className.toLowerCase(), true);
23.272 + classDocument.addPair(FIELD_CASE_INSENSITIVE_CLASS_NAME, className.toLowerCase(), true, true);
23.273
23.274 //Str doc = PythonAstUtils.getDocumentationNode(clz);
23.275 //if (doc != null) {
23.276 @@ -397,7 +426,7 @@
23.277 StringBuilder sig = new StringBuilder();
23.278 sig.append(name);
23.279 appendFlags(sig, 'C', sym, 0);
23.280 - classDocument.addPair(FIELD_ITEM, sig.toString(), true);
23.281 + classDocument.addPair(FIELD_ITEM, sig.toString(), true, true);
23.282
23.283 } else if (sym.isFunction() && sym.node instanceof FunctionDef) {
23.284 if (sym.node instanceof Name) {
23.285 @@ -405,17 +434,17 @@
23.286 }
23.287 FunctionDef def = (FunctionDef)sym.node;
23.288 String sig = computeFunctionSig(name, def, sym);
23.289 - classDocument.addPair(FIELD_MEMBER, sig, true);
23.290 + classDocument.addPair(FIELD_MEMBER, sig, true, true);
23.291 } else if (sym.isData()) {
23.292 StringBuilder sig = new StringBuilder();
23.293 sig.append(name);
23.294 appendFlags(sig, 'D', sym, 0);
23.295 - classDocument.addPair(FIELD_MEMBER, sig.toString(), true);
23.296 + classDocument.addPair(FIELD_MEMBER, sig.toString(), true, true);
23.297 } else if (sym.isMember()) {
23.298 StringBuilder sig = new StringBuilder();
23.299 sig.append(name);
23.300 appendFlags(sig, 'A', sym, 0);
23.301 - classDocument.addPair(FIELD_MEMBER, sig.toString(), true);
23.302 + classDocument.addPair(FIELD_MEMBER, sig.toString(), true, true);
23.303 } else if (!sym.isBound()) {
23.304 continue;
23.305 } else {
23.306 @@ -434,7 +463,7 @@
23.307 StringBuilder sig = new StringBuilder();
23.308 sig.append(name);
23.309 appendFlags(sig, 'C', sym, 0);
23.310 - classDocument.addPair(FIELD_ITEM, sig.toString(), true);
23.311 + classDocument.addPair(FIELD_ITEM, sig.toString(), true, true);
23.312
23.313 } else if (sym.isFunction() && sym.node instanceof FunctionDef) {
23.314 if (sym.node instanceof Name) {
23.315 @@ -442,17 +471,17 @@
23.316 }
23.317 FunctionDef def = (FunctionDef)sym.node;
23.318 String sig = computeFunctionSig(name, def, sym);
23.319 - classDocument.addPair(FIELD_MEMBER, sig, true);
23.320 + classDocument.addPair(FIELD_MEMBER, sig, true, true);
23.321 } else if (sym.isData()) {
23.322 StringBuilder sig = new StringBuilder();
23.323 sig.append(name);
23.324 appendFlags(sig, 'D', sym, 0);
23.325 - classDocument.addPair(FIELD_MEMBER, sig.toString(), true);
23.326 + classDocument.addPair(FIELD_MEMBER, sig.toString(), true, true);
23.327 } else if (sym.isMember()) {
23.328 StringBuilder sig = new StringBuilder();
23.329 sig.append(name);
23.330 appendFlags(sig, 'A', sym, 0);
23.331 - classDocument.addPair(FIELD_MEMBER, sig.toString(), true);
23.332 + classDocument.addPair(FIELD_MEMBER, sig.toString(), true, true);
23.333 } else if (!sym.isBound()) {
23.334 continue;
23.335 } else {
23.336 @@ -466,7 +495,7 @@
23.337
23.338 // TODO - what about nested functions?
23.339 private IndexDocument createDocument() {
23.340 - IndexDocument doc = factory.createDocument(DEFAULT_DOC_SIZE, overrideUrl);
23.341 + IndexDocument doc = support.createDocument(file);
23.342 documents.add(doc);
23.343
23.344 return doc;
23.345 @@ -637,11 +666,11 @@
23.346 }
23.347 }
23.348
23.349 - private List<IndexDocument> scanRst(FileObject fo, IndexDocumentFactory factory, String overrideUrl) {
23.350 + private List<IndexDocument> scanRst(FileObject fo, Indexable indexable, IndexingSupport support, String overrideUrl) {
23.351 List<CachedIndexDocument> documents = new ArrayList<CachedIndexDocument>();
23.352
23.353 List<IndexDocument> docs = new ArrayList<IndexDocument>();
23.354 -
23.355 +
23.356 if (fo != null) {
23.357 String module = fo.getNameExt();
23.358 assert module.endsWith(".rst"); // NOI18N
23.359 @@ -1079,10 +1108,11 @@
23.360 // because I want to modify the documents after adding documents and pairs.
23.361 for (CachedIndexDocument cid : documents) {
23.362 List<CachedIndexDocumentEntry> entries = cid.entries;
23.363 - IndexDocument indexedDoc = factory.createDocument(entries.size(), overrideUrl);
23.364 + IndexDocument indexedDoc = support.createDocument(indexable);
23.365 +// IndexDocument indexedDoc = support.createDocument(entries.size(), overrideUrl);
23.366 docs.add(indexedDoc);
23.367 for (CachedIndexDocumentEntry entry : entries) {
23.368 - indexedDoc.addPair(entry.key, entry.value, entry.index);
23.369 + indexedDoc.addPair(entry.key, entry.value, true, true); // XXX indexable and stored ???
23.370 }
23.371 }
23.372 }
23.373 @@ -1274,22 +1304,19 @@
23.374 }
23.375 }
23.376
23.377 - private List<IndexDocument> scanEgg(ParserResult result, IndexDocumentFactory factory) {
23.378 + private List<IndexDocument> scanEgg(FileObject fo, Indexable indexable, ParserResult result, IndexingSupport support) {
23.379 List<IndexDocument> documents = new ArrayList<IndexDocument>();
23.380
23.381 - FileObject fo = result.getFile().getFileObject();
23.382 if (fo == null) {
23.383 return documents;
23.384 }
23.385
23.386 try {
23.387 - String s = fo.getURL().toExternalForm() + "!"; // NOI18N
23.388 + String s = fo.toURL().toExternalForm() + "!"; // NOI18N
23.389 URL u = new URL("jar:" + s); // NOI18N
23.390 FileObject root = URLMapper.findFileObject(u);
23.391 String rootUrl = PythonIndex.getPreindexUrl(u.toExternalForm());
23.392 - indexScriptDocRecursively(factory, documents, root, rootUrl);
23.393 - } catch (FileStateInvalidException ex) {
23.394 - Exceptions.printStackTrace(ex);
23.395 + indexScriptDocRecursively(support, documents, root, rootUrl);
23.396 } catch (MalformedURLException ex) {
23.397 Exceptions.printStackTrace(ex);
23.398 }
23.399 @@ -1301,46 +1328,46 @@
23.400 * Method which recursively indexes directory trees, such as the yui/ folder
23.401 * for example
23.402 */
23.403 - private void indexScriptDocRecursively(IndexDocumentFactory factory, List<IndexDocument> documents, final FileObject fo, String url) {
23.404 + private void indexScriptDocRecursively(IndexingSupport support, List<IndexDocument> documents, final FileObject fo, String url) {
23.405 if (fo.isFolder()) {
23.406 for (FileObject c : fo.getChildren()) {
23.407 - indexScriptDocRecursively(factory, documents, c, url + "/" + c.getNameExt()); // NOI18N
23.408 + indexScriptDocRecursively(support, documents, c, url + "/" + c.getNameExt()); // NOI18N
23.409 }
23.410 return;
23.411 }
23.412
23.413 String ext = fo.getExt();
23.414
23.415 - if ("py".equals(ext)) { // NOI18N
23.416 - DefaultParseListener listener = new DefaultParseListener();
23.417 - List<ParserFile> files = Collections.<ParserFile>singletonList(new DefaultParserFile(fo, null, false));
23.418 - SourceFileReader reader = new SourceFileReader() {
23.419 - public CharSequence read(ParserFile file) throws IOException {
23.420 - BaseDocument doc = GsfUtilities.getDocument(fo, true);
23.421 - if (doc != null) {
23.422 - try {
23.423 - return doc.getText(0, doc.getLength());
23.424 - } catch (BadLocationException ex) {
23.425 - Exceptions.printStackTrace(ex);
23.426 - }
23.427 - }
23.428 -
23.429 - return "";
23.430 - }
23.431 -
23.432 - public int getCaretOffset(ParserFile file) {
23.433 - return -1;
23.434 - }
23.435 - };
23.436 - Job job = new Job(files, listener, reader, null);
23.437 - new PythonParser().parseFiles(job);
23.438 - ParserResult parserResult = listener.getParserResult();
23.439 - if (parserResult != null && parserResult.isValid()) {
23.440 - documents.addAll(new IndexTask((PythonParserResult)parserResult, factory, url).scan());
23.441 - }
23.442 - } else if ("rst".equals(ext)) { // NOI18N
23.443 - documents.addAll(scanRst(fo, factory, url));
23.444 - }
23.445 +// if ("py".equals(ext)) { // NOI18N
23.446 +// DefaultParseListener listener = new DefaultParseListener();
23.447 +// List<ParserFile> files = Collections.<ParserFile>singletonList(new DefaultParserFile(fo, null, false));
23.448 +// SourceFileReader reader = new SourceFileReader() {
23.449 +// public CharSequence read(ParserFile file) throws IOException {
23.450 +// BaseDocument doc = GsfUtilities.getDocument(fo, true);
23.451 +// if (doc != null) {
23.452 +// try {
23.453 +// return doc.getText(0, doc.getLength());
23.454 +// } catch (BadLocationException ex) {
23.455 +// Exceptions.printStackTrace(ex);
23.456 +// }
23.457 +// }
23.458 +//
23.459 +// return "";
23.460 +// }
23.461 +//
23.462 +// public int getCaretOffset(ParserFile file) {
23.463 +// return -1;
23.464 +// }
23.465 +// };
23.466 +// Job job = new Job(files, listener, reader, null);
23.467 +// new PythonParser().parseFiles(job);
23.468 +// ParserResult parserResult = listener.getParserResult();
23.469 +// if (parserResult != null && parserResult.isValid()) {
23.470 +// documents.addAll(new IndexTask((PythonParserResult)parserResult, support, url).scan());
23.471 +// }
23.472 +// } else if ("rst".equals(ext)) { // NOI18N
23.473 +// documents.addAll(scanRst(fo, support, url));
23.474 +// }
23.475 }
23.476
23.477 private FileObject getLibDir() {
24.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
24.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonIndexerFactory.java Sun Feb 01 15:02:07 2015 -0800
24.3 @@ -0,0 +1,47 @@
24.4 +/*
24.5 + * To change this license header, choose License Headers in Project Properties.
24.6 + * To change this template file, choose Tools | Templates
24.7 + * and open the template in the editor.
24.8 + */
24.9 +package org.netbeans.modules.python.editor;
24.10 +
24.11 +import org.netbeans.modules.parsing.api.Snapshot;
24.12 +import org.netbeans.modules.parsing.spi.indexing.Context;
24.13 +import org.netbeans.modules.parsing.spi.indexing.EmbeddingIndexer;
24.14 +import org.netbeans.modules.parsing.spi.indexing.EmbeddingIndexerFactory;
24.15 +import org.netbeans.modules.parsing.spi.indexing.Indexable;
24.16 +
24.17 +/**
24.18 + *
24.19 + * @author Ralph Benjamin Ruijs
24.20 + */
24.21 +public class PythonIndexerFactory extends EmbeddingIndexerFactory {
24.22 +
24.23 + @Override
24.24 + public EmbeddingIndexer createIndexer(Indexable indexable, Snapshot snapshot) {
24.25 + if(PythonIndexer.isIndexable(indexable, snapshot)) {
24.26 + return new PythonIndexer();
24.27 + }
24.28 + return null;
24.29 + }
24.30 +
24.31 + @Override
24.32 + public void filesDeleted(Iterable<? extends Indexable> indexables, Context context) {
24.33 +// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
24.34 + }
24.35 +
24.36 + @Override
24.37 + public void filesDirty(Iterable<? extends Indexable> arg0, Context arg1) {
24.38 +// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
24.39 + }
24.40 +
24.41 + @Override
24.42 + public String getIndexerName() {
24.43 + return PythonIndexer.NAME;
24.44 + }
24.45 +
24.46 + @Override
24.47 + public int getIndexVersion() {
24.48 + return PythonIndexer.VERSION;
24.49 + }
24.50 +}
25.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonInstantRename.java Sun Jan 04 13:11:53 2015 -0600
25.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonInstantRename.java Sun Feb 01 15:02:07 2015 -0800
25.3 @@ -36,9 +36,9 @@
25.4 import org.netbeans.api.lexer.Token;
25.5 import org.netbeans.api.lexer.TokenSequence;
25.6 import org.netbeans.editor.BaseDocument;
25.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
25.8 -import org.netbeans.modules.gsf.api.InstantRenamer;
25.9 -import org.netbeans.modules.gsf.api.OffsetRange;
25.10 +import org.netbeans.modules.csl.api.InstantRenamer;
25.11 +import org.netbeans.modules.csl.api.OffsetRange;
25.12 +import org.netbeans.modules.csl.spi.ParserResult;
25.13 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
25.14 import org.netbeans.modules.python.editor.lexer.PythonCommentTokenId;
25.15 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
25.16 @@ -54,7 +54,8 @@
25.17 * @author Tor Norbye
25.18 */
25.19 public class PythonInstantRename implements InstantRenamer {
25.20 - public boolean isRenameAllowed(CompilationInfo info, int caretOffset, String[] explanationRetValue) {
25.21 +
25.22 + public boolean isRenameAllowed(ParserResult info, int caretOffset, String[] explanationRetValue) {
25.23 if (findVarName(info, caretOffset) != null) {
25.24 return true;
25.25 }
25.26 @@ -79,8 +80,8 @@
25.27 return false;
25.28 }
25.29
25.30 - private TokenSequence<PythonCommentTokenId> findVarName(CompilationInfo info, int caretOffset) {
25.31 - Document document = info.getDocument();
25.32 + private TokenSequence<PythonCommentTokenId> findVarName(ParserResult info, int caretOffset) {
25.33 + Document document = info.getSnapshot().getSource().getDocument(false);
25.34 if (document != null) {
25.35 BaseDocument doc = (BaseDocument)document;
25.36 TokenSequence<? extends PythonTokenId> ts = PythonLexerUtils.getPositionedSequence(doc, caretOffset);
25.37 @@ -106,12 +107,12 @@
25.38 return null;
25.39 }
25.40
25.41 - public Set<OffsetRange> getRenameRegions(CompilationInfo info, int caretOffset) {
25.42 + public Set<OffsetRange> getRenameRegions(ParserResult info, int caretOffset) {
25.43 TokenSequence<PythonCommentTokenId> embedded = findVarName(info, caretOffset);
25.44 if (embedded != null) {
25.45 Token<PythonCommentTokenId> token = embedded.token();
25.46 String name = token.text().toString();
25.47 - Set<OffsetRange> offsets = PythonAstUtils.getAllOffsets(info, null, caretOffset, name, true);
25.48 + Set<OffsetRange> offsets = PythonAstUtils.getAllOffsets((PythonParserResult) info, null, caretOffset, name, true);
25.49 if (offsets != null) {
25.50 return offsets;
25.51 }
25.52 @@ -127,7 +128,7 @@
25.53 String name = null;
25.54 if (leaf instanceof Name) {
25.55 name = ((Name)leaf).getInternalId();
25.56 - Set<OffsetRange> offsets = PythonAstUtils.getAllOffsets(info, path, caretOffset, name, true);
25.57 + Set<OffsetRange> offsets = PythonAstUtils.getAllOffsets((PythonParserResult) info, path, caretOffset, name, true);
25.58 if (offsets != null) {
25.59 return offsets;
25.60 }
26.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonKeystrokeHandler.java Sun Jan 04 13:11:53 2015 -0600
26.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonKeystrokeHandler.java Sun Feb 01 15:02:07 2015 -0800
26.3 @@ -44,12 +44,13 @@
26.4 import org.netbeans.api.lexer.TokenSequence;
26.5 import org.netbeans.editor.BaseDocument;
26.6 import org.netbeans.editor.Utilities;
26.7 +import org.netbeans.modules.csl.api.EditorOptions;
26.8 +import org.netbeans.modules.csl.api.KeystrokeHandler;
26.9 +import org.netbeans.modules.csl.api.OffsetRange;
26.10 +import org.netbeans.modules.csl.spi.GsfUtilities;
26.11 +import org.netbeans.modules.csl.spi.ParserResult;
26.12 import org.netbeans.modules.editor.indent.api.IndentUtils;
26.13 -import org.netbeans.modules.gsf.api.CompilationInfo;
26.14 -import org.netbeans.modules.gsf.api.EditorOptions;
26.15 -import org.netbeans.modules.gsf.api.KeystrokeHandler;
26.16 -import org.netbeans.modules.gsf.api.OffsetRange;
26.17 -import org.netbeans.modules.gsf.spi.GsfUtilities;
26.18 +import org.netbeans.modules.python.api.PythonMIMEResolver;
26.19 import org.openide.util.Exceptions;
26.20 import org.python.antlr.PythonTree;
26.21
26.22 @@ -260,7 +261,7 @@
26.23 // The editor options code is calling methods on BaseOptions instead of looking in the settings map :(
26.24 //Boolean b = ((Boolean)Settings.getValue(doc.getKitClass(), SettingsNames.PAIR_CHARACTERS_COMPLETION));
26.25 //return b == null || b.booleanValue();
26.26 - EditorOptions options = EditorOptions.get(PythonTokenId.PYTHON_MIME_TYPE);
26.27 + EditorOptions options = EditorOptions.get(PythonMIMEResolver.PYTHON_MIME_TYPE);
26.28 if (options != null) {
26.29 return options.getMatchBrackets();
26.30 }
26.31 @@ -1259,7 +1260,7 @@
26.32 }
26.33 }
26.34
26.35 - public List<OffsetRange> findLogicalRanges(CompilationInfo info, int caretOffset) {
26.36 + public List<OffsetRange> findLogicalRanges(ParserResult info, int caretOffset) {
26.37 PythonTree root = PythonAstUtils.getRoot(info);
26.38 if (root != null) {
26.39 List<OffsetRange> ranges = new ArrayList<OffsetRange>();
26.40 @@ -1267,7 +1268,7 @@
26.41 OffsetRange prevRange = OffsetRange.NONE;
26.42 for (PythonTree node : path) {
26.43 OffsetRange astRange = PythonAstUtils.getRange(node);
26.44 - OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(info, astRange);
26.45 + OffsetRange lexRange = PythonLexerUtils.getLexerOffsets((PythonParserResult) info, astRange);
26.46 if (lexRange != OffsetRange.NONE) {
26.47 if (prevRange == OffsetRange.NONE ||
26.48 prevRange.getStart() > lexRange.getStart() ||
26.49 @@ -1278,7 +1279,7 @@
26.50 }
26.51 }
26.52
26.53 - int docLength = info.getDocument().getLength();
26.54 + int docLength = info.getSnapshot().getSource().getDocument(false).getLength();
26.55 if (prevRange == OffsetRange.NONE || prevRange.getStart() > 0 ||
26.56 prevRange.getEnd() < docLength) {
26.57 ranges.add(new OffsetRange(0, docLength));
27.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonLanguage.java Sun Jan 04 13:11:53 2015 -0600
27.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonLanguage.java Sun Feb 01 15:02:07 2015 -0800
27.3 @@ -31,24 +31,24 @@
27.4 package org.netbeans.modules.python.editor;
27.5
27.6 import java.io.File;
27.7 -import java.util.Collection;
27.8 -import java.util.Collections;
27.9 import org.netbeans.modules.python.editor.hints.PythonHintsProvider;
27.10 import org.netbeans.api.lexer.Language;
27.11 +import org.netbeans.modules.csl.api.CodeCompletionHandler;
27.12 +import org.netbeans.modules.csl.api.DeclarationFinder;
27.13 +import org.netbeans.modules.csl.api.Formatter;
27.14 +import org.netbeans.modules.csl.api.HintsProvider;
27.15 +import org.netbeans.modules.csl.api.IndexSearcher;
27.16 +import org.netbeans.modules.csl.api.InstantRenamer;
27.17 +import org.netbeans.modules.csl.api.KeystrokeHandler;
27.18 +import org.netbeans.modules.csl.api.OccurrencesFinder;
27.19 +import org.netbeans.modules.csl.api.SemanticAnalyzer;
27.20 +import org.netbeans.modules.csl.api.StructureScanner;
27.21 +import org.netbeans.modules.csl.spi.DefaultLanguageConfig;
27.22 +import org.netbeans.modules.csl.spi.LanguageRegistration;
27.23 +import org.netbeans.modules.parsing.spi.Parser;
27.24 +import org.netbeans.modules.parsing.spi.indexing.EmbeddingIndexerFactory;
27.25 +import org.netbeans.modules.python.api.PythonMIMEResolver;
27.26 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
27.27 -import org.netbeans.modules.gsf.api.CodeCompletionHandler;
27.28 -import org.netbeans.modules.gsf.api.DeclarationFinder;
27.29 -import org.netbeans.modules.gsf.api.Formatter;
27.30 -import org.netbeans.modules.gsf.api.HintsProvider;
27.31 -import org.netbeans.modules.gsf.api.IndexSearcher;
27.32 -import org.netbeans.modules.gsf.api.Indexer;
27.33 -import org.netbeans.modules.gsf.api.InstantRenamer;
27.34 -import org.netbeans.modules.gsf.api.KeystrokeHandler;
27.35 -import org.netbeans.modules.gsf.api.OccurrencesFinder;
27.36 -import org.netbeans.modules.gsf.api.Parser;
27.37 -import org.netbeans.modules.gsf.api.SemanticAnalyzer;
27.38 -import org.netbeans.modules.gsf.api.StructureScanner;
27.39 -import org.netbeans.modules.gsf.spi.DefaultLanguageConfig;
27.40 import org.openide.filesystems.FileObject;
27.41 import org.openide.filesystems.FileUtil;
27.42 import org.openide.modules.InstalledFileLocator;
27.43 @@ -58,6 +58,7 @@
27.44 * @author alley
27.45 * @author Tor Norbye
27.46 */
27.47 +@LanguageRegistration(mimeType=PythonMIMEResolver.PYTHON_MIME_TYPE)
27.48 public class PythonLanguage extends DefaultLanguageConfig {
27.49 private static FileObject jsStubsFO;
27.50
27.51 @@ -74,10 +75,12 @@
27.52 c == '_';
27.53 }
27.54
27.55 + @Override
27.56 public Language getLexerLanguage() {
27.57 return PythonTokenId.language();
27.58 }
27.59
27.60 + @Override
27.61 public String getDisplayName() {
27.62 return "Python";
27.63 }
27.64 @@ -107,7 +110,7 @@
27.65 public SemanticAnalyzer getSemanticAnalyzer() {
27.66 return new PythonSemanticHighlighter();
27.67 }
27.68 -
27.69 +
27.70 @Override
27.71 public KeystrokeHandler getKeystrokeHandler() {
27.72 return new PythonKeystrokeHandler();
27.73 @@ -134,8 +137,8 @@
27.74 }
27.75
27.76 @Override
27.77 - public Indexer getIndexer() {
27.78 - return new PythonIndexer();
27.79 + public EmbeddingIndexerFactory getIndexerFactory() {
27.80 + return new PythonIndexerFactory();
27.81 }
27.82
27.83 @Override
27.84 @@ -168,12 +171,6 @@
27.85 return new PythonFormatter();
27.86 }
27.87
27.88 - @Override
27.89 - public Collection<FileObject> getCoreLibraries() {
27.90 - return Collections.singletonList(getPythonStubs());
27.91 - }
27.92 -
27.93 -
27.94 // TODO - add classpath recognizer for these ? No, don't need go to declaration inside these files...
27.95 public static FileObject getPythonStubs() {
27.96 if (jsStubsFO == null) {
28.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonOccurrencesMarker.java Sun Jan 04 13:11:53 2015 -0600
28.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonOccurrencesMarker.java Sun Feb 01 15:02:07 2015 -0800
28.3 @@ -43,10 +43,13 @@
28.4 import org.netbeans.api.lexer.TokenSequence;
28.5 import org.netbeans.editor.BaseDocument;
28.6 import org.netbeans.editor.Utilities;
28.7 -import org.netbeans.modules.gsf.api.ColoringAttributes;
28.8 -import org.netbeans.modules.gsf.api.CompilationInfo;
28.9 -import org.netbeans.modules.gsf.api.OccurrencesFinder;
28.10 -import org.netbeans.modules.gsf.api.OffsetRange;
28.11 +import org.netbeans.modules.csl.api.ColoringAttributes;
28.12 +import org.netbeans.modules.csl.api.OccurrencesFinder;
28.13 +import org.netbeans.modules.csl.api.OffsetRange;
28.14 +import org.netbeans.modules.csl.spi.ParserResult;
28.15 +import org.netbeans.modules.parsing.spi.Parser.Result;
28.16 +import org.netbeans.modules.parsing.spi.Scheduler;
28.17 +import org.netbeans.modules.parsing.spi.SchedulerEvent;
28.18 import org.netbeans.modules.python.editor.lexer.PythonCommentTokenId;
28.19 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
28.20 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
28.21 @@ -69,7 +72,7 @@
28.22 *
28.23 * @author Tor Norbye
28.24 */
28.25 -public class PythonOccurrencesMarker implements OccurrencesFinder {
28.26 +public class PythonOccurrencesMarker extends OccurrencesFinder<PythonParserResult> {
28.27 private boolean cancelled;
28.28 private int caretPosition;
28.29 private Map<OffsetRange, ColoringAttributes> occurrences;
28.30 @@ -99,23 +102,30 @@
28.31 this.caretPosition = position;
28.32 }
28.33
28.34 - public void run(CompilationInfo info) {
28.35 + @Override
28.36 + public int getPriority() {
28.37 + return 0;
28.38 + }
28.39 +
28.40 + @Override
28.41 + public Class<? extends Scheduler> getSchedulerClass() {
28.42 + return Scheduler.CURSOR_SENSITIVE_TASK_SCHEDULER;
28.43 + }
28.44 +
28.45 + @Override
28.46 + public void run(PythonParserResult info, SchedulerEvent event) {
28.47 resume();
28.48
28.49 if (isCancelled()) {
28.50 return;
28.51 }
28.52
28.53 - PythonParserResult ppr = PythonAstUtils.getParseResult(info);
28.54 - if (ppr == null) {
28.55 - return;
28.56 - }
28.57 - PythonTree root = PythonAstUtils.getRoot(ppr);
28.58 + PythonTree root = PythonAstUtils.getRoot(info);
28.59 if (root == null) {
28.60 return;
28.61 }
28.62
28.63 - int astOffset = PythonAstUtils.getAstOffset(info, caretPosition);
28.64 + int astOffset = PythonAstUtils.getAstOffset((ParserResult) info, caretPosition);
28.65 if (astOffset == -1) {
28.66 return;
28.67 }
28.68 @@ -126,13 +136,13 @@
28.69 return;
28.70 }
28.71 PythonTree closest = path.leaf();
28.72 - OffsetRange blankRange = ppr.getSanitizedRange();
28.73 + OffsetRange blankRange = info.getSanitizedRange();
28.74
28.75 if (blankRange.containsInclusive(astOffset)) {
28.76 closest = null;
28.77 }
28.78
28.79 - Document document = info.getDocument();
28.80 + Document document = info.getSnapshot().getSource().getDocument(false);
28.81 if (document == null) {
28.82 return;
28.83 }
28.84 @@ -155,7 +165,7 @@
28.85 if (id == PythonCommentTokenId.VARNAME) {
28.86 String name = token.text().toString();
28.87
28.88 - offsets = findNames(ppr, path, name, info, offsets);
28.89 + offsets = findNames(info, path, name, offsets);
28.90
28.91 int start = embedded.offset();
28.92 offsets.add(new OffsetRange(start, start + name.length()));
28.93 @@ -184,13 +194,13 @@
28.94 //addNodes(scopeNode != null ? scopeNode : root, name, highlights);
28.95 //closest = null;
28.96 String name = ((Name)closest).getInternalId();
28.97 - offsets = findNames(ppr, path, name, info, offsets);
28.98 + offsets = findNames(info, path, name, offsets);
28.99 } else if (closest instanceof Attribute) {
28.100 Attribute attr = (Attribute)closest;
28.101 offsets = findSameAttributes(info, root, attr);
28.102 } else if (closest instanceof Import || closest instanceof ImportFrom) {
28.103 // Try to find occurrences of an imported symbol
28.104 - offsets = findNameFromImport(caretPosition, ppr, path, info, offsets);
28.105 + offsets = findNameFromImport(caretPosition, info, path, offsets);
28.106 } else if ((closest instanceof FunctionDef || closest instanceof ClassDef) &&
28.107 PythonAstUtils.getNameRange(null, closest).containsInclusive(astOffset)) {
28.108 String name;
28.109 @@ -200,7 +210,7 @@
28.110 assert closest instanceof ClassDef;
28.111 name = ((ClassDef)closest).getInternalName();
28.112 }
28.113 - offsets = findNames(ppr, path, name, info, offsets);
28.114 + offsets = findNames(info, path, name, offsets);
28.115
28.116 if (offsets == null || offsets.size() == 0) {
28.117 if (closest instanceof FunctionDef) {
28.118 @@ -236,7 +246,7 @@
28.119 }
28.120 }
28.121 if (nearest != null) {
28.122 - OffsetRange range = PythonAstUtils.getNameRange(info, nearest);
28.123 + OffsetRange range = PythonAstUtils.getNameRange((PythonParserResult) info, nearest);
28.124 if (!range.containsInclusive(astOffset)) {
28.125 nearest = null;
28.126 }
28.127 @@ -300,9 +310,9 @@
28.128 private final FunctionDef def;
28.129 private final String name;
28.130 private final Set<OffsetRange> ranges = new HashSet<OffsetRange>();
28.131 - private final CompilationInfo info;
28.132 + private final PythonParserResult info;
28.133
28.134 - CallVisitor(CompilationInfo info, FunctionDef def, Call call) {
28.135 + CallVisitor(PythonParserResult info, FunctionDef def, Call call) {
28.136 this.info = info;
28.137 this.def = def;
28.138 this.call = call;
28.139 @@ -343,8 +353,8 @@
28.140 }
28.141 }
28.142
28.143 - private Set<OffsetRange> findNameFromImport(int lexOffset, PythonParserResult ppr, AstPath path, CompilationInfo info, Set<OffsetRange> offsets) {
28.144 - BaseDocument doc = (BaseDocument)info.getDocument();
28.145 + private Set<OffsetRange> findNameFromImport(int lexOffset, PythonParserResult ppr, AstPath path, Set<OffsetRange> offsets) {
28.146 + BaseDocument doc = (BaseDocument)ppr.getSnapshot().getSource().getDocument(false);
28.147 try {
28.148 doc.readLock();
28.149 String identifier = Utilities.getIdentifier(doc, lexOffset);
28.150 @@ -358,7 +368,7 @@
28.151 // TODO - determine if you're hovering over a whole module name instead of an imported
28.152 // symbol, and if so, work a bit harder...
28.153 if (identifier.length() > 0) {
28.154 - return findNames(ppr, path, identifier, info, offsets);
28.155 + return findNames(ppr, path, identifier, offsets);
28.156 }
28.157 } catch (BadLocationException ex) {
28.158 Exceptions.printStackTrace(ex);
28.159 @@ -369,12 +379,12 @@
28.160 return null;
28.161 }
28.162
28.163 - private Set<OffsetRange> findNames(PythonParserResult ppr, AstPath path, String name, CompilationInfo info, Set<OffsetRange> offsets) {
28.164 + private Set<OffsetRange> findNames(PythonParserResult ppr, AstPath path, String name, Set<OffsetRange> offsets) {
28.165 //offsets = PythonAstUtils.getLocalVarOffsets(info, scope, name);
28.166 - return PythonAstUtils.getAllOffsets(info, path, caretPosition, name, false);
28.167 + return PythonAstUtils.getAllOffsets(ppr, path, caretPosition, name, false);
28.168 }
28.169
28.170 - private Set<OffsetRange> findSameAttributes(CompilationInfo info, PythonTree root, Attribute attr) {
28.171 + private Set<OffsetRange> findSameAttributes(PythonParserResult info, PythonTree root, Attribute attr) {
28.172 List<PythonTree> result = new ArrayList<PythonTree>();
28.173 PythonAstUtils.addNodesByType(root, new Class[]{Attribute.class}, result);
28.174
28.175 @@ -397,7 +407,7 @@
28.176 OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(info, astRange);
28.177 if (name != null && (node instanceof Import || node instanceof ImportFrom)) {
28.178 // Try to find the exact spot
28.179 - lexRange = PythonLexerUtils.getImportNameOffset((BaseDocument)info.getDocument(), lexRange, node, name);
28.180 + lexRange = PythonLexerUtils.getImportNameOffset((BaseDocument)info.getSnapshot().getSource().getDocument(false), lexRange, node, name);
28.181 }
28.182 if (lexRange != OffsetRange.NONE) {
28.183 offsets.add(lexRange);
29.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonParser.java Sun Jan 04 13:11:53 2015 -0600
29.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonParser.java Sun Feb 01 15:02:07 2015 -0800
29.3 @@ -34,10 +34,20 @@
29.4 import java.io.InputStreamReader;
29.5 import java.util.ArrayList;
29.6 import java.util.List;
29.7 -import java.util.Properties;
29.8 import java.util.logging.Level;
29.9 import java.util.logging.Logger;
29.10 +import javax.swing.event.ChangeListener;
29.11 import javax.swing.text.BadLocationException;
29.12 +import org.netbeans.modules.csl.api.Severity;
29.13 +import org.netbeans.modules.csl.spi.DefaultError;
29.14 +import org.netbeans.modules.csl.api.Error;
29.15 +import org.netbeans.modules.csl.api.OffsetRange;
29.16 +import org.netbeans.modules.csl.spi.GsfUtilities;
29.17 +import org.netbeans.modules.parsing.api.Snapshot;
29.18 +import org.netbeans.modules.parsing.api.Task;
29.19 +import org.netbeans.modules.parsing.spi.Parser;
29.20 +import org.netbeans.modules.parsing.spi.SourceModificationEvent;
29.21 +import org.openide.filesystems.FileObject;
29.22 import org.python.antlr.runtime.ANTLRStringStream;
29.23 import org.python.antlr.runtime.BaseRecognizer;
29.24 import org.python.antlr.runtime.BitSet;
29.25 @@ -47,19 +57,7 @@
29.26 import org.python.antlr.runtime.Lexer;
29.27 import org.python.antlr.runtime.MismatchedTokenException;
29.28 import org.python.antlr.runtime.RecognitionException;
29.29 -import org.netbeans.modules.gsf.api.Error;
29.30 -import org.netbeans.modules.gsf.api.OffsetRange;
29.31 -import org.netbeans.modules.gsf.api.Parser;
29.32 -import org.netbeans.modules.gsf.api.PositionManager;
29.33
29.34 -import org.netbeans.modules.gsf.api.ParseEvent;
29.35 -import org.netbeans.modules.gsf.api.ParseListener;
29.36 -import org.netbeans.modules.gsf.api.ParserFile;
29.37 -import org.netbeans.modules.gsf.api.Severity;
29.38 -import org.netbeans.modules.gsf.api.SourceFileReader;
29.39 -import org.netbeans.modules.gsf.api.TranslatedSource;
29.40 -import org.netbeans.modules.gsf.spi.DefaultError;
29.41 -import org.netbeans.modules.gsf.spi.GsfUtilities;
29.42 import org.openide.filesystems.FileUtil;
29.43 import org.openide.util.Exceptions;
29.44 import org.python.antlr.BaseParser;
29.45 @@ -82,13 +80,15 @@
29.46 * @author Frank Wierzbicki
29.47 * @author Tor Norbye
29.48 */
29.49 -public class PythonParser implements Parser {
29.50 +public class PythonParser extends Parser {
29.51 /** For unit tests such that they can make sure we didn't have a parser abort */
29.52 static Throwable runtimeException;
29.53
29.54 static {
29.55 org.python.core.PySystemState.initialize();
29.56 }
29.57 +
29.58 + private Result lastResult;
29.59
29.60 public mod file_input(CharStream charStream, String fileName) throws RecognitionException {
29.61 ListErrorHandler eh = new ListErrorHandler();
29.62 @@ -107,12 +107,41 @@
29.63 return tree;
29.64 }
29.65
29.66 + @Override
29.67 + public void addChangeListener(ChangeListener changeListener) {}
29.68 +
29.69 + @Override
29.70 + public void removeChangeListener(ChangeListener changeListener) {}
29.71 +
29.72 public PythonTree parse(InputStream istream, String fileName) throws Exception {
29.73 InputStreamReader reader = new InputStreamReader(istream, "ISO-8859-1");
29.74 return file_input(new ANTLRReaderStream(reader), fileName);
29.75 }
29.76 +
29.77 + @Override
29.78 + public final Result getResult(Task task) throws org.netbeans.modules.parsing.spi.ParseException {
29.79 + return lastResult;
29.80 + }
29.81 +
29.82 + private static final Logger LOG = Logger.getLogger(PythonParser.class.getName());
29.83
29.84 - public PythonParserResult parse(final Context context, Sanitize sanitizing) throws Exception {
29.85 + @Override
29.86 + public void parse(Snapshot snapshot, Task task, SourceModificationEvent event) throws org.netbeans.modules.parsing.spi.ParseException {
29.87 + Context context = new Context();
29.88 + context.snapshot = snapshot;
29.89 + context.event = event;
29.90 + context.task = task;
29.91 + context.caretOffset = GsfUtilities.getLastKnownCaretOffset(snapshot, event);
29.92 + context.source = snapshot.getText().toString();
29.93 + context.file = snapshot.getSource().getFileObject();
29.94 + /* Let's not sanitize ;-) Would be great if we could have a more robust parser
29.95 + if (context.caretOffset != -1) {
29.96 + context.sanitized = Sanitize.EDITED_DOT;
29.97 + }
29.98 + */
29.99 + lastResult = parse(context, context.sanitized);
29.100 + }
29.101 + public PythonParserResult parse(final Context context, Sanitize sanitizing) {
29.102 boolean sanitizedSource = false;
29.103 String sourceCode = context.source;
29.104 if (!((sanitizing == Sanitize.NONE) || (sanitizing == Sanitize.NEVER))) {
29.105 @@ -134,7 +163,7 @@
29.106 }
29.107
29.108 final List<Error> errors = new ArrayList<Error>();
29.109 - final ParserFile file = context.file;
29.110 + final FileObject file = context.file;
29.111 try {
29.112 String fileName = file.getNameExt();
29.113 // TODO - sniff file headers etc. Frank's comment:
29.114 @@ -151,7 +180,7 @@
29.115 ListErrorHandler errorHandler = new ListErrorHandler() {
29.116 @Override
29.117 public void error(String message, PythonTree t) {
29.118 - errors.add(new DefaultError(null, message, null, file.getFileObject(), t.getCharStartIndex(), t.getCharStopIndex(), Severity.ERROR));
29.119 + errors.add(new DefaultError(null, message, null, file, t.getCharStartIndex(), t.getCharStopIndex(), Severity.ERROR));
29.120 super.error(message, t);
29.121 }
29.122
29.123 @@ -191,7 +220,7 @@
29.124 }
29.125 int start = lineOffset;//t.getCharStartIndex();
29.126 int stop = lineOffset;//t.getCharStopIndex();
29.127 - errors.add(new DefaultError(null, message, null, file.getFileObject(), start, stop, Severity.ERROR));
29.128 + errors.add(new DefaultError(null, message, null, file, start, stop, Severity.ERROR));
29.129 }
29.130 return super.recoverFromMismatchedToken(br, input, ttype, follow);
29.131 }
29.132 @@ -255,7 +284,7 @@
29.133 end = start;
29.134 }
29.135
29.136 - errors.add(new DefaultError(null, message, null, file.getFileObject(), start, end, Severity.ERROR));
29.137 + errors.add(new DefaultError(null, message, null, file, start, end, Severity.ERROR));
29.138
29.139 super.reportError(br, re);
29.140 }
29.141 @@ -267,16 +296,14 @@
29.142 CommonTokenStream tokens = new CommonTokenStream(lexer);
29.143 tokens.discardOffChannelTokens(true);
29.144 PythonTokenSource indentedSource = new PythonTokenSource(tokens, fileName);
29.145 - tokens = new CommonTokenStream(indentedSource);
29.146 - org.python.antlr.PythonParser parser = new org.python.antlr.PythonParser(tokens);
29.147 + CommonTokenStream indentedTokens = new CommonTokenStream(indentedSource);
29.148 + org.python.antlr.PythonParser parser = new org.python.antlr.PythonParser(indentedTokens);
29.149 parser.setTreeAdaptor(new PythonTreeAdaptor());
29.150 parser.setErrorHandler(errorHandler);
29.151 org.python.antlr.PythonParser.file_input_return r = parser.file_input();
29.152 PythonTree t = (PythonTree)r.getTree();
29.153 - PythonParserResult result = createParseResult(t, file, true);
29.154 - for (Error error : errors) {
29.155 - result.addError(error);
29.156 - }
29.157 + PythonParserResult result = new PythonParserResult(t, context.snapshot);
29.158 + result.setErrors(errors);
29.159
29.160 result.setSanitized(context.sanitized, context.sanitizedRange, context.sanitizedContents);
29.161 result.setSource(sourceCode);
29.162 @@ -294,8 +321,8 @@
29.163 if (desc == null) {
29.164 desc = pe.getMessage();
29.165 }
29.166 - DefaultError error = new DefaultError(null /*key*/, desc, null, file.getFileObject(), offset, offset, Severity.ERROR);
29.167 - PythonParserResult parserResult = createParseResult(null, file, false);
29.168 + DefaultError error = new DefaultError(null /*key*/, desc, null, file, offset, offset, Severity.ERROR);
29.169 + PythonParserResult parserResult = new PythonParserResult(null, context.snapshot);
29.170 parserResult.addError(error);
29.171 for (Error e : errors) {
29.172 parserResult.addError(e);
29.173 @@ -308,11 +335,12 @@
29.174 }
29.175 } catch (NullPointerException e) {
29.176 String fileName = "";
29.177 - if (file.getFileObject() != null) {
29.178 - fileName = FileUtil.getFileDisplayName(file.getFileObject());
29.179 + if (file != null) {
29.180 + fileName = FileUtil.getFileDisplayName(file);
29.181 }
29.182 - Exceptions.attachMessage(e, "Was parsing " + fileName);
29.183 - return createParseResult(null, file, false);
29.184 + e = Exceptions.attachMessage(e, "Was parsing " + fileName);
29.185 + Exceptions.printStackTrace(e);
29.186 + return new PythonParserResult(null, context.snapshot);
29.187 } catch (Throwable t) {
29.188 runtimeException = t;
29.189 StackTraceElement[] stackTrace = t.getStackTrace();
29.190 @@ -321,10 +349,10 @@
29.191 // Don't bug user about it -- we already know
29.192 Logger.getLogger(this.getClass().getName()).log(Level.FINE, "Encountered issue #150921", t);
29.193 } else {
29.194 - Exceptions.attachMessage(t, "Was parsing " + FileUtil.getFileDisplayName(file.getFileObject()));
29.195 + t = Exceptions.attachMessage(t, "Was parsing " + FileUtil.getFileDisplayName(file));
29.196 Exceptions.printStackTrace(t);
29.197 }
29.198 - return createParseResult(null, file, false);
29.199 + return new PythonParserResult(null, context.snapshot);
29.200 }
29.201 }
29.202
29.203 @@ -336,63 +364,13 @@
29.204 }
29.205 }
29.206
29.207 - public void parseFiles(Job job) {
29.208 - ParseListener listener = job.listener;
29.209 - SourceFileReader reader = job.reader;
29.210 -
29.211 - for (ParserFile file : job.files) {
29.212 - ParseEvent beginEvent = new ParseEvent(ParseEvent.Kind.PARSE, file, null);
29.213 - listener.started(beginEvent);
29.214 -
29.215 - PythonParserResult result = null;
29.216 -
29.217 - try {
29.218 - // RST files aren't really Python but I want to index them so
29.219 - // fake up a parser result I can use
29.220 - String nameExt = file.getNameExt();
29.221 - if (nameExt != null && nameExt.endsWith(".rst")) { // NOI18N
29.222 - result = createParseResult(null, file, false);
29.223 - } else if (nameExt != null && nameExt.endsWith(".egg")) { // NOI18N
29.224 - // .Egg files aren't really python but we need the indexer to get
29.225 - // a chance - GSF will only call it if it maps to a Python parser result
29.226 - result = createParseResult(null, file, false);
29.227 - } else {
29.228 - CharSequence buffer = reader.read(file);
29.229 - String source = asString(buffer);
29.230 -
29.231 - int caretOffset = reader.getCaretOffset(file);
29.232 - if (caretOffset != -1 && job.translatedSource != null) {
29.233 - caretOffset = job.translatedSource.getAstOffset(caretOffset);
29.234 - }
29.235 - Context context = new Context(file, listener, source, caretOffset, job.translatedSource, job);
29.236 -
29.237 - result = parse(context, Sanitize.NONE);
29.238 - result.setSource(source);
29.239 - }
29.240 - } catch (Exception ioe) {
29.241 - listener.exception(ioe);
29.242 - }
29.243 -
29.244 - ParseEvent doneEvent = new ParseEvent(ParseEvent.Kind.PARSE, file, result);
29.245 - listener.finished(doneEvent);
29.246 - }
29.247 - }
29.248 -
29.249 - public PositionManager getPositionManager() {
29.250 - return new PythonPositionManager();
29.251 - }
29.252 -
29.253 - private PythonParserResult createParseResult(PythonTree rootNode, ParserFile file, boolean isValid) {
29.254 - return new PythonParserResult(rootNode, this, file, isValid);
29.255 - }
29.256
29.257 @SuppressWarnings("fallthrough")
29.258 - private PythonParserResult sanitize(final Context context,
29.259 - final Sanitize sanitizing) throws Exception {
29.260 + private PythonParserResult sanitize(final Context context, final Sanitize sanitizing) {
29.261
29.262 switch (sanitizing) {
29.263 case NEVER:
29.264 - return createParseResult(null, context.file, false);
29.265 + return new PythonParserResult(null, context.snapshot);
29.266
29.267 case NONE:
29.268 if (context.caretOffset != -1) {
29.269 @@ -433,7 +411,7 @@
29.270 case EDITED_LINE:
29.271 default:
29.272 // We're out of tricks - just return the failed parse result
29.273 - return createParseResult(null, context.file, false);
29.274 + return new PythonParserResult(null, context.snapshot);
29.275 }
29.276 }
29.277
29.278 @@ -641,10 +619,10 @@
29.279 EDITED_LINE,
29.280 }
29.281
29.282 - /** Parsing context */
29.283 + /** Sanitize context */
29.284 public static class Context {
29.285 - private final ParserFile file;
29.286 - private ParseListener listener;
29.287 + private FileObject file;
29.288 +// private ParseListener listener;
29.289 private int errorOffset;
29.290 private String source;
29.291 private String sanitizedSource;
29.292 @@ -652,42 +630,45 @@
29.293 private String sanitizedContents;
29.294 private int caretOffset;
29.295 private Sanitize sanitized = Sanitize.NONE;
29.296 - private TranslatedSource translatedSource;
29.297 - private Parser.Job job;
29.298 -
29.299 - public Context(ParserFile parserFile, ParseListener listener, String source, int caretOffset, TranslatedSource translatedSource, Parser.Job job) {
29.300 - this.file = parserFile;
29.301 - this.listener = listener;
29.302 - this.source = source;
29.303 - this.caretOffset = caretOffset;
29.304 - this.translatedSource = translatedSource;
29.305 - this.job = job;
29.306 -
29.307 -
29.308 - if (caretOffset != -1) {
29.309 - sanitized = Sanitize.EDITED_DOT;
29.310 - }
29.311 - }
29.312 -
29.313 - @Override
29.314 - public String toString() {
29.315 - return "PythonParser.Context(" + file.toString() + ")"; // NOI18N
29.316 - }
29.317 -
29.318 - public OffsetRange getSanitizedRange() {
29.319 - return sanitizedRange;
29.320 - }
29.321 -
29.322 - public Sanitize getSanitized() {
29.323 - return sanitized;
29.324 - }
29.325 -
29.326 - public String getSanitizedSource() {
29.327 - return sanitizedSource;
29.328 - }
29.329 -
29.330 - public int getErrorOffset() {
29.331 - return errorOffset;
29.332 - }
29.333 +// private TranslatedSource translatedSource;
29.334 +// private Parser.Job job;
29.335 + private Snapshot snapshot;
29.336 + private Task task;
29.337 + private SourceModificationEvent event;
29.338 +//
29.339 +// public Context(ParserFile parserFile, ParseListener listener, String source, int caretOffset, TranslatedSource translatedSource, Parser.Job job) {
29.340 +// this.file = parserFile;
29.341 +// this.listener = listener;
29.342 +// this.source = source;
29.343 +// this.caretOffset = caretOffset;
29.344 +// this.translatedSource = translatedSource;
29.345 +// this.job = job;
29.346 +//
29.347 +//
29.348 +// if (caretOffset != -1) {
29.349 +// sanitized = Sanitize.EDITED_DOT;
29.350 +// }
29.351 +// }
29.352 +//
29.353 +// @Override
29.354 +// public String toString() {
29.355 +// return "PythonParser.Context(" + file.toString() + ")"; // NOI18N
29.356 +// }
29.357 +//
29.358 +// public OffsetRange getSanitizedRange() {
29.359 +// return sanitizedRange;
29.360 +// }
29.361 +//
29.362 +// public Sanitize getSanitized() {
29.363 +// return sanitized;
29.364 +// }
29.365 +//
29.366 +// public String getSanitizedSource() {
29.367 +// return sanitizedSource;
29.368 +// }
29.369 +//
29.370 +// public int getErrorOffset() {
29.371 +// return errorOffset;
29.372 +// }
29.373 }
29.374 }
30.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonParserResult.java Sun Jan 04 13:11:53 2015 -0600
30.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonParserResult.java Sun Feb 01 15:02:07 2015 -0800
30.3 @@ -30,23 +30,16 @@
30.4 */
30.5 package org.netbeans.modules.python.editor;
30.6
30.7 -import java.io.IOException;
30.8 -import java.util.Collection;
30.9 import java.util.Collections;
30.10 +import java.util.LinkedList;
30.11 import java.util.List;
30.12 -import javax.swing.text.Document;
30.13 -import org.netbeans.modules.python.editor.lexer.PythonTokenId;
30.14 -import org.netbeans.modules.gsf.api.CompilationInfo;
30.15 -import org.netbeans.modules.gsf.api.Error;
30.16 -import org.netbeans.modules.gsf.api.Index;
30.17 -import org.netbeans.modules.gsf.api.OffsetRange;
30.18 -import org.netbeans.modules.gsf.api.ParserFile;
30.19 -import org.netbeans.modules.gsf.api.ParserResult;
30.20 -import org.netbeans.modules.gsf.api.annotations.NonNull;
30.21 -import org.netbeans.modules.gsf.spi.GsfUtilities;
30.22 +import org.netbeans.api.annotations.common.NonNull;
30.23 +import org.netbeans.modules.csl.api.Error;
30.24 +import org.netbeans.modules.csl.api.OffsetRange;
30.25 +import org.netbeans.modules.csl.spi.ParserResult;
30.26 +import org.netbeans.modules.parsing.api.Snapshot;
30.27 import org.netbeans.modules.python.editor.PythonParser.Sanitize;
30.28 import org.netbeans.modules.python.editor.scopes.SymbolTable;
30.29 -import org.openide.util.Exceptions;
30.30 import org.python.antlr.PythonTree;
30.31
30.32 /**
30.33 @@ -57,6 +50,7 @@
30.34 */
30.35 public class PythonParserResult extends ParserResult {
30.36 private PythonTree root;
30.37 + private List<Error> errors;
30.38 private OffsetRange sanitizedRange = OffsetRange.NONE;
30.39 private String source;
30.40 private String sanitizedContents;
30.41 @@ -65,9 +59,10 @@
30.42 private SymbolTable symbolTable;
30.43 private int codeTemplateOffset = -1;
30.44
30.45 - public PythonParserResult(PythonTree tree, PythonParser parser, ParserFile file, boolean isValid) {
30.46 - super(parser, file, PythonTokenId.PYTHON_MIME_TYPE, isValid);
30.47 + public PythonParserResult(PythonTree tree, @NonNull Snapshot snapshot) {
30.48 + super(snapshot);
30.49 this.root = tree;
30.50 + this.errors = new LinkedList<Error>();
30.51 }
30.52
30.53 public PythonTree getRoot() {
30.54 @@ -75,10 +70,19 @@
30.55 }
30.56
30.57 @Override
30.58 - public AstTreeNode getAst() {
30.59 - return PythonAstTreeNode.get(root);
30.60 + public List<? extends Error> getDiagnostics() {
30.61 + return errors;
30.62 }
30.63
30.64 + @Override
30.65 + protected void invalidate() {
30.66 + }
30.67 +
30.68 + public void setErrors(List<? extends Error> errors) {
30.69 + this.errors.clear();
30.70 + this.errors.addAll(errors);
30.71 + }
30.72 +
30.73 /**
30.74 * Set the range of source that was sanitized, if any.
30.75 */
30.76 @@ -107,7 +111,7 @@
30.77
30.78 public SymbolTable getSymbolTable() {
30.79 if (symbolTable == null) {
30.80 - symbolTable = new SymbolTable(root, file.getFileObject());
30.81 + symbolTable = new SymbolTable(root, getSnapshot().getSource().getFileObject());
30.82 }
30.83
30.84 return symbolTable;
30.85 @@ -125,68 +129,6 @@
30.86 this.source = source;
30.87 }
30.88
30.89 - void setStructure(@NonNull PythonStructureScanner.AnalysisResult result) {
30.90 - this.analysisResult = result;
30.91 - }
30.92 -
30.93 - @NonNull
30.94 - public PythonStructureScanner.AnalysisResult getStructure() {
30.95 - if (analysisResult == null) {
30.96 - CompilationInfo info = getInfo();
30.97 - if (info == null) {
30.98 - try {
30.99 - info = new CompilationInfo(getFile().getFileObject()) {
30.100 - private Document doc;
30.101 -
30.102 - @Override
30.103 - public Collection<? extends ParserResult> getEmbeddedResults(String mimeType) {
30.104 - if (mimeType.equals(PythonTokenId.PYTHON_MIME_TYPE)) {
30.105 - return Collections.singleton(PythonParserResult.this);
30.106 - }
30.107 - return null;
30.108 - }
30.109 -
30.110 - @Override
30.111 - public ParserResult getEmbeddedResult(String mimeType, int offset) {
30.112 - if (mimeType.equals(PythonTokenId.PYTHON_MIME_TYPE)) {
30.113 - return PythonParserResult.this;
30.114 - }
30.115 - return null;
30.116 - }
30.117 -
30.118 - @Override
30.119 - public String getText() {
30.120 - return getSource();
30.121 - }
30.122 -
30.123 - @Override
30.124 - public Index getIndex(String mimeType) {
30.125 - return null;
30.126 - }
30.127 -
30.128 - @Override
30.129 - public List<Error> getErrors() {
30.130 - return Collections.emptyList();
30.131 - }
30.132 -
30.133 - @Override
30.134 - public Document getDocument() {
30.135 - if (doc == null) {
30.136 - doc = GsfUtilities.getDocument(getFileObject(), true);
30.137 - }
30.138 -
30.139 - return doc;
30.140 - }
30.141 - };
30.142 - } catch (IOException ioe) {
30.143 - Exceptions.printStackTrace(ioe);
30.144 - }
30.145 - }
30.146 - analysisResult = PythonStructureScanner.analyze(info);
30.147 - }
30.148 - return analysisResult;
30.149 - }
30.150 -
30.151 /**
30.152 * @return the codeTemplateOffset
30.153 */
30.154 @@ -200,4 +142,12 @@
30.155 public void setCodeTemplateOffset(int codeTemplateOffset) {
30.156 this.codeTemplateOffset = codeTemplateOffset;
30.157 }
30.158 +
30.159 + public void addError(Error e) {
30.160 + errors.add(e);
30.161 + }
30.162 +
30.163 + public boolean isValid() {
30.164 + return errors.isEmpty();
30.165 + }
30.166 }
31.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonPositionManager.java Sun Jan 04 13:11:53 2015 -0600
31.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
31.3 @@ -1,42 +0,0 @@
31.4 -/*
31.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
31.6 - *
31.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
31.8 - *
31.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
31.10 - * Other names may be trademarks of their respective owners.
31.11 - *
31.12 - * The contents of this file are subject to the terms of either the GNU
31.13 - * General Public License Version 2 only ("GPL") or the Common
31.14 - * Development and Distribution License("CDDL") (collectively, the
31.15 - * "License"). You may not use this file except in compliance with the
31.16 - * License. You can obtain a copy of the License at
31.17 - * http://www.netbeans.org/cddl-gplv2.html
31.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
31.19 - * specific language governing permissions and limitations under the
31.20 - * License. When distributing the software, include this License Header
31.21 - * Notice in each file and include the License file at
31.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
31.23 - * particular file as subject to the "Classpath" exception as provided
31.24 - * by Oracle in the GPL Version 2 section of the License file that
31.25 - * accompanied this code. If applicable, add the following below the
31.26 - * License Header, with the fields enclosed by brackets [] replaced by
31.27 - * your own identifying information:
31.28 - * "Portions Copyrighted [year] [name of copyright owner]"
31.29 - *
31.30 - * Contributor(s):
31.31 - *
31.32 - * Portions Copyrighted 2007 Sun Microsystems, Inc.
31.33 - */
31.34 -package org.netbeans.modules.python.editor;
31.35 -
31.36 -import org.netbeans.modules.gsf.api.CompilationInfo;
31.37 -import org.netbeans.modules.gsf.api.ElementHandle;
31.38 -import org.netbeans.modules.gsf.api.OffsetRange;
31.39 -import org.netbeans.modules.gsf.api.PositionManager;
31.40 -
31.41 -class PythonPositionManager implements PositionManager {
31.42 - public OffsetRange getOffsetRange(CompilationInfo info, ElementHandle object) {
31.43 - return OffsetRange.NONE;
31.44 - }
31.45 -}
32.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonSemanticHighlighter.java Sun Jan 04 13:11:53 2015 -0600
32.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonSemanticHighlighter.java Sun Feb 01 15:02:07 2015 -0800
32.3 @@ -34,12 +34,16 @@
32.4 import java.util.HashMap;
32.5 import java.util.Map;
32.6 import java.util.Set;
32.7 -import org.netbeans.modules.gsf.api.ColoringAttributes;
32.8 -import org.netbeans.modules.gsf.api.CompilationInfo;
32.9 -import org.netbeans.modules.gsf.api.OffsetRange;
32.10 -import org.netbeans.modules.gsf.api.SemanticAnalyzer;
32.11 +import org.netbeans.modules.csl.api.ColoringAttributes;
32.12 +import org.netbeans.modules.csl.api.OffsetRange;
32.13 +import org.netbeans.modules.csl.api.SemanticAnalyzer;
32.14 +import org.netbeans.modules.csl.spi.ParserResult;
32.15 +import org.netbeans.modules.parsing.spi.Parser.Result;
32.16 +import org.netbeans.modules.parsing.spi.Scheduler;
32.17 +import org.netbeans.modules.parsing.spi.SchedulerEvent;
32.18 import org.netbeans.modules.python.editor.scopes.ScopeInfo;
32.19 import org.netbeans.modules.python.editor.scopes.SymbolTable;
32.20 +import org.openide.util.Exceptions;
32.21 import org.python.antlr.PythonTree;
32.22 import org.python.antlr.Visitor;
32.23 import org.python.antlr.ast.ClassDef;
32.24 @@ -52,7 +56,7 @@
32.25 *
32.26 * @author Tor Norbye
32.27 */
32.28 -public class PythonSemanticHighlighter implements SemanticAnalyzer {
32.29 +public class PythonSemanticHighlighter extends SemanticAnalyzer<PythonParserResult> {
32.30 private boolean cancelled;
32.31 private Map<OffsetRange, Set<ColoringAttributes>> semanticHighlights;
32.32
32.33 @@ -72,34 +76,47 @@
32.34 cancelled = true;
32.35 }
32.36
32.37 - public void run(CompilationInfo info) throws Exception {
32.38 + @Override
32.39 + public int getPriority() {
32.40 + return 0;
32.41 + }
32.42 +
32.43 + @Override
32.44 + public Class<? extends Scheduler> getSchedulerClass() {
32.45 + return Scheduler.EDITOR_SENSITIVE_TASK_SCHEDULER;
32.46 + }
32.47 +
32.48 + public void run(PythonParserResult pr, SchedulerEvent event) {
32.49 resume();
32.50
32.51 if (isCancelled()) {
32.52 return;
32.53 }
32.54
32.55 - PythonTree root = PythonAstUtils.getRoot(info);
32.56 + PythonTree root = PythonAstUtils.getRoot(pr);
32.57 if (root == null) {
32.58 return;
32.59 }
32.60
32.61 - PythonParserResult pr = PythonAstUtils.getParseResult(info);
32.62 SymbolTable symbolTable = pr.getSymbolTable();
32.63
32.64 - SemanticVisitor visitor = new SemanticVisitor(info, symbolTable);
32.65 - visitor.visit(root);
32.66 + SemanticVisitor visitor = new SemanticVisitor(pr, symbolTable);
32.67 + try {
32.68 + visitor.visit(root);
32.69 + } catch (Exception ex) {
32.70 + Exceptions.printStackTrace(ex);
32.71 + }
32.72 semanticHighlights = visitor.getHighlights();
32.73 }
32.74
32.75 private static class SemanticVisitor extends Visitor {
32.76 - private final CompilationInfo info;
32.77 + private final PythonParserResult info;
32.78 private Map<OffsetRange, Set<ColoringAttributes>> highlights =
32.79 new HashMap<OffsetRange, Set<ColoringAttributes>>(100);
32.80 private final SymbolTable symbolTable;
32.81 private ScopeInfo scope;
32.82
32.83 - SemanticVisitor(CompilationInfo info, SymbolTable symbolTable) {
32.84 + SemanticVisitor(PythonParserResult info, SymbolTable symbolTable) {
32.85 this.info = info;
32.86 this.symbolTable = symbolTable;
32.87 }
33.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonStructureItem.java Sun Jan 04 13:11:53 2015 -0600
33.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonStructureItem.java Sun Feb 01 15:02:07 2015 -0800
33.3 @@ -34,21 +34,33 @@
33.4 import java.util.Collections;
33.5 import java.util.List;
33.6 import javax.swing.ImageIcon;
33.7 +import org.netbeans.modules.csl.api.ElementHandle;
33.8 +import org.netbeans.modules.csl.api.ElementKind;
33.9 +import org.netbeans.modules.csl.api.HtmlFormatter;
33.10 +import org.netbeans.modules.csl.api.Modifier;
33.11 +import org.netbeans.modules.csl.api.StructureItem;
33.12 import org.netbeans.modules.python.editor.elements.AstElement;
33.13 -import org.netbeans.modules.gsf.api.ElementHandle;
33.14 -import org.netbeans.modules.gsf.api.ElementKind;
33.15 -import org.netbeans.modules.gsf.api.HtmlFormatter;
33.16 -import org.netbeans.modules.gsf.api.Modifier;
33.17 -import org.netbeans.modules.gsf.api.StructureItem;
33.18 import org.netbeans.modules.python.editor.scopes.SymbolTable;
33.19 import org.openide.util.ImageUtilities;
33.20 import org.python.antlr.PythonTree;
33.21 +import org.python.antlr.ast.ClassDef;
33.22 import org.python.antlr.ast.FunctionDef;
33.23
33.24 public final class PythonStructureItem extends AstElement implements StructureItem {
33.25 private List<PythonStructureItem> children;
33.26 private PythonStructureItem parent;
33.27
33.28 + public PythonStructureItem(SymbolTable scopes, ClassDef def) {
33.29 + this(scopes, def, def.getInternalName(), ElementKind.CLASS);
33.30 + }
33.31 +
33.32 + public PythonStructureItem(SymbolTable scopes, FunctionDef def) {
33.33 + this(scopes, def, def.getInternalName(), ElementKind.METHOD);
33.34 + if ("__init__".equals(name)) { // NOI18N
33.35 + kind = ElementKind.CONSTRUCTOR;
33.36 + }
33.37 + }
33.38 +
33.39 public PythonStructureItem(SymbolTable scopes, PythonTree node, String name, ElementKind kind) {
33.40 super(scopes, node, name, kind);
33.41 this.node = node;
34.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonStructureScanner.java Sun Jan 04 13:11:53 2015 -0600
34.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonStructureScanner.java Sun Feb 01 15:02:07 2015 -0800
34.3 @@ -39,11 +39,13 @@
34.4 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
34.5 import org.netbeans.editor.BaseDocument;
34.6 import org.netbeans.editor.Utilities;
34.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
34.8 -import org.netbeans.modules.gsf.api.ElementKind;
34.9 -import org.netbeans.modules.gsf.api.OffsetRange;
34.10 -import org.netbeans.modules.gsf.api.StructureItem;
34.11 -import org.netbeans.modules.gsf.api.StructureScanner;
34.12 +import org.netbeans.modules.csl.api.ElementKind;
34.13 +import org.netbeans.modules.csl.api.OffsetRange;
34.14 +import org.netbeans.modules.csl.api.StructureItem;
34.15 +import org.netbeans.modules.csl.api.StructureScanner;
34.16 +import org.netbeans.modules.csl.api.StructureScanner.Configuration;
34.17 +import org.netbeans.modules.csl.spi.GsfUtilities;
34.18 +import org.netbeans.modules.csl.spi.ParserResult;
34.19 import org.netbeans.modules.python.editor.scopes.ScopeInfo;
34.20 import org.netbeans.modules.python.editor.scopes.SymInfo;
34.21 import org.netbeans.modules.python.editor.scopes.SymbolTable;
34.22 @@ -61,24 +63,8 @@
34.23 * @author Tor Norbye
34.24 */
34.25 public class PythonStructureScanner implements StructureScanner {
34.26 - public static PythonStructureItem create(SymbolTable scopes, ClassDef def) {
34.27 - PythonStructureItem item = new PythonStructureItem(scopes, def, def.getInternalName(), ElementKind.CLASS);
34.28 -
34.29 - return item;
34.30 - }
34.31 -
34.32 - public static PythonStructureItem create(SymbolTable scopes, FunctionDef def) {
34.33 - String name = def.getInternalName();
34.34 - ElementKind kind = ElementKind.METHOD;
34.35 - if ("__init__".equals(name)) { // NOI18N
34.36 - kind = ElementKind.CONSTRUCTOR;
34.37 - }
34.38 - PythonStructureItem item = new PythonStructureItem(scopes, def, name, kind);
34.39 -
34.40 - return item;
34.41 - }
34.42 -
34.43 - public static AnalysisResult analyze(CompilationInfo info) {
34.44 +
34.45 + public static AnalysisResult analyze(PythonParserResult info) {
34.46 AnalysisResult analysisResult = new AnalysisResult();
34.47
34.48 PythonTree root = PythonAstUtils.getRoot(info);
34.49 @@ -96,16 +82,24 @@
34.50 return analysisResult;
34.51 }
34.52
34.53 - public List<? extends StructureItem> scan(CompilationInfo info) {
34.54 + @Override
34.55 + public List<? extends StructureItem> scan(ParserResult info) {
34.56 PythonParserResult parseResult = PythonAstUtils.getParseResult(info);
34.57 if (parseResult == null) {
34.58 return Collections.emptyList();
34.59 }
34.60
34.61 - return parseResult.getStructure().getElements();
34.62 + return getStructure(parseResult).getElements();
34.63 + }
34.64 +
34.65 + public PythonStructureScanner.AnalysisResult getStructure(PythonParserResult result) {
34.66 + // TODO Cache ! (Used to be in PythonParserResult
34.67 + AnalysisResult analysisResult = PythonStructureScanner.analyze(result);
34.68 + return analysisResult;
34.69 }
34.70
34.71 - public Map<String, List<OffsetRange>> folds(CompilationInfo info) {
34.72 + @Override
34.73 + public Map<String, List<OffsetRange>> folds(ParserResult info) {
34.74 PythonParserResult result = PythonAstUtils.getParseResult(info);
34.75 PythonTree root = PythonAstUtils.getRoot(result);
34.76 if (root == null) {
34.77 @@ -119,11 +113,11 @@
34.78 //List<?extends AstElement> elements = ar.getElements();
34.79 //List<StructureItem> itemList = new ArrayList<StructureItem>(elements.size());
34.80
34.81 - BaseDocument doc = (BaseDocument)info.getDocument();
34.82 + BaseDocument doc = GsfUtilities.getDocument(result.getSnapshot().getSource().getFileObject(), false);
34.83 if (doc != null) {
34.84 try {
34.85 doc.readLock(); // For Utilities.getRowEnd() access
34.86 - FoldVisitor visitor = new FoldVisitor(info, doc);
34.87 + FoldVisitor visitor = new FoldVisitor((PythonParserResult) info, doc);
34.88 visitor.visit(root);
34.89 List<OffsetRange> codeBlocks = visitor.getCodeBlocks();
34.90
34.91 @@ -140,18 +134,18 @@
34.92 return Collections.emptyMap();
34.93 }
34.94
34.95 + @Override
34.96 public Configuration getConfiguration() {
34.97 - return null;
34.98 + return new Configuration(true, true, -1);
34.99 }
34.100
34.101 private static class FoldVisitor extends Visitor {
34.102 private List<OffsetRange> codeBlocks = new ArrayList<OffsetRange>();
34.103 - private CompilationInfo info;
34.104 + private PythonParserResult info;
34.105 private BaseDocument doc;
34.106
34.107 - private FoldVisitor(CompilationInfo info, BaseDocument doc) {
34.108 + private FoldVisitor(PythonParserResult info, BaseDocument doc) {
34.109 this.info = info;
34.110 -
34.111 this.doc = doc;
34.112 }
34.113
34.114 @@ -211,7 +205,7 @@
34.115
34.116 @Override
34.117 public Object visitClassDef(ClassDef def) throws Exception {
34.118 - PythonStructureItem item = new PythonStructureItem(scopes, def, def.getInternalName(), ElementKind.CLASS);
34.119 + PythonStructureItem item = new PythonStructureItem(scopes, def);
34.120 add(item);
34.121
34.122 ScopeInfo scope = scopes.getScopeInfo(def);
34.123 @@ -237,7 +231,7 @@
34.124
34.125 @Override
34.126 public Object visitFunctionDef(FunctionDef def) throws Exception {
34.127 - PythonStructureItem item = create(scopes, def);
34.128 + PythonStructureItem item = new PythonStructureItem(scopes, def);
34.129
34.130 add(item);
34.131 stack.add(item);
35.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonTypeAnalyzer.java Sun Jan 04 13:11:53 2015 -0600
35.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonTypeAnalyzer.java Sun Feb 01 15:02:07 2015 -0800
35.3 @@ -38,8 +38,7 @@
35.4 import org.netbeans.api.lexer.TokenHierarchy;
35.5 import org.netbeans.api.lexer.TokenSequence;
35.6 import org.netbeans.editor.BaseDocument;
35.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
35.8 -import org.netbeans.modules.gsf.api.OffsetRange;
35.9 +import org.netbeans.modules.csl.api.OffsetRange;
35.10 import org.netbeans.modules.python.editor.lexer.PythonCommentTokenId;
35.11 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
35.12 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
35.13 @@ -117,12 +116,12 @@
35.14 /** PythonTree we are looking for; */
35.15 private PythonTree target;
35.16 private final FileObject fileObject;
35.17 - private final CompilationInfo info;
35.18 + private final PythonParserResult info;
35.19 private long startTime;
35.20
35.21 /** Creates a new instance of JsTypeAnalyzer for a given position.
35.22 * The {@link #analyze} method will do the rest. */
35.23 - public PythonTypeAnalyzer(CompilationInfo info, PythonIndex index, PythonTree root, PythonTree target, int astOffset, int lexOffset, FileObject fileObject) {
35.24 + public PythonTypeAnalyzer(PythonParserResult info, PythonIndex index, PythonTree root, PythonTree target, int astOffset, int lexOffset, FileObject fileObject) {
35.25 this.info = info;
35.26 this.index = index;
35.27 this.root = root;
35.28 @@ -722,7 +721,7 @@
35.29
35.30 if (info != null && root != null) {
35.31 // Look for type annotations
35.32 - BaseDocument doc = (BaseDocument)info.getDocument();
35.33 + BaseDocument doc = (BaseDocument) info.getSnapshot().getSource().getDocument(false);
35.34 if (doc != null) {
35.35 // Look for type declarations that can apply to this variable
35.36 OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(info, PythonAstUtils.getRange(root));
36.1 --- a/python.editor/src/org/netbeans/modules/python/editor/PythonUtils.java Sun Jan 04 13:11:53 2015 -0600
36.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/PythonUtils.java Sun Feb 01 15:02:07 2015 -0800
36.3 @@ -33,20 +33,19 @@
36.4 import java.util.Comparator;
36.5 import java.util.List;
36.6 import javax.swing.text.Document;
36.7 +import org.netbeans.api.annotations.common.NonNull;
36.8 import org.netbeans.api.project.FileOwnerQuery;
36.9 import org.netbeans.api.project.Project;
36.10 +import org.netbeans.api.project.ProjectUtils;
36.11 import org.netbeans.api.project.SourceGroup;
36.12 import org.netbeans.api.project.Sources;
36.13 import org.netbeans.lib.editor.codetemplates.api.CodeTemplate;
36.14 import org.netbeans.lib.editor.codetemplates.api.CodeTemplateManager;
36.15 -import org.netbeans.modules.gsf.api.ParserFile;
36.16 +import org.netbeans.modules.python.api.PythonMIMEResolver;
36.17 import org.netbeans.modules.python.api.PythonPlatform;
36.18 import org.netbeans.modules.python.api.PythonPlatformManager;
36.19 -import org.netbeans.modules.python.editor.lexer.PythonTokenId;
36.20 import org.openide.filesystems.FileObject;
36.21 -import org.openide.filesystems.FileStateInvalidException;
36.22 import org.openide.filesystems.FileUtil;
36.23 -import org.openide.util.Exceptions;
36.24 import org.openide.util.NbBundle;
36.25 import org.python.antlr.PythonTree;
36.26 import org.python.antlr.ast.Attribute;
36.27 @@ -59,13 +58,13 @@
36.28 public class PythonUtils {
36.29 public static boolean canContainPython(FileObject f) {
36.30 String mimeType = f.getMIMEType();
36.31 - return PythonTokenId.PYTHON_MIME_TYPE.equals(mimeType);
36.32 + return PythonMIMEResolver.PYTHON_MIME_TYPE.equals(mimeType);
36.33 // TODO: "text/x-yaml".equals(mimeType) || // NOI18N
36.34 // RubyInstallation.RHTML_MIME_TYPE.equals(mimeType);
36.35 }
36.36
36.37 public static boolean isPythonFile(FileObject f) {
36.38 - return PythonTokenId.PYTHON_MIME_TYPE.equals(f.getMIMEType());
36.39 + return PythonMIMEResolver.PYTHON_MIME_TYPE.equals(f.getMIMEType());
36.40 }
36.41
36.42 public static boolean isRstFile(FileObject f) {
36.43 @@ -75,7 +74,7 @@
36.44 public static boolean isPythonDocument(Document doc) {
36.45 String mimeType = (String)doc.getProperty("mimeType"); // NOI18N
36.46
36.47 - return PythonTokenId.PYTHON_MIME_TYPE.equals(mimeType);
36.48 + return PythonMIMEResolver.PYTHON_MIME_TYPE.equals(mimeType);
36.49 }
36.50 public static final String DOT__INIT__ = ".__init__"; // NOI18N
36.51
36.52 @@ -95,100 +94,83 @@
36.53 * @param projectRelativeName If non null, the path from the project root down to this file
36.54 * @return A string for the full package module name
36.55 */
36.56 - public static String getModuleName(FileObject fo, ParserFile file) {
36.57 - assert fo != null || file != null;
36.58 + public static String getModuleName(@NonNull FileObject fo) {
36.59
36.60 // TODO - use PythonPlatform's library roots!
36.61
36.62 - String module = null;
36.63 - if (file != null) {
36.64 - module = file.getNameExt();
36.65 - fo = file.getFileObject();
36.66 - } else {
36.67 - module = fo.getName();
36.68 + String module = fo.getName();
36.69 +
36.70 + // First see if we're on the load path for the platform, and if so,
36.71 + // use that as the base
36.72 + // TODO - look up platform for the current search context instead of all platforms!!
36.73 + if (fo.getParent() != prevParent) {
36.74 + prevRootUrl = null;
36.75 + prevParent = fo.getParent();
36.76 }
36.77
36.78 - if (fo != null) {
36.79 - // First see if we're on the load path for the platform, and if so,
36.80 - // use that as the base
36.81 - // TODO - look up platform for the current search context instead of all platforms!!
36.82 - try {
36.83 - if (fo.getParent() != prevParent) {
36.84 - prevRootUrl = null;
36.85 - prevParent = fo.getParent();
36.86 - }
36.87 + String url = fo.toURL().toExternalForm();
36.88 + if (prevRootUrl == null) {
36.89 + boolean found = false;
36.90 + PythonPlatformManager manager = PythonPlatformManager.getInstance();
36.91
36.92 - String url = fo.getURL().toExternalForm();
36.93 - if (prevRootUrl == null) {
36.94 - boolean found = false;
36.95 - PythonPlatformManager manager = PythonPlatformManager.getInstance();
36.96 -
36.97 - PlatformSearch:
36.98 - for (String name : manager.getPlatformList()) {
36.99 - PythonPlatform platform = manager.getPlatform(name);
36.100 - if (platform != null) {
36.101 - List<FileObject> unique = platform.getUniqueLibraryRoots();
36.102 - for (FileObject root : unique) {
36.103 - if (FileUtil.isParentOf(root, fo)) {
36.104 - for (FileObject r : platform.getLibraryRoots()) {
36.105 - if (FileUtil.isParentOf(r, fo)) {
36.106 - // See if the folder itself contains
36.107 - // an __init__.py file - if it does,
36.108 - // then include the directory itself
36.109 - // in the package name.
36.110 - if (r.getFileObject("__init__.py") != null) { // NOI18N
36.111 - r = r.getParent();
36.112 - }
36.113 -
36.114 - prevRootUrl = r.getURL().toExternalForm();
36.115 - found = true;
36.116 - break PlatformSearch;
36.117 - }
36.118 - }
36.119 - break PlatformSearch;
36.120 - }
36.121 - }
36.122 - }
36.123 - }
36.124 -
36.125 - if (!found) {
36.126 - Project project = FileOwnerQuery.getOwner(fo);
36.127 - if (project != null) {
36.128 - Sources source = project.getLookup().lookup(Sources.class);
36.129 - // Look up the source path
36.130 - SourceGroup[] sourceGroups = source.getSourceGroups(SOURCES_TYPE_PYTHON);
36.131 - for (SourceGroup group : sourceGroups) {
36.132 - FileObject folder = group.getRootFolder();
36.133 - if (FileUtil.isParentOf(folder, fo)) {
36.134 + PlatformSearch:
36.135 + for (String name : manager.getPlatformList()) {
36.136 + PythonPlatform platform = manager.getPlatform(name);
36.137 + if (platform != null) {
36.138 + List<FileObject> unique = platform.getUniqueLibraryRoots();
36.139 + for (FileObject root : unique) {
36.140 + if (FileUtil.isParentOf(root, fo)) {
36.141 + for (FileObject r : platform.getLibraryRoots()) {
36.142 + if (FileUtil.isParentOf(r, fo)) {
36.143 // See if the folder itself contains
36.144 // an __init__.py file - if it does,
36.145 // then include the directory itself
36.146 // in the package name.
36.147 - if (folder.getFileObject("__init__.py") != null) { // NOI18N
36.148 - folder = folder.getParent();
36.149 + if (r.getFileObject("__init__.py") != null) { // NOI18N
36.150 + r = r.getParent();
36.151 }
36.152
36.153 - prevRootUrl = folder.getURL().toExternalForm();
36.154 - break;
36.155 + prevRootUrl = r.toURL().toExternalForm();
36.156 + found = true;
36.157 + break PlatformSearch;
36.158 }
36.159 }
36.160 + break PlatformSearch;
36.161 }
36.162 }
36.163 }
36.164 + }
36.165
36.166 - if (prevRootUrl != null) {
36.167 - module = url.substring(prevRootUrl.length());
36.168 - if (module.startsWith("/")) {
36.169 - module = module.substring(1);
36.170 + if (!found) {
36.171 + Project project = FileOwnerQuery.getOwner(fo);
36.172 + if (project != null) {
36.173 + Sources source = ProjectUtils.getSources(project);
36.174 + // Look up the source path
36.175 + SourceGroup[] sourceGroups = source.getSourceGroups(SOURCES_TYPE_PYTHON);
36.176 + for (SourceGroup group : sourceGroups) {
36.177 + FileObject folder = group.getRootFolder();
36.178 + if (FileUtil.isParentOf(folder, fo)) {
36.179 + // See if the folder itself contains
36.180 + // an __init__.py file - if it does,
36.181 + // then include the directory itself
36.182 + // in the package name.
36.183 + if (folder.getFileObject("__init__.py") != null) { // NOI18N
36.184 + folder = folder.getParent();
36.185 + }
36.186 +
36.187 + prevRootUrl = folder.toURL().toExternalForm();
36.188 + break;
36.189 + }
36.190 }
36.191 - } else if (file != null && file.getRelativePath() != null) {
36.192 - module = file.getRelativePath();
36.193 }
36.194 - } catch (FileStateInvalidException ex) {
36.195 - Exceptions.printStackTrace(ex);
36.196 }
36.197 - } else if (file != null && file.getRelativePath() != null) {
36.198 - module = file.getRelativePath();
36.199 + }
36.200 +
36.201 + if (prevRootUrl != null) {
36.202 + module = url.substring(prevRootUrl.length());
36.203 + if (module.startsWith("/")) {
36.204 + module = module.substring(1);
36.205 + }
36.206 }
36.207
36.208 // Strip off .y extension
37.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
37.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/QuerySupportFactory.java Sun Feb 01 15:02:07 2015 -0800
37.3 @@ -0,0 +1,74 @@
37.4 +/*
37.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
37.6 + *
37.7 + * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
37.8 + *
37.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
37.10 + * Other names may be trademarks of their respective owners.
37.11 + *
37.12 + * The contents of this file are subject to the terms of either the GNU
37.13 + * General Public License Version 2 only ("GPL") or the Common
37.14 + * Development and Distribution License("CDDL") (collectively, the
37.15 + * "License"). You may not use this file except in compliance with the
37.16 + * License. You can obtain a copy of the License at
37.17 + * http://www.netbeans.org/cddl-gplv2.html
37.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
37.19 + * specific language governing permissions and limitations under the
37.20 + * License. When distributing the software, include this License Header
37.21 + * Notice in each file and include the License file at
37.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
37.23 + * particular file as subject to the "Classpath" exception as provided
37.24 + * by Oracle in the GPL Version 2 section of the License file that
37.25 + * accompanied this code. If applicable, add the following below the
37.26 + * License Header, with the fields enclosed by brackets [] replaced by
37.27 + * your own identifying information:
37.28 + * "Portions Copyrighted [year] [name of copyright owner]"
37.29 + *
37.30 + * If you wish your version of this file to be governed by only the CDDL
37.31 + * or only the GPL Version 2, indicate your decision by adding
37.32 + * "[Contributor] elects to include this software in this distribution
37.33 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
37.34 + * single choice of license, a recipient has the option to distribute
37.35 + * your version of this file under either the CDDL, the GPL Version 2 or
37.36 + * to extend the choice of license to its licensees as provided above.
37.37 + * However, if you add GPL Version 2 code and therefore, elected the GPL
37.38 + * Version 2 license, then the option applies only if the new code is
37.39 + * made subject to such option by the copyright holder.
37.40 + *
37.41 + * Contributor(s):
37.42 + *
37.43 + * Portions Copyrighted 2012 Sun Microsystems, Inc.
37.44 + */
37.45 +package org.netbeans.modules.python.editor;
37.46 +
37.47 +import java.io.IOException;
37.48 +import java.util.Collection;
37.49 +import java.util.Collections;
37.50 +import org.netbeans.modules.parsing.spi.indexing.support.QuerySupport;
37.51 +import org.openide.filesystems.FileObject;
37.52 +import org.openide.util.Exceptions;
37.53 +
37.54 +/**
37.55 + *
37.56 + * @author Petr Pisl
37.57 + */
37.58 +public class QuerySupportFactory {
37.59 +
37.60 + public static QuerySupport get(final Collection<FileObject> roots) {
37.61 + try {
37.62 + return QuerySupport.forRoots(PythonIndexer.NAME,
37.63 + PythonIndexer.VERSION,
37.64 + roots.toArray(new FileObject[roots.size()]));
37.65 + } catch (IOException ex) {
37.66 + Exceptions.printStackTrace(ex);
37.67 + }
37.68 + return null;
37.69 + }
37.70 +
37.71 + public static QuerySupport get(final FileObject source) {
37.72 + return get(QuerySupport.findRoots(source,
37.73 + null,
37.74 + null,
37.75 + Collections.<String>emptySet()));
37.76 + }
37.77 +}
38.1 --- a/python.editor/src/org/netbeans/modules/python/editor/RstFormatter.java Sun Jan 04 13:11:53 2015 -0600
38.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/RstFormatter.java Sun Feb 01 15:02:07 2015 -0800
38.3 @@ -57,10 +57,11 @@
38.4 import org.netbeans.api.lexer.TokenHierarchy;
38.5 import org.netbeans.api.lexer.TokenSequence;
38.6 import org.netbeans.editor.BaseDocument;
38.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
38.8 -import org.netbeans.modules.gsf.api.ElementHandle;
38.9 -import org.netbeans.modules.gsf.api.ElementKind;
38.10 -import org.netbeans.modules.gsf.spi.GsfUtilities;
38.11 +import org.netbeans.modules.csl.api.ElementHandle;
38.12 +import org.netbeans.modules.csl.api.ElementKind;
38.13 +import org.netbeans.modules.csl.spi.GsfUtilities;
38.14 +import org.netbeans.modules.csl.spi.ParserResult;
38.15 +import org.netbeans.modules.python.api.PythonMIMEResolver;
38.16 import org.netbeans.modules.python.editor.elements.Element;
38.17 import org.netbeans.modules.python.editor.elements.IndexedElement;
38.18 import org.netbeans.modules.python.editor.elements.IndexedMethod;
38.19 @@ -186,7 +187,7 @@
38.20 } else if (marker.equals("keyword")) { // NOI18N
38.21 sb.append("<code style=\""); // NOI18N
38.22
38.23 - MimePath mimePath = MimePath.parse(PythonTokenId.PYTHON_MIME_TYPE);
38.24 + MimePath mimePath = MimePath.parse(PythonMIMEResolver.PYTHON_MIME_TYPE);
38.25 Lookup lookup = MimeLookup.getLookup(mimePath);
38.26 FontColorSettings fcs = lookup.lookup(FontColorSettings.class);
38.27
38.28 @@ -1001,7 +1002,7 @@
38.29 return -1;
38.30 }
38.31
38.32 - public static String document(CompilationInfo info, ElementHandle element) {
38.33 + public static String document(ParserResult info, ElementHandle element) {
38.34 if (element instanceof IndexedElement) {
38.35 IndexedElement indexedElement = (IndexedElement)element;
38.36
38.37 @@ -1024,7 +1025,7 @@
38.38 return null;
38.39 }
38.40
38.41 - public static String document(CompilationInfo info, PythonTree node, IndexedElement element) {
38.42 + public static String document(ParserResult info, PythonTree node, IndexedElement element) {
38.43 if (node != null) {
38.44 String doc = PythonAstUtils.getDocumentation(node);
38.45 if (doc != null) {
38.46 @@ -1124,7 +1125,7 @@
38.47 }
38.48
38.49 Language<?> language = PythonTokenId.language();
38.50 - String mimeType = PythonTokenId.PYTHON_MIME_TYPE;
38.51 + String mimeType = PythonMIMEResolver.PYTHON_MIME_TYPE;
38.52 // TODO - handle YAML and other languages I can see in the documentation...
38.53 /*if (python.indexOf(" <%") != -1) { // NOI18N
38.54 mimeType = "application/x-httpd-eruby"; // RHTML
39.1 --- a/python.editor/src/org/netbeans/modules/python/editor/codecoverage/PythonCoverageProvider.java Sun Jan 04 13:11:53 2015 -0600
39.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/codecoverage/PythonCoverageProvider.java Sun Feb 01 15:02:07 2015 -0800
39.3 @@ -65,14 +65,15 @@
39.4 import org.netbeans.api.project.Project;
39.5 import org.netbeans.editor.BaseDocument;
39.6 import org.netbeans.editor.Utilities;
39.7 +import org.netbeans.modules.csl.spi.GsfUtilities;
39.8 import org.netbeans.modules.gsf.codecoverage.api.CoverageManager;
39.9 import org.netbeans.modules.gsf.codecoverage.api.CoverageProvider;
39.10 import org.netbeans.modules.gsf.codecoverage.api.CoverageProviderHelper;
39.11 import org.netbeans.modules.gsf.codecoverage.api.CoverageType;
39.12 import org.netbeans.modules.gsf.codecoverage.api.FileCoverageDetails;
39.13 import org.netbeans.modules.gsf.codecoverage.api.FileCoverageSummary;
39.14 -import org.netbeans.modules.gsf.spi.GsfUtilities;
39.15 import org.netbeans.modules.python.api.PythonExecution;
39.16 +import org.netbeans.modules.python.api.PythonMIMEResolver;
39.17 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
39.18 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
39.19 import org.openide.filesystems.FileObject;
39.20 @@ -96,7 +97,7 @@
39.21 private Map<String, String> fullNames;
39.22 private long timestamp;
39.23 private Project project;
39.24 - private Set<String> mimeTypes = Collections.singleton(PythonTokenId.PYTHON_MIME_TYPE);
39.25 + private Set<String> mimeTypes = Collections.singleton(PythonMIMEResolver.PYTHON_MIME_TYPE);
39.26 private Boolean enabled;
39.27 private Boolean aggregating;
39.28
40.1 --- a/python.editor/src/org/netbeans/modules/python/editor/elements/AstElement.java Sun Jan 04 13:11:53 2015 -0600
40.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/elements/AstElement.java Sun Feb 01 15:02:07 2015 -0800
40.3 @@ -31,10 +31,13 @@
40.4 package org.netbeans.modules.python.editor.elements;
40.5
40.6 import java.util.Set;
40.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
40.8 -import org.netbeans.modules.gsf.api.ElementKind;
40.9 -import org.netbeans.modules.gsf.api.Modifier;
40.10 +import org.netbeans.modules.csl.api.ElementKind;
40.11 +import org.netbeans.modules.csl.api.Modifier;
40.12 +import org.netbeans.modules.csl.api.OffsetRange;
40.13 +import org.netbeans.modules.csl.spi.ParserResult;
40.14 import org.netbeans.modules.python.editor.PythonAstUtils;
40.15 +import org.netbeans.modules.python.editor.PythonParserResult;
40.16 +import org.netbeans.modules.python.editor.PythonStructureItem;
40.17 import org.netbeans.modules.python.editor.PythonStructureScanner;
40.18 import org.netbeans.modules.python.editor.scopes.SymbolTable;
40.19 import org.python.antlr.PythonTree;
40.20 @@ -64,13 +67,13 @@
40.21 this.kind = kind;
40.22 }
40.23
40.24 - public static AstElement create(CompilationInfo info, PythonTree node) {
40.25 - SymbolTable scopes = PythonAstUtils.getParseResult(info).getSymbolTable();
40.26 + public static AstElement create(PythonParserResult result, PythonTree node) {
40.27 + SymbolTable scopes = result.getSymbolTable();
40.28
40.29 if (node instanceof FunctionDef) {
40.30 - return PythonStructureScanner.create(scopes, (FunctionDef)node);
40.31 + return new PythonStructureItem(scopes, (FunctionDef)node);
40.32 } else if (node instanceof ClassDef) {
40.33 - return PythonStructureScanner.create(scopes, (ClassDef)node);
40.34 + return new PythonStructureItem(scopes, (ClassDef)node);
40.35 } else if (node instanceof Call) {
40.36 String name = PythonAstUtils.getCallName((Call)node);
40.37 return new AstElement(scopes, node, name, ElementKind.METHOD);
41.1 --- a/python.editor/src/org/netbeans/modules/python/editor/elements/Element.java Sun Jan 04 13:11:53 2015 -0600
41.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/elements/Element.java Sun Feb 01 15:02:07 2015 -0800
41.3 @@ -32,10 +32,12 @@
41.4
41.5 import java.util.Collections;
41.6 import java.util.Set;
41.7 -import org.netbeans.modules.python.editor.lexer.PythonTokenId;
41.8 -import org.netbeans.modules.gsf.api.ElementHandle;
41.9 -import org.netbeans.modules.gsf.api.ElementKind;
41.10 -import org.netbeans.modules.gsf.api.Modifier;
41.11 +import org.netbeans.modules.csl.api.ElementHandle;
41.12 +import org.netbeans.modules.csl.api.ElementKind;
41.13 +import org.netbeans.modules.csl.api.Modifier;
41.14 +import org.netbeans.modules.csl.api.OffsetRange;
41.15 +import org.netbeans.modules.csl.spi.ParserResult;
41.16 +import org.netbeans.modules.python.api.PythonMIMEResolver;
41.17 import org.openide.filesystems.FileObject;
41.18
41.19 /**
41.20 @@ -43,27 +45,40 @@
41.21 * @author Tor Norbye
41.22 */
41.23 public abstract class Element implements ElementHandle {
41.24 + @Override
41.25 public abstract String getName();
41.26
41.27 + @Override
41.28 public abstract ElementKind getKind();
41.29
41.30 + @Override
41.31 public String getMimeType() {
41.32 - return PythonTokenId.PYTHON_MIME_TYPE;
41.33 + return PythonMIMEResolver.PYTHON_MIME_TYPE;
41.34 }
41.35
41.36 + @Override
41.37 public boolean signatureEquals(ElementHandle handle) {
41.38 // XXX TODO
41.39 return false;
41.40 }
41.41
41.42 + @Override
41.43 + public OffsetRange getOffsetRange(ParserResult pr) {
41.44 + // XXX TODO
41.45 + return null;
41.46 + }
41.47 +
41.48 + @Override
41.49 public FileObject getFileObject() {
41.50 return null;
41.51 }
41.52
41.53 + @Override
41.54 public Set<Modifier> getModifiers() {
41.55 return Collections.emptySet();
41.56 }
41.57
41.58 + @Override
41.59 public String getIn() {
41.60 return null;
41.61 }
42.1 --- a/python.editor/src/org/netbeans/modules/python/editor/elements/IndexedElement.java Sun Jan 04 13:11:53 2015 -0600
42.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/elements/IndexedElement.java Sun Feb 01 15:02:07 2015 -0800
42.3 @@ -33,9 +33,11 @@
42.4 import java.util.Collections;
42.5 import java.util.EnumSet;
42.6 import java.util.Set;
42.7 +import org.netbeans.modules.csl.api.ElementKind;
42.8 +import org.netbeans.modules.csl.api.Modifier;
42.9 +import org.netbeans.modules.csl.api.OffsetRange;
42.10 +import org.netbeans.modules.csl.spi.ParserResult;
42.11 import org.netbeans.modules.python.editor.PythonIndex;
42.12 -import org.netbeans.modules.gsf.api.ElementKind;
42.13 -import org.netbeans.modules.gsf.api.Modifier;
42.14 import org.netbeans.modules.python.editor.PythonAstUtils;
42.15 import org.openide.filesystems.FileObject;
42.16 import org.python.antlr.PythonTree;
43.1 --- a/python.editor/src/org/netbeans/modules/python/editor/elements/IndexedMethod.java Sun Jan 04 13:11:53 2015 -0600
43.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/elements/IndexedMethod.java Sun Feb 01 15:02:07 2015 -0800
43.3 @@ -30,7 +30,7 @@
43.4 */
43.5 package org.netbeans.modules.python.editor.elements;
43.6
43.7 -import org.netbeans.modules.gsf.api.ElementKind;
43.8 +import org.netbeans.modules.csl.api.ElementKind;
43.9
43.10 /**
43.11 *
44.1 --- a/python.editor/src/org/netbeans/modules/python/editor/elements/IndexedPackage.java Sun Jan 04 13:11:53 2015 -0600
44.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/elements/IndexedPackage.java Sun Feb 01 15:02:07 2015 -0800
44.3 @@ -43,8 +43,8 @@
44.4
44.5 import java.util.Collections;
44.6 import java.util.Set;
44.7 -import org.netbeans.modules.gsf.api.ElementKind;
44.8 -import org.netbeans.modules.gsf.api.Modifier;
44.9 +import org.netbeans.modules.csl.api.ElementKind;
44.10 +import org.netbeans.modules.csl.api.Modifier;
44.11
44.12 /**
44.13 *
45.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
45.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/file/PyDataObject.java Sun Feb 01 15:02:07 2015 -0800
45.3 @@ -0,0 +1,111 @@
45.4 +package org.netbeans.modules.python.editor.file;
45.5 +
45.6 +import java.io.IOException;
45.7 +import org.netbeans.core.spi.multiview.MultiViewElement;
45.8 +import org.netbeans.core.spi.multiview.text.MultiViewEditorElement;
45.9 +import org.netbeans.modules.python.api.PythonMIMEResolver;
45.10 +import org.openide.awt.ActionID;
45.11 +import org.openide.awt.ActionReference;
45.12 +import org.openide.awt.ActionReferences;
45.13 +import org.openide.filesystems.FileObject;
45.14 +import org.openide.filesystems.MIMEResolver;
45.15 +import org.openide.loaders.DataObject;
45.16 +import org.openide.loaders.DataObjectExistsException;
45.17 +import org.openide.loaders.MultiDataObject;
45.18 +import org.openide.loaders.MultiFileLoader;
45.19 +import org.openide.util.Lookup;
45.20 +import org.openide.util.NbBundle.Messages;
45.21 +import org.openide.windows.TopComponent;
45.22 +
45.23 +@Messages({
45.24 + "LBL_Py_LOADER=Files of Py"
45.25 +})
45.26 +@MIMEResolver.ExtensionRegistration(
45.27 + displayName = "#LBL_Py_LOADER",
45.28 + mimeType = PythonMIMEResolver.PYTHON_MIME_TYPE,
45.29 + extension = {"py"}
45.30 +)
45.31 +@DataObject.Registration(
45.32 + mimeType = PythonMIMEResolver.PYTHON_MIME_TYPE,
45.33 + iconBase = "org/netbeans/modules/python/editor/resources/pyNode25.png",
45.34 + displayName = "#LBL_Py_LOADER",
45.35 + position = 300
45.36 +)
45.37 +@ActionReferences({
45.38 + @ActionReference(
45.39 + path = "Loaders/text/x-python/Actions",
45.40 + id = @ActionID(category = "System", id = "org.openide.actions.OpenAction"),
45.41 + position = 100,
45.42 + separatorAfter = 200
45.43 + ),
45.44 + @ActionReference(
45.45 + path = "Loaders/text/x-python/Actions",
45.46 + id = @ActionID(category = "Edit", id = "org.openide.actions.CutAction"),
45.47 + position = 300
45.48 + ),
45.49 + @ActionReference(
45.50 + path = "Loaders/text/x-python/Actions",
45.51 + id = @ActionID(category = "Edit", id = "org.openide.actions.CopyAction"),
45.52 + position = 400,
45.53 + separatorAfter = 500
45.54 + ),
45.55 + @ActionReference(
45.56 + path = "Loaders/text/x-python/Actions",
45.57 + id = @ActionID(category = "Edit", id = "org.openide.actions.DeleteAction"),
45.58 + position = 600
45.59 + ),
45.60 + @ActionReference(
45.61 + path = "Loaders/text/x-python/Actions",
45.62 + id = @ActionID(category = "System", id = "org.openide.actions.RenameAction"),
45.63 + position = 700,
45.64 + separatorAfter = 800
45.65 + ),
45.66 + @ActionReference(
45.67 + path = "Loaders/text/x-python/Actions",
45.68 + id = @ActionID(category = "System", id = "org.openide.actions.SaveAsTemplateAction"),
45.69 + position = 900,
45.70 + separatorAfter = 1000
45.71 + ),
45.72 + @ActionReference(
45.73 + path = "Loaders/text/x-python/Actions",
45.74 + id = @ActionID(category = "System", id = "org.openide.actions.FileSystemAction"),
45.75 + position = 1100,
45.76 + separatorAfter = 1200
45.77 + ),
45.78 + @ActionReference(
45.79 + path = "Loaders/text/x-python/Actions",
45.80 + id = @ActionID(category = "System", id = "org.openide.actions.ToolsAction"),
45.81 + position = 1300
45.82 + ),
45.83 + @ActionReference(
45.84 + path = "Loaders/text/x-python/Actions",
45.85 + id = @ActionID(category = "System", id = "org.openide.actions.PropertiesAction"),
45.86 + position = 1400
45.87 + )
45.88 +})
45.89 +public class PyDataObject extends MultiDataObject {
45.90 +
45.91 + public PyDataObject(FileObject pf, MultiFileLoader loader) throws DataObjectExistsException, IOException {
45.92 + super(pf, loader);
45.93 + registerEditor(PythonMIMEResolver.PYTHON_MIME_TYPE, true);
45.94 + }
45.95 +
45.96 + @Override
45.97 + protected int associateLookup() {
45.98 + return 1;
45.99 + }
45.100 +
45.101 + @MultiViewElement.Registration(
45.102 + displayName = "#LBL_Py_EDITOR",
45.103 + iconBase = "org/netbeans/modules/python/editor/resources/pyNode25.png",
45.104 + mimeType = PythonMIMEResolver.PYTHON_MIME_TYPE,
45.105 + persistenceType = TopComponent.PERSISTENCE_ONLY_OPENED,
45.106 + preferredID = "Py",
45.107 + position = 1000
45.108 + )
45.109 + @Messages("LBL_Py_EDITOR=Source")
45.110 + public static MultiViewEditorElement createEditor(Lookup lkp) {
45.111 + return new MultiViewEditorElement(lkp);
45.112 + }
45.113 +
45.114 +}
46.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
46.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/file/PythonTemplateAttributesProvider.java Sun Feb 01 15:02:07 2015 -0800
46.3 @@ -0,0 +1,64 @@
46.4 +/*
46.5 + * To change this license header, choose License Headers in Project Properties.
46.6 + * To change this template file, choose Tools | Templates
46.7 + * and open the template in the editor.
46.8 + */
46.9 +package org.netbeans.modules.python.editor.file;
46.10 +
46.11 +import java.util.HashMap;
46.12 +import java.util.Map;
46.13 +import java.util.logging.Level;
46.14 +import java.util.logging.Logger;
46.15 +import org.netbeans.api.java.classpath.ClassPath;
46.16 +import org.netbeans.modules.python.api.PythonMIMEResolver;
46.17 +import org.netbeans.modules.python.source.queries.SourceLevelQuery;
46.18 +import org.openide.filesystems.FileObject;
46.19 +import org.openide.loaders.CreateFromTemplateAttributesProvider;
46.20 +import org.openide.loaders.DataFolder;
46.21 +import org.openide.loaders.DataObject;
46.22 +import org.openide.modules.SpecificationVersion;
46.23 +import org.openide.util.lookup.ServiceProvider;
46.24 +
46.25 +/**
46.26 + *
46.27 + * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
46.28 + */
46.29 +@ServiceProvider(service = CreateFromTemplateAttributesProvider.class)
46.30 +public class PythonTemplateAttributesProvider implements CreateFromTemplateAttributesProvider {
46.31 +
46.32 + private static final Logger LOG = Logger.getLogger(PythonTemplateAttributesProvider.class.getName());
46.33 + private static final SpecificationVersion VER30 = new SpecificationVersion("3.0");
46.34 +
46.35 + @Override
46.36 + public Map<String, ?> attributesFor(DataObject template, DataFolder target, String name) {
46.37 + FileObject templateFO = template.getPrimaryFile();
46.38 + if (!PythonMIMEResolver.PYTHON_EXTENSION.equals(templateFO.getExt()) || templateFO.isFolder()) {
46.39 + return null;
46.40 + }
46.41 +
46.42 + FileObject targetFO = target.getPrimaryFile();
46.43 + Map<String,Object> result = new HashMap<String,Object>();
46.44 +
46.45 + ClassPath cp = ClassPath.getClassPath(targetFO, ClassPath.SOURCE);
46.46 + if (cp == null) {
46.47 + LOG.log(Level.WARNING, "No classpath was found for folder: {0}", target.getPrimaryFile()); // NOI18N
46.48 + }
46.49 + else {
46.50 + result.put("package", cp.getResourceName(targetFO, '.', false)); // NOI18N
46.51 + }
46.52 +
46.53 + String sourceLevel = SourceLevelQuery.getSourceLevel(targetFO);
46.54 + if (sourceLevel != null) {
46.55 + result.put("pythonSourceLevel", sourceLevel); // NOI18N
46.56 + if (isPython3orLater(sourceLevel))
46.57 + result.put("python3style", Boolean.TRUE); // NOI18N
46.58 + }
46.59 +
46.60 + return result;
46.61 + }
46.62 +
46.63 + private boolean isPython3orLater(String sourceLevel) {
46.64 + SpecificationVersion ver = new SpecificationVersion(sourceLevel);
46.65 + return (ver.compareTo(VER30) >= 0);
46.66 + }
46.67 +}
47.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
47.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/file/package-info.java Sun Feb 01 15:02:07 2015 -0800
47.3 @@ -0,0 +1,6 @@
47.4 +/*
47.5 + * To change this license header, choose License Headers in Project Properties.
47.6 + * To change this template file, choose Tools | Templates
47.7 + * and open the template in the editor.
47.8 + */
47.9 +package org.netbeans.modules.python.editor.file;
48.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/AccessToProtected.java Sun Jan 04 13:11:53 2015 -0600
48.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/AccessToProtected.java Sun Feb 01 15:02:07 2015 -0800
48.3 @@ -46,13 +46,13 @@
48.4 import java.util.Set;
48.5 import java.util.prefs.Preferences;
48.6 import javax.swing.JComponent;
48.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
48.8 -import org.netbeans.modules.gsf.api.Hint;
48.9 -import org.netbeans.modules.gsf.api.HintFix;
48.10 -import org.netbeans.modules.gsf.api.HintSeverity;
48.11 -import org.netbeans.modules.gsf.api.OffsetRange;
48.12 -import org.netbeans.modules.gsf.api.RuleContext;
48.13 +import org.netbeans.modules.csl.api.Hint;
48.14 +import org.netbeans.modules.csl.api.HintFix;
48.15 +import org.netbeans.modules.csl.api.HintSeverity;
48.16 +import org.netbeans.modules.csl.api.OffsetRange;
48.17 +import org.netbeans.modules.csl.api.RuleContext;
48.18 import org.netbeans.modules.python.editor.PythonAstUtils;
48.19 +import org.netbeans.modules.python.editor.PythonParserResult;
48.20 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
48.21 import org.netbeans.modules.python.editor.scopes.SymInfo;
48.22 import org.openide.util.NbBundle;
48.23 @@ -76,7 +76,7 @@
48.24
48.25 @Override
48.26 public void run(PythonRuleContext context, List<Hint> result) {
48.27 - CompilationInfo info = context.compilationInfo;
48.28 + PythonParserResult info = (PythonParserResult) context.parserResult;
48.29 Attribute cur = (Attribute)context.node;
48.30 String curAttr = cur.getInternalAttr();
48.31 if (curAttr == null) {
48.32 @@ -101,7 +101,7 @@
48.33 if (range != OffsetRange.NONE) {
48.34 List<HintFix> fixList = Collections.emptyList();
48.35 String message = NbBundle.getMessage(NameRule.class, ACCESS_PROTECTED_VARIABLE, curAttr);
48.36 - Hint desc = new Hint(this, message, info.getFileObject(), range, fixList, 2305);
48.37 + Hint desc = new Hint(this, message, info.getSnapshot().getSource().getFileObject(), range, fixList, 2305);
48.38 result.add(desc);
48.39 }
48.40 }
49.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/AllAssignExists.java Sun Jan 04 13:11:53 2015 -0600
49.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/AllAssignExists.java Sun Feb 01 15:02:07 2015 -0800
49.3 @@ -46,12 +46,11 @@
49.4 import java.util.Set;
49.5 import java.util.prefs.Preferences;
49.6 import javax.swing.JComponent;
49.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
49.8 -import org.netbeans.modules.gsf.api.Hint;
49.9 -import org.netbeans.modules.gsf.api.HintFix;
49.10 -import org.netbeans.modules.gsf.api.HintSeverity;
49.11 -import org.netbeans.modules.gsf.api.OffsetRange;
49.12 -import org.netbeans.modules.gsf.api.RuleContext;
49.13 +import org.netbeans.modules.csl.api.Hint;
49.14 +import org.netbeans.modules.csl.api.HintFix;
49.15 +import org.netbeans.modules.csl.api.HintSeverity;
49.16 +import org.netbeans.modules.csl.api.OffsetRange;
49.17 +import org.netbeans.modules.csl.api.RuleContext;
49.18 import org.netbeans.modules.python.editor.PythonAstUtils;
49.19 import org.netbeans.modules.python.editor.PythonParserResult;
49.20 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
49.21 @@ -92,13 +91,13 @@
49.22 SymInfo sym = topScope.tbl.get(name);
49.23 if (sym == null) {
49.24 // Uh oh -- missing!
49.25 - CompilationInfo info = context.compilationInfo;
49.26 + PythonParserResult info = (PythonParserResult) context.parserResult;
49.27 OffsetRange range = PythonAstUtils.getNameRange(info, str);
49.28 range = PythonLexerUtils.getLexerOffsets(info, range);
49.29 if (range != OffsetRange.NONE) {
49.30 List<HintFix> fixList = Collections.emptyList();
49.31 String message = NbBundle.getMessage(AllAssignExists.class, "AllAssignExistsMsg", name);
49.32 - Hint desc = new Hint(this, message, info.getFileObject(), range, fixList, 205);
49.33 + Hint desc = new Hint(this, message, info.getSnapshot().getSource().getFileObject(), range, fixList, 205);
49.34 result.add(desc);
49.35 }
49.36 }
50.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/AssignToVariable.java Sun Jan 04 13:11:53 2015 -0600
50.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/AssignToVariable.java Sun Feb 01 15:02:07 2015 -0800
50.3 @@ -54,15 +54,15 @@
50.4 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
50.5 import org.netbeans.editor.BaseDocument;
50.6 import org.netbeans.editor.Utilities;
50.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
50.8 -import org.netbeans.modules.gsf.api.EditList;
50.9 -import org.netbeans.modules.gsf.api.Hint;
50.10 -import org.netbeans.modules.gsf.api.HintFix;
50.11 -import org.netbeans.modules.gsf.api.HintSeverity;
50.12 -import org.netbeans.modules.gsf.api.OffsetRange;
50.13 -import org.netbeans.modules.gsf.api.PreviewableFix;
50.14 -import org.netbeans.modules.gsf.api.RuleContext;
50.15 -import org.netbeans.modules.gsf.spi.GsfUtilities;
50.16 +import org.netbeans.modules.csl.api.EditList;
50.17 +import org.netbeans.modules.csl.api.Hint;
50.18 +import org.netbeans.modules.csl.api.HintFix;
50.19 +import org.netbeans.modules.csl.api.HintSeverity;
50.20 +import org.netbeans.modules.csl.api.OffsetRange;
50.21 +import org.netbeans.modules.csl.api.PreviewableFix;
50.22 +import org.netbeans.modules.csl.api.RuleContext;
50.23 +import org.netbeans.modules.csl.spi.GsfUtilities;
50.24 +import org.netbeans.modules.python.editor.PythonParserResult;
50.25 import org.openide.util.Exceptions;
50.26 import org.openide.util.NbBundle;
50.27 import org.python.antlr.PythonTree;
50.28 @@ -114,7 +114,7 @@
50.29 return;
50.30 }
50.31 }
50.32 - CompilationInfo info = context.compilationInfo;
50.33 + PythonParserResult info = (PythonParserResult) context.parserResult;
50.34 OffsetRange astOffsets = PythonAstUtils.getNameRange(info, node);
50.35 OffsetRange lexOffsets = PythonLexerUtils.getLexerOffsets(info, astOffsets);
50.36 BaseDocument doc = context.doc;
50.37 @@ -125,7 +125,7 @@
50.38 List<HintFix> fixList = new ArrayList<HintFix>();
50.39 fixList.add(new AssignToVariableFix(context, node));
50.40 String displayName = getDisplayName();
50.41 - Hint desc = new Hint(this, displayName, info.getFileObject(), lexOffsets, fixList, 1500);
50.42 + Hint desc = new Hint(this, displayName, info.getSnapshot().getSource().getFileObject(), lexOffsets, fixList, 1500);
50.43 result.add(desc);
50.44 }
50.45 } catch (BadLocationException ex) {
50.46 @@ -190,7 +190,7 @@
50.47
50.48 OffsetRange astRange = PythonAstUtils.getRange(node);
50.49 if (astRange != OffsetRange.NONE) {
50.50 - OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(context.compilationInfo, astRange);
50.51 + OffsetRange lexRange = PythonLexerUtils.getLexerOffsets((PythonParserResult) context.parserResult, astRange);
50.52 if (lexRange != OffsetRange.NONE) {
50.53 int offset = lexRange.getStart();
50.54 StringBuilder sb = new StringBuilder();
50.55 @@ -211,7 +211,7 @@
50.56 Position pos = edits.createPosition(varOffset);
50.57 edits.apply();
50.58 if (pos != null && pos.getOffset() != -1) {
50.59 - JTextComponent target = GsfUtilities.getPaneFor(context.compilationInfo.getFileObject());
50.60 + JTextComponent target = GsfUtilities.getPaneFor(context.parserResult.getSnapshot().getSource().getFileObject());
50.61 if (target != null) {
50.62 int start = pos.getOffset();
50.63 int end = start + varName.length();
51.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/AttributeDefinedOutsideInit.java Sun Jan 04 13:11:53 2015 -0600
51.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/AttributeDefinedOutsideInit.java Sun Feb 01 15:02:07 2015 -0800
51.3 @@ -46,12 +46,11 @@
51.4 import java.util.Set;
51.5 import java.util.prefs.Preferences;
51.6 import javax.swing.JComponent;
51.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
51.8 -import org.netbeans.modules.gsf.api.Hint;
51.9 -import org.netbeans.modules.gsf.api.HintFix;
51.10 -import org.netbeans.modules.gsf.api.HintSeverity;
51.11 -import org.netbeans.modules.gsf.api.OffsetRange;
51.12 -import org.netbeans.modules.gsf.api.RuleContext;
51.13 +import org.netbeans.modules.csl.api.Hint;
51.14 +import org.netbeans.modules.csl.api.HintFix;
51.15 +import org.netbeans.modules.csl.api.HintSeverity;
51.16 +import org.netbeans.modules.csl.api.OffsetRange;
51.17 +import org.netbeans.modules.csl.api.RuleContext;
51.18 import org.netbeans.modules.python.editor.PythonAstUtils;
51.19 import org.netbeans.modules.python.editor.PythonParserResult;
51.20 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
51.21 @@ -76,7 +75,7 @@
51.22
51.23 @Override
51.24 public void run(PythonRuleContext context, List<Hint> result) {
51.25 - CompilationInfo info = context.compilationInfo;
51.26 + PythonParserResult info = (PythonParserResult) context.parserResult;
51.27 PythonParserResult pr = PythonAstUtils.getParseResult(info);
51.28 SymbolTable symbolTable = pr.getSymbolTable();
51.29
51.30 @@ -91,7 +90,7 @@
51.31 String message = NbBundle.getMessage(NameRule.class,
51.32 ATTRIBUTE_DEFINED_OUTSITE_INIT_VAR,
51.33 cur.getInternalAttr());
51.34 - Hint desc = new Hint(this, message, info.getFileObject(), range, fixList, 2305);
51.35 + Hint desc = new Hint(this, message, info.getSnapshot().getSource().getFileObject(), range, fixList, 2305);
51.36 result.add(desc);
51.37 }
51.38 }
52.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/ClassCircularRedundancy.java Sun Jan 04 13:11:53 2015 -0600
52.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/ClassCircularRedundancy.java Sun Feb 01 15:02:07 2015 -0800
52.3 @@ -48,12 +48,11 @@
52.4 import java.util.Set;
52.5 import java.util.prefs.Preferences;
52.6 import javax.swing.JComponent;
52.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
52.8 -import org.netbeans.modules.gsf.api.Hint;
52.9 -import org.netbeans.modules.gsf.api.HintFix;
52.10 -import org.netbeans.modules.gsf.api.HintSeverity;
52.11 -import org.netbeans.modules.gsf.api.OffsetRange;
52.12 -import org.netbeans.modules.gsf.api.RuleContext;
52.13 +import org.netbeans.modules.csl.api.Hint;
52.14 +import org.netbeans.modules.csl.api.HintFix;
52.15 +import org.netbeans.modules.csl.api.HintSeverity;
52.16 +import org.netbeans.modules.csl.api.OffsetRange;
52.17 +import org.netbeans.modules.csl.api.RuleContext;
52.18 import org.netbeans.modules.python.editor.PythonAstUtils;
52.19 import org.netbeans.modules.python.editor.PythonParserResult;
52.20 import org.netbeans.modules.python.editor.scopes.SymbolTable;
52.21 @@ -77,9 +76,8 @@
52.22
52.23 @Override
52.24 public void run(PythonRuleContext context, List<Hint> result) {
52.25 - CompilationInfo info = context.compilationInfo;
52.26 - PythonParserResult pr = PythonAstUtils.getParseResult(info);
52.27 - SymbolTable symbolTable = pr.getSymbolTable();
52.28 + PythonParserResult info = (PythonParserResult) context.parserResult;
52.29 + SymbolTable symbolTable = info.getSymbolTable();
52.30
52.31
52.32 HashMap<ClassDef, String> cyclingRedundancies = symbolTable.getClassesCyclingRedundancies(info);
52.33 @@ -93,7 +91,7 @@
52.34 if (range != OffsetRange.NONE) {
52.35 List<HintFix> fixList = Collections.emptyList();
52.36 String message = NbBundle.getMessage(NameRule.class, CLASS_CIRCULAR_REDUNDANCY_VAR, curCyclingMsg);
52.37 - Hint desc = new Hint(this, message, info.getFileObject(), range, fixList, 2305);
52.38 + Hint desc = new Hint(this, message, info.getSnapshot().getSource().getFileObject(), range, fixList, 2305);
52.39 result.add(desc);
52.40 }
52.41 }
53.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/CreateDocString.java Sun Jan 04 13:11:53 2015 -0600
53.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/CreateDocString.java Sun Feb 01 15:02:07 2015 -0800
53.3 @@ -47,16 +47,16 @@
53.4 import org.netbeans.api.lexer.TokenSequence;
53.5 import org.netbeans.editor.BaseDocument;
53.6 import org.netbeans.editor.Utilities;
53.7 +import org.netbeans.modules.csl.api.EditList;
53.8 +import org.netbeans.modules.csl.api.Hint;
53.9 +import org.netbeans.modules.csl.api.HintFix;
53.10 +import org.netbeans.modules.csl.api.HintSeverity;
53.11 +import org.netbeans.modules.csl.api.OffsetRange;
53.12 +import org.netbeans.modules.csl.api.PreviewableFix;
53.13 +import org.netbeans.modules.csl.api.RuleContext;
53.14 +import org.netbeans.modules.csl.spi.GsfUtilities;
53.15 import org.netbeans.modules.editor.indent.api.IndentUtils;
53.16 -import org.netbeans.modules.gsf.api.CompilationInfo;
53.17 -import org.netbeans.modules.gsf.api.EditList;
53.18 -import org.netbeans.modules.gsf.api.Hint;
53.19 -import org.netbeans.modules.gsf.api.HintFix;
53.20 -import org.netbeans.modules.gsf.api.HintSeverity;
53.21 -import org.netbeans.modules.gsf.api.OffsetRange;
53.22 -import org.netbeans.modules.gsf.api.PreviewableFix;
53.23 -import org.netbeans.modules.gsf.api.RuleContext;
53.24 -import org.netbeans.modules.gsf.spi.GsfUtilities;
53.25 +import org.netbeans.modules.python.editor.PythonParserResult;
53.26 import org.openide.util.Exceptions;
53.27 import org.openide.util.NbBundle;
53.28 import org.python.antlr.PythonTree;
53.29 @@ -89,7 +89,7 @@
53.30 }
53.31
53.32 // Create new fix
53.33 - CompilationInfo info = context.compilationInfo;
53.34 + PythonParserResult info = (PythonParserResult) context.parserResult;
53.35 OffsetRange astOffsets = PythonAstUtils.getNameRange(info, node);
53.36 OffsetRange lexOffsets = PythonLexerUtils.getLexerOffsets(info, astOffsets);
53.37 BaseDocument doc = context.doc;
53.38 @@ -102,7 +102,7 @@
53.39 fixList.add(new CreateDocStringFix(context, node, !singleIsDefault));
53.40 fixList.add(new CreateDocStringFix(context, node, singleIsDefault));
53.41 String displayName = getDisplayName();
53.42 - Hint desc = new Hint(this, displayName, info.getFileObject(), lexOffsets, fixList, 1500);
53.43 + Hint desc = new Hint(this, displayName, info.getSnapshot().getSource().getFileObject(), lexOffsets, fixList, 1500);
53.44 result.add(desc);
53.45 }
53.46 } catch (BadLocationException ex) {
53.47 @@ -168,7 +168,7 @@
53.48
53.49 OffsetRange astRange = PythonAstUtils.getRange(node);
53.50 if (astRange != OffsetRange.NONE) {
53.51 - OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(context.compilationInfo, astRange);
53.52 + OffsetRange lexRange = PythonLexerUtils.getLexerOffsets((PythonParserResult) context.parserResult, astRange);
53.53 if (lexRange != OffsetRange.NONE) {
53.54 // Find the colon
53.55 TokenSequence<? extends PythonTokenId> ts = PythonLexerUtils.getPositionedSequence(doc, lexRange.getStart());
53.56 @@ -209,7 +209,7 @@
53.57 Position pos = edits.createPosition(editListPosition);
53.58 edits.apply();
53.59 if (pos != null && pos.getOffset() != -1) {
53.60 - JTextComponent target = GsfUtilities.getPaneFor(context.compilationInfo.getFileObject());
53.61 + JTextComponent target = GsfUtilities.getPaneFor(context.parserResult.getSnapshot().getSource().getFileObject());
53.62 if (target != null) {
53.63 target.setCaretPosition(pos.getOffset());
53.64 }
54.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/Deprecations.java Sun Jan 04 13:11:53 2015 -0600
54.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/Deprecations.java Sun Feb 01 15:02:07 2015 -0800
54.3 @@ -54,12 +54,12 @@
54.4 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
54.5 import org.netbeans.editor.BaseDocument;
54.6 import org.netbeans.editor.Utilities;
54.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
54.8 -import org.netbeans.modules.gsf.api.Hint;
54.9 -import org.netbeans.modules.gsf.api.HintFix;
54.10 -import org.netbeans.modules.gsf.api.HintSeverity;
54.11 -import org.netbeans.modules.gsf.api.OffsetRange;
54.12 -import org.netbeans.modules.gsf.api.RuleContext;
54.13 +import org.netbeans.modules.csl.api.Hint;
54.14 +import org.netbeans.modules.csl.api.HintFix;
54.15 +import org.netbeans.modules.csl.api.HintSeverity;
54.16 +import org.netbeans.modules.csl.api.OffsetRange;
54.17 +import org.netbeans.modules.csl.api.RuleContext;
54.18 +import org.netbeans.modules.python.editor.PythonParserResult;
54.19 import org.openide.util.Exceptions;
54.20 import org.openide.util.NbBundle;
54.21 import org.python.antlr.PythonTree;
54.22 @@ -228,7 +228,7 @@
54.23 }
54.24
54.25 private void addDeprecation(String module, String rationale, PythonRuleContext context, List<Hint> result) {
54.26 - CompilationInfo info = context.compilationInfo;
54.27 + PythonParserResult info = (PythonParserResult) context.parserResult;
54.28 OffsetRange astOffsets = PythonAstUtils.getNameRange(info, context.node);
54.29 OffsetRange lexOffsets = PythonLexerUtils.getLexerOffsets(info, astOffsets);
54.30 BaseDocument doc = context.doc;
54.31 @@ -243,7 +243,7 @@
54.32 } else {
54.33 displayName = NbBundle.getMessage(Deprecations.class, "DeprecationsMsg", module);
54.34 }
54.35 - Hint desc = new Hint(this, displayName, info.getFileObject(), lexOffsets, fixList, 1500);
54.36 + Hint desc = new Hint(this, displayName, info.getSnapshot().getSource().getFileObject(), lexOffsets, fixList, 1500);
54.37 result.add(desc);
54.38 }
54.39 } catch (BadLocationException ex) {
55.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/ExtractCode.java Sun Jan 04 13:11:53 2015 -0600
55.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/ExtractCode.java Sun Feb 01 15:02:07 2015 -0800
55.3 @@ -40,19 +40,19 @@
55.4 import javax.swing.text.JTextComponent;
55.5 import org.netbeans.editor.BaseDocument;
55.6 import org.netbeans.editor.Utilities;
55.7 +import org.netbeans.modules.csl.api.EditList;
55.8 +import org.netbeans.modules.csl.api.EditRegions;
55.9 +import org.netbeans.modules.csl.api.Hint;
55.10 +import org.netbeans.modules.csl.api.HintFix;
55.11 +import org.netbeans.modules.csl.api.HintSeverity;
55.12 +import org.netbeans.modules.csl.api.OffsetRange;
55.13 +import org.netbeans.modules.csl.api.PreviewableFix;
55.14 +import org.netbeans.modules.csl.api.RuleContext;
55.15 +import org.netbeans.modules.csl.spi.GsfUtilities;
55.16 import org.netbeans.modules.editor.indent.api.IndentUtils;
55.17 -import org.netbeans.modules.gsf.api.CompilationInfo;
55.18 -import org.netbeans.modules.gsf.api.EditList;
55.19 -import org.netbeans.modules.gsf.api.EditRegions;
55.20 -import org.netbeans.modules.gsf.api.Hint;
55.21 -import org.netbeans.modules.gsf.api.HintFix;
55.22 -import org.netbeans.modules.gsf.api.HintSeverity;
55.23 -import org.netbeans.modules.gsf.api.OffsetRange;
55.24 -import org.netbeans.modules.gsf.api.PreviewableFix;
55.25 -import org.netbeans.modules.gsf.api.RuleContext;
55.26 -import org.netbeans.modules.gsf.spi.GsfUtilities;
55.27 import org.netbeans.modules.python.editor.AstPath;
55.28 import org.netbeans.modules.python.editor.PythonAstUtils;
55.29 +import org.netbeans.modules.python.editor.PythonParserResult;
55.30 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
55.31 import org.openide.util.Exceptions;
55.32 import org.openide.util.NbBundle;
55.33 @@ -124,7 +124,7 @@
55.34
55.35 // Adjust the fix range to be right around the dot so that the light bulb ends up
55.36 // on the same line as the caret and alt-enter works
55.37 - JTextComponent target = GsfUtilities.getPaneFor(context.compilationInfo.getFileObject());
55.38 + JTextComponent target = GsfUtilities.getPaneFor(context.parserResult.getSnapshot().getSource().getFileObject());
55.39 if (target != null) {
55.40 int dot = target.getCaret().getDot();
55.41 range = new OffsetRange(dot, dot);
55.42 @@ -145,7 +145,7 @@
55.43 }
55.44 if (fixList.size() > 0) {
55.45 String displayName = getDisplayName();
55.46 - Hint desc = new Hint(this, displayName, context.compilationInfo.getFileObject(),
55.47 + Hint desc = new Hint(this, displayName, context.parserResult.getSnapshot().getSource().getFileObject(),
55.48 range, fixList, 490);
55.49 result.add(desc);
55.50 }
55.51 @@ -227,7 +227,7 @@
55.52
55.53 public EditList getEditList() throws Exception {
55.54 BaseDocument doc = context.doc;
55.55 - CompilationInfo info = context.compilationInfo;
55.56 + PythonParserResult info = (PythonParserResult) context.parserResult;
55.57 EditList edits = new EditList(doc);
55.58
55.59 int extractedOffset = doc.getLength();
55.60 @@ -473,7 +473,7 @@
55.61 ranges.add(new OffsetRange(finalExtractedSiteOffset, finalExtractedSiteOffset + length));
55.62
55.63 // Initiate synchronous editing:
55.64 - EditRegions.getInstance().edit(context.compilationInfo.getFileObject(), ranges, finalExtractedSiteOffset);
55.65 + EditRegions.getInstance().edit(context.parserResult.getSnapshot().getSource().getFileObject(), ranges, finalExtractedSiteOffset);
55.66 }
55.67
55.68 public boolean isSafe() {
56.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/NameRule.java Sun Jan 04 13:11:53 2015 -0600
56.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/NameRule.java Sun Feb 01 15:02:07 2015 -0800
56.3 @@ -39,17 +39,17 @@
56.4 import javax.swing.JComponent;
56.5 import org.netbeans.editor.BaseDocument;
56.6 import org.netbeans.editor.Utilities;
56.7 +import org.netbeans.modules.csl.api.EditList;
56.8 +import org.netbeans.modules.csl.api.Hint;
56.9 +import org.netbeans.modules.csl.api.HintFix;
56.10 +import org.netbeans.modules.csl.api.HintSeverity;
56.11 +import org.netbeans.modules.csl.api.OffsetRange;
56.12 +import org.netbeans.modules.csl.api.PreviewableFix;
56.13 +import org.netbeans.modules.csl.api.RuleContext;
56.14 import org.netbeans.modules.python.editor.PythonAstUtils;
56.15 +import org.netbeans.modules.python.editor.PythonParserResult;
56.16 import org.netbeans.modules.python.editor.PythonUtils;
56.17 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
56.18 -import org.netbeans.modules.gsf.api.CompilationInfo;
56.19 -import org.netbeans.modules.gsf.api.EditList;
56.20 -import org.netbeans.modules.gsf.api.OffsetRange;
56.21 -import org.netbeans.modules.gsf.api.Hint;
56.22 -import org.netbeans.modules.gsf.api.HintFix;
56.23 -import org.netbeans.modules.gsf.api.HintSeverity;
56.24 -import org.netbeans.modules.gsf.api.PreviewableFix;
56.25 -import org.netbeans.modules.gsf.api.RuleContext;
56.26 import org.openide.util.NbBundle;
56.27 import org.python.antlr.PythonTree;
56.28 import org.python.antlr.ast.ClassDef;
56.29 @@ -122,7 +122,7 @@
56.30 PythonTree node = context.node;
56.31 if (node instanceof Module) {
56.32 if (moduleStyle != NO_PREFERENCE) {
56.33 - String moduleName = PythonUtils.getModuleName(context.compilationInfo.getFileObject(), null);
56.34 + String moduleName = PythonUtils.getModuleName(context.parserResult.getSnapshot().getSource().getFileObject());
56.35 if (!moduleStyle.complies(moduleName) && !moduleStyle.complies(moduleName.substring(moduleName.lastIndexOf('.') + 1))) {
56.36 String typeKey = "Module"; // NOI18N
56.37 String message = NbBundle.getMessage(NameRule.class, "WrongStyle", moduleName,
56.38 @@ -220,12 +220,13 @@
56.39 }
56.40 }
56.41 }
56.42 -
56.43 - CompilationInfo info = context.compilationInfo;
56.44 +
56.45 + PythonParserResult info = (PythonParserResult)context.parserResult;
56.46 OffsetRange range;
56.47 if (node instanceof Module) {
56.48 range = new OffsetRange(0, 0);
56.49 } else {
56.50 +
56.51 range = PythonAstUtils.getNameRange(info, node);
56.52 }
56.53 range = PythonLexerUtils.getLexerOffsets(info, range);
56.54 @@ -233,7 +234,7 @@
56.55 if (fixList == null) {
56.56 fixList = Collections.emptyList();
56.57 }
56.58 - Hint desc = new Hint(this, message, info.getFileObject(), range, fixList, 1500);
56.59 + Hint desc = new Hint(this, message, info.getSnapshot().getSource().getFileObject(), range, fixList, 1500);
56.60 result.add(desc);
56.61 }
56.62 }
56.63 @@ -435,8 +436,8 @@
56.64 BaseDocument doc = context.doc;
56.65 EditList edits = new EditList(doc);
56.66
56.67 - OffsetRange astRange = PythonAstUtils.getNameRange(context.compilationInfo, func);
56.68 - OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(context.compilationInfo, astRange);
56.69 + OffsetRange astRange = PythonAstUtils.getNameRange((PythonParserResult) context.parserResult, func);
56.70 + OffsetRange lexRange = PythonLexerUtils.getLexerOffsets((PythonParserResult) context.parserResult, astRange);
56.71 if (lexRange == OffsetRange.NONE) {
56.72 return edits;
56.73 }
57.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/PythonAstRule.java Sun Jan 04 13:11:53 2015 -0600
57.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/PythonAstRule.java Sun Feb 01 15:02:07 2015 -0800
57.3 @@ -32,8 +32,8 @@
57.4
57.5 import java.util.List;
57.6 import java.util.Set;
57.7 -import org.netbeans.modules.gsf.api.Hint;
57.8 -import org.netbeans.modules.gsf.api.Rule.AstRule;
57.9 +import org.netbeans.modules.csl.api.Hint;
57.10 +import org.netbeans.modules.csl.api.Rule.AstRule;
57.11
57.12 public abstract class PythonAstRule implements AstRule {
57.13 /**
58.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/PythonHintsProvider.java Sun Jan 04 13:11:53 2015 -0600
58.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/PythonHintsProvider.java Sun Feb 01 15:02:07 2015 -0800
58.3 @@ -38,19 +38,19 @@
58.4 import java.util.Map;
58.5 import java.util.Map.Entry;
58.6 import java.util.Set;
58.7 -import org.netbeans.modules.gsf.api.HintSeverity;
58.8 +import org.netbeans.modules.csl.api.Error;
58.9 +import org.netbeans.modules.csl.api.Hint;
58.10 +import org.netbeans.modules.csl.api.HintFix;
58.11 +import org.netbeans.modules.csl.api.HintSeverity;
58.12 +import org.netbeans.modules.csl.api.HintsProvider;
58.13 +import org.netbeans.modules.csl.api.HintsProvider.HintsManager;
58.14 +import org.netbeans.modules.csl.api.OffsetRange;
58.15 +import org.netbeans.modules.csl.api.Rule;
58.16 +import org.netbeans.modules.csl.api.RuleContext;
58.17 +import org.netbeans.modules.csl.spi.GsfUtilities;
58.18 +import org.netbeans.modules.csl.spi.ParserResult;
58.19 import org.netbeans.modules.python.editor.AstPath;
58.20 import org.netbeans.modules.python.editor.PythonAstUtils;
58.21 -import org.netbeans.modules.gsf.api.CompilationInfo;
58.22 -import org.netbeans.modules.gsf.api.Error;
58.23 -import org.netbeans.modules.gsf.api.Hint;
58.24 -import org.netbeans.modules.gsf.api.HintFix;
58.25 -import org.netbeans.modules.gsf.api.HintsProvider;
58.26 -import org.netbeans.modules.gsf.api.OffsetRange;
58.27 -import org.netbeans.modules.gsf.api.ParserResult;
58.28 -import org.netbeans.modules.gsf.api.Rule;
58.29 -import org.netbeans.modules.gsf.api.RuleContext;
58.30 -import org.netbeans.modules.gsf.spi.GsfUtilities;
58.31 import org.netbeans.modules.python.editor.PythonParserResult;
58.32 import org.openide.util.Exceptions;
58.33 import org.python.antlr.PythonTree;
58.34 @@ -89,7 +89,7 @@
58.35 return HintSeverity.ERROR;
58.36 }
58.37 }
58.38 -
58.39 +
58.40 public void computeErrors(HintsManager manager, RuleContext context, List<Hint> result, List<Error> unhandled) {
58.41 ParserResult parserResult = context.parserResult;
58.42 if (parserResult == null) {
58.43 @@ -108,7 +108,7 @@
58.44 }
58.45 }
58.46
58.47 - List<Error> errors = parserResult.getDiagnostics();
58.48 + List<? extends Error> errors = parserResult.getDiagnostics();
58.49 if (errors == null || errors.size() == 0) {
58.50 return;
58.51 }
58.52 @@ -147,7 +147,7 @@
58.53 return;
58.54 }
58.55 @SuppressWarnings("unchecked")
58.56 - List<PythonSelectionRule> hints = (List<PythonSelectionRule>)manager.getSelectionHints();
58.57 + List<? extends Rule.SelectionRule> hints = manager.getSelectionHints();
58.58
58.59 if (hints.isEmpty()) {
58.60 return;
58.61 @@ -165,22 +165,26 @@
58.62 }
58.63 }
58.64
58.65 - private void applySelectionRules(HintsManager manager, RuleContext context, List<PythonSelectionRule> rules, List<Hint> result) {
58.66 + private void applySelectionRules(HintsManager manager, RuleContext context, List<? extends Rule.SelectionRule> rules, List<Hint> result) {
58.67
58.68 PythonRuleContext pythonContext = (PythonRuleContext)context;
58.69
58.70 - for (PythonSelectionRule rule : rules) {
58.71 + for (Rule.SelectionRule rule : rules) {
58.72 if (!rule.appliesTo(context)) {
58.73 continue;
58.74 }
58.75 +
58.76 + if(!(rule instanceof PythonSelectionRule)) {
58.77 + continue;
58.78 + }
58.79
58.80 - if (!manager.isEnabled(rule)) {
58.81 + if (!manager.isEnabled((PythonSelectionRule)rule)) {
58.82 continue;
58.83 }
58.84
58.85 try {
58.86 context.doc.readLock();
58.87 - rule.run(pythonContext, result);
58.88 + ((PythonSelectionRule)rule).run(pythonContext, result);
58.89 } finally {
58.90 context.doc.readUnlock();
58.91 }
58.92 @@ -274,7 +278,7 @@
58.93 try {
58.94 context.doc.readLock();
58.95
58.96 - CompilationInfo info = context.compilationInfo;
58.97 + PythonParserResult info = (PythonParserResult)context.parserResult;
58.98 int astOffset = PythonAstUtils.getAstOffset(info, caretOffset);
58.99 AstPath path = AstPath.get(root, astOffset);
58.100 Iterator<PythonTree> it = path.leafToRoot();
59.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/PythonRuleContext.java Sun Jan 04 13:11:53 2015 -0600
59.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/PythonRuleContext.java Sun Feb 01 15:02:07 2015 -0800
59.3 @@ -38,7 +38,7 @@
59.4 *
59.5 * @author Tor Norbye
59.6 */
59.7 -public class PythonRuleContext extends org.netbeans.modules.gsf.api.RuleContext {
59.8 +public class PythonRuleContext extends org.netbeans.modules.csl.api.RuleContext {
59.9 public AstPath path;
59.10 public PythonTree node;
59.11 public boolean remove;
60.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/PythonSelectionRule.java Sun Jan 04 13:11:53 2015 -0600
60.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/PythonSelectionRule.java Sun Feb 01 15:02:07 2015 -0800
60.3 @@ -31,7 +31,6 @@
60.4 package org.netbeans.modules.python.editor.hints;
60.5
60.6 import javax.swing.text.BadLocationException;
60.7 -import org.netbeans.modules.gsf.api.Rule.SelectionRule;
60.8 import java.util.List;
60.9 import org.netbeans.modules.python.editor.PythonAstUtils;
60.10 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
60.11 @@ -40,9 +39,10 @@
60.12 import org.netbeans.api.lexer.TokenId;
60.13 import org.netbeans.editor.BaseDocument;
60.14 import org.netbeans.editor.Utilities;
60.15 -import org.netbeans.modules.gsf.api.Hint;
60.16 -import org.netbeans.modules.gsf.api.OffsetRange;
60.17 -import org.netbeans.modules.gsf.api.Rule.UserConfigurableRule;
60.18 +import org.netbeans.modules.csl.api.Hint;
60.19 +import org.netbeans.modules.csl.api.OffsetRange;
60.20 +import org.netbeans.modules.csl.api.Rule.SelectionRule;
60.21 +import org.netbeans.modules.csl.api.Rule.UserConfigurableRule;
60.22 import org.openide.util.Exceptions;
60.23 import org.python.antlr.PythonTree;
60.24
60.25 @@ -90,7 +90,7 @@
60.26 return;
60.27 }
60.28
60.29 - OffsetRange astRange = PythonAstUtils.getAstOffsets(context.compilationInfo, new OffsetRange(start, end));
60.30 + OffsetRange astRange = PythonAstUtils.getAstOffsets(context.parserResult, new OffsetRange(start, end));
60.31 if (astRange == OffsetRange.NONE) {
60.32 return;
60.33 }
61.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/RelativeImports.java Sun Jan 04 13:11:53 2015 -0600
61.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/RelativeImports.java Sun Feb 01 15:02:07 2015 -0800
61.3 @@ -52,14 +52,15 @@
61.4 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
61.5 import org.netbeans.editor.BaseDocument;
61.6 import org.netbeans.editor.Utilities;
61.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
61.8 -import org.netbeans.modules.gsf.api.EditList;
61.9 -import org.netbeans.modules.gsf.api.Hint;
61.10 -import org.netbeans.modules.gsf.api.HintFix;
61.11 -import org.netbeans.modules.gsf.api.HintSeverity;
61.12 -import org.netbeans.modules.gsf.api.OffsetRange;
61.13 -import org.netbeans.modules.gsf.api.PreviewableFix;
61.14 -import org.netbeans.modules.gsf.api.RuleContext;
61.15 +import org.netbeans.modules.csl.api.EditList;
61.16 +import org.netbeans.modules.csl.api.Hint;
61.17 +import org.netbeans.modules.csl.api.HintFix;
61.18 +import org.netbeans.modules.csl.api.HintSeverity;
61.19 +import org.netbeans.modules.csl.api.OffsetRange;
61.20 +import org.netbeans.modules.csl.api.PreviewableFix;
61.21 +import org.netbeans.modules.csl.api.RuleContext;
61.22 +import org.netbeans.modules.csl.spi.ParserResult;
61.23 +import org.netbeans.modules.python.editor.PythonParserResult;
61.24 import org.openide.filesystems.FileObject;
61.25 import org.openide.util.Exceptions;
61.26 import org.openide.util.NbBundle;
61.27 @@ -87,7 +88,7 @@
61.28 ImportFrom imp = (ImportFrom)context.node;
61.29 if (imp.getInternalModule() != null && imp.getInternalModule().startsWith(".")) {
61.30 PythonTree node = context.node;
61.31 - CompilationInfo info = context.compilationInfo;
61.32 + PythonParserResult info = (PythonParserResult) context.parserResult;
61.33 OffsetRange astOffsets = PythonAstUtils.getNameRange(info, node);
61.34 OffsetRange lexOffsets = PythonLexerUtils.getLexerOffsets(info, astOffsets);
61.35 BaseDocument doc = context.doc;
61.36 @@ -98,7 +99,7 @@
61.37 List<HintFix> fixList = new ArrayList<HintFix>();
61.38 fixList.add(new RelativeImportsFix(context, imp));
61.39 String displayName = getDisplayName();
61.40 - Hint desc = new Hint(this, displayName, info.getFileObject(), lexOffsets, fixList, 1500);
61.41 + Hint desc = new Hint(this, displayName, info.getSnapshot().getSource().getFileObject(), lexOffsets, fixList, 1500);
61.42 result.add(desc);
61.43 }
61.44 } catch (BadLocationException ex) {
61.45 @@ -167,9 +168,10 @@
61.46
61.47 OffsetRange astRange = PythonAstUtils.getRange(imp);
61.48 if (astRange != OffsetRange.NONE) {
61.49 - OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(context.compilationInfo, astRange);
61.50 + PythonParserResult info = (PythonParserResult)context.parserResult;
61.51 + OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(info, astRange);
61.52 if (lexRange != OffsetRange.NONE) {
61.53 - FileObject fo = context.compilationInfo.getFileObject();
61.54 + FileObject fo = info.getSnapshot().getSource().getFileObject();
61.55 if (fo != null) {
61.56 String path = imp.getInternalModule();
61.57 int i = 0;
62.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/SplitImports.java Sun Jan 04 13:11:53 2015 -0600
62.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/SplitImports.java Sun Feb 01 15:02:07 2015 -0800
62.3 @@ -52,16 +52,16 @@
62.4 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
62.5 import org.netbeans.editor.BaseDocument;
62.6 import org.netbeans.editor.Utilities;
62.7 +import org.netbeans.modules.csl.api.EditList;
62.8 +import org.netbeans.modules.csl.api.Hint;
62.9 +import org.netbeans.modules.csl.api.HintFix;
62.10 +import org.netbeans.modules.csl.api.HintSeverity;
62.11 +import org.netbeans.modules.csl.api.OffsetRange;
62.12 +import org.netbeans.modules.csl.api.PreviewableFix;
62.13 +import org.netbeans.modules.csl.api.RuleContext;
62.14 +import org.netbeans.modules.csl.spi.GsfUtilities;
62.15 import org.netbeans.modules.editor.indent.api.IndentUtils;
62.16 -import org.netbeans.modules.gsf.api.CompilationInfo;
62.17 -import org.netbeans.modules.gsf.api.EditList;
62.18 -import org.netbeans.modules.gsf.api.Hint;
62.19 -import org.netbeans.modules.gsf.api.HintFix;
62.20 -import org.netbeans.modules.gsf.api.HintSeverity;
62.21 -import org.netbeans.modules.gsf.api.OffsetRange;
62.22 -import org.netbeans.modules.gsf.api.PreviewableFix;
62.23 -import org.netbeans.modules.gsf.api.RuleContext;
62.24 -import org.netbeans.modules.gsf.spi.GsfUtilities;
62.25 +import org.netbeans.modules.python.editor.PythonParserResult;
62.26 import org.netbeans.modules.python.editor.options.CodeStyle;
62.27 import org.openide.util.Exceptions;
62.28 import org.openide.util.NbBundle;
62.29 @@ -87,7 +87,7 @@
62.30 List<alias> names = imp.getInternalNames();
62.31 if (names != null && names.size() > 1) {
62.32 PythonTree node = context.node;
62.33 - CompilationInfo info = context.compilationInfo;
62.34 + PythonParserResult info = (PythonParserResult)context.parserResult;
62.35 OffsetRange astOffsets = PythonAstUtils.getNameRange(info, node);
62.36 OffsetRange lexOffsets = PythonLexerUtils.getLexerOffsets(info, astOffsets);
62.37 BaseDocument doc = context.doc;
62.38 @@ -98,7 +98,7 @@
62.39 List<HintFix> fixList = new ArrayList<HintFix>();
62.40 fixList.add(new SplitImportsFix(context, imp));
62.41 String displayName = getDisplayName();
62.42 - Hint desc = new Hint(this, displayName, info.getFileObject(), lexOffsets, fixList, 1500);
62.43 + Hint desc = new Hint(this, displayName, info.getSnapshot().getSource().getFileObject(), lexOffsets, fixList, 1500);
62.44 result.add(desc);
62.45 }
62.46 } catch (BadLocationException ex) {
62.47 @@ -163,7 +163,7 @@
62.48
62.49 OffsetRange astRange = PythonAstUtils.getRange(imp);
62.50 if (astRange != OffsetRange.NONE) {
62.51 - OffsetRange lexRange = PythonLexerUtils.getLexerOffsets(context.compilationInfo, astRange);
62.52 + OffsetRange lexRange = PythonLexerUtils.getLexerOffsets((PythonParserResult) context.parserResult, astRange);
62.53 if (lexRange != OffsetRange.NONE) {
62.54 int indent = GsfUtilities.getLineIndent(doc, lexRange.getStart());
62.55 StringBuilder sb = new StringBuilder();
63.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/SurroundWith.java Sun Jan 04 13:11:53 2015 -0600
63.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/SurroundWith.java Sun Feb 01 15:02:07 2015 -0800
63.3 @@ -39,15 +39,15 @@
63.4 import org.netbeans.editor.BaseDocument;
63.5 import org.netbeans.editor.Utilities;
63.6 import org.netbeans.lib.editor.codetemplates.api.CodeTemplateManager;
63.7 +import org.netbeans.modules.csl.api.EditList;
63.8 +import org.netbeans.modules.csl.api.Hint;
63.9 +import org.netbeans.modules.csl.api.HintFix;
63.10 +import org.netbeans.modules.csl.api.HintSeverity;
63.11 +import org.netbeans.modules.csl.api.OffsetRange;
63.12 +import org.netbeans.modules.csl.api.PreviewableFix;
63.13 +import org.netbeans.modules.csl.api.RuleContext;
63.14 +import org.netbeans.modules.csl.spi.GsfUtilities;
63.15 import org.netbeans.modules.editor.indent.api.IndentUtils;
63.16 -import org.netbeans.modules.gsf.api.EditList;
63.17 -import org.netbeans.modules.gsf.api.Hint;
63.18 -import org.netbeans.modules.gsf.api.HintFix;
63.19 -import org.netbeans.modules.gsf.api.HintSeverity;
63.20 -import org.netbeans.modules.gsf.api.OffsetRange;
63.21 -import org.netbeans.modules.gsf.api.PreviewableFix;
63.22 -import org.netbeans.modules.gsf.api.RuleContext;
63.23 -import org.netbeans.modules.gsf.spi.GsfUtilities;
63.24 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
63.25 import org.openide.util.Exceptions;
63.26 import org.openide.util.NbBundle;
63.27 @@ -80,7 +80,7 @@
63.28
63.29 // Adjust the fix range to be right around the dot so that the light bulb ends up
63.30 // on the same line as the caret and alt-enter works
63.31 - JTextComponent target = GsfUtilities.getPaneFor(context.compilationInfo.getFileObject());
63.32 + JTextComponent target = GsfUtilities.getPaneFor(context.parserResult.getSnapshot().getSource().getFileObject());
63.33 if (target != null) {
63.34 int dot = target.getCaret().getDot();
63.35 range = new OffsetRange(dot, dot);
63.36 @@ -91,7 +91,7 @@
63.37 fixList.add(new SurroundWithFix(context, start, end, true, true));
63.38 fixList.add(new SurroundWithFix(context, start, end, true, false));
63.39 String displayName = getDisplayName();
63.40 - Hint desc = new Hint(this, displayName, context.compilationInfo.getFileObject(),
63.41 + Hint desc = new Hint(this, displayName, context.parserResult.getSnapshot().getSource().getFileObject(),
63.42 range, fixList, 1500);
63.43 result.add(desc);
63.44 }
63.45 @@ -250,7 +250,7 @@
63.46 public void implement() throws Exception {
63.47 EditList edits = getEditList(true);
63.48
63.49 - JTextComponent target = GsfUtilities.getPaneFor(context.compilationInfo.getFileObject());
63.50 + JTextComponent target = GsfUtilities.getPaneFor(context.parserResult.getSnapshot().getSource().getFileObject());
63.51 edits.apply();
63.52 if (target != null) {
63.53 if (codeTemplateText != null && codeTemplatePos != null) {
64.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/UnresolvedClassComponents.java Sun Jan 04 13:11:53 2015 -0600
64.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/UnresolvedClassComponents.java Sun Feb 01 15:02:07 2015 -0800
64.3 @@ -46,12 +46,11 @@
64.4 import java.util.Set;
64.5 import java.util.prefs.Preferences;
64.6 import javax.swing.JComponent;
64.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
64.8 -import org.netbeans.modules.gsf.api.Hint;
64.9 -import org.netbeans.modules.gsf.api.HintFix;
64.10 -import org.netbeans.modules.gsf.api.HintSeverity;
64.11 -import org.netbeans.modules.gsf.api.OffsetRange;
64.12 -import org.netbeans.modules.gsf.api.RuleContext;
64.13 +import org.netbeans.modules.csl.api.Hint;
64.14 +import org.netbeans.modules.csl.api.HintFix;
64.15 +import org.netbeans.modules.csl.api.HintSeverity;
64.16 +import org.netbeans.modules.csl.api.OffsetRange;
64.17 +import org.netbeans.modules.csl.api.RuleContext;
64.18 import org.netbeans.modules.python.editor.PythonAstUtils;
64.19 import org.netbeans.modules.python.editor.PythonParserResult;
64.20 import org.netbeans.modules.python.editor.imports.ImportManager;
64.21 @@ -86,7 +85,7 @@
64.22 return Collections.<Class>singleton(Module.class);
64.23 }
64.24
64.25 - private void populateMessages( CompilationInfo info, List<PythonTree> unresolved , List<Hint> result ,boolean isClass ) {
64.26 + private void populateMessages( PythonParserResult info, List<PythonTree> unresolved , List<Hint> result ,boolean isClass ) {
64.27 if (unresolved.size() > 0) {
64.28
64.29 for (PythonTree node : unresolved) {
64.30 @@ -104,7 +103,7 @@
64.31 OffsetRange range = PythonAstUtils.getRange( node);
64.32 range = PythonLexerUtils.getLexerOffsets(info, range);
64.33 if (range != OffsetRange.NONE) {
64.34 - Hint desc = new Hint(this, message, info.getFileObject(), range, fixList, 2305);
64.35 + Hint desc = new Hint(this, message, info.getSnapshot().getSource().getFileObject(), range, fixList, 2305);
64.36 result.add(desc);
64.37 }
64.38 }
64.39 @@ -113,9 +112,8 @@
64.40
64.41
64.42 public void run(PythonRuleContext context, List<Hint> result) {
64.43 - CompilationInfo info = context.compilationInfo;
64.44 - PythonParserResult pr = PythonAstUtils.getParseResult(info);
64.45 - SymbolTable symbolTable = pr.getSymbolTable();
64.46 + PythonParserResult info = (PythonParserResult) context.parserResult;
64.47 + SymbolTable symbolTable = info.getSymbolTable();
64.48
64.49 List<PythonTree> unresolvedAttributes = symbolTable.getUnresolvedAttributes(info);
64.50 populateMessages(info,unresolvedAttributes,result,false) ;
64.51 @@ -181,7 +179,7 @@
64.52 symbol = mod.substring(colon + 1, end).trim();
64.53 mod = mod.substring(0, colon).trim();
64.54 }
64.55 - new ImportManager(context.compilationInfo).ensureImported(mod, symbol, false, false, true);
64.56 + new ImportManager((PythonParserResult) context.parserResult).ensureImported(mod, symbol, false, false, true);
64.57 }
64.58
64.59 public boolean isSafe() {
65.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/UnresolvedDetector.java Sun Jan 04 13:11:53 2015 -0600
65.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/UnresolvedDetector.java Sun Feb 01 15:02:07 2015 -0800
65.3 @@ -47,13 +47,12 @@
65.4 import java.util.Set;
65.5 import java.util.prefs.Preferences;
65.6 import javax.swing.JComponent;
65.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
65.8 -import org.netbeans.modules.gsf.api.Hint;
65.9 -import org.netbeans.modules.gsf.api.HintFix;
65.10 -import org.netbeans.modules.gsf.api.HintSeverity;
65.11 -import org.netbeans.modules.gsf.api.NameKind;
65.12 -import org.netbeans.modules.gsf.api.OffsetRange;
65.13 -import org.netbeans.modules.gsf.api.RuleContext;
65.14 +import org.netbeans.modules.csl.api.Hint;
65.15 +import org.netbeans.modules.csl.api.HintFix;
65.16 +import org.netbeans.modules.csl.api.HintSeverity;
65.17 +import org.netbeans.modules.csl.api.OffsetRange;
65.18 +import org.netbeans.modules.csl.api.RuleContext;
65.19 +import org.netbeans.modules.parsing.spi.indexing.support.QuerySupport;
65.20 import org.netbeans.modules.python.editor.PythonAstUtils;
65.21 import org.netbeans.modules.python.editor.PythonIndex;
65.22 import org.netbeans.modules.python.editor.PythonParserResult;
65.23 @@ -86,13 +85,12 @@
65.24 }
65.25
65.26 public void run(PythonRuleContext context, List<Hint> result) {
65.27 - CompilationInfo info = context.compilationInfo;
65.28 - PythonParserResult pr = PythonAstUtils.getParseResult(info);
65.29 - SymbolTable symbolTable = pr.getSymbolTable();
65.30 + PythonParserResult info = (PythonParserResult) context.parserResult;
65.31 + SymbolTable symbolTable = info.getSymbolTable();
65.32
65.33 List<PythonTree> unresolvedNames = symbolTable.getUnresolved(info);
65.34 if (unresolvedNames.size() > 0) {
65.35 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE), info.getFileObject());
65.36 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
65.37
65.38 for (PythonTree node : unresolvedNames) {
65.39 // Compute suggestions
65.40 @@ -121,7 +119,7 @@
65.41 } else if (name.equals("this")) {
65.42 message = NbBundle.getMessage(NameRule.class, "UnresolvedVariableMaybe", name, "self"); // NOI18N
65.43 } else if (tryModule) {
65.44 - Set<IndexedElement> moduleElements = index.getModules(name, NameKind.EXACT_NAME);
65.45 + Set<IndexedElement> moduleElements = index.getModules(name, QuerySupport.Kind.EXACT);
65.46 if (moduleElements.size() > 0) {
65.47 fixList.add(new ImportFix(context, node, name));
65.48 }
65.49 @@ -137,7 +135,7 @@
65.50 OffsetRange range = PythonAstUtils.getNameRange(info, node);
65.51 range = PythonLexerUtils.getLexerOffsets(info, range);
65.52 if (range != OffsetRange.NONE) {
65.53 - Hint desc = new Hint(this, message, info.getFileObject(), range, fixList, 2305);
65.54 + Hint desc = new Hint(this, message, info.getSnapshot().getSource().getFileObject(), range, fixList, 2305);
65.55 result.add(desc);
65.56 }
65.57 }
65.58 @@ -202,7 +200,7 @@
65.59 symbol = mod.substring(colon + 1, end).trim();
65.60 mod = mod.substring(0, colon).trim();
65.61 }
65.62 - new ImportManager(context.compilationInfo).ensureImported(mod, symbol, false, false, true);
65.63 + new ImportManager((PythonParserResult) context.parserResult).ensureImported(mod, symbol, false, false, true);
65.64 }
65.65
65.66 public boolean isSafe() {
66.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/UnusedDetector.java Sun Jan 04 13:11:53 2015 -0600
66.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/UnusedDetector.java Sun Feb 01 15:02:07 2015 -0800
66.3 @@ -48,12 +48,11 @@
66.4 import java.util.Set;
66.5 import java.util.prefs.Preferences;
66.6 import javax.swing.JComponent;
66.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
66.8 -import org.netbeans.modules.gsf.api.Hint;
66.9 -import org.netbeans.modules.gsf.api.HintFix;
66.10 -import org.netbeans.modules.gsf.api.HintSeverity;
66.11 -import org.netbeans.modules.gsf.api.OffsetRange;
66.12 -import org.netbeans.modules.gsf.api.RuleContext;
66.13 +import org.netbeans.modules.csl.api.Hint;
66.14 +import org.netbeans.modules.csl.api.HintFix;
66.15 +import org.netbeans.modules.csl.api.HintSeverity;
66.16 +import org.netbeans.modules.csl.api.OffsetRange;
66.17 +import org.netbeans.modules.csl.api.RuleContext;
66.18 import org.netbeans.modules.python.editor.PythonAstUtils;
66.19 import org.netbeans.modules.python.editor.PythonParserResult;
66.20 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
66.21 @@ -93,9 +92,8 @@
66.22 }
66.23
66.24 public void run(PythonRuleContext context, List<Hint> result) {
66.25 - CompilationInfo info = context.compilationInfo;
66.26 - PythonParserResult pr = PythonAstUtils.getParseResult(info);
66.27 - SymbolTable symbolTable = pr.getSymbolTable();
66.28 + PythonParserResult info = (PythonParserResult) context.parserResult;
66.29 + SymbolTable symbolTable = info.getSymbolTable();
66.30
66.31 boolean skipParams = true;
66.32 Preferences pref = context.manager.getPreferences(this);
66.33 @@ -138,7 +136,7 @@
66.34 if (range != OffsetRange.NONE) {
66.35 List<HintFix> fixList = new ArrayList<HintFix>(3);
66.36 String message = NbBundle.getMessage(NameRule.class, "UnusedVariable", name);
66.37 - Hint desc = new Hint(this, message, info.getFileObject(), range, fixList, 2305);
66.38 + Hint desc = new Hint(this, message, info.getSnapshot().getSource().getFileObject(), range, fixList, 2305);
66.39 result.add(desc);
66.40 }
66.41 }
67.1 --- a/python.editor/src/org/netbeans/modules/python/editor/hints/UnusedImports.java Sun Jan 04 13:11:53 2015 -0600
67.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/hints/UnusedImports.java Sun Feb 01 15:02:07 2015 -0800
67.3 @@ -50,13 +50,12 @@
67.4 import java.util.prefs.Preferences;
67.5 import javax.swing.JComponent;
67.6 import org.netbeans.editor.BaseDocument;
67.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
67.8 -import org.netbeans.modules.gsf.api.EditList;
67.9 -import org.netbeans.modules.gsf.api.Hint;
67.10 -import org.netbeans.modules.gsf.api.HintFix;
67.11 -import org.netbeans.modules.gsf.api.HintSeverity;
67.12 -import org.netbeans.modules.gsf.api.OffsetRange;
67.13 -import org.netbeans.modules.gsf.api.RuleContext;
67.14 +import org.netbeans.modules.csl.api.EditList;
67.15 +import org.netbeans.modules.csl.api.Hint;
67.16 +import org.netbeans.modules.csl.api.HintFix;
67.17 +import org.netbeans.modules.csl.api.HintSeverity;
67.18 +import org.netbeans.modules.csl.api.OffsetRange;
67.19 +import org.netbeans.modules.csl.api.RuleContext;
67.20 import org.netbeans.modules.python.editor.PythonAstUtils;
67.21 import org.netbeans.modules.python.editor.PythonParserResult;
67.22 import org.netbeans.modules.python.editor.imports.ImportEntry;
67.23 @@ -81,7 +80,7 @@
67.24 }
67.25
67.26 public boolean appliesTo(RuleContext context) {
67.27 - FileObject fo = context.compilationInfo.getFileObject();
67.28 + FileObject fo = context.parserResult.getSnapshot().getSource().getFileObject();
67.29 return fo == null || !fo.getName().equals("__init__"); // NOI18N
67.30 }
67.31
67.32 @@ -96,11 +95,10 @@
67.33 private static void computeUnusedImports(UnusedImports detector, PythonRuleContext context, List<Hint> result, Map<PythonTree, List<String>> unused) {
67.34 assert result == null || unused == null; // compute either results or set of unused
67.35
67.36 - CompilationInfo info = context.compilationInfo;
67.37 - PythonParserResult parseResult = PythonAstUtils.getParseResult(info);
67.38 - SymbolTable symbolTable = parseResult.getSymbolTable();
67.39 + PythonParserResult info = (PythonParserResult) context.parserResult;
67.40 + SymbolTable symbolTable = info.getSymbolTable();
67.41 List<ImportEntry> unusedImports = symbolTable.getUnusedImports();
67.42 - if (unusedImports.size() == 0) {
67.43 + if (unusedImports.isEmpty()) {
67.44 return;
67.45 }
67.46 Map<PythonTree, List<String>> maps = new HashMap<PythonTree, List<String>>();
67.47 @@ -150,7 +148,7 @@
67.48 }
67.49
67.50 private static void addError(UnusedImports detector, PythonRuleContext context, PythonTree node, List<String> symbols, List<Hint> result) {
67.51 - CompilationInfo info = context.compilationInfo;
67.52 + PythonParserResult info = (PythonParserResult) context.parserResult;
67.53 OffsetRange range = PythonAstUtils.getNameRange(info, node);
67.54 range = PythonLexerUtils.getLexerOffsets(info, range);
67.55 if (range != OffsetRange.NONE) {
67.56 @@ -164,7 +162,7 @@
67.57 } else {
67.58 message = NbBundle.getMessage(NameRule.class, "UnusedImport");
67.59 }
67.60 - Hint desc = new Hint(detector, message, info.getFileObject(), range, fixList, 2500);
67.61 + Hint desc = new Hint(detector, message, info.getSnapshot().getSource().getFileObject(), range, fixList, 2500);
67.62 result.add(desc);
67.63 }
67.64 }
67.65 @@ -237,7 +235,7 @@
67.66 BaseDocument doc = context.doc;
67.67 EditList edits = new EditList(doc);
67.68
67.69 - ImportManager importManager = new ImportManager(context.compilationInfo);
67.70 + ImportManager importManager = new ImportManager((PythonParserResult) context.parserResult);
67.71
67.72 if (node == null) {
67.73 if (organizeOnly) {
68.1 --- a/python.editor/src/org/netbeans/modules/python/editor/imports/FastImportAction.java Sun Jan 04 13:11:53 2015 -0600
68.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/imports/FastImportAction.java Sun Feb 01 15:02:07 2015 -0800
68.3 @@ -58,13 +58,10 @@
68.4 import javax.swing.text.JTextComponent;
68.5 import org.netbeans.editor.BaseAction;
68.6 import org.netbeans.editor.Utilities;
68.7 -import org.netbeans.modules.gsf.api.CancellableTask;
68.8 -import org.netbeans.modules.gsf.api.CompilationInfo;
68.9 -import org.netbeans.modules.gsf.api.SourceModel;
68.10 -import org.netbeans.modules.gsf.api.SourceModelFactory;
68.11 -import org.netbeans.modules.gsf.spi.GsfUtilities;
68.12 +import org.netbeans.modules.csl.spi.GsfUtilities;
68.13 import org.netbeans.modules.python.editor.PythonAstUtils;
68.14 import org.netbeans.modules.python.editor.PythonIndex;
68.15 +import org.netbeans.modules.python.editor.PythonParserResult;
68.16 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
68.17 import org.openide.ErrorManager;
68.18 import org.openide.filesystems.FileObject;
68.19 @@ -103,29 +100,29 @@
68.20 return;
68.21 }
68.22
68.23 - SourceModel model = SourceModelFactory.getInstance().getModel(file);
68.24 - if (model != null) {
68.25 - final CompilationInfo[] infoHolder = new CompilationInfo[1];
68.26 - try {
68.27 - model.runUserActionTask(new CancellableTask<CompilationInfo>() {
68.28 - public void cancel() {
68.29 - }
68.30 -
68.31 - public void run(CompilationInfo info) throws Exception {
68.32 - importItem(info, where, caretRectangle, font, position, ident);
68.33 - }
68.34 - }, false);
68.35 - } catch (IOException ex) {
68.36 - Exceptions.printStackTrace(ex);
68.37 - }
68.38 - }
68.39 +// SourceModel model = SourceModelFactory.getInstance().getModel(file);
68.40 +// if (model != null) {
68.41 +// final CompilationInfo[] infoHolder = new CompilationInfo[1];
68.42 +// try {
68.43 +// model.runUserActionTask(new CancellableTask<CompilationInfo>() {
68.44 +// public void cancel() {
68.45 +// }
68.46 +//
68.47 +// public void run(CompilationInfo info) throws Exception {
68.48 +// importItem(info, where, caretRectangle, font, position, ident);
68.49 +// }
68.50 +// }, false);
68.51 +// } catch (IOException ex) {
68.52 +// Exceptions.printStackTrace(ex);
68.53 +// }
68.54 +// }
68.55
68.56 } catch (BadLocationException ex) {
68.57 ErrorManager.getDefault().notify(ex);
68.58 }
68.59 }
68.60
68.61 - private void importItem(final CompilationInfo info, final Point where, final Rectangle caretRectangle, final Font font, final int position, final String ident) {
68.62 + private void importItem(final PythonParserResult info, final Point where, final Rectangle caretRectangle, final Font font, final int position, final String ident) {
68.63 PythonTree root = PythonAstUtils.getRoot(info);
68.64 if (root == null) {
68.65 Toolkit.getDefaultToolkit().beep();
68.66 @@ -133,7 +130,7 @@
68.67 }
68.68
68.69 // Compute suggestions
68.70 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE), info.getFileObject());
68.71 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
68.72 Set<String> modules = index.getImportsFor(ident, true);
68.73
68.74 // TODO - check the file to pick a better default (based on existing imports, usages of the symbol
69.1 --- a/python.editor/src/org/netbeans/modules/python/editor/imports/FixImportsAction.java Sun Jan 04 13:11:53 2015 -0600
69.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/imports/FixImportsAction.java Sun Feb 01 15:02:07 2015 -0800
69.3 @@ -44,7 +44,6 @@
69.4 import java.awt.Dialog;
69.5 import java.awt.Toolkit;
69.6 import java.awt.event.ActionEvent;
69.7 -import java.io.IOException;
69.8 import java.util.ArrayList;
69.9 import java.util.Collections;
69.10 import java.util.HashMap;
69.11 @@ -54,16 +53,17 @@
69.12 import java.util.Set;
69.13 import java.util.prefs.Preferences;
69.14 import javax.swing.Icon;
69.15 -import javax.swing.ImageIcon;
69.16 import javax.swing.text.JTextComponent;
69.17 import org.netbeans.editor.BaseAction;
69.18 import org.netbeans.editor.BaseDocument;
69.19 -import org.netbeans.modules.gsf.api.CancellableTask;
69.20 -import org.netbeans.modules.gsf.api.CompilationInfo;
69.21 -import org.netbeans.modules.gsf.api.SourceModel;
69.22 -import org.netbeans.modules.gsf.api.SourceModelFactory;
69.23 -import org.netbeans.modules.gsf.spi.GsfUtilities;
69.24 +import org.netbeans.modules.csl.spi.GsfUtilities;
69.25 +import org.netbeans.modules.parsing.api.ParserManager;
69.26 +import org.netbeans.modules.parsing.api.ResultIterator;
69.27 +import org.netbeans.modules.parsing.api.Source;
69.28 +import org.netbeans.modules.parsing.api.UserTask;
69.29 +import org.netbeans.modules.parsing.spi.ParseException;
69.30 import org.netbeans.modules.python.editor.PythonAstUtils;
69.31 +import org.netbeans.modules.python.editor.PythonParserResult;
69.32 import org.netbeans.modules.python.editor.options.CodeStyle.ImportCleanupStyle;
69.33 import org.openide.DialogDescriptor;
69.34 import org.openide.DialogDisplayer;
69.35 @@ -129,21 +129,20 @@
69.36 // Move imports that I think may be unused to the end - or just comment them out?
69.37
69.38 // For imports: Gather imports from everywhere... move others into the same section
69.39 - CompilationInfo info = null;
69.40 + PythonParserResult info = null;
69.41
69.42 - SourceModel model = SourceModelFactory.getInstance().getModel(fo);
69.43 + Source model = Source.create(fo);
69.44 if (model != null) {
69.45 - final CompilationInfo[] infoHolder = new CompilationInfo[1];
69.46 + final PythonParserResult[] infoHolder = new PythonParserResult[1];
69.47 try {
69.48 - model.runUserActionTask(new CancellableTask<CompilationInfo>() {
69.49 - public void cancel() {
69.50 + ParserManager.parse(Collections.singleton(model), new UserTask() {
69.51 +
69.52 + @Override
69.53 + public void run(ResultIterator resultIterator) throws Exception {
69.54 + infoHolder[0] = (PythonParserResult) resultIterator.getParserResult();
69.55 }
69.56 -
69.57 - public void run(CompilationInfo info) throws Exception {
69.58 - infoHolder[0] = info;
69.59 - }
69.60 - }, false);
69.61 - } catch (IOException ex) {
69.62 + });
69.63 + } catch (ParseException ex) {
69.64 Exceptions.printStackTrace(ex);
69.65 }
69.66 info = infoHolder[0];
70.1 --- a/python.editor/src/org/netbeans/modules/python/editor/imports/ImportManager.java Sun Jan 04 13:11:53 2015 -0600
70.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/imports/ImportManager.java Sun Feb 01 15:02:07 2015 -0800
70.3 @@ -43,7 +43,6 @@
70.4
70.5 import java.awt.Toolkit;
70.6 import java.util.ArrayList;
70.7 -import java.util.Arrays;
70.8 import java.util.Collection;
70.9 import java.util.Collections;
70.10 import java.util.HashMap;
70.11 @@ -55,14 +54,14 @@
70.12 import org.netbeans.api.editor.EditorRegistry;
70.13 import org.netbeans.editor.BaseDocument;
70.14 import org.netbeans.editor.Utilities;
70.15 +import org.netbeans.modules.csl.api.EditList;
70.16 +import org.netbeans.modules.csl.api.OffsetRange;
70.17 +import org.netbeans.modules.csl.spi.GsfUtilities;
70.18 import org.netbeans.modules.editor.indent.api.IndentUtils;
70.19 -import org.netbeans.modules.gsf.api.CompilationInfo;
70.20 -import org.netbeans.modules.gsf.api.EditList;
70.21 -import org.netbeans.modules.gsf.api.Index;
70.22 -import org.netbeans.modules.gsf.api.NameKind;
70.23 -import org.netbeans.modules.gsf.api.OffsetRange;
70.24 +import org.netbeans.modules.parsing.spi.indexing.support.QuerySupport;
70.25 import org.netbeans.modules.python.editor.PythonAstUtils;
70.26 import org.netbeans.modules.python.editor.PythonIndex;
70.27 +import org.netbeans.modules.python.editor.PythonParserResult;
70.28 import org.netbeans.modules.python.editor.elements.IndexedElement;
70.29 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
70.30 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
70.31 @@ -96,7 +95,7 @@
70.32 static final String PREFS_KEY = FixImportsAction.class.getName();
70.33 // TODO - use document style instead!
70.34 static final String KEY_REMOVE_UNUSED_IMPORTS = "removeUnusedImports"; // NOI18N
70.35 - private CompilationInfo info;
70.36 + private PythonParserResult info;
70.37 private List<Import> imports;
70.38 private List<ImportFrom> importsFrom;
70.39 private PythonTree root;
70.40 @@ -113,15 +112,15 @@
70.41 private boolean removeDuplicates;
70.42 private int rightMargin;
70.43
70.44 - public ImportManager(CompilationInfo info) {
70.45 - this(info, (BaseDocument)info.getDocument(), null);
70.46 + public ImportManager(PythonParserResult info) {
70.47 + this(info, GsfUtilities.getDocument(info.getSnapshot().getSource().getFileObject(), false), null);
70.48 }
70.49
70.50 - public ImportManager(CompilationInfo info, BaseDocument doc) {
70.51 + public ImportManager(PythonParserResult info, BaseDocument doc) {
70.52 this(info, doc, null);
70.53 }
70.54
70.55 - public ImportManager(CompilationInfo info, BaseDocument doc, CodeStyle codeStyle) {
70.56 + public ImportManager(PythonParserResult info, BaseDocument doc, CodeStyle codeStyle) {
70.57 this.info = info;
70.58
70.59 root = PythonAstUtils.getRoot(info);
70.60 @@ -209,7 +208,7 @@
70.61
70.62 boolean ambiguous = false;
70.63
70.64 - SymbolTable symbolTable = new SymbolTable(PythonAstUtils.getRoot(info), info.getFileObject());
70.65 + SymbolTable symbolTable = new SymbolTable(PythonAstUtils.getRoot(info), info.getSnapshot().getSource().getFileObject());
70.66 Map<String, SymInfo> unresolved = symbolTable.getUnresolvedNames(info);
70.67
70.68 if (unresolved.size() > 0) {
70.69 @@ -217,9 +216,8 @@
70.70 Collections.sort(ambiguousSymbols);
70.71
70.72 // Try to compute suggestions.
70.73 - Index gsfIndex = info.getIndex(PythonTokenId.PYTHON_MIME_TYPE);
70.74 - PythonIndex index = PythonIndex.get(gsfIndex, info.getFileObject());
70.75 - Set<IndexedElement> modules = index.getModules("", NameKind.PREFIX);
70.76 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
70.77 + Set<IndexedElement> modules = index.getModules("", QuerySupport.Kind.PREFIX);
70.78 for (IndexedElement module : modules) {
70.79 String name = module.getName();
70.80 if (unresolved.containsKey(name)) {
70.81 @@ -536,8 +534,7 @@
70.82 removeImports(edits, filtered, cleanup == ImportCleanupStyle.COMMENT_OUT, null);
70.83 }
70.84
70.85 - Index gsfIndex = info.getIndex(PythonTokenId.PYTHON_MIME_TYPE);
70.86 - PythonIndex index = PythonIndex.get(gsfIndex, info.getFileObject());
70.87 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
70.88
70.89 Collection<ImportEntry> newEntries = new ArrayList<ImportEntry>();
70.90 if (selections != null) {
70.91 @@ -752,8 +749,7 @@
70.92 public void rewriteMainImports(EditList edits, Collection<ImportEntry> newEntries, Set<ImportEntry> remove) {
70.93 // Items to be deleted should be deleted after this
70.94
70.95 - Index gsfIndex = info.getIndex(PythonTokenId.PYTHON_MIME_TYPE);
70.96 - PythonIndex index = PythonIndex.get(gsfIndex, info.getFileObject());
70.97 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
70.98
70.99 // TODO:
70.100 // Look for comments to preserve
71.1 --- a/python.editor/src/org/netbeans/modules/python/editor/imports/ImportModulePanel.java Sun Jan 04 13:11:53 2015 -0600
71.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/imports/ImportModulePanel.java Sun Feb 01 15:02:07 2015 -0800
71.3 @@ -53,7 +53,6 @@
71.4 import java.util.List;
71.5 import javax.swing.DefaultListCellRenderer;
71.6 import javax.swing.DefaultListModel;
71.7 -import javax.swing.ImageIcon;
71.8 import javax.swing.JLabel;
71.9 import javax.swing.JList;
71.10 import javax.swing.KeyStroke;
71.11 @@ -63,9 +62,10 @@
71.12 import org.netbeans.api.lexer.TokenHierarchy;
71.13 import org.netbeans.editor.BaseDocument;
71.14 import org.netbeans.editor.Utilities;
71.15 -import org.netbeans.modules.gsf.api.CompilationInfo;
71.16 -import org.netbeans.modules.gsf.api.ElementKind;
71.17 +import org.netbeans.modules.csl.api.ElementKind;
71.18 +import org.netbeans.modules.csl.spi.GsfUtilities;
71.19 import org.netbeans.modules.python.editor.PythonIndex;
71.20 +import org.netbeans.modules.python.editor.PythonParserResult;
71.21 import org.netbeans.modules.python.editor.lexer.Call;
71.22 import org.openide.util.Exceptions;
71.23 import org.openide.util.ImageUtilities;
71.24 @@ -84,13 +84,13 @@
71.25 public class ImportModulePanel extends javax.swing.JPanel {
71.26
71.27 private final String ident;
71.28 - private CompilationInfo info;
71.29 + private PythonParserResult info;
71.30 private DefaultListModel model;
71.31 private final int position;
71.32
71.33 /** Creates new form ImportClassPanel */
71.34 @SuppressWarnings("deprecation")
71.35 - public ImportModulePanel(String ident, List</*TypeElement*/String> priviledged, List</*TypeElement*/String> denied, Font font, CompilationInfo info, int position) {
71.36 + public ImportModulePanel(String ident, List</*TypeElement*/String> priviledged, List</*TypeElement*/String> denied, Font font, PythonParserResult info, int position) {
71.37 this.ident = ident;
71.38 // System.err.println("priviledged=" + priviledged);
71.39 // System.err.println("denied=" + denied);
71.40 @@ -304,7 +304,7 @@
71.41 }
71.42 PopupUtil.hidePopup();
71.43
71.44 - Document document = info.getDocument();
71.45 + Document document = info.getSnapshot().getSource().getDocument(false);
71.46 try {
71.47 Position pos = document.createPosition(position);
71.48
72.1 --- a/python.editor/src/org/netbeans/modules/python/editor/layer.xml Sun Jan 04 13:11:53 2015 -0600
72.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/layer.xml Sun Feb 01 15:02:07 2015 -0800
72.3 @@ -1,5 +1,5 @@
72.4 <?xml version="1.0" encoding="UTF-8"?>
72.5 -<!DOCTYPE filesystem PUBLIC "-//NetBeans//DTD Filesystem 1.1//EN" "http://www.netbeans.org/dtds/filesystem-1_1.dtd">
72.6 +<!DOCTYPE filesystem PUBLIC "-//NetBeans//DTD Filesystem 1.2//EN" "http://www.netbeans.org/dtds/filesystem-1_2.dtd">
72.7 <filesystem>
72.8
72.9 <folder name="Editors">
72.10 @@ -104,8 +104,8 @@
72.11
72.12
72.13 </folder>
72.14 -
72.15 - <!-- Embedded double-quoted strings -->
72.16 +<!--
72.17 + Embedded double-quoted strings
72.18 <folder name="x-python-string">
72.19 <attr name="SystemFileSystem.localizingBundle" stringvalue="org.netbeans.modules.python.editor.Bundle"/>
72.20 <file name="language.instance">
72.21 @@ -129,20 +129,20 @@
72.22 </folder>
72.23 <folder name="CityLights">
72.24 <folder name="Defaults">
72.25 - <!-- This is just the bluetheme again - not right, but it's better
72.26 - to use a dark theme than the light theme a a backup. -->
72.27 + This is just the bluetheme again - not right, but it's better
72.28 + to use a dark theme than the light theme a a backup.
72.29 <file name="python-colorings.xml" url="resources/BlueTheme-Python-Strings.xml">
72.30 <attr name="SystemFileSystem.localizingBundle" stringvalue="org.netbeans.modules.python.editor.resources.Bundle"/>
72.31 </file>
72.32 </folder>
72.33 </folder>
72.34 </folder>
72.35 - </folder>
72.36 + </folder>-->
72.37
72.38 </folder>
72.39 </folder>
72.40
72.41 - <folder name="gsf-hints">
72.42 + <folder name="csl-hints">
72.43 <folder name="text">
72.44 <folder name="x-python">
72.45 <folder name="hints">
72.46 @@ -173,11 +173,11 @@
72.47 </folder>
72.48 </folder>
72.49
72.50 - <folder name="GsfPlugins">
72.51 + <folder name="CslPlugins">
72.52 <folder name="text">
72.53 <folder name="x-python">
72.54 <file name="language.instance">
72.55 - <attr name="instanceOf" stringvalue="org.netbeans.modules.gsf.api.GsfLanguage"/>
72.56 +<!-- <attr name="instanceOf" stringvalue="org.netbeans.modules.gsf.api.GsfLanguage"/>-->
72.57 <attr name="instanceClass" stringvalue="org.netbeans.modules.python.editor.PythonLanguage"/>
72.58 </file>
72.59 <file name="structure.instance">
72.60 @@ -334,7 +334,7 @@
72.61 <folder name="Services">
72.62 <folder name="MIMEResolver">
72.63 <file name="PythonResolver.xml" url="PythonResolver.xml">
72.64 - <attr name="SystemFileSystem.localizingBundle" stringvalue="org.netbeans.modules.python.editor.Bundle"/>
72.65 + <attr name="displayName" bundlevalue="org.netbeans.modules.python.editor.Bundle#Services/MIMEResolver/PythonResolver.xml"/>
72.66 <attr name="position" intvalue="184"/>
72.67 </file>
72.68 </folder>
73.1 --- a/python.editor/src/org/netbeans/modules/python/editor/lexer/Call.java Sun Jan 04 13:11:53 2015 -0600
73.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/lexer/Call.java Sun Feb 01 15:02:07 2015 -0800
73.3 @@ -45,8 +45,8 @@
73.4
73.5 import javax.swing.text.BadLocationException;
73.6 import javax.swing.text.Document;
73.7 +import org.netbeans.api.annotations.common.NonNull;
73.8
73.9 -import org.netbeans.modules.gsf.api.annotations.NonNull;
73.10 import org.netbeans.api.lexer.Token;
73.11 import org.netbeans.api.lexer.TokenHierarchy;
73.12 import org.netbeans.api.lexer.TokenId;
74.1 --- a/python.editor/src/org/netbeans/modules/python/editor/lexer/PythonLexerUtils.java Sun Jan 04 13:11:53 2015 -0600
74.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/lexer/PythonLexerUtils.java Sun Feb 01 15:02:07 2015 -0800
74.3 @@ -10,16 +10,14 @@
74.4 import java.util.regex.Pattern;
74.5 import javax.swing.text.BadLocationException;
74.6 import javax.swing.text.Document;
74.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
74.8 -import org.netbeans.modules.gsf.api.OffsetRange;
74.9 -import org.netbeans.modules.gsf.api.ParserResult;
74.10 -import org.netbeans.modules.gsf.api.TranslatedSource;
74.11 import org.netbeans.api.lexer.Token;
74.12 import org.netbeans.api.lexer.TokenHierarchy;
74.13 import org.netbeans.api.lexer.TokenId;
74.14 import org.netbeans.api.lexer.TokenSequence;
74.15 import org.netbeans.editor.BaseDocument;
74.16 import org.netbeans.editor.Utilities;
74.17 +import org.netbeans.modules.csl.api.OffsetRange;
74.18 +import org.netbeans.modules.python.editor.PythonParserResult;
74.19 import org.openide.filesystems.FileUtil;
74.20 import org.openide.loaders.DataObject;
74.21 import org.openide.util.Exceptions;
74.22 @@ -71,33 +69,21 @@
74.23 }
74.24
74.25 /** For a possibly generated offset in an AST, return the corresponding lexing/true document offset */
74.26 - public static int getLexerOffset(CompilationInfo info, int astOffset) {
74.27 - ParserResult result = info.getEmbeddedResult(PythonTokenId.PYTHON_MIME_TYPE, 0);
74.28 - if (result != null) {
74.29 - TranslatedSource ts = result.getTranslatedSource();
74.30 - if (ts != null) {
74.31 - return ts.getLexicalOffset(astOffset);
74.32 - }
74.33 - }
74.34 -
74.35 - return astOffset;
74.36 + public static int getLexerOffset(PythonParserResult result, int astOffset) {
74.37 + return result.getSnapshot().getOriginalOffset(astOffset);
74.38 }
74.39
74.40 - public static OffsetRange getLexerOffsets(CompilationInfo info, OffsetRange astRange) {
74.41 - ParserResult result = info.getEmbeddedResult(PythonTokenId.PYTHON_MIME_TYPE, 0);
74.42 + public static OffsetRange getLexerOffsets(PythonParserResult result, OffsetRange astRange) {
74.43 if (result != null) {
74.44 - TranslatedSource ts = result.getTranslatedSource();
74.45 - if (ts != null) {
74.46 - int rangeStart = astRange.getStart();
74.47 - int start = ts.getLexicalOffset(rangeStart);
74.48 - if (start == rangeStart) {
74.49 - return astRange;
74.50 - } else if (start == -1) {
74.51 - return OffsetRange.NONE;
74.52 - } else {
74.53 - // Assumes the translated range maintains size
74.54 - return new OffsetRange(start, start + astRange.getLength());
74.55 - }
74.56 + int rangeStart = astRange.getStart();
74.57 + int start = result.getSnapshot().getOriginalOffset(rangeStart);
74.58 + if (start == rangeStart) {
74.59 + return astRange;
74.60 + } else if (start == -1) {
74.61 + return OffsetRange.NONE;
74.62 + } else {
74.63 + // Assumes the translated range maintains size
74.64 + return new OffsetRange(start, start + astRange.getLength());
74.65 }
74.66 }
74.67
75.1 --- a/python.editor/src/org/netbeans/modules/python/editor/lexer/PythonTokenId.java Sun Jan 04 13:11:53 2015 -0600
75.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/lexer/PythonTokenId.java Sun Feb 01 15:02:07 2015 -0800
75.3 @@ -52,6 +52,7 @@
75.4 import org.netbeans.api.lexer.LanguagePath;
75.5 import org.netbeans.api.lexer.Token;
75.6 import org.netbeans.api.lexer.TokenId;
75.7 +import org.netbeans.modules.python.api.PythonMIMEResolver;
75.8 import org.netbeans.modules.python.editor.PythonUtils;
75.9 import org.netbeans.spi.lexer.LanguageEmbedding;
75.10 import org.netbeans.spi.lexer.LanguageHierarchy;
75.11 @@ -116,7 +117,6 @@
75.12 NONUNARY_OP(null, OPERATOR_CAT);
75.13 private final String fixedText;
75.14 private final String primaryCategory;
75.15 - public static final String PYTHON_MIME_TYPE = "text/x-python"; // NOI18N
75.16
75.17 PythonTokenId(String fixedText, String primaryCategory) {
75.18 this.fixedText = fixedText;
75.19 @@ -133,7 +133,7 @@
75.20 private static final Language<PythonTokenId> language =
75.21 new LanguageHierarchy<PythonTokenId>() {
75.22 protected String mimeType() {
75.23 - return PythonTokenId.PYTHON_MIME_TYPE;
75.24 + return PythonMIMEResolver.PYTHON_MIME_TYPE;
75.25 }
75.26
75.27 protected Collection<PythonTokenId> createTokenIds() {
76.1 --- a/python.editor/src/org/netbeans/modules/python/editor/options/FmtOptions.java Sun Jan 04 13:11:53 2015 -0600
76.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/options/FmtOptions.java Sun Feb 01 15:02:07 2015 -0800
76.3 @@ -52,7 +52,6 @@
76.4 import java.io.File;
76.5 import java.io.FileWriter;
76.6 import java.io.IOException;
76.7 -import java.util.ArrayList;
76.8 import java.util.Arrays;
76.9 import java.util.HashMap;
76.10 import java.util.HashSet;
76.11 @@ -76,27 +75,12 @@
76.12 import javax.swing.text.BadLocationException;
76.13 import javax.swing.text.Document;
76.14 import org.netbeans.api.editor.settings.SimpleValueNames;
76.15 -import org.netbeans.modules.gsf.api.CancellableTask;
76.16 -import org.netbeans.modules.gsf.api.CompilationInfo;
76.17 -import org.netbeans.modules.gsf.api.SourceModel;
76.18 -import org.netbeans.modules.gsf.api.SourceModelFactory;
76.19 -import org.netbeans.modules.gsf.spi.GsfUtilities;
76.20 -import org.netbeans.modules.gsfpath.api.classpath.ClassPath;
76.21 -import org.netbeans.modules.gsfpath.spi.classpath.support.ClassPathSupport;
76.22 -import org.netbeans.modules.python.editor.PythonLanguage;
76.23 import static org.netbeans.modules.python.editor.options.CodeStyle.*;
76.24 import org.netbeans.modules.options.editor.spi.PreferencesCustomizer;
76.25 import org.netbeans.modules.options.editor.spi.PreviewProvider;
76.26 -
76.27 -import org.netbeans.modules.python.api.PythonPlatform;
76.28 -import org.netbeans.modules.python.api.PythonPlatformManager;
76.29 +import org.netbeans.modules.python.api.PythonMIMEResolver;
76.30 import org.netbeans.modules.python.editor.PythonFormatter;
76.31 -import org.netbeans.modules.python.editor.lexer.PythonTokenId;
76.32 -import org.netbeans.napi.gsfret.source.ClasspathInfo;
76.33 -import org.netbeans.napi.gsfret.source.CompilationController;
76.34 -import org.netbeans.napi.gsfret.source.Phase;
76.35 -import org.netbeans.napi.gsfret.source.Source;
76.36 -import org.netbeans.napi.gsfret.source.SourceUtils;
76.37 +import org.netbeans.modules.python.editor.PythonParserResult;
76.38 import org.openide.cookies.SaveCookie;
76.39 import org.openide.filesystems.FileObject;
76.40 import org.openide.filesystems.FileUtil;
76.41 @@ -563,7 +547,7 @@
76.42 previewPane.getAccessibleContext().setAccessibleName(NbBundle.getMessage(FmtOptions.class, "AN_Preview")); //NOI18N
76.43 previewPane.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(FmtOptions.class, "AD_Preview")); //NOI18N
76.44 previewPane.putClientProperty("HighlightsLayerIncludes", "^org\\.netbeans\\.modules\\.editor\\.lib2\\.highlighting\\.SyntaxHighlighting$"); //NOI18N
76.45 - previewPane.setEditorKit(CloneableEditorSupport.getEditorKit(PythonTokenId.PYTHON_MIME_TYPE));
76.46 + previewPane.setEditorKit(CloneableEditorSupport.getEditorKit(PythonMIMEResolver.PYTHON_MIME_TYPE));
76.47 previewPane.setEditable(false);
76.48 }
76.49 return previewPane;
76.50 @@ -606,7 +590,7 @@
76.51 // to create a temp file, format it, then save it and delete it
76.52 // (to avoid save confirmation dialogs on the modified file etc)
76.53 PythonFormatter formatter = new PythonFormatter(codeStyle);
76.54 - CompilationInfo info = null;
76.55 + PythonParserResult info = null;
76.56 File tmp = null;
76.57 FileObject tmpFo = null;
76.58 if (formatter.needsParserResult()) {
76.59 @@ -619,55 +603,55 @@
76.60 tmpFo = fo;
76.61 // TODO - I need to get the classpath involved here such that it can
76.62 // find used/unused libraries
76.63 - if (!SourceUtils.isScanInProgress()) {
76.64 - // I'm using custom GSF code here because I want to set up an explicit
76.65 - // source path for the fake file object which includes the Python
76.66 - // libraries (since we need them for the isSystemModule lookup
76.67 - //SourceModel model = SourceModelFactory.getInstance().getModel(fo);
76.68 - //if (model != null && !model.isScanInProgress()) {
76.69 - List<FileObject> roots = new ArrayList<FileObject>(new PythonLanguage().getCoreLibraries());
76.70 -
76.71 - final PythonPlatformManager manager = PythonPlatformManager.getInstance();
76.72 - final String platformName = manager.getDefaultPlatform();
76.73 - PythonPlatform activePlatform = manager.getPlatform(platformName);
76.74 - if (activePlatform != null) {
76.75 - roots.addAll(activePlatform.getUniqueLibraryRoots());
76.76 - ClassPath boot = ClassPathSupport.createClassPath(roots.toArray(new FileObject[roots.size()]));
76.77 - ClassPath source = ClassPathSupport.createClassPath(new FileObject[]{fo.getParent()});
76.78 - ClassPath compile = source;
76.79 -
76.80 - ClasspathInfo cpInfo = ClasspathInfo.create(boot, compile, source);
76.81 - Source model = Source.create(cpInfo, fo);
76.82 - if (model != null) {
76.83 - final CompilationInfo[] infoHolder = new CompilationInfo[1];
76.84 - //model.runUserActionTask(new CancellableTask<CompilationInfo>() {
76.85 - model.runUserActionTask(new CancellableTask<CompilationController>() {
76.86 - public void cancel() {
76.87 - }
76.88 -
76.89 - //public void run(CompilationInfo info) throws Exception {
76.90 - public void run(CompilationController info) throws Exception {
76.91 - info.toPhase(Phase.RESOLVED);
76.92 - infoHolder[0] = info;
76.93 - // Force open so info.getFileObject will succeed
76.94 - GsfUtilities.getDocument(fo, true);
76.95 - }
76.96 - }, false);
76.97 - info = infoHolder[0];
76.98 - }
76.99 - }
76.100 - }
76.101 +// if (!SourceUtils.isScanInProgress()) {
76.102 +// // I'm using custom GSF code here because I want to set up an explicit
76.103 +// // source path for the fake file object which includes the Python
76.104 +// // libraries (since we need them for the isSystemModule lookup
76.105 +// //SourceModel model = SourceModelFactory.getInstance().getModel(fo);
76.106 +// //if (model != null && !model.isScanInProgress()) {
76.107 +// List<FileObject> roots = new ArrayList<FileObject>(new PythonLanguage().getCoreLibraries());
76.108 +//
76.109 +// final PythonPlatformManager manager = PythonPlatformManager.getInstance();
76.110 +// final String platformName = manager.getDefaultPlatform();
76.111 +// PythonPlatform activePlatform = manager.getPlatform(platformName);
76.112 +// if (activePlatform != null) {
76.113 +// roots.addAll(activePlatform.getUniqueLibraryRoots());
76.114 +// ClassPath boot = ClassPathSupport.createClassPath(roots.toArray(new FileObject[roots.size()]));
76.115 +// ClassPath source = ClassPathSupport.createClassPath(new FileObject[]{fo.getParent()});
76.116 +// ClassPath compile = source;
76.117 +//
76.118 +// ClasspathInfo cpInfo = ClasspathInfo.create(boot, compile, source);
76.119 +// Source model = Source.create(cpInfo, fo);
76.120 +// if (model != null) {
76.121 +// final CompilationInfo[] infoHolder = new CompilationInfo[1];
76.122 +// //model.runUserActionTask(new CancellableTask<CompilationInfo>() {
76.123 +// model.runUserActionTask(new CancellableTask<CompilationController>() {
76.124 +// public void cancel() {
76.125 +// }
76.126 +//
76.127 +// //public void run(CompilationInfo info) throws Exception {
76.128 +// public void run(CompilationController info) throws Exception {
76.129 +// info.toPhase(Phase.RESOLVED);
76.130 +// infoHolder[0] = info;
76.131 +// // Force open so info.getFileObject will succeed
76.132 +// GsfUtilities.getDocument(fo, true);
76.133 +// }
76.134 +// }, false);
76.135 +// info = infoHolder[0];
76.136 +// }
76.137 +// }
76.138 +// }
76.139 } catch (IOException ex) {
76.140 Exceptions.printStackTrace(ex);
76.141 }
76.142 }
76.143 try {
76.144 - if (info != null && info.getDocument() != null) {
76.145 - Document doc = info.getDocument();
76.146 + if (info != null && info.getSnapshot().getSource().getDocument(false) != null) {
76.147 + Document doc = info.getSnapshot().getSource().getDocument(false);
76.148 formatter.reformat(null, doc, 0, doc.getLength(), info);
76.149 jep.setText(doc.getText(0, doc.getLength()));
76.150 // Save file to avoid warning on exit
76.151 - DataObject dobj = DataObject.find(info.getFileObject());
76.152 + DataObject dobj = DataObject.find(info.getSnapshot().getSource().getFileObject());
76.153 SaveCookie cookie = dobj.getCookie(SaveCookie.class);
76.154 if (cookie != null) {
76.155 cookie.save();
77.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/DiffElement.java Sun Jan 04 13:11:53 2015 -0600
77.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/DiffElement.java Sun Feb 01 15:02:07 2015 -0800
77.3 @@ -45,8 +45,8 @@
77.4
77.5 import java.io.IOException;
77.6 import java.lang.ref.WeakReference;
77.7 -import org.netbeans.napi.gsfret.source.ModificationResult;
77.8 -import org.netbeans.napi.gsfret.source.ModificationResult.Difference;
77.9 +import org.netbeans.modules.csl.spi.support.ModificationResult;
77.10 +import org.netbeans.modules.csl.spi.support.ModificationResult.Difference;
77.11 import org.netbeans.modules.refactoring.spi.SimpleRefactoringElementImplementation;
77.12 import org.netbeans.modules.python.editor.refactoring.ui.ElementGripFactory;
77.13 import org.openide.filesystems.FileObject;
78.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonElementCtx.java Sun Jan 04 13:11:53 2015 -0600
78.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonElementCtx.java Sun Feb 01 15:02:07 2015 -0800
78.3 @@ -32,13 +32,14 @@
78.4
78.5 import java.util.Iterator;
78.6
78.7 -import org.netbeans.modules.gsf.api.ElementKind;
78.8 import org.netbeans.modules.python.editor.elements.AstElement;
78.9 import org.netbeans.modules.python.editor.elements.Element;
78.10 -import org.netbeans.napi.gsfret.source.CompilationInfo;
78.11 import org.netbeans.editor.BaseDocument;
78.12 +import org.netbeans.modules.csl.api.ElementKind;
78.13 +import org.netbeans.modules.csl.spi.GsfUtilities;
78.14 import org.netbeans.modules.python.editor.AstPath;
78.15 import org.netbeans.modules.python.editor.PythonAstUtils;
78.16 +import org.netbeans.modules.python.editor.PythonParserResult;
78.17 import org.netbeans.modules.python.editor.elements.IndexedElement;
78.18 import org.openide.filesystems.FileObject;
78.19 import org.python.antlr.PythonTree;
78.20 @@ -62,7 +63,7 @@
78.21 public class PythonElementCtx {
78.22 private PythonTree node;
78.23 private PythonTree root;
78.24 - private CompilationInfo info;
78.25 + private PythonParserResult info;
78.26 private FileObject fileObject;
78.27 private AstPath path;
78.28 private int caret;
78.29 @@ -79,12 +80,12 @@
78.30 private String defClass;
78.31
78.32 public PythonElementCtx(PythonTree root, PythonTree node, Element element, FileObject fileObject,
78.33 - CompilationInfo info) {
78.34 + PythonParserResult info) {
78.35 initialize(root, node, element, fileObject, info);
78.36 }
78.37
78.38 /** Create a new element holder representing the node closest to the given caret offset in the given compilation job */
78.39 - public PythonElementCtx(CompilationInfo info, int caret) {
78.40 + public PythonElementCtx(PythonParserResult info, int caret) {
78.41 PythonTree root = PythonAstUtils.getRoot(info);
78.42
78.43 int astOffset = PythonAstUtils.getAstOffset(info, caret);
78.44 @@ -117,7 +118,7 @@
78.45 }
78.46 Element element = AstElement.create(info, leaf);
78.47
78.48 - initialize(root, leaf, element, info.getFileObject(), info);
78.49 + initialize(root, leaf, element, info.getSnapshot().getSource().getFileObject(), info);
78.50
78.51 // name = element.getFqn();
78.52 name = element.getName();
78.53 @@ -132,20 +133,20 @@
78.54 }
78.55
78.56 public PythonElementCtx(IndexedElement element) {
78.57 - CompilationInfo[] infoHolder = new CompilationInfo[1];
78.58 + PythonParserResult[] infoHolder = new PythonParserResult[1];
78.59 PythonTree node = PythonAstUtils.getForeignNode(element, infoHolder);
78.60 - CompilationInfo info = infoHolder[0];
78.61 + PythonParserResult info = infoHolder[0];
78.62
78.63 Element e = AstElement.create(info, node);
78.64
78.65 FileObject fo = element.getFileObject();
78.66 - document = PythonRefUtils.getDocument(null, fo);
78.67 + document = GsfUtilities.getDocument(fileObject, false);
78.68
78.69 initialize(root, node, e, fo, info);
78.70 }
78.71
78.72 private void initialize(PythonTree root, PythonTree node, Element element, FileObject fileObject,
78.73 - CompilationInfo info) {
78.74 + PythonParserResult info) {
78.75 this.root = root;
78.76 this.node = node;
78.77 this.element = element;
78.78 @@ -209,7 +210,7 @@
78.79 this.node = node;
78.80 }
78.81
78.82 - public CompilationInfo getInfo() {
78.83 + public PythonParserResult getInfo() {
78.84 return info;
78.85 }
78.86
78.87 @@ -267,7 +268,7 @@
78.88 // }
78.89 public BaseDocument getDocument() {
78.90 if (document == null) {
78.91 - document = PythonRefUtils.getDocument(info, info.getFileObject());
78.92 + document = GsfUtilities.getDocument(info.getSnapshot().getSource().getFileObject(), false);
78.93 }
78.94
78.95 return document;
79.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonRefUtils.java Sun Jan 04 13:11:53 2015 -0600
79.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonRefUtils.java Sun Feb 01 15:02:07 2015 -0800
79.3 @@ -58,9 +58,7 @@
79.4 import org.netbeans.api.editor.mimelookup.MimeLookup;
79.5 import org.netbeans.api.editor.mimelookup.MimePath;
79.6 import org.netbeans.api.editor.settings.FontColorSettings;
79.7 -import org.netbeans.modules.gsf.api.ElementKind;
79.8 -import org.netbeans.modules.gsfpath.api.classpath.ClassPath;
79.9 -import org.netbeans.modules.gsfpath.api.classpath.GlobalPathRegistry;
79.10 +import org.netbeans.api.java.classpath.ClassPath;
79.11 import org.netbeans.api.lexer.Token;
79.12 import org.netbeans.api.lexer.TokenHierarchy;
79.13 import org.netbeans.api.lexer.TokenId;
79.14 @@ -70,13 +68,12 @@
79.15 import org.netbeans.api.project.ProjectUtils;
79.16 import org.netbeans.api.project.SourceGroup;
79.17 import org.netbeans.api.project.ui.OpenProjects;
79.18 -import org.netbeans.napi.gsfret.source.ClasspathInfo;
79.19 -import org.netbeans.napi.gsfret.source.CompilationInfo;
79.20 -import org.netbeans.napi.gsfret.source.Source;
79.21 -import org.netbeans.napi.gsfret.source.SourceUtils;
79.22 import org.netbeans.editor.BaseDocument;
79.23 -import org.netbeans.modules.gsfpath.spi.classpath.support.ClassPathSupport;
79.24 +import org.netbeans.modules.csl.api.ElementKind;
79.25 +import org.netbeans.modules.parsing.api.Source;
79.26 +import org.netbeans.modules.python.api.PythonMIMEResolver;
79.27 import org.netbeans.modules.python.editor.PythonAstUtils;
79.28 +import org.netbeans.modules.python.editor.PythonParserResult;
79.29 import org.netbeans.modules.python.editor.PythonUtils;
79.30 import org.netbeans.modules.python.editor.lexer.PythonTokenId;
79.31 import org.openide.cookies.EditorCookie;
79.32 @@ -103,51 +100,6 @@
79.33 private PythonRefUtils() {
79.34 }
79.35
79.36 - // XXX Should this be unused now?
79.37 - public static Source createSource(ClasspathInfo cpInfo, FileObject fo) {
79.38 - if (PythonUtils.canContainPython(fo)) {
79.39 - return Source.create(cpInfo, fo);
79.40 - }
79.41 -
79.42 - return null;
79.43 - }
79.44 -
79.45 - public static Source getSource(FileObject fo) {
79.46 - Source source = Source.forFileObject(fo);
79.47 -
79.48 - return source;
79.49 - }
79.50 -
79.51 - public static Source getSource(Document doc) {
79.52 - Source source = Source.forDocument(doc);
79.53 -
79.54 - return source;
79.55 - }
79.56 -
79.57 - public static BaseDocument getDocument(CompilationInfo info, FileObject fo) {
79.58 - BaseDocument doc = null;
79.59 -
79.60 - if (info != null) {
79.61 - doc = (BaseDocument)info.getDocument();
79.62 - }
79.63 -
79.64 - if (doc == null) {
79.65 - try {
79.66 - // Gotta open it first
79.67 - DataObject od = DataObject.find(fo);
79.68 - EditorCookie ec = od.getCookie(EditorCookie.class);
79.69 -
79.70 - if (ec != null) {
79.71 - doc = (BaseDocument)ec.openDocument();
79.72 - }
79.73 - } catch (IOException ex) {
79.74 - Exceptions.printStackTrace(ex);
79.75 - }
79.76 - }
79.77 -
79.78 - return doc;
79.79 - }
79.80 -
79.81 /** Compute the names (full and simple, e.g. Foo::Bar and Bar) for the given node, if any, and return as
79.82 * a String[2] = {name,simpleName} */
79.83 public static String[] getNodeNames(PythonTree node) {
79.84 @@ -169,10 +121,10 @@
79.85 return new String[]{name, simpleName};
79.86 }
79.87
79.88 - public static CloneableEditorSupport findCloneableEditorSupport(CompilationInfo info) {
79.89 + public static CloneableEditorSupport findCloneableEditorSupport(PythonParserResult info) {
79.90 DataObject dob = null;
79.91 try {
79.92 - dob = DataObject.find(info.getFileObject());
79.93 + dob = DataObject.find(info.getSnapshot().getSource().getFileObject());
79.94 } catch (DataObjectNotFoundException ex) {
79.95 Exceptions.printStackTrace(ex);
79.96 }
79.97 @@ -211,7 +163,7 @@
79.98 StringBuffer buf = new StringBuffer();
79.99 // TODO - check whether we need python highlighting or rhtml highlighting
79.100 TokenHierarchy tokenH = TokenHierarchy.create(text, PythonTokenId.language());
79.101 - Lookup lookup = MimeLookup.getLookup(MimePath.get(PythonTokenId.PYTHON_MIME_TYPE));
79.102 + Lookup lookup = MimeLookup.getLookup(MimePath.get(PythonMIMEResolver.PYTHON_MIME_TYPE));
79.103 FontColorSettings settings = lookup.lookup(FontColorSettings.class);
79.104 @SuppressWarnings("unchecked")
79.105 TokenSequence<? extends TokenId> tok = tokenH.tokenSequence();
79.106 @@ -341,82 +293,82 @@
79.107 return tph.getKind();
79.108 }
79.109
79.110 - public static ClasspathInfo getClasspathInfoFor(FileObject... files) {
79.111 - assert files.length > 0;
79.112 - Set<URL> dependentRoots = new HashSet<URL>();
79.113 - for (FileObject fo : files) {
79.114 - Project p = null;
79.115 - if (fo != null) {
79.116 - p = FileOwnerQuery.getOwner(fo);
79.117 - }
79.118 - if (p != null) {
79.119 - ClassPath classPath = ClassPath.getClassPath(fo, ClassPath.SOURCE);
79.120 - if (classPath == null) {
79.121 - return null;
79.122 - }
79.123 - FileObject ownerRoot = classPath.findOwnerRoot(fo);
79.124 - if (ownerRoot != null) {
79.125 - URL sourceRoot = URLMapper.findURL(ownerRoot, URLMapper.INTERNAL);
79.126 - dependentRoots.addAll(SourceUtils.getDependentRoots(sourceRoot));
79.127 - for (SourceGroup root : ProjectUtils.getSources(p).getSourceGroups(SOURCES_TYPE_PYTHON)) {
79.128 - dependentRoots.add(URLMapper.findURL(root.getRootFolder(), URLMapper.INTERNAL));
79.129 - }
79.130 - } else {
79.131 - dependentRoots.add(URLMapper.findURL(fo.getParent(), URLMapper.INTERNAL));
79.132 - }
79.133 - } else {
79.134 - for (ClassPath cp : GlobalPathRegistry.getDefault().getPaths(ClassPath.SOURCE)) {
79.135 - for (FileObject root : cp.getRoots()) {
79.136 - dependentRoots.add(URLMapper.findURL(root, URLMapper.INTERNAL));
79.137 - }
79.138 - }
79.139 - }
79.140 - }
79.141 -
79.142 - ClassPath rcp = ClassPathSupport.createClassPath(dependentRoots.toArray(new URL[dependentRoots.size()]));
79.143 - ClassPath nullPath = ClassPathSupport.createClassPath(new FileObject[0]);
79.144 - ClassPath boot = files[0] != null ? ClassPath.getClassPath(files[0], ClassPath.BOOT) : nullPath;
79.145 - ClassPath compile = files[0] != null ? ClassPath.getClassPath(files[0], ClassPath.COMPILE) : nullPath;
79.146 -
79.147 - if (boot == null || compile == null) { // 146499
79.148 - return null;
79.149 - }
79.150 -
79.151 - ClasspathInfo cpInfo = ClasspathInfo.create(boot, compile, rcp);
79.152 - return cpInfo;
79.153 - }
79.154 -
79.155 - public static ClasspathInfo getClasspathInfoFor(PythonElementCtx ctx) {
79.156 - return getClasspathInfoFor(ctx.getFileObject());
79.157 - }
79.158 -
79.159 - public static List<FileObject> getPythonFilesInProject(FileObject fileInProject) {
79.160 - List<FileObject> list = new ArrayList<FileObject>(100);
79.161 - ClasspathInfo cpInfo = PythonRefUtils.getClasspathInfoFor(fileInProject);
79.162 - if (cpInfo == null) {
79.163 - return list;
79.164 - }
79.165 - ClassPath cp = cpInfo.getClassPath(ClasspathInfo.PathKind.SOURCE);
79.166 - for (ClassPath.Entry entry : cp.entries()) {
79.167 - FileObject root = entry.getRoot();
79.168 - String name = root.getName();
79.169 - // Skip non-refactorable parts in renaming
79.170 - if (name.equals("vendor") || name.equals("script")) { // NOI18N
79.171 - continue;
79.172 - }
79.173 - addPythonFiles(list, root);
79.174 - }
79.175 -
79.176 - return list;
79.177 - }
79.178 -
79.179 - private static void addPythonFiles(List<FileObject> list, FileObject f) {
79.180 - if (f.isFolder()) {
79.181 - for (FileObject child : f.getChildren()) {
79.182 - addPythonFiles(list, child);
79.183 - }
79.184 - } else if (PythonUtils.canContainPython(f)) {
79.185 - list.add(f);
79.186 - }
79.187 - }
79.188 +// public static ClasspathInfo getClasspathInfoFor(FileObject... files) {
79.189 +// assert files.length > 0;
79.190 +// Set<URL> dependentRoots = new HashSet<URL>();
79.191 +// for (FileObject fo : files) {
79.192 +// Project p = null;
79.193 +// if (fo != null) {
79.194 +// p = FileOwnerQuery.getOwner(fo);
79.195 +// }
79.196 +// if (p != null) {
79.197 +// ClassPath classPath = ClassPath.getClassPath(fo, ClassPath.SOURCE);
79.198 +// if (classPath == null) {
79.199 +// return null;
79.200 +// }
79.201 +// FileObject ownerRoot = classPath.findOwnerRoot(fo);
79.202 +// if (ownerRoot != null) {
79.203 +// URL sourceRoot = URLMapper.findURL(ownerRoot, URLMapper.INTERNAL);
79.204 +// dependentRoots.addAll(SourceUtils.getDependentRoots(sourceRoot));
79.205 +// for (SourceGroup root : ProjectUtils.getSources(p).getSourceGroups(SOURCES_TYPE_PYTHON)) {
79.206 +// dependentRoots.add(URLMapper.findURL(root.getRootFolder(), URLMapper.INTERNAL));
79.207 +// }
79.208 +// } else {
79.209 +// dependentRoots.add(URLMapper.findURL(fo.getParent(), URLMapper.INTERNAL));
79.210 +// }
79.211 +// } else {
79.212 +// for (ClassPath cp : GlobalPathRegistry.getDefault().getPaths(ClassPath.SOURCE)) {
79.213 +// for (FileObject root : cp.getRoots()) {
79.214 +// dependentRoots.add(URLMapper.findURL(root, URLMapper.INTERNAL));
79.215 +// }
79.216 +// }
79.217 +// }
79.218 +// }
79.219 +//
79.220 +// ClassPath rcp = ClassPathSupport.createClassPath(dependentRoots.toArray(new URL[dependentRoots.size()]));
79.221 +// ClassPath nullPath = ClassPathSupport.createClassPath(new FileObject[0]);
79.222 +// ClassPath boot = files[0] != null ? ClassPath.getClassPath(files[0], ClassPath.BOOT) : nullPath;
79.223 +// ClassPath compile = files[0] != null ? ClassPath.getClassPath(files[0], ClassPath.COMPILE) : nullPath;
79.224 +//
79.225 +// if (boot == null || compile == null) { // 146499
79.226 +// return null;
79.227 +// }
79.228 +//
79.229 +// ClasspathInfo cpInfo = ClasspathInfo.create(boot, compile, rcp);
79.230 +// return cpInfo;
79.231 +// }
79.232 +//
79.233 +// public static ClasspathInfo getClasspathInfoFor(PythonElementCtx ctx) {
79.234 +// return getClasspathInfoFor(ctx.getFileObject());
79.235 +// }
79.236 +//
79.237 +// public static List<FileObject> getPythonFilesInProject(FileObject fileInProject) {
79.238 +// List<FileObject> list = new ArrayList<FileObject>(100);
79.239 +// ClasspathInfo cpInfo = PythonRefUtils.getClasspathInfoFor(fileInProject);
79.240 +// if (cpInfo == null) {
79.241 +// return list;
79.242 +// }
79.243 +// ClassPath cp = cpInfo.getClassPath(ClasspathInfo.PathKind.SOURCE);
79.244 +// for (ClassPath.Entry entry : cp.entries()) {
79.245 +// FileObject root = entry.getRoot();
79.246 +// String name = root.getName();
79.247 +// // Skip non-refactorable parts in renaming
79.248 +// if (name.equals("vendor") || name.equals("script")) { // NOI18N
79.249 +// continue;
79.250 +// }
79.251 +// addPythonFiles(list, root);
79.252 +// }
79.253 +//
79.254 +// return list;
79.255 +// }
79.256 +//
79.257 +// private static void addPythonFiles(List<FileObject> list, FileObject f) {
79.258 +// if (f.isFolder()) {
79.259 +// for (FileObject child : f.getChildren()) {
79.260 +// addPythonFiles(list, child);
79.261 +// }
79.262 +// } else if (PythonUtils.canContainPython(f)) {
79.263 +// list.add(f);
79.264 +// }
79.265 +// }
79.266 }
80.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonRefactoringPlugin.java Sun Jan 04 13:11:53 2015 -0600
80.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonRefactoringPlugin.java Sun Feb 01 15:02:07 2015 -0800
80.3 @@ -43,6 +43,7 @@
80.4 */
80.5 package org.netbeans.modules.python.editor.refactoring;
80.6
80.7 +/*
80.8 import java.io.IOException;
80.9 import java.util.Collection;
80.10 import java.util.HashMap;
80.11 @@ -64,13 +65,14 @@
80.12 import org.netbeans.modules.refactoring.spi.*;
80.13 import org.netbeans.modules.refactoring.api.*;
80.14 import org.openide.filesystems.FileObject;
80.15 -
80.16 +*/
80.17 /**
80.18 * Plugin implementation based on the one for Java refactoring.
80.19 *
80.20 * @author Jan Becicka
80.21 * @author Tor Norbye
80.22 */
80.23 +/* Uncomment when it works ;-)
80.24 public abstract class PythonRefactoringPlugin extends ProgressProviderAdapter implements RefactoringPlugin, CancellableTask<CompilationController> {
80.25 protected enum Phase {
80.26 PRECHECK, FASTCHECKPARAMETERS, CHECKPARAMETERS, PREPARE, DEFAULT
80.27 @@ -262,3 +264,4 @@
80.28 }
80.29 }
80.30 }
80.31 +*/
80.32 \ No newline at end of file
81.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonRefactoringsFactory.java Sun Jan 04 13:11:53 2015 -0600
81.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonRefactoringsFactory.java Sun Feb 01 15:02:07 2015 -0800
81.3 @@ -63,12 +63,12 @@
81.4 PythonElementCtx handle = look.lookup(PythonElementCtx.class);
81.5 if (refactoring instanceof WhereUsedQuery) {
81.6 if (handle != null) {
81.7 - return new PythonWhereUsedQueryPlugin((WhereUsedQuery)refactoring);
81.8 +// return new PythonWhereUsedQueryPlugin((WhereUsedQuery)refactoring);
81.9 }
81.10 } else if (refactoring instanceof RenameRefactoring) {
81.11 if (handle != null || ((file != null) && PythonUtils.canContainPython(file))) {
81.12 //rename java file, class, method etc..
81.13 - return new PythonRenameRefactoringPlugin((RenameRefactoring)refactoring);
81.14 +// return new PythonRenameRefactoringPlugin((RenameRefactoring)refactoring);
81.15 }
81.16 }
81.17 return null;
82.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonRenameRefactoringPlugin.java Sun Jan 04 13:11:53 2015 -0600
82.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonRenameRefactoringPlugin.java Sun Feb 01 15:02:07 2015 -0800
82.3 @@ -42,7 +42,7 @@
82.4 * made subject to such option by the copyright holder.
82.5 */
82.6 package org.netbeans.modules.python.editor.refactoring;
82.7 -
82.8 +/*
82.9 import org.netbeans.modules.gsf.api.Error;
82.10 import org.netbeans.modules.gsf.api.Severity;
82.11 import org.netbeans.modules.python.editor.elements.Element;
82.12 @@ -99,7 +99,7 @@
82.13 import org.python.antlr.ast.FunctionDef;
82.14 import org.python.antlr.ast.Name;
82.15 import org.python.antlr.base.expr;
82.16 -
82.17 +*/
82.18 /**
82.19 * The actual Renaming refactoring work for Python.
82.20 *
82.21 @@ -116,6 +116,7 @@
82.22 *
82.23 * @todo Complete this. Most of the prechecks are not implemented - and the refactorings themselves need a lot of work.
82.24 */
82.25 +/* Uncomment when it works ;-)
82.26 public class PythonRenameRefactoringPlugin extends PythonRefactoringPlugin {
82.27 private PythonElementCtx treePathHandle = null;
82.28 private Collection overriddenByMethods = null; // methods that override the method to be renamed
82.29 @@ -123,7 +124,6 @@
82.30 private boolean doCheckName = true;
82.31 private RenameRefactoring refactoring;
82.32
82.33 - /** Creates a new instance of RenameRefactoring */
82.34 public PythonRenameRefactoringPlugin(RenameRefactoring rename) {
82.35 this.refactoring = rename;
82.36 PythonElementCtx tph = rename.getRefactoringSource().lookup(PythonElementCtx.class);
82.37 @@ -352,10 +352,6 @@
82.38 return NbBundle.getMessage(PythonRenameRefactoringPlugin.class, key);
82.39 }
82.40
82.41 - /**
82.42 - *
82.43 - * @author Jan Becicka
82.44 - */
82.45 public class RenameTransformer extends SearchVisitor {
82.46 private Set<PythonElementCtx> allMethods;
82.47 private String newName;
82.48 @@ -645,14 +641,14 @@
82.49 Difference diff = new Difference(Difference.Kind.CHANGE, startPos, endPos, oldCode, newCode, desc);
82.50 diffs.add(diff);
82.51 }
82.52 -
82.53 +*/
82.54 /**
82.55 * @todo P1: This is matching method names on classes that have nothing to do with the class we're searching for
82.56 * - I've gotta filter fields, methods etc. that are not in the current class
82.57 * (but I also have to search for methods that are OVERRIDING the class... so I've gotta work a little harder!)
82.58 * @todo Arity matching on the methods to preclude methods that aren't overriding or aliasing!
82.59 */
82.60 - private class RenameMethodVisitor extends Visitor {
82.61 +/* private class RenameMethodVisitor extends Visitor {
82.62 private String name;
82.63 private PythonElementCtx searchCtx;
82.64 private PythonElementCtx fileCtx;
82.65 @@ -683,7 +679,7 @@
82.66 }
82.67 }
82.68
82.69 - /** @todo Rename!*/
82.70 + ** @todo Rename!*
82.71 private class RenameClassVisitor extends Visitor {
82.72 private String name;
82.73 private PythonElementCtx searchCtx;
82.74 @@ -724,3 +720,4 @@
82.75 }
82.76 }
82.77 }
82.78 +*/
82.79 \ No newline at end of file
83.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonTransaction.java Sun Jan 04 13:11:53 2015 -0600
83.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonTransaction.java Sun Feb 01 15:02:07 2015 -0800
83.3 @@ -42,18 +42,18 @@
83.4 * made subject to such option by the copyright holder.
83.5 */
83.6 package org.netbeans.modules.python.editor.refactoring;
83.7 -
83.8 +/*
83.9 import java.io.IOException;
83.10 import java.util.ArrayList;
83.11 import java.util.Collection;
83.12 -import org.netbeans.napi.gsfret.source.ModificationResult;
83.13 import org.netbeans.modules.refactoring.spi.BackupFacility;
83.14 import org.netbeans.modules.refactoring.spi.Transaction;
83.15 -
83.16 +*/
83.17 /**
83.18 *
83.19 * @author Jan Becicka
83.20 */
83.21 +/* Probably remove completely ;-)
83.22 public class PythonTransaction implements Transaction {
83.23 ArrayList<BackupFacility.Handle> ids = new ArrayList<BackupFacility.Handle>();
83.24 private boolean commited = false;
83.25 @@ -96,4 +96,4 @@
83.26 }
83.27 }
83.28 }
83.29 -
83.30 +*/
83.31 \ No newline at end of file
84.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonWhereUsedQueryPlugin.java Sun Jan 04 13:11:53 2015 -0600
84.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/PythonWhereUsedQueryPlugin.java Sun Feb 01 15:02:07 2015 -0800
84.3 @@ -42,7 +42,7 @@
84.4 * made subject to such option by the copyright holder.
84.5 */
84.6 package org.netbeans.modules.python.editor.refactoring;
84.7 -
84.8 +/*
84.9 import java.io.IOException;
84.10 import java.util.Collections;
84.11 import java.util.HashSet;
84.12 @@ -90,7 +90,7 @@
84.13 import org.python.antlr.ast.FunctionDef;
84.14 import org.python.antlr.ast.Name;
84.15 import org.python.antlr.base.expr;
84.16 -
84.17 +*/
84.18 /**
84.19 * Actual implementation of Find Usages query search for Python
84.20 *
84.21 @@ -99,13 +99,13 @@
84.22 *
84.23 * @author Tor Norbye
84.24 */
84.25 +/* Uncomment when it works ;-)
84.26 public class PythonWhereUsedQueryPlugin extends PythonRefactoringPlugin {
84.27 private WhereUsedQuery refactoring;
84.28 private PythonElementCtx searchHandle;
84.29 private Set<IndexedElement> subclasses;
84.30 private String targetName;
84.31
84.32 - /** Creates a new instance of WhereUsedQuery */
84.33 public PythonWhereUsedQueryPlugin(WhereUsedQuery refactoring) {
84.34 this.refactoring = refactoring;
84.35 this.searchHandle = refactoring.getRefactoringSource().lookup(PythonElementCtx.class);
84.36 @@ -461,7 +461,7 @@
84.37 * - I've gotta filter fields, methods etc. that are not in the current class
84.38 * (but I also have to search for methods that are OVERRIDING the class... so I've gotta work a little harder!)
84.39 * @todo Arity matching on the methods to preclude methods that aren't overriding or aliasing!
84.40 - */
84.41 + *
84.42 private class FindUsagesMethodVisitor extends Visitor {
84.43 private String name;
84.44 private PythonElementCtx searchCtx;
84.45 @@ -541,3 +541,4 @@
84.46 }
84.47 }
84.48 }
84.49 +*/
84.50 \ No newline at end of file
85.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/SearchVisitor.java Sun Jan 04 13:11:53 2015 -0600
85.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/SearchVisitor.java Sun Feb 01 15:02:07 2015 -0800
85.3 @@ -42,16 +42,15 @@
85.4 * made subject to such option by the copyright holder.
85.5 */
85.6 package org.netbeans.modules.python.editor.refactoring;
85.7 -
85.8 +/*
85.9 import java.io.IOException;
85.10 -import org.netbeans.napi.gsfret.source.Phase;
85.11 -import org.netbeans.napi.gsfret.source.WorkingCopy;
85.12 import org.openide.ErrorManager;
85.13 -
85.14 +*
85.15 /**
85.16 *
85.17 * @author Jan Becicka
85.18 */
85.19 +/* Could use a JavaSource like source rewriter
85.20 public abstract class SearchVisitor {
85.21 protected WorkingCopy workingCopy;
85.22
85.23 @@ -66,3 +65,4 @@
85.24
85.25 public abstract void scan();
85.26 }
85.27 +*/
85.28 \ No newline at end of file
86.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/WhereUsedElement.java Sun Jan 04 13:11:53 2015 -0600
86.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/WhereUsedElement.java Sun Feb 01 15:02:07 2015 -0800
86.3 @@ -47,14 +47,14 @@
86.4 import java.util.Set;
86.5 import javax.swing.Icon;
86.6 import javax.swing.text.Position.Bias;
86.7 -import org.netbeans.modules.gsf.api.Modifier;
86.8 -
86.9 -import org.netbeans.modules.gsf.api.OffsetRange;
86.10 -import org.netbeans.napi.gsfret.source.CompilationInfo;
86.11 -import org.netbeans.napi.gsfret.source.UiUtils;
86.12 import org.netbeans.editor.BaseDocument;
86.13 import org.netbeans.editor.Utilities;
86.14 +import org.netbeans.modules.csl.api.Modifier;
86.15 +import org.netbeans.modules.csl.api.OffsetRange;
86.16 +import org.netbeans.modules.csl.api.UiUtils;
86.17 +import org.netbeans.modules.csl.spi.GsfUtilities;
86.18 import org.netbeans.modules.python.editor.PythonAstUtils;
86.19 +import org.netbeans.modules.python.editor.PythonParserResult;
86.20 import org.netbeans.modules.python.editor.lexer.PythonLexerUtils;
86.21 import org.netbeans.modules.python.editor.refactoring.ui.ElementGripFactory;
86.22 import org.netbeans.modules.refactoring.spi.SimpleRefactoringElementImplementation;
86.23 @@ -115,7 +115,7 @@
86.24 }
86.25
86.26 public static WhereUsedElement create(PythonElementCtx tree) {
86.27 - CompilationInfo info = tree.getInfo();
86.28 + PythonParserResult info = tree.getInfo();
86.29 OffsetRange range = PythonAstUtils.getNameRange(info, tree.getNode());
86.30 assert range != OffsetRange.NONE;
86.31
86.32 @@ -130,8 +130,8 @@
86.33 return create(info, tree.getName(), range, icon);
86.34 }
86.35
86.36 - public static WhereUsedElement create(CompilationInfo info, String name, OffsetRange range, Icon icon) {
86.37 - FileObject fo = info.getFileObject();
86.38 + public static WhereUsedElement create(PythonParserResult info, String name, OffsetRange range, Icon icon) {
86.39 + FileObject fo = info.getSnapshot().getSource().getFileObject();
86.40 int start = range.getStart();
86.41 int end = range.getEnd();
86.42
86.43 @@ -139,7 +139,7 @@
86.44 int en = start; // ! Same line as start
86.45 String content = null;
86.46
86.47 - BaseDocument bdoc = PythonRefUtils.getDocument(info, info.getFileObject());
86.48 + BaseDocument bdoc = GsfUtilities.getDocument(info.getSnapshot().getSource().getFileObject(), false);
86.49 try {
86.50 bdoc.readLock();
86.51
86.52 @@ -204,8 +204,8 @@
86.53 new OffsetRange(start, end), icon);
86.54 }
86.55
86.56 - public static WhereUsedElement create(CompilationInfo info, String name, String html, OffsetRange range, Icon icon) {
86.57 - FileObject fo = info.getFileObject();
86.58 + public static WhereUsedElement create(PythonParserResult info, String name, String html, OffsetRange range, Icon icon) {
86.59 + FileObject fo = info.getSnapshot().getSource().getFileObject();
86.60 int start = range.getStart();
86.61 int end = range.getEnd();
86.62
87.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/ElementGripFactory.java Sun Jan 04 13:11:53 2015 -0600
87.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/ElementGripFactory.java Sun Feb 01 15:02:07 2015 -0800
87.3 @@ -47,7 +47,7 @@
87.4 import java.util.Set;
87.5 import java.util.WeakHashMap;
87.6 import javax.swing.Icon;
87.7 -import org.netbeans.modules.gsf.api.OffsetRange;
87.8 +import org.netbeans.modules.csl.api.OffsetRange;
87.9 import org.openide.filesystems.FileObject;
87.10
87.11 /**
88.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/FolderTreeElement.java Sun Jan 04 13:11:53 2015 -0600
88.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/FolderTreeElement.java Sun Feb 01 15:02:07 2015 -0800
88.3 @@ -44,15 +44,15 @@
88.4 package org.netbeans.modules.python.editor.refactoring.ui;
88.5
88.6 import javax.swing.Icon;
88.7 -import org.netbeans.modules.gsf.api.ElementKind;
88.8 -import org.netbeans.modules.gsfpath.api.classpath.ClassPath;
88.9 +import org.netbeans.api.java.classpath.ClassPath;
88.10 import org.netbeans.api.project.FileOwnerQuery;
88.11 import org.netbeans.api.project.Project;
88.12 import org.netbeans.api.project.ProjectUtils;
88.13 import org.netbeans.api.project.SourceGroup;
88.14 import org.netbeans.api.project.Sources;
88.15 +import org.netbeans.modules.csl.api.ElementKind;
88.16 +import org.netbeans.modules.csl.api.UiUtils;
88.17 import org.netbeans.modules.python.editor.refactoring.PythonRefUtils;
88.18 -import org.netbeans.napi.gsfret.source.UiUtils;
88.19 import org.netbeans.modules.refactoring.spi.ui.*;
88.20 import org.openide.filesystems.FileObject;
88.21 import org.openide.filesystems.FileUtil;
89.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/RefactoringActionsProvider.java Sun Jan 04 13:11:53 2015 -0600
89.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/RefactoringActionsProvider.java Sun Feb 01 15:02:07 2015 -0800
89.3 @@ -47,28 +47,31 @@
89.4 import java.lang.ref.WeakReference;
89.5 import java.util.ArrayList;
89.6 import java.util.Collection;
89.7 +import java.util.Collections;
89.8 import java.util.Dictionary;
89.9 import java.util.List;
89.10 import javax.swing.JOptionPane;
89.11 import javax.swing.text.JTextComponent;
89.12 import org.netbeans.api.fileinfo.NonRecursiveFolder;
89.13 -import org.netbeans.modules.gsf.api.CancellableTask;
89.14 -import org.netbeans.napi.gsfret.source.CompilationController;
89.15 -import org.netbeans.napi.gsfret.source.CompilationInfo;
89.16 -import org.netbeans.napi.gsfret.source.Phase;
89.17 -import org.netbeans.napi.gsfret.source.Source;
89.18 +import org.netbeans.modules.csl.spi.ParserResult;
89.19 +import org.netbeans.modules.parsing.api.ParserManager;
89.20 +import org.netbeans.modules.parsing.api.ResultIterator;
89.21 +import org.netbeans.modules.parsing.api.Source;
89.22 +import org.netbeans.modules.parsing.api.UserTask;
89.23 +import org.netbeans.modules.parsing.spi.ParseException;
89.24 import org.netbeans.modules.python.editor.refactoring.PythonRefUtils;
89.25 import org.netbeans.modules.python.editor.refactoring.PythonElementCtx;
89.26 import org.netbeans.modules.refactoring.spi.ui.UI;
89.27 import org.netbeans.modules.refactoring.spi.ui.ActionsImplementationProvider;
89.28 import org.netbeans.modules.refactoring.spi.ui.RefactoringUI;
89.29 import org.netbeans.modules.python.editor.PythonAstUtils;
89.30 +import org.netbeans.modules.python.editor.PythonIndex;
89.31 import org.netbeans.modules.python.editor.PythonParserResult;
89.32 +import org.netbeans.modules.python.editor.PythonStructureScanner;
89.33 import org.netbeans.modules.python.editor.PythonStructureScanner.AnalysisResult;
89.34 import org.netbeans.modules.python.editor.PythonUtils;
89.35 import org.netbeans.modules.python.editor.elements.AstElement;
89.36 import org.netbeans.modules.python.editor.elements.Element;
89.37 -import org.netbeans.napi.gsfret.source.ClasspathInfo;
89.38 import org.openide.ErrorManager;
89.39 import org.openide.cookies.EditorCookie;
89.40 import org.openide.filesystems.FileObject;
89.41 @@ -98,9 +101,9 @@
89.42 if (isFromEditor(ec)) {
89.43 task = new TextComponentTask(ec) {
89.44 @Override
89.45 - protected RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, int startOffset, int endOffset, final CompilationInfo info) {
89.46 + protected RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, int startOffset, int endOffset, final PythonParserResult info) {
89.47 // If you're trying to rename a constructor, rename the enclosing class instead
89.48 - return new RenameRefactoringUI(selectedElement, info);
89.49 + return new RenameRefactoringUI(selectedElement);
89.50 }
89.51 };
89.52 } else {
89.53 @@ -112,12 +115,12 @@
89.54 if (pkg[0] != null) {
89.55 return new RenameRefactoringUI(pkg[0], newName);
89.56 } else {
89.57 - return new RenameRefactoringUI(selectedElements[0], newName, handles == null || handles.isEmpty() ? null : handles.iterator().next(), cinfo == null ? null : cinfo.get());
89.58 + return new RenameRefactoringUI(selectedElements[0], newName, handles == null || handles.isEmpty() ? null : handles.iterator().next());
89.59 }
89.60 } else if (pkg[0] != null) {
89.61 return new RenameRefactoringUI(pkg[0]);
89.62 } else {
89.63 - return new RenameRefactoringUI(selectedElements[0], handles == null || handles.isEmpty() ? null : handles.iterator().next(), cinfo == null ? null : cinfo.get());
89.64 + return new RenameRefactoringUI(selectedElements[0], handles == null || handles.isEmpty() ? null : handles.iterator().next());
89.65 }
89.66 }
89.67 };
89.68 @@ -218,14 +221,14 @@
89.69 if (isFromEditor(ec)) {
89.70 task = new TextComponentTask(ec) {
89.71 @Override
89.72 - protected RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, int startOffset, int endOffset, CompilationInfo info) {
89.73 - return new WhereUsedQueryUI(selectedElement, info);
89.74 + protected RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, int startOffset, int endOffset, PythonParserResult info) {
89.75 + return new WhereUsedQueryUI(selectedElement);
89.76 }
89.77 };
89.78 } else {
89.79 task = new NodeToElementTask(lookup.lookupAll(Node.class)) {
89.80 - protected RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, CompilationInfo info) {
89.81 - return new WhereUsedQueryUI(selectedElement, info);
89.82 + protected RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, PythonParserResult info) {
89.83 + return new WhereUsedQueryUI(selectedElement);
89.84 }
89.85 };
89.86 }
89.87 @@ -258,7 +261,7 @@
89.88 public void doMove(final Lookup lookup) {
89.89 }
89.90
89.91 - public static abstract class TextComponentTask implements Runnable, CancellableTask<CompilationController> {
89.92 + public static abstract class TextComponentTask extends UserTask implements Runnable {
89.93 private JTextComponent textC;
89.94 private int caret;
89.95 private int start;
89.96 @@ -278,45 +281,41 @@
89.97 public void cancel() {
89.98 }
89.99
89.100 - public void run(CompilationController cc) throws Exception {
89.101 - cc.toPhase(Phase.RESOLVED);
89.102 - PythonTree root = PythonAstUtils.getRoot(cc);
89.103 + public void run(ResultIterator cc) throws Exception {
89.104 + PythonTree root = PythonAstUtils.getRoot((ParserResult) cc.getParserResult());
89.105 if (root == null) {
89.106 // TODO How do I add some kind of error message?
89.107 System.out.println("FAILURE - can't refactor uncompileable sources");
89.108 return;
89.109 }
89.110
89.111 - PythonElementCtx ctx = new PythonElementCtx(cc, caret);
89.112 + PythonElementCtx ctx = new PythonElementCtx((PythonParserResult)cc.getParserResult(), caret);
89.113 if (ctx.getSimpleName() == null) {
89.114 return;
89.115 }
89.116 - ui = createRefactoringUI(ctx, start, end, cc);
89.117 + ui = createRefactoringUI(ctx, start, end, (PythonParserResult)cc.getParserResult());
89.118 }
89.119
89.120 public final void run() {
89.121 FileObject fo = null;
89.122 try {
89.123 - Source source = PythonRefUtils.getSource(textC.getDocument());
89.124 - source.runUserActionTask(this, false);
89.125 - Collection<FileObject> fileObjects = source.getFileObjects();
89.126 - if (fileObjects.size() > 0) {
89.127 - fo = fileObjects.iterator().next();
89.128 - }
89.129 - } catch (IOException ioe) {
89.130 - ErrorManager.getDefault().notify(ioe);
89.131 + Source source = Source.create(textC.getDocument());
89.132 + ParserManager.parse(Collections.singleton(source), this);
89.133 + fo = source.getFileObject();
89.134 + } catch (ParseException ex) {
89.135 + ErrorManager.getDefault().notify(ex);
89.136 return;
89.137 }
89.138 TopComponent activetc = TopComponent.getRegistry().getActivated();
89.139
89.140 if (ui != null) {
89.141 - if (fo != null) {
89.142 - ClasspathInfo classpathInfoFor = PythonRefUtils.getClasspathInfoFor(fo);
89.143 - if (classpathInfoFor == null) {
89.144 - JOptionPane.showMessageDialog(null, NbBundle.getMessage(RefactoringActionsProvider.class, "ERR_CannotFindClasspath"));
89.145 - return;
89.146 - }
89.147 - }
89.148 +// if (fo != null) {
89.149 +// ClasspathInfo classpathInfoFor = PythonRefUtils.getClasspathInfoFor(fo);
89.150 +// if (classpathInfoFor == null) {
89.151 +// JOptionPane.showMessageDialog(null, NbBundle.getMessage(RefactoringActionsProvider.class, "ERR_CannotFindClasspath"));
89.152 +// return;
89.153 +// }
89.154 +// }
89.155
89.156 UI.openRefactoringUI(ui, activetc);
89.157 } else {
89.158 @@ -328,10 +327,10 @@
89.159 }
89.160 }
89.161
89.162 - protected abstract RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, int startOffset, int endOffset, CompilationInfo info);
89.163 + protected abstract RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, int startOffset, int endOffset, PythonParserResult info);
89.164 }
89.165
89.166 - public static abstract class NodeToElementTask implements Runnable, CancellableTask<CompilationController> {
89.167 + public static abstract class NodeToElementTask extends UserTask implements Runnable {
89.168 private Node node;
89.169 private RefactoringUI ui;
89.170
89.171 @@ -343,38 +342,35 @@
89.172 public void cancel() {
89.173 }
89.174
89.175 - public void run(CompilationController info) throws Exception {
89.176 - info.toPhase(Phase.ELEMENTS_RESOLVED);
89.177 - PythonTree root = PythonAstUtils.getRoot(info);
89.178 + public void run(ResultIterator info) throws Exception {
89.179 + PythonTree root = PythonAstUtils.getRoot((ParserResult) info.getParserResult());
89.180 if (root != null) {
89.181 - Element element = AstElement.create(info, root);
89.182 - PythonElementCtx fileCtx = new PythonElementCtx(root, root, element, info.getFileObject(), info);
89.183 - ui = createRefactoringUI(fileCtx, info);
89.184 + Element element = AstElement.create((PythonParserResult) info.getParserResult(), root);
89.185 + PythonElementCtx fileCtx = new PythonElementCtx(root, root, element, info.getSnapshot().getSource().getFileObject(), (PythonParserResult) info.getParserResult());
89.186 + ui = createRefactoringUI(fileCtx, (PythonParserResult) info.getParserResult());
89.187 }
89.188 }
89.189
89.190 public final void run() {
89.191 DataObject o = node.getCookie(DataObject.class);
89.192 - Source source = PythonRefUtils.getSource(o.getPrimaryFile());
89.193 + Source source = Source.create(o.getPrimaryFile());
89.194 assert source != null;
89.195 try {
89.196 - source.runUserActionTask(this, false);
89.197 - } catch (IllegalArgumentException ex) {
89.198 - ex.printStackTrace();
89.199 - } catch (IOException ex) {
89.200 + ParserManager.parse(Collections.singleton(source), this);
89.201 + } catch (ParseException ex) {
89.202 ex.printStackTrace();
89.203 }
89.204 UI.openRefactoringUI(ui);
89.205 }
89.206
89.207 - protected abstract RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, CompilationInfo info);
89.208 + protected abstract RefactoringUI createRefactoringUI(PythonElementCtx selectedElement, PythonParserResult info);
89.209 }
89.210
89.211 - public static abstract class NodeToFileObjectTask implements Runnable, CancellableTask<CompilationController> {
89.212 + public static abstract class NodeToFileObjectTask extends UserTask implements Runnable {
89.213 private Collection<? extends Node> nodes;
89.214 private RefactoringUI ui;
89.215 public NonRecursiveFolder pkg[];
89.216 - public WeakReference<CompilationInfo> cinfo;
89.217 + public WeakReference<ResultIterator> cinfo;
89.218 Collection<PythonElementCtx> handles = new ArrayList<PythonElementCtx>();
89.219
89.220 public NodeToFileObjectTask(Collection<? extends Node> nodes) {
89.221 @@ -384,13 +380,12 @@
89.222 public void cancel() {
89.223 }
89.224
89.225 - public void run(CompilationController info) throws Exception {
89.226 - info.toPhase(Phase.ELEMENTS_RESOLVED);
89.227 - PythonTree root = PythonAstUtils.getRoot(info);
89.228 + public void run(ResultIterator info) throws Exception {
89.229 + PythonTree root = PythonAstUtils.getRoot((ParserResult) info.getParserResult());
89.230 if (root != null) {
89.231 - PythonParserResult rpr = PythonAstUtils.getParseResult(info);
89.232 + PythonParserResult rpr = PythonAstUtils.getParseResult((ParserResult) info.getParserResult());
89.233 if (rpr != null) {
89.234 - AnalysisResult ar = rpr.getStructure();
89.235 + AnalysisResult ar = PythonStructureScanner.analyze(rpr);
89.236 List<? extends AstElement> els = ar.getElements();
89.237 if (els.size() > 0) {
89.238 // TODO - try to find the outermost or most "relevant" module/class in the file?
89.239 @@ -398,14 +393,14 @@
89.240 // It's not as simple in Python.
89.241 AstElement element = els.get(0);
89.242 PythonTree node = element.getNode();
89.243 - PythonElementCtx representedObject = new PythonElementCtx(root, node, element, info.getFileObject(), info);
89.244 + PythonElementCtx representedObject = new PythonElementCtx(root, node, element, info.getParserResult().getSnapshot().getSource().getFileObject(), (PythonParserResult) info.getParserResult());
89.245 //representedObject.setNames(element.getFqn(), element.getName());
89.246 representedObject.setNames(element.getIn() + "." + element.getName(), element.getName());
89.247 handles.add(representedObject);
89.248 }
89.249 }
89.250 }
89.251 - cinfo = new WeakReference<CompilationInfo>(info);
89.252 + cinfo = new WeakReference<ResultIterator>(info);
89.253 }
89.254
89.255 public void run() {
89.256 @@ -416,16 +411,14 @@
89.257 DataObject dob = node.getCookie(DataObject.class);
89.258 if (dob != null) {
89.259 fobs[i] = dob.getPrimaryFile();
89.260 - Source source = PythonRefUtils.getSource(fobs[i]);
89.261 + Source source = Source.create(fobs[i]);
89.262 if (source == null) {
89.263 continue;
89.264 }
89.265 assert source != null;
89.266 try {
89.267 - source.runUserActionTask(this, false);
89.268 - } catch (IllegalArgumentException ex) {
89.269 - ex.printStackTrace();
89.270 - } catch (IOException ex) {
89.271 + ParserManager.parse(Collections.singleton(source), this);
89.272 + } catch (ParseException ex) {
89.273 ex.printStackTrace();
89.274 }
89.275
90.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/RenameRefactoringUI.java Sun Jan 04 13:11:53 2015 -0600
90.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/RenameRefactoringUI.java Sun Feb 01 15:02:07 2015 -0800
90.3 @@ -47,9 +47,7 @@
90.4 import java.text.MessageFormat;
90.5 import javax.swing.event.ChangeListener;
90.6 import org.netbeans.api.fileinfo.NonRecursiveFolder;
90.7 -import org.netbeans.modules.gsf.api.ElementKind;
90.8 -import org.netbeans.napi.gsfret.source.ClasspathInfo;
90.9 -import org.netbeans.napi.gsfret.source.CompilationInfo;
90.10 +import org.netbeans.modules.csl.api.ElementKind;
90.11 import org.netbeans.modules.refactoring.api.AbstractRefactoring;
90.12 import org.netbeans.modules.refactoring.api.RenameRefactoring;
90.13 import org.netbeans.modules.python.editor.refactoring.PythonRefUtils;
90.14 @@ -85,17 +83,17 @@
90.15 private boolean pkgRename = true;
90.16 private String stripPrefix;
90.17
90.18 - public RenameRefactoringUI(PythonElementCtx handle, CompilationInfo info) {
90.19 + public RenameRefactoringUI(PythonElementCtx handle) {
90.20 this.jmiObject = handle;
90.21 stripPrefix = handle.getStripPrefix();
90.22 this.refactoring = new RenameRefactoring(Lookups.singleton(handle));
90.23 //oldName = handle.resolveElement(info).getSimpleName().toString();
90.24 oldName = handle.getSimpleName();
90.25
90.26 - ClasspathInfo classpath = PythonRefUtils.getClasspathInfoFor(handle);
90.27 - if (classpath != null) {
90.28 - refactoring.getContext().add(classpath);
90.29 - }
90.30 +// ClasspathInfo classpath = PythonRefUtils.getClasspathInfoFor(handle);
90.31 +// if (classpath != null) {
90.32 +// refactoring.getContext().add(classpath);
90.33 +// }
90.34
90.35 dispOldName = oldName;
90.36
90.37 @@ -105,7 +103,7 @@
90.38 this.refactoring.getContext().add(UI.Constants.REQUEST_PREVIEW);
90.39 }
90.40
90.41 - public RenameRefactoringUI(FileObject file, PythonElementCtx handle, CompilationInfo info) {
90.42 + public RenameRefactoringUI(FileObject file, PythonElementCtx handle) {
90.43 if (handle != null) {
90.44 jmiObject = handle;
90.45 this.refactoring = new RenameRefactoring(Lookups.fixed(file, handle));
90.46 @@ -116,10 +114,10 @@
90.47 oldName = file.getName();
90.48 }
90.49 dispOldName = oldName;
90.50 - ClasspathInfo cpInfo = handle == null ? PythonRefUtils.getClasspathInfoFor(file) : PythonRefUtils.getClasspathInfoFor(handle);
90.51 - if (cpInfo != null) {
90.52 - refactoring.getContext().add(cpInfo);
90.53 - }
90.54 +// ClasspathInfo cpInfo = handle == null ? PythonRefUtils.getClasspathInfoFor(file) : PythonRefUtils.getClasspathInfoFor(handle);
90.55 +// if (cpInfo != null) {
90.56 +// refactoring.getContext().add(cpInfo);
90.57 +// }
90.58 //this(jmiObject, (FileObject) null, true);
90.59
90.60 // Force refresh!
90.61 @@ -129,10 +127,10 @@
90.62 public RenameRefactoringUI(NonRecursiveFolder file) {
90.63 this.refactoring = new RenameRefactoring(Lookups.singleton(file));
90.64 oldName = PythonRefUtils.getPackageName(file.getFolder());
90.65 - ClasspathInfo classpath = PythonRefUtils.getClasspathInfoFor(file.getFolder());
90.66 - if (classpath != null) {
90.67 - refactoring.getContext().add(classpath);
90.68 - }
90.69 +// ClasspathInfo classpath = PythonRefUtils.getClasspathInfoFor(file.getFolder());
90.70 +// if (classpath != null) {
90.71 +// refactoring.getContext().add(classpath);
90.72 +// }
90.73 dispOldName = oldName;
90.74 pkgRename = true;
90.75 //this(jmiObject, (FileObject) null, true);
90.76 @@ -141,7 +139,7 @@
90.77 this.refactoring.getContext().add(UI.Constants.REQUEST_PREVIEW);
90.78 }
90.79
90.80 - RenameRefactoringUI(FileObject jmiObject, String newName, PythonElementCtx handle, CompilationInfo info) {
90.81 + RenameRefactoringUI(FileObject jmiObject, String newName, PythonElementCtx handle) {
90.82 if (handle != null) {
90.83 this.refactoring = new RenameRefactoring(Lookups.fixed(jmiObject, handle));
90.84 } else {
90.85 @@ -151,10 +149,10 @@
90.86 oldName = newName;
90.87 //[FIXME] this should be oldName of refactored object
90.88 this.dispOldName = newName;
90.89 - ClasspathInfo cpInfo = handle == null ? PythonRefUtils.getClasspathInfoFor(jmiObject) : PythonRefUtils.getClasspathInfoFor(handle);
90.90 - if (cpInfo != null) {
90.91 - refactoring.getContext().add(cpInfo);
90.92 - }
90.93 +// ClasspathInfo cpInfo = handle == null ? PythonRefUtils.getClasspathInfoFor(jmiObject) : PythonRefUtils.getClasspathInfoFor(handle);
90.94 +// if (cpInfo != null) {
90.95 +// refactoring.getContext().add(cpInfo);
90.96 +// }
90.97 fromListener = true;
90.98
90.99 // Force refresh!
90.100 @@ -163,10 +161,10 @@
90.101
90.102 RenameRefactoringUI(NonRecursiveFolder jmiObject, String newName) {
90.103 this.refactoring = new RenameRefactoring(Lookups.singleton(jmiObject));
90.104 - ClasspathInfo classpath = PythonRefUtils.getClasspathInfoFor(jmiObject.getFolder());
90.105 - if (classpath != null) {
90.106 - refactoring.getContext().add(classpath);
90.107 - }
90.108 +// ClasspathInfo classpath = PythonRefUtils.getClasspathInfoFor(jmiObject.getFolder());
90.109 +// if (classpath != null) {
90.110 +// refactoring.getContext().add(classpath);
90.111 +// }
90.112 //this.jmiObject = jmiObject;
90.113 oldName = newName;
90.114 //[FIXME] this should be oldName of refactored object
91.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/WhereUsedPanel.form Sun Jan 04 13:11:53 2015 -0600
91.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/WhereUsedPanel.form Sun Feb 01 15:02:07 2015 -0800
91.3 @@ -1,12 +1,14 @@
91.4 <?xml version="1.0" encoding="UTF-8" ?>
91.5
91.6 -<Form version="1.2" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
91.7 +<Form version="1.2" maxVersion="1.2" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
91.8 <NonVisualComponents>
91.9 <Component class="javax.swing.ButtonGroup" name="buttonGroup">
91.10 </Component>
91.11 </NonVisualComponents>
91.12 <AuxValues>
91.13 <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
91.14 + <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
91.15 + <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
91.16 <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
91.17 <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
91.18 <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
92.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/WhereUsedPanel.java Sun Jan 04 13:11:53 2015 -0600
92.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/WhereUsedPanel.java Sun Feb 01 15:02:07 2015 -0800
92.3 @@ -48,6 +48,7 @@
92.4 import java.awt.Dimension;
92.5 import java.awt.event.ItemEvent;
92.6 import java.io.IOException;
92.7 +import java.util.Collections;
92.8 import java.util.HashSet;
92.9 import java.util.Set;
92.10 import javax.swing.SwingUtilities;
92.11 @@ -58,13 +59,15 @@
92.12 import org.openide.util.NbBundle;
92.13 import org.netbeans.modules.python.editor.refactoring.RefactoringModule;
92.14 import javax.swing.JPanel;
92.15 -import org.netbeans.modules.gsf.api.CancellableTask;
92.16 -import org.netbeans.modules.gsf.api.ElementKind;
92.17 -import org.netbeans.modules.gsf.api.Modifier;
92.18 -import org.netbeans.napi.gsfret.source.CompilationController;
92.19 -import org.netbeans.napi.gsfret.source.Phase;
92.20 -import org.netbeans.napi.gsfret.source.Source;
92.21 +import org.netbeans.modules.csl.api.ElementKind;
92.22 +import org.netbeans.modules.csl.api.Modifier;
92.23 +import org.netbeans.modules.parsing.api.ParserManager;
92.24 +import org.netbeans.modules.parsing.api.ResultIterator;
92.25 +import org.netbeans.modules.parsing.api.Source;
92.26 +import org.netbeans.modules.parsing.api.UserTask;
92.27 +import org.netbeans.modules.parsing.spi.ParseException;
92.28 import org.netbeans.modules.python.editor.refactoring.PythonElementCtx;
92.29 +import org.openide.util.Exceptions;
92.30
92.31 /**
92.32 * Based on the WhereUsedPanel in Java refactoring by Jan Becicka.
92.33 @@ -95,11 +98,8 @@
92.34 if (initialized) {
92.35 return;
92.36 }
92.37 - Source source = PythonRefUtils.getSource(element.getFileObject());
92.38 - CancellableTask<CompilationController> task = new CancellableTask<CompilationController>() {
92.39 - public void cancel() {
92.40 - throw new UnsupportedOperationException("Not supported yet.");
92.41 - }
92.42 + Source source = Source.create(element.getFileObject());
92.43 + UserTask task = new UserTask() {
92.44
92.45 // TODO - handle methods in modules!!!!
92.46 private String getClassName(PythonElementCtx element) {
92.47 @@ -109,8 +109,7 @@
92.48 /**
92.49 * @todo For method calls, try to figure out the call type with the type analyzer
92.50 */
92.51 - public void run(CompilationController info) throws Exception {
92.52 - info.toPhase(Phase.RESOLVED);
92.53 + public void run(ResultIterator iter) throws Exception {
92.54 String m_isBaseClassText = null;
92.55 final String labelText;
92.56 Set<Modifier> modif = new HashSet<Modifier>();
92.57 @@ -192,9 +191,9 @@
92.58 }
92.59 };
92.60 try {
92.61 - source.runUserActionTask(task, true);
92.62 - } catch (IOException ioe) {
92.63 - throw (RuntimeException)new RuntimeException().initCause(ioe);
92.64 + ParserManager.parse(Collections.singleton(source), task);
92.65 + } catch (ParseException ex) {
92.66 + Exceptions.printStackTrace(ex);
92.67 }
92.68 initialized = true;
92.69 }
93.1 --- a/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/WhereUsedQueryUI.java Sun Jan 04 13:11:53 2015 -0600
93.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/refactoring/ui/WhereUsedQueryUI.java Sun Feb 01 15:02:07 2015 -0800
93.3 @@ -46,8 +46,7 @@
93.4 import java.text.MessageFormat;
93.5 import java.util.ResourceBundle;
93.6 import javax.swing.event.ChangeListener;
93.7 -import org.netbeans.modules.gsf.api.ElementKind;
93.8 -import org.netbeans.napi.gsfret.source.CompilationInfo;
93.9 +import org.netbeans.modules.csl.api.ElementKind;
93.10 import org.netbeans.modules.refactoring.api.AbstractRefactoring;
93.11 import org.netbeans.modules.refactoring.api.WhereUsedQuery;
93.12 import org.netbeans.modules.python.editor.refactoring.PythonRefUtils;
93.13 @@ -55,7 +54,6 @@
93.14 import org.netbeans.modules.python.editor.refactoring.WhereUsedQueryConstants;
93.15 import org.netbeans.modules.refactoring.spi.ui.CustomRefactoringPanel;
93.16 import org.netbeans.modules.refactoring.spi.ui.RefactoringUI;
93.17 -import org.netbeans.napi.gsfret.source.ClasspathInfo;
93.18 import org.openide.util.HelpCtx;
93.19 import org.openide.util.NbBundle;
93.20 import org.openide.util.lookup.Lookups;
93.21 @@ -73,12 +71,12 @@
93.22 private ElementKind kind;
93.23 private AbstractRefactoring delegate;
93.24
93.25 - public WhereUsedQueryUI(PythonElementCtx jmiObject, CompilationInfo info) {
93.26 + public WhereUsedQueryUI(PythonElementCtx jmiObject) {
93.27 this.query = new WhereUsedQuery(Lookups.singleton(jmiObject));
93.28 - ClasspathInfo classpathInfoFor = PythonRefUtils.getClasspathInfoFor(jmiObject);
93.29 - if (classpathInfoFor != null) {
93.30 - this.query.getContext().add(classpathInfoFor);
93.31 - }
93.32 +// ClasspathInfo classpathInfoFor = PythonRefUtils.getClasspathInfoFor(jmiObject);
93.33 +// if (classpathInfoFor != null) {
93.34 +// this.query.getContext().add(classpathInfoFor);
93.35 +// }
93.36 this.element = jmiObject;
93.37 name = jmiObject.getName();
93.38 kind = jmiObject.getKind();
94.1 --- a/python.editor/src/org/netbeans/modules/python/editor/scopes/SymbolTable.java Sun Jan 04 13:11:53 2015 -0600
94.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/scopes/SymbolTable.java Sun Feb 01 15:02:07 2015 -0800
94.3 @@ -48,17 +48,16 @@
94.4 import java.util.List;
94.5 import java.util.Map;
94.6 import java.util.Set;
94.7 -import org.netbeans.modules.gsf.api.CompilationInfo;
94.8 -import org.netbeans.modules.gsf.api.ElementKind;
94.9 -import org.netbeans.modules.gsf.api.Error;
94.10 -import org.netbeans.modules.gsf.api.Index;
94.11 -import org.netbeans.modules.gsf.api.NameKind;
94.12 -import org.netbeans.modules.gsf.api.OffsetRange;
94.13 -import org.netbeans.modules.gsf.api.Severity;
94.14 -import org.netbeans.modules.gsf.spi.DefaultError;
94.15 +import org.netbeans.modules.csl.api.ElementKind;
94.16 +import org.netbeans.modules.csl.api.OffsetRange;
94.17 +import org.netbeans.modules.csl.api.Severity;
94.18 +import org.netbeans.modules.csl.api.Error;
94.19 +import org.netbeans.modules.csl.spi.DefaultError;
94.20 +import org.netbeans.modules.parsing.spi.indexing.support.QuerySupport;
94.21 import org.netbeans.modules.python.editor.PythonAstUtils;
94.22 import org.netbeans.modules.python.editor.PythonIndex;
94.23 import org.netbeans.modules.python.editor.PythonIndexer;
94.24 +import org.netbeans.modules.python.editor.PythonParserResult;
94.25 import org.netbeans.modules.python.editor.PythonUtils;
94.26 import org.netbeans.modules.python.editor.elements.AstElement;
94.27 import org.netbeans.modules.python.editor.elements.Element;
94.28 @@ -325,41 +324,39 @@
94.29 return modules;
94.30 }
94.31
94.32 - private void addSymbolsFromModule(CompilationInfo info, String module, String prefix, NameKind kind, Set<? super IndexedElement> result) {
94.33 + private void addSymbolsFromModule(PythonParserResult info, String module, String prefix, QuerySupport.Kind kind, Set<? super IndexedElement> result) {
94.34 if (PythonIndex.isBuiltinModule(module)) {
94.35 Set<IndexedElement> all = getAllSymbolsFromModule(info, module);
94.36 for (IndexedElement e : all) {
94.37 - if (kind == NameKind.PREFIX) {
94.38 + if (kind == QuerySupport.Kind.PREFIX) {
94.39 if (e.getName().startsWith(prefix)) {
94.40 result.add(e);
94.41 }
94.42 - } else if (kind == NameKind.EXACT_NAME) {
94.43 + } else if (kind == QuerySupport.Kind.EXACT) {
94.44 if (prefix.equals(e.getName())) {
94.45 result.add(e);
94.46 }
94.47 - } else if (kind == NameKind.CASE_INSENSITIVE_PREFIX) {
94.48 + } else if (kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX) {
94.49 if (e.getName().regionMatches(true, 0, prefix, 0, prefix.length())) {
94.50 result.add(e);
94.51 }
94.52 }
94.53 }
94.54 } else {
94.55 - Index gsfIndex = info.getIndex(PythonTokenId.PYTHON_MIME_TYPE);
94.56 - PythonIndex index = PythonIndex.get(gsfIndex, info.getFileObject());
94.57 - Set<IndexedElement> elements = index.getImportedElements(prefix, kind, PythonIndex.ALL_SCOPE, Collections.singleton(module), null);
94.58 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
94.59 + Set<IndexedElement> elements = index.getImportedElements(prefix, kind, Collections.singleton(module), null);
94.60 for (IndexedElement e : elements) {
94.61 result.add(e);
94.62 }
94.63 }
94.64 }
94.65
94.66 - private Set<IndexedElement> getAllSymbolsFromModule(CompilationInfo info, String module) {
94.67 + private Set<IndexedElement> getAllSymbolsFromModule(PythonParserResult info, String module) {
94.68 Set<IndexedElement> elements = importedElements.get(module);
94.69 if (elements == null) {
94.70 - Index gsfIndex = info.getIndex(PythonTokenId.PYTHON_MIME_TYPE);
94.71 - PythonIndex index = PythonIndex.get(gsfIndex, info.getFileObject());
94.72 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
94.73 Set<String> systemHolder = new HashSet<String>(3);
94.74 - elements = index.getImportedElements("", NameKind.PREFIX, PythonIndex.ALL_SCOPE, Collections.singleton(module), systemHolder);
94.75 + elements = index.getImportedElements("", QuerySupport.Kind.PREFIX, Collections.singleton(module), systemHolder);
94.76 // Cache system modules - don't cache local modules
94.77 if (!systemHolder.isEmpty()) {
94.78 importedElements.put(module, elements);
94.79 @@ -369,16 +366,11 @@
94.80 return elements;
94.81 }
94.82
94.83 - public Set<Element> getDefinedElements(CompilationInfo info, PythonTree scope, String prefix, NameKind kind) {
94.84 + public Set<Element> getDefinedElements(PythonParserResult info, PythonTree scope, String prefix, QuerySupport.Kind kind) {
94.85 Set<Element> elements = new HashSet<Element>(300);
94.86 ScopeInfo scopeInfo = scopes.get(scope);
94.87 - String module = PythonUtils.getModuleName(fileObject, null);
94.88 - String url = null;
94.89 - try {
94.90 - url = fileObject.getURL().toExternalForm();
94.91 - } catch (FileStateInvalidException ex) {
94.92 - Exceptions.printStackTrace(ex);
94.93 - }
94.94 + String module = PythonUtils.getModuleName(fileObject);
94.95 + String url = fileObject.toURL().toExternalForm();
94.96
94.97 // Get builtin symbols
94.98 for (String mod : getModulesToStarImport()) {
94.99 @@ -401,15 +393,15 @@
94.100 // Something in narrower scope already processed this one
94.101 continue;
94.102 }
94.103 - if (kind == NameKind.EXACT_NAME) {
94.104 + if (kind == QuerySupport.Kind.EXACT) {
94.105 if (!(name.equals(prefix))) {
94.106 continue;
94.107 }
94.108 - } else if (kind == NameKind.PREFIX) {
94.109 + } else if (kind == QuerySupport.Kind.PREFIX) {
94.110 if (!name.startsWith(prefix)) {
94.111 continue;
94.112 }
94.113 - } else if (kind == NameKind.CASE_INSENSITIVE_PREFIX) {
94.114 + } else if (kind == QuerySupport.Kind.CASE_INSENSITIVE_PREFIX) {
94.115 if (!name.regionMatches(true, 0, prefix, 0, prefix.length())) {
94.116 continue;
94.117 }
94.118 @@ -782,7 +774,7 @@
94.119 }
94.120 }
94.121
94.122 - public Map<String, SymInfo> getUnresolvedNames(CompilationInfo info) {
94.123 + public Map<String, SymInfo> getUnresolvedNames(PythonParserResult info) {
94.124 Map<String, SymInfo> unresolved = new HashMap<String, SymInfo>();
94.125 Set<String> builtin = getBuiltin(info);
94.126
94.127 @@ -821,7 +813,7 @@
94.128 return unresolved;
94.129 }
94.130
94.131 - public List<Attribute> getNotInInitAttributes(CompilationInfo info) {
94.132 + public List<Attribute> getNotInInitAttributes(PythonParserResult info) {
94.133 List<Attribute> notInInitAttribs = new ArrayList<Attribute>();
94.134 for (ScopeInfo scopeInfo : scopes.values()) {
94.135 if (scopeInfo.scope_node instanceof ClassDef) {
94.136 @@ -932,11 +924,10 @@
94.137 return false;
94.138 }
94.139
94.140 - public List<PythonTree> getUnresolvedParents(CompilationInfo info) {
94.141 + public List<PythonTree> getUnresolvedParents(PythonParserResult info) {
94.142 // deal with unresolved parents in inherit trees
94.143 List<PythonTree> unresolvedParents = new ArrayList<PythonTree>();
94.144 - Index gsfIndex = info.getIndex(PythonTokenId.PYTHON_MIME_TYPE);
94.145 - PythonIndex index = PythonIndex.get(gsfIndex, info.getFileObject());
94.146 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
94.147
94.148 for (String cur : classes.keySet()) {
94.149 ClassDef cls = classes.get(cur);
94.150 @@ -965,7 +956,7 @@
94.151 if (!isImported(moduleName)) {
94.152 unresolvedParents.add(base);
94.153 } else {
94.154 - Set<IndexedElement> found = index.getImportedElements(clsName, NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, Collections.<String>singleton(moduleName), null);
94.155 + Set<IndexedElement> found = index.getImportedElements(clsName, QuerySupport.Kind.EXACT, Collections.<String>singleton(moduleName), null);
94.156 if (found.size() == 0) {
94.157 unresolvedParents.add(base);
94.158 }
94.159 @@ -980,7 +971,7 @@
94.160 return unresolvedParents;
94.161 }
94.162
94.163 - public HashMap<ClassDef, String> getClassesCyclingRedundancies(CompilationInfo info) {
94.164 + public HashMap<ClassDef, String> getClassesCyclingRedundancies(PythonParserResult info) {
94.165 HashMap<ClassDef, String> cyclingRedundancies = new HashMap<ClassDef, String>();
94.166 for (String cur : classes.keySet()) {
94.167 HashMap<String, String> returned = new HashMap<String, String>();
94.168 @@ -996,8 +987,7 @@
94.169 return cyclingRedundancies;
94.170 }
94.171
94.172 - @SuppressWarnings("unchecked")
94.173 - public List<PythonTree> getUnresolvedAttributes(CompilationInfo info) {
94.174 + public List<PythonTree> getUnresolvedAttributes(PythonParserResult info) {
94.175 List<PythonTree> unresolvedNodes = new ArrayList<PythonTree>();
94.176 for (ScopeInfo scopeInfo : scopes.values()) {
94.177 Set<String> unresolved = new HashSet<String>();
94.178 @@ -1054,8 +1044,7 @@
94.179 return unresolvedNodes;
94.180 }
94.181
94.182 - @SuppressWarnings("unchecked")
94.183 - public List<PythonTree> getUnresolved(CompilationInfo info) {
94.184 + public List<PythonTree> getUnresolved(PythonParserResult info) {
94.185 List<PythonTree> unresolvedNodes = new ArrayList<PythonTree>();
94.186 Set<String> builtin = getBuiltin(info);
94.187
94.188 @@ -1094,8 +1083,7 @@
94.189
94.190 if (unresolved.size() > 0) {
94.191 // Check imports and see if it's resolved by existing imports
94.192 - Index gsfIndex = info.getIndex(PythonTokenId.PYTHON_MIME_TYPE);
94.193 - PythonIndex index = PythonIndex.get(gsfIndex, info.getFileObject());
94.194 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
94.195 // TODO - cache system libraries!
94.196 // TODO - make method which doesn't create elements for these guys!
94.197 // Set<IndexedElement> elements = index.getImportedElements("", NameKind.PREFIX, PythonIndex.ALL_SCOPE, imports, importsFrom);
94.198 @@ -1121,7 +1109,6 @@
94.199 return unresolvedNodes;
94.200 }
94.201
94.202 - @SuppressWarnings("unchecked")
94.203 public List<PythonTree> getUnused(boolean skipSelf, boolean skipParams) { // not used for unused imports, see separate method
94.204 List<PythonTree> unusedNodes = new ArrayList<PythonTree>();
94.205
94.206 @@ -1207,10 +1194,9 @@
94.207 }
94.208 private static Set<String> builtinSymbols;
94.209
94.210 - private Set<String> getBuiltin(CompilationInfo info) {
94.211 + private Set<String> getBuiltin(PythonParserResult info) {
94.212 if (builtinSymbols == null) {
94.213 - Index gsfIndex = info.getIndex(PythonTokenId.PYTHON_MIME_TYPE);
94.214 - PythonIndex index = PythonIndex.get(gsfIndex, info.getFileObject());
94.215 + PythonIndex index = PythonIndex.get(info.getSnapshot().getSource().getFileObject());
94.216 builtinSymbols = index.getBuiltinSymbols();
94.217 }
94.218
95.1 --- a/python.editor/src/org/netbeans/modules/python/editor/templates/module.py.ftl Sun Jan 04 13:11:53 2015 -0600
95.2 +++ b/python.editor/src/org/netbeans/modules/python/editor/templates/module.py.ftl Sun Feb 01 15:02:07 2015 -0800
95.3 @@ -9,4 +9,8 @@
95.4 __date__ ="$${date} ${time}$"
95.5
95.6 if __name__ == "__main__":
95.7 +<#if python3style?? && python3style>
95.8 + print("Hello World")
95.9 +<#else>
95.10 print "Hello World"
95.11 +</#if>
96.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py Sun Jan 04 13:11:53 2015 -0600
96.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
96.3 @@ -1,615 +0,0 @@
96.4 -"""Configuration file parser.
96.5 -
96.6 -A setup file consists of sections, lead by a "[section]" header,
96.7 -and followed by "name: value" entries, with continuations and such in
96.8 -the style of RFC 822.
96.9 -
96.10 - the same section, or values in a special [DEFAULT] section.
96.11 -
96.12 -For example:
96.13 -
96.14 - something: %(dir)s/whatever
96.15 -
96.16 -would resolve the "%(dir)s" to the value of dir. All reference
96.17 -expansions are done late, on demand.
96.18 -
96.19 -Intrinsic defaults can be specified by passing them into the
96.20 -ConfigParser constructor as a dictionary.
96.21 -
96.22 -class:
96.23 -
96.24 -ConfigParser -- responsible for parsing a list of
96.25 - configuration files, and managing the parsed database.
96.26 -
96.27 - methods:
96.28 -
96.29 - __init__(defaults=None)
96.30 - create the parser and specify a dictionary of intrinsic defaults. The
96.31 - keys must be strings, the values must be appropriate for %()s string
96.32 - interpolation. Note that `__name__' is always an intrinsic default;
96.33 - it's value is the section's name.
96.34 -
96.35 - sections()
96.36 - return all the configuration section names, sans DEFAULT
96.37 -
96.38 - has_section(section)
96.39 - return whether the given section exists
96.40 -
96.41 - has_option(section, option)
96.42 - return whether the given option exists in the given section
96.43 -
96.44 - options(section)
96.45 - return list of configuration options for the named section
96.46 -
96.47 - read(filenames)
96.48 - read and parse the list of named configuration files, given by
96.49 - name. A single filename is also allowed. Non-existing files
96.50 - are ignored.
96.51 -
96.52 - readfp(fp, filename=None)
96.53 - read and parse one configuration file, given as a file object.
96.54 - The filename defaults to fp.name; it is only used in error
96.55 - messages (if fp has no `name' attribute, the string `<???>' is used).
96.56 -
96.57 - get(section, option, raw=False, vars=None)
96.58 - return a string value for the named option. All % interpolations are
96.59 - expanded in the return values, based on the defaults passed into the
96.60 - constructor and the DEFAULT section. Additional substitutions may be
96.61 - provided using the `vars' argument, which must be a dictionary whose
96.62 - contents override any pre-existing defaults.
96.63 -
96.64 - getint(section, options)
96.65 - like get(), but convert value to an integer
96.66 -
96.67 - getfloat(section, options)
96.68 - like get(), but convert value to a float
96.69 -
96.70 - getboolean(section, options)
96.71 - like get(), but convert value to a boolean (currently case
96.72 - insensitively defined as 0, false, no, off for False, and 1, true,
96.73 - yes, on for True). Returns False or True.
96.74 -
96.75 - items(section, raw=False, vars=None)
96.76 - return a list of tuples with (name, value) for each option
96.77 - in the section.
96.78 -
96.79 - remove_section(section)
96.80 - remove the given file section and all its options
96.81 -
96.82 - remove_option(section, option)
96.83 - remove the given option from the given section
96.84 -
96.85 - set(section, option, value)
96.86 - set the given option
96.87 -
96.88 - write(fp)
96.89 - write the configuration state in .ini format
96.90 -"""
96.91 -
96.92 -import re
96.93 -
96.94 -__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
96.95 - "InterpolationError", "InterpolationDepthError",
96.96 - "InterpolationSyntaxError", "ParsingError",
96.97 - "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser",
96.98 - "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
96.99 -
96.100 -DEFAULTSECT = "DEFAULT"
96.101 -
96.102 -MAX_INTERPOLATION_DEPTH = 10
96.103 -
96.104 -
96.105 -
96.106 -# exception classes
96.107 -class Error(Exception):
96.108 - """Base class for ConfigParser exceptions."""
96.109 -
96.110 - def __init__(self, msg=''):
96.111 - self.message = msg
96.112 - Exception.__init__(self, msg)
96.113 -
96.114 - def __repr__(self):
96.115 - return self.message
96.116 -
96.117 - __str__ = __repr__
96.118 -
96.119 -class NoSectionError(Error):
96.120 - """Rasssised when no section matches a requested option."""
96.121 -
96.122 - def __init__(self, section):
96.123 - Error.__init__(self, 'No section: ' + `section`)
96.124 - self.section = section
96.125 -
96.126 -class DuplicateSectionError(Error):
96.127 - """Raised when a section is multiply-created."""
96.128 -
96.129 - def __init__(self, section):
96.130 - Error.__init__(self, "Section %r already exists" % section)
96.131 - self.section = section
96.132 -
96.133 -class NoOptionError(Error):
96.134 - """A requested option was not found."""
96.135 -
96.136 - def __init__(self, option, section):
96.137 - Error.__init__(self, "No option %r in section: %r" %
96.138 - (option, section))
96.139 - self.option = option
96.140 - self.section = section
96.141 -
96.142 -class InterpolationError(Error):
96.143 - """Base class for interpolation-related exceptions."""
96.144 -
96.145 - def __init__(self, option, section, msg):
96.146 - Error.__init__(self, msg)
96.147 - self.option = option
96.148 - self.section = section
96.149 -
96.150 -class InterpolationMissingOptionError(InterpolationError):
96.151 - """A string substitution required a setting which was not available."""
96.152 -
96.153 - def __init__(self, option, section, rawval, reference):
96.154 - msg = ("Bad value substitution:\n"
96.155 - "\tsection: [%s]\n"
96.156 - "\toption : %s\n"
96.157 - "\tkey : %s\n"
96.158 - "\trawval : %s\n"
96.159 - % (section, option, reference, rawval))
96.160 - InterpolationError.__init__(self, option, section, msg)
96.161 - self.reference = reference
96.162 -
96.163 -class InterpolationSyntaxError(InterpolationError):
96.164 - """Raised when the source text into which substitutions are made
96.165 - does not conform to the required syntax."""
96.166 -
96.167 -class InterpolationDepthError(InterpolationError):
96.168 - """Raised when substitutions are nested too deeply."""
96.169 -
96.170 - def __init__(self, option, section, rawval):
96.171 - msg = ("Value interpolation too deeply recursive:\n"
96.172 - "\tsection: [%s]\n"
96.173 - "\toption : %s\n"
96.174 - "\trawval : %s\n"
96.175 - % (section, option, rawval))
96.176 - InterpolationError.__init__(self, option, section, msg)
96.177 -
96.178 -class ParsingError(Error):
96.179 - """Raised when a configuration file does not follow legal syntax."""
96.180 -
96.181 - def __init__(self, filename):
96.182 - Error.__init__(self, 'File contains parsing errors: %s' % filename)
96.183 - self.filename = filename
96.184 - self.errors = []
96.185 -
96.186 - def append(self, lineno, line):
96.187 - self.errors.append((lineno, line))
96.188 - self.message += '\n\t[line %2d]: %s' % (lineno, line)
96.189 -
96.190 -class MissingSectionHeaderError(ParsingError):
96.191 - """Raised when a key-value pair is found before any section header."""
96.192 -
96.193 - def __init__(self, filename, lineno, line):
96.194 - Error.__init__(
96.195 - self,
96.196 - 'File contains no section headers.\nfile: %s, line: %d\n%s' %
96.197 - (filename, lineno, line))
96.198 - self.filename = filename
96.199 - self.lineno = lineno
96.200 - self.line = line
96.201 -
96.202 -
96.203 -
96.204 -class RawConfigParser:
96.205 - def __init__(self, defaults=None):
96.206 - self._sections = {}
96.207 - if defaults is None:
96.208 - self._defaults = {}
96.209 - else:
96.210 - self._defaults = defaults
96.211 -
96.212 - def defaults(self):
96.213 - return self._defaults
96.214 -
96.215 - def sections(self):
96.216 - """Return a list of section names, excluding [DEFAULT]"""
96.217 - # self._sections will never have [DEFAULT] in it
96.218 - return self._sections.keys()
96.219 -
96.220 - def add_section(self, section):
96.221 - """Create a new section in the configuration.
96.222 -
96.223 - Raise DuplicateSectionError if a section by the specified name
96.224 - already exists.
96.225 - """
96.226 - if section in self._sections:
96.227 - raise DuplicateSectionError(section)
96.228 - self._sections[section] = {}
96.229 -
96.230 - def has_section(self, section):
96.231 - """Indicate whether the named section is present in the configuration.
96.232 -
96.233 - The DEFAULT section is not acknowledged.
96.234 - """
96.235 - return section in self._sections
96.236 -
96.237 - def options(self, section):
96.238 - """Return a list of option names for the given section name."""
96.239 - try:
96.240 - opts = self._sections[section].copy()
96.241 - except KeyError:
96.242 - raise NoSectionError(section)
96.243 - opts.update(self._defaults)
96.244 - if '__name__' in opts:
96.245 - del opts['__name__']
96.246 - return opts.keys()
96.247 -
96.248 - def read(self, filenames):
96.249 - """Read and parse a filename or a list of filenames.
96.250 -
96.251 - Files that cannot be opened are silently ignored; this is
96.252 - designed so that you can specify a list of potential
96.253 - configuration file locations (e.g. current directory, user's
96.254 - home directory, systemwide directory), and all existing
96.255 - configuration files in the list will be read. A single
96.256 - filename may also be given.
96.257 - """
96.258 - if isinstance(filenames, basestring):
96.259 - filenames = [filenames]
96.260 - for filename in filenames:
96.261 - try:
96.262 - fp = open(filename)
96.263 - except IOError:
96.264 - continue
96.265 - self._read(fp, filename)
96.266 - fp.close()
96.267 -
96.268 - def readfp(self, fp, filename=None):
96.269 - """Like read() but the argument must be a file-like object.
96.270 -
96.271 - The `fp' argument must have a `readline' method. Optional
96.272 - second argument is the `filename', which if not given, is
96.273 - taken from fp.name. If fp has no `name' attribute, `<???>' is
96.274 - used.
96.275 -
96.276 - """
96.277 - if filename is None:
96.278 - try:
96.279 - filename = fp.name
96.280 - except AttributeError:
96.281 - filename = '<???>'
96.282 - self._read(fp, filename)
96.283 -
96.284 - def get(self, section, option):
96.285 - opt = self.optionxform(option)
96.286 - if section not in self._sections:
96.287 - if section != DEFAULTSECT:
96.288 - raise NoSectionError(section)
96.289 - if opt in self._defaults:
96.290 - return self._defaults[opt]
96.291 - else:
96.292 - raise NoOptionError(option, section)
96.293 - elif opt in self._sections[section]:
96.294 - return self._sections[section][opt]
96.295 - elif opt in self._defaults:
96.296 - return self._defaults[opt]
96.297 - else:
96.298 - raise NoOptionError(option, section)
96.299 -
96.300 - def items(self, section):
96.301 - try:
96.302 - d2 = self._sections[section]
96.303 - except KeyError:
96.304 - if section != DEFAULTSECT:
96.305 - raise NoSectionError(section)
96.306 - d2 = {}
96.307 - d = self._defaults.copy()
96.308 - d.update(d2)
96.309 - if "__name__" in d:
96.310 - del d["__name__"]
96.311 - return d.items()
96.312 -
96.313 - def _get(self, section, conv, option):
96.314 - return conv(self.get(section, option))
96.315 -
96.316 - def getint(self, section, option):
96.317 - return self._get(section, int, option)
96.318 -
96.319 - def getfloat(self, section, option):
96.320 - return self._get(section, float, option)
96.321 -
96.322 - _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
96.323 - '0': False, 'no': False, 'false': False, 'off': False}
96.324 -
96.325 - def getboolean(self, section, option):
96.326 - v = self.get(section, option)
96.327 - if v.lower() not in self._boolean_states:
96.328 - raise ValueError, 'Not a boolean: %s' % v
96.329 - return self._boolean_states[v.lower()]
96.330 -
96.331 - def optionxform(self, optionstr):
96.332 - return optionstr.lower()
96.333 -
96.334 - def has_option(self, section, option):
96.335 - """Check for the existence of a given option in a given section."""
96.336 - if not section or section == DEFAULTSECT:
96.337 - option = self.optionxform(option)
96.338 - return option in self._defaults
96.339 - elif section not in self._sections:
96.340 - return False
96.341 - else:
96.342 - option = self.optionxform(option)
96.343 - return (option in self._sections[section]
96.344 - or option in self._defaults)
96.345 -
96.346 - def set(self, section, option, value):
96.347 - """Set an option."""
96.348 - if not section or section == DEFAULTSECT:
96.349 - sectdict = self._defaults
96.350 - else:
96.351 - try:
96.352 - sectdict = self._sections[section]
96.353 - except KeyError:
96.354 - raise NoSectionError(section)
96.355 - sectdict[self.optionxform(option)] = value
96.356 -
96.357 - def write(self, fp):
96.358 - """Write an .ini-format representation of the configuration state."""
96.359 - if self._defaults:
96.360 - fp.write("[%s]\n" % DEFAULTSECT)
96.361 - for (key, value) in self._defaults.items():
96.362 - fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
96.363 - fp.write("\n")
96.364 - for section in self._sections:
96.365 - fp.write("[%s]\n" % section)
96.366 - for (key, value) in self._sections[section].items():
96.367 - if key != "__name__":
96.368 - fp.write("%s = %s\n" %
96.369 - (key, str(value).replace('\n', '\n\t')))
96.370 - fp.write("\n")
96.371 -
96.372 - def remove_option(self, section, option):
96.373 - """Remove an option."""
96.374 - if not section or section == DEFAULTSECT:
96.375 - sectdict = self._defaults
96.376 - else:
96.377 - try:
96.378 - sectdict = self._sections[section]
96.379 - except KeyError:
96.380 - raise NoSectionError(section)
96.381 - option = self.optionxform(option)
96.382 - existed = option in sectdict
96.383 - if existed:
96.384 - del sectdict[option]
96.385 - return existed
96.386 -
96.387 - def remove_section(self, section):
96.388 - """Remove a file section."""
96.389 - existed = section in self._sections
96.390 - if existed:
96.391 - del self._sections[section]
96.392 - return existed
96.393 -
96.394 - #
96.395 - # Regular expressions for parsing section headers and options.
96.396 - #
96.397 - SECTCRE = re.compile(
96.398 - r'\[' # [
96.399 - r'(?P<header>[^]]+)' # very permissive!
96.400 - r'\]' # ]
96.401 - )
96.402 - OPTCRE = re.compile(
96.403 - r'(?P<option>[^:=\s][^:=]*)' # very permissive!
96.404 - r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
96.405 - # followed by separator
96.406 - # (either : or =), followed
96.407 - # by any # space/tab
96.408 - r'(?P<value>.*)$' # everything up to eol
96.409 - )
96.410 -
96.411 - def _read(self, fp, fpname):
96.412 - """Parse a sectioned setup file.
96.413 -
96.414 - The sections in setup file contains a title line at the top,
96.415 - indicated by a name in square brackets (`[]'), plus key/value
96.416 - options lines, indicated by `name: value' format lines.
96.417 - Continuations are represented by an embedded newline then
96.418 - leading whitespace. Blank lines, lines beginning with a '#',
96.419 - and just about everything else are ignored.
96.420 - """
96.421 - cursect = None # None, or a dictionary
96.422 - optname = None
96.423 - lineno = 0
96.424 - e = None # None, or an exception
96.425 - while True:
96.426 - line = fp.readline()
96.427 - if not line:
96.428 - break
96.429 - lineno = lineno + 1
96.430 - # comment or blank line?
96.431 - if line.strip() == '' or line[0] in '#;':
96.432 - continue
96.433 - if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
96.434 - # no leading whitespace
96.435 - continue
96.436 - # continuation line?
96.437 - if line[0].isspace() and cursect is not None and optname:
96.438 - value = line.strip()
96.439 - if value:
96.440 - cursect[optname] = "%s\n%s" % (cursect[optname], value)
96.441 - # a section header or option header?
96.442 - else:
96.443 - # is it a section header?
96.444 - mo = self.SECTCRE.match(line)
96.445 - if mo:
96.446 - sectname = mo.group('header')
96.447 - if sectname in self._sections:
96.448 - cursect = self._sections[sectname]
96.449 - elif sectname == DEFAULTSECT:
96.450 - cursect = self._defaults
96.451 - else:
96.452 - cursect = {'__name__': sectname}
96.453 - self._sections[sectname] = cursect
96.454 - # So sections can't start with a continuation line
96.455 - optname = None
96.456 - # no section header in the file?
96.457 - elif cursect is None:
96.458 - raise MissingSectionHeaderError(fpname, lineno, `line`)
96.459 - # an option line?
96.460 - else:
96.461 - mo = self.OPTCRE.match(line)
96.462 - if mo:
96.463 - optname, vi, optval = mo.group('option', 'vi', 'value')
96.464 - if vi in ('=', ':') and ';' in optval:
96.465 - # ';' is a comment delimiter only if it follows
96.466 - # a spacing character
96.467 - pos = optval.find(';')
96.468 - if pos != -1 and optval[pos-1].isspace():
96.469 - optval = optval[:pos]
96.470 - optval = optval.strip()
96.471 - # allow empty values
96.472 - if optval == '""':
96.473 - optval = ''
96.474 - optname = self.optionxform(optname.rstrip())
96.475 - cursect[optname] = optval
96.476 - else:
96.477 - # a non-fatal parsing error occurred. set up the
96.478 - # exception but keep going. the exception will be
96.479 - # raised at the end of the file and will contain a
96.480 - # list of all bogus lines
96.481 - if not e:
96.482 - e = ParsingError(fpname)
96.483 - e.append(lineno, `line`)
96.484 - # if any parsing errors occurred, raise an exception
96.485 - if e:
96.486 - raise e
96.487 -
96.488 -
96.489 -class ConfigParser(RawConfigParser):
96.490 -
96.491 - def get(self, section, option, raw=False, vars=None):
96.492 - """Get an option value for a given section.
96.493 -
96.494 - All % interpolations are expanded in the return values, based on the
96.495 - defaults passed into the constructor, unless the optional argument
96.496 - `raw' is true. Additional substitutions may be provided using the
96.497 - `vars' argument, which must be a dictionary whose contents overrides
96.498 - any pre-existing defaults.
96.499 -
96.500 - The section DEFAULT is special.
96.501 - """
96.502 - d = self._defaults.copy()
96.503 - try:
96.504 - d.update(self._sections[section])
96.505 - except KeyError:
96.506 - if section != DEFAULTSECT:
96.507 - raise NoSectionError(section)
96.508 - # Update with the entry specific variables
96.509 - if vars is not None:
96.510 - d.update(vars)
96.511 - option = self.optionxform(option)
96.512 - try:
96.513 - value = d[option]
96.514 - except KeyError:
96.515 - raise NoOptionError(option, section)
96.516 -
96.517 - if raw:
96.518 - return value
96.519 - else:
96.520 - return self._interpolate(section, option, value, d)
96.521 -
96.522 - def items(self, section, raw=False, vars=None):
96.523 - """Return a list of tuples with (name, value) for each option
96.524 - in the section.
96.525 -
96.526 - All % interpolations are expanded in the return values, based on the
96.527 - defaults passed into the constructor, unless the optional argument
96.528 - `raw' is true. Additional substitutions may be provided using the
96.529 - `vars' argument, which must be a dictionary whose contents overrides
96.530 - any pre-existing defaults.
96.531 -
96.532 - The section DEFAULT is special.
96.533 - """
96.534 - d = self._defaults.copy()
96.535 - try:
96.536 - d.update(self._sections[section])
96.537 - except KeyError:
96.538 - if section != DEFAULTSECT:
96.539 - raise NoSectionError(section)
96.540 - # Update with the entry specific variables
96.541 - if vars:
96.542 - d.update(vars)
96.543 - options = d.keys()
96.544 - if "__name__" in options:
96.545 - options.remove("__name__")
96.546 - if raw:
96.547 - return [(option, d[option])
96.548 - for option in options]
96.549 - else:
96.550 - return [(option, self._interpolate(section, option, d[option], d))
96.551 - for option in options]
96.552 -
96.553 - def _interpolate(self, section, option, rawval, vars):
96.554 - # do the string interpolation
96.555 - value = rawval
96.556 - depth = MAX_INTERPOLATION_DEPTH
96.557 - while depth: # Loop through this until it's done
96.558 - depth -= 1
96.559 - if value.find("%(") != -1:
96.560 - try:
96.561 - value = value % vars
96.562 - except KeyError, e:
96.563 - raise InterpolationMissingOptionError(
96.564 - option, section, rawval, e[0])
96.565 - else:
96.566 - break
96.567 - if value.find("%(") != -1:
96.568 - raise InterpolationDepthError(option, section, rawval)
96.569 - return value
96.570 -
96.571 -
96.572 -class SafeConfigParser(ConfigParser):
96.573 -
96.574 - def _interpolate(self, section, option, rawval, vars):
96.575 - # do the string interpolation
96.576 - L = []
96.577 - self._interpolate_some(option, L, rawval, section, vars, 1)
96.578 - return ''.join(L)
96.579 -
96.580 - _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
96.581 -
96.582 - def _interpolate_some(self, option, accum, rest, section, map, depth):
96.583 - if depth > MAX_INTERPOLATION_DEPTH:
96.584 - raise InterpolationDepthError(option, section, rest)
96.585 - while rest:
96.586 - p = rest.find("%")
96.587 - if p < 0:
96.588 - accum.append(rest)
96.589 - return
96.590 - if p > 0:
96.591 - accum.append(rest[:p])
96.592 - rest = rest[p:]
96.593 - # p is no longer used
96.594 - c = rest[1:2]
96.595 - if c == "%":
96.596 - accum.append("%")
96.597 - rest = rest[2:]
96.598 - elif c == "(":
96.599 - m = self._interpvar_match(rest)
96.600 - if m is None:
96.601 - raise InterpolationSyntaxError(option, section,
96.602 - "bad interpolation variable reference %r" % rest)
96.603 - var = m.group(1)
96.604 - rest = rest[m.end():]
96.605 - try:
96.606 - v = map[var]
96.607 - except KeyError:
96.608 - raise InterpolationMissingOptionError(
96.609 - option, section, rest, var)
96.610 - if "%" in v:
96.611 - self._interpolate_some(option, accum, v,
96.612 - section, map, depth + 1)
96.613 - else:
96.614 - accum.append(v)
96.615 - else:
96.616 - raise InterpolationSyntaxError(
96.617 - option, section,
96.618 - "'%' must be followed by '%' or '(', found: " + `ret`)
97.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.folds Sun Jan 04 13:11:53 2015 -0600
97.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
97.3 @@ -1,616 +0,0 @@
97.4 -+ """Configuration file parser.
97.5 -|
97.6 -| A setup file consists of sections, lead by a "[section]" header,
97.7 -| and followed by "name: value" entries, with continuations and such in
97.8 -| the style of RFC 822.
97.9 -|
97.10 -| the same section, or values in a special [DEFAULT] section.
97.11 -|
97.12 -| For example:
97.13 -|
97.14 -| something: %(dir)s/whatever
97.15 -|
97.16 -| would resolve the "%(dir)s" to the value of dir. All reference
97.17 -| expansions are done late, on demand.
97.18 -|
97.19 -| Intrinsic defaults can be specified by passing them into the
97.20 -| ConfigParser constructor as a dictionary.
97.21 -|
97.22 -| class:
97.23 -|
97.24 -| ConfigParser -- responsible for parsing a list of
97.25 -| configuration files, and managing the parsed database.
97.26 -|
97.27 -| methods:
97.28 -|
97.29 -| __init__(defaults=None)
97.30 -| create the parser and specify a dictionary of intrinsic defaults. The
97.31 -| keys must be strings, the values must be appropriate for %()s string
97.32 -| interpolation. Note that `__name__' is always an intrinsic default;
97.33 -| it's value is the section's name.
97.34 -|
97.35 -| sections()
97.36 -| return all the configuration section names, sans DEFAULT
97.37 -|
97.38 -| has_section(section)
97.39 -| return whether the given section exists
97.40 -|
97.41 -| has_option(section, option)
97.42 -| return whether the given option exists in the given section
97.43 -|
97.44 -| options(section)
97.45 -| return list of configuration options for the named section
97.46 -|
97.47 -| read(filenames)
97.48 -| read and parse the list of named configuration files, given by
97.49 -| name. A single filename is also allowed. Non-existing files
97.50 -| are ignored.
97.51 -|
97.52 -| readfp(fp, filename=None)
97.53 -| read and parse one configuration file, given as a file object.
97.54 -| The filename defaults to fp.name; it is only used in error
97.55 -| messages (if fp has no `name' attribute, the string `<???>' is used).
97.56 -|
97.57 -| get(section, option, raw=False, vars=None)
97.58 -| return a string value for the named option. All % interpolations are
97.59 -| expanded in the return values, based on the defaults passed into the
97.60 -| constructor and the DEFAULT section. Additional substitutions may be
97.61 -| provided using the `vars' argument, which must be a dictionary whose
97.62 -| contents override any pre-existing defaults.
97.63 -|
97.64 -| getint(section, options)
97.65 -| like get(), but convert value to an integer
97.66 -|
97.67 -| getfloat(section, options)
97.68 -| like get(), but convert value to a float
97.69 -|
97.70 -| getboolean(section, options)
97.71 -| like get(), but convert value to a boolean (currently case
97.72 -| insensitively defined as 0, false, no, off for False, and 1, true,
97.73 -| yes, on for True). Returns False or True.
97.74 -|
97.75 -| items(section, raw=False, vars=None)
97.76 -| return a list of tuples with (name, value) for each option
97.77 -| in the section.
97.78 -|
97.79 -| remove_section(section)
97.80 -| remove the given file section and all its options
97.81 -|
97.82 -| remove_option(section, option)
97.83 -| remove the given option from the given section
97.84 -|
97.85 -| set(section, option, value)
97.86 -| set the given option
97.87 -|
97.88 -| write(fp)
97.89 -| write the configuration state in .ini format
97.90 -- """
97.91 -
97.92 - import re
97.93 -
97.94 - __all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
97.95 - "InterpolationError", "InterpolationDepthError",
97.96 - "InterpolationSyntaxError", "ParsingError",
97.97 - "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser",
97.98 - "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
97.99 -
97.100 - DEFAULTSECT = "DEFAULT"
97.101 -
97.102 - MAX_INTERPOLATION_DEPTH = 10
97.103 -
97.104 -
97.105 -
97.106 - # exception classes
97.107 -+ class Error(Exception):
97.108 -| """Base class for ConfigParser exceptions."""
97.109 -|
97.110 -+ def __init__(self, msg=''):
97.111 -| self.message = msg
97.112 -| Exception.__init__(self, msg)
97.113 --
97.114 -+ def __repr__(self):
97.115 -| return self.message
97.116 --
97.117 -| __str__ = __repr__
97.118 --
97.119 -+ class NoSectionError(Error):
97.120 -| """Rasssised when no section matches a requested option."""
97.121 -|
97.122 -+ def __init__(self, section):
97.123 -| Error.__init__(self, 'No section: ' + `section`)
97.124 -| self.section = section
97.125 --
97.126 -+ class DuplicateSectionError(Error):
97.127 -| """Raised when a section is multiply-created."""
97.128 -|
97.129 -+ def __init__(self, section):
97.130 -| Error.__init__(self, "Section %r already exists" % section)
97.131 -| self.section = section
97.132 --
97.133 -+ class NoOptionError(Error):
97.134 -| """A requested option was not found."""
97.135 -|
97.136 -+ def __init__(self, option, section):
97.137 -| Error.__init__(self, "No option %r in section: %r" %
97.138 -| (option, section))
97.139 -| self.option = option
97.140 -| self.section = section
97.141 --
97.142 -+ class InterpolationError(Error):
97.143 -| """Base class for interpolation-related exceptions."""
97.144 -|
97.145 -+ def __init__(self, option, section, msg):
97.146 -| Error.__init__(self, msg)
97.147 -| self.option = option
97.148 -| self.section = section
97.149 --
97.150 -+ class InterpolationMissingOptionError(InterpolationError):
97.151 -| """A string substitution required a setting which was not available."""
97.152 -|
97.153 -+ def __init__(self, option, section, rawval, reference):
97.154 -+ msg = ("Bad value substitution:\n"
97.155 -| "\tsection: [%s]\n"
97.156 -| "\toption : %s\n"
97.157 -| "\tkey : %s\n"
97.158 -- "\trawval : %s\n"
97.159 -| % (section, option, reference, rawval))
97.160 -| InterpolationError.__init__(self, option, section, msg)
97.161 -| self.reference = reference
97.162 --
97.163 -+ class InterpolationSyntaxError(InterpolationError):
97.164 -+ """Raised when the source text into which substitutions are made
97.165 -- does not conform to the required syntax."""
97.166 --
97.167 -+ class InterpolationDepthError(InterpolationError):
97.168 -| """Raised when substitutions are nested too deeply."""
97.169 -|
97.170 -+ def __init__(self, option, section, rawval):
97.171 -+ msg = ("Value interpolation too deeply recursive:\n"
97.172 -| "\tsection: [%s]\n"
97.173 -| "\toption : %s\n"
97.174 -- "\trawval : %s\n"
97.175 -| % (section, option, rawval))
97.176 -| InterpolationError.__init__(self, option, section, msg)
97.177 --
97.178 -+ class ParsingError(Error):
97.179 -| """Raised when a configuration file does not follow legal syntax."""
97.180 -|
97.181 -+ def __init__(self, filename):
97.182 -| Error.__init__(self, 'File contains parsing errors: %s' % filename)
97.183 -| self.filename = filename
97.184 -| self.errors = []
97.185 --
97.186 -+ def append(self, lineno, line):
97.187 -| self.errors.append((lineno, line))
97.188 -| self.message += '\n\t[line %2d]: %s' % (lineno, line)
97.189 --
97.190 -+ class MissingSectionHeaderError(ParsingError):
97.191 -| """Raised when a key-value pair is found before any section header."""
97.192 -|
97.193 -+ def __init__(self, filename, lineno, line):
97.194 -| Error.__init__(
97.195 -| self,
97.196 -| 'File contains no section headers.\nfile: %s, line: %d\n%s' %
97.197 -| (filename, lineno, line))
97.198 -| self.filename = filename
97.199 -| self.lineno = lineno
97.200 -| self.line = line
97.201 -|
97.202 -|
97.203 --
97.204 -+ class RawConfigParser:
97.205 -+ def __init__(self, defaults=None):
97.206 -| self._sections = {}
97.207 -| if defaults is None:
97.208 -| self._defaults = {}
97.209 -| else:
97.210 -| self._defaults = defaults
97.211 --
97.212 -+ def defaults(self):
97.213 -| return self._defaults
97.214 --
97.215 -+ def sections(self):
97.216 -| """Return a list of section names, excluding [DEFAULT]"""
97.217 -| # self._sections will never have [DEFAULT] in it
97.218 -| return self._sections.keys()
97.219 --
97.220 -+ def add_section(self, section):
97.221 -+ """Create a new section in the configuration.
97.222 -|
97.223 -| Raise DuplicateSectionError if a section by the specified name
97.224 -| already exists.
97.225 -- """
97.226 -| if section in self._sections:
97.227 -| raise DuplicateSectionError(section)
97.228 -| self._sections[section] = {}
97.229 --
97.230 -+ def has_section(self, section):
97.231 -+ """Indicate whether the named section is present in the configuration.
97.232 -|
97.233 -| The DEFAULT section is not acknowledged.
97.234 -- """
97.235 -| return section in self._sections
97.236 --
97.237 -+ def options(self, section):
97.238 -| """Return a list of option names for the given section name."""
97.239 -| try:
97.240 -| opts = self._sections[section].copy()
97.241 -| except KeyError:
97.242 -| raise NoSectionError(section)
97.243 -| opts.update(self._defaults)
97.244 -| if '__name__' in opts:
97.245 -| del opts['__name__']
97.246 -| return opts.keys()
97.247 --
97.248 -+ def read(self, filenames):
97.249 -+ """Read and parse a filename or a list of filenames.
97.250 -|
97.251 -| Files that cannot be opened are silently ignored; this is
97.252 -| designed so that you can specify a list of potential
97.253 -| configuration file locations (e.g. current directory, user's
97.254 -| home directory, systemwide directory), and all existing
97.255 -| configuration files in the list will be read. A single
97.256 -| filename may also be given.
97.257 -- """
97.258 -| if isinstance(filenames, basestring):
97.259 -| filenames = [filenames]
97.260 -| for filename in filenames:
97.261 -| try:
97.262 -| fp = open(filename)
97.263 -| except IOError:
97.264 -| continue
97.265 -| self._read(fp, filename)
97.266 -| fp.close()
97.267 --
97.268 -+ def readfp(self, fp, filename=None):
97.269 -+ """Like read() but the argument must be a file-like object.
97.270 -|
97.271 -| The `fp' argument must have a `readline' method. Optional
97.272 -| second argument is the `filename', which if not given, is
97.273 -| taken from fp.name. If fp has no `name' attribute, `<???>' is
97.274 -| used.
97.275 -|
97.276 -- """
97.277 -| if filename is None:
97.278 -| try:
97.279 -| filename = fp.name
97.280 -| except AttributeError:
97.281 -| filename = '<???>'
97.282 -| self._read(fp, filename)
97.283 --
97.284 -+ def get(self, section, option):
97.285 -| opt = self.optionxform(option)
97.286 -| if section not in self._sections:
97.287 -| if section != DEFAULTSECT:
97.288 -| raise NoSectionError(section)
97.289 -| if opt in self._defaults:
97.290 -| return self._defaults[opt]
97.291 -| else:
97.292 -| raise NoOptionError(option, section)
97.293 -| elif opt in self._sections[section]:
97.294 -| return self._sections[section][opt]
97.295 -| elif opt in self._defaults:
97.296 -| return self._defaults[opt]
97.297 -| else:
97.298 -| raise NoOptionError(option, section)
97.299 --
97.300 -+ def items(self, section):
97.301 -| try:
97.302 -| d2 = self._sections[section]
97.303 -| except KeyError:
97.304 -| if section != DEFAULTSECT:
97.305 -| raise NoSectionError(section)
97.306 -| d2 = {}
97.307 -| d = self._defaults.copy()
97.308 -| d.update(d2)
97.309 -| if "__name__" in d:
97.310 -| del d["__name__"]
97.311 -| return d.items()
97.312 --
97.313 -+ def _get(self, section, conv, option):
97.314 -| return conv(self.get(section, option))
97.315 --
97.316 -+ def getint(self, section, option):
97.317 -| return self._get(section, int, option)
97.318 --
97.319 -+ def getfloat(self, section, option):
97.320 -| return self._get(section, float, option)
97.321 --
97.322 -| _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
97.323 -| '0': False, 'no': False, 'false': False, 'off': False}
97.324 -|
97.325 -+ def getboolean(self, section, option):
97.326 -| v = self.get(section, option)
97.327 -| if v.lower() not in self._boolean_states:
97.328 -| raise ValueError, 'Not a boolean: %s' % v
97.329 -| return self._boolean_states[v.lower()]
97.330 --
97.331 -+ def optionxform(self, optionstr):
97.332 -| return optionstr.lower()
97.333 --
97.334 -+ def has_option(self, section, option):
97.335 -| """Check for the existence of a given option in a given section."""
97.336 -| if not section or section == DEFAULTSECT:
97.337 -| option = self.optionxform(option)
97.338 -| return option in self._defaults
97.339 -| elif section not in self._sections:
97.340 -| return False
97.341 -| else:
97.342 -| option = self.optionxform(option)
97.343 -| return (option in self._sections[section]
97.344 -| or option in self._defaults)
97.345 --
97.346 -+ def set(self, section, option, value):
97.347 -| """Set an option."""
97.348 -| if not section or section == DEFAULTSECT:
97.349 -| sectdict = self._defaults
97.350 -| else:
97.351 -| try:
97.352 -| sectdict = self._sections[section]
97.353 -| except KeyError:
97.354 -| raise NoSectionError(section)
97.355 -| sectdict[self.optionxform(option)] = value
97.356 --
97.357 -+ def write(self, fp):
97.358 -| """Write an .ini-format representation of the configuration state."""
97.359 -| if self._defaults:
97.360 -| fp.write("[%s]\n" % DEFAULTSECT)
97.361 -| for (key, value) in self._defaults.items():
97.362 -| fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
97.363 -| fp.write("\n")
97.364 -| for section in self._sections:
97.365 -| fp.write("[%s]\n" % section)
97.366 -| for (key, value) in self._sections[section].items():
97.367 -| if key != "__name__":
97.368 -| fp.write("%s = %s\n" %
97.369 -| (key, str(value).replace('\n', '\n\t')))
97.370 -| fp.write("\n")
97.371 --
97.372 -+ def remove_option(self, section, option):
97.373 -| """Remove an option."""
97.374 -| if not section or section == DEFAULTSECT:
97.375 -| sectdict = self._defaults
97.376 -| else:
97.377 -| try:
97.378 -| sectdict = self._sections[section]
97.379 -| except KeyError:
97.380 -| raise NoSectionError(section)
97.381 -| option = self.optionxform(option)
97.382 -| existed = option in sectdict
97.383 -| if existed:
97.384 -| del sectdict[option]
97.385 -| return existed
97.386 --
97.387 -+ def remove_section(self, section):
97.388 -| """Remove a file section."""
97.389 -| existed = section in self._sections
97.390 -| if existed:
97.391 -| del self._sections[section]
97.392 -| return existed
97.393 -|
97.394 -| #
97.395 -| # Regular expressions for parsing section headers and options.
97.396 -- #
97.397 -| SECTCRE = re.compile(
97.398 -+ r'\[' # [
97.399 -- r'(?P<header>[^]]+)' # very permissive!
97.400 -| r'\]' # ]
97.401 -| )
97.402 -| OPTCRE = re.compile(
97.403 -+ r'(?P<option>[^:=\s][^:=]*)' # very permissive!
97.404 -| r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
97.405 -| # followed by separator
97.406 -| # (either : or =), followed
97.407 -- # by any # space/tab
97.408 -| r'(?P<value>.*)$' # everything up to eol
97.409 -| )
97.410 -|
97.411 -+ def _read(self, fp, fpname):
97.412 -+ """Parse a sectioned setup file.
97.413 -|
97.414 -| The sections in setup file contains a title line at the top,
97.415 -| indicated by a name in square brackets (`[]'), plus key/value
97.416 -| options lines, indicated by `name: value' format lines.
97.417 -| Continuations are represented by an embedded newline then
97.418 -| leading whitespace. Blank lines, lines beginning with a '#',
97.419 -| and just about everything else are ignored.
97.420 -- """
97.421 -| cursect = None # None, or a dictionary
97.422 -| optname = None
97.423 -| lineno = 0
97.424 -| e = None # None, or an exception
97.425 -| while True:
97.426 -| line = fp.readline()
97.427 -| if not line:
97.428 -| break
97.429 -| lineno = lineno + 1
97.430 -| # comment or blank line?
97.431 -| if line.strip() == '' or line[0] in '#;':
97.432 -| continue
97.433 -| if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
97.434 -| # no leading whitespace
97.435 -| continue
97.436 -| # continuation line?
97.437 -| if line[0].isspace() and cursect is not None and optname:
97.438 -| value = line.strip()
97.439 -| if value:
97.440 -| cursect[optname] = "%s\n%s" % (cursect[optname], value)
97.441 -| # a section header or option header?
97.442 -| else:
97.443 -| # is it a section header?
97.444 -| mo = self.SECTCRE.match(line)
97.445 -| if mo:
97.446 -| sectname = mo.group('header')
97.447 -| if sectname in self._sections:
97.448 -| cursect = self._sections[sectname]
97.449 -| elif sectname == DEFAULTSECT:
97.450 -| cursect = self._defaults
97.451 -| else:
97.452 -| cursect = {'__name__': sectname}
97.453 -| self._sections[sectname] = cursect
97.454 -| # So sections can't start with a continuation line
97.455 -| optname = None
97.456 -| # no section header in the file?
97.457 -| elif cursect is None:
97.458 -| raise MissingSectionHeaderError(fpname, lineno, `line`)
97.459 -| # an option line?
97.460 -| else:
97.461 -| mo = self.OPTCRE.match(line)
97.462 -| if mo:
97.463 -| optname, vi, optval = mo.group('option', 'vi', 'value')
97.464 -| if vi in ('=', ':') and ';' in optval:
97.465 -| # ';' is a comment delimiter only if it follows
97.466 -| # a spacing character
97.467 -| pos = optval.find(';')
97.468 -| if pos != -1 and optval[pos-1].isspace():
97.469 -| optval = optval[:pos]
97.470 -| optval = optval.strip()
97.471 -| # allow empty values
97.472 -| if optval == '""':
97.473 -| optval = ''
97.474 -| optname = self.optionxform(optname.rstrip())
97.475 -| cursect[optname] = optval
97.476 -| else:
97.477 -| # a non-fatal parsing error occurred. set up the
97.478 -| # exception but keep going. the exception will be
97.479 -| # raised at the end of the file and will contain a
97.480 -| # list of all bogus lines
97.481 -| if not e:
97.482 -| e = ParsingError(fpname)
97.483 -| e.append(lineno, `line`)
97.484 -| # if any parsing errors occurred, raise an exception
97.485 -| if e:
97.486 -| raise e
97.487 -|
97.488 --
97.489 -+ class ConfigParser(RawConfigParser):
97.490 -|
97.491 -+ def get(self, section, option, raw=False, vars=None):
97.492 -+ """Get an option value for a given section.
97.493 -|
97.494 -| All % interpolations are expanded in the return values, based on the
97.495 -| defaults passed into the constructor, unless the optional argument
97.496 -| `raw' is true. Additional substitutions may be provided using the
97.497 -| `vars' argument, which must be a dictionary whose contents overrides
97.498 -| any pre-existing defaults.
97.499 -|
97.500 -| The section DEFAULT is special.
97.501 -- """
97.502 -| d = self._defaults.copy()
97.503 -| try:
97.504 -| d.update(self._sections[section])
97.505 -| except KeyError:
97.506 -| if section != DEFAULTSECT:
97.507 -| raise NoSectionError(section)
97.508 -| # Update with the entry specific variables
97.509 -| if vars is not None:
97.510 -| d.update(vars)
97.511 -| option = self.optionxform(option)
97.512 -| try:
97.513 -| value = d[option]
97.514 -| except KeyError:
97.515 -| raise NoOptionError(option, section)
97.516 -|
97.517 -| if raw:
97.518 -| return value
97.519 -| else:
97.520 -| return self._interpolate(section, option, value, d)
97.521 --
97.522 -+ def items(self, section, raw=False, vars=None):
97.523 -+ """Return a list of tuples with (name, value) for each option
97.524 -| in the section.
97.525 -|
97.526 -| All % interpolations are expanded in the return values, based on the
97.527 -| defaults passed into the constructor, unless the optional argument
97.528 -| `raw' is true. Additional substitutions may be provided using the
97.529 -| `vars' argument, which must be a dictionary whose contents overrides
97.530 -| any pre-existing defaults.
97.531 -|
97.532 -| The section DEFAULT is special.
97.533 -- """
97.534 -| d = self._defaults.copy()
97.535 -| try:
97.536 -| d.update(self._sections[section])
97.537 -| except KeyError:
97.538 -| if section != DEFAULTSECT:
97.539 -| raise NoSectionError(section)
97.540 -| # Update with the entry specific variables
97.541 -| if vars:
97.542 -| d.update(vars)
97.543 -| options = d.keys()
97.544 -| if "__name__" in options:
97.545 -| options.remove("__name__")
97.546 -| if raw:
97.547 -| return [(option, d[option])
97.548 -| for option in options]
97.549 -| else:
97.550 -| return [(option, self._interpolate(section, option, d[option], d))
97.551 -| for option in options]
97.552 --
97.553 -+ def _interpolate(self, section, option, rawval, vars):
97.554 -| # do the string interpolation
97.555 -| value = rawval
97.556 -| depth = MAX_INTERPOLATION_DEPTH
97.557 -| while depth: # Loop through this until it's done
97.558 -| depth -= 1
97.559 -| if value.find("%(") != -1:
97.560 -| try:
97.561 -| value = value % vars
97.562 -| except KeyError, e:
97.563 -| raise InterpolationMissingOptionError(
97.564 -| option, section, rawval, e[0])
97.565 -| else:
97.566 -| break
97.567 -| if value.find("%(") != -1:
97.568 -| raise InterpolationDepthError(option, section, rawval)
97.569 -| return value
97.570 -|
97.571 --
97.572 -+ class SafeConfigParser(ConfigParser):
97.573 -|
97.574 -+ def _interpolate(self, section, option, rawval, vars):
97.575 -| # do the string interpolation
97.576 -| L = []
97.577 -| self._interpolate_some(option, L, rawval, section, vars, 1)
97.578 -| return ''.join(L)
97.579 --
97.580 -| _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
97.581 -|
97.582 -+ def _interpolate_some(self, option, accum, rest, section, map, depth):
97.583 -| if depth > MAX_INTERPOLATION_DEPTH:
97.584 -| raise InterpolationDepthError(option, section, rest)
97.585 -| while rest:
97.586 -| p = rest.find("%")
97.587 -| if p < 0:
97.588 -| accum.append(rest)
97.589 -| return
97.590 -| if p > 0:
97.591 -| accum.append(rest[:p])
97.592 -| rest = rest[p:]
97.593 -| # p is no longer used
97.594 -| c = rest[1:2]
97.595 -| if c == "%":
97.596 -| accum.append("%")
97.597 -| rest = rest[2:]
97.598 -| elif c == "(":
97.599 -| m = self._interpvar_match(rest)
97.600 -| if m is None:
97.601 -| raise InterpolationSyntaxError(option, section,
97.602 -| "bad interpolation variable reference %r" % rest)
97.603 -| var = m.group(1)
97.604 -| rest = rest[m.end():]
97.605 -| try:
97.606 -| v = map[var]
97.607 -| except KeyError:
97.608 -| raise InterpolationMissingOptionError(
97.609 -| option, section, rest, var)
97.610 -| if "%" in v:
97.611 -| self._interpolate_some(option, accum, v,
97.612 -| section, map, depth + 1)
97.613 -| else:
97.614 -| accum.append(v)
97.615 -| else:
97.616 -| raise InterpolationSyntaxError(
97.617 -| option, section,
97.618 -- "'%' must be followed by '%' or '(', found: " + `ret`)
97.619 -
98.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.formatted Sun Jan 04 13:11:53 2015 -0600
98.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
98.3 @@ -1,615 +0,0 @@
98.4 -"""Configuration file parser.
98.5 -
98.6 -A setup file consists of sections, lead by a "[section]" header,
98.7 -and followed by "name: value" entries, with continuations and such in
98.8 -the style of RFC 822.
98.9 -
98.10 - the same section, or values in a special [DEFAULT] section.
98.11 -
98.12 -For example:
98.13 -
98.14 - something: %(dir)s/whatever
98.15 -
98.16 -would resolve the "%(dir)s" to the value of dir. All reference
98.17 -expansions are done late, on demand.
98.18 -
98.19 -Intrinsic defaults can be specified by passing them into the
98.20 -ConfigParser constructor as a dictionary.
98.21 -
98.22 -class:
98.23 -
98.24 -ConfigParser -- responsible for parsing a list of
98.25 - configuration files, and managing the parsed database.
98.26 -
98.27 - methods:
98.28 -
98.29 - __init__(defaults=None)
98.30 - create the parser and specify a dictionary of intrinsic defaults. The
98.31 - keys must be strings, the values must be appropriate for %()s string
98.32 - interpolation. Note that `__name__' is always an intrinsic default;
98.33 - it's value is the section's name.
98.34 -
98.35 - sections()
98.36 - return all the configuration section names, sans DEFAULT
98.37 -
98.38 - has_section(section)
98.39 - return whether the given section exists
98.40 -
98.41 - has_option(section, option)
98.42 - return whether the given option exists in the given section
98.43 -
98.44 - options(section)
98.45 - return list of configuration options for the named section
98.46 -
98.47 - read(filenames)
98.48 - read and parse the list of named configuration files, given by
98.49 - name. A single filename is also allowed. Non-existing files
98.50 - are ignored.
98.51 -
98.52 - readfp(fp, filename=None)
98.53 - read and parse one configuration file, given as a file object.
98.54 - The filename defaults to fp.name; it is only used in error
98.55 - messages (if fp has no `name' attribute, the string `<???>' is used).
98.56 -
98.57 - get(section, option, raw=False, vars=None)
98.58 - return a string value for the named option. All % interpolations are
98.59 - expanded in the return values, based on the defaults passed into the
98.60 - constructor and the DEFAULT section. Additional substitutions may be
98.61 - provided using the `vars' argument, which must be a dictionary whose
98.62 - contents override any pre-existing defaults.
98.63 -
98.64 - getint(section, options)
98.65 - like get(), but convert value to an integer
98.66 -
98.67 - getfloat(section, options)
98.68 - like get(), but convert value to a float
98.69 -
98.70 - getboolean(section, options)
98.71 - like get(), but convert value to a boolean (currently case
98.72 - insensitively defined as 0, false, no, off for False, and 1, true,
98.73 - yes, on for True). Returns False or True.
98.74 -
98.75 - items(section, raw=False, vars=None)
98.76 - return a list of tuples with (name, value) for each option
98.77 - in the section.
98.78 -
98.79 - remove_section(section)
98.80 - remove the given file section and all its options
98.81 -
98.82 - remove_option(section, option)
98.83 - remove the given option from the given section
98.84 -
98.85 - set(section, option, value)
98.86 - set the given option
98.87 -
98.88 - write(fp)
98.89 - write the configuration state in .ini format
98.90 -"""
98.91 -
98.92 -import re
98.93 -
98.94 -__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
98.95 - "InterpolationError", "InterpolationDepthError",
98.96 - "InterpolationSyntaxError", "ParsingError",
98.97 - "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser",
98.98 - "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
98.99 -
98.100 -DEFAULTSECT = "DEFAULT"
98.101 -
98.102 -MAX_INTERPOLATION_DEPTH = 10
98.103 -
98.104 -
98.105 -
98.106 -# exception classes
98.107 -class Error(Exception):
98.108 - """Base class for ConfigParser exceptions."""
98.109 -
98.110 - def __init__(self, msg=''):
98.111 - self.message = msg
98.112 - Exception.__init__(self, msg)
98.113 -
98.114 - def __repr__(self):
98.115 - return self.message
98.116 -
98.117 - __str__ = __repr__
98.118 -
98.119 -class NoSectionError(Error):
98.120 - """Rasssised when no section matches a requested option."""
98.121 -
98.122 - def __init__(self, section):
98.123 - Error.__init__(self, 'No section: ' + `section`)
98.124 - self.section = section
98.125 -
98.126 -class DuplicateSectionError(Error):
98.127 - """Raised when a section is multiply-created."""
98.128 -
98.129 - def __init__(self, section):
98.130 - Error.__init__(self, "Section %r already exists" % section)
98.131 - self.section = section
98.132 -
98.133 -class NoOptionError(Error):
98.134 - """A requested option was not found."""
98.135 -
98.136 - def __init__(self, option, section):
98.137 - Error.__init__(self, "No option %r in section: %r" %
98.138 - (option, section))
98.139 - self.option = option
98.140 - self.section = section
98.141 -
98.142 -class InterpolationError(Error):
98.143 - """Base class for interpolation-related exceptions."""
98.144 -
98.145 - def __init__(self, option, section, msg):
98.146 - Error.__init__(self, msg)
98.147 - self.option = option
98.148 - self.section = section
98.149 -
98.150 -class InterpolationMissingOptionError(InterpolationError):
98.151 - """A string substitution required a setting which was not available."""
98.152 -
98.153 - def __init__(self, option, section, rawval, reference):
98.154 - msg = ("Bad value substitution:\n"
98.155 - "\tsection: [%s]\n"
98.156 - "\toption : %s\n"
98.157 - "\tkey : %s\n"
98.158 - "\trawval : %s\n"
98.159 - % (section, option, reference, rawval))
98.160 - InterpolationError.__init__(self, option, section, msg)
98.161 - self.reference = reference
98.162 -
98.163 -class InterpolationSyntaxError(InterpolationError):
98.164 - """Raised when the source text into which substitutions are made
98.165 - does not conform to the required syntax."""
98.166 -
98.167 -class InterpolationDepthError(InterpolationError):
98.168 - """Raised when substitutions are nested too deeply."""
98.169 -
98.170 - def __init__(self, option, section, rawval):
98.171 - msg = ("Value interpolation too deeply recursive:\n"
98.172 - "\tsection: [%s]\n"
98.173 - "\toption : %s\n"
98.174 - "\trawval : %s\n"
98.175 - % (section, option, rawval))
98.176 - InterpolationError.__init__(self, option, section, msg)
98.177 -
98.178 -class ParsingError(Error):
98.179 - """Raised when a configuration file does not follow legal syntax."""
98.180 -
98.181 - def __init__(self, filename):
98.182 - Error.__init__(self, 'File contains parsing errors: %s' % filename)
98.183 - self.filename = filename
98.184 - self.errors = []
98.185 -
98.186 - def append(self, lineno, line):
98.187 - self.errors.append((lineno, line))
98.188 - self.message += '\n\t[line %2d]: %s' % (lineno, line)
98.189 -
98.190 -class MissingSectionHeaderError(ParsingError):
98.191 - """Raised when a key-value pair is found before any section header."""
98.192 -
98.193 - def __init__(self, filename, lineno, line):
98.194 - Error.__init__(
98.195 - self,
98.196 - 'File contains no section headers.\nfile: %s, line: %d\n%s' %
98.197 - (filename, lineno, line))
98.198 - self.filename = filename
98.199 - self.lineno = lineno
98.200 - self.line = line
98.201 -
98.202 -
98.203 -
98.204 -class RawConfigParser:
98.205 - def __init__(self, defaults=None):
98.206 - self._sections = {}
98.207 - if defaults is None:
98.208 - self._defaults = {}
98.209 - else:
98.210 - self._defaults = defaults
98.211 -
98.212 - def defaults(self):
98.213 - return self._defaults
98.214 -
98.215 - def sections(self):
98.216 - """Return a list of section names, excluding [DEFAULT]"""
98.217 - # self._sections will never have [DEFAULT] in it
98.218 - return self._sections.keys()
98.219 -
98.220 - def add_section(self, section):
98.221 - """Create a new section in the configuration.
98.222 -
98.223 - Raise DuplicateSectionError if a section by the specified name
98.224 - already exists.
98.225 - """
98.226 - if section in self._sections:
98.227 - raise DuplicateSectionError(section)
98.228 - self._sections[section] = {}
98.229 -
98.230 - def has_section(self, section):
98.231 - """Indicate whether the named section is present in the configuration.
98.232 -
98.233 - The DEFAULT section is not acknowledged.
98.234 - """
98.235 - return section in self._sections
98.236 -
98.237 - def options(self, section):
98.238 - """Return a list of option names for the given section name."""
98.239 - try:
98.240 - opts = self._sections[section].copy()
98.241 - except KeyError:
98.242 - raise NoSectionError(section)
98.243 - opts.update(self._defaults)
98.244 - if '__name__' in opts:
98.245 - del opts['__name__']
98.246 - return opts.keys()
98.247 -
98.248 - def read(self, filenames):
98.249 - """Read and parse a filename or a list of filenames.
98.250 -
98.251 - Files that cannot be opened are silently ignored; this is
98.252 - designed so that you can specify a list of potential
98.253 - configuration file locations (e.g. current directory, user's
98.254 - home directory, systemwide directory), and all existing
98.255 - configuration files in the list will be read. A single
98.256 - filename may also be given.
98.257 - """
98.258 - if isinstance(filenames, basestring):
98.259 - filenames = [filenames]
98.260 - for filename in filenames:
98.261 - try:
98.262 - fp = open(filename)
98.263 - except IOError:
98.264 - continue
98.265 - self._read(fp, filename)
98.266 - fp.close()
98.267 -
98.268 - def readfp(self, fp, filename=None):
98.269 - """Like read() but the argument must be a file-like object.
98.270 -
98.271 - The `fp' argument must have a `readline' method. Optional
98.272 - second argument is the `filename', which if not given, is
98.273 - taken from fp.name. If fp has no `name' attribute, `<???>' is
98.274 - used.
98.275 -
98.276 - """
98.277 - if filename is None:
98.278 - try:
98.279 - filename = fp.name
98.280 - except AttributeError:
98.281 - filename = '<???>'
98.282 - self._read(fp, filename)
98.283 -
98.284 - def get(self, section, option):
98.285 - opt = self.optionxform(option)
98.286 - if section not in self._sections:
98.287 - if section != DEFAULTSECT:
98.288 - raise NoSectionError(section)
98.289 - if opt in self._defaults:
98.290 - return self._defaults[opt]
98.291 - else:
98.292 - raise NoOptionError(option, section)
98.293 - elif opt in self._sections[section]:
98.294 - return self._sections[section][opt]
98.295 - elif opt in self._defaults:
98.296 - return self._defaults[opt]
98.297 - else:
98.298 - raise NoOptionError(option, section)
98.299 -
98.300 - def items(self, section):
98.301 - try:
98.302 - d2 = self._sections[section]
98.303 - except KeyError:
98.304 - if section != DEFAULTSECT:
98.305 - raise NoSectionError(section)
98.306 - d2 = {}
98.307 - d = self._defaults.copy()
98.308 - d.update(d2)
98.309 - if "__name__" in d:
98.310 - del d["__name__"]
98.311 - return d.items()
98.312 -
98.313 - def _get(self, section, conv, option):
98.314 - return conv(self.get(section, option))
98.315 -
98.316 - def getint(self, section, option):
98.317 - return self._get(section, int, option)
98.318 -
98.319 - def getfloat(self, section, option):
98.320 - return self._get(section, float, option)
98.321 -
98.322 - _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
98.323 - '0': False, 'no': False, 'false': False, 'off': False}
98.324 -
98.325 - def getboolean(self, section, option):
98.326 - v = self.get(section, option)
98.327 - if v.lower() not in self._boolean_states:
98.328 - raise ValueError, 'Not a boolean: %s' % v
98.329 - return self._boolean_states[v.lower()]
98.330 -
98.331 - def optionxform(self, optionstr):
98.332 - return optionstr.lower()
98.333 -
98.334 - def has_option(self, section, option):
98.335 - """Check for the existence of a given option in a given section."""
98.336 - if not section or section == DEFAULTSECT:
98.337 - option = self.optionxform(option)
98.338 - return option in self._defaults
98.339 - elif section not in self._sections:
98.340 - return False
98.341 - else:
98.342 - option = self.optionxform(option)
98.343 - return (option in self._sections[section]
98.344 - or option in self._defaults)
98.345 -
98.346 - def set(self, section, option, value):
98.347 - """Set an option."""
98.348 - if not section or section == DEFAULTSECT:
98.349 - sectdict = self._defaults
98.350 - else:
98.351 - try:
98.352 - sectdict = self._sections[section]
98.353 - except KeyError:
98.354 - raise NoSectionError(section)
98.355 - sectdict[self.optionxform(option)] = value
98.356 -
98.357 - def write(self, fp):
98.358 - """Write an .ini-format representation of the configuration state."""
98.359 - if self._defaults:
98.360 - fp.write("[%s]\n" % DEFAULTSECT)
98.361 - for (key, value) in self._defaults.items():
98.362 - fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
98.363 - fp.write("\n")
98.364 - for section in self._sections:
98.365 - fp.write("[%s]\n" % section)
98.366 - for (key, value) in self._sections[section].items():
98.367 - if key != "__name__":
98.368 - fp.write("%s = %s\n" %
98.369 - (key, str(value).replace('\n', '\n\t')))
98.370 - fp.write("\n")
98.371 -
98.372 - def remove_option(self, section, option):
98.373 - """Remove an option."""
98.374 - if not section or section == DEFAULTSECT:
98.375 - sectdict = self._defaults
98.376 - else:
98.377 - try:
98.378 - sectdict = self._sections[section]
98.379 - except KeyError:
98.380 - raise NoSectionError(section)
98.381 - option = self.optionxform(option)
98.382 - existed = option in sectdict
98.383 - if existed:
98.384 - del sectdict[option]
98.385 - return existed
98.386 -
98.387 - def remove_section(self, section):
98.388 - """Remove a file section."""
98.389 - existed = section in self._sections
98.390 - if existed:
98.391 - del self._sections[section]
98.392 - return existed
98.393 -
98.394 - #
98.395 - # Regular expressions for parsing section headers and options.
98.396 - #
98.397 - SECTCRE = re.compile(
98.398 - r'\[' # [
98.399 - r'(?P<header>[^]]+)' # very permissive!
98.400 - r'\]' # ]
98.401 - )
98.402 - OPTCRE = re.compile(
98.403 - r'(?P<option>[^:=\s][^:=]*)' # very permissive!
98.404 - r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
98.405 - # followed by separator
98.406 - # (either : or =), followed
98.407 - # by any # space/tab
98.408 - r'(?P<value>.*)$' # everything up to eol
98.409 - )
98.410 -
98.411 - def _read(self, fp, fpname):
98.412 - """Parse a sectioned setup file.
98.413 -
98.414 - The sections in setup file contains a title line at the top,
98.415 - indicated by a name in square brackets (`[]'), plus key/value
98.416 - options lines, indicated by `name: value' format lines.
98.417 - Continuations are represented by an embedded newline then
98.418 - leading whitespace. Blank lines, lines beginning with a '#',
98.419 - and just about everything else are ignored.
98.420 - """
98.421 - cursect = None # None, or a dictionary
98.422 - optname = None
98.423 - lineno = 0
98.424 - e = None # None, or an exception
98.425 - while True:
98.426 - line = fp.readline()
98.427 - if not line:
98.428 - break
98.429 - lineno = lineno + 1
98.430 - # comment or blank line?
98.431 - if line.strip() == '' or line[0] in '#;':
98.432 - continue
98.433 - if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
98.434 - # no leading whitespace
98.435 - continue
98.436 - # continuation line?
98.437 - if line[0].isspace() and cursect is not None and optname:
98.438 - value = line.strip()
98.439 - if value:
98.440 - cursect[optname] = "%s\n%s" % (cursect[optname], value)
98.441 - # a section header or option header?
98.442 - else:
98.443 - # is it a section header?
98.444 - mo = self.SECTCRE.match(line)
98.445 - if mo:
98.446 - sectname = mo.group('header')
98.447 - if sectname in self._sections:
98.448 - cursect = self._sections[sectname]
98.449 - elif sectname == DEFAULTSECT:
98.450 - cursect = self._defaults
98.451 - else:
98.452 - cursect = {'__name__': sectname}
98.453 - self._sections[sectname] = cursect
98.454 - # So sections can't start with a continuation line
98.455 - optname = None
98.456 - # no section header in the file?
98.457 - elif cursect is None:
98.458 - raise MissingSectionHeaderError(fpname, lineno, `line`)
98.459 - # an option line?
98.460 - else:
98.461 - mo = self.OPTCRE.match(line)
98.462 - if mo:
98.463 - optname, vi, optval = mo.group('option', 'vi', 'value')
98.464 - if vi in ('=', ':') and ';' in optval:
98.465 - # ';' is a comment delimiter only if it follows
98.466 - # a spacing character
98.467 - pos = optval.find(';')
98.468 - if pos != -1 and optval[pos-1].isspace():
98.469 - optval = optval[:pos]
98.470 - optval = optval.strip()
98.471 - # allow empty values
98.472 - if optval == '""':
98.473 - optval = ''
98.474 - optname = self.optionxform(optname.rstrip())
98.475 - cursect[optname] = optval
98.476 - else:
98.477 - # a non-fatal parsing error occurred. set up the
98.478 - # exception but keep going. the exception will be
98.479 - # raised at the end of the file and will contain a
98.480 - # list of all bogus lines
98.481 - if not e:
98.482 - e = ParsingError(fpname)
98.483 - e.append(lineno, `line`)
98.484 - # if any parsing errors occurred, raise an exception
98.485 - if e:
98.486 - raise e
98.487 -
98.488 -
98.489 -class ConfigParser(RawConfigParser):
98.490 -
98.491 - def get(self, section, option, raw=False, vars=None):
98.492 - """Get an option value for a given section.
98.493 -
98.494 - All % interpolations are expanded in the return values, based on the
98.495 - defaults passed into the constructor, unless the optional argument
98.496 - `raw' is true. Additional substitutions may be provided using the
98.497 - `vars' argument, which must be a dictionary whose contents overrides
98.498 - any pre-existing defaults.
98.499 -
98.500 - The section DEFAULT is special.
98.501 - """
98.502 - d = self._defaults.copy()
98.503 - try:
98.504 - d.update(self._sections[section])
98.505 - except KeyError:
98.506 - if section != DEFAULTSECT:
98.507 - raise NoSectionError(section)
98.508 - # Update with the entry specific variables
98.509 - if vars is not None:
98.510 - d.update(vars)
98.511 - option = self.optionxform(option)
98.512 - try:
98.513 - value = d[option]
98.514 - except KeyError:
98.515 - raise NoOptionError(option, section)
98.516 -
98.517 - if raw:
98.518 - return value
98.519 - else:
98.520 - return self._interpolate(section, option, value, d)
98.521 -
98.522 - def items(self, section, raw=False, vars=None):
98.523 - """Return a list of tuples with (name, value) for each option
98.524 - in the section.
98.525 -
98.526 - All % interpolations are expanded in the return values, based on the
98.527 - defaults passed into the constructor, unless the optional argument
98.528 - `raw' is true. Additional substitutions may be provided using the
98.529 - `vars' argument, which must be a dictionary whose contents overrides
98.530 - any pre-existing defaults.
98.531 -
98.532 - The section DEFAULT is special.
98.533 - """
98.534 - d = self._defaults.copy()
98.535 - try:
98.536 - d.update(self._sections[section])
98.537 - except KeyError:
98.538 - if section != DEFAULTSECT:
98.539 - raise NoSectionError(section)
98.540 - # Update with the entry specific variables
98.541 - if vars:
98.542 - d.update(vars)
98.543 - options = d.keys()
98.544 - if "__name__" in options:
98.545 - options.remove("__name__")
98.546 - if raw:
98.547 - return [(option, d[option])
98.548 - for option in options]
98.549 - else:
98.550 - return [(option, self._interpolate(section, option, d[option], d))
98.551 - for option in options]
98.552 -
98.553 - def _interpolate(self, section, option, rawval, vars):
98.554 - # do the string interpolation
98.555 - value = rawval
98.556 - depth = MAX_INTERPOLATION_DEPTH
98.557 - while depth: # Loop through this until it's done
98.558 - depth -= 1
98.559 - if value.find("%(") != -1:
98.560 - try:
98.561 - value = value % vars
98.562 - except KeyError, e:
98.563 - raise InterpolationMissingOptionError(
98.564 - option, section, rawval, e[0])
98.565 - else:
98.566 - break
98.567 - if value.find("%(") != -1:
98.568 - raise InterpolationDepthError(option, section, rawval)
98.569 - return value
98.570 -
98.571 -
98.572 -class SafeConfigParser(ConfigParser):
98.573 -
98.574 - def _interpolate(self, section, option, rawval, vars):
98.575 - # do the string interpolation
98.576 - L = []
98.577 - self._interpolate_some(option, L, rawval, section, vars, 1)
98.578 - return ''.join(L)
98.579 -
98.580 - _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
98.581 -
98.582 - def _interpolate_some(self, option, accum, rest, section, map, depth):
98.583 - if depth > MAX_INTERPOLATION_DEPTH:
98.584 - raise InterpolationDepthError(option, section, rest)
98.585 - while rest:
98.586 - p = rest.find("%")
98.587 - if p < 0:
98.588 - accum.append(rest)
98.589 - return
98.590 - if p > 0:
98.591 - accum.append(rest[:p])
98.592 - rest = rest[p:]
98.593 - # p is no longer used
98.594 - c = rest[1:2]
98.595 - if c == "%":
98.596 - accum.append("%")
98.597 - rest = rest[2:]
98.598 - elif c == "(":
98.599 - m = self._interpvar_match(rest)
98.600 - if m is None:
98.601 - raise InterpolationSyntaxError(option, section,
98.602 - "bad interpolation variable reference %r" % rest)
98.603 - var = m.group(1)
98.604 - rest = rest[m.end():]
98.605 - try:
98.606 - v = map[var]
98.607 - except KeyError:
98.608 - raise InterpolationMissingOptionError(
98.609 - option, section, rest, var)
98.610 - if "%" in v:
98.611 - self._interpolate_some(option, accum, v,
98.612 - section, map, depth + 1)
98.613 - else:
98.614 - accum.append(v)
98.615 - else:
98.616 - raise InterpolationSyntaxError(
98.617 - option, section,
98.618 - "'%' must be followed by '%' or '(', found: " + `ret`)
99.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.html Sun Jan 04 13:11:53 2015 -0600
99.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
99.3 @@ -1,302 +0,0 @@
99.4 -<html><body>
99.5 -<h2 style="color: green">Next Comment</h2>
99.6 -<pre><b>ConfigParser.py</b></pre>
99.7 -
99.8 -<hr>
99.9 -Configuration file parser.
99.10 -
99.11 -<br><br>
99.12 -A setup file consists of sections, lead by a "[section]" header,
99.13 -and followed by "name: value" entries, with continuations and such in
99.14 -the style of RFC 822.
99.15 -
99.16 -<br><br>
99.17 - the same section, or values in a special [DEFAULT] section.
99.18 -
99.19 -<br><br>
99.20 -For example:
99.21 -
99.22 -<br><br>
99.23 - something: %(dir)s/whatever
99.24 -
99.25 -<br><br>
99.26 -would resolve the "%(dir)s" to the value of dir. All reference
99.27 -expansions are done late, on demand.
99.28 -
99.29 -<br><br>
99.30 -Intrinsic defaults can be specified by passing them into the
99.31 -ConfigParser constructor as a dictionary.
99.32 -
99.33 -<br><br>
99.34 -class:
99.35 -
99.36 -<br><br>
99.37 -ConfigParser -- responsible for parsing a list of
99.38 - configuration files, and managing the parsed database.
99.39 -
99.40 -<br><br>
99.41 - methods:
99.42 -
99.43 -<br><br>
99.44 - __init__(defaults=None)
99.45 - create the parser and specify a dictionary of intrinsic defaults. The
99.46 - keys must be strings, the values must be appropriate for %()s string
99.47 - interpolation. Note that `__name__' is always an intrinsic default;
99.48 - it's value is the section's name.
99.49 -
99.50 -<br><br>
99.51 - sections()
99.52 - return all the configuration section names, sans DEFAULT
99.53 -
99.54 -<br><br>
99.55 - has_section(section)
99.56 - return whether the given section exists
99.57 -
99.58 -<br><br>
99.59 - has_option(section, option)
99.60 - return whether the given option exists in the given section
99.61 -
99.62 -<br><br>
99.63 - options(section)
99.64 - return list of configuration options for the named section
99.65 -
99.66 -<br><br>
99.67 - read(filenames)
99.68 - read and parse the list of named configuration files, given by
99.69 - name. A single filename is also allowed. Non-existing files
99.70 - are ignored.
99.71 -
99.72 -<br><br>
99.73 - readfp(fp, filename=None)
99.74 - read and parse one configuration file, given as a file object.
99.75 - The filename defaults to fp.name; it is only used in error
99.76 - messages (if fp has no `name' attribute, the string `<???>' is used).
99.77 -
99.78 -<br><br>
99.79 - get(section, option, raw=False, vars=None)
99.80 - return a string value for the named option. All % interpolations are
99.81 - expanded in the return values, based on the defaults passed into the
99.82 - constructor and the DEFAULT section. Additional substitutions may be
99.83 - provided using the `vars' argument, which must be a dictionary whose
99.84 - contents override any pre-existing defaults.
99.85 -
99.86 -<br><br>
99.87 - getint(section, options)
99.88 - like get(), but convert value to an integer
99.89 -
99.90 -<br><br>
99.91 - getfloat(section, options)
99.92 - like get(), but convert value to a float
99.93 -
99.94 -<br><br>
99.95 - getboolean(section, options)
99.96 - like get(), but convert value to a boolean (currently case
99.97 - insensitively defined as 0, false, no, off for False, and 1, true,
99.98 - yes, on for True). Returns False or True.
99.99 -
99.100 -<br><br>
99.101 - items(section, raw=False, vars=None)
99.102 - return a list of tuples with (name, value) for each option
99.103 - in the section.
99.104 -
99.105 -<br><br>
99.106 - remove_section(section)
99.107 - remove the given file section and all its options
99.108 -
99.109 -<br><br>
99.110 - remove_option(section, option)
99.111 - remove the given option from the given section
99.112 -
99.113 -<br><br>
99.114 - set(section, option, value)
99.115 - set the given option
99.116 -
99.117 -<br><br>
99.118 - write(fp)
99.119 - write the configuration state in .ini format
99.120 -<h2 style="color: green">Next Comment</h2>
99.121 -<pre><b>Error</b></pre>
99.122 -
99.123 -<hr>
99.124 -Base class for ConfigParser exceptions.
99.125 -<h2 style="color: green">Next Comment</h2>
99.126 -<pre><b>NoSectionError</b></pre>
99.127 -
99.128 -<hr>
99.129 -Rasssised when no section matches a requested option.
99.130 -<h2 style="color: green">Next Comment</h2>
99.131 -<pre><b>DuplicateSectionError</b></pre>
99.132 -
99.133 -<hr>
99.134 -Raised when a section is multiply-created.
99.135 -<h2 style="color: green">Next Comment</h2>
99.136 -<pre><b>NoOptionError</b></pre>
99.137 -
99.138 -<hr>
99.139 -A requested option was not found.
99.140 -<h2 style="color: green">Next Comment</h2>
99.141 -<pre><b>InterpolationError</b></pre>
99.142 -
99.143 -<hr>
99.144 -Base class for interpolation-related exceptions.
99.145 -<h2 style="color: green">Next Comment</h2>
99.146 -<pre><b>InterpolationMissingOptionError</b></pre>
99.147 -
99.148 -<hr>
99.149 -A string substitution required a setting which was not available.
99.150 -<h2 style="color: green">Next Comment</h2>
99.151 -<pre><b>InterpolationSyntaxError</b></pre>
99.152 -
99.153 -<hr>
99.154 -Raised when the source text into which substitutions are made
99.155 - does not conform to the required syntax.
99.156 -<h2 style="color: green">Next Comment</h2>
99.157 -<pre><b>InterpolationDepthError</b></pre>
99.158 -
99.159 -<hr>
99.160 -Raised when substitutions are nested too deeply.
99.161 -<h2 style="color: green">Next Comment</h2>
99.162 -<pre><b>ParsingError</b></pre>
99.163 -
99.164 -<hr>
99.165 -Raised when a configuration file does not follow legal syntax.
99.166 -<h2 style="color: green">Next Comment</h2>
99.167 -<pre><b>MissingSectionHeaderError</b></pre>
99.168 -
99.169 -<hr>
99.170 -Raised when a key-value pair is found before any section header.
99.171 -<h2 style="color: green">Next Comment</h2>
99.172 -<pre><b>sections</b>(<font color="#808080">self</font>)</pre>
99.173 -
99.174 -<hr>
99.175 -Return a list of section names, excluding [DEFAULT]
99.176 -<h2 style="color: green">Next Comment</h2>
99.177 -<pre><b>add_section</b>(<font color="#808080">self, section</font>)</pre>
99.178 -
99.179 -<hr>
99.180 -Create a new section in the configuration.
99.181 -
99.182 -<br><br>
99.183 - Raise DuplicateSectionError if a section by the specified name
99.184 - already exists.
99.185 -
99.186 -<br><br>
99.187 -<h2 style="color: green">Next Comment</h2>
99.188 -<pre><b>has_section</b>(<font color="#808080">self, section</font>)</pre>
99.189 -
99.190 -<hr>
99.191 -Indicate whether the named section is present in the configuration.
99.192 -
99.193 -<br><br>
99.194 - The DEFAULT section is not acknowledged.
99.195 -
99.196 -<br><br>
99.197 -<h2 style="color: green">Next Comment</h2>
99.198 -<pre><b>options</b>(<font color="#808080">self, section</font>)</pre>
99.199 -
99.200 -<hr>
99.201 -Return a list of option names for the given section name.
99.202 -<h2 style="color: green">Next Comment</h2>
99.203 -<pre><b>read</b>(<font color="#808080">self, filenames</font>)</pre>
99.204 -
99.205 -<hr>
99.206 -Read and parse a filename or a list of filenames.
99.207 -
99.208 -<br><br>
99.209 - Files that cannot be opened are silently ignored; this is
99.210 - designed so that you can specify a list of potential
99.211 - configuration file locations (e.g. current directory, user's
99.212 - home directory, systemwide directory), and all existing
99.213 - configuration files in the list will be read. A single
99.214 - filename may also be given.
99.215 -
99.216 -<br><br>
99.217 -<h2 style="color: green">Next Comment</h2>
99.218 -<pre><b>readfp</b>(<font color="#808080">self, fp, filename</font>)</pre>
99.219 -
99.220 -<hr>
99.221 -Like read() but the argument must be a file-like object.
99.222 -
99.223 -<br><br>
99.224 - The `fp' argument must have a `readline' method. Optional
99.225 - second argument is the `filename', which if not given, is
99.226 - taken from fp.name. If fp has no `name' attribute, `<???>' is
99.227 - used.
99.228 -
99.229 -<br><br>
99.230 -<h2 style="color: green">Next Comment</h2>
99.231 -<pre><b>has_option</b>(<font color="#808080">self, section, option</font>)</pre>
99.232 -
99.233 -<hr>
99.234 -Check for the existence of a given option in a given section.
99.235 -<h2 style="color: green">Next Comment</h2>
99.236 -<pre><b>set</b>(<font color="#808080">self, section, option, value</font>)</pre>
99.237 -
99.238 -<hr>
99.239 -Set an option.
99.240 -<h2 style="color: green">Next Comment</h2>
99.241 -<pre><b>write</b>(<font color="#808080">self, fp</font>)</pre>
99.242 -
99.243 -<hr>
99.244 -Write an .ini-format representation of the configuration state.
99.245 -<h2 style="color: green">Next Comment</h2>
99.246 -<pre><b>remove_option</b>(<font color="#808080">self, section, option</font>)</pre>
99.247 -
99.248 -<hr>
99.249 -Remove an option.
99.250 -<h2 style="color: green">Next Comment</h2>
99.251 -<pre><b>remove_section</b>(<font color="#808080">self, section</font>)</pre>
99.252 -
99.253 -<hr>
99.254 -Remove a file section.
99.255 -<h2 style="color: green">Next Comment</h2>
99.256 -<pre><b>_read</b>(<font color="#808080">self, fp, fpname</font>)</pre>
99.257 -
99.258 -<hr>
99.259 -Parse a sectioned setup file.
99.260 -
99.261 -<br><br>
99.262 - The sections in setup file contains a title line at the top,
99.263 - indicated by a name in square brackets (`[]'), plus key/value
99.264 - options lines, indicated by `name: value' format lines.
99.265 - Continuations are represented by an embedded newline then
99.266 - leading whitespace. Blank lines, lines beginning with a '#',
99.267 - and just about everything else are ignored.
99.268 -
99.269 -<br><br>
99.270 -<h2 style="color: green">Next Comment</h2>
99.271 -<pre><b>get</b>(<font color="#808080">self, section, option, raw, vars</font>)</pre>
99.272 -
99.273 -<hr>
99.274 -Get an option value for a given section.
99.275 -
99.276 -<br><br>
99.277 - All % interpolations are expanded in the return values, based on the
99.278 - defaults passed into the constructor, unless the optional argument
99.279 - `raw' is true. Additional substitutions may be provided using the
99.280 - `vars' argument, which must be a dictionary whose contents overrides
99.281 - any pre-existing defaults.
99.282 -
99.283 -<br><br>
99.284 - The section DEFAULT is special.
99.285 -
99.286 -<br><br>
99.287 -<h2 style="color: green">Next Comment</h2>
99.288 -<pre><b>items</b>(<font color="#808080">self, section, raw, vars</font>)</pre>
99.289 -
99.290 -<hr>
99.291 -Return a list of tuples with (name, value) for each option
99.292 - in the section.
99.293 -
99.294 -<br><br>
99.295 - All % interpolations are expanded in the return values, based on the
99.296 - defaults passed into the constructor, unless the optional argument
99.297 - `raw' is true. Additional substitutions may be provided using the
99.298 - `vars' argument, which must be a dictionary whose contents overrides
99.299 - any pre-existing defaults.
99.300 -
99.301 -<br><br>
99.302 - The section DEFAULT is special.
99.303 -
99.304 -<br><br>
99.305 -</body></html>
100.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.indexed Sun Jan 04 13:11:53 2015 -0600
100.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
100.3 @@ -1,213 +0,0 @@
100.4 -
100.5 -
100.6 -Document 0
100.7 -Searchable Keys:
100.8 - class : ConfigParser
100.9 - class-ig : configparser
100.10 - extends : RawConfigParser
100.11 - in : ConfigParser
100.12 - member : _interpolate;F;|PRIVATE|;self,section,option,rawval,vars;
100.13 - member : get;F;;self,section,option,raw,vars;
100.14 - member : items;F;;self,section,raw,vars;
100.15 -
100.16 -Not Searchable Keys:
100.17 -
100.18 -
100.19 -Document 1
100.20 -Searchable Keys:
100.21 - class : DuplicateSectionError
100.22 - class-ig : duplicatesectionerror
100.23 - extends : Error
100.24 - in : ConfigParser
100.25 - member : __init__;c;|CONSTRUCTOR|;self,section;
100.26 - member : section;D;;
100.27 -
100.28 -Not Searchable Keys:
100.29 -
100.30 -
100.31 -Document 2
100.32 -Searchable Keys:
100.33 - class : Error
100.34 - class-ig : error
100.35 - extends : Exception
100.36 - in : ConfigParser
100.37 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,msg;
100.38 - member : __repr__;F;|PRIVATE|;self;
100.39 - member : __str__;F;|PRIVATE|;self;
100.40 - member : message;D;;
100.41 -
100.42 -Not Searchable Keys:
100.43 - clzattrs : ;|PRIVATE|;
100.44 -
100.45 -
100.46 -Document 3
100.47 -Searchable Keys:
100.48 - class : InterpolationDepthError
100.49 - class-ig : interpolationdeptherror
100.50 - extends : InterpolationError
100.51 - in : ConfigParser
100.52 - member : __init__;c;|CONSTRUCTOR|;self,option,section,rawval;
100.53 -
100.54 -Not Searchable Keys:
100.55 -
100.56 -
100.57 -Document 4
100.58 -Searchable Keys:
100.59 - class : InterpolationError
100.60 - class-ig : interpolationerror
100.61 - extends : Error
100.62 - in : ConfigParser
100.63 - member : __init__;c;|CONSTRUCTOR|;self,option,section,msg;
100.64 - member : option;D;;
100.65 - member : section;D;;
100.66 -
100.67 -Not Searchable Keys:
100.68 -
100.69 -
100.70 -Document 5
100.71 -Searchable Keys:
100.72 - class : InterpolationMissingOptionError
100.73 - class-ig : interpolationmissingoptionerror
100.74 - extends : InterpolationError
100.75 - in : ConfigParser
100.76 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,option,section,rawval,reference;
100.77 - member : reference;D;;
100.78 -
100.79 -Not Searchable Keys:
100.80 - clzattrs : ;|PRIVATE|;
100.81 -
100.82 -
100.83 -Document 6
100.84 -Searchable Keys:
100.85 - class : InterpolationSyntaxError
100.86 - class-ig : interpolationsyntaxerror
100.87 - extends : InterpolationError
100.88 - in : ConfigParser
100.89 -
100.90 -Not Searchable Keys:
100.91 -
100.92 -
100.93 -Document 7
100.94 -Searchable Keys:
100.95 - class : MissingSectionHeaderError
100.96 - class-ig : missingsectionheadererror
100.97 - extends : ParsingError
100.98 - in : ConfigParser
100.99 - member : __init__;c;|CONSTRUCTOR|;self,filename,lineno,line;
100.100 - member : filename;D;;
100.101 - member : line;D;;
100.102 - member : lineno;D;;
100.103 -
100.104 -Not Searchable Keys:
100.105 -
100.106 -
100.107 -Document 8
100.108 -Searchable Keys:
100.109 - class : NoOptionError
100.110 - class-ig : nooptionerror
100.111 - extends : Error
100.112 - in : ConfigParser
100.113 - member : __init__;c;|CONSTRUCTOR|;self,option,section;
100.114 - member : option;D;;
100.115 - member : section;D;;
100.116 -
100.117 -Not Searchable Keys:
100.118 -
100.119 -
100.120 -Document 9
100.121 -Searchable Keys:
100.122 - class : NoSectionError
100.123 - class-ig : nosectionerror
100.124 - extends : Error
100.125 - in : ConfigParser
100.126 - member : __init__;c;|CONSTRUCTOR|;self,section;
100.127 - member : section;D;;
100.128 -
100.129 -Not Searchable Keys:
100.130 -
100.131 -
100.132 -Document 10
100.133 -Searchable Keys:
100.134 - class : ParsingError
100.135 - class-ig : parsingerror
100.136 - extends : Error
100.137 - in : ConfigParser
100.138 - member : __init__;c;|CONSTRUCTOR|;self,filename;
100.139 - member : append;F;;self,lineno,line;
100.140 - member : errors;D;;
100.141 - member : filename;D;;
100.142 -
100.143 -Not Searchable Keys:
100.144 -
100.145 -
100.146 -Document 11
100.147 -Searchable Keys:
100.148 - class : RawConfigParser
100.149 - class-ig : rawconfigparser
100.150 - in : ConfigParser
100.151 - member : OPTCRE;D;|PRIVATE|;
100.152 - member : SECTCRE;D;|PRIVATE|;
100.153 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,defaults;
100.154 - member : _boolean_states;D;|PRIVATE|;
100.155 - member : _defaults;D;|PRIVATE|;
100.156 - member : _get;F;|PRIVATE|;self,section,conv,option;
100.157 - member : _read;F;|PRIVATE|;self,fp,fpname;
100.158 - member : _sections;D;|PRIVATE|;
100.159 - member : add_section;F;|PRIVATE|;self,section;
100.160 - member : defaults;F;|PRIVATE|;self;
100.161 - member : get;F;|PRIVATE|;self,section,option;
100.162 - member : getboolean;F;|PRIVATE|;self,section,option;
100.163 - member : getfloat;F;|PRIVATE|;self,section,option;
100.164 - member : getint;F;|PRIVATE|;self,section,option;
100.165 - member : has_option;F;|PRIVATE|;self,section,option;
100.166 - member : has_section;F;|PRIVATE|;self,section;
100.167 - member : items;F;|PRIVATE|;self,section;
100.168 - member : options;F;|PRIVATE|;self,section;
100.169 - member : optionxform;F;|PRIVATE|;self,optionstr;
100.170 - member : read;F;|PRIVATE|;self,filenames;
100.171 - member : readfp;F;|PRIVATE|;self,fp,filename;
100.172 - member : remove_option;F;|PRIVATE|;self,section,option;
100.173 - member : remove_section;F;|PRIVATE|;self,section;
100.174 - member : sections;F;|PRIVATE|;self;
100.175 - member : set;F;|PRIVATE|;self,section,option,value;
100.176 - member : write;F;|PRIVATE|;self,fp;
100.177 -
100.178 -Not Searchable Keys:
100.179 - clzattrs : ;|PRIVATE|;
100.180 -
100.181 -
100.182 -Document 12
100.183 -Searchable Keys:
100.184 - class : SafeConfigParser
100.185 - class-ig : safeconfigparser
100.186 - extends : ConfigParser
100.187 - in : ConfigParser
100.188 - member : _interpolate;F;|PRIVATE|;self,section,option,rawval,vars;
100.189 - member : _interpolate_some;F;|PRIVATE|;self,option,accum,rest,section,map,depth;
100.190 - member : _interpvar_match;D;|PRIVATE|;
100.191 -
100.192 -Not Searchable Keys:
100.193 -
100.194 -
100.195 -Document 13
100.196 -Searchable Keys:
100.197 - item : ConfigParser;C;;
100.198 - item : DEFAULTSECT;D;;
100.199 - item : DuplicateSectionError;C;;
100.200 - item : Error;C;|PRIVATE|;
100.201 - item : InterpolationDepthError;C;;
100.202 - item : InterpolationError;C;;
100.203 - item : InterpolationMissingOptionError;C;|PRIVATE|;
100.204 - item : InterpolationSyntaxError;C;;
100.205 - item : MAX_INTERPOLATION_DEPTH;D;;
100.206 - item : MissingSectionHeaderError;C;;
100.207 - item : NoOptionError;C;;
100.208 - item : NoSectionError;C;;
100.209 - item : ParsingError;C;;
100.210 - item : RawConfigParser;C;|PRIVATE|;
100.211 - item : SafeConfigParser;C;;
100.212 - item : __all__;D;;
100.213 - item : re;I;|PRIVATE|;
100.214 - module : ConfigParser
100.215 -
100.216 -Not Searchable Keys:
101.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.nameoffsets Sun Jan 04 13:11:53 2015 -0600
101.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
101.3 @@ -1,616 +0,0 @@
101.4 -
101.5 -"""Configuration file parser.
101.6 -
101.7 -A setup file consists of sections, lead by a "[section]" header,
101.8 -and followed by "name: value" entries, with continuations and such in
101.9 -the style of RFC 822.
101.10 -
101.11 - the same section, or values in a special [DEFAULT] section.
101.12 -
101.13 -For example:
101.14 -
101.15 - something: %(dir)s/whatever
101.16 -
101.17 -would resolve the "%(dir)s" to the value of dir. All reference
101.18 -expansions are done late, on demand.
101.19 -
101.20 -Intrinsic defaults can be specified by passing them into the
101.21 -ConfigParser constructor as a dictionary.
101.22 -
101.23 -class:
101.24 -
101.25 -ConfigParser -- responsible for parsing a list of
101.26 - configuration files, and managing the parsed database.
101.27 -
101.28 - methods:
101.29 -
101.30 - __init__(defaults=None)
101.31 - create the parser and specify a dictionary of intrinsic defaults. The
101.32 - keys must be strings, the values must be appropriate for %()s string
101.33 - interpolation. Note that `__name__' is always an intrinsic default;
101.34 - it's value is the section's name.
101.35 -
101.36 - sections()
101.37 - return all the configuration section names, sans DEFAULT
101.38 -
101.39 - has_section(section)
101.40 - return whether the given section exists
101.41 -
101.42 - has_option(section, option)
101.43 - return whether the given option exists in the given section
101.44 -
101.45 - options(section)
101.46 - return list of configuration options for the named section
101.47 -
101.48 - read(filenames)
101.49 - read and parse the list of named configuration files, given by
101.50 - name. A single filename is also allowed. Non-existing files
101.51 - are ignored.
101.52 -
101.53 - readfp(fp, filename=None)
101.54 - read and parse one configuration file, given as a file object.
101.55 - The filename defaults to fp.name; it is only used in error
101.56 - messages (if fp has no `name' attribute, the string `<???>' is used).
101.57 -
101.58 - get(section, option, raw=False, vars=None)
101.59 - return a string value for the named option. All % interpolations are
101.60 - expanded in the return values, based on the defaults passed into the
101.61 - constructor and the DEFAULT section. Additional substitutions may be
101.62 - provided using the `vars' argument, which must be a dictionary whose
101.63 - contents override any pre-existing defaults.
101.64 -
101.65 - getint(section, options)
101.66 - like get(), but convert value to an integer
101.67 -
101.68 - getfloat(section, options)
101.69 - like get(), but convert value to a float
101.70 -
101.71 - getboolean(section, options)
101.72 - like get(), but convert value to a boolean (currently case
101.73 - insensitively defined as 0, false, no, off for False, and 1, true,
101.74 - yes, on for True). Returns False or True.
101.75 -
101.76 - items(section, raw=False, vars=None)
101.77 - return a list of tuples with (name, value) for each option
101.78 - in the section.
101.79 -
101.80 - remove_section(section)
101.81 - remove the given file section and all its options
101.82 -
101.83 - remove_option(section, option)
101.84 - remove the given option from the given section
101.85 -
101.86 - set(section, option, value)
101.87 - set the given option
101.88 -
101.89 - write(fp)
101.90 - write the configuration state in .ini format
101.91 -"""
101.92 -
101.93 -import re
101.94 -
101.95 -<Name>__all__</Name> = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
101.96 - "InterpolationError", "InterpolationDepthError",
101.97 - "InterpolationSyntaxError", "ParsingError",
101.98 - "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser",
101.99 - "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
101.100 -
101.101 -<Name>DEFAULTSECT</Name> = "DEFAULT"
101.102 -
101.103 -<Name>MAX_INTERPOLATION_DEPTH</Name> = 10
101.104 -
101.105 -
101.106 -
101.107 -# exception classes
101.108 -class <ClassDef>Error</ClassDef>(<Name>Exception</Name>):
101.109 - """Base class for ConfigParser exceptions."""
101.110 -
101.111 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>msg</Name>=''):
101.112 - <Attribute><Name>self</Name></Attribute>.message = <Name>msg</Name>
101.113 - <Attribute><Name>Exception</Name></Attribute>.<Call>__init__</Call>(<Name>self</Name>, <Name>msg</Name>)
101.114 -
101.115 - def <FunctionDef>__repr__</FunctionDef>(<Name>self</Name>):
101.116 - return <Attribute><Name>self</Name></Attribute>.message
101.117 -
101.118 - <Name>__str__</Name> = <Name>__repr__</Name>
101.119 -
101.120 -class <ClassDef>NoSectionError</ClassDef>(<Name>Error</Name>):
101.121 - """Rasssised when no section matches a requested option."""
101.122 -
101.123 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>section</Name>):
101.124 - <Attribute><Name>Error</Name></Attribute>.<Call>__init__</Call>(<Name>self</Name>, 'No section: ' + `<Name>section</Name>`)
101.125 - <Attribute><Name>self</Name></Attribute>.section = <Name>section</Name>
101.126 -
101.127 -class <ClassDef>DuplicateSectionError</ClassDef>(<Name>Error</Name>):
101.128 - """Raised when a section is multiply-created."""
101.129 -
101.130 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>section</Name>):
101.131 - <Attribute><Name>Error</Name></Attribute>.<Call>__init__</Call>(<Name>self</Name>, "Section %r already exists" % <Name>section</Name>)
101.132 - <Attribute><Name>self</Name></Attribute>.section = <Name>section</Name>
101.133 -
101.134 -class <ClassDef>NoOptionError</ClassDef>(<Name>Error</Name>):
101.135 - """A requested option was not found."""
101.136 -
101.137 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>):
101.138 - <Attribute><Name>Error</Name></Attribute>.<Call>__init__</Call>(<Name>self</Name>, "No option %r in section: %r" %
101.139 - (<Name>option</Name>, <Name>section</Name>))
101.140 - <Attribute><Name>self</Name></Attribute>.option = <Name>option</Name>
101.141 - <Attribute><Name>self</Name></Attribute>.section = <Name>section</Name>
101.142 -
101.143 -class <ClassDef>InterpolationError</ClassDef>(<Name>Error</Name>):
101.144 - """Base class for interpolation-related exceptions."""
101.145 -
101.146 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>msg</Name>):
101.147 - <Attribute><Name>Error</Name></Attribute>.<Call>__init__</Call>(<Name>self</Name>, <Name>msg</Name>)
101.148 - <Attribute><Name>self</Name></Attribute>.option = <Name>option</Name>
101.149 - <Attribute><Name>self</Name></Attribute>.section = <Name>section</Name>
101.150 -
101.151 -class <ClassDef>InterpolationMissingOptionError</ClassDef>(<Name>InterpolationError</Name>):
101.152 - """A string substitution required a setting which was not available."""
101.153 -
101.154 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>rawval</Name>, <Name>reference</Name>):
101.155 - <Name>msg</Name> = ("Bad value substitution:\n"
101.156 - "\tsection: [%s]\n"
101.157 - "\toption : %s\n"
101.158 - "\tkey : %s\n"
101.159 - "\trawval : %s\n"
101.160 - % (<Name>section</Name>, <Name>option</Name>, <Name>reference</Name>, <Name>rawval</Name>))
101.161 - <Attribute><Name>InterpolationError</Name></Attribute>.<Call>__init__</Call>(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>msg</Name>)
101.162 - <Attribute><Name>self</Name></Attribute>.reference = <Name>reference</Name>
101.163 -
101.164 -class <ClassDef>InterpolationSyntaxError</ClassDef>(<Name>InterpolationError</Name>):
101.165 - """Raised when the source text into which substitutions are made
101.166 - does not conform to the required syntax."""
101.167 -
101.168 -class <ClassDef>InterpolationDepthError</ClassDef>(<Name>InterpolationError</Name>):
101.169 - """Raised when substitutions are nested too deeply."""
101.170 -
101.171 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>rawval</Name>):
101.172 - <Name>msg</Name> = ("Value interpolation too deeply recursive:\n"
101.173 - "\tsection: [%s]\n"
101.174 - "\toption : %s\n"
101.175 - "\trawval : %s\n"
101.176 - % (<Name>section</Name>, <Name>option</Name>, <Name>rawval</Name>))
101.177 - <Attribute><Name>InterpolationError</Name></Attribute>.<Call>__init__</Call>(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>msg</Name>)
101.178 -
101.179 -class <ClassDef>ParsingError</ClassDef>(<Name>Error</Name>):
101.180 - """Raised when a configuration file does not follow legal syntax."""
101.181 -
101.182 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>filename</Name>):
101.183 - <Attribute><Name>Error</Name></Attribute>.<Call>__init__</Call>(<Name>self</Name>, 'File contains parsing errors: %s' % <Name>filename</Name>)
101.184 - <Attribute><Name>self</Name></Attribute>.filename = <Name>filename</Name>
101.185 - <Attribute><Name>self</Name></Attribute>.errors = []
101.186 -
101.187 - def <FunctionDef>append</FunctionDef>(<Name>self</Name>, <Name>lineno</Name>, <Name>line</Name>):
101.188 - <Attribute><Attribute><Name>self</Name></Attribute></Attribute>.errors.<Call>append</Call>((<Name>lineno</Name>, <Name>line</Name>))
101.189 - <Attribute><Name>self</Name></Attribute>.message += '\n\t[line %2d]: %s' % (<Name>lineno</Name>, <Name>line</Name>)
101.190 -
101.191 -class <ClassDef>MissingSectionHeaderError</ClassDef>(<Name>ParsingError</Name>):
101.192 - """Raised when a key-value pair is found before any section header."""
101.193 -
101.194 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>filename</Name>, <Name>lineno</Name>, <Name>line</Name>):
101.195 - <Attribute><Name>Error</Name></Attribute>.<Call>__init__</Call>(
101.196 - <Name>self</Name>,
101.197 - 'File contains no section headers.\nfile: %s, line: %d\n%s' %
101.198 - (<Name>filename</Name>, <Name>lineno</Name>, <Name>line</Name>))
101.199 - <Attribute><Name>self</Name></Attribute>.filename = <Name>filename</Name>
101.200 - <Attribute><Name>self</Name></Attribute>.lineno = <Name>lineno</Name>
101.201 - <Attribute><Name>self</Name></Attribute>.line = <Name>line</Name>
101.202 -
101.203 -
101.204 -
101.205 -class <ClassDef>RawConfigParser</ClassDef>:
101.206 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>defaults</Name>=<Name>None</Name>):
101.207 - <Attribute><Name>self</Name></Attribute>._sections = {}
101.208 - if <Name>defaults</Name> is <Name>None</Name>:
101.209 - <Attribute><Name>self</Name></Attribute>._defaults = {}
101.210 - else:
101.211 - <Attribute><Name>self</Name></Attribute>._defaults = <Name>defaults</Name>
101.212 -
101.213 - def <FunctionDef>defaults</FunctionDef>(<Name>self</Name>):
101.214 - return <Attribute><Name>self</Name></Attribute>._defaults
101.215 -
101.216 - def <FunctionDef>sections</FunctionDef>(<Name>self</Name>):
101.217 - """Return a list of section names, excluding [DEFAULT]"""
101.218 - # self._sections will never have [DEFAULT] in it
101.219 - return <Attribute><Attribute><Name>self</Name></Attribute></Attribute>._sections.<Call>keys</Call>()
101.220 -
101.221 - def <FunctionDef>add_section</FunctionDef>(<Name>self</Name>, <Name>section</Name>):
101.222 - """Create a new section in the configuration.
101.223 -
101.224 - Raise DuplicateSectionError if a section by the specified name
101.225 - already exists.
101.226 - """
101.227 - if <Name>section</Name> in <Attribute><Name>self</Name></Attribute>._sections:
101.228 - raise <Call><Name>DuplicateSectionError</Name></Call>(<Name>section</Name>)
101.229 - <Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>] = {}
101.230 -
101.231 - def <FunctionDef>has_section</FunctionDef>(<Name>self</Name>, <Name>section</Name>):
101.232 - """Indicate whether the named section is present in the configuration.
101.233 -
101.234 - The DEFAULT section is not acknowledged.
101.235 - """
101.236 - return <Name>section</Name> in <Attribute><Name>self</Name></Attribute>._sections
101.237 -
101.238 - def <FunctionDef>options</FunctionDef>(<Name>self</Name>, <Name>section</Name>):
101.239 - """Return a list of option names for the given section name."""
101.240 - try:
101.241 - <Name>opts</Name> = <Attribute><Name>self</Name></Attribute>._sections<Attribute>[<Name>section</Name>]</Attribute>.<Call>copy</Call>()
101.242 - except <Name>KeyError</Name>:
101.243 - raise <Call><Name>NoSectionError</Name></Call>(<Name>section</Name>)
101.244 - <Attribute><Name>opts</Name></Attribute>.<Call>update</Call>(<Attribute><Name>self</Name></Attribute>._defaults)
101.245 - if '__name__' in <Name>opts</Name>:
101.246 - del <Name>opts</Name>['__name__']
101.247 - return <Attribute><Name>opts</Name></Attribute>.<Call>keys</Call>()
101.248 -
101.249 - def <FunctionDef>read</FunctionDef>(<Name>self</Name>, <Name>filenames</Name>):
101.250 - """Read and parse a filename or a list of filenames.
101.251 -
101.252 - Files that cannot be opened are silently ignored; this is
101.253 - designed so that you can specify a list of potential
101.254 - configuration file locations (e.g. current directory, user's
101.255 - home directory, systemwide directory), and all existing
101.256 - configuration files in the list will be read. A single
101.257 - filename may also be given.
101.258 - """
101.259 - if <Call><Name>isinstance</Name></Call>(<Name>filenames</Name>, <Name>basestring</Name>):
101.260 - <Name>filenames</Name> = [<Name>filenames</Name>]
101.261 - for <Name>filename</Name> in <Name>filenames</Name>:
101.262 - try:
101.263 - <Name>fp</Name> = <Call><Name>open</Name></Call>(<Name>filename</Name>)
101.264 - except <Name>IOError</Name>:
101.265 - continue
101.266 - <Attribute><Name>self</Name></Attribute>.<Call>_read</Call>(<Name>fp</Name>, <Name>filename</Name>)
101.267 - <Attribute><Name>fp</Name></Attribute>.<Call>close</Call>()
101.268 -
101.269 - def <FunctionDef>readfp</FunctionDef>(<Name>self</Name>, <Name>fp</Name>, <Name>filename</Name>=<Name>None</Name>):
101.270 - """Like read() but the argument must be a file-like object.
101.271 -
101.272 - The `fp' argument must have a `readline' method. Optional
101.273 - second argument is the `filename', which if not given, is
101.274 - taken from fp.name. If fp has no `name' attribute, `<???>' is
101.275 - used.
101.276 -
101.277 - """
101.278 - if <Name>filename</Name> is <Name>None</Name>:
101.279 - try:
101.280 - <Name>filename</Name> = <Attribute><Name>fp</Name></Attribute>.name
101.281 - except <Name>AttributeError</Name>:
101.282 - <Name>filename</Name> = '<???>'
101.283 - <Attribute><Name>self</Name></Attribute>.<Call>_read</Call>(<Name>fp</Name>, <Name>filename</Name>)
101.284 -
101.285 - def <FunctionDef>get</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
101.286 - <Name>opt</Name> = <Attribute><Name>self</Name></Attribute>.<Call>optionxform</Call>(<Name>option</Name>)
101.287 - if <Name>section</Name> not in <Attribute><Name>self</Name></Attribute>._sections:
101.288 - if <Name>section</Name> != <Name>DEFAULTSECT</Name>:
101.289 - raise <Call><Name>NoSectionError</Name></Call>(<Name>section</Name>)
101.290 - if <Name>opt</Name> in <Attribute><Name>self</Name></Attribute>._defaults:
101.291 - return <Attribute><Name>self</Name></Attribute>._defaults[<Name>opt</Name>]
101.292 - else:
101.293 - raise <Call><Name>NoOptionError</Name></Call>(<Name>option</Name>, <Name>section</Name>)
101.294 - elif <Name>opt</Name> in <Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>]:
101.295 - return <Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>][<Name>opt</Name>]
101.296 - elif <Name>opt</Name> in <Attribute><Name>self</Name></Attribute>._defaults:
101.297 - return <Attribute><Name>self</Name></Attribute>._defaults[<Name>opt</Name>]
101.298 - else:
101.299 - raise <Call><Name>NoOptionError</Name></Call>(<Name>option</Name>, <Name>section</Name>)
101.300 -
101.301 - def <FunctionDef>items</FunctionDef>(<Name>self</Name>, <Name>section</Name>):
101.302 - try:
101.303 - <Name>d2</Name> = <Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>]
101.304 - except <Name>KeyError</Name>:
101.305 - if <Name>section</Name> != <Name>DEFAULTSECT</Name>:
101.306 - raise <Call><Name>NoSectionError</Name></Call>(<Name>section</Name>)
101.307 - <Name>d2</Name> = {}
101.308 - <Name>d</Name> = <Attribute><Attribute><Name>self</Name></Attribute></Attribute>._defaults.<Call>copy</Call>()
101.309 - <Attribute><Name>d</Name></Attribute>.<Call>update</Call>(<Name>d2</Name>)
101.310 - if "__name__" in <Name>d</Name>:
101.311 - del <Name>d</Name>["__name__"]
101.312 - return <Attribute><Name>d</Name></Attribute>.<Call>items</Call>()
101.313 -
101.314 - def <FunctionDef>_get</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>conv</Name>, <Name>option</Name>):
101.315 - return <Call><Name>conv</Name></Call>(<Attribute><Name>self</Name></Attribute>.<Call>get</Call>(<Name>section</Name>, <Name>option</Name>))
101.316 -
101.317 - def <FunctionDef>getint</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
101.318 - return <Attribute><Name>self</Name></Attribute>.<Call>_get</Call>(<Name>section</Name>, <Name>int</Name>, <Name>option</Name>)
101.319 -
101.320 - def <FunctionDef>getfloat</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
101.321 - return <Attribute><Name>self</Name></Attribute>.<Call>_get</Call>(<Name>section</Name>, <Name>float</Name>, <Name>option</Name>)
101.322 -
101.323 - <Name>_boolean_states</Name> = {'1': <Name>True</Name>, 'yes': <Name>True</Name>, 'true': <Name>True</Name>, 'on': <Name>True</Name>,
101.324 - '0': <Name>False</Name>, 'no': <Name>False</Name>, 'false': <Name>False</Name>, 'off': <Name>False</Name>}
101.325 -
101.326 - def <FunctionDef>getboolean</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
101.327 - <Name>v</Name> = <Attribute><Name>self</Name></Attribute>.<Call>get</Call>(<Name>section</Name>, <Name>option</Name>)
101.328 - if <Attribute><Name>v</Name></Attribute>.<Call>lower</Call>() not in <Attribute><Name>self</Name></Attribute>._boolean_states:
101.329 - raise <Name>ValueError</Name>, 'Not a boolean: %s' % <Name>v</Name>
101.330 - return <Attribute><Name>self</Name></Attribute>._boolean_states[<Attribute><Name>v</Name></Attribute>.<Call>lower</Call>()]
101.331 -
101.332 - def <FunctionDef>optionxform</FunctionDef>(<Name>self</Name>, <Name>optionstr</Name>):
101.333 - return <Attribute><Name>optionstr</Name></Attribute>.<Call>lower</Call>()
101.334 -
101.335 - def <FunctionDef>has_option</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
101.336 - """Check for the existence of a given option in a given section."""
101.337 - if not <Name>section</Name> or <Name>section</Name> == <Name>DEFAULTSECT</Name>:
101.338 - <Name>option</Name> = <Attribute><Name>self</Name></Attribute>.<Call>optionxform</Call>(<Name>option</Name>)
101.339 - return <Name>option</Name> in <Attribute><Name>self</Name></Attribute>._defaults
101.340 - elif <Name>section</Name> not in <Attribute><Name>self</Name></Attribute>._sections:
101.341 - return <Name>False</Name>
101.342 - else:
101.343 - <Name>option</Name> = <Attribute><Name>self</Name></Attribute>.<Call>optionxform</Call>(<Name>option</Name>)
101.344 - return (<Name>option</Name> in <Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>]
101.345 - or <Name>option</Name> in <Attribute><Name>self</Name></Attribute>._defaults)
101.346 -
101.347 - def <FunctionDef>set</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>, <Name>value</Name>):
101.348 - """Set an option."""
101.349 - if not <Name>section</Name> or <Name>section</Name> == <Name>DEFAULTSECT</Name>:
101.350 - <Name>sectdict</Name> = <Attribute><Name>self</Name></Attribute>._defaults
101.351 - else:
101.352 - try:
101.353 - <Name>sectdict</Name> = <Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>]
101.354 - except <Name>KeyError</Name>:
101.355 - raise <Call><Name>NoSectionError</Name></Call>(<Name>section</Name>)
101.356 - <Name>sectdict</Name>[<Attribute><Name>self</Name></Attribute>.<Call>optionxform</Call>(<Name>option</Name>)] = <Name>value</Name>
101.357 -
101.358 - def <FunctionDef>write</FunctionDef>(<Name>self</Name>, <Name>fp</Name>):
101.359 - """Write an .ini-format representation of the configuration state."""
101.360 - if <Attribute><Name>self</Name></Attribute>._defaults:
101.361 - <Attribute><Name>fp</Name></Attribute>.<Call>write</Call>("[%s]\n" % <Name>DEFAULTSECT</Name>)
101.362 - for (<Name>key</Name>, <Name>value</Name>) in <Attribute><Attribute><Name>self</Name></Attribute></Attribute>._defaults.<Call>items</Call>():
101.363 - <Attribute><Name>fp</Name></Attribute>.<Call>write</Call>("%s = %s\n" % (<Name>key</Name>, <Attribute><Call><Name>str</Name></Call></Attribute>(<Name>value</Name>).<Call>replace</Call>('\n', '\n\t')))
101.364 - <Attribute><Name>fp</Name></Attribute>.<Call>write</Call>("\n")
101.365 - for <Name>section</Name> in <Attribute><Name>self</Name></Attribute>._sections:
101.366 - <Attribute><Name>fp</Name></Attribute>.<Call>write</Call>("[%s]\n" % <Name>section</Name>)
101.367 - for (<Name>key</Name>, <Name>value</Name>) in <Attribute><Name>self</Name></Attribute>._sections<Attribute>[<Name>section</Name>]</Attribute>.<Call>items</Call>():
101.368 - if <Name>key</Name> != "__name__":
101.369 - <Attribute><Name>fp</Name></Attribute>.<Call>write</Call>("%s = %s\n" %
101.370 - (<Name>key</Name>, <Attribute><Call><Name>str</Name></Call></Attribute>(<Name>value</Name>).<Call>replace</Call>('\n', '\n\t')))
101.371 - <Attribute><Name>fp</Name></Attribute>.<Call>write</Call>("\n")
101.372 -
101.373 - def <FunctionDef>remove_option</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
101.374 - """Remove an option."""
101.375 - if not <Name>section</Name> or <Name>section</Name> == <Name>DEFAULTSECT</Name>:
101.376 - <Name>sectdict</Name> = <Attribute><Name>self</Name></Attribute>._defaults
101.377 - else:
101.378 - try:
101.379 - <Name>sectdict</Name> = <Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>]
101.380 - except <Name>KeyError</Name>:
101.381 - raise <Call><Name>NoSectionError</Name></Call>(<Name>section</Name>)
101.382 - <Name>option</Name> = <Attribute><Name>self</Name></Attribute>.<Call>optionxform</Call>(<Name>option</Name>)
101.383 - <Name>existed</Name> = <Name>option</Name> in <Name>sectdict</Name>
101.384 - if <Name>existed</Name>:
101.385 - del <Name>sectdict</Name>[<Name>option</Name>]
101.386 - return <Name>existed</Name>
101.387 -
101.388 - def <FunctionDef>remove_section</FunctionDef>(<Name>self</Name>, <Name>section</Name>):
101.389 - """Remove a file section."""
101.390 - <Name>existed</Name> = <Name>section</Name> in <Attribute><Name>self</Name></Attribute>._sections
101.391 - if <Name>existed</Name>:
101.392 - del <Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>]
101.393 - return <Name>existed</Name>
101.394 -
101.395 - #
101.396 - # Regular expressions for parsing section headers and options.
101.397 - #
101.398 - <Name>SECTCRE</Name> = <Attribute><Name>re</Name></Attribute>.<Call>compile</Call>(
101.399 - r'\[' # [
101.400 - r'(?P<header>[^]]+)' # very permissive!
101.401 - r'\]' # ]
101.402 - )
101.403 - <Name>OPTCRE</Name> = <Attribute><Name>re</Name></Attribute>.<Call>compile</Call>(
101.404 - r'(?P<option>[^:=\s][^:=]*)' # very permissive!
101.405 - r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
101.406 - # followed by separator
101.407 - # (either : or =), followed
101.408 - # by any # space/tab
101.409 - r'(?P<value>.*)$' # everything up to eol
101.410 - )
101.411 -
101.412 - def <FunctionDef>_read</FunctionDef>(<Name>self</Name>, <Name>fp</Name>, <Name>fpname</Name>):
101.413 - """Parse a sectioned setup file.
101.414 -
101.415 - The sections in setup file contains a title line at the top,
101.416 - indicated by a name in square brackets (`[]'), plus key/value
101.417 - options lines, indicated by `name: value' format lines.
101.418 - Continuations are represented by an embedded newline then
101.419 - leading whitespace. Blank lines, lines beginning with a '#',
101.420 - and just about everything else are ignored.
101.421 - """
101.422 - <Name>cursect</Name> = <Name>None</Name> # None, or a dictionary
101.423 - <Name>optname</Name> = <Name>None</Name>
101.424 - <Name>lineno</Name> = 0
101.425 - <Name>e</Name> = <Name>None</Name> # None, or an exception
101.426 - while <Name>True</Name>:
101.427 - <Name>line</Name> = <Attribute><Name>fp</Name></Attribute>.<Call>readline</Call>()
101.428 - if not <Name>line</Name>:
101.429 - break
101.430 - <Name>lineno</Name> = <Name>lineno</Name> + 1
101.431 - # comment or blank line?
101.432 - if <Attribute><Name>line</Name></Attribute>.<Call>strip</Call>() == '' or <Name>line</Name>[0] in '#;':
101.433 - continue
101.434 - if <Attribute><Name>line</Name></Attribute>.<Call>split</Call>(<Name>None</Name>, 1)<Attribute>[0]</Attribute>.<Call>lower</Call>() == 'rem' and <Name>line</Name>[0] in "rR":
101.435 - # no leading whitespace
101.436 - continue
101.437 - # continuation line?
101.438 - if <Name>line</Name><Attribute>[0]</Attribute>.<Call>isspace</Call>() and <Name>cursect</Name> is not <Name>None</Name> and <Name>optname</Name>:
101.439 - <Name>value</Name> = <Attribute><Name>line</Name></Attribute>.<Call>strip</Call>()
101.440 - if <Name>value</Name>:
101.441 - <Name>cursect</Name>[<Name>optname</Name>] = "%s\n%s" % (<Name>cursect</Name>[<Name>optname</Name>], <Name>value</Name>)
101.442 - # a section header or option header?
101.443 - else:
101.444 - # is it a section header?
101.445 - <Name>mo</Name> = <Attribute><Attribute><Name>self</Name></Attribute></Attribute>.SECTCRE.<Call>match</Call>(<Name>line</Name>)
101.446 - if <Name>mo</Name>:
101.447 - <Name>sectname</Name> = <Attribute><Name>mo</Name></Attribute>.<Call>group</Call>('header')
101.448 - if <Name>sectname</Name> in <Attribute><Name>self</Name></Attribute>._sections:
101.449 - <Name>cursect</Name> = <Attribute><Name>self</Name></Attribute>._sections[<Name>sectname</Name>]
101.450 - elif <Name>sectname</Name> == <Name>DEFAULTSECT</Name>:
101.451 - <Name>cursect</Name> = <Attribute><Name>self</Name></Attribute>._defaults
101.452 - else:
101.453 - <Name>cursect</Name> = {'__name__': <Name>sectname</Name>}
101.454 - <Attribute><Name>self</Name></Attribute>._sections[<Name>sectname</Name>] = <Name>cursect</Name>
101.455 - # So sections can't start with a continuation line
101.456 - <Name>optname</Name> = <Name>None</Name>
101.457 - # no section header in the file?
101.458 - elif <Name>cursect</Name> is <Name>None</Name>:
101.459 - raise <Call><Name>MissingSectionHeaderError</Name></Call>(<Name>fpname</Name>, <Name>lineno</Name>, `<Name>line</Name>`)
101.460 - # an option line?
101.461 - else:
101.462 - <Name>mo</Name> = <Attribute><Attribute><Name>self</Name></Attribute></Attribute>.OPTCRE.<Call>match</Call>(<Name>line</Name>)
101.463 - if <Name>mo</Name>:
101.464 - <Name>optname</Name>, <Name>vi</Name>, <Name>optval</Name> = <Attribute><Name>mo</Name></Attribute>.<Call>group</Call>('option', 'vi', 'value')
101.465 - if <Name>vi</Name> in ('=', ':') and ';' in <Name>optval</Name>:
101.466 - # ';' is a comment delimiter only if it follows
101.467 - # a spacing character
101.468 - <Name>pos</Name> = <Attribute><Name>optval</Name></Attribute>.<Call>find</Call>(';')
101.469 - if <Name>pos</Name> != -1 and <Name>optval</Name><Attribute>[<Name>pos</Name>-1]</Attribute>.<Call>isspace</Call>():
101.470 - <Name>optval</Name> = <Name>optval</Name>[:<Name>pos</Name>]
101.471 - <Name>optval</Name> = <Attribute><Name>optval</Name></Attribute>.<Call>strip</Call>()
101.472 - # allow empty values
101.473 - if <Name>optval</Name> == '""':
101.474 - <Name>optval</Name> = ''
101.475 - <Name>optname</Name> = <Attribute><Name>self</Name></Attribute>.<Call>optionxform</Call>(<Attribute><Name>optname</Name></Attribute>.<Call>rstrip</Call>())
101.476 - <Name>cursect</Name>[<Name>optname</Name>] = <Name>optval</Name>
101.477 - else:
101.478 - # a non-fatal parsing error occurred. set up the
101.479 - # exception but keep going. the exception will be
101.480 - # raised at the end of the file and will contain a
101.481 - # list of all bogus lines
101.482 - if not <Name>e</Name>:
101.483 - <Name>e</Name> = <Call><Name>ParsingError</Name></Call>(<Name>fpname</Name>)
101.484 - <Attribute><Name>e</Name></Attribute>.<Call>append</Call>(<Name>lineno</Name>, `<Name>line</Name>`)
101.485 - # if any parsing errors occurred, raise an exception
101.486 - if <Name>e</Name>:
101.487 - raise <Name>e</Name>
101.488 -
101.489 -
101.490 -class <ClassDef>ConfigParser</ClassDef>(<Name>RawConfigParser</Name>):
101.491 -
101.492 - def <FunctionDef>get</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>, <Name>raw</Name>=<Name>False</Name>, <Name>vars</Name>=<Name>None</Name>):
101.493 - """Get an option value for a given section.
101.494 -
101.495 - All % interpolations are expanded in the return values, based on the
101.496 - defaults passed into the constructor, unless the optional argument
101.497 - `raw' is true. Additional substitutions may be provided using the
101.498 - `vars' argument, which must be a dictionary whose contents overrides
101.499 - any pre-existing defaults.
101.500 -
101.501 - The section DEFAULT is special.
101.502 - """
101.503 - <Name>d</Name> = <Attribute><Attribute><Name>self</Name></Attribute></Attribute>._defaults.<Call>copy</Call>()
101.504 - try:
101.505 - <Attribute><Name>d</Name></Attribute>.<Call>update</Call>(<Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>])
101.506 - except <Name>KeyError</Name>:
101.507 - if <Name>section</Name> != <Name>DEFAULTSECT</Name>:
101.508 - raise <Call><Name>NoSectionError</Name></Call>(<Name>section</Name>)
101.509 - # Update with the entry specific variables
101.510 - if <Name>vars</Name> is not <Name>None</Name>:
101.511 - <Attribute><Name>d</Name></Attribute>.<Call>update</Call>(<Name>vars</Name>)
101.512 - <Name>option</Name> = <Attribute><Name>self</Name></Attribute>.<Call>optionxform</Call>(<Name>option</Name>)
101.513 - try:
101.514 - <Name>value</Name> = <Name>d</Name>[<Name>option</Name>]
101.515 - except <Name>KeyError</Name>:
101.516 - raise <Call><Name>NoOptionError</Name></Call>(<Name>option</Name>, <Name>section</Name>)
101.517 -
101.518 - if <Name>raw</Name>:
101.519 - return <Name>value</Name>
101.520 - else:
101.521 - return <Attribute><Name>self</Name></Attribute>.<Call>_interpolate</Call>(<Name>section</Name>, <Name>option</Name>, <Name>value</Name>, <Name>d</Name>)
101.522 -
101.523 - def <FunctionDef>items</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>raw</Name>=<Name>False</Name>, <Name>vars</Name>=<Name>None</Name>):
101.524 - """Return a list of tuples with (name, value) for each option
101.525 - in the section.
101.526 -
101.527 - All % interpolations are expanded in the return values, based on the
101.528 - defaults passed into the constructor, unless the optional argument
101.529 - `raw' is true. Additional substitutions may be provided using the
101.530 - `vars' argument, which must be a dictionary whose contents overrides
101.531 - any pre-existing defaults.
101.532 -
101.533 - The section DEFAULT is special.
101.534 - """
101.535 - <Name>d</Name> = <Attribute><Attribute><Name>self</Name></Attribute></Attribute>._defaults.<Call>copy</Call>()
101.536 - try:
101.537 - <Attribute><Name>d</Name></Attribute>.<Call>update</Call>(<Attribute><Name>self</Name></Attribute>._sections[<Name>section</Name>])
101.538 - except <Name>KeyError</Name>:
101.539 - if <Name>section</Name> != <Name>DEFAULTSECT</Name>:
101.540 - raise <Call><Name>NoSectionError</Name></Call>(<Name>section</Name>)
101.541 - # Update with the entry specific variables
101.542 - if <Name>vars</Name>:
101.543 - <Attribute><Name>d</Name></Attribute>.<Call>update</Call>(<Name>vars</Name>)
101.544 - <Name>options</Name> = <Attribute><Name>d</Name></Attribute>.<Call>keys</Call>()
101.545 - if "__name__" in <Name>options</Name>:
101.546 - <Attribute><Name>options</Name></Attribute>.<Call>remove</Call>("__name__")
101.547 - if <Name>raw</Name>:
101.548 - return [(<Name>option</Name>, <Name>d</Name>[<Name>option</Name>])
101.549 - for <Name>option</Name> in <Name>options</Name>]
101.550 - else:
101.551 - return [(<Name>option</Name>, <Attribute><Name>self</Name></Attribute>.<Call>_interpolate</Call>(<Name>section</Name>, <Name>option</Name>, <Name>d</Name>[<Name>option</Name>], <Name>d</Name>))
101.552 - for <Name>option</Name> in <Name>options</Name>]
101.553 -
101.554 - def <FunctionDef>_interpolate</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>, <Name>rawval</Name>, <Name>vars</Name>):
101.555 - # do the string interpolation
101.556 - <Name>value</Name> = <Name>rawval</Name>
101.557 - <Name>depth</Name> = <Name>MAX_INTERPOLATION_DEPTH</Name>
101.558 - while <Name>depth</Name>: # Loop through this until it's done
101.559 - <Name>depth</Name> -= 1
101.560 - if <Attribute><Name>value</Name></Attribute>.<Call>find</Call>("%(") != -1:
101.561 - try:
101.562 - <Name>value</Name> = <Name>value</Name> % <Name>vars</Name>
101.563 - except <Name>KeyError</Name>, <Name>e</Name>:
101.564 - raise <Call><Name>InterpolationMissingOptionError</Name></Call>(
101.565 - <Name>option</Name>, <Name>section</Name>, <Name>rawval</Name>, <Name>e</Name>[0])
101.566 - else:
101.567 - break
101.568 - if <Attribute><Name>value</Name></Attribute>.<Call>find</Call>("%(") != -1:
101.569 - raise <Call><Name>InterpolationDepthError</Name></Call>(<Name>option</Name>, <Name>section</Name>, <Name>rawval</Name>)
101.570 - return <Name>value</Name>
101.571 -
101.572 -
101.573 -class <ClassDef>SafeConfigParser</ClassDef>(<Name>ConfigParser</Name>):
101.574 -
101.575 - def <FunctionDef>_interpolate</FunctionDef>(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>, <Name>rawval</Name>, <Name>vars</Name>):
101.576 - # do the string interpolation
101.577 - <Name>L</Name> = []
101.578 - <Attribute><Name>self</Name></Attribute>.<Call>_interpolate_some</Call>(<Name>option</Name>, <Name>L</Name>, <Name>rawval</Name>, <Name>section</Name>, <Name>vars</Name>, 1)
101.579 - return <Attribute>''</Attribute>.<Call>join</Call>(<Name>L</Name>)
101.580 -
101.581 - <Name>_interpvar_match</Name> = <Attribute><Name>re</Name></Attribute>.<Attribute><Call>compile</Call></Attribute>(r"%\(([^)]+)\)s").match
101.582 -
101.583 - def <FunctionDef>_interpolate_some</FunctionDef>(<Name>self</Name>, <Name>option</Name>, <Name>accum</Name>, <Name>rest</Name>, <Name>section</Name>, <Name>map</Name>, <Name>depth</Name>):
101.584 - if <Name>depth</Name> > <Name>MAX_INTERPOLATION_DEPTH</Name>:
101.585 - raise <Call><Name>InterpolationDepthError</Name></Call>(<Name>option</Name>, <Name>section</Name>, <Name>rest</Name>)
101.586 - while <Name>rest</Name>:
101.587 - <Name>p</Name> = <Attribute><Name>rest</Name></Attribute>.<Call>find</Call>("%")
101.588 - if <Name>p</Name> < 0:
101.589 - <Attribute><Name>accum</Name></Attribute>.<Call>append</Call>(<Name>rest</Name>)
101.590 - return
101.591 - if <Name>p</Name> > 0:
101.592 - <Attribute><Name>accum</Name></Attribute>.<Call>append</Call>(<Name>rest</Name>[:<Name>p</Name>])
101.593 - <Name>rest</Name> = <Name>rest</Name>[<Name>p</Name>:]
101.594 - # p is no longer used
101.595 - <Name>c</Name> = <Name>rest</Name>[1:2]
101.596 - if <Name>c</Name> == "%":
101.597 - <Attribute><Name>accum</Name></Attribute>.<Call>append</Call>("%")
101.598 - <Name>rest</Name> = <Name>rest</Name>[2:]
101.599 - elif <Name>c</Name> == "(":
101.600 - <Name>m</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_interpvar_match</Call>(<Name>rest</Name>)
101.601 - if <Name>m</Name> is <Name>None</Name>:
101.602 - raise <Call><Name>InterpolationSyntaxError</Name></Call>(<Name>option</Name>, <Name>section</Name>,
101.603 - "bad interpolation variable reference %r" % <Name>rest</Name>)
101.604 - <Name>var</Name> = <Attribute><Name>m</Name></Attribute>.<Call>group</Call>(1)
101.605 - <Name>rest</Name> = <Name>rest</Name>[<Attribute><Name>m</Name></Attribute>.<Call>end</Call>():]
101.606 - try:
101.607 - <Name>v</Name> = <Name>map</Name>[<Name>var</Name>]
101.608 - except <Name>KeyError</Name>:
101.609 - raise <Call><Name>InterpolationMissingOptionError</Name></Call>(
101.610 - <Name>option</Name>, <Name>section</Name>, <Name>rest</Name>, <Name>var</Name>)
101.611 - if "%" in <Name>v</Name>:
101.612 - <Attribute><Name>self</Name></Attribute>.<Call>_interpolate_some</Call>(<Name>option</Name>, <Name>accum</Name>, <Name>v</Name>,
101.613 - <Name>section</Name>, <Name>map</Name>, <Name>depth</Name> + 1)
101.614 - else:
101.615 - <Attribute><Name>accum</Name></Attribute>.<Call>append</Call>(<Name>v</Name>)
101.616 - else:
101.617 - raise <Call><Name>InterpolationSyntaxError</Name></Call>(
101.618 - <Name>option</Name>, <Name>section</Name>,
101.619 - "'%' must be followed by '%' or '(', found: " + `<Name>ret</Name>`)
102.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.offsets Sun Jan 04 13:11:53 2015 -0600
102.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
102.3 @@ -1,616 +0,0 @@
102.4 -
102.5 -<Module><Expr><Str>"""Configuration file parser.
102.6 -
102.7 -A setup file consists of sections, lead by a "[section]" header,
102.8 -and followed by "name: value" entries, with continuations and such in
102.9 -the style of RFC 822.
102.10 -
102.11 - the same section, or values in a special [DEFAULT] section.
102.12 -
102.13 -For example:
102.14 -
102.15 - something: %(dir)s/whatever
102.16 -
102.17 -would resolve the "%(dir)s" to the value of dir. All reference
102.18 -expansions are done late, on demand.
102.19 -
102.20 -Intrinsic defaults can be specified by passing them into the
102.21 -ConfigParser constructor as a dictionary.
102.22 -
102.23 -class:
102.24 -
102.25 -ConfigParser -- responsible for parsing a list of
102.26 - configuration files, and managing the parsed database.
102.27 -
102.28 - methods:
102.29 -
102.30 - __init__(defaults=None)
102.31 - create the parser and specify a dictionary of intrinsic defaults. The
102.32 - keys must be strings, the values must be appropriate for %()s string
102.33 - interpolation. Note that `__name__' is always an intrinsic default;
102.34 - it's value is the section's name.
102.35 -
102.36 - sections()
102.37 - return all the configuration section names, sans DEFAULT
102.38 -
102.39 - has_section(section)
102.40 - return whether the given section exists
102.41 -
102.42 - has_option(section, option)
102.43 - return whether the given option exists in the given section
102.44 -
102.45 - options(section)
102.46 - return list of configuration options for the named section
102.47 -
102.48 - read(filenames)
102.49 - read and parse the list of named configuration files, given by
102.50 - name. A single filename is also allowed. Non-existing files
102.51 - are ignored.
102.52 -
102.53 - readfp(fp, filename=None)
102.54 - read and parse one configuration file, given as a file object.
102.55 - The filename defaults to fp.name; it is only used in error
102.56 - messages (if fp has no `name' attribute, the string `<???>' is used).
102.57 -
102.58 - get(section, option, raw=False, vars=None)
102.59 - return a string value for the named option. All % interpolations are
102.60 - expanded in the return values, based on the defaults passed into the
102.61 - constructor and the DEFAULT section. Additional substitutions may be
102.62 - provided using the `vars' argument, which must be a dictionary whose
102.63 - contents override any pre-existing defaults.
102.64 -
102.65 - getint(section, options)
102.66 - like get(), but convert value to an integer
102.67 -
102.68 - getfloat(section, options)
102.69 - like get(), but convert value to a float
102.70 -
102.71 - getboolean(section, options)
102.72 - like get(), but convert value to a boolean (currently case
102.73 - insensitively defined as 0, false, no, off for False, and 1, true,
102.74 - yes, on for True). Returns False or True.
102.75 -
102.76 - items(section, raw=False, vars=None)
102.77 - return a list of tuples with (name, value) for each option
102.78 - in the section.
102.79 -
102.80 - remove_section(section)
102.81 - remove the given file section and all its options
102.82 -
102.83 - remove_option(section, option)
102.84 - remove the given option from the given section
102.85 -
102.86 - set(section, option, value)
102.87 - set the given option
102.88 -
102.89 - write(fp)
102.90 - write the configuration state in .ini format
102.91 -"""</Str></Expr>
102.92 -
102.93 -<Import>import re</Import>
102.94 -
102.95 -<Assign><Name>__all__</Name> = <List>[<Str>"NoSectionError"</Str>, <Str>"DuplicateSectionError"</Str>, <Str>"NoOptionError"</Str>,
102.96 - <Str>"InterpolationError"</Str>, <Str>"InterpolationDepthError"</Str>,
102.97 - <Str>"InterpolationSyntaxError"</Str>, <Str>"ParsingError"</Str>,
102.98 - <Str>"MissingSectionHeaderError"</Str>, <Str>"ConfigParser"</Str>, <Str>"SafeConfigParser"</Str>,
102.99 - <Str>"DEFAULTSECT"</Str>, <Str>"MAX_INTERPOLATION_DEPTH"</Str>]</List></Assign>
102.100 -
102.101 -<Assign><Name>DEFAULTSECT</Name> = <Str>"DEFAULT"</Str></Assign>
102.102 -
102.103 -<Assign><Name>MAX_INTERPOLATION_DEPTH</Name> = <Num>10</Num></Assign>
102.104 -
102.105 -
102.106 -
102.107 -# exception classes
102.108 -<ClassDef>class Error(<Name>Exception</Name>):
102.109 - <Expr><Str>"""Base class for ConfigParser exceptions."""</Str></Expr>
102.110 -
102.111 - <FunctionDef>def __init__(<Name>self</Name>, <Name>msg</Name>=<Str>''</Str>):
102.112 - <Assign><Attribute><Name>self</Name>.message</Attribute> = <Name>msg</Name></Assign>
102.113 - <Expr><Call><Attribute><Name>Exception</Name>.__init__</Attribute>(<Name>self</Name>, <Name>msg</Name>)</Call></Expr>
102.114 -
102.115 - </FunctionDef> <FunctionDef>def __repr__(<Name>self</Name>):
102.116 - <Return>return <Attribute><Name>self</Name>.message</Attribute></Return>
102.117 -
102.118 - </FunctionDef> <Assign><Name>__str__</Name> = <Name>__repr__</Name></Assign>
102.119 -
102.120 -</ClassDef><ClassDef>class NoSectionError(<Name>Error</Name>):
102.121 - <Expr><Str>"""Rasssised when no section matches a requested option."""</Str></Expr>
102.122 -
102.123 - <FunctionDef>def __init__(<Name>self</Name>, <Name>section</Name>):
102.124 - <Expr><Call><Attribute><Name>Error</Name>.__init__</Attribute>(<Name>self</Name>, <BinOp><Str>'No section: '</Str> + <Repr>`<Name>section</Name>`</Repr></BinOp>)</Call></Expr>
102.125 - <Assign><Attribute><Name>self</Name>.section</Attribute> = <Name>section</Name></Assign>
102.126 -
102.127 -</FunctionDef></ClassDef><ClassDef>class DuplicateSectionError(<Name>Error</Name>):
102.128 - <Expr><Str>"""Raised when a section is multiply-created."""</Str></Expr>
102.129 -
102.130 - <FunctionDef>def __init__(<Name>self</Name>, <Name>section</Name>):
102.131 - <Expr><Call><Attribute><Name>Error</Name>.__init__</Attribute>(<Name>self</Name>, <BinOp><Str>"Section %r already exists"</Str> % <Name>section</Name></BinOp>)</Call></Expr>
102.132 - <Assign><Attribute><Name>self</Name>.section</Attribute> = <Name>section</Name></Assign>
102.133 -
102.134 -</FunctionDef></ClassDef><ClassDef>class NoOptionError(<Name>Error</Name>):
102.135 - <Expr><Str>"""A requested option was not found."""</Str></Expr>
102.136 -
102.137 - <FunctionDef>def __init__(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>):
102.138 - <Expr><Call><Attribute><Name>Error</Name>.__init__</Attribute>(<Name>self</Name>, <BinOp><Str>"No option %r in section: %r"</Str> %
102.139 - <Tuple>(<Name>option</Name>, <Name>section</Name>)</Tuple></BinOp>)</Call></Expr>
102.140 - <Assign><Attribute><Name>self</Name>.option</Attribute> = <Name>option</Name></Assign>
102.141 - <Assign><Attribute><Name>self</Name>.section</Attribute> = <Name>section</Name></Assign>
102.142 -
102.143 -</FunctionDef></ClassDef><ClassDef>class InterpolationError(<Name>Error</Name>):
102.144 - <Expr><Str>"""Base class for interpolation-related exceptions."""</Str></Expr>
102.145 -
102.146 - <FunctionDef>def __init__(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>msg</Name>):
102.147 - <Expr><Call><Attribute><Name>Error</Name>.__init__</Attribute>(<Name>self</Name>, <Name>msg</Name>)</Call></Expr>
102.148 - <Assign><Attribute><Name>self</Name>.option</Attribute> = <Name>option</Name></Assign>
102.149 - <Assign><Attribute><Name>self</Name>.section</Attribute> = <Name>section</Name></Assign>
102.150 -
102.151 -</FunctionDef></ClassDef><ClassDef>class InterpolationMissingOptionError(<Name>InterpolationError</Name>):
102.152 - <Expr><Str>"""A string substitution required a setting which was not available."""</Str></Expr>
102.153 -
102.154 - <FunctionDef>def __init__(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>rawval</Name>, <Name>reference</Name>):
102.155 - <Assign><Name>msg</Name> = <BinOp>(<Str>"Bad value substitution:\n"
102.156 - "\tsection: [%s]\n"
102.157 - "\toption : %s\n"
102.158 - "\tkey : %s\n"
102.159 - "\trawval : %s\n"</Str>
102.160 - % <Tuple>(<Name>section</Name>, <Name>option</Name>, <Name>reference</Name>, <Name>rawval</Name>)</Tuple>)</BinOp></Assign>
102.161 - <Expr><Call><Attribute><Name>InterpolationError</Name>.__init__</Attribute>(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>msg</Name>)</Call></Expr>
102.162 - <Assign><Attribute><Name>self</Name>.reference</Attribute> = <Name>reference</Name></Assign>
102.163 -
102.164 -</FunctionDef></ClassDef><ClassDef>class InterpolationSyntaxError(<Name>InterpolationError</Name>):
102.165 - <Expr><Str>"""Raised when the source text into which substitutions are made
102.166 - does not conform to the required syntax."""</Str></Expr>
102.167 -
102.168 -</ClassDef><ClassDef>class InterpolationDepthError(<Name>InterpolationError</Name>):
102.169 - <Expr><Str>"""Raised when substitutions are nested too deeply."""</Str></Expr>
102.170 -
102.171 - <FunctionDef>def __init__(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>rawval</Name>):
102.172 - <Assign><Name>msg</Name> = <BinOp>(<Str>"Value interpolation too deeply recursive:\n"
102.173 - "\tsection: [%s]\n"
102.174 - "\toption : %s\n"
102.175 - "\trawval : %s\n"</Str>
102.176 - % <Tuple>(<Name>section</Name>, <Name>option</Name>, <Name>rawval</Name>)</Tuple>)</BinOp></Assign>
102.177 - <Expr><Call><Attribute><Name>InterpolationError</Name>.__init__</Attribute>(<Name>self</Name>, <Name>option</Name>, <Name>section</Name>, <Name>msg</Name>)</Call></Expr>
102.178 -
102.179 -</FunctionDef></ClassDef><ClassDef>class ParsingError(<Name>Error</Name>):
102.180 - <Expr><Str>"""Raised when a configuration file does not follow legal syntax."""</Str></Expr>
102.181 -
102.182 - <FunctionDef>def __init__(<Name>self</Name>, <Name>filename</Name>):
102.183 - <Expr><Call><Attribute><Name>Error</Name>.__init__</Attribute>(<Name>self</Name>, <BinOp><Str>'File contains parsing errors: %s'</Str> % <Name>filename</Name></BinOp>)</Call></Expr>
102.184 - <Assign><Attribute><Name>self</Name>.filename</Attribute> = <Name>filename</Name></Assign>
102.185 - <Assign><Attribute><Name>self</Name>.errors</Attribute> = <List>[]</List></Assign>
102.186 -
102.187 - </FunctionDef> <FunctionDef>def append(<Name>self</Name>, <Name>lineno</Name>, <Name>line</Name>):
102.188 - <Expr><Call><Attribute><Attribute><Name>self</Name>.errors</Attribute>.append</Attribute>(<Tuple>(<Name>lineno</Name>, <Name>line</Name>)</Tuple>)</Call></Expr>
102.189 - <AugAssign><Attribute><Name>self</Name>.message</Attribute> += <BinOp><Str>'\n\t[line %2d]: %s'</Str> % <Tuple>(<Name>lineno</Name>, <Name>line</Name>)</Tuple></BinOp></AugAssign>
102.190 -
102.191 -</FunctionDef></ClassDef><ClassDef>class MissingSectionHeaderError(<Name>ParsingError</Name>):
102.192 - <Expr><Str>"""Raised when a key-value pair is found before any section header."""</Str></Expr>
102.193 -
102.194 - <FunctionDef>def __init__(<Name>self</Name>, <Name>filename</Name>, <Name>lineno</Name>, <Name>line</Name>):
102.195 - <Expr><Call><Attribute><Name>Error</Name>.__init__</Attribute>(
102.196 - <Name>self</Name>,
102.197 - <BinOp><Str>'File contains no section headers.\nfile: %s, line: %d\n%s'</Str> %
102.198 - <Tuple>(<Name>filename</Name>, <Name>lineno</Name>, <Name>line</Name>)</Tuple></BinOp>)</Call></Expr>
102.199 - <Assign><Attribute><Name>self</Name>.filename</Attribute> = <Name>filename</Name></Assign>
102.200 - <Assign><Attribute><Name>self</Name>.lineno</Attribute> = <Name>lineno</Name></Assign>
102.201 - <Assign><Attribute><Name>self</Name>.line</Attribute> = <Name>line</Name></Assign>
102.202 -
102.203 -
102.204 -
102.205 -</FunctionDef></ClassDef><ClassDef>class RawConfigParser:
102.206 - <FunctionDef>def __init__(<Name>self</Name>, <Name>defaults</Name>=<Name>None</Name>):
102.207 - <Assign><Attribute><Name>self</Name>._sections</Attribute> = <Dict>{}</Dict></Assign>
102.208 - <If>if <Compare><Name>defaults</Name> is <Name>None</Name></Compare>:
102.209 - <Assign><Attribute><Name>self</Name>._defaults</Attribute> = <Dict>{}</Dict></Assign>
102.210 - else:
102.211 - <Assign><Attribute><Name>self</Name>._defaults</Attribute> = <Name>defaults</Name></Assign>
102.212 -
102.213 - </If></FunctionDef> <FunctionDef>def defaults(<Name>self</Name>):
102.214 - <Return>return <Attribute><Name>self</Name>._defaults</Attribute></Return>
102.215 -
102.216 - </FunctionDef> <FunctionDef>def sections(<Name>self</Name>):
102.217 - <Expr><Str>"""Return a list of section names, excluding [DEFAULT]"""</Str></Expr>
102.218 - # self._sections will never have [DEFAULT] in it
102.219 - <Return>return <Call><Attribute><Attribute><Name>self</Name>._sections</Attribute>.keys</Attribute>()</Call></Return>
102.220 -
102.221 - </FunctionDef> <FunctionDef>def add_section(<Name>self</Name>, <Name>section</Name>):
102.222 - <Expr><Str>"""Create a new section in the configuration.
102.223 -
102.224 - Raise DuplicateSectionError if a section by the specified name
102.225 - already exists.
102.226 - """</Str></Expr>
102.227 - <If>if <Compare><Name>section</Name> in <Attribute><Name>self</Name>._sections</Attribute></Compare>:
102.228 - <Raise>raise <Call><Name>DuplicateSectionError</Name>(<Name>section</Name>)</Call></Raise>
102.229 - </If> <Assign><Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>section</Name></Index>]</Subscript> = <Dict>{}</Dict></Assign>
102.230 -
102.231 - </FunctionDef> <FunctionDef>def has_section(<Name>self</Name>, <Name>section</Name>):
102.232 - <Expr><Str>"""Indicate whether the named section is present in the configuration.
102.233 -
102.234 - The DEFAULT section is not acknowledged.
102.235 - """</Str></Expr>
102.236 - <Return>return <Compare><Name>section</Name> in <Attribute><Name>self</Name>._sections</Attribute></Compare></Return>
102.237 -
102.238 - </FunctionDef> <FunctionDef>def options(<Name>self</Name>, <Name>section</Name>):
102.239 - <Expr><Str>"""Return a list of option names for the given section name."""</Str></Expr>
102.240 - <TryExcept>try:
102.241 - <Assign><Name>opts</Name> = <Call><Attribute><Name>self</Name>._sections</Attribute><Attribute><Subscript>[<Index><Name>section</Name></Index>]</Subscript>.copy</Attribute>()</Call></Assign>
102.242 - <ExceptHandler>except <Name>KeyError</Name>:
102.243 - <Raise>raise <Call><Name>NoSectionError</Name>(<Name>section</Name>)</Call></Raise>
102.244 - </ExceptHandler></TryExcept> <Expr><Call><Attribute><Name>opts</Name>.update</Attribute>(<Attribute><Name>self</Name>._defaults</Attribute>)</Call></Expr>
102.245 - <If>if <Compare><Str>'__name__'</Str> in <Name>opts</Name></Compare>:
102.246 - <Delete>del <Subscript><Name>opts</Name>[<Index><Str>'__name__'</Str></Index>]</Subscript></Delete>
102.247 - </If> <Return>return <Call><Attribute><Name>opts</Name>.keys</Attribute>()</Call></Return>
102.248 -
102.249 - </FunctionDef> <FunctionDef>def read(<Name>self</Name>, <Name>filenames</Name>):
102.250 - <Expr><Str>"""Read and parse a filename or a list of filenames.
102.251 -
102.252 - Files that cannot be opened are silently ignored; this is
102.253 - designed so that you can specify a list of potential
102.254 - configuration file locations (e.g. current directory, user's
102.255 - home directory, systemwide directory), and all existing
102.256 - configuration files in the list will be read. A single
102.257 - filename may also be given.
102.258 - """</Str></Expr>
102.259 - <If>if <Call><Name>isinstance</Name>(<Name>filenames</Name>, <Name>basestring</Name>)</Call>:
102.260 - <Assign><Name>filenames</Name> = <List>[<Name>filenames</Name>]</List></Assign>
102.261 - </If> <For>for <Name>filename</Name> in <Name>filenames</Name>:
102.262 - <TryExcept>try:
102.263 - <Assign><Name>fp</Name> = <Call><Name>open</Name>(<Name>filename</Name>)</Call></Assign>
102.264 - <ExceptHandler>except <Name>IOError</Name>:
102.265 - <Continue>continue</Continue>
102.266 - </ExceptHandler></TryExcept> <Expr><Call><Attribute><Name>self</Name>._read</Attribute>(<Name>fp</Name>, <Name>filename</Name>)</Call></Expr>
102.267 - <Expr><Call><Attribute><Name>fp</Name>.close</Attribute>()</Call></Expr>
102.268 -
102.269 - </For></FunctionDef> <FunctionDef>def readfp(<Name>self</Name>, <Name>fp</Name>, <Name>filename</Name>=<Name>None</Name>):
102.270 - <Expr><Str>"""Like read() but the argument must be a file-like object.
102.271 -
102.272 - The `fp' argument must have a `readline' method. Optional
102.273 - second argument is the `filename', which if not given, is
102.274 - taken from fp.name. If fp has no `name' attribute, `<???>' is
102.275 - used.
102.276 -
102.277 - """</Str></Expr>
102.278 - <If>if <Compare><Name>filename</Name> is <Name>None</Name></Compare>:
102.279 - <TryExcept>try:
102.280 - <Assign><Name>filename</Name> = <Attribute><Name>fp</Name>.name</Attribute></Assign>
102.281 - <ExceptHandler>except <Name>AttributeError</Name>:
102.282 - <Assign><Name>filename</Name> = <Str>'<???>'</Str></Assign>
102.283 - </ExceptHandler></TryExcept></If> <Expr><Call><Attribute><Name>self</Name>._read</Attribute>(<Name>fp</Name>, <Name>filename</Name>)</Call></Expr>
102.284 -
102.285 - </FunctionDef> <FunctionDef>def get(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
102.286 - <Assign><Name>opt</Name> = <Call><Attribute><Name>self</Name>.optionxform</Attribute>(<Name>option</Name>)</Call></Assign>
102.287 - <If>if <Compare><Name>section</Name> not in <Attribute><Name>self</Name>._sections</Attribute></Compare>:
102.288 - <If>if <Compare><Name>section</Name> != <Name>DEFAULTSECT</Name></Compare>:
102.289 - <Raise>raise <Call><Name>NoSectionError</Name>(<Name>section</Name>)</Call></Raise>
102.290 - </If> <If>if <Compare><Name>opt</Name> in <Attribute><Name>self</Name>._defaults</Attribute></Compare>:
102.291 - <Return>return <Subscript><Attribute><Name>self</Name>._defaults</Attribute>[<Index><Name>opt</Name></Index>]</Subscript></Return>
102.292 - else:
102.293 - <Raise>raise <Call><Name>NoOptionError</Name>(<Name>option</Name>, <Name>section</Name>)</Call></Raise>
102.294 - </If> <If>elif <Compare><Name>opt</Name> in <Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>section</Name></Index>]</Subscript></Compare>:
102.295 - <Return>return <Subscript><Attribute><Name>self</Name>._sections</Attribute><Subscript>[<Index><Name>section</Name></Index>]</Subscript>[<Index><Name>opt</Name></Index>]</Subscript></Return>
102.296 - <If>elif <Compare><Name>opt</Name> in <Attribute><Name>self</Name>._defaults</Attribute></Compare>:
102.297 - <Return>return <Subscript><Attribute><Name>self</Name>._defaults</Attribute>[<Index><Name>opt</Name></Index>]</Subscript></Return>
102.298 - else:
102.299 - <Raise>raise <Call><Name>NoOptionError</Name>(<Name>option</Name>, <Name>section</Name>)</Call></Raise>
102.300 -
102.301 - </If></If></If></FunctionDef> <FunctionDef>def items(<Name>self</Name>, <Name>section</Name>):
102.302 - <TryExcept>try:
102.303 - <Assign><Name>d2</Name> = <Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>section</Name></Index>]</Subscript></Assign>
102.304 - <ExceptHandler>except <Name>KeyError</Name>:
102.305 - <If>if <Compare><Name>section</Name> != <Name>DEFAULTSECT</Name></Compare>:
102.306 - <Raise>raise <Call><Name>NoSectionError</Name>(<Name>section</Name>)</Call></Raise>
102.307 - </If> <Assign><Name>d2</Name> = <Dict>{}</Dict></Assign>
102.308 - </ExceptHandler></TryExcept> <Assign><Name>d</Name> = <Call><Attribute><Attribute><Name>self</Name>._defaults</Attribute>.copy</Attribute>()</Call></Assign>
102.309 - <Expr><Call><Attribute><Name>d</Name>.update</Attribute>(<Name>d2</Name>)</Call></Expr>
102.310 - <If>if <Compare><Str>"__name__"</Str> in <Name>d</Name></Compare>:
102.311 - <Delete>del <Subscript><Name>d</Name>[<Index><Str>"__name__"</Str></Index>]</Subscript></Delete>
102.312 - </If> <Return>return <Call><Attribute><Name>d</Name>.items</Attribute>()</Call></Return>
102.313 -
102.314 - </FunctionDef> <FunctionDef>def _get(<Name>self</Name>, <Name>section</Name>, <Name>conv</Name>, <Name>option</Name>):
102.315 - <Return>return <Call><Name>conv</Name>(<Call><Attribute><Name>self</Name>.get</Attribute>(<Name>section</Name>, <Name>option</Name>)</Call>)</Call></Return>
102.316 -
102.317 - </FunctionDef> <FunctionDef>def getint(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
102.318 - <Return>return <Call><Attribute><Name>self</Name>._get</Attribute>(<Name>section</Name>, <Name>int</Name>, <Name>option</Name>)</Call></Return>
102.319 -
102.320 - </FunctionDef> <FunctionDef>def getfloat(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
102.321 - <Return>return <Call><Attribute><Name>self</Name>._get</Attribute>(<Name>section</Name>, <Name>float</Name>, <Name>option</Name>)</Call></Return>
102.322 -
102.323 - </FunctionDef> <Assign><Name>_boolean_states</Name> = <Dict>{<Str>'1'</Str>: <Name>True</Name>, <Str>'yes'</Str>: <Name>True</Name>, <Str>'true'</Str>: <Name>True</Name>, <Str>'on'</Str>: <Name>True</Name>,
102.324 - <Str>'0'</Str>: <Name>False</Name>, <Str>'no'</Str>: <Name>False</Name>, <Str>'false'</Str>: <Name>False</Name>, <Str>'off'</Str>: <Name>False</Name>}</Dict></Assign>
102.325 -
102.326 - <FunctionDef>def getboolean(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
102.327 - <Assign><Name>v</Name> = <Call><Attribute><Name>self</Name>.get</Attribute>(<Name>section</Name>, <Name>option</Name>)</Call></Assign>
102.328 - <If>if <Compare><Call><Attribute><Name>v</Name>.lower</Attribute>()</Call> not in <Attribute><Name>self</Name>._boolean_states</Attribute></Compare>:
102.329 - <Raise>raise <Name>ValueError</Name>, <BinOp><Str>'Not a boolean: %s'</Str> % <Name>v</Name></BinOp></Raise>
102.330 - </If> <Return>return <Subscript><Attribute><Name>self</Name>._boolean_states</Attribute>[<Index><Call><Attribute><Name>v</Name>.lower</Attribute>()</Call></Index>]</Subscript></Return>
102.331 -
102.332 - </FunctionDef> <FunctionDef>def optionxform(<Name>self</Name>, <Name>optionstr</Name>):
102.333 - <Return>return <Call><Attribute><Name>optionstr</Name>.lower</Attribute>()</Call></Return>
102.334 -
102.335 - </FunctionDef> <FunctionDef>def has_option(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
102.336 - <Expr><Str>"""Check for the existence of a given option in a given section."""</Str></Expr>
102.337 - <If>if <BoolOp><UnaryOp>not <Name>section</Name></UnaryOp> or <Compare><Name>section</Name> == <Name>DEFAULTSECT</Name></Compare></BoolOp>:
102.338 - <Assign><Name>option</Name> = <Call><Attribute><Name>self</Name>.optionxform</Attribute>(<Name>option</Name>)</Call></Assign>
102.339 - <Return>return <Compare><Name>option</Name> in <Attribute><Name>self</Name>._defaults</Attribute></Compare></Return>
102.340 - <If>elif <Compare><Name>section</Name> not in <Attribute><Name>self</Name>._sections</Attribute></Compare>:
102.341 - <Return>return <Name>False</Name></Return>
102.342 - else:
102.343 - <Assign><Name>option</Name> = <Call><Attribute><Name>self</Name>.optionxform</Attribute>(<Name>option</Name>)</Call></Assign>
102.344 - <Return>return <BoolOp>(<Compare><Name>option</Name> in <Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>section</Name></Index>]</Subscript></Compare>
102.345 - or <Compare><Name>option</Name> in <Attribute><Name>self</Name>._defaults</Attribute></Compare>)</BoolOp></Return>
102.346 -
102.347 - </If></If></FunctionDef> <FunctionDef>def set(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>, <Name>value</Name>):
102.348 - <Expr><Str>"""Set an option."""</Str></Expr>
102.349 - <If>if <BoolOp><UnaryOp>not <Name>section</Name></UnaryOp> or <Compare><Name>section</Name> == <Name>DEFAULTSECT</Name></Compare></BoolOp>:
102.350 - <Assign><Name>sectdict</Name> = <Attribute><Name>self</Name>._defaults</Attribute></Assign>
102.351 - else:
102.352 - <TryExcept>try:
102.353 - <Assign><Name>sectdict</Name> = <Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>section</Name></Index>]</Subscript></Assign>
102.354 - <ExceptHandler>except <Name>KeyError</Name>:
102.355 - <Raise>raise <Call><Name>NoSectionError</Name>(<Name>section</Name>)</Call></Raise>
102.356 - </ExceptHandler></TryExcept></If> <Assign><Subscript><Name>sectdict</Name>[<Index><Call><Attribute><Name>self</Name>.optionxform</Attribute>(<Name>option</Name>)</Call></Index>]</Subscript> = <Name>value</Name></Assign>
102.357 -
102.358 - </FunctionDef> <FunctionDef>def write(<Name>self</Name>, <Name>fp</Name>):
102.359 - <Expr><Str>"""Write an .ini-format representation of the configuration state."""</Str></Expr>
102.360 - <If>if <Attribute><Name>self</Name>._defaults</Attribute>:
102.361 - <Expr><Call><Attribute><Name>fp</Name>.write</Attribute>(<BinOp><Str>"[%s]\n"</Str> % <Name>DEFAULTSECT</Name></BinOp>)</Call></Expr>
102.362 - <For>for <Tuple>(<Name>key</Name>, <Name>value</Name>)</Tuple> in <Call><Attribute><Attribute><Name>self</Name>._defaults</Attribute>.items</Attribute>()</Call>:
102.363 - <Expr><Call><Attribute><Name>fp</Name>.write</Attribute>(<BinOp><Str>"%s = %s\n"</Str> % <Tuple>(<Name>key</Name>, <Call><Name>str</Name><Attribute><Call>(<Name>value</Name>)</Call>.replace</Attribute>(<Str>'\n'</Str>, <Str>'\n\t'</Str>)</Call>)</Tuple></BinOp>)</Call></Expr>
102.364 - </For> <Expr><Call><Attribute><Name>fp</Name>.write</Attribute>(<Str>"\n"</Str>)</Call></Expr>
102.365 - </If> <For>for <Name>section</Name> in <Attribute><Name>self</Name>._sections</Attribute>:
102.366 - <Expr><Call><Attribute><Name>fp</Name>.write</Attribute>(<BinOp><Str>"[%s]\n"</Str> % <Name>section</Name></BinOp>)</Call></Expr>
102.367 - <For>for <Tuple>(<Name>key</Name>, <Name>value</Name>)</Tuple> in <Call><Attribute><Name>self</Name>._sections</Attribute><Attribute><Subscript>[<Index><Name>section</Name></Index>]</Subscript>.items</Attribute>()</Call>:
102.368 - <If>if <Compare><Name>key</Name> != <Str>"__name__"</Str></Compare>:
102.369 - <Expr><Call><Attribute><Name>fp</Name>.write</Attribute>(<BinOp><Str>"%s = %s\n"</Str> %
102.370 - <Tuple>(<Name>key</Name>, <Call><Name>str</Name><Attribute><Call>(<Name>value</Name>)</Call>.replace</Attribute>(<Str>'\n'</Str>, <Str>'\n\t'</Str>)</Call>)</Tuple></BinOp>)</Call></Expr>
102.371 - </If></For> <Expr><Call><Attribute><Name>fp</Name>.write</Attribute>(<Str>"\n"</Str>)</Call></Expr>
102.372 -
102.373 - </For></FunctionDef> <FunctionDef>def remove_option(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>):
102.374 - <Expr><Str>"""Remove an option."""</Str></Expr>
102.375 - <If>if <BoolOp><UnaryOp>not <Name>section</Name></UnaryOp> or <Compare><Name>section</Name> == <Name>DEFAULTSECT</Name></Compare></BoolOp>:
102.376 - <Assign><Name>sectdict</Name> = <Attribute><Name>self</Name>._defaults</Attribute></Assign>
102.377 - else:
102.378 - <TryExcept>try:
102.379 - <Assign><Name>sectdict</Name> = <Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>section</Name></Index>]</Subscript></Assign>
102.380 - <ExceptHandler>except <Name>KeyError</Name>:
102.381 - <Raise>raise <Call><Name>NoSectionError</Name>(<Name>section</Name>)</Call></Raise>
102.382 - </ExceptHandler></TryExcept></If> <Assign><Name>option</Name> = <Call><Attribute><Name>self</Name>.optionxform</Attribute>(<Name>option</Name>)</Call></Assign>
102.383 - <Assign><Name>existed</Name> = <Compare><Name>option</Name> in <Name>sectdict</Name></Compare></Assign>
102.384 - <If>if <Name>existed</Name>:
102.385 - <Delete>del <Subscript><Name>sectdict</Name>[<Index><Name>option</Name></Index>]</Subscript></Delete>
102.386 - </If> <Return>return <Name>existed</Name></Return>
102.387 -
102.388 - </FunctionDef> <FunctionDef>def remove_section(<Name>self</Name>, <Name>section</Name>):
102.389 - <Expr><Str>"""Remove a file section."""</Str></Expr>
102.390 - <Assign><Name>existed</Name> = <Compare><Name>section</Name> in <Attribute><Name>self</Name>._sections</Attribute></Compare></Assign>
102.391 - <If>if <Name>existed</Name>:
102.392 - <Delete>del <Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>section</Name></Index>]</Subscript></Delete>
102.393 - </If> <Return>return <Name>existed</Name></Return>
102.394 -
102.395 - #
102.396 - # Regular expressions for parsing section headers and options.
102.397 - #
102.398 - </FunctionDef> <Assign><Name>SECTCRE</Name> = <Call><Attribute><Name>re</Name>.compile</Attribute>(
102.399 - <Str>r'\[' # [
102.400 - r'(?P<header>[^]]+)' # very permissive!
102.401 - r'\]'</Str> # ]
102.402 - )</Call></Assign>
102.403 - <Assign><Name>OPTCRE</Name> = <Call><Attribute><Name>re</Name>.compile</Attribute>(
102.404 - <Str>r'(?P<option>[^:=\s][^:=]*)' # very permissive!
102.405 - r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
102.406 - # followed by separator
102.407 - # (either : or =), followed
102.408 - # by any # space/tab
102.409 - r'(?P<value>.*)$'</Str> # everything up to eol
102.410 - )</Call></Assign>
102.411 -
102.412 - <FunctionDef>def _read(<Name>self</Name>, <Name>fp</Name>, <Name>fpname</Name>):
102.413 - <Expr><Str>"""Parse a sectioned setup file.
102.414 -
102.415 - The sections in setup file contains a title line at the top,
102.416 - indicated by a name in square brackets (`[]'), plus key/value
102.417 - options lines, indicated by `name: value' format lines.
102.418 - Continuations are represented by an embedded newline then
102.419 - leading whitespace. Blank lines, lines beginning with a '#',
102.420 - and just about everything else are ignored.
102.421 - """</Str></Expr>
102.422 - <Assign><Name>cursect</Name> = <Name>None</Name></Assign> # None, or a dictionary
102.423 - <Assign><Name>optname</Name> = <Name>None</Name></Assign>
102.424 - <Assign><Name>lineno</Name> = <Num>0</Num></Assign>
102.425 - <Assign><Name>e</Name> = <Name>None</Name></Assign> # None, or an exception
102.426 - <While>while <Name>True</Name>:
102.427 - <Assign><Name>line</Name> = <Call><Attribute><Name>fp</Name>.readline</Attribute>()</Call></Assign>
102.428 - <If>if <UnaryOp>not <Name>line</Name></UnaryOp>:
102.429 - <Break>break</Break>
102.430 - </If> <Assign><Name>lineno</Name> = <BinOp><Name>lineno</Name> + <Num>1</Num></BinOp></Assign>
102.431 - # comment or blank line?
102.432 - <If>if <BoolOp><Compare><Call><Attribute><Name>line</Name>.strip</Attribute>()</Call> == <Str>''</Str></Compare> or <Compare><Subscript><Name>line</Name>[<Index><Num>0</Num></Index>]</Subscript> in <Str>'#;'</Str></Compare></BoolOp>:
102.433 - <Continue>continue</Continue>
102.434 - </If> <If>if <BoolOp><Compare><Call><Attribute><Name>line</Name>.split</Attribute><Call>(<Name>None</Name>, <Num>1</Num>)</Call><Attribute><Subscript>[<Index><Num>0</Num></Index>]</Subscript>.lower</Attribute>()</Call> == <Str>'rem'</Str></Compare> and <Compare><Subscript><Name>line</Name>[<Index><Num>0</Num></Index>]</Subscript> in <Str>"rR"</Str></Compare></BoolOp>:
102.435 - # no leading whitespace
102.436 - <Continue>continue</Continue>
102.437 - # continuation line?
102.438 - </If> <If>if <BoolOp><Call><Name>line</Name><Attribute><Subscript>[<Index><Num>0</Num></Index>]</Subscript>.isspace</Attribute>()</Call> and <Compare><Name>cursect</Name> is not <Name>None</Name></Compare> and <Name>optname</Name></BoolOp>:
102.439 - <Assign><Name>value</Name> = <Call><Attribute><Name>line</Name>.strip</Attribute>()</Call></Assign>
102.440 - <If>if <Name>value</Name>:
102.441 - <Assign><Subscript><Name>cursect</Name>[<Index><Name>optname</Name></Index>]</Subscript> = <BinOp><Str>"%s\n%s"</Str> % <Tuple>(<Subscript><Name>cursect</Name>[<Index><Name>optname</Name></Index>]</Subscript>, <Name>value</Name>)</Tuple></BinOp></Assign>
102.442 - # a section header or option header?
102.443 - </If> else:
102.444 - # is it a section header?
102.445 - <Assign><Name>mo</Name> = <Call><Attribute><Attribute><Name>self</Name>.SECTCRE</Attribute>.match</Attribute>(<Name>line</Name>)</Call></Assign>
102.446 - <If>if <Name>mo</Name>:
102.447 - <Assign><Name>sectname</Name> = <Call><Attribute><Name>mo</Name>.group</Attribute>(<Str>'header'</Str>)</Call></Assign>
102.448 - <If>if <Compare><Name>sectname</Name> in <Attribute><Name>self</Name>._sections</Attribute></Compare>:
102.449 - <Assign><Name>cursect</Name> = <Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>sectname</Name></Index>]</Subscript></Assign>
102.450 - <If>elif <Compare><Name>sectname</Name> == <Name>DEFAULTSECT</Name></Compare>:
102.451 - <Assign><Name>cursect</Name> = <Attribute><Name>self</Name>._defaults</Attribute></Assign>
102.452 - else:
102.453 - <Assign><Name>cursect</Name> = <Dict>{<Str>'__name__'</Str>: <Name>sectname</Name>}</Dict></Assign>
102.454 - <Assign><Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>sectname</Name></Index>]</Subscript> = <Name>cursect</Name></Assign>
102.455 - # So sections can't start with a continuation line
102.456 - </If></If> <Assign><Name>optname</Name> = <Name>None</Name></Assign>
102.457 - # no section header in the file?
102.458 - <If>elif <Compare><Name>cursect</Name> is <Name>None</Name></Compare>:
102.459 - <Raise>raise <Call><Name>MissingSectionHeaderError</Name>(<Name>fpname</Name>, <Name>lineno</Name>, <Repr>`<Name>line</Name>`</Repr>)</Call></Raise>
102.460 - # an option line?
102.461 - else:
102.462 - <Assign><Name>mo</Name> = <Call><Attribute><Attribute><Name>self</Name>.OPTCRE</Attribute>.match</Attribute>(<Name>line</Name>)</Call></Assign>
102.463 - <If>if <Name>mo</Name>:
102.464 - <Assign><Tuple><Name>optname</Name>, <Name>vi</Name>, <Name>optval</Name></Tuple> = <Call><Attribute><Name>mo</Name>.group</Attribute>(<Str>'option'</Str>, <Str>'vi'</Str>, <Str>'value'</Str>)</Call></Assign>
102.465 - <If>if <BoolOp><Compare><Name>vi</Name> in <Tuple>(<Str>'='</Str>, <Str>':'</Str>)</Tuple></Compare> and <Compare><Str>';'</Str> in <Name>optval</Name></Compare></BoolOp>:
102.466 - # ';' is a comment delimiter only if it follows
102.467 - # a spacing character
102.468 - <Assign><Name>pos</Name> = <Call><Attribute><Name>optval</Name>.find</Attribute>(<Str>';'</Str>)</Call></Assign>
102.469 - <If>if <BoolOp><Compare><Name>pos</Name> != <Num>-1</Num></Compare> and <Call><Name>optval</Name><Attribute><Subscript>[<Index><BinOp><Name>pos</Name>-<Num>1</Num></BinOp></Index>]</Subscript>.isspace</Attribute>()</Call></BoolOp>:
102.470 - <Assign><Name>optval</Name> = <Subscript><Name>optval</Name>[<Slice>:<Name>pos</Name></Slice>]</Subscript></Assign>
102.471 - </If></If> <Assign><Name>optval</Name> = <Call><Attribute><Name>optval</Name>.strip</Attribute>()</Call></Assign>
102.472 - # allow empty values
102.473 - <If>if <Compare><Name>optval</Name> == <Str>'""'</Str></Compare>:
102.474 - <Assign><Name>optval</Name> = <Str>''</Str></Assign>
102.475 - </If> <Assign><Name>optname</Name> = <Call><Attribute><Name>self</Name>.optionxform</Attribute>(<Call><Attribute><Name>optname</Name>.rstrip</Attribute>()</Call>)</Call></Assign>
102.476 - <Assign><Subscript><Name>cursect</Name>[<Index><Name>optname</Name></Index>]</Subscript> = <Name>optval</Name></Assign>
102.477 - else:
102.478 - # a non-fatal parsing error occurred. set up the
102.479 - # exception but keep going. the exception will be
102.480 - # raised at the end of the file and will contain a
102.481 - # list of all bogus lines
102.482 - <If>if <UnaryOp>not <Name>e</Name></UnaryOp>:
102.483 - <Assign><Name>e</Name> = <Call><Name>ParsingError</Name>(<Name>fpname</Name>)</Call></Assign>
102.484 - </If> <Expr><Call><Attribute><Name>e</Name>.append</Attribute>(<Name>lineno</Name>, <Repr>`<Name>line</Name>`</Repr>)</Call></Expr>
102.485 - # if any parsing errors occurred, raise an exception
102.486 - </If></If></If></If></While> <If>if <Name>e</Name>:
102.487 - <Raise>raise <Name>e</Name></Raise>
102.488 -
102.489 -
102.490 -</If></FunctionDef></ClassDef><ClassDef>class ConfigParser(<Name>RawConfigParser</Name>):
102.491 -
102.492 - <FunctionDef>def get(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>, <Name>raw</Name>=<Name>False</Name>, <Name>vars</Name>=<Name>None</Name>):
102.493 - <Expr><Str>"""Get an option value for a given section.
102.494 -
102.495 - All % interpolations are expanded in the return values, based on the
102.496 - defaults passed into the constructor, unless the optional argument
102.497 - `raw' is true. Additional substitutions may be provided using the
102.498 - `vars' argument, which must be a dictionary whose contents overrides
102.499 - any pre-existing defaults.
102.500 -
102.501 - The section DEFAULT is special.
102.502 - """</Str></Expr>
102.503 - <Assign><Name>d</Name> = <Call><Attribute><Attribute><Name>self</Name>._defaults</Attribute>.copy</Attribute>()</Call></Assign>
102.504 - <TryExcept>try:
102.505 - <Expr><Call><Attribute><Name>d</Name>.update</Attribute>(<Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>section</Name></Index>]</Subscript>)</Call></Expr>
102.506 - <ExceptHandler>except <Name>KeyError</Name>:
102.507 - <If>if <Compare><Name>section</Name> != <Name>DEFAULTSECT</Name></Compare>:
102.508 - <Raise>raise <Call><Name>NoSectionError</Name>(<Name>section</Name>)</Call></Raise>
102.509 - # Update with the entry specific variables
102.510 - </If></ExceptHandler></TryExcept> <If>if <Compare><Name>vars</Name> is not <Name>None</Name></Compare>:
102.511 - <Expr><Call><Attribute><Name>d</Name>.update</Attribute>(<Name>vars</Name>)</Call></Expr>
102.512 - </If> <Assign><Name>option</Name> = <Call><Attribute><Name>self</Name>.optionxform</Attribute>(<Name>option</Name>)</Call></Assign>
102.513 - <TryExcept>try:
102.514 - <Assign><Name>value</Name> = <Subscript><Name>d</Name>[<Index><Name>option</Name></Index>]</Subscript></Assign>
102.515 - <ExceptHandler>except <Name>KeyError</Name>:
102.516 - <Raise>raise <Call><Name>NoOptionError</Name>(<Name>option</Name>, <Name>section</Name>)</Call></Raise>
102.517 -
102.518 - </ExceptHandler></TryExcept> <If>if <Name>raw</Name>:
102.519 - <Return>return <Name>value</Name></Return>
102.520 - else:
102.521 - <Return>return <Call><Attribute><Name>self</Name>._interpolate</Attribute>(<Name>section</Name>, <Name>option</Name>, <Name>value</Name>, <Name>d</Name>)</Call></Return>
102.522 -
102.523 - </If></FunctionDef> <FunctionDef>def items(<Name>self</Name>, <Name>section</Name>, <Name>raw</Name>=<Name>False</Name>, <Name>vars</Name>=<Name>None</Name>):
102.524 - <Expr><Str>"""Return a list of tuples with (name, value) for each option
102.525 - in the section.
102.526 -
102.527 - All % interpolations are expanded in the return values, based on the
102.528 - defaults passed into the constructor, unless the optional argument
102.529 - `raw' is true. Additional substitutions may be provided using the
102.530 - `vars' argument, which must be a dictionary whose contents overrides
102.531 - any pre-existing defaults.
102.532 -
102.533 - The section DEFAULT is special.
102.534 - """</Str></Expr>
102.535 - <Assign><Name>d</Name> = <Call><Attribute><Attribute><Name>self</Name>._defaults</Attribute>.copy</Attribute>()</Call></Assign>
102.536 - <TryExcept>try:
102.537 - <Expr><Call><Attribute><Name>d</Name>.update</Attribute>(<Subscript><Attribute><Name>self</Name>._sections</Attribute>[<Index><Name>section</Name></Index>]</Subscript>)</Call></Expr>
102.538 - <ExceptHandler>except <Name>KeyError</Name>:
102.539 - <If>if <Compare><Name>section</Name> != <Name>DEFAULTSECT</Name></Compare>:
102.540 - <Raise>raise <Call><Name>NoSectionError</Name>(<Name>section</Name>)</Call></Raise>
102.541 - # Update with the entry specific variables
102.542 - </If></ExceptHandler></TryExcept> <If>if <Name>vars</Name>:
102.543 - <Expr><Call><Attribute><Name>d</Name>.update</Attribute>(<Name>vars</Name>)</Call></Expr>
102.544 - </If> <Assign><Name>options</Name> = <Call><Attribute><Name>d</Name>.keys</Attribute>()</Call></Assign>
102.545 - <If>if <Compare><Str>"__name__"</Str> in <Name>options</Name></Compare>:
102.546 - <Expr><Call><Attribute><Name>options</Name>.remove</Attribute>(<Str>"__name__"</Str>)</Call></Expr>
102.547 - </If> <If>if <Name>raw</Name>:
102.548 - <Return>return <ListComp>[<Tuple>(<Name>option</Name>, <Subscript><Name>d</Name>[<Index><Name>option</Name></Index>]</Subscript>)</Tuple>
102.549 - for <Name>option</Name> in <Name>options</Name>]</ListComp></Return>
102.550 - else:
102.551 - <Return>return <ListComp>[<Tuple>(<Name>option</Name>, <Call><Attribute><Name>self</Name>._interpolate</Attribute>(<Name>section</Name>, <Name>option</Name>, <Subscript><Name>d</Name>[<Index><Name>option</Name></Index>]</Subscript>, <Name>d</Name>)</Call>)</Tuple>
102.552 - for <Name>option</Name> in <Name>options</Name>]</ListComp></Return>
102.553 -
102.554 - </If></FunctionDef> <FunctionDef>def _interpolate(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>, <Name>rawval</Name>, <Name>vars</Name>):
102.555 - # do the string interpolation
102.556 - <Assign><Name>value</Name> = <Name>rawval</Name></Assign>
102.557 - <Assign><Name>depth</Name> = <Name>MAX_INTERPOLATION_DEPTH</Name></Assign>
102.558 - <While>while <Name>depth</Name>: # Loop through this until it's done
102.559 - <AugAssign><Name>depth</Name> -= <Num>1</Num></AugAssign>
102.560 - <If>if <Compare><Call><Attribute><Name>value</Name>.find</Attribute>(<Str>"%("</Str>)</Call> != <Num>-1</Num></Compare>:
102.561 - <TryExcept>try:
102.562 - <Assign><Name>value</Name> = <BinOp><Name>value</Name> % <Name>vars</Name></BinOp></Assign>
102.563 - <ExceptHandler>except <Name>KeyError</Name>, <Name>e</Name>:
102.564 - <Raise>raise <Call><Name>InterpolationMissingOptionError</Name>(
102.565 - <Name>option</Name>, <Name>section</Name>, <Name>rawval</Name>, <Subscript><Name>e</Name>[<Index><Num>0</Num></Index>]</Subscript>)</Call></Raise>
102.566 - </ExceptHandler></TryExcept> else:
102.567 - <Break>break</Break>
102.568 - </If></While> <If>if <Compare><Call><Attribute><Name>value</Name>.find</Attribute>(<Str>"%("</Str>)</Call> != <Num>-1</Num></Compare>:
102.569 - <Raise>raise <Call><Name>InterpolationDepthError</Name>(<Name>option</Name>, <Name>section</Name>, <Name>rawval</Name>)</Call></Raise>
102.570 - </If> <Return>return <Name>value</Name></Return>
102.571 -
102.572 -
102.573 -</FunctionDef></ClassDef><ClassDef>class SafeConfigParser(<Name>ConfigParser</Name>):
102.574 -
102.575 - <FunctionDef>def _interpolate(<Name>self</Name>, <Name>section</Name>, <Name>option</Name>, <Name>rawval</Name>, <Name>vars</Name>):
102.576 - # do the string interpolation
102.577 - <Assign><Name>L</Name> = <List>[]</List></Assign>
102.578 - <Expr><Call><Attribute><Name>self</Name>._interpolate_some</Attribute>(<Name>option</Name>, <Name>L</Name>, <Name>rawval</Name>, <Name>section</Name>, <Name>vars</Name>, <Num>1</Num>)</Call></Expr>
102.579 - <Return>return <Call><Attribute><Str>''</Str>.join</Attribute>(<Name>L</Name>)</Call></Return>
102.580 -
102.581 - </FunctionDef> <Assign><Name>_interpvar_match</Name> = <Attribute><Attribute><Name>re</Name>.compile</Attribute><Call>(<Str>r"%\(([^)]+)\)s"</Str>)</Call>.match</Attribute></Assign>
102.582 -
102.583 - <FunctionDef>def _interpolate_some(<Name>self</Name>, <Name>option</Name>, <Name>accum</Name>, <Name>rest</Name>, <Name>section</Name>, <Name>map</Name>, <Name>depth</Name>):
102.584 - <If>if <Compare><Name>depth</Name> > <Name>MAX_INTERPOLATION_DEPTH</Name></Compare>:
102.585 - <Raise>raise <Call><Name>InterpolationDepthError</Name>(<Name>option</Name>, <Name>section</Name>, <Name>rest</Name>)</Call></Raise>
102.586 - </If> <While>while <Name>rest</Name>:
102.587 - <Assign><Name>p</Name> = <Call><Attribute><Name>rest</Name>.find</Attribute>(<Str>"%"</Str>)</Call></Assign>
102.588 - <If>if <Compare><Name>p</Name> < <Num>0</Num></Compare>:
102.589 - <Expr><Call><Attribute><Name>accum</Name>.append</Attribute>(<Name>rest</Name>)</Call></Expr>
102.590 - <Return>return</Return>
102.591 - </If> <If>if <Compare><Name>p</Name> > <Num>0</Num></Compare>:
102.592 - <Expr><Call><Attribute><Name>accum</Name>.append</Attribute>(<Subscript><Name>rest</Name>[<Slice>:<Name>p</Name></Slice>]</Subscript>)</Call></Expr>
102.593 - <Assign><Name>rest</Name> = <Subscript><Name>rest</Name>[<Slice><Name>p</Name>:</Slice>]</Subscript></Assign>
102.594 - # p is no longer used
102.595 - </If> <Assign><Name>c</Name> = <Subscript><Name>rest</Name>[<Slice><Num>1</Num>:<Num>2</Num></Slice>]</Subscript></Assign>
102.596 - <If>if <Compare><Name>c</Name> == <Str>"%"</Str></Compare>:
102.597 - <Expr><Call><Attribute><Name>accum</Name>.append</Attribute>(<Str>"%"</Str>)</Call></Expr>
102.598 - <Assign><Name>rest</Name> = <Subscript><Name>rest</Name>[<Slice><Num>2</Num>:</Slice>]</Subscript></Assign>
102.599 - <If>elif <Compare><Name>c</Name> == <Str>"("</Str></Compare>:
102.600 - <Assign><Name>m</Name> = <Call><Attribute><Name>self</Name>._interpvar_match</Attribute>(<Name>rest</Name>)</Call></Assign>
102.601 - <If>if <Compare><Name>m</Name> is <Name>None</Name></Compare>:
102.602 - <Raise>raise <Call><Name>InterpolationSyntaxError</Name>(<Name>option</Name>, <Name>section</Name>,
102.603 - <BinOp><Str>"bad interpolation variable reference %r"</Str> % <Name>rest</Name></BinOp>)</Call></Raise>
102.604 - </If> <Assign><Name>var</Name> = <Call><Attribute><Name>m</Name>.group</Attribute>(<Num>1</Num>)</Call></Assign>
102.605 - <Assign><Name>rest</Name> = <Subscript><Name>rest</Name>[<Slice><Call><Attribute><Name>m</Name>.end</Attribute>()</Call>:</Slice>]</Subscript></Assign>
102.606 - <TryExcept>try:
102.607 - <Assign><Name>v</Name> = <Subscript><Name>map</Name>[<Index><Name>var</Name></Index>]</Subscript></Assign>
102.608 - <ExceptHandler>except <Name>KeyError</Name>:
102.609 - <Raise>raise <Call><Name>InterpolationMissingOptionError</Name>(
102.610 - <Name>option</Name>, <Name>section</Name>, <Name>rest</Name>, <Name>var</Name>)</Call></Raise>
102.611 - </ExceptHandler></TryExcept> <If>if <Compare><Str>"%"</Str> in <Name>v</Name></Compare>:
102.612 - <Expr><Call><Attribute><Name>self</Name>._interpolate_some</Attribute>(<Name>option</Name>, <Name>accum</Name>, <Name>v</Name>,
102.613 - <Name>section</Name>, <Name>map</Name>, <BinOp><Name>depth</Name> + <Num>1</Num></BinOp>)</Call></Expr>
102.614 - else:
102.615 - <Expr><Call><Attribute><Name>accum</Name>.append</Attribute>(<Name>v</Name>)</Call></Expr>
102.616 - </If> else:
102.617 - <Raise>raise <Call><Name>InterpolationSyntaxError</Name>(
102.618 - <Name>option</Name>, <Name>section</Name>,
102.619 - <BinOp><Str>"'%' must be followed by '%' or '(', found: "</Str> + <Repr>`<Name>ret</Name>`</Repr></BinOp>)</Call></Raise></If></If></While></FunctionDef></ClassDef></Module>
103.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.scopes Sun Jan 04 13:11:53 2015 -0600
103.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
103.3 @@ -1,548 +0,0 @@
103.4 -=============================================
103.5 -<file-top>: Module : OffsetRange[0,22066>
103.6 -ConfigParser [bound][class][def][read][node=ClassDef]
103.7 -DEFAULTSECT [bound][data][read][node=Name]
103.8 -DuplicateSectionError [bound][class][def][read][called][node=ClassDef]
103.9 -Error [bound][private][class][def][read][node=ClassDef]
103.10 -Exception [private][read][UNRESOLVED][node=Name]
103.11 -InterpolationDepthError [bound][class][def][read][called][node=ClassDef]
103.12 -InterpolationError [bound][class][def][read][node=ClassDef]
103.13 -InterpolationMissingOptionError [bound][private][class][def][read][called][node=ClassDef]
103.14 -InterpolationSyntaxError [bound][class][def][read][called][node=ClassDef]
103.15 -MAX_INTERPOLATION_DEPTH [bound][data][read][node=Name]
103.16 -MissingSectionHeaderError [bound][class][def][read][called][node=ClassDef]
103.17 -NoOptionError [bound][class][def][read][called][node=ClassDef]
103.18 -NoSectionError [bound][class][def][read][called][node=ClassDef]
103.19 -ParsingError [bound][class][def][read][called][node=ClassDef]
103.20 -RawConfigParser [bound][private][class][def][read][node=ClassDef]
103.21 -SafeConfigParser [bound][class][def][node=ClassDef]
103.22 -__all__ [bound][data][node=Name]
103.23 -re [bound][imported][private][data][read][node=Import]
103.24 -
103.25 - =============================================
103.26 - class Error: ClassDef : OffsetRange[3377,3627>
103.27 - __init__ [bound][private][function][def][node=FunctionDef]
103.28 - __repr__ [bound][private][function][def][read][node=FunctionDef]
103.29 - __str__ [bound][private][function][alias][node=FunctionDef]
103.30 - ------ Attributes ---------------------------------------
103.31 - message : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
103.32 -
103.33 - =============================================
103.34 - __init__: FunctionDef : OffsetRange[3456,3553>
103.35 - Exception [free][private][read][node=Name]
103.36 - msg [bound][param][private][data][read][node=Name]
103.37 - self [bound][param][private][data][read][node=Name]
103.38 - ------ Attributes ---------------------------------------
103.39 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
103.40 -
103.41 - =============================================
103.42 - __repr__: FunctionDef : OffsetRange[3554,3606>
103.43 - self [bound][param][private][data][read][node=Name]
103.44 - ------ Attributes ---------------------------------------
103.45 - message : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
103.46 -
103.47 - =============================================
103.48 - class NoSectionError: ClassDef : OffsetRange[3627,3844>
103.49 - __init__ [bound][function][def][node=FunctionDef]
103.50 - ------ Attributes ---------------------------------------
103.51 - section : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
103.52 -
103.53 - =============================================
103.54 - __init__: FunctionDef : OffsetRange[3726,3844>
103.55 - Error [free][read][node=Name]
103.56 - section [bound][param][data][read][node=Name]
103.57 - self [bound][param][data][read][node=Name]
103.58 - ------ Attributes ---------------------------------------
103.59 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
103.60 -
103.61 - =============================================
103.62 - class DuplicateSectionError: ClassDef : OffsetRange[3844,4067>
103.63 - __init__ [bound][function][def][node=FunctionDef]
103.64 - ------ Attributes ---------------------------------------
103.65 - section : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
103.66 -
103.67 - =============================================
103.68 - __init__: FunctionDef : OffsetRange[3938,4067>
103.69 - Error [free][read][node=Name]
103.70 - section [bound][param][data][read][node=Name]
103.71 - self [bound][param][data][read][node=Name]
103.72 - ------ Attributes ---------------------------------------
103.73 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
103.74 -
103.75 - =============================================
103.76 - class NoOptionError: ClassDef : OffsetRange[4067,4345>
103.77 - __init__ [bound][function][def][node=FunctionDef]
103.78 - ------ Attributes ---------------------------------------
103.79 - option : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
103.80 - section : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
103.81 -
103.82 - =============================================
103.83 - __init__: FunctionDef : OffsetRange[4144,4345>
103.84 - Error [free][read][node=Name]
103.85 - option [bound][param][data][read][node=Name]
103.86 - section [bound][param][data][read][node=Name]
103.87 - self [bound][param][data][read][node=Name]
103.88 - ------ Attributes ---------------------------------------
103.89 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
103.90 -
103.91 - =============================================
103.92 - class InterpolationError: ClassDef : OffsetRange[4345,4579>
103.93 - __init__ [bound][function][def][node=FunctionDef]
103.94 - ------ Attributes ---------------------------------------
103.95 - option : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
103.96 - section : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
103.97 -
103.98 - =============================================
103.99 - __init__: FunctionDef : OffsetRange[4442,4579>
103.100 - Error [free][read][node=Name]
103.101 - msg [bound][param][data][read][node=Name]
103.102 - option [bound][param][data][read][node=Name]
103.103 - section [bound][param][data][read][node=Name]
103.104 - self [bound][param][data][read][node=Name]
103.105 - ------ Attributes ---------------------------------------
103.106 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
103.107 -
103.108 - =============================================
103.109 - class InterpolationMissingOptionError: ClassDef : OffsetRange[4579,5107>
103.110 - __init__ [bound][private][function][def][node=FunctionDef]
103.111 - ------ Attributes ---------------------------------------
103.112 - reference : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
103.113 -
103.114 - =============================================
103.115 - __init__: FunctionDef : OffsetRange[4719,5107>
103.116 - InterpolationError [free][private][read][node=Name]
103.117 - msg [bound][private][data][read][node=Name]
103.118 - option [bound][param][private][data][read][node=Name]
103.119 - rawval [bound][param][private][data][read][node=Name]
103.120 - reference [bound][param][private][data][read][node=Name]
103.121 - section [bound][param][private][data][read][node=Name]
103.122 - self [bound][param][private][data][read][node=Name]
103.123 - ------ Attributes ---------------------------------------
103.124 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
103.125 -
103.126 - =============================================
103.127 - class InterpolationSyntaxError: ClassDef : OffsetRange[5107,5277>
103.128 -
103.129 - =============================================
103.130 - class InterpolationDepthError: ClassDef : OffsetRange[5277,5708>
103.131 - __init__ [bound][function][def][node=FunctionDef]
103.132 -
103.133 - =============================================
103.134 - __init__: FunctionDef : OffsetRange[5392,5708>
103.135 - InterpolationError [free][read][node=Name]
103.136 - msg [bound][data][read][node=Name]
103.137 - option [bound][param][data][read][node=Name]
103.138 - rawval [bound][param][data][read][node=Name]
103.139 - section [bound][param][data][read][node=Name]
103.140 - self [bound][param][data][read][node=Name]
103.141 - ------ Attributes ---------------------------------------
103.142 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
103.143 -
103.144 - =============================================
103.145 - class ParsingError: ClassDef : OffsetRange[5708,6121>
103.146 - __init__ [bound][function][def][node=FunctionDef]
103.147 - append [bound][function][def][node=FunctionDef]
103.148 - ------ Attributes ---------------------------------------
103.149 - errors : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
103.150 - filename : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
103.151 -
103.152 - =============================================
103.153 - __init__: FunctionDef : OffsetRange[5813,5982>
103.154 - Error [free][read][node=Name]
103.155 - filename [bound][param][data][read][node=Name]
103.156 - self [bound][param][data][read][node=Name]
103.157 - ------ Attributes ---------------------------------------
103.158 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
103.159 -
103.160 - =============================================
103.161 - append: FunctionDef : OffsetRange[5983,6121>
103.162 - line [bound][param][data][read][node=Name]
103.163 - lineno [bound][param][data][read][node=Name]
103.164 - self [bound][param][data][read][node=Name]
103.165 - ------ Attributes ---------------------------------------
103.166 - errors : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
103.167 - message : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
103.168 -
103.169 - =============================================
103.170 - class MissingSectionHeaderError: ClassDef : OffsetRange[6121,6536>
103.171 - __init__ [bound][function][def][node=FunctionDef]
103.172 - ------ Attributes ---------------------------------------
103.173 - filename : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
103.174 - line : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
103.175 - lineno : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
103.176 -
103.177 - =============================================
103.178 - __init__: FunctionDef : OffsetRange[6248,6536>
103.179 - Error [free][read][node=Name]
103.180 - filename [bound][param][data][read][node=Name]
103.181 - line [bound][param][data][read][node=Name]
103.182 - lineno [bound][param][data][read][node=Name]
103.183 - self [bound][param][data][read][node=Name]
103.184 -
103.185 - =============================================
103.186 - class RawConfigParser: ClassDef : OffsetRange[6536,17314>
103.187 - False [free][private][read][node=Name]
103.188 - None [free][private][read][node=Name]
103.189 - OPTCRE [bound][private][data][node=Name]
103.190 - SECTCRE [bound][private][data][node=Name]
103.191 - True [free][private][read][node=Name]
103.192 - __init__ [bound][private][function][def][node=FunctionDef]
103.193 - _boolean_states [bound][private][data][node=Name]
103.194 - _get [bound][private][function][def][node=FunctionDef]
103.195 - _read [bound][private][function][def][node=FunctionDef]
103.196 - add_section [bound][private][function][def][node=FunctionDef]
103.197 - defaults [bound][private][function][def][node=FunctionDef]
103.198 - get [bound][private][function][def][node=FunctionDef]
103.199 - getboolean [bound][private][function][def][node=FunctionDef]
103.200 - getfloat [bound][private][function][def][node=FunctionDef]
103.201 - getint [bound][private][function][def][node=FunctionDef]
103.202 - has_option [bound][private][function][def][node=FunctionDef]
103.203 - has_section [bound][private][function][def][node=FunctionDef]
103.204 - items [bound][private][function][def][node=FunctionDef]
103.205 - options [bound][private][function][def][node=FunctionDef]
103.206 - optionxform [bound][private][function][def][node=FunctionDef]
103.207 - re [free][private][read][node=Name]
103.208 - read [bound][private][function][def][node=FunctionDef]
103.209 - readfp [bound][private][function][def][node=FunctionDef]
103.210 - remove_option [bound][private][function][def][node=FunctionDef]
103.211 - remove_section [bound][private][function][def][node=FunctionDef]
103.212 - sections [bound][private][function][def][node=FunctionDef]
103.213 - set [bound][private][function][def][node=FunctionDef]
103.214 - write [bound][private][function][def][node=FunctionDef]
103.215 - ------ Attributes ---------------------------------------
103.216 - _defaults : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
103.217 - _sections : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
103.218 -
103.219 - =============================================
103.220 - __init__: FunctionDef : OffsetRange[6563,6743>
103.221 - None [free][private][read][node=Name]
103.222 - defaults [bound][param][private][data][read][node=Name]
103.223 - self [bound][param][private][data][read][node=Name]
103.224 -
103.225 - =============================================
103.226 - defaults: FunctionDef : OffsetRange[6744,6798>
103.227 - self [bound][param][private][data][read][node=Name]
103.228 - ------ Attributes ---------------------------------------
103.229 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.230 -
103.231 - =============================================
103.232 - sections: FunctionDef : OffsetRange[6799,6983>
103.233 - self [bound][param][private][data][read][node=Name]
103.234 - ------ Attributes ---------------------------------------
103.235 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.236 -
103.237 - =============================================
103.238 - add_section: FunctionDef : OffsetRange[6984,7306>
103.239 - DuplicateSectionError [free][private][read][called][node=Name]
103.240 - section [bound][param][private][data][read][node=Name]
103.241 - self [bound][param][private][data][read][node=Name]
103.242 - ------ Attributes ---------------------------------------
103.243 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.244 -
103.245 - =============================================
103.246 - has_section: FunctionDef : OffsetRange[7307,7525>
103.247 - section [bound][param][private][data][read][node=Name]
103.248 - self [bound][param][private][data][read][node=Name]
103.249 - ------ Attributes ---------------------------------------
103.250 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.251 -
103.252 - =============================================
103.253 - options: FunctionDef : OffsetRange[7526,7887>
103.254 - KeyError [free][private][read][node=Name]
103.255 - NoSectionError [free][private][read][called][node=Name]
103.256 - opts [bound][private][data][read][node=Name]
103.257 - section [bound][param][private][data][read][node=Name]
103.258 - self [bound][param][private][data][read][node=Name]
103.259 - ------ Attributes ---------------------------------------
103.260 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.261 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.262 -
103.263 - =============================================
103.264 - read: FunctionDef : OffsetRange[7888,8636>
103.265 - IOError [free][private][read][node=Name]
103.266 - basestring [free][private][read][node=Name]
103.267 - filename [bound][private][data][read][node=Name]
103.268 - filenames [bound][param][private][data][read][node=Name]
103.269 - fp [bound][private][data][read][node=Name]
103.270 - isinstance [free][private][read][called][node=Name]
103.271 - open [free][private][read][called][node=Name]
103.272 - self [bound][param][private][data][read][node=Name]
103.273 - ------ Attributes ---------------------------------------
103.274 - _read : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
103.275 -
103.276 - =============================================
103.277 - readfp: FunctionDef : OffsetRange[8637,9162>
103.278 - AttributeError [free][private][read][node=Name]
103.279 - None [free][private][read][node=Name]
103.280 - filename [bound][param][private][data][read][node=Name]
103.281 - fp [bound][param][private][data][read][node=Name]
103.282 - self [bound][param][private][data][read][node=Name]
103.283 - ------ Attributes ---------------------------------------
103.284 - _read : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
103.285 -
103.286 - =============================================
103.287 - get: FunctionDef : OffsetRange[9163,9748>
103.288 - DEFAULTSECT [free][private][read][node=Name]
103.289 - NoOptionError [free][private][read][called][node=Name]
103.290 - NoSectionError [free][private][read][called][node=Name]
103.291 - opt [bound][private][data][read][node=Name]
103.292 - option [bound][param][private][data][read][node=Name]
103.293 - section [bound][param][private][data][read][node=Name]
103.294 - self [bound][param][private][data][read][node=Name]
103.295 - ------ Attributes ---------------------------------------
103.296 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.297 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.298 - optionxform : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
103.299 -
103.300 - =============================================
103.301 - items: FunctionDef : OffsetRange[9749,10101>
103.302 - DEFAULTSECT [free][private][read][node=Name]
103.303 - KeyError [free][private][read][node=Name]
103.304 - NoSectionError [free][private][read][called][node=Name]
103.305 - d [bound][private][data][read][node=Name]
103.306 - d2 [bound][private][data][read][node=Name]
103.307 - section [bound][param][private][data][read][node=Name]
103.308 - self [bound][param][private][data][read][node=Name]
103.309 - ------ Attributes ---------------------------------------
103.310 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.311 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.312 -
103.313 - =============================================
103.314 - _get: FunctionDef : OffsetRange[10102,10192>
103.315 - conv [bound][param][private][data][read][called][node=Name]
103.316 - option [bound][param][private][data][read][node=Name]
103.317 - section [bound][param][private][data][read][node=Name]
103.318 - self [bound][param][private][data][read][node=Name]
103.319 - ------ Attributes ---------------------------------------
103.320 - get : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
103.321 -
103.322 - =============================================
103.323 - getint: FunctionDef : OffsetRange[10193,10279>
103.324 - int [free][private][read][node=Name]
103.325 - option [bound][param][private][data][read][node=Name]
103.326 - section [bound][param][private][data][read][node=Name]
103.327 - self [bound][param][private][data][read][node=Name]
103.328 - ------ Attributes ---------------------------------------
103.329 - _get : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
103.330 -
103.331 - =============================================
103.332 - getfloat: FunctionDef : OffsetRange[10280,10370>
103.333 - float [free][private][read][node=Name]
103.334 - option [bound][param][private][data][read][node=Name]
103.335 - section [bound][param][private][data][read][node=Name]
103.336 - self [bound][param][private][data][read][node=Name]
103.337 - ------ Attributes ---------------------------------------
103.338 - _get : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
103.339 -
103.340 - =============================================
103.341 - getboolean: FunctionDef : OffsetRange[10523,10755>
103.342 - ValueError [free][private][read][node=Name]
103.343 - option [bound][param][private][data][read][node=Name]
103.344 - section [bound][param][private][data][read][node=Name]
103.345 - self [bound][param][private][data][read][node=Name]
103.346 - v [bound][private][data][read][node=Name]
103.347 - ------ Attributes ---------------------------------------
103.348 - _boolean_states : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.349 - get : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
103.350 -
103.351 - =============================================
103.352 - optionxform: FunctionDef : OffsetRange[10756,10827>
103.353 - optionstr [bound][param][private][data][read][node=Name]
103.354 - self [bound][param][private][data][unused][node=Name]
103.355 -
103.356 - =============================================
103.357 - has_option: FunctionDef : OffsetRange[10828,11319>
103.358 - DEFAULTSECT [free][private][read][node=Name]
103.359 - False [free][private][read][node=Name]
103.360 - option [bound][param][private][data][read][node=Name]
103.361 - section [bound][param][private][data][read][node=Name]
103.362 - self [bound][param][private][data][read][node=Name]
103.363 - ------ Attributes ---------------------------------------
103.364 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.365 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.366 - optionxform : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
103.367 -
103.368 - =============================================
103.369 - set: FunctionDef : OffsetRange[11320,11688>
103.370 - DEFAULTSECT [free][private][read][node=Name]
103.371 - KeyError [free][private][read][node=Name]
103.372 - NoSectionError [free][private][read][called][node=Name]
103.373 - option [bound][param][private][data][read][node=Name]
103.374 - sectdict [bound][private][data][read][node=Name]
103.375 - section [bound][param][private][data][read][node=Name]
103.376 - self [bound][param][private][data][read][node=Name]
103.377 - value [bound][param][private][data][read][node=Name]
103.378 - ------ Attributes ---------------------------------------
103.379 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.380 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.381 - optionxform : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
103.382 -
103.383 - =============================================
103.384 - write: FunctionDef : OffsetRange[11689,12350>
103.385 - DEFAULTSECT [free][private][read][node=Name]
103.386 - fp [bound][param][private][data][read][node=Name]
103.387 - key [bound][private][data][read][node=Name]
103.388 - section [bound][private][data][read][node=Name]
103.389 - self [bound][param][private][data][read][node=Name]
103.390 - str [free][private][read][called][node=Name]
103.391 - value [bound][private][data][read][node=Name]
103.392 - ------ Attributes ---------------------------------------
103.393 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.394 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.395 -
103.396 - =============================================
103.397 - remove_option: FunctionDef : OffsetRange[12351,12829>
103.398 - DEFAULTSECT [free][private][read][node=Name]
103.399 - KeyError [free][private][read][node=Name]
103.400 - NoSectionError [free][private][read][called][node=Name]
103.401 - existed [bound][private][data][read][node=Name]
103.402 - option [bound][param][private][data][read][node=Name]
103.403 - sectdict [bound][private][data][read][node=Name]
103.404 - section [bound][param][private][data][read][node=Name]
103.405 - self [bound][param][private][data][read][node=Name]
103.406 - ------ Attributes ---------------------------------------
103.407 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.408 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.409 - optionxform : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
103.410 -
103.411 - =============================================
103.412 - remove_section: FunctionDef : OffsetRange[12830,13112>
103.413 - existed [bound][private][data][read][node=Name]
103.414 - section [bound][param][private][data][read][node=Name]
103.415 - self [bound][param][private][data][read][node=Name]
103.416 - ------ Attributes ---------------------------------------
103.417 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.418 -
103.419 - =============================================
103.420 - _read: FunctionDef : OffsetRange[13768,17314>
103.421 - DEFAULTSECT [free][private][read][node=Name]
103.422 - MissingSectionHeaderError [free][private][read][called][node=Name]
103.423 - None [free][private][read][node=Name]
103.424 - ParsingError [free][private][read][called][node=Name]
103.425 - True [free][private][read][node=Name]
103.426 - cursect [bound][private][data][read][node=Name]
103.427 - e [bound][private][data][read][node=Name]
103.428 - fp [bound][param][private][data][read][node=Name]
103.429 - fpname [bound][param][private][data][read][node=Name]
103.430 - line [bound][private][data][read][node=Name]
103.431 - lineno [bound][private][data][read][node=Name]
103.432 - mo [bound][private][data][read][node=Name]
103.433 - optname [bound][private][data][read][node=Name]
103.434 - optval [bound][private][data][read][node=Name]
103.435 - pos [bound][private][data][read][node=Name]
103.436 - sectname [bound][private][data][read][node=Name]
103.437 - self [bound][param][private][data][read][node=Name]
103.438 - value [bound][private][data][read][node=Name]
103.439 - vi [bound][private][data][read][node=Name]
103.440 - ------ Attributes ---------------------------------------
103.441 - OPTCRE : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
103.442 - SECTCRE : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
103.443 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.444 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.445 - optionxform : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
103.446 -
103.447 - =============================================
103.448 - class ConfigParser: ClassDef : OffsetRange[17314,20293>
103.449 - False [free][read][node=Name]
103.450 - None [free][read][node=Name]
103.451 - _interpolate [bound][private][function][def][node=FunctionDef]
103.452 - get [bound][function][def][node=FunctionDef]
103.453 - items [bound][function][def][node=FunctionDef]
103.454 -
103.455 - =============================================
103.456 - get: FunctionDef : OffsetRange[17356,18448>
103.457 - DEFAULTSECT [free][read][node=Name]
103.458 - KeyError [free][read][node=Name]
103.459 - NoOptionError [free][read][called][node=Name]
103.460 - NoSectionError [free][read][called][node=Name]
103.461 - None [free][read][node=Name]
103.462 - d [bound][data][read][node=Name]
103.463 - option [bound][param][data][read][node=Name]
103.464 - raw [bound][param][data][read][node=Name]
103.465 - section [bound][param][data][read][node=Name]
103.466 - self [bound][param][data][read][node=Name]
103.467 - value [bound][data][read][node=Name]
103.468 - vars [bound][param][data][read][node=Name]
103.469 - ------ Attributes ---------------------------------------
103.470 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.471 - _interpolate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
103.472 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.473 - optionxform : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
103.474 -
103.475 - =============================================
103.476 - items: FunctionDef : OffsetRange[18449,19621>
103.477 - DEFAULTSECT [free][read][node=Name]
103.478 - KeyError [free][read][node=Name]
103.479 - NoSectionError [free][read][called][node=Name]
103.480 - _[544_20] [bound][private][data][unused][node=ListComp]
103.481 - _[547_20] [bound][private][data][unused][node=ListComp]
103.482 - d [bound][data][read][node=Name]
103.483 - option [bound][data][read][node=Name]
103.484 - options [bound][data][read][node=Name]
103.485 - raw [bound][param][data][read][node=Name]
103.486 - section [bound][param][data][read][node=Name]
103.487 - self [bound][param][data][read][node=Name]
103.488 - vars [bound][param][data][read][node=Name]
103.489 - ------ Attributes ---------------------------------------
103.490 - _defaults : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.491 - _interpolate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
103.492 - _sections : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
103.493 -
103.494 - =============================================
103.495 - _interpolate: FunctionDef : OffsetRange[19622,20293>
103.496 - InterpolationDepthError [free][read][called][node=Name]
103.497 - InterpolationMissingOptionError [free][read][called][node=Name]
103.498 - KeyError [free][read][node=Name]
103.499 - MAX_INTERPOLATION_DEPTH [free][read][node=Name]
103.500 - depth [bound][data][read][node=Name]
103.501 - e [bound][data][read][node=Name]
103.502 - option [bound][param][data][read][node=Name]
103.503 - rawval [bound][param][data][read][node=Name]
103.504 - section [bound][param][data][read][node=Name]
103.505 - self [bound][param][data][unused][node=Name]
103.506 - value [bound][data][read][node=Name]
103.507 - vars [bound][param][data][read][node=Name]
103.508 -
103.509 - =============================================
103.510 - class SafeConfigParser: ClassDef : OffsetRange[20293,22066>
103.511 - _interpolate [bound][private][function][def][node=FunctionDef]
103.512 - _interpolate_some [bound][private][function][def][node=FunctionDef]
103.513 - _interpvar_match [bound][private][data][node=Name]
103.514 - re [free][read][node=Name]
103.515 -
103.516 - =============================================
103.517 - _interpolate: FunctionDef : OffsetRange[20336,20542>
103.518 - L [bound][data][read][node=Name]
103.519 - option [bound][param][data][read][node=Name]
103.520 - rawval [bound][param][data][read][node=Name]
103.521 - section [bound][param][data][read][node=Name]
103.522 - self [bound][param][data][read][node=Name]
103.523 - vars [bound][param][data][read][node=Name]
103.524 - ------ Attributes ---------------------------------------
103.525 - _interpolate_some : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
103.526 -
103.527 - =============================================
103.528 - _interpolate_some: FunctionDef : OffsetRange[20602,22066>
103.529 - InterpolationDepthError [free][read][called][node=Name]
103.530 - InterpolationMissingOptionError [free][read][called][node=Name]
103.531 - InterpolationSyntaxError [free][read][called][node=Name]
103.532 - KeyError [free][read][node=Name]
103.533 - MAX_INTERPOLATION_DEPTH [free][read][node=Name]
103.534 - None [free][read][node=Name]
103.535 - accum [bound][param][data][read][node=Name]
103.536 - c [bound][data][read][node=Name]
103.537 - depth [bound][param][data][read][node=Name]
103.538 - m [bound][data][read][node=Name]
103.539 - map [bound][param][data][read][node=Name]
103.540 - option [bound][param][data][read][node=Name]
103.541 - p [bound][data][read][node=Name]
103.542 - rest [bound][param][data][read][node=Name]
103.543 - ret [free][read][node=Name]
103.544 - section [bound][param][data][read][node=Name]
103.545 - self [bound][param][data][read][node=Name]
103.546 - v [bound][data][read][node=Name]
103.547 - var [bound][data][read][node=Name]
103.548 - ------ Attributes ---------------------------------------
103.549 - _interpolate_some : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
103.550 - _interpvar_match : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
103.551 -
104.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.semantic Sun Jan 04 13:11:53 2015 -0600
104.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
104.3 @@ -1,615 +0,0 @@
104.4 -"""Configuration file parser.
104.5 -
104.6 -A setup file consists of sections, lead by a "[section]" header,
104.7 -and followed by "name: value" entries, with continuations and such in
104.8 -the style of RFC 822.
104.9 -
104.10 - the same section, or values in a special [DEFAULT] section.
104.11 -
104.12 -For example:
104.13 -
104.14 - something: %(dir)s/whatever
104.15 -
104.16 -would resolve the "%(dir)s" to the value of dir. All reference
104.17 -expansions are done late, on demand.
104.18 -
104.19 -Intrinsic defaults can be specified by passing them into the
104.20 -ConfigParser constructor as a dictionary.
104.21 -
104.22 -class:
104.23 -
104.24 -ConfigParser -- responsible for parsing a list of
104.25 - configuration files, and managing the parsed database.
104.26 -
104.27 - methods:
104.28 -
104.29 - __init__(defaults=None)
104.30 - create the parser and specify a dictionary of intrinsic defaults. The
104.31 - keys must be strings, the values must be appropriate for %()s string
104.32 - interpolation. Note that `__name__' is always an intrinsic default;
104.33 - it's value is the section's name.
104.34 -
104.35 - sections()
104.36 - return all the configuration section names, sans DEFAULT
104.37 -
104.38 - has_section(section)
104.39 - return whether the given section exists
104.40 -
104.41 - has_option(section, option)
104.42 - return whether the given option exists in the given section
104.43 -
104.44 - options(section)
104.45 - return list of configuration options for the named section
104.46 -
104.47 - read(filenames)
104.48 - read and parse the list of named configuration files, given by
104.49 - name. A single filename is also allowed. Non-existing files
104.50 - are ignored.
104.51 -
104.52 - readfp(fp, filename=None)
104.53 - read and parse one configuration file, given as a file object.
104.54 - The filename defaults to fp.name; it is only used in error
104.55 - messages (if fp has no `name' attribute, the string `<???>' is used).
104.56 -
104.57 - get(section, option, raw=False, vars=None)
104.58 - return a string value for the named option. All % interpolations are
104.59 - expanded in the return values, based on the defaults passed into the
104.60 - constructor and the DEFAULT section. Additional substitutions may be
104.61 - provided using the `vars' argument, which must be a dictionary whose
104.62 - contents override any pre-existing defaults.
104.63 -
104.64 - getint(section, options)
104.65 - like get(), but convert value to an integer
104.66 -
104.67 - getfloat(section, options)
104.68 - like get(), but convert value to a float
104.69 -
104.70 - getboolean(section, options)
104.71 - like get(), but convert value to a boolean (currently case
104.72 - insensitively defined as 0, false, no, off for False, and 1, true,
104.73 - yes, on for True). Returns False or True.
104.74 -
104.75 - items(section, raw=False, vars=None)
104.76 - return a list of tuples with (name, value) for each option
104.77 - in the section.
104.78 -
104.79 - remove_section(section)
104.80 - remove the given file section and all its options
104.81 -
104.82 - remove_option(section, option)
104.83 - remove the given option from the given section
104.84 -
104.85 - set(section, option, value)
104.86 - set the given option
104.87 -
104.88 - write(fp)
104.89 - write the configuration state in .ini format
104.90 -"""
104.91 -
104.92 -import re
104.93 -
104.94 -__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
104.95 - "InterpolationError", "InterpolationDepthError",
104.96 - "InterpolationSyntaxError", "ParsingError",
104.97 - "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser",
104.98 - "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
104.99 -
104.100 -DEFAULTSECT = "DEFAULT"
104.101 -
104.102 -MAX_INTERPOLATION_DEPTH = 10
104.103 -
104.104 -
104.105 -
104.106 -# exception classes
104.107 -class Error(Exception):
104.108 - """Base class for ConfigParser exceptions."""
104.109 -
104.110 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:msg<|=''):
104.111 - |>PARAMETER:self<|.message = |>PARAMETER:msg<|
104.112 - Exception.__init__(|>PARAMETER:self<|, |>PARAMETER:msg<|)
104.113 -
104.114 - def |>METHOD:__repr__<|(|>PARAMETER:self<|):
104.115 - return |>PARAMETER:self<|.message
104.116 -
104.117 - __str__ = __repr__
104.118 -
104.119 -class NoSectionError(Error):
104.120 - """Rasssised when no section matches a requested option."""
104.121 -
104.122 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:section<|):
104.123 - Error.__init__(|>PARAMETER:self<|, 'No section: ' + `|>PARAMETER:section<|`)
104.124 - |>PARAMETER:self<|.section = |>PARAMETER:section<|
104.125 -
104.126 -class DuplicateSectionError(Error):
104.127 - """Raised when a section is multiply-created."""
104.128 -
104.129 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:section<|):
104.130 - Error.__init__(|>PARAMETER:self<|, "Section %r already exists" % |>PARAMETER:section<|)
104.131 - |>PARAMETER:self<|.section = |>PARAMETER:section<|
104.132 -
104.133 -class NoOptionError(Error):
104.134 - """A requested option was not found."""
104.135 -
104.136 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:option<|, |>PARAMETER:section<|):
104.137 - Error.__init__(|>PARAMETER:self<|, "No option %r in section: %r" %
104.138 - (|>PARAMETER:option<|, |>PARAMETER:section<|))
104.139 - |>PARAMETER:self<|.option = |>PARAMETER:option<|
104.140 - |>PARAMETER:self<|.section = |>PARAMETER:section<|
104.141 -
104.142 -class InterpolationError(Error):
104.143 - """Base class for interpolation-related exceptions."""
104.144 -
104.145 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:option<|, |>PARAMETER:section<|, |>PARAMETER:msg<|):
104.146 - Error.__init__(|>PARAMETER:self<|, |>PARAMETER:msg<|)
104.147 - |>PARAMETER:self<|.option = |>PARAMETER:option<|
104.148 - |>PARAMETER:self<|.section = |>PARAMETER:section<|
104.149 -
104.150 -class InterpolationMissingOptionError(InterpolationError):
104.151 - """A string substitution required a setting which was not available."""
104.152 -
104.153 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:option<|, |>PARAMETER:section<|, |>PARAMETER:rawval<|, |>PARAMETER:reference<|):
104.154 - msg = ("Bad value substitution:\n"
104.155 - "\tsection: [%s]\n"
104.156 - "\toption : %s\n"
104.157 - "\tkey : %s\n"
104.158 - "\trawval : %s\n"
104.159 - % (|>PARAMETER:section<|, |>PARAMETER:option<|, |>PARAMETER:reference<|, |>PARAMETER:rawval<|))
104.160 - InterpolationError.__init__(|>PARAMETER:self<|, |>PARAMETER:option<|, |>PARAMETER:section<|, msg)
104.161 - |>PARAMETER:self<|.reference = |>PARAMETER:reference<|
104.162 -
104.163 -class InterpolationSyntaxError(InterpolationError):
104.164 - """Raised when the source text into which substitutions are made
104.165 - does not conform to the required syntax."""
104.166 -
104.167 -class InterpolationDepthError(InterpolationError):
104.168 - """Raised when substitutions are nested too deeply."""
104.169 -
104.170 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:option<|, |>PARAMETER:section<|, |>PARAMETER:rawval<|):
104.171 - msg = ("Value interpolation too deeply recursive:\n"
104.172 - "\tsection: [%s]\n"
104.173 - "\toption : %s\n"
104.174 - "\trawval : %s\n"
104.175 - % (|>PARAMETER:section<|, |>PARAMETER:option<|, |>PARAMETER:rawval<|))
104.176 - InterpolationError.__init__(|>PARAMETER:self<|, |>PARAMETER:option<|, |>PARAMETER:section<|, msg)
104.177 -
104.178 -class ParsingError(Error):
104.179 - """Raised when a configuration file does not follow legal syntax."""
104.180 -
104.181 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:filename<|):
104.182 - Error.__init__(|>PARAMETER:self<|, 'File contains parsing errors: %s' % |>PARAMETER:filename<|)
104.183 - |>PARAMETER:self<|.filename = |>PARAMETER:filename<|
104.184 - |>PARAMETER:self<|.errors = []
104.185 -
104.186 - def |>METHOD:append<|(|>PARAMETER:self<|, |>PARAMETER:lineno<|, |>PARAMETER:line<|):
104.187 - |>PARAMETER:self<|.errors.append((|>PARAMETER:lineno<|, |>PARAMETER:line<|))
104.188 - |>PARAMETER:self<|.message += '\n\t[line %2d]: %s' % (|>PARAMETER:lineno<|, |>PARAMETER:line<|)
104.189 -
104.190 -class MissingSectionHeaderError(ParsingError):
104.191 - """Raised when a key-value pair is found before any section header."""
104.192 -
104.193 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:filename<|, |>PARAMETER:lineno<|, |>PARAMETER:line<|):
104.194 - Error.__init__(
104.195 - |>PARAMETER:self<|,
104.196 - 'File contains no section headers.\nfile: %s, line: %d\n%s' %
104.197 - (|>PARAMETER:filename<|, |>PARAMETER:lineno<|, |>PARAMETER:line<|))
104.198 - |>PARAMETER:self<|.filename = |>PARAMETER:filename<|
104.199 - |>PARAMETER:self<|.lineno = |>PARAMETER:lineno<|
104.200 - |>PARAMETER:self<|.line = |>PARAMETER:line<|
104.201 -
104.202 -
104.203 -
104.204 -class RawConfigParser:
104.205 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:defaults<|=None):
104.206 - |>PARAMETER:self<|._sections = {}
104.207 - if |>PARAMETER:defaults<| is None:
104.208 - |>PARAMETER:self<|._defaults = {}
104.209 - else:
104.210 - |>PARAMETER:self<|._defaults = |>PARAMETER:defaults<|
104.211 -
104.212 - def |>METHOD:defaults<|(|>PARAMETER:self<|):
104.213 - return |>PARAMETER:self<|._defaults
104.214 -
104.215 - def |>METHOD:sections<|(|>PARAMETER:self<|):
104.216 - """Return a list of section names, excluding [DEFAULT]"""
104.217 - # self._sections will never have [DEFAULT] in it
104.218 - return |>PARAMETER:self<|._sections.keys()
104.219 -
104.220 - def |>METHOD:add_section<|(|>PARAMETER:self<|, |>PARAMETER:section<|):
104.221 - """Create a new section in the configuration.
104.222 -
104.223 - Raise DuplicateSectionError if a section by the specified name
104.224 - already exists.
104.225 - """
104.226 - if |>PARAMETER:section<| in |>PARAMETER:self<|._sections:
104.227 - raise DuplicateSectionError(|>PARAMETER:section<|)
104.228 - |>PARAMETER:self<|._sections[|>PARAMETER:section<|] = {}
104.229 -
104.230 - def |>METHOD:has_section<|(|>PARAMETER:self<|, |>PARAMETER:section<|):
104.231 - """Indicate whether the named section is present in the configuration.
104.232 -
104.233 - The DEFAULT section is not acknowledged.
104.234 - """
104.235 - return |>PARAMETER:section<| in |>PARAMETER:self<|._sections
104.236 -
104.237 - def |>METHOD:options<|(|>PARAMETER:self<|, |>PARAMETER:section<|):
104.238 - """Return a list of option names for the given section name."""
104.239 - try:
104.240 - opts = |>PARAMETER:self<|._sections[|>PARAMETER:section<|].copy()
104.241 - except KeyError:
104.242 - raise NoSectionError(|>PARAMETER:section<|)
104.243 - opts.update(|>PARAMETER:self<|._defaults)
104.244 - if '__name__' in opts:
104.245 - del opts['__name__']
104.246 - return opts.keys()
104.247 -
104.248 - def |>METHOD:read<|(|>PARAMETER:self<|, |>PARAMETER:filenames<|):
104.249 - """Read and parse a filename or a list of filenames.
104.250 -
104.251 - Files that cannot be opened are silently ignored; this is
104.252 - designed so that you can specify a list of potential
104.253 - configuration file locations (e.g. current directory, user's
104.254 - home directory, systemwide directory), and all existing
104.255 - configuration files in the list will be read. A single
104.256 - filename may also be given.
104.257 - """
104.258 - if isinstance(|>PARAMETER:filenames<|, basestring):
104.259 - |>PARAMETER:filenames<| = [|>PARAMETER:filenames<|]
104.260 - for filename in |>PARAMETER:filenames<|:
104.261 - try:
104.262 - fp = open(filename)
104.263 - except IOError:
104.264 - continue
104.265 - |>PARAMETER:self<|._read(fp, filename)
104.266 - fp.close()
104.267 -
104.268 - def |>METHOD:readfp<|(|>PARAMETER:self<|, |>PARAMETER:fp<|, |>PARAMETER:filename<|=None):
104.269 - """Like read() but the argument must be a file-like object.
104.270 -
104.271 - The `fp' argument must have a `readline' method. Optional
104.272 - second argument is the `filename', which if not given, is
104.273 - taken from fp.name. If fp has no `name' attribute, `<???>' is
104.274 - used.
104.275 -
104.276 - """
104.277 - if |>PARAMETER:filename<| is None:
104.278 - try:
104.279 - |>PARAMETER:filename<| = |>PARAMETER:fp<|.name
104.280 - except AttributeError:
104.281 - |>PARAMETER:filename<| = '<???>'
104.282 - |>PARAMETER:self<|._read(|>PARAMETER:fp<|, |>PARAMETER:filename<|)
104.283 -
104.284 - def |>METHOD:get<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|):
104.285 - opt = |>PARAMETER:self<|.optionxform(|>PARAMETER:option<|)
104.286 - if |>PARAMETER:section<| not in |>PARAMETER:self<|._sections:
104.287 - if |>PARAMETER:section<| != DEFAULTSECT:
104.288 - raise NoSectionError(|>PARAMETER:section<|)
104.289 - if opt in |>PARAMETER:self<|._defaults:
104.290 - return |>PARAMETER:self<|._defaults[opt]
104.291 - else:
104.292 - raise NoOptionError(|>PARAMETER:option<|, |>PARAMETER:section<|)
104.293 - elif opt in |>PARAMETER:self<|._sections[|>PARAMETER:section<|]:
104.294 - return |>PARAMETER:self<|._sections[|>PARAMETER:section<|][opt]
104.295 - elif opt in |>PARAMETER:self<|._defaults:
104.296 - return |>PARAMETER:self<|._defaults[opt]
104.297 - else:
104.298 - raise NoOptionError(|>PARAMETER:option<|, |>PARAMETER:section<|)
104.299 -
104.300 - def |>METHOD:items<|(|>PARAMETER:self<|, |>PARAMETER:section<|):
104.301 - try:
104.302 - d2 = |>PARAMETER:self<|._sections[|>PARAMETER:section<|]
104.303 - except KeyError:
104.304 - if |>PARAMETER:section<| != DEFAULTSECT:
104.305 - raise NoSectionError(|>PARAMETER:section<|)
104.306 - d2 = {}
104.307 - d = |>PARAMETER:self<|._defaults.copy()
104.308 - d.update(d2)
104.309 - if "__name__" in d:
104.310 - del d["__name__"]
104.311 - return d.items()
104.312 -
104.313 - def |>METHOD:_get<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:conv<|, |>PARAMETER:option<|):
104.314 - return |>PARAMETER:conv<|(|>PARAMETER:self<|.get(|>PARAMETER:section<|, |>PARAMETER:option<|))
104.315 -
104.316 - def |>METHOD:getint<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|):
104.317 - return |>PARAMETER:self<|._get(|>PARAMETER:section<|, int, |>PARAMETER:option<|)
104.318 -
104.319 - def |>METHOD:getfloat<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|):
104.320 - return |>PARAMETER:self<|._get(|>PARAMETER:section<|, float, |>PARAMETER:option<|)
104.321 -
104.322 - _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
104.323 - '0': False, 'no': False, 'false': False, 'off': False}
104.324 -
104.325 - def |>METHOD:getboolean<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|):
104.326 - v = |>PARAMETER:self<|.get(|>PARAMETER:section<|, |>PARAMETER:option<|)
104.327 - if v.lower() not in |>PARAMETER:self<|._boolean_states:
104.328 - raise ValueError, 'Not a boolean: %s' % v
104.329 - return |>PARAMETER:self<|._boolean_states[v.lower()]
104.330 -
104.331 - def |>METHOD:optionxform<|(|>PARAMETER,UNUSED:self<|, |>PARAMETER:optionstr<|):
104.332 - return |>PARAMETER:optionstr<|.lower()
104.333 -
104.334 - def |>METHOD:has_option<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|):
104.335 - """Check for the existence of a given option in a given section."""
104.336 - if not |>PARAMETER:section<| or |>PARAMETER:section<| == DEFAULTSECT:
104.337 - |>PARAMETER:option<| = |>PARAMETER:self<|.optionxform(|>PARAMETER:option<|)
104.338 - return |>PARAMETER:option<| in |>PARAMETER:self<|._defaults
104.339 - elif |>PARAMETER:section<| not in |>PARAMETER:self<|._sections:
104.340 - return False
104.341 - else:
104.342 - |>PARAMETER:option<| = |>PARAMETER:self<|.optionxform(|>PARAMETER:option<|)
104.343 - return (|>PARAMETER:option<| in |>PARAMETER:self<|._sections[|>PARAMETER:section<|]
104.344 - or |>PARAMETER:option<| in |>PARAMETER:self<|._defaults)
104.345 -
104.346 - def |>METHOD:set<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|, |>PARAMETER:value<|):
104.347 - """Set an option."""
104.348 - if not |>PARAMETER:section<| or |>PARAMETER:section<| == DEFAULTSECT:
104.349 - sectdict = |>PARAMETER:self<|._defaults
104.350 - else:
104.351 - try:
104.352 - sectdict = |>PARAMETER:self<|._sections[|>PARAMETER:section<|]
104.353 - except KeyError:
104.354 - raise NoSectionError(|>PARAMETER:section<|)
104.355 - sectdict[|>PARAMETER:self<|.optionxform(|>PARAMETER:option<|)] = |>PARAMETER:value<|
104.356 -
104.357 - def |>METHOD:write<|(|>PARAMETER:self<|, |>PARAMETER:fp<|):
104.358 - """Write an .ini-format representation of the configuration state."""
104.359 - if |>PARAMETER:self<|._defaults:
104.360 - |>PARAMETER:fp<|.write("[%s]\n" % DEFAULTSECT)
104.361 - for (key, value) in |>PARAMETER:self<|._defaults.items():
104.362 - |>PARAMETER:fp<|.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
104.363 - |>PARAMETER:fp<|.write("\n")
104.364 - for section in |>PARAMETER:self<|._sections:
104.365 - |>PARAMETER:fp<|.write("[%s]\n" % section)
104.366 - for (key, value) in |>PARAMETER:self<|._sections[section].items():
104.367 - if key != "__name__":
104.368 - |>PARAMETER:fp<|.write("%s = %s\n" %
104.369 - (key, str(value).replace('\n', '\n\t')))
104.370 - |>PARAMETER:fp<|.write("\n")
104.371 -
104.372 - def |>METHOD:remove_option<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|):
104.373 - """Remove an option."""
104.374 - if not |>PARAMETER:section<| or |>PARAMETER:section<| == DEFAULTSECT:
104.375 - sectdict = |>PARAMETER:self<|._defaults
104.376 - else:
104.377 - try:
104.378 - sectdict = |>PARAMETER:self<|._sections[|>PARAMETER:section<|]
104.379 - except KeyError:
104.380 - raise NoSectionError(|>PARAMETER:section<|)
104.381 - |>PARAMETER:option<| = |>PARAMETER:self<|.optionxform(|>PARAMETER:option<|)
104.382 - existed = |>PARAMETER:option<| in sectdict
104.383 - if existed:
104.384 - del sectdict[|>PARAMETER:option<|]
104.385 - return existed
104.386 -
104.387 - def |>METHOD:remove_section<|(|>PARAMETER:self<|, |>PARAMETER:section<|):
104.388 - """Remove a file section."""
104.389 - existed = |>PARAMETER:section<| in |>PARAMETER:self<|._sections
104.390 - if existed:
104.391 - del |>PARAMETER:self<|._sections[|>PARAMETER:section<|]
104.392 - return existed
104.393 -
104.394 - #
104.395 - # Regular expressions for parsing section headers and options.
104.396 - #
104.397 - SECTCRE = re.compile(
104.398 - r'\[' # [
104.399 - r'(?P<header>[^]]+)' # very permissive!
104.400 - r'\]' # ]
104.401 - )
104.402 - OPTCRE = re.compile(
104.403 - r'(?P<option>[^:=\s][^:=]*)' # very permissive!
104.404 - r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
104.405 - # followed by separator
104.406 - # (either : or =), followed
104.407 - # by any # space/tab
104.408 - r'(?P<value>.*)$' # everything up to eol
104.409 - )
104.410 -
104.411 - def |>METHOD:_read<|(|>PARAMETER:self<|, |>PARAMETER:fp<|, |>PARAMETER:fpname<|):
104.412 - """Parse a sectioned setup file.
104.413 -
104.414 - The sections in setup file contains a title line at the top,
104.415 - indicated by a name in square brackets (`[]'), plus key/value
104.416 - options lines, indicated by `name: value' format lines.
104.417 - Continuations are represented by an embedded newline then
104.418 - leading whitespace. Blank lines, lines beginning with a '#',
104.419 - and just about everything else are ignored.
104.420 - """
104.421 - cursect = None # None, or a dictionary
104.422 - optname = None
104.423 - lineno = 0
104.424 - e = None # None, or an exception
104.425 - while True:
104.426 - line = |>PARAMETER:fp<|.readline()
104.427 - if not line:
104.428 - break
104.429 - lineno = lineno + 1
104.430 - # comment or blank line?
104.431 - if line.strip() == '' or line[0] in '#;':
104.432 - continue
104.433 - if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
104.434 - # no leading whitespace
104.435 - continue
104.436 - # continuation line?
104.437 - if line[0].isspace() and cursect is not None and optname:
104.438 - value = line.strip()
104.439 - if value:
104.440 - cursect[optname] = "%s\n%s" % (cursect[optname], value)
104.441 - # a section header or option header?
104.442 - else:
104.443 - # is it a section header?
104.444 - mo = |>PARAMETER:self<|.SECTCRE.match(line)
104.445 - if mo:
104.446 - sectname = mo.group('header')
104.447 - if sectname in |>PARAMETER:self<|._sections:
104.448 - cursect = |>PARAMETER:self<|._sections[sectname]
104.449 - elif sectname == DEFAULTSECT:
104.450 - cursect = |>PARAMETER:self<|._defaults
104.451 - else:
104.452 - cursect = {'__name__': sectname}
104.453 - |>PARAMETER:self<|._sections[sectname] = cursect
104.454 - # So sections can't start with a continuation line
104.455 - optname = None
104.456 - # no section header in the file?
104.457 - elif cursect is None:
104.458 - raise MissingSectionHeaderError(|>PARAMETER:fpname<|, lineno, `line`)
104.459 - # an option line?
104.460 - else:
104.461 - mo = |>PARAMETER:self<|.OPTCRE.match(line)
104.462 - if mo:
104.463 - optname, vi, optval = mo.group('option', 'vi', 'value')
104.464 - if vi in ('=', ':') and ';' in optval:
104.465 - # ';' is a comment delimiter only if it follows
104.466 - # a spacing character
104.467 - pos = optval.find(';')
104.468 - if pos != -1 and optval[pos-1].isspace():
104.469 - optval = optval[:pos]
104.470 - optval = optval.strip()
104.471 - # allow empty values
104.472 - if optval == '""':
104.473 - optval = ''
104.474 - optname = |>PARAMETER:self<|.optionxform(optname.rstrip())
104.475 - cursect[optname] = optval
104.476 - else:
104.477 - # a non-fatal parsing error occurred. set up the
104.478 - # exception but keep going. the exception will be
104.479 - # raised at the end of the file and will contain a
104.480 - # list of all bogus lines
104.481 - if not e:
104.482 - e = ParsingError(|>PARAMETER:fpname<|)
104.483 - e.append(lineno, `line`)
104.484 - # if any parsing errors occurred, raise an exception
104.485 - if e:
104.486 - raise e
104.487 -
104.488 -
104.489 -class ConfigParser(RawConfigParser):
104.490 -
104.491 - def |>METHOD:get<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|, |>PARAMETER:raw<|=False, |>PARAMETER:vars<|=None):
104.492 - """Get an option value for a given section.
104.493 -
104.494 - All % interpolations are expanded in the return values, based on the
104.495 - defaults passed into the constructor, unless the optional argument
104.496 - `raw' is true. Additional substitutions may be provided using the
104.497 - `vars' argument, which must be a dictionary whose contents overrides
104.498 - any pre-existing defaults.
104.499 -
104.500 - The section DEFAULT is special.
104.501 - """
104.502 - d = |>PARAMETER:self<|._defaults.copy()
104.503 - try:
104.504 - d.update(|>PARAMETER:self<|._sections[|>PARAMETER:section<|])
104.505 - except KeyError:
104.506 - if |>PARAMETER:section<| != DEFAULTSECT:
104.507 - raise NoSectionError(|>PARAMETER:section<|)
104.508 - # Update with the entry specific variables
104.509 - if |>PARAMETER:vars<| is not None:
104.510 - d.update(|>PARAMETER:vars<|)
104.511 - |>PARAMETER:option<| = |>PARAMETER:self<|.optionxform(|>PARAMETER:option<|)
104.512 - try:
104.513 - value = d[|>PARAMETER:option<|]
104.514 - except KeyError:
104.515 - raise NoOptionError(|>PARAMETER:option<|, |>PARAMETER:section<|)
104.516 -
104.517 - if |>PARAMETER:raw<|:
104.518 - return value
104.519 - else:
104.520 - return |>PARAMETER:self<|._interpolate(|>PARAMETER:section<|, |>PARAMETER:option<|, value, d)
104.521 -
104.522 - def |>METHOD:items<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:raw<|=False, |>PARAMETER:vars<|=None):
104.523 - """Return a list of tuples with (name, value) for each option
104.524 - in the section.
104.525 -
104.526 - All % interpolations are expanded in the return values, based on the
104.527 - defaults passed into the constructor, unless the optional argument
104.528 - `raw' is true. Additional substitutions may be provided using the
104.529 - `vars' argument, which must be a dictionary whose contents overrides
104.530 - any pre-existing defaults.
104.531 -
104.532 - The section DEFAULT is special.
104.533 - """
104.534 - d = |>PARAMETER:self<|._defaults.copy()
104.535 - try:
104.536 - d.update(|>PARAMETER:self<|._sections[|>PARAMETER:section<|])
104.537 - except KeyError:
104.538 - if |>PARAMETER:section<| != DEFAULTSECT:
104.539 - raise NoSectionError(|>PARAMETER:section<|)
104.540 - # Update with the entry specific variables
104.541 - if |>PARAMETER:vars<|:
104.542 - d.update(|>PARAMETER:vars<|)
104.543 - options = d.keys()
104.544 - if "__name__" in options:
104.545 - options.remove("__name__")
104.546 - if |>PARAMETER:raw<|:
104.547 - return [(option, d[option])
104.548 - for option in options]
104.549 - else:
104.550 - return [(option, |>PARAMETER:self<|._interpolate(|>PARAMETER:section<|, option, d[option], d))
104.551 - for option in options]
104.552 -
104.553 - def |>METHOD:_interpolate<|(|>PARAMETER,UNUSED:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|, |>PARAMETER:rawval<|, |>PARAMETER:vars<|):
104.554 - # do the string interpolation
104.555 - value = |>PARAMETER:rawval<|
104.556 - depth = MAX_INTERPOLATION_DEPTH
104.557 - while depth: # Loop through this until it's done
104.558 - depth -= 1
104.559 - if value.find("%(") != -1:
104.560 - try:
104.561 - value = value % |>PARAMETER:vars<|
104.562 - except KeyError, e:
104.563 - raise InterpolationMissingOptionError(
104.564 - |>PARAMETER:option<|, |>PARAMETER:section<|, |>PARAMETER:rawval<|, e[0])
104.565 - else:
104.566 - break
104.567 - if value.find("%(") != -1:
104.568 - raise InterpolationDepthError(|>PARAMETER:option<|, |>PARAMETER:section<|, |>PARAMETER:rawval<|)
104.569 - return value
104.570 -
104.571 -
104.572 -class SafeConfigParser(ConfigParser):
104.573 -
104.574 - def |>METHOD:_interpolate<|(|>PARAMETER:self<|, |>PARAMETER:section<|, |>PARAMETER:option<|, |>PARAMETER:rawval<|, |>PARAMETER:vars<|):
104.575 - # do the string interpolation
104.576 - L = []
104.577 - |>PARAMETER:self<|._interpolate_some(|>PARAMETER:option<|, L, |>PARAMETER:rawval<|, |>PARAMETER:section<|, |>PARAMETER:vars<|, 1)
104.578 - return ''.join(L)
104.579 -
104.580 - _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
104.581 -
104.582 - def |>METHOD:_interpolate_some<|(|>PARAMETER:self<|, |>PARAMETER:option<|, |>PARAMETER:accum<|, |>PARAMETER:rest<|, |>PARAMETER:section<|, |>PARAMETER:map<|, |>PARAMETER:depth<|):
104.583 - if |>PARAMETER:depth<| > MAX_INTERPOLATION_DEPTH:
104.584 - raise InterpolationDepthError(|>PARAMETER:option<|, |>PARAMETER:section<|, |>PARAMETER:rest<|)
104.585 - while |>PARAMETER:rest<|:
104.586 - p = |>PARAMETER:rest<|.find("%")
104.587 - if p < 0:
104.588 - |>PARAMETER:accum<|.append(|>PARAMETER:rest<|)
104.589 - return
104.590 - if p > 0:
104.591 - |>PARAMETER:accum<|.append(|>PARAMETER:rest<|[:p])
104.592 - |>PARAMETER:rest<| = |>PARAMETER:rest<|[p:]
104.593 - # p is no longer used
104.594 - c = |>PARAMETER:rest<|[1:2]
104.595 - if c == "%":
104.596 - |>PARAMETER:accum<|.append("%")
104.597 - |>PARAMETER:rest<| = |>PARAMETER:rest<|[2:]
104.598 - elif c == "(":
104.599 - m = |>PARAMETER:self<|._interpvar_match(|>PARAMETER:rest<|)
104.600 - if m is None:
104.601 - raise InterpolationSyntaxError(|>PARAMETER:option<|, |>PARAMETER:section<|,
104.602 - "bad interpolation variable reference %r" % |>PARAMETER:rest<|)
104.603 - var = m.group(1)
104.604 - |>PARAMETER:rest<| = |>PARAMETER:rest<|[m.end():]
104.605 - try:
104.606 - v = |>PARAMETER:map<|[var]
104.607 - except KeyError:
104.608 - raise InterpolationMissingOptionError(
104.609 - |>PARAMETER:option<|, |>PARAMETER:section<|, |>PARAMETER:rest<|, var)
104.610 - if "%" in v:
104.611 - |>PARAMETER:self<|._interpolate_some(|>PARAMETER:option<|, |>PARAMETER:accum<|, v,
104.612 - |>PARAMETER:section<|, |>PARAMETER:map<|, |>PARAMETER:depth<| + 1)
104.613 - else:
104.614 - |>PARAMETER:accum<|.append(v)
104.615 - else:
104.616 - raise InterpolationSyntaxError(
104.617 - |>PARAMETER:option<|, |>PARAMETER:section<|,
104.618 - "'%' must be followed by '%' or '(', found: " + `ret`)
105.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.structure Sun Jan 04 13:11:53 2015 -0600
105.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
105.3 @@ -1,65 +0,0 @@
105.4 -Error:CLASS:[PRIVATE]:ESCAPED{Error}:
105.5 - __init__:CONSTRUCTOR:[PRIVATE]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{msg}}):
105.6 - __repr__:METHOD:[PRIVATE]:ESCAPED{__repr__}(PARAMETERS{ESCAPED{self}}):
105.7 - message:ATTRIBUTE:[]:ESCAPED{message}:
105.8 -NoSectionError:CLASS:[]:ESCAPED{NoSectionError}:
105.9 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}}):
105.10 - section:ATTRIBUTE:[]:ESCAPED{section}:
105.11 -DuplicateSectionError:CLASS:[]:ESCAPED{DuplicateSectionError}:
105.12 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}}):
105.13 - section:ATTRIBUTE:[]:ESCAPED{section}:
105.14 -NoOptionError:CLASS:[]:ESCAPED{NoOptionError}:
105.15 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{option}ESCAPED{,}ESCAPED{section}}):
105.16 - option:ATTRIBUTE:[]:ESCAPED{option}:
105.17 - section:ATTRIBUTE:[]:ESCAPED{section}:
105.18 -InterpolationError:CLASS:[]:ESCAPED{InterpolationError}:
105.19 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{option}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{msg}}):
105.20 - option:ATTRIBUTE:[]:ESCAPED{option}:
105.21 - section:ATTRIBUTE:[]:ESCAPED{section}:
105.22 -InterpolationMissingOptionError:CLASS:[PRIVATE]:ESCAPED{InterpolationMissingOptionError}:
105.23 - __init__:CONSTRUCTOR:[PRIVATE]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{option}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{rawval}ESCAPED{,}ESCAPED{reference}}):
105.24 - reference:ATTRIBUTE:[]:ESCAPED{reference}:
105.25 -InterpolationSyntaxError:CLASS:[]:ESCAPED{InterpolationSyntaxError}:
105.26 -InterpolationDepthError:CLASS:[]:ESCAPED{InterpolationDepthError}:
105.27 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{option}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{rawval}}):
105.28 -ParsingError:CLASS:[]:ESCAPED{ParsingError}:
105.29 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{filename}}):
105.30 - append:METHOD:[]:ESCAPED{append}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{lineno}ESCAPED{,}ESCAPED{line}}):
105.31 - errors:ATTRIBUTE:[]:ESCAPED{errors}:
105.32 - filename:ATTRIBUTE:[]:ESCAPED{filename}:
105.33 -MissingSectionHeaderError:CLASS:[]:ESCAPED{MissingSectionHeaderError}:
105.34 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{filename}ESCAPED{,}ESCAPED{lineno}ESCAPED{,}ESCAPED{line}}):
105.35 - filename:ATTRIBUTE:[]:ESCAPED{filename}:
105.36 - line:ATTRIBUTE:[]:ESCAPED{line}:
105.37 - lineno:ATTRIBUTE:[]:ESCAPED{lineno}:
105.38 -RawConfigParser:CLASS:[PRIVATE]:ESCAPED{RawConfigParser}:
105.39 - __init__:CONSTRUCTOR:[PRIVATE]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{defaults}}):
105.40 - _defaults:ATTRIBUTE:[]:ESCAPED{_defaults}:
105.41 - _get:METHOD:[PRIVATE]:ESCAPED{_get}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{conv}ESCAPED{,}ESCAPED{option}}):
105.42 - _read:METHOD:[PRIVATE]:ESCAPED{_read}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{fp}ESCAPED{,}ESCAPED{fpname}}):
105.43 - _sections:ATTRIBUTE:[]:ESCAPED{_sections}:
105.44 - add_section:METHOD:[PRIVATE]:ESCAPED{add_section}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}}):
105.45 - defaults:METHOD:[PRIVATE]:ESCAPED{defaults}(PARAMETERS{ESCAPED{self}}):
105.46 - get:METHOD:[PRIVATE]:ESCAPED{get}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}}):
105.47 - getboolean:METHOD:[PRIVATE]:ESCAPED{getboolean}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}}):
105.48 - getfloat:METHOD:[PRIVATE]:ESCAPED{getfloat}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}}):
105.49 - getint:METHOD:[PRIVATE]:ESCAPED{getint}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}}):
105.50 - has_option:METHOD:[PRIVATE]:ESCAPED{has_option}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}}):
105.51 - has_section:METHOD:[PRIVATE]:ESCAPED{has_section}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}}):
105.52 - items:METHOD:[PRIVATE]:ESCAPED{items}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}}):
105.53 - options:METHOD:[PRIVATE]:ESCAPED{options}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}}):
105.54 - optionxform:METHOD:[PRIVATE]:ESCAPED{optionxform}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{optionstr}}):
105.55 - read:METHOD:[PRIVATE]:ESCAPED{read}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{filenames}}):
105.56 - readfp:METHOD:[PRIVATE]:ESCAPED{readfp}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{fp}ESCAPED{,}ESCAPED{filename}}):
105.57 - remove_option:METHOD:[PRIVATE]:ESCAPED{remove_option}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}}):
105.58 - remove_section:METHOD:[PRIVATE]:ESCAPED{remove_section}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}}):
105.59 - sections:METHOD:[PRIVATE]:ESCAPED{sections}(PARAMETERS{ESCAPED{self}}):
105.60 - set:METHOD:[PRIVATE]:ESCAPED{set}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}ESCAPED{,}ESCAPED{value}}):
105.61 - write:METHOD:[PRIVATE]:ESCAPED{write}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{fp}}):
105.62 -ConfigParser:CLASS:[]:ESCAPED{ConfigParser}:
105.63 - _interpolate:METHOD:[PRIVATE]:ESCAPED{_interpolate}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}ESCAPED{,}ESCAPED{rawval}ESCAPED{,}ESCAPED{vars}}):
105.64 - get:METHOD:[]:ESCAPED{get}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}ESCAPED{,}ESCAPED{raw}ESCAPED{,}ESCAPED{vars}}):
105.65 - items:METHOD:[]:ESCAPED{items}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{raw}ESCAPED{,}ESCAPED{vars}}):
105.66 -SafeConfigParser:CLASS:[]:ESCAPED{SafeConfigParser}:
105.67 - _interpolate:METHOD:[PRIVATE]:ESCAPED{_interpolate}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{option}ESCAPED{,}ESCAPED{rawval}ESCAPED{,}ESCAPED{vars}}):
105.68 - _interpolate_some:METHOD:[PRIVATE]:ESCAPED{_interpolate_some}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{option}ESCAPED{,}ESCAPED{accum}ESCAPED{,}ESCAPED{rest}ESCAPED{,}ESCAPED{section}ESCAPED{,}ESCAPED{map}ESCAPED{,}ESCAPED{depth}}):
106.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testClasses.completion Sun Jan 04 13:11:53 2015 -0600
106.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
106.3 @@ -1,1241 +0,0 @@
106.4 -Code completion result for source line:
106.5 -|self.section = section
106.6 -(QueryType=COMPLETION, NameKind=PREFIX)
106.7 -MODULE re [PRIVATE]
106.8 -CLASS ConfigParser
106.9 -CLASS DuplicateSectionError
106.10 -CLASS Error [PRIVATE]
106.11 -CLASS InterpolationDepthError
106.12 -CLASS InterpolationError
106.13 -CLASS InterpolationMissingOptionErro [PRIVATE]
106.14 -CLASS InterpolationSyntaxError
106.15 -CLASS MissingSectionHeaderError
106.16 -CLASS NoOptionError
106.17 -CLASS NoSectionError
106.18 -CLASS ParsingError
106.19 -CLASS RawConfigParser [PRIVATE]
106.20 -CLASS SafeConfigParser
106.21 -VARIABLE DEFAULTSECT
106.22 -VARIABLE MAX_INTERPOLATION_DEPTH
106.23 -VARIABLE __all__
106.24 -VARIABLE section
106.25 -VARIABLE self
106.26 -------------------------------------
106.27 -CLASS A
106.28 -CLASS ABCMeta
106.29 -CLASS AEServer
106.30 -CLASS AEText
106.31 -CLASS ASTVisitor
106.32 -CLASS AbstractBasicAuthHandler
106.33 -CLASS AbstractClassCode
106.34 -CLASS AbstractCompileMode
106.35 -CLASS AbstractDigestAuthHandler
106.36 -CLASS AbstractFormatter
106.37 -CLASS AbstractFunctionCode
106.38 -CLASS AbstractHTTPHandler
106.39 -CLASS AbstractWriter
106.40 -CLASS Add
106.41 -CLASS AddressList
106.42 -CLASS And
106.43 -CLASS Application
106.44 -CLASS ArgumentError
106.45 -CLASS ArithmeticError
106.46 -CLASS ArithmeticError
106.47 -CLASS Array
106.48 -CLASS ArrayInstance
106.49 -CLASS AssAttr
106.50 -CLASS AssList
106.51 -CLASS AssName
106.52 -CLASS AssTuple
106.53 -CLASS Assert
106.54 -CLASS AssertionError
106.55 -CLASS AssertionError
106.56 -CLASS Assign
106.57 -CLASS AsyncResult
106.58 -CLASS Attr
106.59 -CLASS AttributeError
106.60 -CLASS AttributeError
106.61 -CLASS AttributeList
106.62 -CLASS AttributeMap
106.63 -CLASS Attributes
106.64 -CLASS AttributesImpl
106.65 -CLASS AttributesNS
106.66 -CLASS AttributesNSImpl
106.67 -CLASS AugAssign
106.68 -CLASS AugGetattr
106.69 -CLASS AugName
106.70 -CLASS AugSlice
106.71 -CLASS AugSubscript
106.72 -CLASS AuthenticationError
106.73 -CLASS AutoGILError
106.74 -CLASS B
106.75 -CLASS BCPPCompiler
106.76 -CLASS BCPTestCase
106.77 -CLASS BZ2Compressor
106.78 -CLASS BZ2Decompressor
106.79 -CLASS BZ2File
106.80 -CLASS Babyl
106.81 -CLASS BabylMailbox
106.82 -CLASS BabylMessage
106.83 -CLASS Backquote
106.84 -CLASS BadBoundaryPointsErr
106.85 -CLASS BadFutureParser
106.86 -CLASS BadOptionError
106.87 -CLASS BadStatusLine
106.88 -CLASS BadZipfile
106.89 -CLASS Balloon
106.90 -CLASS Bar
106.91 -CLASS BaseCGIHandler
106.92 -CLASS BaseCookie
106.93 -CLASS BaseException
106.94 -CLASS BaseException
106.95 -CLASS BaseHTTPRequestHandler
106.96 -CLASS BaseHandler
106.97 -CLASS BaseIncrementalParser
106.98 -CLASS BaseManager
106.99 -CLASS BaseProxy
106.100 -CLASS BaseRequestHandler
106.101 -CLASS BaseRotatingHandler
106.102 -CLASS BaseSet
106.103 -CLASS BasicModuleImporter
106.104 -CLASS BasicModuleLoader
106.105 -CLASS BastionClass
106.106 -CLASS Baz
106.107 -CLASS Bdb
106.108 -CLASS BdbQuit
106.109 -CLASS BigEndianStructure
106.110 -CLASS Binary
106.111 -CLASS Bitand
106.112 -CLASS Bitor
106.113 -CLASS Bitxor
106.114 -CLASS Block
106.115 -CLASS BlockFinder
106.116 -CLASS BlockingIOError
106.117 -CLASS Boolean
106.118 -CLASS BoundaryError
106.119 -CLASS BoundedSemaphore
106.120 -CLASS Break
106.121 -CLASS Breakpoint
106.122 -CLASS BsdDbShelf
106.123 -CLASS BufferTooShort
106.124 -CLASS BufferedIOBase
106.125 -CLASS BufferedRWPair
106.126 -CLASS BufferedRandom
106.127 -CLASS BufferedReader
106.128 -CLASS BufferedWriter
106.129 -CLASS BufferingFormatter
106.130 -CLASS BufferingHandler
106.131 -CLASS BuildPyTestCase
106.132 -CLASS BuildScriptsTestCase
106.133 -CLASS BuiltinImporter
106.134 -CLASS Bulkcopy
106.135 -CLASS ButtonBox
106.136 -CLASS BytesIO
106.137 -CLASS C
106.138 -CLASS CAB
106.139 -CLASS CCompiler
106.140 -CLASS CCompilerError
106.141 -CLASS CDATASection
106.142 -CLASS CDLL
106.143 -CLASS CGIHTTPRequestHandler
106.144 -CLASS CGIHandler
106.145 -CLASS CGIXMLRPCRequestHandler
106.146 -CLASS CacheFTPHandler
106.147 -CLASS CallFunc
106.148 -CLASS CalledProcessError
106.149 -CLASS CannotSendHeader
106.150 -CLASS CannotSendRequest
106.151 -CLASS Canonizer
106.152 -CLASS CharacterData
106.153 -CLASS Charset
106.154 -CLASS CharsetError
106.155 -CLASS CheckList
106.156 -CLASS Childless
106.157 -CLASS Chunk
106.158 -CLASS Clamped
106.159 -CLASS Class
106.160 -CLASS ClassCodeGenerator
106.161 -CLASS ClassScope
106.162 -CLASS Cmd
106.163 -CLASS CodeGenerator
106.164 -CLASS Codec
106.165 -CLASS CodecRegistryError
106.166 -CLASS ComboBox
106.167 -CLASS Command
106.168 -CLASS CommandCompiler
106.169 -CLASS Comment
106.170 -CLASS Compare
106.171 -CLASS Comparison
106.172 -CLASS Compile
106.173 -CLASS CompileError
106.174 -CLASS Completer
106.175 -CLASS Complex
106.176 -CLASS ComponentItem
106.177 -CLASS Condition
106.178 -CLASS ConfigParser
106.179 -CLASS Connection
106.180 -CLASS Const
106.181 -CLASS ContentGenerator
106.182 -CLASS ContentHandler
106.183 -CLASS Context
106.184 -CLASS Continue
106.185 -CLASS Control
106.186 -CLASS ControlsWindow
106.187 -CLASS ConversionError
106.188 -CLASS Cookie
106.189 -CLASS CookieError
106.190 -CLASS CookieJar
106.191 -CLASS CookiePolicy
106.192 -CLASS CoverageResults
106.193 -CLASS Cursor
106.194 -CLASS CygwinCCompiler
106.195 -CLASS D
106.196 -CLASS DOMBuilder
106.197 -CLASS DOMEntityResolver
106.198 -CLASS DOMError
106.199 -CLASS DOMEventStream
106.200 -CLASS DOMException
106.201 -CLASS DOMImplementation
106.202 -CLASS DOMInputSource
106.203 -CLASS DOMStringSizeErr
106.204 -CLASS DTDHandler
106.205 -CLASS Data
106.206 -CLASS Database
106.207 -CLASS DatagramHandler
106.208 -CLASS DatagramRequestHandler
106.209 -CLASS DateTime
106.210 -CLASS DbfilenameShelf
106.211 -CLASS DebugRunner
106.212 -CLASS DebuggingServer
106.213 -CLASS Decimal
106.214 -CLASS DecimalException
106.215 -CLASS DeclHandler
106.216 -CLASS DecodedGenerator
106.217 -CLASS Decorators
106.218 -CLASS DefaultCookiePolicy
106.219 -CLASS DefaultHandler
106.220 -CLASS Delegator
106.221 -CLASS DeprecationWarning
106.222 -CLASS DeprecationWarning
106.223 -CLASS Dialect
106.224 -CLASS Dialog
106.225 -CLASS DialogWindow
106.226 -CLASS Dict
106.227 -CLASS DictMixin
106.228 -CLASS DictReader
106.229 -CLASS DictWriter
106.230 -CLASS Differ
106.231 -CLASS DirList
106.232 -CLASS DirSelectBox
106.233 -CLASS DirSelectDialog
106.234 -CLASS DirTree
106.235 -CLASS Directory
106.236 -CLASS Discard
106.237 -CLASS Distribution
106.238 -CLASS DistributionMetadata
106.239 -CLASS DistributionTestCase
106.240 -CLASS DistutilsArgError
106.241 -CLASS DistutilsClassError
106.242 -CLASS DistutilsError
106.243 -CLASS DistutilsExecError
106.244 -CLASS DistutilsFileError
106.245 -CLASS DistutilsGetoptError
106.246 -CLASS DistutilsInternalError
106.247 -CLASS DistutilsModuleError
106.248 -CLASS DistutilsOptionError
106.249 -CLASS DistutilsPlatformError
106.250 -CLASS DistutilsSetupError
106.251 -CLASS DistutilsTemplateError
106.252 -CLASS Div
106.253 -CLASS DivisionByZero
106.254 -CLASS Doc
106.255 -CLASS DocCGIXMLRPCRequestHandler
106.256 -CLASS DocTest
106.257 -CLASS DocTestFailure
106.258 -CLASS DocTestFinder
106.259 -CLASS DocTestParser
106.260 -CLASS DocTestRunner
106.261 -CLASS DocXMLRPCRequestHandler
106.262 -CLASS DocXMLRPCServer
106.263 -CLASS Document
106.264 -CLASS DocumentFragment
106.265 -CLASS DocumentHandler
106.266 -CLASS DocumentType
106.267 -CLASS DomstringSizeErr
106.268 -CLASS DumbWriter
106.269 -CLASS DummyCommand
106.270 -CLASS DuplicateSectionError
106.271 -CLASS DynLoadSuffixImporter
106.272 -CLASS EMXCCompiler
106.273 -CLASS EOFError
106.274 -CLASS EOFError
106.275 -CLASS ESISDocHandler
106.276 -CLASS Element
106.277 -CLASS ElementInfo
106.278 -CLASS ElementTree
106.279 -CLASS Ellipsis
106.280 -CLASS Empty
106.281 -CLASS EmptyNode
106.282 -CLASS EndOfBlock
106.283 -CLASS Entity
106.284 -CLASS EntityResolver
106.285 -CLASS Enum
106.286 -CLASS EnvironmentError
106.287 -CLASS EnvironmentError
106.288 -CLASS Error
106.289 -CLASS ErrorDuringImport
106.290 -CLASS ErrorHandler
106.291 -CLASS ErrorPrinter
106.292 -CLASS ErrorRaiser
106.293 -CLASS Event
106.294 -CLASS EventBroadcaster
106.295 -CLASS EventException
106.296 -CLASS ExFileSelectBox
106.297 -CLASS Example
106.298 -CLASS ExampleASTVisitor
106.299 -CLASS Exception
106.300 -CLASS Exception
106.301 -CLASS Exec
106.302 -CLASS ExitNow
106.303 -CLASS ExpatError
106.304 -CLASS ExpatParser
106.305 -CLASS Expression
106.306 -CLASS ExpressionCodeGenerator
106.307 -CLASS Extension
106.308 -CLASS F
106.309 -CLASS FTP
106.310 -CLASS FTPHandler
106.311 -CLASS Factory
106.312 -CLASS FancyGetopt
106.313 -CLASS FancyModuleLoader
106.314 -CLASS FancyURLopener
106.315 -CLASS Fault
106.316 -CLASS Feature
106.317 -CLASS FeedParser
106.318 -CLASS FieldStorage
106.319 -CLASS FileCookieJar
106.320 -CLASS FileEntry
106.321 -CLASS FileHandler
106.322 -CLASS FileIO
106.323 -CLASS FileInput
106.324 -CLASS FileList
106.325 -CLASS FileSelectBox
106.326 -CLASS FileWrapper
106.327 -CLASS Filter
106.328 -CLASS Filterer
106.329 -CLASS FingerHandler
106.330 -CLASS FirstHeaderLineIsContinuationD
106.331 -CLASS FloatingPointError
106.332 -CLASS FloatingPointError
106.333 -CLASS FloorDiv
106.334 -CLASS FlowGraph
106.335 -CLASS Folder
106.336 -CLASS Foo
106.337 -CLASS For
106.338 -CLASS ForkingMixIn
106.339 -CLASS ForkingTCPServer
106.340 -CLASS ForkingUDPServer
106.341 -CLASS Form
106.342 -CLASS FormContent
106.343 -CLASS FormContentDict
106.344 -CLASS Formatter
106.345 -CLASS Fraction
106.346 -CLASS From
106.347 -CLASS FtException
106.348 -CLASS Full
106.349 -CLASS FuncPtr
106.350 -CLASS Function
106.351 -CLASS FunctionCodeGenerator
106.352 -CLASS FunctionScope
106.353 -CLASS FunctionTestCase
106.354 -CLASS FutureParser
106.355 -CLASS FutureWarning
106.356 -CLASS FutureWarning
106.357 -CLASS GNUTranslations
106.358 -CLASS GenExpr
106.359 -CLASS GenExprFor
106.360 -CLASS GenExprIf
106.361 -CLASS GenExprInner
106.362 -CLASS GenExprScope
106.363 -CLASS Generator
106.364 -CLASS GeneratorExit
106.365 -CLASS GeneratorExit
106.366 -CLASS Getattr
106.367 -CLASS GetattrMagic
106.368 -CLASS GetoptError
106.369 -CLASS Global
106.370 -CLASS GopherError
106.371 -CLASS GopherHandler
106.372 -CLASS GridBag
106.373 -CLASS GzipFile
106.374 -CLASS HList
106.375 -CLASS HMAC
106.376 -CLASS HRESULT
106.377 -CLASS HTMLDoc
106.378 -CLASS HTMLParseError
106.379 -CLASS HTMLParser
106.380 -CLASS HTMLRepr
106.381 -CLASS HTTP
106.382 -CLASS HTTPBasicAuthHandler
106.383 -CLASS HTTPConnection
106.384 -CLASS HTTPCookieProcessor
106.385 -CLASS HTTPDefaultErrorHandler
106.386 -CLASS HTTPDigestAuthHandler
106.387 -CLASS HTTPError
106.388 -CLASS HTTPErrorProcessor
106.389 -CLASS HTTPException
106.390 -CLASS HTTPHandler
106.391 -CLASS HTTPPasswordMgr
106.392 -CLASS HTTPPasswordMgrWithDefaultReal
106.393 -CLASS HTTPRedirectHandler
106.394 -CLASS HTTPResponse
106.395 -CLASS HTTPSConnection
106.396 -CLASS HTTPSHandler
106.397 -CLASS HTTPServer
106.398 -CLASS Handler
106.399 -CLASS HandlerBase
106.400 -CLASS Header
106.401 -CLASS HeaderParseError
106.402 -CLASS HeaderParser
106.403 -CLASS Headers
106.404 -CLASS HelpFormatter
106.405 -CLASS Helper
106.406 -CLASS HierarchyRequestErr
106.407 -CLASS Hook
106.408 -CLASS Hooks
106.409 -CLASS HtmlDiff
106.410 -CLASS IC
106.411 -CLASS IMAP4
106.412 -CLASS IMAP4_SSL
106.413 -CLASS IMAP4_stream
106.414 -CLASS IOBase
106.415 -CLASS IOError
106.416 -CLASS IOError
106.417 -CLASS Identified
106.418 -CLASS If
106.419 -CLASS IfExp
106.420 -CLASS Ignore
106.421 -CLASS IllegalMonthError
106.422 -CLASS IllegalWeekdayError
106.423 -CLASS ImmutableSet
106.424 -CLASS ImpImporter
106.425 -CLASS ImpLoader
106.426 -CLASS Import
106.427 -CLASS ImportError
106.428 -CLASS ImportError
106.429 -CLASS ImportManager
106.430 -CLASS ImportWarning
106.431 -CLASS ImportWarning
106.432 -CLASS Importer
106.433 -CLASS ImproperConnectionState
106.434 -CLASS Incomplete
106.435 -CLASS IncompleteRead
106.436 -CLASS IncrementalDecoder
106.437 -CLASS IncrementalEncoder
106.438 -CLASS IncrementalNewlineDecoder
106.439 -CLASS IncrementalParser
106.440 -CLASS IndentedHelpFormatter
106.441 -CLASS IndexError
106.442 -CLASS IndexError
106.443 -CLASS IndexSizeErr
106.444 -CLASS Inexact
106.445 -CLASS IniParser
106.446 -CLASS InputOnly
106.447 -CLASS InputSource
106.448 -CLASS InsertionLoc
106.449 -CLASS InstallScriptsTestCase
106.450 -CLASS InstallTestCase
106.451 -CLASS Integral
106.452 -CLASS Interactive
106.453 -CLASS InteractiveCodeGenerator
106.454 -CLASS InteractiveConsole
106.455 -CLASS InteractiveInterpreter
106.456 -CLASS InterpFormContentDict
106.457 -CLASS InterpolationDepthError
106.458 -CLASS InterpolationError
106.459 -CLASS InterpolationSyntaxError
106.460 -CLASS IntlText
106.461 -CLASS IntlWritingCode
106.462 -CLASS InuseAttributeErr
106.463 -CLASS InvalidAccessErr
106.464 -CLASS InvalidCharacterErr
106.465 -CLASS InvalidModificationErr
106.466 -CLASS InvalidNodeTypeErr
106.467 -CLASS InvalidOperation
106.468 -CLASS InvalidStateErr
106.469 -CLASS InvalidURL
106.470 -CLASS Invert
106.471 -CLASS IsqlCmd
106.472 -CLASS IsqlExit
106.473 -CLASS IterableUserDict
106.474 -CLASS JSONDecoder
106.475 -CLASS JSONEncoder
106.476 -CLASS JavaSAXParser
106.477 -CLASS JoinableQueue
106.478 -CLASS JyDTDHandlerWrapper
106.479 -CLASS JyEntityResolverWrapper
106.480 -CLASS JyErrorHandlerWrapper
106.481 -CLASS JyInputSourceWrapper
106.482 -CLASS JythonCompiler
106.483 -CLASS JythonSignalHandler
106.484 -CLASS KeyError
106.485 -CLASS KeyError
106.486 -CLASS KeyboardInterrupt
106.487 -CLASS KeyboardInterrupt
106.488 -CLASS Keyword
106.489 -CLASS LOBTestCase
106.490 -CLASS LWPCookieJar
106.491 -CLASS LabelEntry
106.492 -CLASS LabelFrame
106.493 -CLASS Lambda
106.494 -CLASS LambdaScope
106.495 -CLASS LargeZipFile
106.496 -CLASS LeftShift
106.497 -CLASS LexicalHandler
106.498 -CLASS LexicalXMLGenerator
106.499 -CLASS LibError
106.500 -CLASS LibraryLoader
106.501 -CLASS LineAddrTable
106.502 -CLASS LinkError
106.503 -CLASS List
106.504 -CLASS ListComp
106.505 -CLASS ListCompFor
106.506 -CLASS ListCompIf
106.507 -CLASS ListNoteBook
106.508 -CLASS Listener
106.509 -CLASS LittleEndianStructure
106.510 -CLASS LoadError
106.511 -CLASS LocalNameFinder
106.512 -CLASS Location
106.513 -CLASS Locator
106.514 -CLASS Lock
106.515 -CLASS Log
106.516 -CLASS LogRecord
106.517 -CLASS Logger
106.518 -CLASS LoggingSilencer
106.519 -CLASS Logical
106.520 -CLASS LookupError
106.521 -CLASS LookupError
106.522 -CLASS LooseVersion
106.523 -CLASS MH
106.524 -CLASS MHMailbox
106.525 -CLASS MHMessage
106.526 -CLASS MIMEApplication
106.527 -CLASS MIMEAudio
106.528 -CLASS MIMEBase
106.529 -CLASS MIMEImage
106.530 -CLASS MIMEMessage
106.531 -CLASS MIMEMultipart
106.532 -CLASS MIMENonMultipart
106.533 -CLASS MIMEText
106.534 -CLASS MMDF
106.535 -CLASS MMDFMessage
106.536 -CLASS MSVCCompiler
106.537 -CLASS MWerksCompiler
106.538 -CLASS MacroExpander
106.539 -CLASS Mailbox
106.540 -CLASS Maildir
106.541 -CLASS MaildirMessage
106.542 -CLASS MailmanProxy
106.543 -CLASS MalformedHeaderDefect
106.544 -CLASS Manager
106.545 -CLASS Marshaller
106.546 -CLASS MemoryError
106.547 -CLASS MemoryError
106.548 -CLASS MemoryHandler
106.549 -CLASS Message
106.550 -CLASS MessageDefect
106.551 -CLASS MessageError
106.552 -CLASS MessageParseError
106.553 -CLASS MetadataTestCase
106.554 -CLASS Meter
106.555 -CLASS MimeWriter
106.556 -CLASS Mingw32CCompiler
106.557 -CLASS MiniApplication
106.558 -CLASS MiniFieldStorage
106.559 -CLASS MisplacedEnvelopeHeaderDefect
106.560 -CLASS MissingSectionHeaderError
106.561 -CLASS MmdfMailbox
106.562 -CLASS Mod
106.563 -CLASS Model
106.564 -CLASS Module
106.565 -CLASS ModuleCodeGenerator
106.566 -CLASS ModuleFinder
106.567 -CLASS ModuleImporter
106.568 -CLASS ModuleLoader
106.569 -CLASS ModuleScanner
106.570 -CLASS ModuleScope
106.571 -CLASS MozillaCookieJar
106.572 -CLASS Mul
106.573 -CLASS MultiCall
106.574 -CLASS MultiCallIterator
106.575 -CLASS MultiFile
106.576 -CLASS MultipartConversionError
106.577 -CLASS MultipartInvariantViolationDef
106.578 -CLASS MutableString
106.579 -CLASS MyClass
106.580 -CLASS MyTest
106.581 -CLASS NNTP
106.582 -CLASS NNTPDataError
106.583 -CLASS NNTPPermanentError
106.584 -CLASS NNTPProtocolError
106.585 -CLASS NNTPReplyError
106.586 -CLASS NNTPTemporaryError
106.587 -CLASS NProperty
106.588 -CLASS NTEventLogHandler
106.589 -CLASS NULL
106.590 -CLASS Name
106.591 -CLASS NameError
106.592 -CLASS NameError
106.593 -CLASS NamedNodeMap
106.594 -CLASS NamespaceErr
106.595 -CLASS NannyNag
106.596 -CLASS NestedScopeMixin
106.597 -CLASS Netrc
106.598 -CLASS NetrcParseError
106.599 -CLASS NewStyle
106.600 -CLASS NoBoundaryInMultipartDefect
106.601 -CLASS NoDataAllowedErr
106.602 -CLASS NoModificationAllowedErr
106.603 -CLASS NoOpMetaClass
106.604 -CLASS NoOptionError
106.605 -CLASS NoSectionError
106.606 -CLASS Node
106.607 -CLASS NodeFilter
106.608 -CLASS NodeTransformer
106.609 -CLASS NodeVisitor
106.610 -CLASS Not
106.611 -CLASS NotANumber
106.612 -CLASS NotConnected
106.613 -CLASS NotFoundErr
106.614 -CLASS NotImplementedError
106.615 -CLASS NotImplementedError
106.616 -CLASS NotSupportedErr
106.617 -CLASS Notation
106.618 -CLASS NoteBook
106.619 -CLASS NullFormatter
106.620 -CLASS NullImporter
106.621 -CLASS NullTranslations
106.622 -CLASS NullWriter
106.623 -CLASS Number
106.624 -CLASS OSError
106.625 -CLASS OSError
106.626 -CLASS OSSAudioError
106.627 -CLASS ObjectSpecifier
106.628 -CLASS OleDLL
106.629 -CLASS OpFinder
106.630 -CLASS OpenerDirector
106.631 -CLASS OptParseError
106.632 -CLASS Option
106.633 -CLASS OptionConflictError
106.634 -CLASS OptionContainer
106.635 -CLASS OptionDummy
106.636 -CLASS OptionError
106.637 -CLASS OptionGroup
106.638 -CLASS OptionMenu
106.639 -CLASS OptionParser
106.640 -CLASS OptionValueError
106.641 -CLASS Or
106.642 -CLASS OracleSPTest
106.643 -CLASS Ordinal
106.644 -CLASS OutputChecker
106.645 -CLASS Overflow
106.646 -CLASS OverflowError
106.647 -CLASS OverflowError
106.648 -CLASS POP3
106.649 -CLASS POP3_SSL
106.650 -CLASS Packer
106.651 -CLASS PanedWindow
106.652 -CLASS Panel
106.653 -CLASS Parser
106.654 -CLASS ParserBase
106.655 -CLASS ParserError
106.656 -CLASS ParsingError
106.657 -CLASS Pass
106.658 -CLASS Pattern
106.659 -CLASS Pdb
106.660 -CLASS PendingDeprecationWarning
106.661 -CLASS PendingDeprecationWarning
106.662 -CLASS PickleError
106.663 -CLASS Pickler
106.664 -CLASS PicklingError
106.665 -CLASS PlaceHolder
106.666 -CLASS Popen
106.667 -CLASS Popen3
106.668 -CLASS Popen4
106.669 -CLASS PopupMenu
106.670 -CLASS PortableUnixMailbox
106.671 -CLASS Power
106.672 -CLASS PreprocessError
106.673 -CLASS PrettyPrinter
106.674 -CLASS Print
106.675 -CLASS Printnl
106.676 -CLASS Process
106.677 -CLASS ProcessingInstruction
106.678 -CLASS Profile
106.679 -CLASS ProgressBar
106.680 -CLASS Prompt
106.681 -CLASS ProtocolError
106.682 -CLASS ProxyBasicAuthHandler
106.683 -CLASS ProxyDigestAuthHandler
106.684 -CLASS ProxyHandler
106.685 -CLASS PullDOM
106.686 -CLASS PureProxy
106.687 -CLASS PyCompileError
106.688 -CLASS PyDLL
106.689 -CLASS PyDialog
106.690 -CLASS PyFlowGraph
106.691 -CLASS PyHKEY
106.692 -CLASS PyZipFile
106.693 -CLASS QDPoint
106.694 -CLASS QDRectangle
106.695 -CLASS QName
106.696 -CLASS Queue
106.697 -CLASS RExec
106.698 -CLASS RGBColor
106.699 -CLASS RLock
106.700 -CLASS RadioButtonGroup
106.701 -CLASS Raise
106.702 -CLASS Random
106.703 -CLASS Range
106.704 -CLASS RangeException
106.705 -CLASS Rational
106.706 -CLASS RawConfigParser
106.707 -CLASS RawIOBase
106.708 -CLASS RawTurtle
106.709 -CLASS ReadOnlySequentialNamedNodeMap
106.710 -CLASS Real
106.711 -CLASS Record
106.712 -CLASS ReferenceError
106.713 -CLASS ReferenceError
106.714 -CLASS Repr
106.715 -CLASS Request
106.716 -CLASS ResponseError
106.717 -CLASS ResponseNotReady
106.718 -CLASS ResultSet
106.719 -CLASS ResultSetRow
106.720 -CLASS Return
106.721 -CLASS RightShift
106.722 -CLASS RobotFileParser
106.723 -CLASS RootLogger
106.724 -CLASS RotatingFileHandler
106.725 -CLASS Rounded
106.726 -CLASS Row
106.727 -CLASS RuntimeError
106.728 -CLASS RuntimeError
106.729 -CLASS RuntimeWarning
106.730 -CLASS RuntimeWarning
106.731 -CLASS SAX2DOM
106.732 -CLASS SAXException
106.733 -CLASS SAXNotRecognizedException
106.734 -CLASS SAXNotSupportedException
106.735 -CLASS SAXParseException
106.736 -CLASS SAXReaderNotAvailable
106.737 -CLASS SGMLParseError
106.738 -CLASS SGMLParser
106.739 -CLASS SMTP
106.740 -CLASS SMTPAuthenticationError
106.741 -CLASS SMTPConnectError
106.742 -CLASS SMTPDataError
106.743 -CLASS SMTPException
106.744 -CLASS SMTPHandler
106.745 -CLASS SMTPHeloError
106.746 -CLASS SMTPRecipientsRefused
106.747 -CLASS SMTPResponseException
106.748 -CLASS SMTPSenderRefused
106.749 -CLASS SMTPServer
106.750 -CLASS SMTPServerDisconnected
106.751 -CLASS SQLServerSPTest
106.752 -CLASS SQLTestCase
106.753 -CLASS SSLError
106.754 -CLASS SSLSocket
106.755 -CLASS ST
106.756 -CLASS SafeConfigParser
106.757 -CLASS SafeTransport
106.758 -CLASS Schema
106.759 -CLASS Scope
106.760 -CLASS Screen
106.761 -CLASS ScrolledCavas
106.762 -CLASS ScrolledText
106.763 -CLASS ScrolledWindow
106.764 -CLASS Select
106.765 -CLASS Semaphore
106.766 -CLASS SequenceMatcher
106.767 -CLASS SerialCookie
106.768 -CLASS Server
106.769 -CLASS ServerHTMLDoc
106.770 -CLASS ServerProxy
106.771 -CLASS Set
106.772 -CLASS SgmlopParser
106.773 -CLASS Shape
106.774 -CLASS Shelf
106.775 -CLASS SimpleCookie
106.776 -CLASS SimpleHTTPRequestHandler
106.777 -CLASS SimpleHandler
106.778 -CLASS SimpleLocator
106.779 -CLASS SimpleXMLRPCDispatcher
106.780 -CLASS SimpleXMLRPCRequestHandler
106.781 -CLASS SimpleXMLRPCServer
106.782 -CLASS Slice
106.783 -CLASS Sliceobj
106.784 -CLASS SlowParser
106.785 -CLASS SmartCookie
106.786 -CLASS Sniffer
106.787 -CLASS SocketHandler
106.788 -CLASS SocketType
106.789 -CLASS Stack
106.790 -CLASS StackDepthTracker
106.791 -CLASS StandardError
106.792 -CLASS StandardError
106.793 -CLASS StartBoundaryNotFoundDefect
106.794 -CLASS Stats
106.795 -CLASS StdButtonBox
106.796 -CLASS Stmt
106.797 -CLASS StopIteration
106.798 -CLASS StopIteration
106.799 -CLASS StopTokenizing
106.800 -CLASS Strange
106.801 -CLASS StreamConverter
106.802 -CLASS StreamHandler
106.803 -CLASS StreamReader
106.804 -CLASS StreamRequestHandler
106.805 -CLASS StreamWriter
106.806 -CLASS StrictVersion
106.807 -CLASS StringIO
106.808 -CLASS Struct
106.809 -CLASS Structure
106.810 -CLASS StyledText
106.811 -CLASS Sub
106.812 -CLASS SubPattern
106.813 -CLASS Subnormal
106.814 -CLASS Subscript
106.815 -CLASS SummaryInformation
106.816 -CLASS Super
106.817 -CLASS SuperSuper
106.818 -CLASS SvFormContentDict
106.819 -CLASS Symbol
106.820 -CLASS SymbolTable
106.821 -CLASS SymbolVisitor
106.822 -CLASS SyncManager
106.823 -CLASS SyntaxErr
106.824 -CLASS SyntaxError
106.825 -CLASS SyntaxError
106.826 -CLASS SyntaxErrorChecker
106.827 -CLASS SyntaxWarning
106.828 -CLASS SyntaxWarning
106.829 -CLASS SysLogHandler
106.830 -CLASS SystemError
106.831 -CLASS SystemError
106.832 -CLASS SystemExit
106.833 -CLASS SystemExit
106.834 -CLASS SystemRandom
106.835 -CLASS TCPServer
106.836 -CLASS TList
106.837 -CLASS TalkTo
106.838 -CLASS TarError
106.839 -CLASS TarFile
106.840 -CLASS TarInfo
106.841 -CLASS Telnet
106.842 -CLASS TempdirManager
106.843 -CLASS Template
106.844 -CLASS Test
106.845 -CLASS TestCase
106.846 -CLASS TestClass
106.847 -CLASS TestCrispinTorture
106.848 -CLASS TestDistribution
106.849 -CLASS TestLoader
106.850 -CLASS TestResult
106.851 -CLASS TestSuite
106.852 -CLASS TestThread
106.853 -CLASS TestXMLParser
106.854 -CLASS Testcase
106.855 -CLASS Tester
106.856 -CLASS Text
106.857 -CLASS TextDoc
106.858 -CLASS TextFile
106.859 -CLASS TextIOBase
106.860 -CLASS TextIOWrapper
106.861 -CLASS TextRepr
106.862 -CLASS TextTestRunner
106.863 -CLASS TextWrapper
106.864 -CLASS Textbox
106.865 -CLASS Thread
106.866 -CLASS ThreadingMixIn
106.867 -CLASS ThreadingTCPServer
106.868 -CLASS ThreadingUDPServer
106.869 -CLASS ThreadingUnixDatagramServer
106.870 -CLASS ThreadingUnixStreamServer
106.871 -CLASS TimedRotatingFileHandler
106.872 -CLASS Timer
106.873 -CLASS TitledHelpFormatter
106.874 -CLASS Tix
106.875 -CLASS Tk
106.876 -CLASS TokenError
106.877 -CLASS Tokenizer
106.878 -CLASS TortureBase
106.879 -CLASS Trace
106.880 -CLASS Transformer
106.881 -CLASS Transport
106.882 -CLASS Tree
106.883 -CLASS TreeBuilder
106.884 -CLASS TryExcept
106.885 -CLASS TryFinally
106.886 -CLASS Tuple
106.887 -CLASS TupleArg
106.888 -CLASS Turtle
106.889 -CLASS TurtleScreen
106.890 -CLASS Type
106.891 -CLASS TypeError
106.892 -CLASS TypeError
106.893 -CLASS TypeInfo
106.894 -CLASS UDPServer
106.895 -CLASS URLError
106.896 -CLASS URLopener
106.897 -CLASS UUID
106.898 -CLASS UnaryAdd
106.899 -CLASS UnarySub
106.900 -CLASS UnboundLocalError
106.901 -CLASS UnboundLocalError
106.902 -CLASS Underflow
106.903 -CLASS UnexpectedException
106.904 -CLASS UnicodeDecodeError
106.905 -CLASS UnicodeDecodeError
106.906 -CLASS UnicodeEncodeError
106.907 -CLASS UnicodeEncodeError
106.908 -CLASS UnicodeError
106.909 -CLASS UnicodeError
106.910 -CLASS UnicodeTranslateError
106.911 -CLASS UnicodeTranslateError
106.912 -CLASS UnicodeWarning
106.913 -CLASS UnicodeWarning
106.914 -CLASS UnimplementedFileMode
106.915 -CLASS Union
106.916 -CLASS UnixCCompiler
106.917 -CLASS UnixDatagramServer
106.918 -CLASS UnixMailbox
106.919 -CLASS UnixStreamServer
106.920 -CLASS Unknown
106.921 -CLASS UnknownFileError
106.922 -CLASS UnknownHandler
106.923 -CLASS UnknownProtocol
106.924 -CLASS UnknownTransferEncoding
106.925 -CLASS Unload
106.926 -CLASS Unmarshaller
106.927 -CLASS Unpacker
106.928 -CLASS Unpickler
106.929 -CLASS UnpicklingError
106.930 -CLASS UnspecifiedEventTypeErr
106.931 -CLASS UnsupportedOperation
106.932 -CLASS UserDataHandler
106.933 -CLASS UserDict
106.934 -CLASS UserList
106.935 -CLASS UserString
106.936 -CLASS UserWarning
106.937 -CLASS UserWarning
106.938 -CLASS ValidationErr
106.939 -CLASS ValueError
106.940 -CLASS ValueError
106.941 -CLASS Values
106.942 -CLASS Vec2D
106.943 -CLASS Vendor
106.944 -CLASS Version
106.945 -CLASS VersionPredicate
106.946 -CLASS View
106.947 -CLASS WSGIRequestHandler
106.948 -CLASS WSGIServer
106.949 -CLASS Warning
106.950 -CLASS Warning
106.951 -CLASS Wave_read
106.952 -CLASS Wave_write
106.953 -CLASS WeakKeyDictionary
106.954 -CLASS WeakValueDictionary
106.955 -CLASS While
106.956 -CLASS WichmannHill
106.957 -CLASS WinDLL
106.958 -CLASS Window
106.959 -CLASS WindowsError
106.960 -CLASS WindowsError
106.961 -CLASS With
106.962 -CLASS WrongDocumentErr
106.963 -CLASS X
106.964 -CLASS XMLFilter
106.965 -CLASS XMLFilterBase
106.966 -CLASS XMLFilterImpl
106.967 -CLASS XMLGenerator
106.968 -CLASS XMLParser
106.969 -CLASS XMLRPCDocGenerator
106.970 -CLASS XMLReader
106.971 -CLASS XMLTreeBuilder
106.972 -CLASS XmlParseErr
106.973 -CLASS Yield
106.974 -CLASS Yuck
106.975 -CLASS ZeroDivisionError
106.976 -CLASS ZeroDivisionError
106.977 -CLASS ZipFile
106.978 -CLASS ZipImportError
106.979 -CLASS ZipInfo
106.980 -CLASS _CData [PROTECTE
106.981 -CLASS _FuncPtr [PROTECTE
106.982 -CLASS _SimpleCData [PROTECTE
106.983 -CLASS _posixfile_
106.984 -CLASS array
106.985 -CLASS async_chat
106.986 -CLASS bdist
106.987 -CLASS bdist_dumb
106.988 -CLASS bdist_msi
106.989 -CLASS bdist_rpm
106.990 -CLASS bdist_wininst
106.991 -CLASS bool
106.992 -CLASS bsddbobject
106.993 -CLASS build
106.994 -CLASS build_clib
106.995 -CLASS build_ext
106.996 -CLASS build_py
106.997 -CLASS build_scripts
106.998 -CLASS c_bool
106.999 -CLASS c_byte
106.1000 -CLASS c_char
106.1001 -CLASS c_char_p
106.1002 -CLASS c_double
106.1003 -CLASS c_float
106.1004 -CLASS c_int
106.1005 -CLASS c_int16
106.1006 -CLASS c_int32
106.1007 -CLASS c_int64
106.1008 -CLASS c_int8
106.1009 -CLASS c_long
106.1010 -CLASS c_longdouble
106.1011 -CLASS c_longlong
106.1012 -CLASS c_short
106.1013 -CLASS c_size_t
106.1014 -CLASS c_ubyte
106.1015 -CLASS c_uint
106.1016 -CLASS c_uint16
106.1017 -CLASS c_uint32
106.1018 -CLASS c_uint64
106.1019 -CLASS c_uint8
106.1020 -CLASS c_ulong
106.1021 -CLASS c_ulonglong
106.1022 -CLASS c_ushort
106.1023 -CLASS c_void_p
106.1024 -CLASS c_wchar
106.1025 -CLASS c_wchar_p
106.1026 -CLASS class
106.1027 -CLASS class
106.1028 -CLASS clean
106.1029 -CLASS closing
106.1030 -CLASS complex
106.1031 -CLASS compressobj
106.1032 -CLASS config
106.1033 -CLASS container
106.1034 -CLASS container
106.1035 -CLASS contextmanager
106.1036 -CLASS contextmanager
106.1037 -CLASS controller
106.1038 -CLASS date
106.1039 -CLASS datetime
106.1040 -CLASS dbexts
106.1041 -CLASS dbextsTestCase
106.1042 -CLASS dbhash
106.1043 -CLASS decompressobj
106.1044 -CLASS deque
106.1045 -CLASS dict
106.1046 -CLASS dict
106.1047 -CLASS dircmp
106.1048 -CLASS dispatcher
106.1049 -CLASS dispatcher_with_send
106.1050 -CLASS dl
106.1051 -CLASS error
106.1052 -CLASS error_data
106.1053 -CLASS error_reply
106.1054 -CLASS excel
106.1055 -CLASS excel_tab
106.1056 -CLASS executor
106.1057 -CLASS fifo
106.1058 -CLASS file
106.1059 -CLASS file
106.1060 -CLASS file_dispatcher
106.1061 -CLASS file_wrapper
106.1062 -CLASS float
106.1063 -CLASS float
106.1064 -CLASS foo
106.1065 -CLASS gaierror
106.1066 -CLASS herror
106.1067 -CLASS install
106.1068 -CLASS install_data
106.1069 -CLASS install_egg_info
106.1070 -CLASS install_headers
106.1071 -CLASS install_lib
106.1072 -CLASS install_misc
106.1073 -CLASS install_scripts
106.1074 -CLASS instance
106.1075 -CLASS instance
106.1076 -CLASS int
106.1077 -CLASS iterator
106.1078 -CLASS iterator
106.1079 -CLASS list
106.1080 -CLASS local
106.1081 -CLASS lock
106.1082 -CLASS long
106.1083 -CLASS main
106.1084 -CLASS mbox
106.1085 -CLASS mboxMessage
106.1086 -CLASS mllib
106.1087 -CLASS mmap
106.1088 -CLASS multiprocessing.Pool
106.1089 -CLASS mutex
106.1090 -CLASS mxODBCProxy
106.1091 -CLASS netrc
106.1092 -CLASS object
106.1093 -CLASS object
106.1094 -CLASS oss_audio_device
106.1095 -CLASS oss_mixer_device
106.1096 -CLASS poll
106.1097 -CLASS py_object
106.1098 -CLASS register
106.1099 -CLASS scheduler
106.1100 -CLASS sdist
106.1101 -CLASS set
106.1102 -CLASS set
106.1103 -CLASS shlex
106.1104 -CLASS simple_producer
106.1105 -CLASS socket
106.1106 -CLASS stat_result
106.1107 -CLASS str
106.1108 -CLASS str
106.1109 -CLASS test_dist
106.1110 -CLASS test_zxjdbc
106.1111 -CLASS time
106.1112 -CLASS timedelta
106.1113 -CLASS timeout
106.1114 -CLASS tixCommand
106.1115 -CLASS tmxxx
106.1116 -CLASS tuple
106.1117 -CLASS tzinfo
106.1118 -CLASS unicode
106.1119 -CLASS unicode
106.1120 -CLASS upload
106.1121 -CLASS window
106.1122 -CLASS xmlparser
106.1123 -CLASS zipimporter
106.1124 -CLASS zxAPITestCase
106.1125 -CLASS zxCoreTestCase
106.1126 -CLASS zxJDBCTestCase
106.1127 -METHOD __import__(name, globals, loca
106.1128 -METHOD abs(x)
106.1129 -METHOD all(iterable)
106.1130 -METHOD any(iterable)
106.1131 -METHOD ---apply(function, args, ke---
106.1132 -METHOD basestring()
106.1133 -METHOD bin(x)
106.1134 -METHOD bool(x)
106.1135 -METHOD buffer(object, offset, size)
106.1136 -METHOD callable(object)
106.1137 -METHOD chr(i)
106.1138 -METHOD classmethod(function)
106.1139 -METHOD cmp(x, y)
106.1140 -METHOD coerce(x, y)
106.1141 -METHOD compile(source, filename, mode
106.1142 -METHOD complex(real, imag)
106.1143 -METHOD delattr(object, name)
106.1144 -METHOD dict(arg)
106.1145 -METHOD dir(object)
106.1146 -METHOD divmod(a, b)
106.1147 -METHOD enumerate(sequence, start)
106.1148 -METHOD eval(expression, globals, loca
106.1149 -METHOD execfile(filename, globals, lo
106.1150 -METHOD exit(code)
106.1151 -METHOD file(filename, mode, bufsize)
106.1152 -METHOD filter(function, iterable)
106.1153 -METHOD float(x)
106.1154 -METHOD frozenset(iterable)
106.1155 -METHOD getattr(object, name, default)
106.1156 -METHOD globals()
106.1157 -METHOD hasattr(object, name)
106.1158 -METHOD hash(object)
106.1159 -METHOD help(object)
106.1160 -METHOD hex(x)
106.1161 -METHOD id(object)
106.1162 -METHOD input(prompt)
106.1163 -METHOD int(x, radix)
106.1164 -METHOD intern(string)
106.1165 -METHOD isinstance(object, classinfo)
106.1166 -METHOD issubclass(class, classinfo)
106.1167 -METHOD iter(o, sentinel)
106.1168 -METHOD len(s)
106.1169 -METHOD list(iterable)
106.1170 -METHOD locals()
106.1171 -METHOD long(x, radix)
106.1172 -METHOD map(function, iterable)
106.1173 -METHOD max(iterable, argskey)
106.1174 -METHOD min(iterable, argskey)
106.1175 -METHOD next(iterator, default)
106.1176 -METHOD object()
106.1177 -METHOD oct(x)
106.1178 -METHOD open(filename, mode, bufsize)
106.1179 -METHOD ord(c)
106.1180 -METHOD pow(x, y, z)
106.1181 -METHOD print(object, sep, end, file)
106.1182 -METHOD property(fget, fset, fdel, doc
106.1183 -METHOD quit(code)
106.1184 -METHOD range(start, stop, step)
106.1185 -METHOD raw_input(prompt)
106.1186 -METHOD reduce(function, iterable, ini
106.1187 -METHOD reload(module)
106.1188 -METHOD repr(object)
106.1189 -METHOD reversed(seq)
106.1190 -METHOD round(x, n)
106.1191 -METHOD set(iterable)
106.1192 -METHOD setattr(object, name, value)
106.1193 -METHOD slice(start, stop, step)
106.1194 -METHOD sorted(iterable, cmp, key, rev
106.1195 -METHOD staticmethod(function)
106.1196 -METHOD str(object)
106.1197 -METHOD sum(iterable, start)
106.1198 -METHOD super(type, object-or-type)
106.1199 -METHOD tuple(iterable)
106.1200 -METHOD type(name, bases, dict)
106.1201 -METHOD type(object)
106.1202 -METHOD unichr(i)
106.1203 -METHOD unicode(object, encoding, erro
106.1204 -METHOD vars(object)
106.1205 -METHOD xrange(start, stop, step)
106.1206 -METHOD zip(iterable)
106.1207 -VARIABLE Ellipsis
106.1208 -VARIABLE False
106.1209 -VARIABLE None
106.1210 -VARIABLE NotImplemented
106.1211 -VARIABLE True
106.1212 -VARIABLE __debug__
106.1213 -VARIABLE copyright
106.1214 -KEYWORD and
106.1215 -KEYWORD as
106.1216 -KEYWORD assert
106.1217 -KEYWORD break
106.1218 -KEYWORD class
106.1219 -KEYWORD continue
106.1220 -KEYWORD def
106.1221 -KEYWORD del
106.1222 -KEYWORD elif
106.1223 -KEYWORD else
106.1224 -KEYWORD except
106.1225 -KEYWORD exec
106.1226 -KEYWORD finally
106.1227 -KEYWORD for
106.1228 -KEYWORD from
106.1229 -KEYWORD global
106.1230 -KEYWORD if
106.1231 -KEYWORD import
106.1232 -KEYWORD in
106.1233 -KEYWORD is
106.1234 -KEYWORD lambda
106.1235 -KEYWORD not
106.1236 -KEYWORD or
106.1237 -KEYWORD pass
106.1238 -KEYWORD print
106.1239 -KEYWORD raise
106.1240 -KEYWORD return
106.1241 -KEYWORD try
106.1242 -KEYWORD while
106.1243 -KEYWORD with
106.1244 -KEYWORD yield
107.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testClasses2.completion Sun Jan 04 13:11:53 2015 -0600
107.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
107.3 @@ -1,26 +0,0 @@
107.4 -Code completion result for source line:
107.5 -raise D|uplicateSectionError(section)
107.6 -(QueryType=COMPLETION, NameKind=PREFIX)
107.7 -------------------------------------
107.8 -CLASS DOMException
107.9 -CLASS DOMStringSizeErr
107.10 -CLASS DecimalException
107.11 -CLASS DeprecationWarning
107.12 -CLASS DistutilsArgError
107.13 -CLASS DistutilsClassError
107.14 -CLASS DistutilsError
107.15 -CLASS DistutilsExecError
107.16 -CLASS DistutilsFileError
107.17 -CLASS DistutilsGetoptError
107.18 -CLASS DistutilsInternalError
107.19 -CLASS DistutilsModuleError
107.20 -CLASS DistutilsOptionError
107.21 -CLASS DistutilsPlatformError
107.22 -CLASS DistutilsSetupError
107.23 -CLASS DistutilsTemplateError
107.24 -CLASS DivisionByZero
107.25 -CLASS DivisionImpossible [PRIVATE]
107.26 -CLASS DivisionUndefined [PRIVATE]
107.27 -CLASS DocTestFailure
107.28 -CLASS DomstringSizeErr
107.29 -CLASS DuplicateSectionError
108.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testFix8.fixed Sun Jan 04 13:11:53 2015 -0600
108.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
108.3 @@ -1,621 +0,0 @@
108.4 -"""Configuration file parser.
108.5 -
108.6 -A setup file consists of sections, lead by a "[section]" header,
108.7 -and followed by "name: value" entries, with continuations and such in
108.8 -the style of RFC 822.
108.9 -
108.10 - the same section, or values in a special [DEFAULT] section.
108.11 -
108.12 -For example:
108.13 -
108.14 - something: %(dir)s/whatever
108.15 -
108.16 -would resolve the "%(dir)s" to the value of dir. All reference
108.17 -expansions are done late, on demand.
108.18 -
108.19 -Intrinsic defaults can be specified by passing them into the
108.20 -ConfigParser constructor as a dictionary.
108.21 -
108.22 -class:
108.23 -
108.24 -ConfigParser -- responsible for parsing a list of
108.25 - configuration files, and managing the parsed database.
108.26 -
108.27 - methods:
108.28 -
108.29 - __init__(defaults=None)
108.30 - create the parser and specify a dictionary of intrinsic defaults. The
108.31 - keys must be strings, the values must be appropriate for %()s string
108.32 - interpolation. Note that `__name__' is always an intrinsic default;
108.33 - it's value is the section's name.
108.34 -
108.35 - sections()
108.36 - return all the configuration section names, sans DEFAULT
108.37 -
108.38 - has_section(section)
108.39 - return whether the given section exists
108.40 -
108.41 - has_option(section, option)
108.42 - return whether the given option exists in the given section
108.43 -
108.44 - options(section)
108.45 - return list of configuration options for the named section
108.46 -
108.47 - read(filenames)
108.48 - read and parse the list of named configuration files, given by
108.49 - name. A single filename is also allowed. Non-existing files
108.50 - are ignored.
108.51 -
108.52 - readfp(fp, filename=None)
108.53 - read and parse one configuration file, given as a file object.
108.54 - The filename defaults to fp.name; it is only used in error
108.55 - messages (if fp has no `name' attribute, the string `<???>' is used).
108.56 -
108.57 - get(section, option, raw=False, vars=None)
108.58 - return a string value for the named option. All % interpolations are
108.59 - expanded in the return values, based on the defaults passed into the
108.60 - constructor and the DEFAULT section. Additional substitutions may be
108.61 - provided using the `vars' argument, which must be a dictionary whose
108.62 - contents override any pre-existing defaults.
108.63 -
108.64 - getint(section, options)
108.65 - like get(), but convert value to an integer
108.66 -
108.67 - getfloat(section, options)
108.68 - like get(), but convert value to a float
108.69 -
108.70 - getboolean(section, options)
108.71 - like get(), but convert value to a boolean (currently case
108.72 - insensitively defined as 0, false, no, off for False, and 1, true,
108.73 - yes, on for True). Returns False or True.
108.74 -
108.75 - items(section, raw=False, vars=None)
108.76 - return a list of tuples with (name, value) for each option
108.77 - in the section.
108.78 -
108.79 - remove_section(section)
108.80 - remove the given file section and all its options
108.81 -
108.82 - remove_option(section, option)
108.83 - remove the given option from the given section
108.84 -
108.85 - set(section, option, value)
108.86 - set the given option
108.87 -
108.88 - write(fp)
108.89 - write the configuration state in .ini format
108.90 -"""
108.91 -
108.92 -import re
108.93 -
108.94 -__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
108.95 - "InterpolationError", "InterpolationDepthError",
108.96 - "InterpolationSyntaxError", "ParsingError",
108.97 - "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser",
108.98 - "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
108.99 -
108.100 -DEFAULTSECT = "DEFAULT"
108.101 -
108.102 -MAX_INTERPOLATION_DEPTH = 10
108.103 -
108.104 -
108.105 -
108.106 -# exception classes
108.107 -class Error(Exception):
108.108 - """Base class for ConfigParser exceptions."""
108.109 -
108.110 - def __init__(self, msg=''):
108.111 - self.message = msg
108.112 - Exception.__init__(self, msg)
108.113 -
108.114 - def __repr__(self):
108.115 - return self.message
108.116 -
108.117 - __str__ = __repr__
108.118 -
108.119 -class NoSectionError(Error):
108.120 - """Rasssised when no section matches a requested option."""
108.121 -
108.122 - def __init__(self, section):
108.123 - Error.__init__(self, 'No section: ' + `section`)
108.124 - self.section = section
108.125 -
108.126 -class DuplicateSectionError(Error):
108.127 - """Raised when a section is multiply-created."""
108.128 -
108.129 - def __init__(self, section):
108.130 - Error.__init__(self, "Section %r already exists" % section)
108.131 - self.section = section
108.132 -
108.133 -class NoOptionError(Error):
108.134 - """A requested option was not found."""
108.135 -
108.136 - def __init__(self, option, section):
108.137 - Error.__init__(self, "No option %r in section: %r" %
108.138 - (option, section))
108.139 - self.option = option
108.140 - self.section = section
108.141 -
108.142 -class InterpolationError(Error):
108.143 - """Base class for interpolation-related exceptions."""
108.144 -
108.145 - def __init__(self, option, section, msg):
108.146 - Error.__init__(self, msg)
108.147 - self.option = option
108.148 - self.section = section
108.149 -
108.150 -class InterpolationMissingOptionError(InterpolationError):
108.151 - """A string substitution required a setting which was not available."""
108.152 -
108.153 - def __init__(self, option, section, rawval, reference):
108.154 - msg = ("Bad value substitution:\n"
108.155 - "\tsection: [%s]\n"
108.156 - "\toption : %s\n"
108.157 - "\tkey : %s\n"
108.158 - "\trawval : %s\n"
108.159 - % (section, option, reference, rawval))
108.160 - InterpolationError.__init__(self, option, section, msg)
108.161 - self.reference = reference
108.162 -
108.163 -class InterpolationSyntaxError(InterpolationError):
108.164 - """Raised when the source text into which substitutions are made
108.165 - does not conform to the required syntax."""
108.166 -
108.167 -class InterpolationDepthError(InterpolationError):
108.168 - """Raised when substitutions are nested too deeply."""
108.169 -
108.170 - def __init__(self, option, section, rawval):
108.171 - msg = ("Value interpolation too deeply recursive:\n"
108.172 - "\tsection: [%s]\n"
108.173 - "\toption : %s\n"
108.174 - "\trawval : %s\n"
108.175 - % (section, option, rawval))
108.176 - InterpolationError.__init__(self, option, section, msg)
108.177 -
108.178 -class ParsingError(Error):
108.179 - """Raised when a configuration file does not follow legal syntax."""
108.180 -
108.181 - def __init__(self, filename):
108.182 - Error.__init__(self, 'File contains parsing errors: %s' % filename)
108.183 - self.filename = filename
108.184 - self.errors = []
108.185 -
108.186 - def append(self, lineno, line):
108.187 - self.errors.append((lineno, line))
108.188 - self.message += '\n\t[line %2d]: %s' % (lineno, line)
108.189 -
108.190 -class MissingSectionHeaderError(ParsingError):
108.191 - """Raised when a key-value pair is found before any section header."""
108.192 -
108.193 - def __init__(self, filename, lineno, line):
108.194 - Error.__init__(
108.195 - self,
108.196 - 'File contains no section headers.\nfile: %s, line: %d\n%s' %
108.197 - (filename, lineno, line))
108.198 - self.filename = filename
108.199 - self.lineno = lineno
108.200 - self.line = line
108.201 -
108.202 -
108.203 -
108.204 -class RawConfigParser:
108.205 - def __init__(self, defaults=None):
108.206 - self._sections = {}
108.207 - if defaults is None:
108.208 - self._defaults = {}
108.209 - else:
108.210 - self._defaults = defaults
108.211 -
108.212 - def defaults(self):
108.213 - return self._defaults
108.214 -
108.215 - def sections(self):
108.216 - """Return a list of section names, excluding [DEFAULT]"""
108.217 - # self._sections will never have [DEFAULT] in it
108.218 - return self._sections.keys()
108.219 -
108.220 - def add_section(self, section):
108.221 - """Create a new section in the configuration.
108.222 -
108.223 - Raise DuplicateSectionError if a section by the specified name
108.224 - already exists.
108.225 - """
108.226 - if section in self._sections:
108.227 - raise DuplicateSectionError(section)
108.228 - self._sections[section] = {}
108.229 -
108.230 - def has_section(self, section):
108.231 - """Indicate whether the named section is present in the configuration.
108.232 -
108.233 - The DEFAULT section is not acknowledged.
108.234 - """
108.235 - return section in self._sections
108.236 -
108.237 - def options(self, section):
108.238 - """Return a list of option names for the given section name."""
108.239 - opts = |>new_name<|(self, section, self)
108.240 - opts.update(self._defaults)
108.241 - if '__name__' in opts:
108.242 - del opts['__name__']
108.243 - return opts.keys()
108.244 -
108.245 -
108.246 - def |>^new_name<|(self, section, self):
108.247 - try:
108.248 - opts = self._sections[section].copy()
108.249 - except KeyError:
108.250 - raise NoSectionError(section)
108.251 -
108.252 - return opts
108.253 -
108.254 - def read(self, filenames):
108.255 - """Read and parse a filename or a list of filenames.
108.256 -
108.257 - Files that cannot be opened are silently ignored; this is
108.258 - designed so that you can specify a list of potential
108.259 - configuration file locations (e.g. current directory, user's
108.260 - home directory, systemwide directory), and all existing
108.261 - configuration files in the list will be read. A single
108.262 - filename may also be given.
108.263 - """
108.264 - if isinstance(filenames, basestring):
108.265 - filenames = [filenames]
108.266 - for filename in filenames:
108.267 - try:
108.268 - fp = open(filename)
108.269 - except IOError:
108.270 - continue
108.271 - self._read(fp, filename)
108.272 - fp.close()
108.273 -
108.274 - def readfp(self, fp, filename=None):
108.275 - """Like read() but the argument must be a file-like object.
108.276 -
108.277 - The `fp' argument must have a `readline' method. Optional
108.278 - second argument is the `filename', which if not given, is
108.279 - taken from fp.name. If fp has no `name' attribute, `<???>' is
108.280 - used.
108.281 -
108.282 - """
108.283 - if filename is None:
108.284 - try:
108.285 - filename = fp.name
108.286 - except AttributeError:
108.287 - filename = '<???>'
108.288 - self._read(fp, filename)
108.289 -
108.290 - def get(self, section, option):
108.291 - opt = self.optionxform(option)
108.292 - if section not in self._sections:
108.293 - if section != DEFAULTSECT:
108.294 - raise NoSectionError(section)
108.295 - if opt in self._defaults:
108.296 - return self._defaults[opt]
108.297 - else:
108.298 - raise NoOptionError(option, section)
108.299 - elif opt in self._sections[section]:
108.300 - return self._sections[section][opt]
108.301 - elif opt in self._defaults:
108.302 - return self._defaults[opt]
108.303 - else:
108.304 - raise NoOptionError(option, section)
108.305 -
108.306 - def items(self, section):
108.307 - try:
108.308 - d2 = self._sections[section]
108.309 - except KeyError:
108.310 - if section != DEFAULTSECT:
108.311 - raise NoSectionError(section)
108.312 - d2 = {}
108.313 - d = self._defaults.copy()
108.314 - d.update(d2)
108.315 - if "__name__" in d:
108.316 - del d["__name__"]
108.317 - return d.items()
108.318 -
108.319 - def _get(self, section, conv, option):
108.320 - return conv(self.get(section, option))
108.321 -
108.322 - def getint(self, section, option):
108.323 - return self._get(section, int, option)
108.324 -
108.325 - def getfloat(self, section, option):
108.326 - return self._get(section, float, option)
108.327 -
108.328 - _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
108.329 - '0': False, 'no': False, 'false': False, 'off': False}
108.330 -
108.331 - def getboolean(self, section, option):
108.332 - v = self.get(section, option)
108.333 - if v.lower() not in self._boolean_states:
108.334 - raise ValueError, 'Not a boolean: %s' % v
108.335 - return self._boolean_states[v.lower()]
108.336 -
108.337 - def optionxform(self, optionstr):
108.338 - return optionstr.lower()
108.339 -
108.340 - def has_option(self, section, option):
108.341 - """Check for the existence of a given option in a given section."""
108.342 - if not section or section == DEFAULTSECT:
108.343 - option = self.optionxform(option)
108.344 - return option in self._defaults
108.345 - elif section not in self._sections:
108.346 - return False
108.347 - else:
108.348 - option = self.optionxform(option)
108.349 - return (option in self._sections[section]
108.350 - or option in self._defaults)
108.351 -
108.352 - def set(self, section, option, value):
108.353 - """Set an option."""
108.354 - if not section or section == DEFAULTSECT:
108.355 - sectdict = self._defaults
108.356 - else:
108.357 - try:
108.358 - sectdict = self._sections[section]
108.359 - except KeyError:
108.360 - raise NoSectionError(section)
108.361 - sectdict[self.optionxform(option)] = value
108.362 -
108.363 - def write(self, fp):
108.364 - """Write an .ini-format representation of the configuration state."""
108.365 - if self._defaults:
108.366 - fp.write("[%s]\n" % DEFAULTSECT)
108.367 - for (key, value) in self._defaults.items():
108.368 - fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
108.369 - fp.write("\n")
108.370 - for section in self._sections:
108.371 - fp.write("[%s]\n" % section)
108.372 - for (key, value) in self._sections[section].items():
108.373 - if key != "__name__":
108.374 - fp.write("%s = %s\n" %
108.375 - (key, str(value).replace('\n', '\n\t')))
108.376 - fp.write("\n")
108.377 -
108.378 - def remove_option(self, section, option):
108.379 - """Remove an option."""
108.380 - if not section or section == DEFAULTSECT:
108.381 - sectdict = self._defaults
108.382 - else:
108.383 - try:
108.384 - sectdict = self._sections[section]
108.385 - except KeyError:
108.386 - raise NoSectionError(section)
108.387 - option = self.optionxform(option)
108.388 - existed = option in sectdict
108.389 - if existed:
108.390 - del sectdict[option]
108.391 - return existed
108.392 -
108.393 - def remove_section(self, section):
108.394 - """Remove a file section."""
108.395 - existed = section in self._sections
108.396 - if existed:
108.397 - del self._sections[section]
108.398 - return existed
108.399 -
108.400 - #
108.401 - # Regular expressions for parsing section headers and options.
108.402 - #
108.403 - SECTCRE = re.compile(
108.404 - r'\[' # [
108.405 - r'(?P<header>[^]]+)' # very permissive!
108.406 - r'\]' # ]
108.407 - )
108.408 - OPTCRE = re.compile(
108.409 - r'(?P<option>[^:=\s][^:=]*)' # very permissive!
108.410 - r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
108.411 - # followed by separator
108.412 - # (either : or =), followed
108.413 - # by any # space/tab
108.414 - r'(?P<value>.*)$' # everything up to eol
108.415 - )
108.416 -
108.417 - def _read(self, fp, fpname):
108.418 - """Parse a sectioned setup file.
108.419 -
108.420 - The sections in setup file contains a title line at the top,
108.421 - indicated by a name in square brackets (`[]'), plus key/value
108.422 - options lines, indicated by `name: value' format lines.
108.423 - Continuations are represented by an embedded newline then
108.424 - leading whitespace. Blank lines, lines beginning with a '#',
108.425 - and just about everything else are ignored.
108.426 - """
108.427 - cursect = None # None, or a dictionary
108.428 - optname = None
108.429 - lineno = 0
108.430 - e = None # None, or an exception
108.431 - while True:
108.432 - line = fp.readline()
108.433 - if not line:
108.434 - break
108.435 - lineno = lineno + 1
108.436 - # comment or blank line?
108.437 - if line.strip() == '' or line[0] in '#;':
108.438 - continue
108.439 - if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
108.440 - # no leading whitespace
108.441 - continue
108.442 - # continuation line?
108.443 - if line[0].isspace() and cursect is not None and optname:
108.444 - value = line.strip()
108.445 - if value:
108.446 - cursect[optname] = "%s\n%s" % (cursect[optname], value)
108.447 - # a section header or option header?
108.448 - else:
108.449 - # is it a section header?
108.450 - mo = self.SECTCRE.match(line)
108.451 - if mo:
108.452 - sectname = mo.group('header')
108.453 - if sectname in self._sections:
108.454 - cursect = self._sections[sectname]
108.455 - elif sectname == DEFAULTSECT:
108.456 - cursect = self._defaults
108.457 - else:
108.458 - cursect = {'__name__': sectname}
108.459 - self._sections[sectname] = cursect
108.460 - # So sections can't start with a continuation line
108.461 - optname = None
108.462 - # no section header in the file?
108.463 - elif cursect is None:
108.464 - raise MissingSectionHeaderError(fpname, lineno, `line`)
108.465 - # an option line?
108.466 - else:
108.467 - mo = self.OPTCRE.match(line)
108.468 - if mo:
108.469 - optname, vi, optval = mo.group('option', 'vi', 'value')
108.470 - if vi in ('=', ':') and ';' in optval:
108.471 - # ';' is a comment delimiter only if it follows
108.472 - # a spacing character
108.473 - pos = optval.find(';')
108.474 - if pos != -1 and optval[pos-1].isspace():
108.475 - optval = optval[:pos]
108.476 - optval = optval.strip()
108.477 - # allow empty values
108.478 - if optval == '""':
108.479 - optval = ''
108.480 - optname = self.optionxform(optname.rstrip())
108.481 - cursect[optname] = optval
108.482 - else:
108.483 - # a non-fatal parsing error occurred. set up the
108.484 - # exception but keep going. the exception will be
108.485 - # raised at the end of the file and will contain a
108.486 - # list of all bogus lines
108.487 - if not e:
108.488 - e = ParsingError(fpname)
108.489 - e.append(lineno, `line`)
108.490 - # if any parsing errors occurred, raise an exception
108.491 - if e:
108.492 - raise e
108.493 -
108.494 -
108.495 -class ConfigParser(RawConfigParser):
108.496 -
108.497 - def get(self, section, option, raw=False, vars=None):
108.498 - """Get an option value for a given section.
108.499 -
108.500 - All % interpolations are expanded in the return values, based on the
108.501 - defaults passed into the constructor, unless the optional argument
108.502 - `raw' is true. Additional substitutions may be provided using the
108.503 - `vars' argument, which must be a dictionary whose contents overrides
108.504 - any pre-existing defaults.
108.505 -
108.506 - The section DEFAULT is special.
108.507 - """
108.508 - d = self._defaults.copy()
108.509 - try:
108.510 - d.update(self._sections[section])
108.511 - except KeyError:
108.512 - if section != DEFAULTSECT:
108.513 - raise NoSectionError(section)
108.514 - # Update with the entry specific variables
108.515 - if vars is not None:
108.516 - d.update(vars)
108.517 - option = self.optionxform(option)
108.518 - try:
108.519 - value = d[option]
108.520 - except KeyError:
108.521 - raise NoOptionError(option, section)
108.522 -
108.523 - if raw:
108.524 - return value
108.525 - else:
108.526 - return self._interpolate(section, option, value, d)
108.527 -
108.528 - def items(self, section, raw=False, vars=None):
108.529 - """Return a list of tuples with (name, value) for each option
108.530 - in the section.
108.531 -
108.532 - All % interpolations are expanded in the return values, based on the
108.533 - defaults passed into the constructor, unless the optional argument
108.534 - `raw' is true. Additional substitutions may be provided using the
108.535 - `vars' argument, which must be a dictionary whose contents overrides
108.536 - any pre-existing defaults.
108.537 -
108.538 - The section DEFAULT is special.
108.539 - """
108.540 - d = self._defaults.copy()
108.541 - try:
108.542 - d.update(self._sections[section])
108.543 - except KeyError:
108.544 - if section != DEFAULTSECT:
108.545 - raise NoSectionError(section)
108.546 - # Update with the entry specific variables
108.547 - if vars:
108.548 - d.update(vars)
108.549 - options = d.keys()
108.550 - if "__name__" in options:
108.551 - options.remove("__name__")
108.552 - if raw:
108.553 - return [(option, d[option])
108.554 - for option in options]
108.555 - else:
108.556 - return [(option, self._interpolate(section, option, d[option], d))
108.557 - for option in options]
108.558 -
108.559 - def _interpolate(self, section, option, rawval, vars):
108.560 - # do the string interpolation
108.561 - value = rawval
108.562 - depth = MAX_INTERPOLATION_DEPTH
108.563 - while depth: # Loop through this until it's done
108.564 - depth -= 1
108.565 - if value.find("%(") != -1:
108.566 - try:
108.567 - value = value % vars
108.568 - except KeyError, e:
108.569 - raise InterpolationMissingOptionError(
108.570 - option, section, rawval, e[0])
108.571 - else:
108.572 - break
108.573 - if value.find("%(") != -1:
108.574 - raise InterpolationDepthError(option, section, rawval)
108.575 - return value
108.576 -
108.577 -
108.578 -class SafeConfigParser(ConfigParser):
108.579 -
108.580 - def _interpolate(self, section, option, rawval, vars):
108.581 - # do the string interpolation
108.582 - L = []
108.583 - self._interpolate_some(option, L, rawval, section, vars, 1)
108.584 - return ''.join(L)
108.585 -
108.586 - _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
108.587 -
108.588 - def _interpolate_some(self, option, accum, rest, section, map, depth):
108.589 - if depth > MAX_INTERPOLATION_DEPTH:
108.590 - raise InterpolationDepthError(option, section, rest)
108.591 - while rest:
108.592 - p = rest.find("%")
108.593 - if p < 0:
108.594 - accum.append(rest)
108.595 - return
108.596 - if p > 0:
108.597 - accum.append(rest[:p])
108.598 - rest = rest[p:]
108.599 - # p is no longer used
108.600 - c = rest[1:2]
108.601 - if c == "%":
108.602 - accum.append("%")
108.603 - rest = rest[2:]
108.604 - elif c == "(":
108.605 - m = self._interpvar_match(rest)
108.606 - if m is None:
108.607 - raise InterpolationSyntaxError(option, section,
108.608 - "bad interpolation variable reference %r" % rest)
108.609 - var = m.group(1)
108.610 - rest = rest[m.end():]
108.611 - try:
108.612 - v = map[var]
108.613 - except KeyError:
108.614 - raise InterpolationMissingOptionError(
108.615 - option, section, rest, var)
108.616 - if "%" in v:
108.617 - self._interpolate_some(option, accum, v,
108.618 - section, map, depth + 1)
108.619 - else:
108.620 - accum.append(v)
108.621 - else:
108.622 - raise InterpolationSyntaxError(
108.623 - option, section,
108.624 - "'%' must be followed by '%' or '(', found: " + `ret`)
109.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testGetByCaretOffset.path Sun Jan 04 13:11:53 2015 -0600
109.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
109.3 @@ -1,6 +0,0 @@
109.4 -Module:OffsetRange[0,22066>
109.5 -ClassDef:OffsetRange[3844,4067>
109.6 -FunctionDef:OffsetRange[3938,4067>
109.7 -Expr:OffsetRange[3975,4034>
109.8 -Call:OffsetRange[3975,4034>
109.9 -Name:OffsetRange[3990,3994>
110.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testGetByNode1.path Sun Jan 04 13:11:53 2015 -0600
110.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
110.3 @@ -1,6 +0,0 @@
110.4 -Module:OffsetRange[0,22066>
110.5 -ClassDef:OffsetRange[3844,4067>
110.6 -FunctionDef:OffsetRange[3938,4067>
110.7 -Expr:OffsetRange[3975,4034>
110.8 -Call:OffsetRange[3975,4034>
110.9 -Name:OffsetRange[3990,3994>
111.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testGetByNode2.path Sun Jan 04 13:11:53 2015 -0600
111.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
111.3 @@ -1,5 +0,0 @@
111.4 -Module:OffsetRange[0,22066>
111.5 -ClassDef:OffsetRange[3844,4067>
111.6 -FunctionDef:OffsetRange[3938,4067>
111.7 -Expr:OffsetRange[3975,4034>
111.8 -Call:OffsetRange[3975,4034>
112.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testImports1.completion Sun Jan 04 13:11:53 2015 -0600
112.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
112.3 @@ -1,638 +0,0 @@
112.4 -Code completion result for source line:
112.5 -import |re
112.6 -(QueryType=COMPLETION, NameKind=PREFIX)
112.7 -------------------------------------
112.8 -KEYWORD BaseHTTPServer
112.9 -KEYWORD ---Bastion ---
112.10 -KEYWORD CGIHTTPServer
112.11 -KEYWORD ---Carbon.AE ---
112.12 -KEYWORD ---Carbon.AH ---
112.13 -KEYWORD ---Carbon.App ---
112.14 -KEYWORD ---Carbon.CF ---
112.15 -KEYWORD ---Carbon.CG ---
112.16 -KEYWORD ---Carbon.CarbonEvt ---
112.17 -KEYWORD ---Carbon.Cm ---
112.18 -KEYWORD ---Carbon.Ctl ---
112.19 -KEYWORD ---Carbon.Dlg ---
112.20 -KEYWORD ---Carbon.Evt ---
112.21 -KEYWORD ---Carbon.Fm ---
112.22 -KEYWORD ---Carbon.Folder ---
112.23 -KEYWORD ---Carbon.Help ---
112.24 -KEYWORD ---Carbon.List ---
112.25 -KEYWORD ---Carbon.Menu ---
112.26 -KEYWORD ---Carbon.Mlte ---
112.27 -KEYWORD ---Carbon.Qd ---
112.28 -KEYWORD ---Carbon.Qdoffs ---
112.29 -KEYWORD ---Carbon.Qt ---
112.30 -KEYWORD ---Carbon.Res ---
112.31 -KEYWORD ---Carbon.Scrap ---
112.32 -KEYWORD ---Carbon.Snd ---
112.33 -KEYWORD ---Carbon.TE ---
112.34 -KEYWORD ---Carbon.Win ---
112.35 -KEYWORD ---ColorPicker ---
112.36 -KEYWORD ConfigParser
112.37 -KEYWORD Cookie
112.38 -KEYWORD DocXMLRPCServer
112.39 -KEYWORD ---EasyDialogs ---
112.40 -KEYWORD ---FrameWork ---
112.41 -KEYWORD HTMLParser
112.42 -KEYWORD ---MacOS ---
112.43 -KEYWORD ---MimeWriter ---
112.44 -KEYWORD MiniAEFrame
112.45 -KEYWORD ---Nav ---
112.46 -KEYWORD ---PixMapWrapper ---
112.47 -KEYWORD Queue
112.48 -KEYWORD ScrolledText
112.49 -KEYWORD SimpleHTTPServer
112.50 -KEYWORD SimpleXMLRPCServer
112.51 -KEYWORD SocketServer
112.52 -KEYWORD StringIO
112.53 -KEYWORD Tix
112.54 -KEYWORD Tkinter
112.55 -KEYWORD UserDict
112.56 -KEYWORD UserList
112.57 -KEYWORD UserString
112.58 -KEYWORD ---W ---
112.59 -KEYWORD _LWPCookieJar
112.60 -KEYWORD _MozillaCookieJar
112.61 -KEYWORD __builtin__
112.62 -KEYWORD __future__
112.63 -KEYWORD __main__
112.64 -KEYWORD _ast
112.65 -KEYWORD _rawffi
112.66 -KEYWORD _strptime
112.67 -KEYWORD _threading_local
112.68 -KEYWORD _winreg
112.69 -KEYWORD abc
112.70 -KEYWORD ---aepack ---
112.71 -KEYWORD ---aetools ---
112.72 -KEYWORD ---aetypes ---
112.73 -KEYWORD aifc
112.74 -KEYWORD anydbm
112.75 -KEYWORD ---applesingle ---
112.76 -KEYWORD array
112.77 -KEYWORD ast
112.78 -KEYWORD asynchat
112.79 -KEYWORD asyncore
112.80 -KEYWORD atexit
112.81 -KEYWORD audioop
112.82 -KEYWORD ---autoGIL ---
112.83 -KEYWORD base64
112.84 -KEYWORD bdb
112.85 -KEYWORD binascii
112.86 -KEYWORD binhex
112.87 -KEYWORD bisect
112.88 -KEYWORD bsddb
112.89 -KEYWORD ---buildtools ---
112.90 -KEYWORD bz2
112.91 -KEYWORD calendar
112.92 -KEYWORD ---cfmfile ---
112.93 -KEYWORD cgi
112.94 -KEYWORD cgitb
112.95 -KEYWORD chunk
112.96 -KEYWORD cmath
112.97 -KEYWORD cmd
112.98 -KEYWORD code
112.99 -KEYWORD codecs
112.100 -KEYWORD codeop
112.101 -KEYWORD collections
112.102 -KEYWORD colorsys
112.103 -KEYWORD commands
112.104 -KEYWORD compileall
112.105 -KEYWORD compiler
112.106 -KEYWORD compiler.ast
112.107 -KEYWORD compiler.consts
112.108 -KEYWORD compiler.future
112.109 -KEYWORD compiler.misc
112.110 -KEYWORD compiler.pyassem
112.111 -KEYWORD compiler.pycodegen
112.112 -KEYWORD compiler.symbols
112.113 -KEYWORD compiler.syntax
112.114 -KEYWORD compiler.transformer
112.115 -KEYWORD compiler.visitor
112.116 -KEYWORD compl
112.117 -KEYWORD compl2
112.118 -KEYWORD compl3
112.119 -KEYWORD compl4
112.120 -KEYWORD compl5
112.121 -KEYWORD constants
112.122 -KEYWORD contextlib
112.123 -KEYWORD cookielib
112.124 -KEYWORD copy
112.125 -KEYWORD copy_reg
112.126 -KEYWORD crypt
112.127 -KEYWORD csv
112.128 -KEYWORD ctypes
112.129 -KEYWORD curses
112.130 -KEYWORD curses.ascii
112.131 -KEYWORD curses.panel
112.132 -KEYWORD curses.textpad
112.133 -KEYWORD curses.wrapper
112.134 -KEYWORD datetime
112.135 -KEYWORD dbexts
112.136 -KEYWORD dbhash
112.137 -KEYWORD dbm
112.138 -KEYWORD decimal
112.139 -KEYWORD difflib
112.140 -KEYWORD dircache
112.141 -KEYWORD dis
112.142 -KEYWORD distutils
112.143 -KEYWORD distutils.archive_util
112.144 -KEYWORD distutils.bcppcompiler
112.145 -KEYWORD distutils.ccompiler
112.146 -KEYWORD distutils.cmd
112.147 -KEYWORD distutils.command
112.148 -KEYWORD distutils.command.bdist
112.149 -KEYWORD distutils.command.bdist_dumb
112.150 -KEYWORD distutils.command.bdist_msi
112.151 -KEYWORD distutils.command.bdist_rpm
112.152 -KEYWORD distutils.command.bdist_winins
112.153 -KEYWORD distutils.command.build
112.154 -KEYWORD distutils.command.build_clib
112.155 -KEYWORD distutils.command.build_ext
112.156 -KEYWORD distutils.command.build_py
112.157 -KEYWORD distutils.command.build_script
112.158 -KEYWORD distutils.command.clean
112.159 -KEYWORD distutils.command.config
112.160 -KEYWORD distutils.command.install
112.161 -KEYWORD distutils.command.install_data
112.162 -KEYWORD distutils.command.install_egg_
112.163 -KEYWORD distutils.command.install_head
112.164 -KEYWORD distutils.command.install_lib
112.165 -KEYWORD distutils.command.install_scri
112.166 -KEYWORD distutils.command.register
112.167 -KEYWORD distutils.command.sdist
112.168 -KEYWORD distutils.command.upload
112.169 -KEYWORD distutils.core
112.170 -KEYWORD distutils.cygwinccompiler
112.171 -KEYWORD distutils.debug
112.172 -KEYWORD distutils.dep_util
112.173 -KEYWORD distutils.dir_util
112.174 -KEYWORD distutils.dist
112.175 -KEYWORD distutils.emxccompiler
112.176 -KEYWORD distutils.errors
112.177 -KEYWORD distutils.extension
112.178 -KEYWORD distutils.fancy_getopt
112.179 -KEYWORD distutils.file_util
112.180 -KEYWORD distutils.filelist
112.181 -KEYWORD distutils.jythoncompiler
112.182 -KEYWORD distutils.log
112.183 -KEYWORD distutils.msvccompiler
112.184 -KEYWORD distutils.mwerkscompiler
112.185 -KEYWORD distutils.spawn
112.186 -KEYWORD distutils.sysconfig
112.187 -KEYWORD distutils.tests
112.188 -KEYWORD distutils.tests.support
112.189 -KEYWORD distutils.tests.test_build_py
112.190 -KEYWORD distutils.tests.test_build_scr
112.191 -KEYWORD distutils.tests.test_dist
112.192 -KEYWORD distutils.tests.test_install
112.193 -KEYWORD distutils.tests.test_install_s
112.194 -KEYWORD distutils.tests.test_versionpr
112.195 -KEYWORD distutils.text_file
112.196 -KEYWORD distutils.unixccompiler
112.197 -KEYWORD distutils.util
112.198 -KEYWORD distutils.version
112.199 -KEYWORD distutils.versionpredicate
112.200 -KEYWORD ---dl ---
112.201 -KEYWORD doctest
112.202 -KEYWORD dumbdbm
112.203 -KEYWORD dummy_thread
112.204 -KEYWORD dummy_threading
112.205 -KEYWORD email
112.206 -KEYWORD email._parseaddr
112.207 -KEYWORD email.base64mime
112.208 -KEYWORD email.charset
112.209 -KEYWORD email.encoders
112.210 -KEYWORD email.errors
112.211 -KEYWORD email.feedparser
112.212 -KEYWORD email.generator
112.213 -KEYWORD email.header
112.214 -KEYWORD email.iterators
112.215 -KEYWORD email.message
112.216 -KEYWORD email.mime
112.217 -KEYWORD email.mime.application
112.218 -KEYWORD email.mime.audio
112.219 -KEYWORD email.mime.base
112.220 -KEYWORD email.mime.image
112.221 -KEYWORD email.mime.message
112.222 -KEYWORD email.mime.multipart
112.223 -KEYWORD email.mime.nonmultipart
112.224 -KEYWORD email.mime.text
112.225 -KEYWORD email.parser
112.226 -KEYWORD email.quoprimime
112.227 -KEYWORD email.test.test_email_torture
112.228 -KEYWORD email.utils
112.229 -KEYWORD empty
112.230 -KEYWORD encodings
112.231 -KEYWORD encodings.aliases
112.232 -KEYWORD encodings.ascii
112.233 -KEYWORD encodings.base64_codec
112.234 -KEYWORD encodings.big5
112.235 -KEYWORD encodings.big5hkscs
112.236 -KEYWORD encodings.bz2_codec
112.237 -KEYWORD encodings.charmap
112.238 -KEYWORD encodings.cp037
112.239 -KEYWORD encodings.cp1006
112.240 -KEYWORD encodings.cp1026
112.241 -KEYWORD encodings.cp1140
112.242 -KEYWORD encodings.cp1250
112.243 -KEYWORD encodings.cp1251
112.244 -KEYWORD encodings.cp1252
112.245 -KEYWORD encodings.cp1253
112.246 -KEYWORD encodings.cp1254
112.247 -KEYWORD encodings.cp1255
112.248 -KEYWORD encodings.cp1256
112.249 -KEYWORD encodings.cp1257
112.250 -KEYWORD encodings.cp1258
112.251 -KEYWORD encodings.cp424
112.252 -KEYWORD encodings.cp437
112.253 -KEYWORD encodings.cp500
112.254 -KEYWORD encodings.cp737
112.255 -KEYWORD encodings.cp775
112.256 -KEYWORD encodings.cp850
112.257 -KEYWORD encodings.cp852
112.258 -KEYWORD encodings.cp855
112.259 -KEYWORD encodings.cp856
112.260 -KEYWORD encodings.cp857
112.261 -KEYWORD encodings.cp860
112.262 -KEYWORD encodings.cp861
112.263 -KEYWORD encodings.cp862
112.264 -KEYWORD encodings.cp863
112.265 -KEYWORD encodings.cp864
112.266 -KEYWORD encodings.cp865
112.267 -KEYWORD encodings.cp866
112.268 -KEYWORD encodings.cp869
112.269 -KEYWORD encodings.cp874
112.270 -KEYWORD encodings.cp875
112.271 -KEYWORD encodings.cp932
112.272 -KEYWORD encodings.cp949
112.273 -KEYWORD encodings.cp950
112.274 -KEYWORD encodings.euc_jis_2004
112.275 -KEYWORD encodings.euc_jisx0213
112.276 -KEYWORD encodings.euc_jp
112.277 -KEYWORD encodings.euc_kr
112.278 -KEYWORD encodings.gb18030
112.279 -KEYWORD encodings.gb2312
112.280 -KEYWORD encodings.gbk
112.281 -KEYWORD encodings.hex_codec
112.282 -KEYWORD encodings.hp_roman8
112.283 -KEYWORD encodings.hz
112.284 -KEYWORD encodings.idna
112.285 -KEYWORD encodings.iso2022_jp
112.286 -KEYWORD encodings.iso2022_jp_1
112.287 -KEYWORD encodings.iso2022_jp_2
112.288 -KEYWORD encodings.iso2022_jp_2004
112.289 -KEYWORD encodings.iso2022_jp_3
112.290 -KEYWORD encodings.iso2022_jp_ext
112.291 -KEYWORD encodings.iso2022_kr
112.292 -KEYWORD encodings.iso8859_1
112.293 -KEYWORD encodings.iso8859_10
112.294 -KEYWORD encodings.iso8859_11
112.295 -KEYWORD encodings.iso8859_13
112.296 -KEYWORD encodings.iso8859_14
112.297 -KEYWORD encodings.iso8859_15
112.298 -KEYWORD encodings.iso8859_16
112.299 -KEYWORD encodings.iso8859_2
112.300 -KEYWORD encodings.iso8859_3
112.301 -KEYWORD encodings.iso8859_4
112.302 -KEYWORD encodings.iso8859_5
112.303 -KEYWORD encodings.iso8859_6
112.304 -KEYWORD encodings.iso8859_7
112.305 -KEYWORD encodings.iso8859_8
112.306 -KEYWORD encodings.iso8859_9
112.307 -KEYWORD encodings.johab
112.308 -KEYWORD encodings.koi8_r
112.309 -KEYWORD encodings.koi8_u
112.310 -KEYWORD encodings.latin_1
112.311 -KEYWORD encodings.mac_arabic
112.312 -KEYWORD encodings.mac_centeuro
112.313 -KEYWORD encodings.mac_croatian
112.314 -KEYWORD encodings.mac_cyrillic
112.315 -KEYWORD encodings.mac_farsi
112.316 -KEYWORD encodings.mac_greek
112.317 -KEYWORD encodings.mac_iceland
112.318 -KEYWORD encodings.mac_latin2
112.319 -KEYWORD encodings.mac_roman
112.320 -KEYWORD encodings.mac_romanian
112.321 -KEYWORD encodings.mac_turkish
112.322 -KEYWORD encodings.mbcs
112.323 -KEYWORD encodings.palmos
112.324 -KEYWORD encodings.ptcp154
112.325 -KEYWORD encodings.punycode
112.326 -KEYWORD encodings.quopri_codec
112.327 -KEYWORD encodings.raw_unicode_escape
112.328 -KEYWORD encodings.rot_13
112.329 -KEYWORD encodings.shift_jis
112.330 -KEYWORD encodings.shift_jis_2004
112.331 -KEYWORD encodings.shift_jisx0213
112.332 -KEYWORD encodings.string_escape
112.333 -KEYWORD encodings.tis_620
112.334 -KEYWORD encodings.undefined
112.335 -KEYWORD encodings.unicode_escape
112.336 -KEYWORD encodings.unicode_internal
112.337 -KEYWORD encodings.utf_16
112.338 -KEYWORD encodings.utf_16_be
112.339 -KEYWORD encodings.utf_16_le
112.340 -KEYWORD encodings.utf_7
112.341 -KEYWORD encodings.utf_8
112.342 -KEYWORD encodings.utf_8_sig
112.343 -KEYWORD encodings.uu_codec
112.344 -KEYWORD encodings.zlib_codec
112.345 -KEYWORD errno
112.346 -KEYWORD exceptions
112.347 -KEYWORD fcntl
112.348 -KEYWORD filecmp
112.349 -KEYWORD fileinput
112.350 -KEYWORD findertools
112.351 -KEYWORD fnmatch
112.352 -KEYWORD formatter
112.353 -KEYWORD fpectl
112.354 -KEYWORD fpformat
112.355 -KEYWORD fractions
112.356 -KEYWORD ftplib
112.357 -KEYWORD functions
112.358 -KEYWORD functools
112.359 -KEYWORD future_builtins
112.360 -KEYWORD gc
112.361 -KEYWORD gdbm
112.362 -KEYWORD gensuitemodule
112.363 -KEYWORD getopt
112.364 -KEYWORD getpass
112.365 -KEYWORD gettext
112.366 -KEYWORD glob
112.367 -KEYWORD ---gopherlib ---
112.368 -KEYWORD grp
112.369 -KEYWORD gzip
112.370 -KEYWORD hashlib
112.371 -KEYWORD heapq
112.372 -KEYWORD hmac
112.373 -KEYWORD hotshot
112.374 -KEYWORD hotshot.stats
112.375 -KEYWORD htmlentitydefs
112.376 -KEYWORD htmllib
112.377 -KEYWORD httplib
112.378 -KEYWORD ---ic ---
112.379 -KEYWORD ---icopen ---
112.380 -KEYWORD ihooks
112.381 -KEYWORD ---imageop ---
112.382 -KEYWORD imaplib
112.383 -KEYWORD imghdr
112.384 -KEYWORD imp
112.385 -KEYWORD imports3
112.386 -KEYWORD imports4
112.387 -KEYWORD imports5
112.388 -KEYWORD imports6
112.389 -KEYWORD imports7
112.390 -KEYWORD imports8
112.391 -KEYWORD imports9
112.392 -KEYWORD ---imputil ---
112.393 -KEYWORD inspect
112.394 -KEYWORD io
112.395 -KEYWORD isql
112.396 -KEYWORD itertools
112.397 -KEYWORD javapath
112.398 -KEYWORD javashell
112.399 -KEYWORD jreload
112.400 -KEYWORD json
112.401 -KEYWORD keyword
112.402 -KEYWORD lib2to3
112.403 -KEYWORD linecache
112.404 -KEYWORD locale
112.405 -KEYWORD logging
112.406 -KEYWORD logging.config
112.407 -KEYWORD logging.handlers
112.408 -KEYWORD ---macerrors ---
112.409 -KEYWORD ---macostools ---
112.410 -KEYWORD macpath
112.411 -KEYWORD ---macresource ---
112.412 -KEYWORD macurl2path
112.413 -KEYWORD mailbox
112.414 -KEYWORD mailcap
112.415 -KEYWORD markupbase
112.416 -KEYWORD marshal
112.417 -KEYWORD math
112.418 -KEYWORD ---md5 ---
112.419 -KEYWORD mhlib
112.420 -KEYWORD ---mimetools ---
112.421 -KEYWORD mimetypes
112.422 -KEYWORD ---mimify ---
112.423 -KEYWORD mmap
112.424 -KEYWORD modulefinder
112.425 -KEYWORD msilib
112.426 -KEYWORD msvcrt
112.427 -KEYWORD ---multifile ---
112.428 -KEYWORD multiprocessing
112.429 -KEYWORD multiprocessing.connection
112.430 -KEYWORD multiprocessing.dummy
112.431 -KEYWORD multiprocessing.managers
112.432 -KEYWORD multiprocessing.pool
112.433 -KEYWORD multiprocessing.sharedctypes
112.434 -KEYWORD mutex
112.435 -KEYWORD netrc
112.436 -KEYWORD new
112.437 -KEYWORD nis
112.438 -KEYWORD nntplib
112.439 -KEYWORD ntpath
112.440 -KEYWORD nturl2path
112.441 -KEYWORD numbers
112.442 -KEYWORD occurrences2
112.443 -KEYWORD opcode
112.444 -KEYWORD operator
112.445 -KEYWORD optparse
112.446 -KEYWORD os
112.447 -KEYWORD os.path
112.448 -KEYWORD ossaudiodev
112.449 -KEYWORD parser
112.450 -KEYWORD pawt
112.451 -KEYWORD pawt.colors
112.452 -KEYWORD pawt.swing
112.453 -KEYWORD pdb
112.454 -KEYWORD pickle
112.455 -KEYWORD pickletools
112.456 -KEYWORD pipes
112.457 -KEYWORD pkgutil
112.458 -KEYWORD platform
112.459 -KEYWORD plistlib
112.460 -KEYWORD popen2
112.461 -KEYWORD poplib
112.462 -KEYWORD posix
112.463 -KEYWORD ---posixfile ---
112.464 -KEYWORD posixpath
112.465 -KEYWORD pprint
112.466 -KEYWORD profile
112.467 -KEYWORD pstats
112.468 -KEYWORD pty
112.469 -KEYWORD pwd
112.470 -KEYWORD py_compile
112.471 -KEYWORD pyclbr
112.472 -KEYWORD pydoc
112.473 -KEYWORD quopri
112.474 -KEYWORD random
112.475 -KEYWORD re
112.476 -KEYWORD readline
112.477 -KEYWORD repr
112.478 -KEYWORD resource
112.479 -KEYWORD ---rexec ---
112.480 -KEYWORD ---rfc822 ---
112.481 -KEYWORD rlcompleter
112.482 -KEYWORD robotparser
112.483 -KEYWORD runpy
112.484 -KEYWORD sched
112.485 -KEYWORD select
112.486 -KEYWORD ---sets ---
112.487 -KEYWORD sgmllib
112.488 -KEYWORD ---sha ---
112.489 -KEYWORD shelve
112.490 -KEYWORD shlex
112.491 -KEYWORD shutil
112.492 -KEYWORD signal
112.493 -KEYWORD site
112.494 -KEYWORD smtpd
112.495 -KEYWORD smtplib
112.496 -KEYWORD sndhdr
112.497 -KEYWORD socket
112.498 -KEYWORD spwd
112.499 -KEYWORD sqlite3
112.500 -KEYWORD sre
112.501 -KEYWORD sre_compile
112.502 -KEYWORD sre_constants
112.503 -KEYWORD sre_parse
112.504 -KEYWORD ssl
112.505 -KEYWORD stat
112.506 -KEYWORD ---statvfs ---
112.507 -KEYWORD stdtypes
112.508 -KEYWORD string
112.509 -KEYWORD ---stringprep ---
112.510 -KEYWORD struct
112.511 -KEYWORD subprocess
112.512 -KEYWORD symbol
112.513 -KEYWORD symtable
112.514 -KEYWORD sys
112.515 -KEYWORD syslog
112.516 -KEYWORD tabnanny
112.517 -KEYWORD tarfile
112.518 -KEYWORD telnetlib
112.519 -KEYWORD tempfile
112.520 -KEYWORD termios
112.521 -KEYWORD test.bugs.bugs100
112.522 -KEYWORD test.bugs.bugs101
112.523 -KEYWORD test.bugs.jdkbugs
112.524 -KEYWORD test.bugs.pr101
112.525 -KEYWORD test.bugs.pr104
112.526 -KEYWORD test.bugs.pr112
112.527 -KEYWORD test.bugs.pr119
112.528 -KEYWORD test.bugs.pr127
112.529 -KEYWORD test.bugs.pr133
112.530 -KEYWORD test.bugs.pr133.test
112.531 -KEYWORD test.bugs.pr134
112.532 -KEYWORD test.bugs.pr139
112.533 -KEYWORD test.bugs.pr142
112.534 -KEYWORD test.bugs.pr144
112.535 -KEYWORD test.bugs.pr148
112.536 -KEYWORD test.bugs.pr149
112.537 -KEYWORD test.bugs.pr155
112.538 -KEYWORD test.bugs.pr170
112.539 -KEYWORD test.bugs.pr171
112.540 -KEYWORD test.bugs.pr174
112.541 -KEYWORD test.bugs.pr178
112.542 -KEYWORD test.bugs.pr183
112.543 -KEYWORD test.bugs.pr186
112.544 -KEYWORD test.bugs.pr191
112.545 -KEYWORD test.bugs.pr192
112.546 -KEYWORD test.bugs.pr195
112.547 -KEYWORD test.bugs.pr208
112.548 -KEYWORD test.bugs.pr233
112.549 -KEYWORD test.bugs.pr234
112.550 -KEYWORD test.bugs.pr235
112.551 -KEYWORD test.bugs.pr239
112.552 -KEYWORD test.bugs.pr241
112.553 -KEYWORD test.bugs.pr242
112.554 -KEYWORD test.crashers.bogus_code_obj
112.555 -KEYWORD test.crashers.borrowed_ref_1
112.556 -KEYWORD test.crashers.borrowed_ref_2
112.557 -KEYWORD test.crashers.gc_inspection
112.558 -KEYWORD test.crashers.infinite_rec_1
112.559 -KEYWORD test.crashers.infinite_rec_2
112.560 -KEYWORD test.crashers.infinite_rec_4
112.561 -KEYWORD test.crashers.infinite_rec_5
112.562 -KEYWORD test.crashers.loosing_dict_ref
112.563 -KEYWORD test.crashers.nasty_eq_vs_dict
112.564 -KEYWORD test.crashers.recursion_limit_
112.565 -KEYWORD test.crashers.recursive_call
112.566 -KEYWORD test.leakers
112.567 -KEYWORD test.leakers.test_ctypes
112.568 -KEYWORD test.leakers.test_gestalt
112.569 -KEYWORD test.leakers.test_selftype
112.570 -KEYWORD test.test_metaclass_support
112.571 -KEYWORD test.test_metaclass_support.me
112.572 -KEYWORD test.test_metaclass_support.si
112.573 -KEYWORD test.xmltests
112.574 -KEYWORD test.zxjdbc.dbextstest
112.575 -KEYWORD test.zxjdbc.jndi
112.576 -KEYWORD test.zxjdbc.runner
112.577 -KEYWORD test.zxjdbc.sptest
112.578 -KEYWORD test.zxjdbc.test_zxjdbc_dbapi2
112.579 -KEYWORD test.zxjdbc.zxtest
112.580 -KEYWORD textwrap
112.581 -KEYWORD this
112.582 -KEYWORD thread
112.583 -KEYWORD threading
112.584 -KEYWORD time
112.585 -KEYWORD timeit
112.586 -KEYWORD token
112.587 -KEYWORD tokenize
112.588 -KEYWORD trace
112.589 -KEYWORD traceback
112.590 -KEYWORD tty
112.591 -KEYWORD turtle
112.592 -KEYWORD types
112.593 -KEYWORD unicodedata
112.594 -KEYWORD unittest
112.595 -KEYWORD urllib
112.596 -KEYWORD urllib2
112.597 -KEYWORD urlparse
112.598 -KEYWORD user
112.599 -KEYWORD uu
112.600 -KEYWORD uuid
112.601 -KEYWORD ---videoreader ---
112.602 -KEYWORD warnings
112.603 -KEYWORD wave
112.604 -KEYWORD weakref
112.605 -KEYWORD webbrowser
112.606 -KEYWORD whichdb
112.607 -KEYWORD winsound
112.608 -KEYWORD wsgiref
112.609 -KEYWORD wsgiref.handlers
112.610 -KEYWORD wsgiref.headers
112.611 -KEYWORD wsgiref.simple_server
112.612 -KEYWORD wsgiref.util
112.613 -KEYWORD wsgiref.validate
112.614 -KEYWORD xdrlib
112.615 -KEYWORD xml
112.616 -KEYWORD xml.FtCore
112.617 -KEYWORD xml.Uri
112.618 -KEYWORD xml.dom
112.619 -KEYWORD xml.dom.MessageSource
112.620 -KEYWORD xml.dom.NodeFilter
112.621 -KEYWORD xml.dom.domreg
112.622 -KEYWORD xml.dom.minicompat
112.623 -KEYWORD xml.dom.minidom
112.624 -KEYWORD xml.dom.pulldom
112.625 -KEYWORD xml.dom.xmlbuilder
112.626 -KEYWORD xml.etree
112.627 -KEYWORD xml.etree.ElementTree
112.628 -KEYWORD xml.parsers.expat
112.629 -KEYWORD xml.sax
112.630 -KEYWORD xml.sax._exceptions
112.631 -KEYWORD xml.sax.drivers2
112.632 -KEYWORD xml.sax.drivers2.drv_javasax
112.633 -KEYWORD xml.sax.handler
112.634 -KEYWORD xml.sax.saxlib
112.635 -KEYWORD xml.sax.saxutils
112.636 -KEYWORD xml.sax.xmlreader
112.637 -KEYWORD xmllib
112.638 -KEYWORD xmlrpclib
112.639 -KEYWORD zipfile
112.640 -KEYWORD zipimport
112.641 -KEYWORD zlib
113.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testImports2.completion Sun Jan 04 13:11:53 2015 -0600
113.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
113.3 @@ -1,14 +0,0 @@
113.4 -Code completion result for source line:
113.5 -import r|e
113.6 -(QueryType=COMPLETION, NameKind=PREFIX)
113.7 -------------------------------------
113.8 -KEYWORD random
113.9 -KEYWORD re
113.10 -KEYWORD readline
113.11 -KEYWORD repr
113.12 -KEYWORD resource
113.13 -KEYWORD ---rexec ---
113.14 -KEYWORD ---rfc822 ---
113.15 -KEYWORD rlcompleter
113.16 -KEYWORD robotparser
113.17 -KEYWORD runpy
114.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testLocals1.completion Sun Jan 04 13:11:53 2015 -0600
114.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
114.3 @@ -1,16 +0,0 @@
114.4 -Code completion result for source line:
114.5 -s|elf.section = section
114.6 -(QueryType=COMPLETION, NameKind=PREFIX)
114.7 -VARIABLE section
114.8 -VARIABLE self
114.9 -------------------------------------
114.10 -CLASS set
114.11 -CLASS str
114.12 -METHOD set(iterable)
114.13 -METHOD setattr(object, name, value)
114.14 -METHOD slice(start, stop, step)
114.15 -METHOD sorted(iterable, cmp, key, rev
114.16 -METHOD staticmethod(function)
114.17 -METHOD str(object)
114.18 -METHOD sum(iterable, start)
114.19 -METHOD super(type, object-or-type)
115.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testMarks1.occurrences Sun Jan 04 13:11:53 2015 -0600
115.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
115.3 @@ -1,3 +0,0 @@
115.4 - def __init__(self, |>MARK_OCCURRENCES:m^sg<|=''):
115.5 - self.message = |>MARK_OCCURRENCES:msg<|
115.6 - Exception.__init__(self, |>MARK_OCCURRENCES:msg<|)
116.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testMarks2.occurrences Sun Jan 04 13:11:53 2015 -0600
116.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
116.3 @@ -1,5 +0,0 @@
116.4 - for (|>MARK_OCCURRENCES:key<|, value) in self._defaults.items():
116.5 - fp.write("%s = %s\n" % (|>MARK_OCCURRENCES:key<|, str(value).replace('\n', '\n\t')))
116.6 - for (|>MARK_OCCURRENCES:ke^y<|, value) in self._sections[section].items():
116.7 - if |>MARK_OCCURRENCES:key<| != "__name__":
116.8 - (|>MARK_OCCURRENCES:key<|, str(value).replace('\n', '\n\t')))
117.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testRename1.rename Sun Jan 04 13:11:53 2015 -0600
117.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
117.3 @@ -1,3 +0,0 @@
117.4 -107: def __init__(self, |>msg<|=''):
117.5 -108: self.message = |>msg<|
117.6 -109: Exception.__init__(self, |>msg<|)
118.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testRename2.rename Sun Jan 04 13:11:53 2015 -0600
118.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
118.3 @@ -1,5 +0,0 @@
118.4 -358: for (|>key<|, value) in self._defaults.items():
118.5 -359: fp.write("%s = %s\n" % (|>key<|, str(value).replace('\n', '\n\t')))
118.6 -363: for (|>key<|, value) in self._sections[section].items():
118.7 -364: if |>key<| != "__name__":
118.8 -366: (|>key<|, str(value).replace('\n', '\n\t')))
119.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testRename3.rename Sun Jan 04 13:11:53 2015 -0600
119.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
119.3 @@ -1,1 +0,0 @@
119.4 -Requires Interactive Refactoring
120.1 --- a/python.editor/test/unit/data/testfiles/ConfigParser.py.testStringCompletion.completion Sun Jan 04 13:11:53 2015 -0600
120.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
120.3 @@ -1,19 +0,0 @@
120.4 -Code completion result for source line:
120.5 -if line.split(None, 1)[0].lower() == 'rem' and line[0] in "|rR":
120.6 -(QueryType=COMPLETION, NameKind=PREFIX)
120.7 -------------------------------------
120.8 -KEYWORD ' Single quote (')
120.9 -KEYWORD \" Double quote (")
120.10 -KEYWORD \N{name} Character named name
120.11 -KEYWORD \Uxxxxxxxx Character with 32-b
120.12 -KEYWORD \\ Backslash (\)
120.13 -KEYWORD \a ASCII Bell (BEL)
120.14 -KEYWORD \b ASCII Backspace (BS)
120.15 -KEYWORD \f ASCII Formfeed (FF)
120.16 -KEYWORD \n ASCII Linefeed (LF)
120.17 -KEYWORD \ooo Character with octal valu
120.18 -KEYWORD \r ASCII Carriage Return (CR)
120.19 -KEYWORD \t ASCII Horizontal Tab (TAB)
120.20 -KEYWORD \uxxxx Character with 16-bit h
120.21 -KEYWORD \v ASCII Vertical Tab (VT)
120.22 -KEYWORD \xhh Character with hex value
121.1 --- a/python.editor/test/unit/data/testfiles/SocketServer.py Sun Jan 04 13:11:53 2015 -0600
121.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
121.3 @@ -1,588 +0,0 @@
121.4 -"""Generic socket server classes.
121.5 -
121.6 -This module tries to capture the various aspects of defining a server:
121.7 -
121.8 -For socket-based servers:
121.9 -
121.10 -- address family:
121.11 - - AF_INET{,6}: IP (Internet Protocol) sockets (default)
121.12 - - AF_UNIX: Unix domain sockets
121.13 - - others, e.g. AF_DECNET are conceivable (see <socket.h>
121.14 -- socket type:
121.15 - - SOCK_STREAM (reliable stream, e.g. TCP)
121.16 - - SOCK_DGRAM (datagrams, e.g. UDP)
121.17 -
121.18 -For request-based servers (including socket-based):
121.19 -
121.20 -- client address verification before further looking at the request
121.21 - (This is actually a hook for any processing that needs to look
121.22 - at the request before anything else, e.g. logging)
121.23 -- how to handle multiple requests:
121.24 - - synchronous (one request is handled at a time)
121.25 - - forking (each request is handled by a new process)
121.26 - - threading (each request is handled by a new thread)
121.27 -
121.28 -The classes in this module favor the server type that is simplest to
121.29 -write: a synchronous TCP/IP server. This is bad class design, but
121.30 -save some typing. (There's also the issue that a deep class hierarchy
121.31 -slows down method lookups.)
121.32 -
121.33 -There are five classes in an inheritance diagram, four of which represent
121.34 -synchronous servers of four types:
121.35 -
121.36 - +------------+
121.37 - | BaseServer |
121.38 - +------------+
121.39 - |
121.40 - v
121.41 - +-----------+ +------------------+
121.42 - | TCPServer |------->| UnixStreamServer |
121.43 - +-----------+ +------------------+
121.44 - |
121.45 - v
121.46 - +-----------+ +--------------------+
121.47 - | UDPServer |------->| UnixDatagramServer |
121.48 - +-----------+ +--------------------+
121.49 -
121.50 -Note that UnixDatagramServer derives from UDPServer, not from
121.51 -UnixStreamServer -- the only difference between an IP and a Unix
121.52 -stream server is the address family, which is simply repeated in both
121.53 -unix server classes.
121.54 -
121.55 -Forking and threading versions of each type of server can be created
121.56 -using the ForkingMixIn and ThreadingMixIn mix-in classes. For
121.57 -instance, a threading UDP server class is created as follows:
121.58 -
121.59 - class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
121.60 -
121.61 -The Mix-in class must come first, since it overrides a method defined
121.62 -in UDPServer! Setting the various member variables also changes
121.63 -the behavior of the underlying server mechanism.
121.64 -
121.65 -To implement a service, you must derive a class from
121.66 -BaseRequestHandler and redefine its handle() method. You can then run
121.67 -various versions of the service by combining one of the server classes
121.68 -with your request handler class.
121.69 -
121.70 -The request handler class must be different for datagram or stream
121.71 -services. This can be hidden by using the request handler
121.72 -subclasses StreamRequestHandler or DatagramRequestHandler.
121.73 -
121.74 -Of course, you still have to use your head!
121.75 -
121.76 -For instance, it makes no sense to use a forking server if the service
121.77 -contains state in memory that can be modified by requests (since the
121.78 -modifications in the child process would never reach the initial state
121.79 -kept in the parent process and passed to each child). In this case,
121.80 -you can use a threading server, but you will probably have to use
121.81 -locks to avoid two requests that come in nearly simultaneous to apply
121.82 -conflicting changes to the server state.
121.83 -
121.84 -On the other hand, if you are building e.g. an HTTP server, where all
121.85 -data is stored externally (e.g. in the file system), a synchronous
121.86 -class will essentially render the service "deaf" while one request is
121.87 -being handled -- which may be for a very long time if a client is slow
121.88 -to reqd all the data it has requested. Here a threading or forking
121.89 -server is appropriate.
121.90 -
121.91 -In some cases, it may be appropriate to process part of a request
121.92 -synchronously, but to finish processing in a forked child depending on
121.93 -the request data. This can be implemented by using a synchronous
121.94 -server and doing an explicit fork in the request handler class
121.95 -handle() method.
121.96 -
121.97 -Another approach to handling multiple simultaneous requests in an
121.98 -environment that supports neither threads nor fork (or where these are
121.99 -too expensive or inappropriate for the service) is to maintain an
121.100 -explicit table of partially finished requests and to use select() to
121.101 -decide which request to work on next (or whether to handle a new
121.102 -incoming request). This is particularly important for stream services
121.103 -where each client can potentially be connected for a long time (if
121.104 -threads or subprocesses cannot be used).
121.105 -
121.106 -Future work:
121.107 -- Standard classes for Sun RPC (which uses either UDP or TCP)
121.108 -- Standard mix-in classes to implement various authentication
121.109 - and encryption schemes
121.110 -- Standard framework for select-based multiplexing
121.111 -
121.112 -XXX Open problems:
121.113 -- What to do with out-of-band data?
121.114 -
121.115 -BaseServer:
121.116 -- split generic "request" functionality out into BaseServer class.
121.117 - Copyright (C) 2000 Luke Kenneth Casson Leighton <lkcl@samba.org>
121.118 -
121.119 - example: read entries from a SQL database (requires overriding
121.120 - get_request() to return a table entry from the database).
121.121 - entry is processed by a RequestHandlerClass.
121.122 -
121.123 -"""
121.124 -
121.125 -# Author of the BaseServer patch: Luke Kenneth Casson Leighton
121.126 -
121.127 -# XXX Warning!
121.128 -# There is a test suite for this module, but it cannot be run by the
121.129 -# standard regression test.
121.130 -# To run it manually, run Lib/test/test_socketserver.py.
121.131 -
121.132 -__version__ = "0.4"
121.133 -
121.134 -
121.135 -import socket
121.136 -import sys
121.137 -import os
121.138 -
121.139 -__all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer",
121.140 - "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler",
121.141 - "StreamRequestHandler","DatagramRequestHandler",
121.142 - "ThreadingMixIn", "ForkingMixIn"]
121.143 -if hasattr(socket, "AF_UNIX"):
121.144 - __all__.extend(["UnixStreamServer","UnixDatagramServer",
121.145 - "ThreadingUnixStreamServer",
121.146 - "ThreadingUnixDatagramServer"])
121.147 -
121.148 -class BaseServer:
121.149 -
121.150 - """Base class for server classes.
121.151 -
121.152 - Methods for the caller:
121.153 -
121.154 - - __init__(server_address, RequestHandlerClass)
121.155 - - serve_forever()
121.156 - - handle_request() # if you do not use serve_forever()
121.157 - - fileno() -> int # for select()
121.158 -
121.159 - Methods that may be overridden:
121.160 -
121.161 - - server_bind()
121.162 - - server_activate()
121.163 - - get_request() -> request, client_address
121.164 - - verify_request(request, client_address)
121.165 - - server_close()
121.166 - - process_request(request, client_address)
121.167 - - close_request(request)
121.168 - - handle_error()
121.169 -
121.170 - Methods for derived classes:
121.171 -
121.172 - - finish_request(request, client_address)
121.173 -
121.174 - Class variables that may be overridden by derived classes or
121.175 - instances:
121.176 -
121.177 - - address_family
121.178 - - socket_type
121.179 - - allow_reuse_address
121.180 -
121.181 - Instance variables:
121.182 -
121.183 - - RequestHandlerClass
121.184 - - socket
121.185 -
121.186 - """
121.187 -
121.188 - def __init__(self, server_address, RequestHandlerClass):
121.189 - """Constructor. May be extended, do not override."""
121.190 - self.server_address = server_address
121.191 - self.RequestHandlerClass = RequestHandlerClass
121.192 -
121.193 - def server_activate(self):
121.194 - """Called by constructor to activate the server.
121.195 -
121.196 - May be overridden.
121.197 -
121.198 - """
121.199 - pass
121.200 -
121.201 - def serve_forever(self):
121.202 - """Handle one request at a time until doomsday."""
121.203 - while 1:
121.204 - self.handle_request()
121.205 -
121.206 - # The distinction between handling, getting, processing and
121.207 - # finishing a request is fairly arbitrary. Remember:
121.208 - #
121.209 - # - handle_request() is the top-level call. It calls
121.210 - # get_request(), verify_request() and process_request()
121.211 - # - get_request() is different for stream or datagram sockets
121.212 - # - process_request() is the place that may fork a new process
121.213 - # or create a new thread to finish the request
121.214 - # - finish_request() instantiates the request handler class;
121.215 - # this constructor will handle the request all by itself
121.216 -
121.217 - def handle_request(self):
121.218 - """Handle one request, possibly blocking."""
121.219 - try:
121.220 - request, client_address = self.get_request()
121.221 - except socket.error:
121.222 - return
121.223 - if self.verify_request(request, client_address):
121.224 - try:
121.225 - self.process_request(request, client_address)
121.226 - except:
121.227 - self.handle_error(request, client_address)
121.228 - self.close_request(request)
121.229 -
121.230 - def verify_request(self, request, client_address):
121.231 - """Verify the request. May be overridden.
121.232 -
121.233 - Return True if we should proceed with this request.
121.234 -
121.235 - """
121.236 - return True
121.237 -
121.238 - def process_request(self, request, client_address):
121.239 - """Call finish_request.
121.240 -
121.241 - Overridden by ForkingMixIn and ThreadingMixIn.
121.242 -
121.243 - """
121.244 - self.finish_request(request, client_address)
121.245 - self.close_request(request)
121.246 -
121.247 - def server_close(self):
121.248 - """Called to clean-up the server.
121.249 -
121.250 - May be overridden.
121.251 -
121.252 - """
121.253 - pass
121.254 -
121.255 - def finish_request(self, request, client_address):
121.256 - """Finish one request by instantiating RequestHandlerClass."""
121.257 - self.RequestHandlerClass(request, client_address, self)
121.258 -
121.259 - def close_request(self, request):
121.260 - """Called to clean up an individual request."""
121.261 - pass
121.262 -
121.263 - def handle_error(self, request, client_address):
121.264 - """Handle an error gracefully. May be overridden.
121.265 -
121.266 - The default is to print a traceback and continue.
121.267 -
121.268 - """
121.269 - print '-'*40
121.270 - print 'Exception happened during processing of request from',
121.271 - print client_address
121.272 - import traceback
121.273 - traceback.print_exc() # XXX But this goes to stderr!
121.274 - print '-'*40
121.275 -
121.276 -
121.277 -class TCPServer(BaseServer):
121.278 -
121.279 - """Base class for various socket-based server classes.
121.280 -
121.281 - Defaults to synchronous IP stream (i.e., TCP).
121.282 -
121.283 - Methods for the caller:
121.284 -
121.285 - - __init__(server_address, RequestHandlerClass)
121.286 - - serve_forever()
121.287 - - handle_request() # if you don't use serve_forever()
121.288 - - fileno() -> int # for select()
121.289 -
121.290 - Methods that may be overridden:
121.291 -
121.292 - - server_bind()
121.293 - - server_activate()
121.294 - - get_request() -> request, client_address
121.295 - - verify_request(request, client_address)
121.296 - - process_request(request, client_address)
121.297 - - close_request(request)
121.298 - - handle_error()
121.299 -
121.300 - Methods for derived classes:
121.301 -
121.302 - - finish_request(request, client_address)
121.303 -
121.304 - Class variables that may be overridden by derived classes or
121.305 - instances:
121.306 -
121.307 - - address_family
121.308 - - socket_type
121.309 - - request_queue_size (only for stream sockets)
121.310 - - allow_reuse_address
121.311 -
121.312 - Instance variables:
121.313 -
121.314 - - server_address
121.315 - - RequestHandlerClass
121.316 - - socket
121.317 -
121.318 - """
121.319 -
121.320 - address_family = socket.AF_INET
121.321 -
121.322 - socket_type = socket.SOCK_STREAM
121.323 -
121.324 - request_queue_size = 5
121.325 -
121.326 - allow_reuse_address = False
121.327 -
121.328 - def __init__(self, server_address, RequestHandlerClass):
121.329 - """Constructor. May be extended, do not override."""
121.330 - BaseServer.__init__(self, server_address, RequestHandlerClass)
121.331 - self.socket = socket.socket(self.address_family,
121.332 - self.socket_type)
121.333 - self.server_bind()
121.334 - self.server_activate()
121.335 -
121.336 - def server_bind(self):
121.337 - """Called by constructor to bind the socket.
121.338 -
121.339 - May be overridden.
121.340 -
121.341 - """
121.342 - if self.allow_reuse_address:
121.343 - self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
121.344 - self.socket.bind(self.server_address)
121.345 - self.server_address = self.socket.getsockname()
121.346 -
121.347 - def server_activate(self):
121.348 - """Called by constructor to activate the server.
121.349 -
121.350 - May be overridden.
121.351 -
121.352 - """
121.353 - self.socket.listen(self.request_queue_size)
121.354 -
121.355 - def server_close(self):
121.356 - """Called to clean-up the server.
121.357 -
121.358 - May be overridden.
121.359 -
121.360 - """
121.361 - self.socket.close()
121.362 -
121.363 - def fileno(self):
121.364 - """Return socket file number.
121.365 -
121.366 - Interface required by select().
121.367 -
121.368 - """
121.369 - return self.socket.fileno()
121.370 -
121.371 - def get_request(self):
121.372 - """Get the request and client address from the socket.
121.373 -
121.374 - May be overridden.
121.375 -
121.376 - """
121.377 - return self.socket.accept()
121.378 -
121.379 - def close_request(self, request):
121.380 - """Called to clean up an individual request."""
121.381 - request.close()
121.382 -
121.383 -
121.384 -class UDPServer(TCPServer):
121.385 -
121.386 - """UDP server class."""
121.387 -
121.388 - allow_reuse_address = False
121.389 -
121.390 - socket_type = socket.SOCK_DGRAM
121.391 -
121.392 - max_packet_size = 8192
121.393 -
121.394 - def get_request(self):
121.395 - data, client_addr = self.socket.recvfrom(self.max_packet_size)
121.396 - return (data, self.socket), client_addr
121.397 -
121.398 - def server_activate(self):
121.399 - # No need to call listen() for UDP.
121.400 - pass
121.401 -
121.402 - def close_request(self, request):
121.403 - # No need to close anything.
121.404 - pass
121.405 -
121.406 -class ForkingMixIn:
121.407 -
121.408 - """Mix-in class to handle each request in a new process."""
121.409 -
121.410 - active_children = None
121.411 - max_children = 40
121.412 -
121.413 - def collect_children(self):
121.414 - """Internal routine to wait for died children."""
121.415 - while self.active_children:
121.416 - if len(self.active_children) < self.max_children:
121.417 - options = os.WNOHANG
121.418 - else:
121.419 - # If the maximum number of children are already
121.420 - # running, block while waiting for a child to exit
121.421 - options = 0
121.422 - try:
121.423 - pid, status = os.waitpid(0, options)
121.424 - except os.error:
121.425 - pid = None
121.426 - if not pid: break
121.427 - self.active_children.remove(pid)
121.428 -
121.429 - def process_request(self, request, client_address):
121.430 - """Fork a new subprocess to process the request."""
121.431 - self.collect_children()
121.432 - pid = os.fork()
121.433 - if pid:
121.434 - # Parent process
121.435 - if self.active_children is None:
121.436 - self.active_children = []
121.437 - self.active_children.append(pid)
121.438 - self.close_request(request)
121.439 - return
121.440 - else:
121.441 - # Child process.
121.442 - # This must never return, hence os._exit()!
121.443 - try:
121.444 - self.finish_request(request, client_address)
121.445 - os._exit(0)
121.446 - except:
121.447 - try:
121.448 - self.handle_error(request, client_address)
121.449 - finally:
121.450 - os._exit(1)
121.451 -
121.452 -
121.453 -class ThreadingMixIn:
121.454 - """Mix-in class to handle each request in a new thread."""
121.455 -
121.456 - # Decides how threads will act upon termination of the
121.457 - # main process
121.458 - daemon_threads = False
121.459 -
121.460 - def process_request_thread(self, request, client_address):
121.461 - """Same as in BaseServer but as a thread.
121.462 -
121.463 - In addition, exception handling is done here.
121.464 -
121.465 - """
121.466 - try:
121.467 - self.finish_request(request, client_address)
121.468 - self.close_request(request)
121.469 - except:
121.470 - self.handle_error(request, client_address)
121.471 - self.close_request(request)
121.472 -
121.473 - def process_request(self, request, client_address):
121.474 - """Start a new thread to process the request."""
121.475 - import threading
121.476 - t = threading.Thread(target = self.process_request_thread,
121.477 - args = (request, client_address))
121.478 - if self.daemon_threads:
121.479 - t.setDaemon (1)
121.480 - t.start()
121.481 -
121.482 -
121.483 -class ForkingUDPServer(ForkingMixIn, UDPServer): pass
121.484 -class ForkingTCPServer(ForkingMixIn, TCPServer): pass
121.485 -
121.486 -class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
121.487 -class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
121.488 -
121.489 -if hasattr(socket, 'AF_UNIX'):
121.490 -
121.491 - class UnixStreamServer(TCPServer):
121.492 - address_family = socket.AF_UNIX
121.493 -
121.494 - class UnixDatagramServer(UDPServer):
121.495 - address_family = socket.AF_UNIX
121.496 -
121.497 - class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass
121.498 -
121.499 - class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass
121.500 -
121.501 -class BaseRequestHandler:
121.502 -
121.503 - """Base class for request handler classes.
121.504 -
121.505 - This class is instantiated for each request to be handled. The
121.506 - constructor sets the instance variables request, client_address
121.507 - and server, and then calls the handle() method. To implement a
121.508 - specific service, all you need to do is to derive a class which
121.509 - defines a handle() method.
121.510 -
121.511 - The handle() method can find the request as self.request, the
121.512 - client address as self.client_address, and the server (in case it
121.513 - needs access to per-server information) as self.server. Since a
121.514 - separate instance is created for each request, the handle() method
121.515 - can define arbitrary other instance variariables.
121.516 -
121.517 - """
121.518 -
121.519 - def __init__(self, request, client_address, server):
121.520 - self.request = request
121.521 - self.client_address = client_address
121.522 - self.server = server
121.523 - try:
121.524 - self.setup()
121.525 - self.handle()
121.526 - self.finish()
121.527 - finally:
121.528 - sys.exc_traceback = None # Help garbage collection
121.529 -
121.530 - def setup(self):
121.531 - pass
121.532 -
121.533 - def handle(self):
121.534 - pass
121.535 -
121.536 - def finish(self):
121.537 - pass
121.538 -
121.539 -
121.540 -# The following two classes make it possible to use the same service
121.541 -# class for stream or datagram servers.
121.542 -# Each class sets up these instance variables:
121.543 -# - rfile: a file object from which receives the request is read
121.544 -# - wfile: a file object to which the reply is written
121.545 -# When the handle() method returns, wfile is flushed properly
121.546 -
121.547 -
121.548 -class StreamRequestHandler(BaseRequestHandler):
121.549 -
121.550 - """Define self.rfile and self.wfile for stream sockets."""
121.551 -
121.552 - # Default buffer sizes for rfile, wfile.
121.553 - # We default rfile to buffered because otherwise it could be
121.554 - # really slow for large data (a getc() call per byte); we make
121.555 - # wfile unbuffered because (a) often after a write() we want to
121.556 - # read and we need to flush the line; (b) big writes to unbuffered
121.557 - # files are typically optimized by stdio even when big reads
121.558 - # aren't.
121.559 - rbufsize = -1
121.560 - wbufsize = 0
121.561 -
121.562 - def setup(self):
121.563 - self.connection = self.request
121.564 - self.rfile = self.connection.makefile('rb', self.rbufsize)
121.565 - self.wfile = self.connection.makefile('wb', self.wbufsize)
121.566 -
121.567 - def finish(self):
121.568 - if not self.wfile.closed:
121.569 - self.wfile.flush()
121.570 - self.wfile.close()
121.571 - self.rfile.close()
121.572 -
121.573 -
121.574 -class DatagramRequestHandler(BaseRequestHandler):
121.575 -
121.576 - # XXX Regrettably, I cannot get this working on Linux;
121.577 - # s.recvfrom() doesn't return a meaningful client address.
121.578 -
121.579 - """Define self.rfile and self.wfile for datagram sockets."""
121.580 -
121.581 - def setup(self):
121.582 - try:
121.583 - from cStringIO import StringIO
121.584 - except ImportError:
121.585 - from StringIO import StringIO
121.586 - self.packet, self.socket = self.request
121.587 - self.rfile = StringIO(self.packet)
121.588 - self.wfile = StringIO()
121.589 -
121.590 - def finish(self):
121.591 - self.socket.sendto(self.wfile.getvalue(), self.client_address)
122.1 --- a/python.editor/test/unit/data/testfiles/SocketServer.py.testDoc1.html Sun Jan 04 13:11:53 2015 -0600
122.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
122.3 @@ -1,57 +0,0 @@
122.4 -<html><body>
122.5 -<pre>Code completion result for source line:
122.6 -class TCPServer(BaseSer|ver):
122.7 -(QueryType=COMPLETION, NameKind=PREFIX)
122.8 -------------------------------------
122.9 -CLASS BaseServer [PRIVATE] SocketServer
122.10 -</pre><h2>Documentation:</h2><pre><b>BaseServer</b></pre>
122.11 -
122.12 -<hr>
122.13 -Base class for server classes.
122.14 -
122.15 -<br><br>
122.16 - Methods for the caller:
122.17 -
122.18 -<br><br>
122.19 - - __init__(server_address, RequestHandlerClass)
122.20 -<br> - serve_forever()
122.21 -<br> - handle_request() # if you do not use serve_forever()
122.22 -<br> - fileno() -> int # for select()
122.23 -
122.24 -<br><br>
122.25 - Methods that may be overridden:
122.26 -
122.27 -<br><br>
122.28 - - server_bind()
122.29 -<br> - server_activate()
122.30 -<br> - get_request() -> request, client_address
122.31 -<br> - verify_request(request, client_address)
122.32 -<br> - server_close()
122.33 -<br> - process_request(request, client_address)
122.34 -<br> - close_request(request)
122.35 -<br> - handle_error()
122.36 -
122.37 -<br><br>
122.38 - Methods for derived classes:
122.39 -
122.40 -<br><br>
122.41 - - finish_request(request, client_address)
122.42 -
122.43 -<br><br>
122.44 - Class variables that may be overridden by derived classes or
122.45 - instances:
122.46 -
122.47 -<br><br>
122.48 - - address_family
122.49 -<br> - socket_type
122.50 -<br> - allow_reuse_address
122.51 -
122.52 -<br><br>
122.53 - Instance variables:
122.54 -
122.55 -<br><br>
122.56 - - RequestHandlerClass
122.57 -<br> - socket
122.58 -
122.59 -<br><br>
122.60 -</body></html>
123.1 --- a/python.editor/test/unit/data/testfiles/SocketServer.py.testDoc2.html Sun Jan 04 13:11:53 2015 -0600
123.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
123.3 @@ -1,27 +0,0 @@
123.4 -<html><body>
123.5 -<pre>Code completion result for source line:
123.6 -class BaseRequestHandler|:
123.7 -(QueryType=COMPLETION, NameKind=PREFIX)
123.8 -------------------------------------
123.9 -CLASS BaseRequestHandler SocketServer
123.10 -</pre><h2>Documentation:</h2><pre><b>BaseRequestHandler</b></pre>
123.11 -
123.12 -<hr>
123.13 -Base class for request handler classes.
123.14 -
123.15 -<br><br>
123.16 - This class is instantiated for each request to be handled. The
123.17 - constructor sets the instance variables request, client_address
123.18 - and server, and then calls the handle() method. To implement a
123.19 - specific service, all you need to do is to derive a class which
123.20 - defines a handle() method.
123.21 -
123.22 -<br><br>
123.23 - The handle() method can find the request as self.request, the
123.24 - client address as self.client_address, and the server (in case it
123.25 - needs access to per-server information) as self.server. Since a
123.26 - separate instance is created for each request, the handle() method
123.27 - can define arbitrary other instance variariables.
123.28 -
123.29 -<br><br>
123.30 -</body></html>
124.1 --- a/python.editor/test/unit/data/testfiles/SocketServer.py.testDoc4.html Sun Jan 04 13:11:53 2015 -0600
124.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
124.3 @@ -1,10 +0,0 @@
124.4 -<html><body>
124.5 -<pre>Code completion result for source line:
124.6 -def serve_fore|ver(self):
124.7 -(QueryType=COMPLETION, NameKind=PREFIX)
124.8 -METHOD serve_forever() [PRIVATE] SocketServer
124.9 -</pre><h2>Documentation:</h2><pre><i>SocketServer</i><br><b>serve_forever</b>(<font color="#808080">self</font>)</pre>
124.10 -
124.11 -<hr>
124.12 -Handle one request at a time until doomsday.
124.13 -</body></html>
125.1 --- a/python.editor/test/unit/data/testfiles/all.py Sun Jan 04 13:11:53 2015 -0600
125.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
125.3 @@ -1,9 +0,0 @@
125.4 -__all__ = [ "MyPublikClass", "MyPublicClass" ]
125.5 -
125.6 -class MyPublicClass:
125.7 - def mymethod(self):
125.8 - pass
125.9 -
125.10 -class MyPrivateClass:
125.11 - def mymethod2(self):
125.12 - pass
126.1 --- a/python.editor/test/unit/data/testfiles/all.py.testAssign1.hints Sun Jan 04 13:11:53 2015 -0600
126.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
126.3 @@ -1,3 +0,0 @@
126.4 -__all__ = [ "MyPublikClass", "MyPublicClass" ]
126.5 - ---------------
126.6 -HINT:"MyPublikClass" defined in __all__ does not exist!
127.1 --- a/python.editor/test/unit/data/testfiles/all2.py Sun Jan 04 13:11:53 2015 -0600
127.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
127.3 @@ -1,13 +0,0 @@
127.4 -__all__ = [ "MyPublikClass", "MyPublicClass" ]
127.5 -__all__.extend(["makedirs", "removedirs", "renames"])
127.6 -__all__.append("three")
127.7 -
127.8 -class MyPublicClass:
127.9 - def mymethod(self):
127.10 - pass
127.11 -
127.12 -class MyPrivateClass:
127.13 - def mymethod2(self):
127.14 - pass
127.15 -
127.16 -
128.1 --- a/python.editor/test/unit/data/testfiles/all2.py.testAssign2.hints Sun Jan 04 13:11:53 2015 -0600
128.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
128.3 @@ -1,11 +0,0 @@
128.4 -__all__ = [ "MyPublikClass", "MyPublicClass" ]
128.5 - ---------------
128.6 -HINT:"MyPublikClass" defined in __all__ does not exist!
128.7 -__all__.extend(["makedirs", "removedirs", "renames"])
128.8 - ---------
128.9 -HINT:"makedirs" defined in __all__ does not exist!
128.10 -HINT:"removedirs" defined in __all__ does not exist!
128.11 -HINT:"renames" defined in __all__ does not exist!
128.12 -__all__.append("three")
128.13 - -------
128.14 -HINT:"three" defined in __all__ does not exist!
129.1 Binary file python.editor/test/unit/data/testfiles/antlr_python_runtime-3.1.1-py2.5.egg has changed
130.1 --- a/python.editor/test/unit/data/testfiles/antlr_python_runtime-3.1.1-py2.5.egg.indexed Sun Jan 04 13:11:53 2015 -0600
130.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
130.3 @@ -1,1728 +0,0 @@
130.4 -
130.5 -
130.6 -Document 0
130.7 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/__init__.py
130.8 -Searchable Keys:
130.9 - item : __version__;D;;
130.10 - item : runtime_version;D;;
130.11 - item : runtime_version_str;D;;
130.12 - item : version_str_to_tuple;F;;version_str;
130.13 - module : __init__
130.14 -
130.15 -Not Searchable Keys:
130.16 -
130.17 -
130.18 -Document 1
130.19 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/compat.py
130.20 -Searchable Keys:
130.21 - item : frozenset;I;;
130.22 - item : reversed;F;;l;
130.23 - item : set;I;;
130.24 - module : compat
130.25 -
130.26 -Not Searchable Keys:
130.27 -
130.28 -
130.29 -Document 2
130.30 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/constants.py
130.31 -Searchable Keys:
130.32 - item : DEFAULT_CHANNEL;D;;
130.33 - item : DOWN;D;;
130.34 - item : EOF;D;;
130.35 - item : EOR_TOKEN_TYPE;D;;
130.36 - item : HIDDEN_CHANNEL;D;;
130.37 - item : INVALID_TOKEN_TYPE;D;;
130.38 - item : MIN_TOKEN_TYPE;D;;
130.39 - item : UP;D;;
130.40 - module : constants
130.41 -
130.42 -Not Searchable Keys:
130.43 -
130.44 -
130.45 -Document 3
130.46 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/dfa.py
130.47 -Searchable Keys:
130.48 - class : DFA
130.49 - class-ig : dfa
130.50 - extends : object
130.51 - in : dfa
130.52 - member : __init__;c;|CONSTRUCTOR|;self,recognizer,decisionNumber,eot,eof,min,max,accept,special,transition;
130.53 - member : accept;D;;
130.54 - member : decisionNumber;D;;
130.55 - member : eof;D;;
130.56 - member : eot;D;;
130.57 - member : error;F;;self,nvae;
130.58 - member : getDescription;F;;self;
130.59 - member : max;D;;
130.60 - member : min;D;;
130.61 - member : noViableAlt;F;;self,s,input;
130.62 - member : predict;F;;self,input;
130.63 - member : recognizer;D;;
130.64 - member : special;D;;
130.65 - member : specialStateTransition;F;;self,s,input;
130.66 - member : transition;D;;
130.67 - member : unpack;F;;cls,string;
130.68 -
130.69 -Not Searchable Keys:
130.70 -
130.71 -
130.72 -Document 4
130.73 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/dfa.py
130.74 -Searchable Keys:
130.75 - item : BacktrackingFailed;I;;
130.76 - item : DFA;C;;
130.77 - item : EOF;I;;
130.78 - item : NoViableAltException;I;;
130.79 - module : dfa
130.80 -
130.81 -Not Searchable Keys:
130.82 -
130.83 -
130.84 -Document 5
130.85 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/dottreegen.py
130.86 -Searchable Keys:
130.87 - class : DOTTreeGenerator
130.88 - class-ig : dottreegenerator
130.89 - extends : object
130.90 - in : dottreegen
130.91 - member : __init__;c;|CONSTRUCTOR|;self;
130.92 - member : _edgeST;D;|PRIVATE|;
130.93 - member : _nodeST;D;|PRIVATE|;
130.94 - member : _treeST;D;|PRIVATE|;
130.95 - member : getNodeNumber;F;;self,t;
130.96 - member : getNodeST;F;;self,adaptor,t;
130.97 - member : nodeNumber;D;;
130.98 - member : nodeToNumberMap;D;;
130.99 - member : toDOT;F;;self,tree,adaptor,treeST,edgeST;
130.100 - member : toDOTDefineEdges;F;;self,tree,adaptor,treeST,edgeST;
130.101 - member : toDOTDefineNodes;F;;self,tree,adaptor,treeST,knownNodes;
130.102 -
130.103 -Not Searchable Keys:
130.104 -
130.105 -
130.106 -Document 6
130.107 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/dottreegen.py
130.108 -Searchable Keys:
130.109 - item : CommonTreeAdaptor;I;;
130.110 - item : DOTTreeGenerator;C;;
130.111 - item : stringtemplate3;I;;
130.112 - item : toDOT;F;;tree,adaptor,treeST,edgeST;
130.113 - module : dottreegen
130.114 -
130.115 -Not Searchable Keys:
130.116 -
130.117 -
130.118 -Document 7
130.119 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
130.120 -Searchable Keys:
130.121 - class : BacktrackingFailed
130.122 - class-ig : backtrackingfailed
130.123 - extends : Exception
130.124 - in : exceptions
130.125 -
130.126 -Not Searchable Keys:
130.127 -
130.128 -
130.129 -Document 8
130.130 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
130.131 -Searchable Keys:
130.132 - class : EarlyExitException
130.133 - class-ig : earlyexitexception
130.134 - extends : RecognitionException
130.135 - in : exceptions
130.136 - member : __init__;c;|CONSTRUCTOR|;self,decisionNumber,input;
130.137 - member : decisionNumber;D;;
130.138 -
130.139 -Not Searchable Keys:
130.140 -
130.141 -
130.142 -Document 9
130.143 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
130.144 -Searchable Keys:
130.145 - class : FailedPredicateException
130.146 - class-ig : failedpredicateexception
130.147 - extends : RecognitionException
130.148 - in : exceptions
130.149 - member : __init__;c;|CONSTRUCTOR|;self,input,ruleName,predicateText;
130.150 - member : __repr__;F;;self;
130.151 - member : __str__;F;;self;
130.152 - member : predicateText;D;;
130.153 - member : ruleName;D;;
130.154 -
130.155 -Not Searchable Keys:
130.156 -
130.157 -
130.158 -Document 10
130.159 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
130.160 -Searchable Keys:
130.161 - class : MismatchedNotSetException
130.162 - class-ig : mismatchednotsetexception
130.163 - extends : MismatchedSetException
130.164 - in : exceptions
130.165 - member : __repr__;F;;self;
130.166 - member : __str__;F;;self;
130.167 -
130.168 -Not Searchable Keys:
130.169 -
130.170 -
130.171 -Document 11
130.172 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
130.173 -Searchable Keys:
130.174 - class : MismatchedRangeException
130.175 - class-ig : mismatchedrangeexception
130.176 - extends : RecognitionException
130.177 - in : exceptions
130.178 - member : __init__;c;|CONSTRUCTOR|;self,a,b,input;
130.179 - member : __repr__;F;;self;
130.180 - member : __str__;F;;self;
130.181 - member : a;D;;
130.182 - member : b;D;;
130.183 -
130.184 -Not Searchable Keys:
130.185 -
130.186 -
130.187 -Document 12
130.188 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
130.189 -Searchable Keys:
130.190 - class : MismatchedSetException
130.191 - class-ig : mismatchedsetexception
130.192 - extends : RecognitionException
130.193 - in : exceptions
130.194 - member : __init__;c;|CONSTRUCTOR|;self,expecting,input;
130.195 - member : __repr__;F;;self;
130.196 - member : __str__;F;;self;
130.197 - member : expecting;D;;
130.198 -
130.199 -Not Searchable Keys:
130.200 -
130.201 -
130.202 -Document 13
130.203 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
130.204 -Searchable Keys:
130.205 - class : MismatchedTokenException
130.206 - class-ig : mismatchedtokenexception
130.207 - extends : RecognitionException
130.208 - in : exceptions
130.209 - member : __init__;c;|CONSTRUCTOR|;self,expecting,input;
130.210 - member : __repr__;F;;self;
130.211 - member : __str__;F;;self;
130.212 - member : expecting;D;;
130.213 -
130.214 -Not Searchable Keys:
130.215 -
130.216 -
130.217 -Document 14
130.218 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
130.219 -Searchable Keys:
130.220 - class : MismatchedTreeNodeException
130.221 - class-ig : mismatchedtreenodeexception
130.222 - extends : RecognitionException
130.223 - in : exceptions
130.224 - member : __init__;c;|CONSTRUCTOR|;self,expecting,input;
130.225 - member : __repr__;F;;self;
130.226 - member : __str__;F;;self;
130.227 - member : expecting;D;;
130.228 -
130.229 -Not Searchable Keys:
130.230 -
130.231 -
130.232 -Document 15
130.233 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
130.234 -Searchable Keys:
130.235 - class : MissingTokenException
130.236 - class-ig : missingtokenexception
130.237 - extends : MismatchedTokenException
130.238 - in : exceptions
130.239 - member : __init__;c;|CONSTRUCTOR|;self,expecting,input,inserted;
130.240 - member : __repr__;F;;self;
130.241 - member : __str__;F;;self;
130.242 - member : getMissingType;F;;self;
130.243 - member : inserted;D;;
130.244 -
130.245 -Not Searchable Keys:
130.246 -
130.247 -
130.248 -Document 16
130.249 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
130.250 -Searchable Keys:
130.251 - class : NoViableAltException
130.252 - class-ig : noviablealtexception
130.253 - extends : RecognitionException
130.254 - in : exceptions
130.255 - member : __init__;c;|CONSTRUCTOR|;self,grammarDecisionDescription,decisionNumber,stateNumber,input;
130.256 - member : __repr__;F;;self;
130.257 - member : __str__;F;;self;
130.258 - member : decisionNumber;D;;
130.259 - member : grammarDecisionDescription;D;;
130.260 - member : stateNumber;D;;
130.261 -
130.262 -Not Searchable Keys:
130.263 -
130.264 -
130.265 -Document 17
130.266 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
130.267 -Searchable Keys:
130.268 - class : RecognitionException
130.269 - class-ig : recognitionexception
130.270 - extends : Exception
130.271 - in : exceptions
130.272 - member : __init__;c;|CONSTRUCTOR|;self,input;
130.273 - member : approximateLineInfo;D;;
130.274 - member : c;D;;
130.275 - member : charPositionInLine;D;;
130.276 - member : extractInformationFromTreeNodeStream;F;;self,nodes;
130.277 - member : getUnexpectedType;F;;self;
130.278 - member : index;D;;
130.279 - member : input;D;;
130.280 - member : line;D;;
130.281 - member : node;D;;
130.282 - member : token;D;;
130.283 - member : unexpectedType;D;;
130.284 -
130.285 -Not Searchable Keys:
130.286 -
130.287 -
130.288 -Document 18
130.289 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
130.290 -Searchable Keys:
130.291 - class : UnwantedTokenException
130.292 - class-ig : unwantedtokenexception
130.293 - extends : MismatchedTokenException
130.294 - in : exceptions
130.295 - member : __repr__;F;;self;
130.296 - member : __str__;F;;self;
130.297 - member : getUnexpectedToken;F;;self;
130.298 -
130.299 -Not Searchable Keys:
130.300 -
130.301 -
130.302 -Document 19
130.303 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/exceptions.py
130.304 -Searchable Keys:
130.305 - item : BacktrackingFailed;C;;
130.306 - item : EarlyExitException;C;;
130.307 - item : FailedPredicateException;C;;
130.308 - item : INVALID_TOKEN_TYPE;I;;
130.309 - item : MismatchedNotSetException;C;;
130.310 - item : MismatchedRangeException;C;;
130.311 - item : MismatchedSetException;C;;
130.312 - item : MismatchedTokenException;C;;
130.313 - item : MismatchedTreeNodeException;C;;
130.314 - item : MissingTokenException;C;;
130.315 - item : NoViableAltException;C;;
130.316 - item : RecognitionException;C;;
130.317 - item : UnwantedTokenException;C;;
130.318 - module : exceptions
130.319 -
130.320 -Not Searchable Keys:
130.321 -
130.322 -
130.323 -Document 20
130.324 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/extras.py
130.325 -Searchable Keys:
130.326 - item : TreeWizard;I;;
130.327 - item : exc;D;;
130.328 - item : toDOT;F;;args,kwargs;
130.329 - module : extras
130.330 -
130.331 -Not Searchable Keys:
130.332 -
130.333 -
130.334 -Document 21
130.335 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/main.py
130.336 -Searchable Keys:
130.337 - class : LexerMain
130.338 - class-ig : lexermain
130.339 - extends : _Main
130.340 - in : main
130.341 - member : __init__;c;|CONSTRUCTOR|;self,lexerClass;
130.342 - member : lexerClass;D;;
130.343 - member : parseStream;F;;self,options,inStream;
130.344 -
130.345 -Not Searchable Keys:
130.346 -
130.347 -
130.348 -Document 22
130.349 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/main.py
130.350 -Searchable Keys:
130.351 - class : ParserMain
130.352 - class-ig : parsermain
130.353 - extends : _Main
130.354 - in : main
130.355 - member : __init__;c;|CONSTRUCTOR|;self,lexerClassName,parserClass;
130.356 - member : lexerClass;D;;
130.357 - member : lexerClassName;D;;
130.358 - member : parseStream;F;;self,options,inStream;
130.359 - member : parserClass;D;;
130.360 - member : setUp;F;;self,options;
130.361 - member : setupOptions;F;;self,optParser;
130.362 -
130.363 -Not Searchable Keys:
130.364 -
130.365 -
130.366 -Document 23
130.367 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/main.py
130.368 -Searchable Keys:
130.369 - class : WalkerMain
130.370 - class-ig : walkermain
130.371 - extends : _Main
130.372 - in : main
130.373 - member : __init__;c;|CONSTRUCTOR|;self,walkerClass;
130.374 - member : lexerClass;D;;
130.375 - member : parseStream;F;;self,options,inStream;
130.376 - member : parserClass;D;;
130.377 - member : setUp;F;;self,options;
130.378 - member : setupOptions;F;;self,optParser;
130.379 - member : walkerClass;D;;
130.380 -
130.381 -Not Searchable Keys:
130.382 -
130.383 -
130.384 -Document 24
130.385 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/main.py
130.386 -Searchable Keys:
130.387 - class : _Main
130.388 - class-ig : _main
130.389 - extends : object
130.390 - in : main
130.391 - member : __init__;c;|CONSTRUCTOR|;self;
130.392 - member : execute;F;;self,argv;
130.393 - member : parseOptions;F;;self,argv;
130.394 - member : parseStream;F;;self,options,inStream;
130.395 - member : setUp;F;;self,options;
130.396 - member : setupOptions;F;;self,optParser;
130.397 - member : stderr;D;;
130.398 - member : stdin;D;;
130.399 - member : stdout;D;;
130.400 - member : write;F;;self,options,text;
130.401 - member : writeln;F;;self,options,text;
130.402 -
130.403 -Not Searchable Keys:
130.404 - clzattrs : ;|PRIVATE|;
130.405 -
130.406 -
130.407 -Document 25
130.408 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/main.py
130.409 -Searchable Keys:
130.410 - item : LexerMain;C;;
130.411 - item : ParserMain;C;;
130.412 - item : WalkerMain;C;;
130.413 - item : _Main;C;|PRIVATE|;
130.414 - item : antlr3;I;;
130.415 - item : optparse;I;;
130.416 - item : sys;I;;
130.417 - module : main
130.418 -
130.419 -Not Searchable Keys:
130.420 -
130.421 -
130.422 -Document 26
130.423 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/recognizers.py
130.424 -Searchable Keys:
130.425 - class : BaseRecognizer
130.426 - class-ig : baserecognizer
130.427 - extends : object
130.428 - in : recognizers
130.429 - member : DEFAULT_TOKEN_CHANNEL;D;;
130.430 - member : HIDDEN;D;;
130.431 - member : MEMO_RULE_FAILED;D;;
130.432 - member : MEMO_RULE_UNKNOWN;D;;
130.433 - member : __init__;c;|CONSTRUCTOR|;self,state;
130.434 - member : _getRuleInvocationStack;F;|PRIVATE|;cls,module;
130.435 - member : _state;D;|PRIVATE|;
130.436 - member : alreadyParsedRule;F;;self,input,ruleIndex;
130.437 - member : antlr_version;D;;
130.438 - member : antlr_version_str;D;;
130.439 - member : beginResync;F;;self;
130.440 - member : combineFollows;F;;self,exact;
130.441 - member : computeContextSensitiveRuleFOLLOW;F;;self;
130.442 - member : computeErrorRecoverySet;F;;self;
130.443 - member : consumeUntil;F;;self,input,tokenTypes;
130.444 - member : displayRecognitionError;F;;self,tokenNames,e;
130.445 - member : emitErrorMessage;F;;self,msg;
130.446 - member : endResync;F;;self;
130.447 - member : getBacktrackingLevel;F;;self;
130.448 - member : getCurrentInputSymbol;F;;self,input;
130.449 - member : getErrorHeader;F;;self,e;
130.450 - member : getErrorMessage;F;;self,e,tokenNames;
130.451 - member : getGrammarFileName;F;;self;
130.452 - member : getMissingSymbol;F;;self,input,e,expectedTokenType,follow;
130.453 - member : getNumberOfSyntaxErrors;F;;self;
130.454 - member : getRuleInvocationStack;F;;self;
130.455 - member : getRuleMemoization;F;;self,ruleIndex,ruleStartIndex;
130.456 - member : getSourceName;F;;self;
130.457 - member : getTokenErrorDisplay;F;;self,t;
130.458 - member : input;D;;
130.459 - member : match;F;;self,input,ttype,follow;
130.460 - member : matchAny;F;;self,input;
130.461 - member : memoize;F;;self,input,ruleIndex,ruleStartIndex,success;
130.462 - member : mismatch;F;;self,input,ttype,follow;
130.463 - member : mismatchIsMissingToken;F;;self,input,follow;
130.464 - member : mismatchIsUnwantedToken;F;;self,input,ttype;
130.465 - member : recover;F;;self,input,re;
130.466 - member : recoverFromMismatchedSet;F;;self,input,e,follow;
130.467 - member : recoverFromMismatchedToken;F;;self,input,ttype,follow;
130.468 - member : reportError;F;;self,e;
130.469 - member : reset;F;;self;
130.470 - member : setInput;F;;self,input;
130.471 - member : toStrings;F;;self,tokens;
130.472 - member : tokenNames;D;;
130.473 - member : traceIn;F;;self,ruleName,ruleIndex,inputSymbol;
130.474 - member : traceOut;F;;self,ruleName,ruleIndex,inputSymbol;
130.475 -
130.476 -Not Searchable Keys:
130.477 -
130.478 -
130.479 -Document 27
130.480 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/recognizers.py
130.481 -Searchable Keys:
130.482 - class : Lexer
130.483 - class-ig : lexer
130.484 - extends : BaseRecognizer
130.485 - extends : TokenSource
130.486 - in : recognizers
130.487 - member : __init__;c;|CONSTRUCTOR|;self,input,state;
130.488 - member : emit;F;;self,token;
130.489 - member : getCharErrorDisplay;F;;self,c;
130.490 - member : getCharIndex;F;;self;
130.491 - member : getCharPositionInLine;F;;self;
130.492 - member : getErrorMessage;F;;self,e,tokenNames;
130.493 - member : getLine;F;;self;
130.494 - member : getSourceName;F;;self;
130.495 - member : getText;F;;self;
130.496 - member : input;D;;
130.497 - member : mTokens;F;;self;
130.498 - member : match;F;;self,s;
130.499 - member : matchAny;F;;self;
130.500 - member : matchRange;F;;self,a,b;
130.501 - member : nextToken;F;;self;
130.502 - member : recover;F;;self,re;
130.503 - member : reportError;F;;self,e;
130.504 - member : reset;F;;self;
130.505 - member : setCharStream;F;;self,input;
130.506 - member : setText;F;;self,text;
130.507 - member : skip;F;;self;
130.508 - member : text;D;;
130.509 - member : traceIn;F;;self,ruleName,ruleIndex;
130.510 - member : traceOut;F;;self,ruleName,ruleIndex;
130.511 -
130.512 -Not Searchable Keys:
130.513 -
130.514 -
130.515 -Document 28
130.516 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/recognizers.py
130.517 -Searchable Keys:
130.518 - class : Parser
130.519 - class-ig : parser
130.520 - extends : BaseRecognizer
130.521 - in : recognizers
130.522 - member : __init__;c;|CONSTRUCTOR|;self,lexer,state;
130.523 - member : getCurrentInputSymbol;F;;self,input;
130.524 - member : getMissingSymbol;F;;self,input,e,expectedTokenType,follow;
130.525 - member : getSourceName;F;;self;
130.526 - member : getTokenStream;F;;self;
130.527 - member : input;D;;
130.528 - member : reset;F;;self;
130.529 - member : setTokenStream;F;;self,input;
130.530 - member : traceIn;F;;self,ruleName,ruleIndex;
130.531 - member : traceOut;F;;self,ruleName,ruleIndex;
130.532 -
130.533 -Not Searchable Keys:
130.534 -
130.535 -
130.536 -Document 29
130.537 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/recognizers.py
130.538 -Searchable Keys:
130.539 - class : ParserRuleReturnScope
130.540 - class-ig : parserrulereturnscope
130.541 - extends : RuleReturnScope
130.542 - in : recognizers
130.543 - member : __init__;c;|CONSTRUCTOR|;self;
130.544 - member : getStart;F;;self;
130.545 - member : getStop;F;;self;
130.546 - member : start;D;;
130.547 - member : stop;D;;
130.548 -
130.549 -Not Searchable Keys:
130.550 -
130.551 -
130.552 -Document 30
130.553 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/recognizers.py
130.554 -Searchable Keys:
130.555 - class : RecognizerSharedState
130.556 - class-ig : recognizersharedstate
130.557 - extends : object
130.558 - in : recognizers
130.559 - member : __init__;c;|CONSTRUCTOR|;self;
130.560 - member : backtracking;D;;
130.561 - member : channel;D;;
130.562 - member : errorRecovery;D;;
130.563 - member : following;D;;
130.564 - member : lastErrorIndex;D;;
130.565 - member : ruleMemo;D;;
130.566 - member : syntaxErrors;D;;
130.567 - member : text;D;;
130.568 - member : token;D;;
130.569 - member : tokenStartCharIndex;D;;
130.570 - member : tokenStartCharPositionInLine;D;;
130.571 - member : tokenStartLine;D;;
130.572 - member : type;D;;
130.573 -
130.574 -Not Searchable Keys:
130.575 -
130.576 -
130.577 -Document 31
130.578 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/recognizers.py
130.579 -Searchable Keys:
130.580 - class : RuleReturnScope
130.581 - class-ig : rulereturnscope
130.582 - extends : object
130.583 - in : recognizers
130.584 - member : getStart;F;;self;
130.585 - member : getStop;F;;self;
130.586 - member : getTemplate;F;;self;
130.587 - member : getTree;F;;self;
130.588 -
130.589 -Not Searchable Keys:
130.590 -
130.591 -
130.592 -Document 32
130.593 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/recognizers.py
130.594 -Searchable Keys:
130.595 - class : TokenSource
130.596 - class-ig : tokensource
130.597 - extends : object
130.598 - in : recognizers
130.599 - member : __iter__;F;;self;
130.600 - member : next;F;;self;
130.601 - member : nextToken;F;;self;
130.602 -
130.603 -Not Searchable Keys:
130.604 -
130.605 -
130.606 -Document 33
130.607 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/recognizers.py
130.608 -Searchable Keys:
130.609 - item : BacktrackingFailed;I;;
130.610 - item : BaseRecognizer;C;;
130.611 - item : CommonToken;I;;
130.612 - item : DEFAULT_CHANNEL;I;;
130.613 - item : EOF;I;;
130.614 - item : EOF_TOKEN;I;;
130.615 - item : EOR_TOKEN_TYPE;I;;
130.616 - item : EarlyExitException;I;;
130.617 - item : FailedPredicateException;I;;
130.618 - item : HIDDEN_CHANNEL;I;;
130.619 - item : INVALID_TOKEN_TYPE;I;;
130.620 - item : Lexer;C;;
130.621 - item : MismatchedNotSetException;I;;
130.622 - item : MismatchedRangeException;I;;
130.623 - item : MismatchedSetException;I;;
130.624 - item : MismatchedTokenException;I;;
130.625 - item : MismatchedTreeNodeException;I;;
130.626 - item : MissingTokenException;I;;
130.627 - item : NoViableAltException;I;;
130.628 - item : Parser;C;;
130.629 - item : ParserRuleReturnScope;C;;
130.630 - item : RecognitionException;I;;
130.631 - item : RecognizerSharedState;C;;
130.632 - item : RuleReturnScope;C;;
130.633 - item : SKIP_TOKEN;I;;
130.634 - item : TokenSource;C;;
130.635 - item : UnwantedTokenException;I;;
130.636 - item : frozenset;I;;
130.637 - item : inspect;I;;
130.638 - item : reversed;I;;
130.639 - item : runtime_version;I;;
130.640 - item : runtime_version_str;I;;
130.641 - item : set;I;;
130.642 - item : sys;I;;
130.643 - module : recognizers
130.644 -
130.645 -Not Searchable Keys:
130.646 -
130.647 -
130.648 -Document 34
130.649 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
130.650 -Searchable Keys:
130.651 - class : ANTLRFileStream
130.652 - class-ig : antlrfilestream
130.653 - extends : ANTLRStringStream
130.654 - in : streams
130.655 - member : __init__;c;|CONSTRUCTOR|;self,fileName,encoding;
130.656 - member : fileName;D;;
130.657 - member : getSourceName;F;;self;
130.658 -
130.659 -Not Searchable Keys:
130.660 -
130.661 -
130.662 -Document 35
130.663 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
130.664 -Searchable Keys:
130.665 - class : ANTLRInputStream
130.666 - class-ig : antlrinputstream
130.667 - extends : ANTLRStringStream
130.668 - in : streams
130.669 - member : __init__;c;|CONSTRUCTOR|;self,file,encoding;
130.670 -
130.671 -Not Searchable Keys:
130.672 -
130.673 -
130.674 -Document 36
130.675 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
130.676 -Searchable Keys:
130.677 - class : ANTLRStringStream
130.678 - class-ig : antlrstringstream
130.679 - extends : CharStream
130.680 - in : streams
130.681 - member : LA;F;;self,i;
130.682 - member : LT;F;;self,i;
130.683 - member : __init__;c;|CONSTRUCTOR|;self,data;
130.684 - member : _markers;D;|PRIVATE|;
130.685 - member : charPositionInLine;D;;
130.686 - member : consume;F;;self;
130.687 - member : data;D;;
130.688 - member : getCharPositionInLine;F;;self;
130.689 - member : getLine;F;;self;
130.690 - member : getSourceName;F;;self;
130.691 - member : index;F;;self;
130.692 - member : lastMarker;D;;
130.693 - member : line;D;;
130.694 - member : mark;F;;self;
130.695 - member : markDepth;D;;
130.696 - member : n;D;;
130.697 - member : name;D;;
130.698 - member : p;D;;
130.699 - member : release;F;;self,marker;
130.700 - member : reset;F;;self;
130.701 - member : rewind;F;;self,marker;
130.702 - member : seek;F;;self,index;
130.703 - member : setCharPositionInLine;F;;self,pos;
130.704 - member : setLine;F;;self,line;
130.705 - member : size;F;;self;
130.706 - member : strdata;D;;
130.707 - member : substring;F;;self,start,stop;
130.708 -
130.709 -Not Searchable Keys:
130.710 -
130.711 -
130.712 -Document 37
130.713 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
130.714 -Searchable Keys:
130.715 - class : CharStream
130.716 - class-ig : charstream
130.717 - extends : IntStream
130.718 - in : streams
130.719 - member : EOF;D;;
130.720 - member : LT;F;;self,i;
130.721 - member : getCharPositionInLine;F;;self;
130.722 - member : getLine;F;;self;
130.723 - member : setCharPositionInLine;F;;self,pos;
130.724 - member : setLine;F;;self,line;
130.725 - member : substring;F;;self,start,stop;
130.726 -
130.727 -Not Searchable Keys:
130.728 -
130.729 -
130.730 -Document 38
130.731 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
130.732 -Searchable Keys:
130.733 - class : CommonTokenStream
130.734 - class-ig : commontokenstream
130.735 - extends : TokenStream
130.736 - in : streams
130.737 - member : LA;F;;self,i;
130.738 - member : LB;F;;self,k;
130.739 - member : LT;F;;self,k;
130.740 - member : __init__;c;|CONSTRUCTOR|;self,tokenSource,channel;
130.741 - member : channel;D;;
130.742 - member : channelOverrideMap;D;;
130.743 - member : consume;F;;self;
130.744 - member : discardOffChannelTokens;D;;
130.745 - member : discardSet;D;;
130.746 - member : discardTokenType;F;;self,ttype;
130.747 - member : fillBuffer;F;;self;
130.748 - member : get;F;;self,i;
130.749 - member : getSourceName;F;;self;
130.750 - member : getTokenSource;F;;self;
130.751 - member : getTokens;F;;self,start,stop,types;
130.752 - member : index;F;;self;
130.753 - member : lastMarker;D;;
130.754 - member : mark;F;;self;
130.755 - member : p;D;;
130.756 - member : release;F;;self,marker;
130.757 - member : reset;F;;self;
130.758 - member : rewind;F;;self,marker;
130.759 - member : seek;F;;self,index;
130.760 - member : setTokenSource;F;;self,tokenSource;
130.761 - member : setTokenTypeChannel;F;;self,ttype,channel;
130.762 - member : size;F;;self;
130.763 - member : skipOffTokenChannels;F;;self,i;
130.764 - member : skipOffTokenChannelsReverse;F;;self,i;
130.765 - member : toString;F;;self,start,stop;
130.766 - member : tokenSource;D;;
130.767 - member : tokens;D;;
130.768 -
130.769 -Not Searchable Keys:
130.770 -
130.771 -
130.772 -Document 39
130.773 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
130.774 -Searchable Keys:
130.775 - class : DeleteOp
130.776 - class-ig : deleteop
130.777 - extends : ReplaceOp
130.778 - in : streams
130.779 - member : __init__;c;|CONSTRUCTOR|;self,stream,first,last;
130.780 - member : __repr__;F;;self;
130.781 - member : __str__;F;;self;
130.782 - member : toString;F;;self;
130.783 -
130.784 -Not Searchable Keys:
130.785 -
130.786 -
130.787 -Document 40
130.788 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
130.789 -Searchable Keys:
130.790 - class : FileStream
130.791 - class-ig : filestream
130.792 - extends : ANTLRStringStream
130.793 - in : streams
130.794 - member : __init__;c;|CONSTRUCTOR|;self,fileName,encoding;
130.795 - member : fileName;D;;
130.796 - member : getSourceName;F;;self;
130.797 -
130.798 -Not Searchable Keys:
130.799 -
130.800 -
130.801 -Document 41
130.802 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
130.803 -Searchable Keys:
130.804 - class : InputStream
130.805 - class-ig : inputstream
130.806 - extends : ANTLRStringStream
130.807 - in : streams
130.808 - member : __init__;c;|CONSTRUCTOR|;self,file,encoding;
130.809 -
130.810 -Not Searchable Keys:
130.811 -
130.812 -
130.813 -Document 42
130.814 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
130.815 -Searchable Keys:
130.816 - class : InsertBeforeOp
130.817 - class-ig : insertbeforeop
130.818 - extends : RewriteOperation
130.819 - in : streams
130.820 - member : execute;F;;self,buf;
130.821 -
130.822 -Not Searchable Keys:
130.823 -
130.824 -
130.825 -Document 43
130.826 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
130.827 -Searchable Keys:
130.828 - class : IntStream
130.829 - class-ig : intstream
130.830 - extends : object
130.831 - in : streams
130.832 - member : LA;F;;self,i;
130.833 - member : consume;F;;self;
130.834 - member : getSourceName;F;;self;
130.835 - member : index;F;;self;
130.836 - member : mark;F;;self;
130.837 - member : release;F;;self,marker;
130.838 - member : rewind;F;;self,marker;
130.839 - member : seek;F;;self,index;
130.840 - member : size;F;;self;
130.841 -
130.842 -Not Searchable Keys:
130.843 -
130.844 -
130.845 -Document 44
130.846 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
130.847 -Searchable Keys:
130.848 - class : ReplaceOp
130.849 - class-ig : replaceop
130.850 - extends : RewriteOperation
130.851 - in : streams
130.852 - member : __init__;c;|CONSTRUCTOR|;self,stream,first,last,text;
130.853 - member : __repr__;F;;self;
130.854 - member : __str__;F;;self;
130.855 - member : execute;F;;self,buf;
130.856 - member : lastIndex;D;;
130.857 - member : toString;F;;self;
130.858 -
130.859 -Not Searchable Keys:
130.860 -
130.861 -
130.862 -Document 45
130.863 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
130.864 -Searchable Keys:
130.865 - class : RewriteOperation
130.866 - class-ig : rewriteoperation
130.867 - extends : object
130.868 - in : streams
130.869 - member : __init__;c;|CONSTRUCTOR|;self,stream,index,text;
130.870 - member : __repr__;F;;self;
130.871 - member : __str__;F;;self;
130.872 - member : execute;F;;self,buf;
130.873 - member : index;D;;
130.874 - member : stream;D;;
130.875 - member : text;D;;
130.876 - member : toString;F;;self;
130.877 -
130.878 -Not Searchable Keys:
130.879 -
130.880 -
130.881 -Document 46
130.882 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
130.883 -Searchable Keys:
130.884 - class : StringStream
130.885 - class-ig : stringstream
130.886 - extends : CharStream
130.887 - in : streams
130.888 - member : LA;F;;self,i;
130.889 - member : LT;F;;self,i;
130.890 - member : __init__;c;|CONSTRUCTOR|;self,data;
130.891 - member : _markers;D;|PRIVATE|;
130.892 - member : charPositionInLine;D;;
130.893 - member : consume;F;;self;
130.894 - member : data;D;;
130.895 - member : getCharPositionInLine;F;;self;
130.896 - member : getLine;F;;self;
130.897 - member : getSourceName;F;;self;
130.898 - member : index;F;;self;
130.899 - member : lastMarker;D;;
130.900 - member : line;D;;
130.901 - member : mark;F;;self;
130.902 - member : markDepth;D;;
130.903 - member : n;D;;
130.904 - member : name;D;;
130.905 - member : p;D;;
130.906 - member : release;F;;self,marker;
130.907 - member : reset;F;;self;
130.908 - member : rewind;F;;self,marker;
130.909 - member : seek;F;;self,index;
130.910 - member : setCharPositionInLine;F;;self,pos;
130.911 - member : setLine;F;;self,line;
130.912 - member : size;F;;self;
130.913 - member : strdata;D;;
130.914 - member : substring;F;;self,start,stop;
130.915 -
130.916 -Not Searchable Keys:
130.917 -
130.918 -
130.919 -Document 47
130.920 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
130.921 -Searchable Keys:
130.922 - class : TokenRewriteStream
130.923 - class-ig : tokenrewritestream
130.924 - extends : CommonTokenStream
130.925 - in : streams
130.926 - member : DEFAULT_PROGRAM_NAME;D;;
130.927 - member : MIN_TOKEN_INDEX;D;;
130.928 - member : __init__;c;|CONSTRUCTOR|;self,tokenSource,channel;
130.929 - member : __str__;F;;self,args;
130.930 - member : catOpText;F;;self,a,b;
130.931 - member : delete;F;;self,args;
130.932 - member : deleteProgram;F;;self,programName;
130.933 - member : getKindOfOps;F;;self,rewrites,kind,before;
130.934 - member : getLastRewriteTokenIndex;F;;self,programName;
130.935 - member : getProgram;F;;self,name;
130.936 - member : initializeProgram;F;;self,name;
130.937 - member : insertAfter;F;;self,args;
130.938 - member : insertBefore;F;;self,args;
130.939 - member : lastRewriteTokenIndexes;D;;
130.940 - member : programs;D;;
130.941 - member : reduceToSingleOperationPerIndex;F;;self,rewrites;
130.942 - member : replace;F;;self,args;
130.943 - member : rollback;F;;self,args;
130.944 - member : setLastRewriteTokenIndex;F;;self,programName,i;
130.945 - member : toDebugString;F;;self,start,end;
130.946 - member : toOriginalString;F;;self,start,end;
130.947 - member : toString;F;;self,args;
130.948 -
130.949 -Not Searchable Keys:
130.950 -
130.951 -
130.952 -Document 48
130.953 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
130.954 -Searchable Keys:
130.955 - class : TokenStream
130.956 - class-ig : tokenstream
130.957 - extends : IntStream
130.958 - in : streams
130.959 - member : LT;F;;self,k;
130.960 - member : get;F;;self,i;
130.961 - member : getTokenSource;F;;self;
130.962 - member : toString;F;;self,start,stop;
130.963 -
130.964 -Not Searchable Keys:
130.965 -
130.966 -
130.967 -Document 49
130.968 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/streams.py
130.969 -Searchable Keys:
130.970 - item : ANTLRFileStream;C;;
130.971 - item : ANTLRInputStream;C;;
130.972 - item : ANTLRStringStream;C;;
130.973 - item : CharStream;C;;
130.974 - item : CommonTokenStream;C;;
130.975 - item : DEFAULT_CHANNEL;I;;
130.976 - item : DeleteOp;C;;
130.977 - item : EOF;I;;
130.978 - item : EOF_TOKEN;I;;
130.979 - item : FileStream;C;;
130.980 - item : InputStream;C;;
130.981 - item : InsertBeforeOp;C;;
130.982 - item : IntStream;C;;
130.983 - item : ReplaceOp;C;;
130.984 - item : RewriteOperation;C;;
130.985 - item : StringIO;I;;
130.986 - item : StringStream;C;;
130.987 - item : Token;I;;
130.988 - item : TokenRewriteStream;C;;
130.989 - item : TokenStream;C;;
130.990 - item : codecs;I;;
130.991 - module : streams
130.992 -
130.993 -Not Searchable Keys:
130.994 -
130.995 -
130.996 -Document 50
130.997 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tokens.py
130.998 -Searchable Keys:
130.999 - class : ClassicToken
130.1000 - class-ig : classictoken
130.1001 - extends : Token
130.1002 - in : tokens
130.1003 - member : __init__;c;|CONSTRUCTOR|;self,type,text,channel,oldToken;
130.1004 - member : __repr__;F;;self;
130.1005 - member : __str__;F;;self;
130.1006 - member : channel;D;;
130.1007 - member : charPositionInLine;D;;
130.1008 - member : getChannel;F;;self;
130.1009 - member : getCharPositionInLine;F;;self;
130.1010 - member : getInputStream;F;;self;
130.1011 - member : getLine;F;;self;
130.1012 - member : getText;F;;self;
130.1013 - member : getTokenIndex;F;;self;
130.1014 - member : getType;F;;self;
130.1015 - member : index;D;;
130.1016 - member : line;D;;
130.1017 - member : setChannel;F;;self,channel;
130.1018 - member : setCharPositionInLine;F;;self,pos;
130.1019 - member : setInputStream;F;;self,input;
130.1020 - member : setLine;F;;self,line;
130.1021 - member : setText;F;;self,text;
130.1022 - member : setTokenIndex;F;;self,index;
130.1023 - member : setType;F;;self,ttype;
130.1024 - member : text;D;;
130.1025 - member : toString;F;;self;
130.1026 - member : type;D;;
130.1027 -
130.1028 -Not Searchable Keys:
130.1029 -
130.1030 -
130.1031 -Document 51
130.1032 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tokens.py
130.1033 -Searchable Keys:
130.1034 - class : CommonToken
130.1035 - class-ig : commontoken
130.1036 - extends : Token
130.1037 - in : tokens
130.1038 - member : __init__;c;|CONSTRUCTOR|;self,type,channel,text,input,start,stop,oldToken;
130.1039 - member : __str__;F;;self;
130.1040 - member : _text;D;|PRIVATE|;
130.1041 - member : channel;D;;
130.1042 - member : charPositionInLine;D;;
130.1043 - member : getChannel;F;;self;
130.1044 - member : getCharPositionInLine;F;;self;
130.1045 - member : getInputStream;F;;self;
130.1046 - member : getLine;F;;self;
130.1047 - member : getText;F;;self;
130.1048 - member : getTokenIndex;F;;self;
130.1049 - member : getType;F;;self;
130.1050 - member : index;D;;
130.1051 - member : input;D;;
130.1052 - member : line;D;;
130.1053 - member : setChannel;F;;self,channel;
130.1054 - member : setCharPositionInLine;F;;self,pos;
130.1055 - member : setInputStream;F;;self,input;
130.1056 - member : setLine;F;;self,line;
130.1057 - member : setText;F;;self,text;
130.1058 - member : setTokenIndex;F;;self,index;
130.1059 - member : setType;F;;self,ttype;
130.1060 - member : start;D;;
130.1061 - member : stop;D;;
130.1062 - member : text;D;;
130.1063 - member : type;D;;
130.1064 -
130.1065 -Not Searchable Keys:
130.1066 -
130.1067 -
130.1068 -Document 52
130.1069 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tokens.py
130.1070 -Searchable Keys:
130.1071 - class : Token
130.1072 - class-ig : token
130.1073 - extends : object
130.1074 - in : tokens
130.1075 - member : getChannel;F;;self;
130.1076 - member : getCharPositionInLine;F;;self;
130.1077 - member : getInputStream;F;;self;
130.1078 - member : getLine;F;;self;
130.1079 - member : getText;F;;self;
130.1080 - member : getTokenIndex;F;;self;
130.1081 - member : getType;F;;self;
130.1082 - member : setChannel;F;;self,channel;
130.1083 - member : setCharPositionInLine;F;;self,pos;
130.1084 - member : setInputStream;F;;self,input;
130.1085 - member : setLine;F;;self,line;
130.1086 - member : setText;F;;self,text;
130.1087 - member : setTokenIndex;F;;self,index;
130.1088 - member : setType;F;;self,ttype;
130.1089 -
130.1090 -Not Searchable Keys:
130.1091 -
130.1092 -
130.1093 -Document 53
130.1094 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tokens.py
130.1095 -Searchable Keys:
130.1096 - item : ClassicToken;C;;
130.1097 - item : CommonToken;C;;
130.1098 - item : DEFAULT_CHANNEL;I;;
130.1099 - item : EOF;I;;
130.1100 - item : EOF_TOKEN;D;;
130.1101 - item : INVALID_TOKEN;D;;
130.1102 - item : INVALID_TOKEN_TYPE;I;;
130.1103 - item : SKIP_TOKEN;D;;
130.1104 - item : Token;C;;
130.1105 - module : tokens
130.1106 -
130.1107 -Not Searchable Keys:
130.1108 -
130.1109 -
130.1110 -Document 54
130.1111 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1112 -Searchable Keys:
130.1113 - class : BaseTree
130.1114 - class-ig : basetree
130.1115 - extends : Tree
130.1116 - in : tree
130.1117 - member : __init__;c;|CONSTRUCTOR|;self,node;
130.1118 - member : addChild;F;;self,childTree;
130.1119 - member : addChildren;F;;self,children;
130.1120 - member : childIndex;D;;
130.1121 - member : children;D;;
130.1122 - member : deleteChild;F;;self,i;
130.1123 - member : freshenParentAndChildIndexes;F;;self,offset;
130.1124 - member : getCharPositionInLine;F;;self;
130.1125 - member : getChild;F;;self,i;
130.1126 - member : getChildCount;F;;self;
130.1127 - member : getChildIndex;F;;self;
130.1128 - member : getChildren;F;;self;
130.1129 - member : getFirstChildWithType;F;;self,treeType;
130.1130 - member : getLine;F;;self;
130.1131 - member : getParent;F;;self;
130.1132 - member : isNil;F;;self;
130.1133 - member : parent;D;;
130.1134 - member : replaceChildren;F;;self,startChildIndex,stopChildIndex,newTree;
130.1135 - member : sanityCheckParentAndChildIndexes;F;;self,parent,i;
130.1136 - member : setChild;F;;self,i,t;
130.1137 - member : setChildIndex;F;;self,index;
130.1138 - member : setParent;F;;self,t;
130.1139 - member : toString;F;;self;
130.1140 - member : toStringTree;F;;self;
130.1141 -
130.1142 -Not Searchable Keys:
130.1143 -
130.1144 -
130.1145 -Document 55
130.1146 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1147 -Searchable Keys:
130.1148 - class : BaseTreeAdaptor
130.1149 - class-ig : basetreeadaptor
130.1150 - extends : TreeAdaptor
130.1151 - in : tree
130.1152 - member : addChild;F;;self,tree,child;
130.1153 - member : becomeRoot;F;;self,newRoot,oldRoot;
130.1154 - member : createFromToken;F;;self,tokenType,fromToken,text;
130.1155 - member : createFromType;F;;self,tokenType,text;
130.1156 - member : createToken;F;;self,fromToken,tokenType,text;
130.1157 - member : deleteChild;F;;self,t,i;
130.1158 - member : dupTree;F;;self,t,parent;
130.1159 - member : errorNode;F;;self,input,start,stop,exc;
130.1160 - member : getChild;F;;self,t,i;
130.1161 - member : getChildCount;F;;self,t;
130.1162 - member : getText;F;;self,t;
130.1163 - member : getType;F;;self,t;
130.1164 - member : getUniqueID;F;;self,node;
130.1165 - member : isNil;F;;self,tree;
130.1166 - member : nil;F;;self;
130.1167 - member : rulePostProcessing;F;;self,root;
130.1168 - member : setChild;F;;self,t,i,child;
130.1169 - member : setText;F;;self,t,text;
130.1170 - member : setType;F;;self,t,type;
130.1171 -
130.1172 -Not Searchable Keys:
130.1173 -
130.1174 -
130.1175 -Document 56
130.1176 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1177 -Searchable Keys:
130.1178 - class : CommonErrorNode
130.1179 - class-ig : commonerrornode
130.1180 - extends : CommonTree
130.1181 - in : tree
130.1182 - member : __init__;c;|CONSTRUCTOR|;self,input,start,stop,exc;
130.1183 - member : getText;F;;self;
130.1184 - member : getType;F;;self;
130.1185 - member : input;D;;
130.1186 - member : isNil;F;;self;
130.1187 - member : start;D;;
130.1188 - member : stop;D;;
130.1189 - member : toString;F;;self;
130.1190 - member : trappedException;D;;
130.1191 -
130.1192 -Not Searchable Keys:
130.1193 -
130.1194 -
130.1195 -Document 57
130.1196 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1197 -Searchable Keys:
130.1198 - class : CommonTree
130.1199 - class-ig : commontree
130.1200 - extends : BaseTree
130.1201 - in : tree
130.1202 - member : __init__;c;|CONSTRUCTOR|;self,payload;
130.1203 - member : __str__;F;;self;
130.1204 - member : charPositionInLine;D;;
130.1205 - member : childIndex;D;;
130.1206 - member : dupNode;F;;self;
130.1207 - member : getCharPositionInLine;F;;self;
130.1208 - member : getChildIndex;F;;self;
130.1209 - member : getLine;F;;self;
130.1210 - member : getParent;F;;self;
130.1211 - member : getText;F;;self;
130.1212 - member : getToken;F;;self;
130.1213 - member : getTokenStartIndex;F;;self;
130.1214 - member : getTokenStopIndex;F;;self;
130.1215 - member : getType;F;;self;
130.1216 - member : isNil;F;;self;
130.1217 - member : line;D;;
130.1218 - member : parent;D;;
130.1219 - member : setChildIndex;F;;self,idx;
130.1220 - member : setParent;F;;self,t;
130.1221 - member : setTokenStartIndex;F;;self,index;
130.1222 - member : setTokenStopIndex;F;;self,index;
130.1223 - member : startIndex;D;;
130.1224 - member : stopIndex;D;;
130.1225 - member : text;D;;
130.1226 - member : toString;F;;self;
130.1227 - member : toStringTree;F;;self;
130.1228 - member : token;D;;
130.1229 - member : tokenStartIndex;D;;
130.1230 - member : tokenStopIndex;D;;
130.1231 - member : type;D;;
130.1232 -
130.1233 -Not Searchable Keys:
130.1234 -
130.1235 -
130.1236 -Document 58
130.1237 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1238 -Searchable Keys:
130.1239 - class : CommonTreeAdaptor
130.1240 - class-ig : commontreeadaptor
130.1241 - extends : BaseTreeAdaptor
130.1242 - in : tree
130.1243 - member : createToken;F;;self,fromToken,tokenType,text;
130.1244 - member : createWithPayload;F;;self,payload;
130.1245 - member : dupNode;F;;self,treeNode;
130.1246 - member : getChild;F;;self,t,i;
130.1247 - member : getChildCount;F;;self,t;
130.1248 - member : getChildIndex;F;;self,t;
130.1249 - member : getParent;F;;self,t;
130.1250 - member : getText;F;;self,t;
130.1251 - member : getToken;F;;self,t;
130.1252 - member : getTokenStartIndex;F;;self,t;
130.1253 - member : getTokenStopIndex;F;;self,t;
130.1254 - member : getType;F;;self,t;
130.1255 - member : replaceChildren;F;;self,parent,startChildIndex,stopChildIndex,t;
130.1256 - member : setChildIndex;F;;self,t,index;
130.1257 - member : setParent;F;;self,t,parent;
130.1258 - member : setTokenBoundaries;F;;self,t,startToken,stopToken;
130.1259 -
130.1260 -Not Searchable Keys:
130.1261 -
130.1262 -
130.1263 -Document 59
130.1264 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1265 -Searchable Keys:
130.1266 - class : CommonTreeNodeStream
130.1267 - class-ig : commontreenodestream
130.1268 - extends : TreeNodeStream
130.1269 - in : tree
130.1270 - member : LA;F;;self,i;
130.1271 - member : LB;F;;self,k;
130.1272 - member : LT;F;;self,k;
130.1273 - member : __init__;c;|CONSTRUCTOR|;self,args;
130.1274 - member : __iter__;F;;self;
130.1275 - member : __str__;F;;self;
130.1276 - member : _fillBuffer;F;|PRIVATE|;self,t;
130.1277 - member : adaptor;D;;
130.1278 - member : addNavigationNode;F;;self,ttype;
130.1279 - member : calls;D;;
130.1280 - member : consume;F;;self;
130.1281 - member : down;D;;
130.1282 - member : eof;D;;
130.1283 - member : fillBuffer;F;;self;
130.1284 - member : get;F;;self,i;
130.1285 - member : getCurrentSymbol;F;;self;
130.1286 - member : getNodeIndex;F;;self,node;
130.1287 - member : getSourceName;F;;self;
130.1288 - member : getTokenStream;F;;self;
130.1289 - member : getTreeAdaptor;F;;self;
130.1290 - member : getTreeSource;F;;self;
130.1291 - member : hasUniqueNavigationNodes;F;;self;
130.1292 - member : index;F;;self;
130.1293 - member : lastMarker;D;;
130.1294 - member : mark;F;;self;
130.1295 - member : nodes;D;;
130.1296 - member : p;D;;
130.1297 - member : pop;F;;self;
130.1298 - member : push;F;;self,index;
130.1299 - member : release;F;;self,marker;
130.1300 - member : replaceChildren;F;;self,parent,startChildIndex,stopChildIndex,t;
130.1301 - member : reset;F;;self;
130.1302 - member : rewind;F;;self,marker;
130.1303 - member : root;D;;
130.1304 - member : seek;F;;self,index;
130.1305 - member : setTokenStream;F;;self,tokens;
130.1306 - member : setUniqueNavigationNodes;F;;self,uniqueNavigationNodes;
130.1307 - member : size;F;;self;
130.1308 - member : toString;F;;self,start,stop;
130.1309 - member : tokens;D;;
130.1310 - member : uniqueNavigationNodes;D;;
130.1311 - member : up;D;;
130.1312 -
130.1313 -Not Searchable Keys:
130.1314 -
130.1315 -
130.1316 -Document 60
130.1317 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1318 -Searchable Keys:
130.1319 - class : RewriteCardinalityException
130.1320 - class-ig : rewritecardinalityexception
130.1321 - extends : RuntimeError
130.1322 - in : tree
130.1323 - member : __init__;c;|CONSTRUCTOR|;self,elementDescription;
130.1324 - member : elementDescription;D;;
130.1325 - member : getMessage;F;;self;
130.1326 -
130.1327 -Not Searchable Keys:
130.1328 -
130.1329 -
130.1330 -Document 61
130.1331 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1332 -Searchable Keys:
130.1333 - class : RewriteEarlyExitException
130.1334 - class-ig : rewriteearlyexitexception
130.1335 - extends : RewriteCardinalityException
130.1336 - in : tree
130.1337 - member : __init__;c;|CONSTRUCTOR|;self,elementDescription;
130.1338 -
130.1339 -Not Searchable Keys:
130.1340 -
130.1341 -
130.1342 -Document 62
130.1343 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1344 -Searchable Keys:
130.1345 - class : RewriteEmptyStreamException
130.1346 - class-ig : rewriteemptystreamexception
130.1347 - extends : RewriteCardinalityException
130.1348 - in : tree
130.1349 -
130.1350 -Not Searchable Keys:
130.1351 -
130.1352 -
130.1353 -Document 63
130.1354 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1355 -Searchable Keys:
130.1356 - class : RewriteRuleElementStream
130.1357 - class-ig : rewriteruleelementstream
130.1358 - extends : object
130.1359 - in : tree
130.1360 - member : __init__;c;|CONSTRUCTOR|;self,adaptor,elementDescription,elements;
130.1361 - member : __len__;F;;self;
130.1362 - member : _next;F;|PRIVATE|;self;
130.1363 - member : adaptor;D;;
130.1364 - member : add;F;;self,el;
130.1365 - member : cursor;D;;
130.1366 - member : dirty;D;;
130.1367 - member : dup;F;;self,el;
130.1368 - member : elementDescription;D;;
130.1369 - member : elements;D;;
130.1370 - member : getDescription;F;;self;
130.1371 - member : hasNext;F;;self;
130.1372 - member : nextTree;F;;self;
130.1373 - member : reset;F;;self;
130.1374 - member : singleElement;D;;
130.1375 - member : size;F;;self;
130.1376 - member : toTree;F;;self,el;
130.1377 -
130.1378 -Not Searchable Keys:
130.1379 -
130.1380 -
130.1381 -Document 64
130.1382 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1383 -Searchable Keys:
130.1384 - class : RewriteRuleNodeStream
130.1385 - class-ig : rewriterulenodestream
130.1386 - extends : RewriteRuleElementStream
130.1387 - in : tree
130.1388 - member : dup;F;;self,el;
130.1389 - member : nextNode;F;;self;
130.1390 - member : toTree;F;;self,el;
130.1391 -
130.1392 -Not Searchable Keys:
130.1393 -
130.1394 -
130.1395 -Document 65
130.1396 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1397 -Searchable Keys:
130.1398 - class : RewriteRuleSubtreeStream
130.1399 - class-ig : rewriterulesubtreestream
130.1400 - extends : RewriteRuleElementStream
130.1401 - in : tree
130.1402 - member : dup;F;;self,el;
130.1403 - member : nextNode;F;;self;
130.1404 -
130.1405 -Not Searchable Keys:
130.1406 -
130.1407 -
130.1408 -Document 66
130.1409 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1410 -Searchable Keys:
130.1411 - class : RewriteRuleTokenStream
130.1412 - class-ig : rewriteruletokenstream
130.1413 - extends : RewriteRuleElementStream
130.1414 - in : tree
130.1415 - member : dup;F;;self,el;
130.1416 - member : nextNode;F;;self;
130.1417 - member : nextToken;F;;self;
130.1418 - member : toTree;F;;self,el;
130.1419 -
130.1420 -Not Searchable Keys:
130.1421 -
130.1422 -
130.1423 -Document 67
130.1424 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1425 -Searchable Keys:
130.1426 - class : Tree
130.1427 - class-ig : tree
130.1428 - extends : object
130.1429 - in : tree
130.1430 - member : addChild;F;;self,t;
130.1431 - member : deleteChild;F;;self,i;
130.1432 - member : dupNode;F;;self;
130.1433 - member : freshenParentAndChildIndexes;F;;self;
130.1434 - member : getCharPositionInLine;F;;self;
130.1435 - member : getChild;F;;self,i;
130.1436 - member : getChildCount;F;;self;
130.1437 - member : getChildIndex;F;;self;
130.1438 - member : getLine;F;;self;
130.1439 - member : getParent;F;;self;
130.1440 - member : getText;F;;self;
130.1441 - member : getTokenStartIndex;F;;self;
130.1442 - member : getTokenStopIndex;F;;self;
130.1443 - member : getType;F;;self;
130.1444 - member : isNil;F;;self;
130.1445 - member : replaceChildren;F;;self,startChildIndex,stopChildIndex,t;
130.1446 - member : setChild;F;;self,i,t;
130.1447 - member : setChildIndex;F;;self,index;
130.1448 - member : setParent;F;;self,t;
130.1449 - member : setTokenStartIndex;F;;self,index;
130.1450 - member : setTokenStopIndex;F;;self,index;
130.1451 - member : toString;F;;self;
130.1452 - member : toStringTree;F;;self;
130.1453 -
130.1454 -Not Searchable Keys:
130.1455 -
130.1456 -
130.1457 -Document 68
130.1458 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1459 -Searchable Keys:
130.1460 - class : TreeAdaptor
130.1461 - class-ig : treeadaptor
130.1462 - extends : object
130.1463 - in : tree
130.1464 - member : addChild;F;;self,t,child;
130.1465 - member : becomeRoot;F;;self,newRoot,oldRoot;
130.1466 - member : create;F;;self,args;
130.1467 - member : createFromToken;F;;self,tokenType,fromToken,text;
130.1468 - member : createFromType;F;;self,tokenType,text;
130.1469 - member : createWithPayload;F;;self,payload;
130.1470 - member : deleteChild;F;;self,t,i;
130.1471 - member : dupNode;F;;self,treeNode;
130.1472 - member : dupTree;F;;self,tree;
130.1473 - member : errorNode;F;;self,input,start,stop,exc;
130.1474 - member : getChild;F;;self,t,i;
130.1475 - member : getChildCount;F;;self,t;
130.1476 - member : getChildIndex;F;;self,t;
130.1477 - member : getParent;F;;self,t;
130.1478 - member : getText;F;;self,t;
130.1479 - member : getToken;F;;self,t;
130.1480 - member : getTokenStartIndex;F;;self,t;
130.1481 - member : getTokenStopIndex;F;;self,t;
130.1482 - member : getType;F;;self,t;
130.1483 - member : getUniqueID;F;;self,node;
130.1484 - member : isNil;F;;self,tree;
130.1485 - member : nil;F;;self;
130.1486 - member : replaceChildren;F;;self,parent,startChildIndex,stopChildIndex,t;
130.1487 - member : rulePostProcessing;F;;self,root;
130.1488 - member : setChild;F;;self,t,i,child;
130.1489 - member : setChildIndex;F;;self,t,index;
130.1490 - member : setParent;F;;self,t,parent;
130.1491 - member : setText;F;;self,t,text;
130.1492 - member : setTokenBoundaries;F;;self,t,startToken,stopToken;
130.1493 - member : setType;F;;self,t,type;
130.1494 -
130.1495 -Not Searchable Keys:
130.1496 -
130.1497 -
130.1498 -Document 69
130.1499 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1500 -Searchable Keys:
130.1501 - class : TreeNodeStream
130.1502 - class-ig : treenodestream
130.1503 - extends : IntStream
130.1504 - in : tree
130.1505 - member : LT;F;;self,k;
130.1506 - member : get;F;;self,i;
130.1507 - member : getTokenStream;F;;self;
130.1508 - member : getTreeAdaptor;F;;self;
130.1509 - member : getTreeSource;F;;self;
130.1510 - member : replaceChildren;F;;self,parent,startChildIndex,stopChildIndex,t;
130.1511 - member : setUniqueNavigationNodes;F;;self,uniqueNavigationNodes;
130.1512 - member : toString;F;;self,start,stop;
130.1513 -
130.1514 -Not Searchable Keys:
130.1515 -
130.1516 -
130.1517 -Document 70
130.1518 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1519 -Searchable Keys:
130.1520 - class : TreeParser
130.1521 - class-ig : treeparser
130.1522 - extends : BaseRecognizer
130.1523 - in : tree
130.1524 - member : __init__;c;|CONSTRUCTOR|;self,input,state;
130.1525 - member : getCurrentInputSymbol;F;;self,input;
130.1526 - member : getErrorHeader;F;;self,e;
130.1527 - member : getErrorMessage;F;;self,e,tokenNames;
130.1528 - member : getMissingSymbol;F;;self,input,e,expectedTokenType,follow;
130.1529 - member : getSourceName;F;;self;
130.1530 - member : getTreeNodeStream;F;;self;
130.1531 - member : input;D;;
130.1532 - member : matchAny;F;;self,ignore;
130.1533 - member : mismatch;F;;self,input,ttype,follow;
130.1534 - member : reset;F;;self;
130.1535 - member : setTreeNodeStream;F;;self,input;
130.1536 - member : traceIn;F;;self,ruleName,ruleIndex;
130.1537 - member : traceOut;F;;self,ruleName,ruleIndex;
130.1538 -
130.1539 -Not Searchable Keys:
130.1540 -
130.1541 -
130.1542 -Document 71
130.1543 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1544 -Searchable Keys:
130.1545 - class : TreeRuleReturnScope
130.1546 - class-ig : treerulereturnscope
130.1547 - extends : RuleReturnScope
130.1548 - in : tree
130.1549 - member : __init__;c;|CONSTRUCTOR|;self;
130.1550 - member : getStart;F;;self;
130.1551 - member : getTree;F;;self;
130.1552 - member : start;D;;
130.1553 - member : tree;D;;
130.1554 -
130.1555 -Not Searchable Keys:
130.1556 -
130.1557 -
130.1558 -Document 72
130.1559 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/tree.py
130.1560 -Searchable Keys:
130.1561 - item : BaseRecognizer;I;;
130.1562 - item : BaseTree;C;;
130.1563 - item : BaseTreeAdaptor;C;;
130.1564 - item : CommonErrorNode;C;;
130.1565 - item : CommonToken;I;;
130.1566 - item : CommonTree;C;;
130.1567 - item : CommonTreeAdaptor;C;;
130.1568 - item : CommonTreeNodeStream;C;;
130.1569 - item : DOWN;I;;
130.1570 - item : EOF;I;;
130.1571 - item : INVALID_NODE;D;;
130.1572 - item : INVALID_TOKEN;I;;
130.1573 - item : INVALID_TOKEN_TYPE;I;;
130.1574 - item : IntStream;I;;
130.1575 - item : MismatchedTokenException;I;;
130.1576 - item : MismatchedTreeNodeException;I;;
130.1577 - item : MissingTokenException;I;;
130.1578 - item : NoViableAltException;I;;
130.1579 - item : RewriteCardinalityException;C;;
130.1580 - item : RewriteEarlyExitException;C;;
130.1581 - item : RewriteEmptyStreamException;C;;
130.1582 - item : RewriteRuleElementStream;C;;
130.1583 - item : RewriteRuleNodeStream;C;;
130.1584 - item : RewriteRuleSubtreeStream;C;;
130.1585 - item : RewriteRuleTokenStream;C;;
130.1586 - item : RuleReturnScope;I;;
130.1587 - item : Token;I;;
130.1588 - item : Tree;C;;
130.1589 - item : TreeAdaptor;C;;
130.1590 - item : TreeNodeStream;C;;
130.1591 - item : TreeParser;C;;
130.1592 - item : TreeRuleReturnScope;C;;
130.1593 - item : UP;I;;
130.1594 - item : UnwantedTokenException;I;;
130.1595 - module : tree
130.1596 -
130.1597 -Not Searchable Keys:
130.1598 -
130.1599 -
130.1600 -Document 73
130.1601 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/treewizard.py
130.1602 -Searchable Keys:
130.1603 - class : TreePattern
130.1604 - class-ig : treepattern
130.1605 - extends : CommonTree
130.1606 - in : treewizard
130.1607 - member : __init__;c;|CONSTRUCTOR|;self,payload;
130.1608 - member : hasTextArg;D;;
130.1609 - member : label;D;;
130.1610 - member : toString;F;;self;
130.1611 -
130.1612 -Not Searchable Keys:
130.1613 -
130.1614 -
130.1615 -Document 74
130.1616 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/treewizard.py
130.1617 -Searchable Keys:
130.1618 - class : TreePatternLexer
130.1619 - class-ig : treepatternlexer
130.1620 - extends : object
130.1621 - in : treewizard
130.1622 - member : __idChar;D;|PRIVATE|;
130.1623 - member : __idStartChar;D;|PRIVATE|;
130.1624 - member : __init__;c;|CONSTRUCTOR|;self,pattern;
130.1625 - member : c;D;;
130.1626 - member : consume;F;;self;
130.1627 - member : error;D;;
130.1628 - member : n;D;;
130.1629 - member : nextToken;F;;self;
130.1630 - member : p;D;;
130.1631 - member : pattern;D;;
130.1632 - member : sval;D;;
130.1633 -
130.1634 -Not Searchable Keys:
130.1635 -
130.1636 -
130.1637 -Document 75
130.1638 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/treewizard.py
130.1639 -Searchable Keys:
130.1640 - class : TreePatternParser
130.1641 - class-ig : treepatternparser
130.1642 - extends : object
130.1643 - in : treewizard
130.1644 - member : __init__;c;|CONSTRUCTOR|;self,tokenizer,wizard,adaptor;
130.1645 - member : adaptor;D;;
130.1646 - member : parseNode;F;;self;
130.1647 - member : parseTree;F;;self;
130.1648 - member : pattern;F;;self;
130.1649 - member : tokenizer;D;;
130.1650 - member : ttype;D;;
130.1651 - member : wizard;D;;
130.1652 -
130.1653 -Not Searchable Keys:
130.1654 -
130.1655 -
130.1656 -Document 76
130.1657 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/treewizard.py
130.1658 -Searchable Keys:
130.1659 - class : TreePatternTreeAdaptor
130.1660 - class-ig : treepatterntreeadaptor
130.1661 - extends : CommonTreeAdaptor
130.1662 - in : treewizard
130.1663 - member : createWithPayload;F;;self,payload;
130.1664 -
130.1665 -Not Searchable Keys:
130.1666 -
130.1667 -
130.1668 -Document 77
130.1669 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/treewizard.py
130.1670 -Searchable Keys:
130.1671 - class : TreeWizard
130.1672 - class-ig : treewizard
130.1673 - extends : object
130.1674 - in : treewizard
130.1675 - member : __init__;c;|CONSTRUCTOR|;self,adaptor,tokenNames,typeMap;
130.1676 - member : _equals;F;|PRIVATE|;self,t1,t2,adaptor;
130.1677 - member : _findPattern;F;|PRIVATE|;self,t,pattern;
130.1678 - member : _findTokenType;F;|PRIVATE|;self,t,ttype;
130.1679 - member : _index;F;|PRIVATE|;self,t,m;
130.1680 - member : _parse;F;|PRIVATE|;self,t1,t2,labels;
130.1681 - member : _visitPattern;F;|PRIVATE|;self,tree,pattern,visitor;
130.1682 - member : _visitType;F;|PRIVATE|;self,t,parent,childIndex,ttype,visitor;
130.1683 - member : adaptor;D;;
130.1684 - member : create;F;;self,pattern;
130.1685 - member : equals;F;;self,t1,t2,adaptor;
130.1686 - member : find;F;;self,tree,what;
130.1687 - member : getTokenType;F;;self,tokenName;
130.1688 - member : index;F;;self,tree;
130.1689 - member : parse;F;;self,t,pattern,labels;
130.1690 - member : tokenNameToTypeMap;D;;
130.1691 - member : visit;F;;self,tree,what,visitor;
130.1692 -
130.1693 -Not Searchable Keys:
130.1694 -
130.1695 -
130.1696 -Document 78
130.1697 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/treewizard.py
130.1698 -Searchable Keys:
130.1699 - class : WildcardTreePattern
130.1700 - class-ig : wildcardtreepattern
130.1701 - extends : TreePattern
130.1702 - in : treewizard
130.1703 -
130.1704 -Not Searchable Keys:
130.1705 -
130.1706 -
130.1707 -Document 79
130.1708 -Override URL: jar:<TESTURL>/antlr_python_runtime-3.1.1-py2.5.egg!/antlr3/treewizard.py
130.1709 -Searchable Keys:
130.1710 - item : ARG;D;;
130.1711 - item : BEGIN;D;;
130.1712 - item : COLON;D;;
130.1713 - item : CommonToken;I;;
130.1714 - item : CommonTree;I;;
130.1715 - item : CommonTreeAdaptor;I;;
130.1716 - item : DOT;D;;
130.1717 - item : END;D;;
130.1718 - item : EOF;D;;
130.1719 - item : ID;D;;
130.1720 - item : INVALID_TOKEN_TYPE;I;;
130.1721 - item : PERCENT;D;;
130.1722 - item : TreePattern;C;;
130.1723 - item : TreePatternLexer;C;;
130.1724 - item : TreePatternParser;C;;
130.1725 - item : TreePatternTreeAdaptor;C;;
130.1726 - item : TreeWizard;C;;
130.1727 - item : WildcardTreePattern;C;;
130.1728 - item : computeTokenTypes;F;;tokenNames;
130.1729 - module : treewizard
130.1730 -
130.1731 -Not Searchable Keys:
131.1 --- a/python.editor/test/unit/data/testfiles/assign.py Sun Jan 04 13:11:53 2015 -0600
131.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
131.3 @@ -1,7 +0,0 @@
131.4 -if __name__ == "__main__":
131.5 - print "Hello";
131.6 - "foo"
131.7 - 3+1
131.8 - preprocess1(foo, source, output_file, macros, include_dirs, extra_preargs, extra_postargs);
131.9 - get_preprocess2(self, source, output_file, macros, include_dirs, extra_preargs, extra_postargs)
131.10 -
132.1 --- a/python.editor/test/unit/data/testfiles/assign.py.testAssign1.hints Sun Jan 04 13:11:53 2015 -0600
132.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
132.3 @@ -1,4 +0,0 @@
132.4 - ^"foo"
132.5 - -----
132.6 -HINT:Assign expression to a variable
132.7 -FIX:Assign expression to a variable
133.1 --- a/python.editor/test/unit/data/testfiles/assign.py.testAssign2.hints Sun Jan 04 13:11:53 2015 -0600
133.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
133.3 @@ -1,4 +0,0 @@
133.4 - 3+1^
133.5 - ---
133.6 -HINT:Assign expression to a variable
133.7 -FIX:Assign expression to a variable
134.1 --- a/python.editor/test/unit/data/testfiles/assign.py.testAssign3.hints Sun Jan 04 13:11:53 2015 -0600
134.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
134.3 @@ -1,4 +0,0 @@
134.4 - ^get_preprocess2(self, source, output_file, macros, include_dirs, extra_preargs, extra_postargs)
134.5 - -----------------------------------------------------------------------------------------------
134.6 -HINT:Assign expression to a variable
134.7 -FIX:Assign expression to a variable
135.1 --- a/python.editor/test/unit/data/testfiles/assign.py.testFixAssign.fixed Sun Jan 04 13:11:53 2015 -0600
135.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
135.3 @@ -1,7 +0,0 @@
135.4 -if __name__ == "__main__":
135.5 - print "Hello";
135.6 - "foo"
135.7 - name = 3+1
135.8 - preprocess1(foo, source, output_file, macros, include_dirs, extra_preargs, extra_postargs);
135.9 - get_preprocess2(self, source, output_file, macros, include_dirs, extra_preargs, extra_postargs)
135.10 -
136.1 --- a/python.editor/test/unit/data/testfiles/assign2.py Sun Jan 04 13:11:53 2015 -0600
136.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
136.3 @@ -1,4 +0,0 @@
136.4 -def _is_leap(year):
136.5 - "year -> 1 if leap year, else 0."
136.6 - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
136.7 -
137.1 --- a/python.editor/test/unit/data/testfiles/attribute.py Sun Jan 04 13:11:53 2015 -0600
137.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
137.3 @@ -1,6 +0,0 @@
137.4 -# Test 1
137.5 -foo.bar
137.6 -
137.7 -# Test 2
137.8 -foo.bar()
137.9 -
138.1 --- a/python.editor/test/unit/data/testfiles/attribute.py.offsets Sun Jan 04 13:11:53 2015 -0600
138.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
138.3 @@ -1,7 +0,0 @@
138.4 -
138.5 -# Test 1
138.6 -<Module><Expr><Attribute><Name>foo</Name>.bar</Attribute></Expr>
138.7 -
138.8 -# Test 2
138.9 -<Expr><Call><Attribute><Name>foo</Name>.bar</Attribute>()</Call></Expr></Module>
138.10 -
139.1 --- a/python.editor/test/unit/data/testfiles/attributes.py Sun Jan 04 13:11:53 2015 -0600
139.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
139.3 @@ -1,20 +0,0 @@
139.4 -
139.5 -class AttributeTest:
139.6 - def __init__(self):
139.7 - self.okay = true;
139.8 - self._private = true;
139.9 -
139.10 - def notconstructor(self):
139.11 - self.notokay = true;
139.12 -
139.13 -
139.14 - print self.okay
139.15 - print self.notokay
139.16 -
139.17 -
139.18 - def usage(self):
139.19 - other.notokay = true;
139.20 - other._notokay = true;
139.21 - print other._notokay
139.22 -
139.23 -
140.1 --- a/python.editor/test/unit/data/testfiles/attributes.py.scopes Sun Jan 04 13:11:53 2015 -0600
140.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
140.3 @@ -1,33 +0,0 @@
140.4 - =============================================
140.5 - class AttributeTest: ClassDef : OffsetRange[1,361>
140.6 - __init__ [bound][function][def][node=FunctionDef]
140.7 - notconstructor [bound][function][def][node=FunctionDef]
140.8 - usage [bound][function][def][node=FunctionDef]
140.9 - ------ Attributes ---------------------------------------
140.10 - _private : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
140.11 - notokay : SymInfo[8195 0 0][bound][func-global][data][member][generator][unused][node=Attribute]
140.12 - okay : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
140.13 -
140.14 -=============================================
140.15 -<file-top>: Module : OffsetRange[1,361>
140.16 -AttributeTest [bound][class][def][node=ClassDef]
140.17 -
140.18 - =============================================
140.19 - __init__: FunctionDef : OffsetRange[26,106>
140.20 - self [bound][param][data][read][node=Name]
140.21 - true [free][read][node=Name]
140.22 -
140.23 - =============================================
140.24 - notconstructor: FunctionDef : OffsetRange[107,244>
140.25 - self [bound][param][data][read][node=Name]
140.26 - true [free][read][node=Name]
140.27 - ------ Attributes ---------------------------------------
140.28 - notokay : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
140.29 - okay : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
140.30 -
140.31 - =============================================
140.32 - usage: FunctionDef : OffsetRange[245,361>
140.33 - other [free][read][node=Name]
140.34 - self [bound][param][data][unused][node=Name]
140.35 - true [free][read][node=Name]
140.36 -
141.1 --- a/python.editor/test/unit/data/testfiles/attributes.py.testAccessToProtected.hints Sun Jan 04 13:11:53 2015 -0600
141.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
141.3 @@ -1,6 +0,0 @@
141.4 - other._notokay = true;
141.5 - --------------
141.6 -HINT:Access to protected variable "_notokay"
141.7 - print other._notokay
141.8 - --------------
141.9 -HINT:Access to protected variable "_notokay"
142.1 --- a/python.editor/test/unit/data/testfiles/attributes.py.testAttributeDefinedOutsideInit.hints Sun Jan 04 13:11:53 2015 -0600
142.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
142.3 @@ -1,3 +0,0 @@
142.4 - self.notokay = true;
142.5 - ------------
142.6 -HINT:Attribute Defined Outside __init__ "notokay"
143.1 --- a/python.editor/test/unit/data/testfiles/attributes.py.testRename9.rename Sun Jan 04 13:11:53 2015 -0600
143.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
143.3 @@ -1,1 +0,0 @@
143.4 -Requires Interactive Refactoring
144.1 --- a/python.editor/test/unit/data/testfiles/circularredundancy.py Sun Jan 04 13:11:53 2015 -0600
144.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
144.3 @@ -1,23 +0,0 @@
144.4 -#
144.5 -# checking redundancy cycling
144.6 -#
144.7 -
144.8 -# circular
144.9 -class First (Third ):
144.10 - pass
144.11 -
144.12 -class Second (First) :
144.13 - pass
144.14 -
144.15 -class Third (Second) :
144.16 - pass
144.17 -
144.18 -# not circular
144.19 -class Fourth :
144.20 - pass
144.21 -
144.22 -class Fifth(Fourth):
144.23 - pass
144.24 -
144.25 -
144.26 -
145.1 --- a/python.editor/test/unit/data/testfiles/circularredundancy.py.testCircularRedundancy.hints Sun Jan 04 13:11:53 2015 -0600
145.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
145.3 @@ -1,9 +0,0 @@
145.4 -class First (Third ):
145.5 - -----
145.6 -HINT:Parent/child First/Third inheritance circular redundancy
145.7 -class Second (First) :
145.8 - ------
145.9 -HINT:Parent/child Second/First inheritance circular redundancy
145.10 -class Third (Second) :
145.11 - -----
145.12 -HINT:Parent/child Third/Second inheritance circular redundancy
146.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/nbproject/project.properties Sun Jan 04 13:11:53 2015 -0600
146.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
146.3 @@ -1,5 +0,0 @@
146.4 -java.lib.path=
146.5 -main.file=md5driver.py
146.6 -platform.active=Python_2.5.1
146.7 -python.lib.path=
146.8 -src.dir=src
147.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/nbproject/project.xml Sun Jan 04 13:11:53 2015 -0600
147.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
147.3 @@ -1,13 +0,0 @@
147.4 -<?xml version="1.0" encoding="UTF-8"?>
147.5 -<project xmlns="http://www.netbeans.org/ns/project/1">
147.6 - <type>org.netbeans.modules.python.project</type>
147.7 - <configuration>
147.8 - <data xmlns="http://nbpython.dev.java.net/ns/php-project/1">
147.9 - <name>CoveragePrj</name>
147.10 - <sources>
147.11 - <root id="src.dir"/>
147.12 - </sources>
147.13 - <tests/>
147.14 - </data>
147.15 - </configuration>
147.16 -</project>
148.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/src/coverageprj.py Sun Jan 04 13:11:53 2015 -0600
148.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
148.3 @@ -1,10 +0,0 @@
148.4 -# To change this template, choose Tools | Templates
148.5 -# and open the template in the editor.
148.6 -
148.7 -__author__="tor"
148.8 -__date__ ="$Dec 15, 2008 12:29:43 PM$"
148.9 -
148.10 -if __name__ == "__mmain__":
148.11 - print "Hello World";
148.12 -
148.13 -print "Bye"
149.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/src/coverageprj.py.coverage.html Sun Jan 04 13:11:53 2015 -0600
149.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
149.3 @@ -1,25 +0,0 @@
149.4 -<html>
149.5 -<head>
149.6 -<style>
149.7 -div { white-space: pre; font-family: monospace; margin: 0px; padding: 0px }
149.8 -.covered { background-color: CCFFCC }
149.9 -.partial { background-color: FFFFCC }
149.10 -.not_covered { background-color: FFCCCC }
149.11 -.inferred { background-color: E0FFE0 }
149.12 -.unknown { background-color: EEEEEE }
149.13 -</style>
149.14 -</head>
149.15 -<body>
149.16 -<h1>File Coverage for coverageprj.py</h1>
149.17 -<div class="inferred"># To change this template, choose Tools | Templates</div>
149.18 -<div class="inferred"># and open the template in the editor.</div>
149.19 -<div class="inferred"></div>
149.20 -<div class="covered">__author__="tor"</div>
149.21 -<div class="covered">__date__ ="$Dec 15, 2008 12:29:43 PM$"</div>
149.22 -<div class="inferred"></div>
149.23 -<div class="covered">if __name__ == "__mmain__":</div>
149.24 -<div class="not_covered"> print "Hello World";</div>
149.25 -<div class="not_covered"></div>
149.26 -<div class="covered">print "Bye"</div>
149.27 -
149.28 -</body></html>
150.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/src/coverageprj2.py Sun Jan 04 13:11:53 2015 -0600
150.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
150.3 @@ -1,13 +0,0 @@
150.4 -#import
150.5 -__author__="tor"
150.6 -__date__ ="$Nov 1, 2008 4:43:31 PM$"
150.7 -
150.8 -
150.9 -
150.10 -if __name__ == "__mmain__":
150.11 - print "Hello";
150.12 -
150.13 -
150.14 - def fenamme():
150.15 - pass
150.16 -
151.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/src/coverageprj2.py.coverage.html Sun Jan 04 13:11:53 2015 -0600
151.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
151.3 @@ -1,28 +0,0 @@
151.4 -<html>
151.5 -<head>
151.6 -<style>
151.7 -div { white-space: pre; font-family: monospace; margin: 0px; padding: 0px }
151.8 -.covered { background-color: CCFFCC }
151.9 -.partial { background-color: FFFFCC }
151.10 -.not_covered { background-color: FFCCCC }
151.11 -.inferred { background-color: E0FFE0 }
151.12 -.unknown { background-color: EEEEEE }
151.13 -</style>
151.14 -</head>
151.15 -<body>
151.16 -<h1>File Coverage for coverageprj2.py</h1>
151.17 -<div class="inferred">#import</div>
151.18 -<div class="covered">__author__="tor"</div>
151.19 -<div class="covered">__date__ ="$Nov 1, 2008 4:43:31 PM$"</div>
151.20 -<div class="inferred"></div>
151.21 -<div class="inferred"></div>
151.22 -<div class="inferred"></div>
151.23 -<div class="covered">if __name__ == "__mmain__":</div>
151.24 -<div class="not_covered"> print "Hello";</div>
151.25 -<div class="not_covered"></div>
151.26 -<div class="not_covered"></div>
151.27 -<div class="not_covered"> def fenamme():</div>
151.28 -<div class="not_covered"> pass</div>
151.29 -<div class="not_covered"></div>
151.30 -
151.31 -</body></html>
152.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/src/coverageprj3.py Sun Jan 04 13:11:53 2015 -0600
152.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
152.3 @@ -1,12 +0,0 @@
152.4 -#import
152.5 -__author__="tor"
152.6 -__date__ ="$Nov 1, 2008 4:43:31 PM$"
152.7 -
152.8 -
152.9 -
152.10 -if __name__ == "__main__":
152.11 - print "Hello";
152.12 -
152.13 -# This line is inferred to be executed
152.14 -# This one too
152.15 -
153.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/src/coverageprj3.py.coverage.html Sun Jan 04 13:11:53 2015 -0600
153.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
153.3 @@ -1,27 +0,0 @@
153.4 -<html>
153.5 -<head>
153.6 -<style>
153.7 -div { white-space: pre; font-family: monospace; margin: 0px; padding: 0px }
153.8 -.covered { background-color: CCFFCC }
153.9 -.partial { background-color: FFFFCC }
153.10 -.not_covered { background-color: FFCCCC }
153.11 -.inferred { background-color: E0FFE0 }
153.12 -.unknown { background-color: EEEEEE }
153.13 -</style>
153.14 -</head>
153.15 -<body>
153.16 -<h1>File Coverage for coverageprj3.py</h1>
153.17 -<div class="inferred">#import</div>
153.18 -<div class="covered">__author__="tor"</div>
153.19 -<div class="covered">__date__ ="$Nov 1, 2008 4:43:31 PM$"</div>
153.20 -<div class="inferred"></div>
153.21 -<div class="inferred"></div>
153.22 -<div class="inferred"></div>
153.23 -<div class="covered">if __name__ == "__main__":</div>
153.24 -<div class="covered"> print "Hello";</div>
153.25 -<div class="inferred"></div>
153.26 -<div class="inferred"># This line is inferred to be executed</div>
153.27 -<div class="inferred"># This one too</div>
153.28 -<div class="inferred"></div>
153.29 -
153.30 -</body></html>
154.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/src/foo Sun Jan 04 13:11:53 2015 -0600
154.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
154.3 @@ -1,1 +0,0 @@
154.4 -Hello World
155.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/src/md5driver.py Sun Jan 04 13:11:53 2015 -0600
155.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
155.3 @@ -1,126 +0,0 @@
155.4 -import string
155.5 -import md5
155.6 -from sys import argv
155.7 -
155.8 -def MDPrint(str):
155.9 - outstr = ''
155.10 - for i in str:
155.11 - o = ord(i)
155.12 - outstr = (outstr
155.13 - + string.hexdigits[(o >> 4) & 0xF]
155.14 - + string.hexdigits[o & 0xF])
155.15 - print outstr,
155.16 -
155.17 -
155.18 -from time import time
155.19 -
155.20 -def makestr(start, end):
155.21 - result = ''
155.22 -
155.23 - for i in range(start, end + 1):
155.24 - result = result + chr(i)
155.25 -
155.26 - return result
155.27 -
155.28 -
155.29 -def MDTimeTrial():
155.30 - TEST_BLOCK_SIZE = 1000
155.31 - TEST_BLOCKS = 10000
155.32 -
155.33 - TEST_BYTES = TEST_BLOCK_SIZE * TEST_BLOCKS
155.34 -
155.35 - # initialize test data, need temporary string filler
155.36 -
155.37 - filsiz = 1 << 8
155.38 - filler = makestr(0, filsiz-1)
155.39 - data = filler * (TEST_BLOCK_SIZE // filsiz)
155.40 - data = data + filler[:(TEST_BLOCK_SIZE % filsiz)]
155.41 -
155.42 - del filsiz, filler
155.43 -
155.44 -
155.45 - # start timer
155.46 - print 'MD5 time trial. Processing', TEST_BYTES, 'characters...'
155.47 - t1 = time()
155.48 -
155.49 - mdContext = md5.new()
155.50 -
155.51 - for i in range(TEST_BLOCKS):
155.52 - mdContext.update(data)
155.53 -
155.54 - str = mdContext.digest()
155.55 - t2 = time()
155.56 -
155.57 - MDPrint(str)
155.58 - print 'is digest of test input.'
155.59 - print 'Seconds to process test input:', t2 - t1
155.60 - print 'Characters processed per second:', TEST_BYTES / (t2 - t1)
155.61 -
155.62 -
155.63 -def MDString(str):
155.64 - MDPrint(md5.new(str).digest())
155.65 - print '"' + str + '"'
155.66 -
155.67 -
155.68 -def MDFile(filename):
155.69 - f = open(filename, 'rb')
155.70 - mdContext = md5.new()
155.71 -
155.72 - while 1:
155.73 - data = f.read(1024)
155.74 - if not data:
155.75 - break
155.76 - mdContext.update(data)
155.77 -
155.78 - MDPrint(mdContext.digest())
155.79 - print filename
155.80 -
155.81 -
155.82 -import sys
155.83 -
155.84 -# This comment should be
155.85 -# inferred as part of the previous one
155.86 -def MDFilter():
155.87 - mdContext = md5.new()
155.88 -
155.89 - while 1:
155.90 - data = sys.stdin.read(16)
155.91 - if not data:
155.92 - break
155.93 - mdContext.update(data)
155.94 -
155.95 - MDPrint(mdContext.digest())
155.96 - print
155.97 -
155.98 -
155.99 -def MDTestSuite():
155.100 - print 'MD5 test suite results:'
155.101 - MDString('')
155.102 - MDString('a')
155.103 - MDString('abc')
155.104 - MDString('message digest')
155.105 - MDString(makestr(ord('a'), ord('z')))
155.106 - MDString(makestr(ord('A'), ord('Z'))
155.107 - + makestr(ord('a'), ord('z'))
155.108 - + makestr(ord('0'), ord('9')))
155.109 - MDString((makestr(ord('1'), ord('9')) + '0') * 8)
155.110 -
155.111 - # Contents of file foo are "abc"
155.112 - MDFile('foo')
155.113 -
155.114 -
155.115 -# I don't wanna use getopt(), since I want to use the same i/f...
155.116 -def main():
155.117 - if len(argv) == 1:
155.118 - MDFilter()
155.119 - for arg in argv[1:]:
155.120 - if arg[:2] == '-s':
155.121 - MDString(arg[2:])
155.122 - elif arg == '-t':
155.123 - MDTimeTrial()
155.124 - elif arg == '-x':
155.125 - MDTestSuite()
155.126 - else:
155.127 - MDFile(arg)
155.128 -
155.129 -main()
156.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj/src/md5driver.py.coverage.html Sun Jan 04 13:11:53 2015 -0600
156.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
156.3 @@ -1,141 +0,0 @@
156.4 -<html>
156.5 -<head>
156.6 -<style>
156.7 -div { white-space: pre; font-family: monospace; margin: 0px; padding: 0px }
156.8 -.covered { background-color: CCFFCC }
156.9 -.partial { background-color: FFFFCC }
156.10 -.not_covered { background-color: FFCCCC }
156.11 -.inferred { background-color: E0FFE0 }
156.12 -.unknown { background-color: EEEEEE }
156.13 -</style>
156.14 -</head>
156.15 -<body>
156.16 -<h1>File Coverage for md5driver.py</h1>
156.17 -<div class="covered">import string</div>
156.18 -<div class="covered">import md5</div>
156.19 -<div class="covered">from sys import argv</div>
156.20 -<div class="unknown"></div>
156.21 -<div class="covered">def MDPrint(str):</div>
156.22 -<div class="covered"> outstr = ''</div>
156.23 -<div class="covered"> for i in str:</div>
156.24 -<div class="covered"> o = ord(i)</div>
156.25 -<div class="covered"> outstr = (outstr</div>
156.26 -<div class="unknown"> + string.hexdigits[(o >> 4) & 0xF]</div>
156.27 -<div class="unknown"> + string.hexdigits[o & 0xF])</div>
156.28 -<div class="covered"> print outstr,</div>
156.29 -<div class="inferred"></div>
156.30 -<div class="inferred"></div>
156.31 -<div class="covered">from time import time</div>
156.32 -<div class="unknown"></div>
156.33 -<div class="covered">def makestr(start, end):</div>
156.34 -<div class="not_covered"> result = ''</div>
156.35 -<div class="not_covered"> </div>
156.36 -<div class="not_covered"> for i in range(start, end + 1):</div>
156.37 -<div class="not_covered"> result = result + chr(i)</div>
156.38 -<div class="not_covered"></div>
156.39 -<div class="not_covered"> return result</div>
156.40 -<div class="not_covered"></div>
156.41 -<div class="not_covered"></div>
156.42 -<div class="covered">def MDTimeTrial():</div>
156.43 -<div class="not_covered"> TEST_BLOCK_SIZE = 1000</div>
156.44 -<div class="not_covered"> TEST_BLOCKS = 10000</div>
156.45 -<div class="not_covered"></div>
156.46 -<div class="not_covered"> TEST_BYTES = TEST_BLOCK_SIZE * TEST_BLOCKS</div>
156.47 -<div class="not_covered"></div>
156.48 -<div class="not_covered"> # initialize test data, need temporary string filler</div>
156.49 -<div class="not_covered"></div>
156.50 -<div class="not_covered"> filsiz = 1 << 8</div>
156.51 -<div class="not_covered"> filler = makestr(0, filsiz-1)</div>
156.52 -<div class="not_covered"> data = filler * (TEST_BLOCK_SIZE // filsiz)</div>
156.53 -<div class="not_covered"> data = data + filler[:(TEST_BLOCK_SIZE % filsiz)]</div>
156.54 -<div class="not_covered"></div>
156.55 -<div class="not_covered"> del filsiz, filler</div>
156.56 -<div class="not_covered"></div>
156.57 -<div class="not_covered"></div>
156.58 -<div class="not_covered"> # start timer</div>
156.59 -<div class="not_covered"> print 'MD5 time trial. Processing', TEST_BYTES, 'characters...'</div>
156.60 -<div class="not_covered"> t1 = time()</div>
156.61 -<div class="not_covered"></div>
156.62 -<div class="not_covered"> mdContext = md5.new()</div>
156.63 -<div class="not_covered"></div>
156.64 -<div class="not_covered"> for i in range(TEST_BLOCKS):</div>
156.65 -<div class="not_covered"> mdContext.update(data)</div>
156.66 -<div class="not_covered"></div>
156.67 -<div class="not_covered"> str = mdContext.digest()</div>
156.68 -<div class="not_covered"> t2 = time()</div>
156.69 -<div class="not_covered"></div>
156.70 -<div class="not_covered"> MDPrint(str)</div>
156.71 -<div class="not_covered"> print 'is digest of test input.'</div>
156.72 -<div class="not_covered"> print 'Seconds to process test input:', t2 - t1</div>
156.73 -<div class="not_covered"> print 'Characters processed per second:', TEST_BYTES / (t2 - t1)</div>
156.74 -<div class="not_covered"></div>
156.75 -<div class="not_covered"></div>
156.76 -<div class="covered">def MDString(str):</div>
156.77 -<div class="not_covered"> MDPrint(md5.new(str).digest())</div>
156.78 -<div class="not_covered"> print '"' + str + '"'</div>
156.79 -<div class="not_covered"></div>
156.80 -<div class="not_covered"></div>
156.81 -<div class="covered">def MDFile(filename):</div>
156.82 -<div class="not_covered"> f = open(filename, 'rb')</div>
156.83 -<div class="not_covered"> mdContext = md5.new()</div>
156.84 -<div class="not_covered"></div>
156.85 -<div class="not_covered"> while 1:</div>
156.86 -<div class="not_covered"> data = f.read(1024)</div>
156.87 -<div class="not_covered"> if not data:</div>
156.88 -<div class="not_covered"> break</div>
156.89 -<div class="not_covered"> mdContext.update(data)</div>
156.90 -<div class="not_covered"></div>
156.91 -<div class="not_covered"> MDPrint(mdContext.digest())</div>
156.92 -<div class="not_covered"> print filename</div>
156.93 -<div class="not_covered"></div>
156.94 -<div class="not_covered"></div>
156.95 -<div class="covered">import sys</div>
156.96 -<div class="inferred"></div>
156.97 -<div class="inferred"># This comment should be</div>
156.98 -<div class="inferred"># inferred as part of the previous one</div>
156.99 -<div class="covered">def MDFilter():</div>
156.100 -<div class="covered"> mdContext = md5.new()</div>
156.101 -<div class="inferred"></div>
156.102 -<div class="covered"> while 1:</div>
156.103 -<div class="covered"> data = sys.stdin.read(16)</div>
156.104 -<div class="covered"> if not data:</div>
156.105 -<div class="not_covered"> break</div>
156.106 -<div class="not_covered"> mdContext.update(data)</div>
156.107 -<div class="not_covered"></div>
156.108 -<div class="covered"> MDPrint(mdContext.digest())</div>
156.109 -<div class="covered"> print</div>
156.110 -<div class="unknown"></div>
156.111 -<div class="unknown"></div>
156.112 -<div class="covered">def MDTestSuite():</div>
156.113 -<div class="not_covered"> print 'MD5 test suite results:'</div>
156.114 -<div class="not_covered"> MDString('')</div>
156.115 -<div class="not_covered"> MDString('a')</div>
156.116 -<div class="not_covered"> MDString('abc')</div>
156.117 -<div class="not_covered"> MDString('message digest')</div>
156.118 -<div class="not_covered"> MDString(makestr(ord('a'), ord('z')))</div>
156.119 -<div class="not_covered"> MDString(makestr(ord('A'), ord('Z'))</div>
156.120 -<div class="not_covered"> + makestr(ord('a'), ord('z'))</div>
156.121 -<div class="not_covered"> + makestr(ord('0'), ord('9')))</div>
156.122 -<div class="not_covered"> MDString((makestr(ord('1'), ord('9')) + '0') * 8)</div>
156.123 -<div class="not_covered"></div>
156.124 -<div class="not_covered"> # Contents of file foo are "abc"</div>
156.125 -<div class="not_covered"> MDFile('foo')</div>
156.126 -<div class="not_covered"></div>
156.127 -<div class="not_covered"></div>
156.128 -<div class="inferred"># I don't wanna use getopt(), since I want to use the same i/f...</div>
156.129 -<div class="covered">def main():</div>
156.130 -<div class="covered"> if len(argv) == 1:</div>
156.131 -<div class="covered"> MDFilter()</div>
156.132 -<div class="covered"> for arg in argv[1:]:</div>
156.133 -<div class="not_covered"> if arg[:2] == '-s':</div>
156.134 -<div class="not_covered"> MDString(arg[2:])</div>
156.135 -<div class="not_covered"> elif arg == '-t':</div>
156.136 -<div class="not_covered"> MDTimeTrial()</div>
156.137 -<div class="not_covered"> elif arg == '-x':</div>
156.138 -<div class="not_covered"> MDTestSuite()</div>
156.139 -<div class="not_covered"> else:</div>
156.140 -<div class="not_covered"> MDFile(arg)</div>
156.141 -<div class="not_covered"></div>
156.142 -<div class="covered">main()</div>
156.143 -
156.144 -</body></html>
157.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj2/nbproject/project.properties Sun Jan 04 13:11:53 2015 -0600
157.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
157.3 @@ -1,5 +0,0 @@
157.4 -java.lib.path=
157.5 -main.file=md5driver.py
157.6 -platform.active=Python_2.5.1
157.7 -python.lib.path=
157.8 -src.dir=src
158.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj2/nbproject/project.xml Sun Jan 04 13:11:53 2015 -0600
158.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
158.3 @@ -1,13 +0,0 @@
158.4 -<?xml version="1.0" encoding="UTF-8"?>
158.5 -<project xmlns="http://www.netbeans.org/ns/project/1">
158.6 - <type>org.netbeans.modules.python.project</type>
158.7 - <configuration>
158.8 - <data xmlns="http://nbpython.dev.java.net/ns/php-project/1">
158.9 - <name>CoveragePrj2</name>
158.10 - <sources>
158.11 - <root id="src.dir"/>
158.12 - </sources>
158.13 - <tests/>
158.14 - </data>
158.15 - </configuration>
158.16 -</project>
159.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj2/src/roman9.py Sun Jan 04 13:11:53 2015 -0600
159.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
159.3 @@ -1,83 +0,0 @@
159.4 -"""Convert to and from Roman numerals
159.5 -
159.6 -This program is part of "Dive Into Python", a free Python book for
159.7 -experienced programmers. Visit http://diveintopython.org/ for the
159.8 -latest version.
159.9 -"""
159.10 -
159.11 -__author__ = "Steve Lamm, Mark Pilgrim (mark@diveintopython.org)"
159.12 -__version__ = "$Revision: 1.3 $"
159.13 -__date__ = "$Date: 2004/05/05 21:57:20 $"
159.14 -__copyright__ = "Copyright (c) 2001 Steve Lamm, Copyright (c) 2001 Mark Pilgrim"
159.15 -__license__ = "Python"
159.16 -
159.17 -import re
159.18 -
159.19 -#Define exceptions
159.20 -class RomanError(Exception): pass
159.21 -class OutOfRangeError(RomanError): pass
159.22 -class NotIntegerError(RomanError): pass
159.23 -class InvalidRomanNumeralError(RomanError): pass
159.24 -
159.25 -#Roman numerals must be less than 5000
159.26 -MAX_ROMAN_NUMERAL = 4999
159.27 -
159.28 -#Define digit mapping
159.29 -romanNumeralMap = (('M', 1000),
159.30 - ('CM', 900),
159.31 - ('D', 500),
159.32 - ('CD', 300),
159.33 - ('C', 100),
159.34 - ('XC', 90),
159.35 - ('L', 50),
159.36 - ('XL', 40),
159.37 - ('X', 10),
159.38 - ('IX', 9),
159.39 - ('V', 5),
159.40 - ('IV', 4),
159.41 - ('I', 1))
159.42 -
159.43 -#Create tables for fast conversion of roman numerals.
159.44 -#See fillLookupTables() below.
159.45 -toRomanTable = [ None ] # Skip an index since Roman numerals have no zero
159.46 -fromRomanTable = {}
159.47 -
159.48 -def toRoman(n):
159.49 - """convert integer to Roman numeral"""
159.50 - if not (0 < n <= MAX_ROMAN_NUMERAL):
159.51 - raise OutOfRangeError, "number out of range (must be 1..4999)"
159.52 - if int(n) <> n:
159.53 - raise NotIntegerError, "non-integers can not be converted"
159.54 - return toRomanTable[n]
159.55 -
159.56 -def fromRoman(s):
159.57 - """convert Roman numeral to integer"""
159.58 - if not s:
159.59 - raise InvalidRomanNumeralError, 'Input can not be blank'
159.60 - if not fromRomanTable.has_key(s):
159.61 - raise InvalidRomanNumeralError, 'Invalid Roman numeral: %s' % s
159.62 - return fromRomanTable[s]
159.63 -
159.64 -def toRomanDynamic(n):
159.65 - """convert integer to Roman numeral using dynamic programming"""
159.66 - assert(0 < n <= MAX_ROMAN_NUMERAL)
159.67 - assert(int(n) == n)
159.68 - result = ""
159.69 - for numeral, integer in romanNumeralMap:
159.70 - if n >= integer:
159.71 - result = numeral
159.72 - n -= integer
159.73 - break
159.74 - if n > 0:
159.75 - result += toRomanTable[n]
159.76 - return result
159.77 -
159.78 -def fillLookupTables():
159.79 - """compute all the possible roman numerals"""
159.80 - #Save the values in two global tables to convert to and from integers.
159.81 - for integer in range(1, MAX_ROMAN_NUMERAL + 1):
159.82 - romanNumber = toRomanDynamic(integer)
159.83 - toRomanTable.append(romanNumber)
159.84 - fromRomanTable[romanNumber] = integer
159.85 -
159.86 -fillLookupTables()
160.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj2/src/roman9.py.coverage.html Sun Jan 04 13:11:53 2015 -0600
160.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
160.3 @@ -1,98 +0,0 @@
160.4 -<html>
160.5 -<head>
160.6 -<style>
160.7 -div { white-space: pre; font-family: monospace; margin: 0px; padding: 0px }
160.8 -.covered { background-color: CCFFCC }
160.9 -.partial { background-color: FFFFCC }
160.10 -.not_covered { background-color: FFCCCC }
160.11 -.inferred { background-color: E0FFE0 }
160.12 -.unknown { background-color: EEEEEE }
160.13 -</style>
160.14 -</head>
160.15 -<body>
160.16 -<h1>File Coverage for roman9.py</h1>
160.17 -<div class="inferred">"""Convert to and from Roman numerals</div>
160.18 -<div class="inferred"></div>
160.19 -<div class="inferred">This program is part of "Dive Into Python", a free Python book for</div>
160.20 -<div class="inferred">experienced programmers. Visit http://diveintopython.org/ for the</div>
160.21 -<div class="inferred">latest version.</div>
160.22 -<div class="inferred">"""</div>
160.23 -<div class="inferred"></div>
160.24 -<div class="covered">__author__ = "Steve Lamm, Mark Pilgrim (mark@diveintopython.org)"</div>
160.25 -<div class="covered">__version__ = "$Revision: 1.3 $"</div>
160.26 -<div class="covered">__date__ = "$Date: 2004/05/05 21:57:20 $"</div>
160.27 -<div class="covered">__copyright__ = "Copyright (c) 2001 Steve Lamm, Copyright (c) 2001 Mark Pilgrim"</div>
160.28 -<div class="covered">__license__ = "Python"</div>
160.29 -<div class="inferred"></div>
160.30 -<div class="covered">import re</div>
160.31 -<div class="inferred"></div>
160.32 -<div class="inferred">#Define exceptions</div>
160.33 -<div class="covered">class RomanError(Exception): pass</div>
160.34 -<div class="covered">class OutOfRangeError(RomanError): pass</div>
160.35 -<div class="covered">class NotIntegerError(RomanError): pass</div>
160.36 -<div class="covered">class InvalidRomanNumeralError(RomanError): pass</div>
160.37 -<div class="inferred"></div>
160.38 -<div class="inferred">#Roman numerals must be less than 5000</div>
160.39 -<div class="covered">MAX_ROMAN_NUMERAL = 4999</div>
160.40 -<div class="inferred"></div>
160.41 -<div class="inferred">#Define digit mapping</div>
160.42 -<div class="covered">romanNumeralMap = (('M', 1000),</div>
160.43 -<div class="unknown"> ('CM', 900),</div>
160.44 -<div class="unknown"> ('D', 500),</div>
160.45 -<div class="unknown"> ('CD', 300),</div>
160.46 -<div class="unknown"> ('C', 100),</div>
160.47 -<div class="unknown"> ('XC', 90),</div>
160.48 -<div class="unknown"> ('L', 50),</div>
160.49 -<div class="unknown"> ('XL', 40),</div>
160.50 -<div class="unknown"> ('X', 10),</div>
160.51 -<div class="unknown"> ('IX', 9),</div>
160.52 -<div class="unknown"> ('V', 5),</div>
160.53 -<div class="unknown"> ('IV', 4),</div>
160.54 -<div class="unknown"> ('I', 1))</div>
160.55 -<div class="inferred"></div>
160.56 -<div class="inferred">#Create tables for fast conversion of roman numerals.</div>
160.57 -<div class="inferred">#See fillLookupTables() below.</div>
160.58 -<div class="covered">toRomanTable = [ None ] # Skip an index since Roman numerals have no zero</div>
160.59 -<div class="covered">fromRomanTable = {}</div>
160.60 -<div class="unknown"></div>
160.61 -<div class="covered">def toRoman(n):</div>
160.62 -<div class="covered"> """convert integer to Roman numeral"""</div>
160.63 -<div class="covered"> if not (0 < n <= MAX_ROMAN_NUMERAL):</div>
160.64 -<div class="covered"> raise OutOfRangeError, "number out of range (must be 1..4999)"</div>
160.65 -<div class="covered"> if int(n) <> n:</div>
160.66 -<div class="covered"> raise NotIntegerError, "non-integers can not be converted"</div>
160.67 -<div class="covered"> return toRomanTable[n]</div>
160.68 -<div class="unknown"></div>
160.69 -<div class="covered">def fromRoman(s):</div>
160.70 -<div class="covered"> """convert Roman numeral to integer"""</div>
160.71 -<div class="covered"> if not s:</div>
160.72 -<div class="covered"> raise InvalidRomanNumeralError, 'Input can not be blank'</div>
160.73 -<div class="covered"> if not fromRomanTable.has_key(s):</div>
160.74 -<div class="covered"> raise InvalidRomanNumeralError, 'Invalid Roman numeral: %s' % s</div>
160.75 -<div class="covered"> return fromRomanTable[s]</div>
160.76 -<div class="unknown"></div>
160.77 -<div class="covered">def toRomanDynamic(n):</div>
160.78 -<div class="covered"> """convert integer to Roman numeral using dynamic programming"""</div>
160.79 -<div class="covered"> assert(0 < n <= MAX_ROMAN_NUMERAL)</div>
160.80 -<div class="covered"> assert(int(n) == n)</div>
160.81 -<div class="covered"> result = ""</div>
160.82 -<div class="covered"> for numeral, integer in romanNumeralMap:</div>
160.83 -<div class="covered"> if n >= integer:</div>
160.84 -<div class="covered"> result = numeral</div>
160.85 -<div class="covered"> n -= integer</div>
160.86 -<div class="not_covered"> break </div>
160.87 -<div class="covered"> if n > 0:</div>
160.88 -<div class="covered"> result += toRomanTable[n]</div>
160.89 -<div class="covered"> return result</div>
160.90 -<div class="unknown"></div>
160.91 -<div class="covered">def fillLookupTables():</div>
160.92 -<div class="covered"> """compute all the possible roman numerals"""</div>
160.93 -<div class="inferred"> #Save the values in two global tables to convert to and from integers.</div>
160.94 -<div class="covered"> for integer in range(1, MAX_ROMAN_NUMERAL + 1):</div>
160.95 -<div class="covered"> romanNumber = toRomanDynamic(integer)</div>
160.96 -<div class="covered"> toRomanTable.append(romanNumber)</div>
160.97 -<div class="covered"> fromRomanTable[romanNumber] = integer</div>
160.98 -<div class="inferred"> </div>
160.99 -<div class="covered">fillLookupTables()</div>
160.100 -
160.101 -</body></html>
161.1 --- a/python.editor/test/unit/data/testfiles/codecoverage/CoveragePrj2/src/romantest9.py Sun Jan 04 13:11:53 2015 -0600
161.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
161.3 @@ -1,153 +0,0 @@
161.4 -"""Unit test for roman9.py
161.5 -
161.6 -This program is part of "Dive Into Python", a free Python book for
161.7 -experienced programmers. Visit http://diveintopython.org/ for the
161.8 -latest version.
161.9 -"""
161.10 -
161.11 -__author__ = "Mark Pilgrim (mark@diveintopython.org)"
161.12 -__version__ = "$Revision: 1.3 $"
161.13 -__date__ = "$Date: 2004/05/05 21:57:20 $"
161.14 -__copyright__ = "Copyright (c) 2001 Mark Pilgrim"
161.15 -__license__ = "Python"
161.16 -
161.17 -import roman9
161.18 -import unittest
161.19 -
161.20 -class KnownValues(unittest.TestCase):
161.21 - knownValues = ((1, 'I'),
161.22 - (2, 'II'),
161.23 - (3, 'III'),
161.24 - (4, 'IV'),
161.25 - (5, 'V'),
161.26 - (6, 'VI'),
161.27 - (7, 'VII'),
161.28 - (8, 'VIII'),
161.29 - (9, 'IX'),
161.30 - (10, 'X'),
161.31 - (50, 'L'),
161.32 - (100, 'C'),
161.33 - (500, 'D'),
161.34 - (1000, 'M'),
161.35 - (31, 'XXXI'),
161.36 - (148, 'CXLVIII'),
161.37 - (294, 'CCXCIV'),
161.38 - (312, 'CCCXII'),
161.39 - (421, 'CDXXI'),
161.40 - (528, 'DXXVIII'),
161.41 - (621, 'DCXXI'),
161.42 - (782, 'DCCLXXXII'),
161.43 - (870, 'DCCCLXX'),
161.44 - (941, 'CMXLI'),
161.45 - (1043, 'MXLIII'),
161.46 - (1110, 'MCX'),
161.47 - (1226, 'MCCXXVI'),
161.48 - (1301, 'MCCCI'),
161.49 - (1485, 'MCDLXXXV'),
161.50 - (1509, 'MDIX'),
161.51 - (1607, 'MDCVII'),
161.52 - (1754, 'MDCCLIV'),
161.53 - (1832, 'MDCCCXXXII'),
161.54 - (1993, 'MCMXCIII'),
161.55 - (2074, 'MMLXXIV'),
161.56 - (2152, 'MMCLII'),
161.57 - (2212, 'MMCCXII'),
161.58 - (2343, 'MMCCCXLIII'),
161.59 - (2499, 'MMCDXCIX'),
161.60 - (2574, 'MMDLXXIV'),
161.61 - (2646, 'MMDCXLVI'),
161.62 - (2723, 'MMDCCXXIII'),
161.63 - (2892, 'MMDCCCXCII'),
161.64 - (2975, 'MMCMLXXV'),
161.65 - (3051, 'MMMLI'),
161.66 - (3185, 'MMMCLXXXV'),
161.67 - (3250, 'MMMCCL'),
161.68 - (3313, 'MMMCCCXIII'),
161.69 - (3408, 'MMMCDVIII'),
161.70 - (3501, 'MMMDI'),
161.71 - (3610, 'MMMDCX'),
161.72 - (3743, 'MMMDCCXLIII'),
161.73 - (3844, 'MMMDCCCXLIV'),
161.74 - (3888, 'MMMDCCCLXXXVIII'),
161.75 - (3940, 'MMMCMXL'),
161.76 - (3999, 'MMMCMXCIX'),
161.77 - (4000, 'MMMM'),
161.78 - (4500, 'MMMMD'),
161.79 - (4888, 'MMMMDCCCLXXXVIII'),
161.80 - (4999, 'MMMMCMXCIX'))
161.81 -
161.82 - def testToRomanKnownValues(self):
161.83 - """toRoman should give known result with known input"""
161.84 - for integer, numeral in self.knownValues:
161.85 - result = roman9.toRoman(integer)
161.86 - self.assertEqual(numeral, result)
161.87 -
161.88 - def testFromRomanKnownValues(self):
161.89 - """fromRoman should give known result with known input"""
161.90 - for integer, numeral in self.knownValues:
161.91 - result = roman9.fromRoman(numeral)
161.92 - self.assertEqual(integer, result)
161.93 -
161.94 -class ToRomanBadInput(unittest.TestCase):
161.95 - def testTooLarge(self):
161.96 - """toRoman should fail with large input"""
161.97 - self.assertRaises(roman9.OutOfRangeError, roman9.toRoman, 5000)
161.98 -
161.99 - def testZero(self):
161.100 - """toRoman should fail with 0 input"""
161.101 - self.assertRaises(roman9.OutOfRangeError, roman9.toRoman, 0)
161.102 -
161.103 - def testNegative(self):
161.104 - """toRoman should fail with negative input"""
161.105 - self.assertRaises(roman9.OutOfRangeError, roman9.toRoman, -1)
161.106 -
161.107 - def testNonInteger(self):
161.108 - """toRoman should fail with non-integer input"""
161.109 - self.assertRaises(roman9.NotIntegerError, roman9.toRoman, 0.5)
161.110 -
161.111 -class FromRomanBadInput(unittest.TestCase):
161.112 - def testTooManyRepeatedNumerals(self):
161.113 - """fromRoman should fail with too many repeated numerals"""
161.114 - for s in ('MMMMM', 'DD', 'CCCC', 'LL', 'XXXX', 'VV', 'IIII'):
161.115 - self.assertRaises(roman9.InvalidRomanNumeralError, roman9.fromRoman, s)
161.116 -
161.117 - def testRepeatedPairs(self):
161.118 - """fromRoman should fail with repeated pairs of numerals"""
161.119 - for s in ('CMCM', 'CDCD', 'XCXC', 'XLXL', 'IXIX', 'IVIV'):
161.120 - self.assertRaises(roman9.InvalidRomanNumeralError, roman9.fromRoman, s)
161.121 -
161.122 - def testMalformedAntecedent(self):
161.123 - """fromRoman should fail with malformed antecedents"""
161.124 - for s in ('IIMXCC', 'VX', 'DCM', 'CMM', 'IXIV',
161.125 - 'MCMC', 'XCX', 'IVI', 'LM', 'LD', 'LC'):
161.126 - self.assertRaises(roman9.InvalidRomanNumeralError, roman9.fromRoman, s)
161.127 -
161.128 - def testBlank(self):
161.129 - """fromRoman should fail with blank string"""
161.130 - self.assertRaises(roman9.InvalidRomanNumeralError, roman9.fromRoman, "")
161.131 -
161.132 -class SanityCheck(unittest.TestCase):
161.133 - def testSanity(self):
161.134 - """fromRoman(toRoman(n))==n for all n"""
161.135 - for integer in range(1, 5000):
161.136 - numeral = roman9.toRoman(integer)
161.137 - result = roman9.fromRoman(numeral)
161.138 - self.assertEqual(integer, result)
161.139 -
161.140 -class CaseCheck(unittest.TestCase):
161.141 - def testToRomanCase(self):
161.142 - """toRoman should always return uppercase"""
161.143 - for integer in range(1, 5000):
161.144 - numeral = roman9.toRoman(integer)
161.145 - self.assertEqual(numeral, numeral.upper())
161.146 -
161.147 - def testFromRomanCase(self):
161.148 - """fromRoman should only accept uppercase input"""
161.149 - for integer in range(1, 5000):
161.150 - numeral = roman9.toRoman(integer)
161.151 - roman9.fromRoman(numeral.upper())
161.152 - self.assertRaises(roman9.InvalidRomanNumeralError,
161.153 - roman9.fromRoman, numeral.lower())
161.154 -
161.155 -if __name__ == "__main__":
161.156 - unittest.main()
162.1 --- a/python.editor/test/unit/data/testfiles/compl.py Sun Jan 04 13:11:53 2015 -0600
162.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
162.3 @@ -1,19 +0,0 @@
162.4 -class SuperSuper:
162.5 - def mysupersupermethod(self):
162.6 - print "World"
162.7 -
162.8 -class Super(SuperSuper):
162.9 - def mysupermethod(self):
162.10 - print "Hello"
162.11 -
162.12 -
162.13 -
162.14 -class MyClass(Super):
162.15 - def mymethod(self):
162.16 - print "Hello World"
162.17 - self.mysupersupermethod()
162.18 - print dir()
162.19 -
162.20 -x = MyClass()
162.21 -x.mymethod()
162.22 -
163.1 --- a/python.editor/test/unit/data/testfiles/compl.py.scopes Sun Jan 04 13:11:53 2015 -0600
163.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
163.3 @@ -1,34 +0,0 @@
163.4 -=============================================
163.5 -<file-top>: Module : OffsetRange[0,309>
163.6 -MyClass [bound][class][def][read][called][node=ClassDef]
163.7 -Super [bound][class][def][read][node=ClassDef]
163.8 -SuperSuper [bound][class][def][read][node=ClassDef]
163.9 -x [bound][data][read][node=Name]
163.10 -
163.11 - =============================================
163.12 - class SuperSuper: ClassDef : OffsetRange[0,75>
163.13 - mysupersupermethod [bound][function][def][node=FunctionDef]
163.14 -
163.15 - =============================================
163.16 - mysupersupermethod: FunctionDef : OffsetRange[22,75>
163.17 - self [bound][param][data][unused][node=Name]
163.18 -
163.19 - =============================================
163.20 - class Super: ClassDef : OffsetRange[75,154>
163.21 - mysupermethod [bound][function][def][node=FunctionDef]
163.22 -
163.23 - =============================================
163.24 - mysupermethod: FunctionDef : OffsetRange[104,154>
163.25 - self [bound][param][data][unused][node=Name]
163.26 -
163.27 - =============================================
163.28 - class MyClass: ClassDef : OffsetRange[154,283>
163.29 - mymethod [bound][function][def][node=FunctionDef]
163.30 -
163.31 - =============================================
163.32 - mymethod: FunctionDef : OffsetRange[180,283>
163.33 - dir [free][read][called][node=Name]
163.34 - self [bound][param][data][read][node=Name]
163.35 - ------ Attributes ---------------------------------------
163.36 - mysupersupermethod : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
163.37 -
164.1 --- a/python.editor/test/unit/data/testfiles/compl.py.testObjMethodCompletion1.completion Sun Jan 04 13:11:53 2015 -0600
164.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
164.3 @@ -1,1225 +0,0 @@
164.4 -Code completion result for source line:
164.5 -|self.mysupersupermethod()
164.6 -(QueryType=COMPLETION, NameKind=PREFIX)
164.7 -CLASS MyClass
164.8 -CLASS Super
164.9 -CLASS SuperSuper
164.10 -VARIABLE self
164.11 -VARIABLE x
164.12 -------------------------------------
164.13 -CLASS A
164.14 -CLASS ABCMeta
164.15 -CLASS AEServer
164.16 -CLASS AEText
164.17 -CLASS ASTVisitor
164.18 -CLASS AbstractBasicAuthHandler
164.19 -CLASS AbstractClassCode
164.20 -CLASS AbstractCompileMode
164.21 -CLASS AbstractDigestAuthHandler
164.22 -CLASS AbstractFormatter
164.23 -CLASS AbstractFunctionCode
164.24 -CLASS AbstractHTTPHandler
164.25 -CLASS AbstractWriter
164.26 -CLASS Add
164.27 -CLASS AddressList
164.28 -CLASS And
164.29 -CLASS Application
164.30 -CLASS ArgumentError
164.31 -CLASS ArithmeticError
164.32 -CLASS ArithmeticError
164.33 -CLASS Array
164.34 -CLASS ArrayInstance
164.35 -CLASS AssAttr
164.36 -CLASS AssList
164.37 -CLASS AssName
164.38 -CLASS AssTuple
164.39 -CLASS Assert
164.40 -CLASS AssertionError
164.41 -CLASS AssertionError
164.42 -CLASS Assign
164.43 -CLASS AsyncResult
164.44 -CLASS Attr
164.45 -CLASS AttributeError
164.46 -CLASS AttributeError
164.47 -CLASS AttributeList
164.48 -CLASS AttributeMap
164.49 -CLASS Attributes
164.50 -CLASS AttributesImpl
164.51 -CLASS AttributesNS
164.52 -CLASS AttributesNSImpl
164.53 -CLASS AugAssign
164.54 -CLASS AugGetattr
164.55 -CLASS AugName
164.56 -CLASS AugSlice
164.57 -CLASS AugSubscript
164.58 -CLASS AuthenticationError
164.59 -CLASS AutoGILError
164.60 -CLASS B
164.61 -CLASS BCPPCompiler
164.62 -CLASS BCPTestCase
164.63 -CLASS BZ2Compressor
164.64 -CLASS BZ2Decompressor
164.65 -CLASS BZ2File
164.66 -CLASS Babyl
164.67 -CLASS BabylMailbox
164.68 -CLASS BabylMessage
164.69 -CLASS Backquote
164.70 -CLASS BadBoundaryPointsErr
164.71 -CLASS BadFutureParser
164.72 -CLASS BadOptionError
164.73 -CLASS BadStatusLine
164.74 -CLASS BadZipfile
164.75 -CLASS Balloon
164.76 -CLASS Bar
164.77 -CLASS BaseCGIHandler
164.78 -CLASS BaseCookie
164.79 -CLASS BaseException
164.80 -CLASS BaseException
164.81 -CLASS BaseHTTPRequestHandler
164.82 -CLASS BaseHandler
164.83 -CLASS BaseIncrementalParser
164.84 -CLASS BaseManager
164.85 -CLASS BaseProxy
164.86 -CLASS BaseRequestHandler
164.87 -CLASS BaseRotatingHandler
164.88 -CLASS BaseSet
164.89 -CLASS BasicModuleImporter
164.90 -CLASS BasicModuleLoader
164.91 -CLASS BastionClass
164.92 -CLASS Baz
164.93 -CLASS Bdb
164.94 -CLASS BdbQuit
164.95 -CLASS BigEndianStructure
164.96 -CLASS Binary
164.97 -CLASS Bitand
164.98 -CLASS Bitor
164.99 -CLASS Bitxor
164.100 -CLASS Block
164.101 -CLASS BlockFinder
164.102 -CLASS BlockingIOError
164.103 -CLASS Boolean
164.104 -CLASS BoundaryError
164.105 -CLASS BoundedSemaphore
164.106 -CLASS Break
164.107 -CLASS Breakpoint
164.108 -CLASS BsdDbShelf
164.109 -CLASS BufferTooShort
164.110 -CLASS BufferedIOBase
164.111 -CLASS BufferedRWPair
164.112 -CLASS BufferedRandom
164.113 -CLASS BufferedReader
164.114 -CLASS BufferedWriter
164.115 -CLASS BufferingFormatter
164.116 -CLASS BufferingHandler
164.117 -CLASS BuildPyTestCase
164.118 -CLASS BuildScriptsTestCase
164.119 -CLASS BuiltinImporter
164.120 -CLASS Bulkcopy
164.121 -CLASS ButtonBox
164.122 -CLASS BytesIO
164.123 -CLASS C
164.124 -CLASS CAB
164.125 -CLASS CCompiler
164.126 -CLASS CCompilerError
164.127 -CLASS CDATASection
164.128 -CLASS CDLL
164.129 -CLASS CGIHTTPRequestHandler
164.130 -CLASS CGIHandler
164.131 -CLASS CGIXMLRPCRequestHandler
164.132 -CLASS CacheFTPHandler
164.133 -CLASS CallFunc
164.134 -CLASS CalledProcessError
164.135 -CLASS CannotSendHeader
164.136 -CLASS CannotSendRequest
164.137 -CLASS Canonizer
164.138 -CLASS CharacterData
164.139 -CLASS Charset
164.140 -CLASS CharsetError
164.141 -CLASS CheckList
164.142 -CLASS Childless
164.143 -CLASS Chunk
164.144 -CLASS Clamped
164.145 -CLASS Class
164.146 -CLASS ClassCodeGenerator
164.147 -CLASS ClassScope
164.148 -CLASS Cmd
164.149 -CLASS CodeGenerator
164.150 -CLASS Codec
164.151 -CLASS CodecRegistryError
164.152 -CLASS ComboBox
164.153 -CLASS Command
164.154 -CLASS CommandCompiler
164.155 -CLASS Comment
164.156 -CLASS Compare
164.157 -CLASS Comparison
164.158 -CLASS Compile
164.159 -CLASS CompileError
164.160 -CLASS Completer
164.161 -CLASS Complex
164.162 -CLASS ComponentItem
164.163 -CLASS Condition
164.164 -CLASS ConfigParser
164.165 -CLASS Connection
164.166 -CLASS Const
164.167 -CLASS ContentGenerator
164.168 -CLASS ContentHandler
164.169 -CLASS Context
164.170 -CLASS Continue
164.171 -CLASS Control
164.172 -CLASS ControlsWindow
164.173 -CLASS ConversionError
164.174 -CLASS Cookie
164.175 -CLASS CookieError
164.176 -CLASS CookieJar
164.177 -CLASS CookiePolicy
164.178 -CLASS CoverageResults
164.179 -CLASS Cursor
164.180 -CLASS CygwinCCompiler
164.181 -CLASS D
164.182 -CLASS DOMBuilder
164.183 -CLASS DOMEntityResolver
164.184 -CLASS DOMError
164.185 -CLASS DOMEventStream
164.186 -CLASS DOMException
164.187 -CLASS DOMImplementation
164.188 -CLASS DOMInputSource
164.189 -CLASS DOMStringSizeErr
164.190 -CLASS DTDHandler
164.191 -CLASS Data
164.192 -CLASS Database
164.193 -CLASS DatagramHandler
164.194 -CLASS DatagramRequestHandler
164.195 -CLASS DateTime
164.196 -CLASS DbfilenameShelf
164.197 -CLASS DebugRunner
164.198 -CLASS DebuggingServer
164.199 -CLASS Decimal
164.200 -CLASS DecimalException
164.201 -CLASS DeclHandler
164.202 -CLASS DecodedGenerator
164.203 -CLASS Decorators
164.204 -CLASS DefaultCookiePolicy
164.205 -CLASS DefaultHandler
164.206 -CLASS Delegator
164.207 -CLASS DeprecationWarning
164.208 -CLASS DeprecationWarning
164.209 -CLASS Dialect
164.210 -CLASS Dialog
164.211 -CLASS DialogWindow
164.212 -CLASS Dict
164.213 -CLASS DictMixin
164.214 -CLASS DictReader
164.215 -CLASS DictWriter
164.216 -CLASS Differ
164.217 -CLASS DirList
164.218 -CLASS DirSelectBox
164.219 -CLASS DirSelectDialog
164.220 -CLASS DirTree
164.221 -CLASS Directory
164.222 -CLASS Discard
164.223 -CLASS Distribution
164.224 -CLASS DistributionMetadata
164.225 -CLASS DistributionTestCase
164.226 -CLASS DistutilsArgError
164.227 -CLASS DistutilsClassError
164.228 -CLASS DistutilsError
164.229 -CLASS DistutilsExecError
164.230 -CLASS DistutilsFileError
164.231 -CLASS DistutilsGetoptError
164.232 -CLASS DistutilsInternalError
164.233 -CLASS DistutilsModuleError
164.234 -CLASS DistutilsOptionError
164.235 -CLASS DistutilsPlatformError
164.236 -CLASS DistutilsSetupError
164.237 -CLASS DistutilsTemplateError
164.238 -CLASS Div
164.239 -CLASS DivisionByZero
164.240 -CLASS Doc
164.241 -CLASS DocCGIXMLRPCRequestHandler
164.242 -CLASS DocTest
164.243 -CLASS DocTestFailure
164.244 -CLASS DocTestFinder
164.245 -CLASS DocTestParser
164.246 -CLASS DocTestRunner
164.247 -CLASS DocXMLRPCRequestHandler
164.248 -CLASS DocXMLRPCServer
164.249 -CLASS Document
164.250 -CLASS DocumentFragment
164.251 -CLASS DocumentHandler
164.252 -CLASS DocumentType
164.253 -CLASS DomstringSizeErr
164.254 -CLASS DumbWriter
164.255 -CLASS DummyCommand
164.256 -CLASS DuplicateSectionError
164.257 -CLASS DynLoadSuffixImporter
164.258 -CLASS EMXCCompiler
164.259 -CLASS EOFError
164.260 -CLASS EOFError
164.261 -CLASS ESISDocHandler
164.262 -CLASS Element
164.263 -CLASS ElementInfo
164.264 -CLASS ElementTree
164.265 -CLASS Ellipsis
164.266 -CLASS Empty
164.267 -CLASS EmptyNode
164.268 -CLASS EndOfBlock
164.269 -CLASS Entity
164.270 -CLASS EntityResolver
164.271 -CLASS Enum
164.272 -CLASS EnvironmentError
164.273 -CLASS EnvironmentError
164.274 -CLASS Error
164.275 -CLASS ErrorDuringImport
164.276 -CLASS ErrorHandler
164.277 -CLASS ErrorPrinter
164.278 -CLASS ErrorRaiser
164.279 -CLASS Event
164.280 -CLASS EventBroadcaster
164.281 -CLASS EventException
164.282 -CLASS ExFileSelectBox
164.283 -CLASS Example
164.284 -CLASS ExampleASTVisitor
164.285 -CLASS Exception
164.286 -CLASS Exception
164.287 -CLASS Exec
164.288 -CLASS ExitNow
164.289 -CLASS ExpatError
164.290 -CLASS ExpatParser
164.291 -CLASS Expression
164.292 -CLASS ExpressionCodeGenerator
164.293 -CLASS Extension
164.294 -CLASS F
164.295 -CLASS FTP
164.296 -CLASS FTPHandler
164.297 -CLASS Factory
164.298 -CLASS FancyGetopt
164.299 -CLASS FancyModuleLoader
164.300 -CLASS FancyURLopener
164.301 -CLASS Fault
164.302 -CLASS Feature
164.303 -CLASS FeedParser
164.304 -CLASS FieldStorage
164.305 -CLASS FileCookieJar
164.306 -CLASS FileEntry
164.307 -CLASS FileHandler
164.308 -CLASS FileIO
164.309 -CLASS FileInput
164.310 -CLASS FileList
164.311 -CLASS FileSelectBox
164.312 -CLASS FileWrapper
164.313 -CLASS Filter
164.314 -CLASS Filterer
164.315 -CLASS FingerHandler
164.316 -CLASS FirstHeaderLineIsContinuationD
164.317 -CLASS FloatingPointError
164.318 -CLASS FloatingPointError
164.319 -CLASS FloorDiv
164.320 -CLASS FlowGraph
164.321 -CLASS Folder
164.322 -CLASS Foo
164.323 -CLASS For
164.324 -CLASS ForkingMixIn
164.325 -CLASS ForkingTCPServer
164.326 -CLASS ForkingUDPServer
164.327 -CLASS Form
164.328 -CLASS FormContent
164.329 -CLASS FormContentDict
164.330 -CLASS Formatter
164.331 -CLASS Fraction
164.332 -CLASS From
164.333 -CLASS FtException
164.334 -CLASS Full
164.335 -CLASS FuncPtr
164.336 -CLASS Function
164.337 -CLASS FunctionCodeGenerator
164.338 -CLASS FunctionScope
164.339 -CLASS FunctionTestCase
164.340 -CLASS FutureParser
164.341 -CLASS FutureWarning
164.342 -CLASS FutureWarning
164.343 -CLASS GNUTranslations
164.344 -CLASS GenExpr
164.345 -CLASS GenExprFor
164.346 -CLASS GenExprIf
164.347 -CLASS GenExprInner
164.348 -CLASS GenExprScope
164.349 -CLASS Generator
164.350 -CLASS GeneratorExit
164.351 -CLASS GeneratorExit
164.352 -CLASS Getattr
164.353 -CLASS GetattrMagic
164.354 -CLASS GetoptError
164.355 -CLASS Global
164.356 -CLASS GopherError
164.357 -CLASS GopherHandler
164.358 -CLASS GridBag
164.359 -CLASS GzipFile
164.360 -CLASS HList
164.361 -CLASS HMAC
164.362 -CLASS HRESULT
164.363 -CLASS HTMLDoc
164.364 -CLASS HTMLParseError
164.365 -CLASS HTMLParser
164.366 -CLASS HTMLRepr
164.367 -CLASS HTTP
164.368 -CLASS HTTPBasicAuthHandler
164.369 -CLASS HTTPConnection
164.370 -CLASS HTTPCookieProcessor
164.371 -CLASS HTTPDefaultErrorHandler
164.372 -CLASS HTTPDigestAuthHandler
164.373 -CLASS HTTPError
164.374 -CLASS HTTPErrorProcessor
164.375 -CLASS HTTPException
164.376 -CLASS HTTPHandler
164.377 -CLASS HTTPPasswordMgr
164.378 -CLASS HTTPPasswordMgrWithDefaultReal
164.379 -CLASS HTTPRedirectHandler
164.380 -CLASS HTTPResponse
164.381 -CLASS HTTPSConnection
164.382 -CLASS HTTPSHandler
164.383 -CLASS HTTPServer
164.384 -CLASS Handler
164.385 -CLASS HandlerBase
164.386 -CLASS Header
164.387 -CLASS HeaderParseError
164.388 -CLASS HeaderParser
164.389 -CLASS Headers
164.390 -CLASS HelpFormatter
164.391 -CLASS Helper
164.392 -CLASS HierarchyRequestErr
164.393 -CLASS Hook
164.394 -CLASS Hooks
164.395 -CLASS HtmlDiff
164.396 -CLASS IC
164.397 -CLASS IMAP4
164.398 -CLASS IMAP4_SSL
164.399 -CLASS IMAP4_stream
164.400 -CLASS IOBase
164.401 -CLASS IOError
164.402 -CLASS IOError
164.403 -CLASS Identified
164.404 -CLASS If
164.405 -CLASS IfExp
164.406 -CLASS Ignore
164.407 -CLASS IllegalMonthError
164.408 -CLASS IllegalWeekdayError
164.409 -CLASS ImmutableSet
164.410 -CLASS ImpImporter
164.411 -CLASS ImpLoader
164.412 -CLASS Import
164.413 -CLASS ImportError
164.414 -CLASS ImportError
164.415 -CLASS ImportManager
164.416 -CLASS ImportWarning
164.417 -CLASS ImportWarning
164.418 -CLASS Importer
164.419 -CLASS ImproperConnectionState
164.420 -CLASS Incomplete
164.421 -CLASS IncompleteRead
164.422 -CLASS IncrementalDecoder
164.423 -CLASS IncrementalEncoder
164.424 -CLASS IncrementalNewlineDecoder
164.425 -CLASS IncrementalParser
164.426 -CLASS IndentedHelpFormatter
164.427 -CLASS IndexError
164.428 -CLASS IndexError
164.429 -CLASS IndexSizeErr
164.430 -CLASS Inexact
164.431 -CLASS IniParser
164.432 -CLASS InputOnly
164.433 -CLASS InputSource
164.434 -CLASS InsertionLoc
164.435 -CLASS InstallScriptsTestCase
164.436 -CLASS InstallTestCase
164.437 -CLASS Integral
164.438 -CLASS Interactive
164.439 -CLASS InteractiveCodeGenerator
164.440 -CLASS InteractiveConsole
164.441 -CLASS InteractiveInterpreter
164.442 -CLASS InterpFormContentDict
164.443 -CLASS InterpolationDepthError
164.444 -CLASS InterpolationError
164.445 -CLASS InterpolationSyntaxError
164.446 -CLASS IntlText
164.447 -CLASS IntlWritingCode
164.448 -CLASS InuseAttributeErr
164.449 -CLASS InvalidAccessErr
164.450 -CLASS InvalidCharacterErr
164.451 -CLASS InvalidModificationErr
164.452 -CLASS InvalidNodeTypeErr
164.453 -CLASS InvalidOperation
164.454 -CLASS InvalidStateErr
164.455 -CLASS InvalidURL
164.456 -CLASS Invert
164.457 -CLASS IsqlCmd
164.458 -CLASS IsqlExit
164.459 -CLASS IterableUserDict
164.460 -CLASS JSONDecoder
164.461 -CLASS JSONEncoder
164.462 -CLASS JavaSAXParser
164.463 -CLASS JoinableQueue
164.464 -CLASS JyDTDHandlerWrapper
164.465 -CLASS JyEntityResolverWrapper
164.466 -CLASS JyErrorHandlerWrapper
164.467 -CLASS JyInputSourceWrapper
164.468 -CLASS JythonCompiler
164.469 -CLASS JythonSignalHandler
164.470 -CLASS KeyError
164.471 -CLASS KeyError
164.472 -CLASS KeyboardInterrupt
164.473 -CLASS KeyboardInterrupt
164.474 -CLASS Keyword
164.475 -CLASS LOBTestCase
164.476 -CLASS LWPCookieJar
164.477 -CLASS LabelEntry
164.478 -CLASS LabelFrame
164.479 -CLASS Lambda
164.480 -CLASS LambdaScope
164.481 -CLASS LargeZipFile
164.482 -CLASS LeftShift
164.483 -CLASS LexicalHandler
164.484 -CLASS LexicalXMLGenerator
164.485 -CLASS LibError
164.486 -CLASS LibraryLoader
164.487 -CLASS LineAddrTable
164.488 -CLASS LinkError
164.489 -CLASS List
164.490 -CLASS ListComp
164.491 -CLASS ListCompFor
164.492 -CLASS ListCompIf
164.493 -CLASS ListNoteBook
164.494 -CLASS Listener
164.495 -CLASS LittleEndianStructure
164.496 -CLASS LoadError
164.497 -CLASS LocalNameFinder
164.498 -CLASS Location
164.499 -CLASS Locator
164.500 -CLASS Lock
164.501 -CLASS Log
164.502 -CLASS LogRecord
164.503 -CLASS Logger
164.504 -CLASS LoggingSilencer
164.505 -CLASS Logical
164.506 -CLASS LookupError
164.507 -CLASS LookupError
164.508 -CLASS LooseVersion
164.509 -CLASS MH
164.510 -CLASS MHMailbox
164.511 -CLASS MHMessage
164.512 -CLASS MIMEApplication
164.513 -CLASS MIMEAudio
164.514 -CLASS MIMEBase
164.515 -CLASS MIMEImage
164.516 -CLASS MIMEMessage
164.517 -CLASS MIMEMultipart
164.518 -CLASS MIMENonMultipart
164.519 -CLASS MIMEText
164.520 -CLASS MMDF
164.521 -CLASS MMDFMessage
164.522 -CLASS MSVCCompiler
164.523 -CLASS MWerksCompiler
164.524 -CLASS MacroExpander
164.525 -CLASS Mailbox
164.526 -CLASS Maildir
164.527 -CLASS MaildirMessage
164.528 -CLASS MailmanProxy
164.529 -CLASS MalformedHeaderDefect
164.530 -CLASS Manager
164.531 -CLASS Marshaller
164.532 -CLASS MemoryError
164.533 -CLASS MemoryError
164.534 -CLASS MemoryHandler
164.535 -CLASS Message
164.536 -CLASS MessageDefect
164.537 -CLASS MessageError
164.538 -CLASS MessageParseError
164.539 -CLASS MetadataTestCase
164.540 -CLASS Meter
164.541 -CLASS MimeWriter
164.542 -CLASS Mingw32CCompiler
164.543 -CLASS MiniApplication
164.544 -CLASS MiniFieldStorage
164.545 -CLASS MisplacedEnvelopeHeaderDefect
164.546 -CLASS MissingSectionHeaderError
164.547 -CLASS MmdfMailbox
164.548 -CLASS Mod
164.549 -CLASS Model
164.550 -CLASS Module
164.551 -CLASS ModuleCodeGenerator
164.552 -CLASS ModuleFinder
164.553 -CLASS ModuleImporter
164.554 -CLASS ModuleLoader
164.555 -CLASS ModuleScanner
164.556 -CLASS ModuleScope
164.557 -CLASS MozillaCookieJar
164.558 -CLASS Mul
164.559 -CLASS MultiCall
164.560 -CLASS MultiCallIterator
164.561 -CLASS MultiFile
164.562 -CLASS MultipartConversionError
164.563 -CLASS MultipartInvariantViolationDef
164.564 -CLASS MutableString
164.565 -CLASS MyClass
164.566 -CLASS MyTest
164.567 -CLASS NNTP
164.568 -CLASS NNTPDataError
164.569 -CLASS NNTPPermanentError
164.570 -CLASS NNTPProtocolError
164.571 -CLASS NNTPReplyError
164.572 -CLASS NNTPTemporaryError
164.573 -CLASS NProperty
164.574 -CLASS NTEventLogHandler
164.575 -CLASS NULL
164.576 -CLASS Name
164.577 -CLASS NameError
164.578 -CLASS NameError
164.579 -CLASS NamedNodeMap
164.580 -CLASS NamespaceErr
164.581 -CLASS NannyNag
164.582 -CLASS NestedScopeMixin
164.583 -CLASS Netrc
164.584 -CLASS NetrcParseError
164.585 -CLASS NewStyle
164.586 -CLASS NoBoundaryInMultipartDefect
164.587 -CLASS NoDataAllowedErr
164.588 -CLASS NoModificationAllowedErr
164.589 -CLASS NoOpMetaClass
164.590 -CLASS NoOptionError
164.591 -CLASS NoSectionError
164.592 -CLASS Node
164.593 -CLASS NodeFilter
164.594 -CLASS NodeTransformer
164.595 -CLASS NodeVisitor
164.596 -CLASS Not
164.597 -CLASS NotANumber
164.598 -CLASS NotConnected
164.599 -CLASS NotFoundErr
164.600 -CLASS NotImplementedError
164.601 -CLASS NotImplementedError
164.602 -CLASS NotSupportedErr
164.603 -CLASS Notation
164.604 -CLASS NoteBook
164.605 -CLASS NullFormatter
164.606 -CLASS NullImporter
164.607 -CLASS NullTranslations
164.608 -CLASS NullWriter
164.609 -CLASS Number
164.610 -CLASS OSError
164.611 -CLASS OSError
164.612 -CLASS OSSAudioError
164.613 -CLASS ObjectSpecifier
164.614 -CLASS OleDLL
164.615 -CLASS OpFinder
164.616 -CLASS OpenerDirector
164.617 -CLASS OptParseError
164.618 -CLASS Option
164.619 -CLASS OptionConflictError
164.620 -CLASS OptionContainer
164.621 -CLASS OptionDummy
164.622 -CLASS OptionError
164.623 -CLASS OptionGroup
164.624 -CLASS OptionMenu
164.625 -CLASS OptionParser
164.626 -CLASS OptionValueError
164.627 -CLASS Or
164.628 -CLASS OracleSPTest
164.629 -CLASS Ordinal
164.630 -CLASS OutputChecker
164.631 -CLASS Overflow
164.632 -CLASS OverflowError
164.633 -CLASS OverflowError
164.634 -CLASS POP3
164.635 -CLASS POP3_SSL
164.636 -CLASS Packer
164.637 -CLASS PanedWindow
164.638 -CLASS Panel
164.639 -CLASS Parser
164.640 -CLASS ParserBase
164.641 -CLASS ParserError
164.642 -CLASS ParsingError
164.643 -CLASS Pass
164.644 -CLASS Pattern
164.645 -CLASS Pdb
164.646 -CLASS PendingDeprecationWarning
164.647 -CLASS PendingDeprecationWarning
164.648 -CLASS PickleError
164.649 -CLASS Pickler
164.650 -CLASS PicklingError
164.651 -CLASS PlaceHolder
164.652 -CLASS Popen
164.653 -CLASS Popen3
164.654 -CLASS Popen4
164.655 -CLASS PopupMenu
164.656 -CLASS PortableUnixMailbox
164.657 -CLASS Power
164.658 -CLASS PreprocessError
164.659 -CLASS PrettyPrinter
164.660 -CLASS Print
164.661 -CLASS Printnl
164.662 -CLASS Process
164.663 -CLASS ProcessingInstruction
164.664 -CLASS Profile
164.665 -CLASS ProgressBar
164.666 -CLASS Prompt
164.667 -CLASS ProtocolError
164.668 -CLASS ProxyBasicAuthHandler
164.669 -CLASS ProxyDigestAuthHandler
164.670 -CLASS ProxyHandler
164.671 -CLASS PullDOM
164.672 -CLASS PureProxy
164.673 -CLASS PyCompileError
164.674 -CLASS PyDLL
164.675 -CLASS PyDialog
164.676 -CLASS PyFlowGraph
164.677 -CLASS PyHKEY
164.678 -CLASS PyZipFile
164.679 -CLASS QDPoint
164.680 -CLASS QDRectangle
164.681 -CLASS QName
164.682 -CLASS Queue
164.683 -CLASS RExec
164.684 -CLASS RGBColor
164.685 -CLASS RLock
164.686 -CLASS RadioButtonGroup
164.687 -CLASS Raise
164.688 -CLASS Random
164.689 -CLASS Range
164.690 -CLASS RangeException
164.691 -CLASS Rational
164.692 -CLASS RawIOBase
164.693 -CLASS RawTurtle
164.694 -CLASS ReadOnlySequentialNamedNodeMap
164.695 -CLASS Real
164.696 -CLASS Record
164.697 -CLASS ReferenceError
164.698 -CLASS ReferenceError
164.699 -CLASS Repr
164.700 -CLASS Request
164.701 -CLASS ResponseError
164.702 -CLASS ResponseNotReady
164.703 -CLASS ResultSet
164.704 -CLASS ResultSetRow
164.705 -CLASS Return
164.706 -CLASS RightShift
164.707 -CLASS RobotFileParser
164.708 -CLASS RootLogger
164.709 -CLASS RotatingFileHandler
164.710 -CLASS Rounded
164.711 -CLASS Row
164.712 -CLASS RuntimeError
164.713 -CLASS RuntimeError
164.714 -CLASS RuntimeWarning
164.715 -CLASS RuntimeWarning
164.716 -CLASS SAX2DOM
164.717 -CLASS SAXException
164.718 -CLASS SAXNotRecognizedException
164.719 -CLASS SAXNotSupportedException
164.720 -CLASS SAXParseException
164.721 -CLASS SAXReaderNotAvailable
164.722 -CLASS SGMLParseError
164.723 -CLASS SGMLParser
164.724 -CLASS SMTP
164.725 -CLASS SMTPAuthenticationError
164.726 -CLASS SMTPConnectError
164.727 -CLASS SMTPDataError
164.728 -CLASS SMTPException
164.729 -CLASS SMTPHandler
164.730 -CLASS SMTPHeloError
164.731 -CLASS SMTPRecipientsRefused
164.732 -CLASS SMTPResponseException
164.733 -CLASS SMTPSenderRefused
164.734 -CLASS SMTPServer
164.735 -CLASS SMTPServerDisconnected
164.736 -CLASS SQLServerSPTest
164.737 -CLASS SQLTestCase
164.738 -CLASS SSLError
164.739 -CLASS SSLSocket
164.740 -CLASS ST
164.741 -CLASS SafeConfigParser
164.742 -CLASS SafeTransport
164.743 -CLASS Scanner
164.744 -CLASS Schema
164.745 -CLASS Scope
164.746 -CLASS Screen
164.747 -CLASS ScrolledCavas
164.748 -CLASS ScrolledText
164.749 -CLASS ScrolledWindow
164.750 -CLASS Select
164.751 -CLASS Semaphore
164.752 -CLASS SequenceMatcher
164.753 -CLASS SerialCookie
164.754 -CLASS Server
164.755 -CLASS ServerHTMLDoc
164.756 -CLASS ServerProxy
164.757 -CLASS Set
164.758 -CLASS SgmlopParser
164.759 -CLASS Shape
164.760 -CLASS Shelf
164.761 -CLASS SimpleCookie
164.762 -CLASS SimpleHTTPRequestHandler
164.763 -CLASS SimpleHandler
164.764 -CLASS SimpleLocator
164.765 -CLASS SimpleXMLRPCDispatcher
164.766 -CLASS SimpleXMLRPCRequestHandler
164.767 -CLASS SimpleXMLRPCServer
164.768 -CLASS Slice
164.769 -CLASS Sliceobj
164.770 -CLASS SlowParser
164.771 -CLASS SmartCookie
164.772 -CLASS Sniffer
164.773 -CLASS SocketHandler
164.774 -CLASS SocketType
164.775 -CLASS Stack
164.776 -CLASS StackDepthTracker
164.777 -CLASS StandardError
164.778 -CLASS StandardError
164.779 -CLASS StartBoundaryNotFoundDefect
164.780 -CLASS Stats
164.781 -CLASS StdButtonBox
164.782 -CLASS Stmt
164.783 -CLASS StopIteration
164.784 -CLASS StopIteration
164.785 -CLASS StopTokenizing
164.786 -CLASS Strange
164.787 -CLASS StreamConverter
164.788 -CLASS StreamHandler
164.789 -CLASS StreamReader
164.790 -CLASS StreamRequestHandler
164.791 -CLASS StreamWriter
164.792 -CLASS StrictVersion
164.793 -CLASS StringIO
164.794 -CLASS Struct
164.795 -CLASS Structure
164.796 -CLASS StyledText
164.797 -CLASS Sub
164.798 -CLASS SubPattern
164.799 -CLASS Subnormal
164.800 -CLASS Subscript
164.801 -CLASS SummaryInformation
164.802 -CLASS Super
164.803 -CLASS SuperSuper
164.804 -CLASS SvFormContentDict
164.805 -CLASS Symbol
164.806 -CLASS SymbolTable
164.807 -CLASS SymbolVisitor
164.808 -CLASS SyncManager
164.809 -CLASS SyntaxErr
164.810 -CLASS SyntaxError
164.811 -CLASS SyntaxError
164.812 -CLASS SyntaxErrorChecker
164.813 -CLASS SyntaxWarning
164.814 -CLASS SyntaxWarning
164.815 -CLASS SysLogHandler
164.816 -CLASS SystemError
164.817 -CLASS SystemError
164.818 -CLASS SystemExit
164.819 -CLASS SystemExit
164.820 -CLASS SystemRandom
164.821 -CLASS TCPServer
164.822 -CLASS TList
164.823 -CLASS TalkTo
164.824 -CLASS TarError
164.825 -CLASS TarFile
164.826 -CLASS TarInfo
164.827 -CLASS Telnet
164.828 -CLASS TempdirManager
164.829 -CLASS Template
164.830 -CLASS Test
164.831 -CLASS TestCase
164.832 -CLASS TestClass
164.833 -CLASS TestCrispinTorture
164.834 -CLASS TestDistribution
164.835 -CLASS TestLoader
164.836 -CLASS TestResult
164.837 -CLASS TestSuite
164.838 -CLASS TestThread
164.839 -CLASS TestXMLParser
164.840 -CLASS Testcase
164.841 -CLASS Tester
164.842 -CLASS Text
164.843 -CLASS TextDoc
164.844 -CLASS TextFile
164.845 -CLASS TextIOBase
164.846 -CLASS TextIOWrapper
164.847 -CLASS TextRepr
164.848 -CLASS TextTestRunner
164.849 -CLASS TextWrapper
164.850 -CLASS Textbox
164.851 -CLASS Thread
164.852 -CLASS ThreadingMixIn
164.853 -CLASS ThreadingTCPServer
164.854 -CLASS ThreadingUDPServer
164.855 -CLASS ThreadingUnixDatagramServer
164.856 -CLASS ThreadingUnixStreamServer
164.857 -CLASS TimedRotatingFileHandler
164.858 -CLASS Timer
164.859 -CLASS TitledHelpFormatter
164.860 -CLASS Tix
164.861 -CLASS Tk
164.862 -CLASS TokenError
164.863 -CLASS Tokenizer
164.864 -CLASS TortureBase
164.865 -CLASS Trace
164.866 -CLASS Transformer
164.867 -CLASS Transport
164.868 -CLASS Tree
164.869 -CLASS TreeBuilder
164.870 -CLASS TryExcept
164.871 -CLASS TryFinally
164.872 -CLASS Tuple
164.873 -CLASS TupleArg
164.874 -CLASS Turtle
164.875 -CLASS TurtleScreen
164.876 -CLASS Type
164.877 -CLASS TypeError
164.878 -CLASS TypeError
164.879 -CLASS TypeInfo
164.880 -CLASS UDPServer
164.881 -CLASS URLError
164.882 -CLASS UUID
164.883 -CLASS UnaryAdd
164.884 -CLASS UnarySub
164.885 -CLASS UnboundLocalError
164.886 -CLASS UnboundLocalError
164.887 -CLASS Underflow
164.888 -CLASS UnexpectedException
164.889 -CLASS UnicodeDecodeError
164.890 -CLASS UnicodeDecodeError
164.891 -CLASS UnicodeEncodeError
164.892 -CLASS UnicodeEncodeError
164.893 -CLASS UnicodeError
164.894 -CLASS UnicodeError
164.895 -CLASS UnicodeTranslateError
164.896 -CLASS UnicodeTranslateError
164.897 -CLASS UnicodeWarning
164.898 -CLASS UnicodeWarning
164.899 -CLASS UnimplementedFileMode
164.900 -CLASS Union
164.901 -CLASS UnixCCompiler
164.902 -CLASS UnixDatagramServer
164.903 -CLASS UnixMailbox
164.904 -CLASS UnixStreamServer
164.905 -CLASS Unknown
164.906 -CLASS UnknownFileError
164.907 -CLASS UnknownHandler
164.908 -CLASS UnknownProtocol
164.909 -CLASS UnknownTransferEncoding
164.910 -CLASS Unload
164.911 -CLASS Unmarshaller
164.912 -CLASS Unpacker
164.913 -CLASS Unpickler
164.914 -CLASS UnpicklingError
164.915 -CLASS UnspecifiedEventTypeErr
164.916 -CLASS UnsupportedOperation
164.917 -CLASS UserDataHandler
164.918 -CLASS UserDict
164.919 -CLASS UserList
164.920 -CLASS UserString
164.921 -CLASS UserWarning
164.922 -CLASS UserWarning
164.923 -CLASS ValidationErr
164.924 -CLASS ValueError
164.925 -CLASS ValueError
164.926 -CLASS Values
164.927 -CLASS Vec2D
164.928 -CLASS Vendor
164.929 -CLASS Version
164.930 -CLASS VersionPredicate
164.931 -CLASS View
164.932 -CLASS WSGIRequestHandler
164.933 -CLASS WSGIServer
164.934 -CLASS Warning
164.935 -CLASS Warning
164.936 -CLASS Wave_read
164.937 -CLASS Wave_write
164.938 -CLASS WeakKeyDictionary
164.939 -CLASS WeakValueDictionary
164.940 -CLASS While
164.941 -CLASS WichmannHill
164.942 -CLASS WinDLL
164.943 -CLASS Window
164.944 -CLASS WindowsError
164.945 -CLASS WindowsError
164.946 -CLASS With
164.947 -CLASS WrongDocumentErr
164.948 -CLASS X
164.949 -CLASS XMLFilter
164.950 -CLASS XMLFilterBase
164.951 -CLASS XMLFilterImpl
164.952 -CLASS XMLGenerator
164.953 -CLASS XMLParser
164.954 -CLASS XMLRPCDocGenerator
164.955 -CLASS XMLReader
164.956 -CLASS XMLTreeBuilder
164.957 -CLASS XmlParseErr
164.958 -CLASS Yield
164.959 -CLASS Yuck
164.960 -CLASS ZeroDivisionError
164.961 -CLASS ZeroDivisionError
164.962 -CLASS ZipFile
164.963 -CLASS ZipImportError
164.964 -CLASS ZipInfo
164.965 -CLASS _CData [PROTECTE
164.966 -CLASS _FuncPtr [PROTECTE
164.967 -CLASS _SimpleCData [PROTECTE
164.968 -CLASS _posixfile_
164.969 -CLASS array
164.970 -CLASS async_chat
164.971 -CLASS bdist
164.972 -CLASS bdist_dumb
164.973 -CLASS bdist_msi
164.974 -CLASS bdist_rpm
164.975 -CLASS bdist_wininst
164.976 -CLASS bool
164.977 -CLASS bsddbobject
164.978 -CLASS build
164.979 -CLASS build_clib
164.980 -CLASS build_ext
164.981 -CLASS build_py
164.982 -CLASS build_scripts
164.983 -CLASS c_bool
164.984 -CLASS c_byte
164.985 -CLASS c_char
164.986 -CLASS c_char_p
164.987 -CLASS c_double
164.988 -CLASS c_float
164.989 -CLASS c_int
164.990 -CLASS c_int16
164.991 -CLASS c_int32
164.992 -CLASS c_int64
164.993 -CLASS c_int8
164.994 -CLASS c_long
164.995 -CLASS c_longdouble
164.996 -CLASS c_longlong
164.997 -CLASS c_short
164.998 -CLASS c_size_t
164.999 -CLASS c_ubyte
164.1000 -CLASS c_uint
164.1001 -CLASS c_uint16
164.1002 -CLASS c_uint32
164.1003 -CLASS c_uint64
164.1004 -CLASS c_uint8
164.1005 -CLASS c_ulong
164.1006 -CLASS c_ulonglong
164.1007 -CLASS c_ushort
164.1008 -CLASS c_void_p
164.1009 -CLASS c_wchar
164.1010 -CLASS c_wchar_p
164.1011 -CLASS class
164.1012 -CLASS class
164.1013 -CLASS clean
164.1014 -CLASS closing
164.1015 -CLASS complex
164.1016 -CLASS compressobj
164.1017 -CLASS config
164.1018 -CLASS container
164.1019 -CLASS container
164.1020 -CLASS contextmanager
164.1021 -CLASS contextmanager
164.1022 -CLASS controller
164.1023 -CLASS date
164.1024 -CLASS datetime
164.1025 -CLASS dbexts
164.1026 -CLASS dbextsTestCase
164.1027 -CLASS dbhash
164.1028 -CLASS decompressobj
164.1029 -CLASS deque
164.1030 -CLASS dict
164.1031 -CLASS dict
164.1032 -CLASS dircmp
164.1033 -CLASS dispatcher
164.1034 -CLASS dispatcher_with_send
164.1035 -CLASS dl
164.1036 -CLASS error
164.1037 -CLASS error_data
164.1038 -CLASS excel
164.1039 -CLASS excel_tab
164.1040 -CLASS executor
164.1041 -CLASS fifo
164.1042 -CLASS file
164.1043 -CLASS file
164.1044 -CLASS file_dispatcher
164.1045 -CLASS file_wrapper
164.1046 -CLASS float
164.1047 -CLASS float
164.1048 -CLASS foo
164.1049 -CLASS gaierror
164.1050 -CLASS herror
164.1051 -CLASS install
164.1052 -CLASS install_data
164.1053 -CLASS install_egg_info
164.1054 -CLASS install_headers
164.1055 -CLASS install_lib
164.1056 -CLASS install_misc
164.1057 -CLASS install_scripts
164.1058 -CLASS instance
164.1059 -CLASS instance
164.1060 -CLASS int
164.1061 -CLASS iterator
164.1062 -CLASS iterator
164.1063 -CLASS list
164.1064 -CLASS local
164.1065 -CLASS lock
164.1066 -CLASS long
164.1067 -CLASS main
164.1068 -CLASS mbox
164.1069 -CLASS mboxMessage
164.1070 -CLASS mllib
164.1071 -CLASS mmap
164.1072 -CLASS multiprocessing.Pool
164.1073 -CLASS mutex
164.1074 -CLASS mxODBCProxy
164.1075 -CLASS netrc
164.1076 -CLASS object
164.1077 -CLASS object
164.1078 -CLASS oss_audio_device
164.1079 -CLASS oss_mixer_device
164.1080 -CLASS poll
164.1081 -CLASS py_object
164.1082 -CLASS register
164.1083 -CLASS scheduler
164.1084 -CLASS sdist
164.1085 -CLASS set
164.1086 -CLASS set
164.1087 -CLASS shlex
164.1088 -CLASS simple_producer
164.1089 -CLASS socket
164.1090 -CLASS stat_result
164.1091 -CLASS str
164.1092 -CLASS str
164.1093 -CLASS test_dist
164.1094 -CLASS test_zxjdbc
164.1095 -CLASS time
164.1096 -CLASS timedelta
164.1097 -CLASS timeout
164.1098 -CLASS tixCommand
164.1099 -CLASS tmxxx
164.1100 -CLASS tuple
164.1101 -CLASS tzinfo
164.1102 -CLASS unicode
164.1103 -CLASS unicode
164.1104 -CLASS upload
164.1105 -CLASS window
164.1106 -CLASS xmlparser
164.1107 -CLASS zipimporter
164.1108 -CLASS zxAPITestCase
164.1109 -CLASS zxCoreTestCase
164.1110 -CLASS zxJDBCTestCase
164.1111 -METHOD __import__(name, globals, loca
164.1112 -METHOD abs(x)
164.1113 -METHOD all(iterable)
164.1114 -METHOD any(iterable)
164.1115 -METHOD ---apply(function, args, ke---
164.1116 -METHOD basestring()
164.1117 -METHOD bin(x)
164.1118 -METHOD bool(x)
164.1119 -METHOD buffer(object, offset, size)
164.1120 -METHOD callable(object)
164.1121 -METHOD chr(i)
164.1122 -METHOD classmethod(function)
164.1123 -METHOD cmp(x, y)
164.1124 -METHOD coerce(x, y)
164.1125 -METHOD compile(source, filename, mode
164.1126 -METHOD complex(real, imag)
164.1127 -METHOD delattr(object, name)
164.1128 -METHOD dict(arg)
164.1129 -METHOD dir(object)
164.1130 -METHOD divmod(a, b)
164.1131 -METHOD enumerate(sequence, start)
164.1132 -METHOD eval(expression, globals, loca
164.1133 -METHOD execfile(filename, globals, lo
164.1134 -METHOD exit(code)
164.1135 -METHOD file(filename, mode, bufsize)
164.1136 -METHOD filter(function, iterable)
164.1137 -METHOD float(x)
164.1138 -METHOD frozenset(iterable)
164.1139 -METHOD getattr(object, name, default)
164.1140 -METHOD globals()
164.1141 -METHOD hasattr(object, name)
164.1142 -METHOD hash(object)
164.1143 -METHOD help(object)
164.1144 -METHOD hex(x)
164.1145 -METHOD id(object)
164.1146 -METHOD input(prompt)
164.1147 -METHOD int(x, radix)
164.1148 -METHOD intern(string)
164.1149 -METHOD isinstance(object, classinfo)
164.1150 -METHOD issubclass(class, classinfo)
164.1151 -METHOD iter(o, sentinel)
164.1152 -METHOD len(s)
164.1153 -METHOD list(iterable)
164.1154 -METHOD locals()
164.1155 -METHOD long(x, radix)
164.1156 -METHOD map(function, iterable)
164.1157 -METHOD max(iterable, argskey)
164.1158 -METHOD min(iterable, argskey)
164.1159 -METHOD next(iterator, default)
164.1160 -METHOD object()
164.1161 -METHOD oct(x)
164.1162 -METHOD open(filename, mode, bufsize)
164.1163 -METHOD ord(c)
164.1164 -METHOD pow(x, y, z)
164.1165 -METHOD print(object, sep, end, file)
164.1166 -METHOD property(fget, fset, fdel, doc
164.1167 -METHOD quit(code)
164.1168 -METHOD range(start, stop, step)
164.1169 -METHOD raw_input(prompt)
164.1170 -METHOD reduce(function, iterable, ini
164.1171 -METHOD reload(module)
164.1172 -METHOD repr(object)
164.1173 -METHOD reversed(seq)
164.1174 -METHOD round(x, n)
164.1175 -METHOD set(iterable)
164.1176 -METHOD setattr(object, name, value)
164.1177 -METHOD slice(start, stop, step)
164.1178 -METHOD sorted(iterable, cmp, key, rev
164.1179 -METHOD staticmethod(function)
164.1180 -METHOD str(object)
164.1181 -METHOD sum(iterable, start)
164.1182 -METHOD super(type, object-or-type)
164.1183 -METHOD tuple(iterable)
164.1184 -METHOD type(name, bases, dict)
164.1185 -METHOD type(object)
164.1186 -METHOD unichr(i)
164.1187 -METHOD unicode(object, encoding, erro
164.1188 -METHOD vars(object)
164.1189 -METHOD xrange(start, stop, step)
164.1190 -METHOD zip(iterable)
164.1191 -VARIABLE Ellipsis
164.1192 -VARIABLE False
164.1193 -VARIABLE None
164.1194 -VARIABLE NotImplemented
164.1195 -VARIABLE True
164.1196 -VARIABLE __debug__
164.1197 -VARIABLE copyright
164.1198 -KEYWORD and
164.1199 -KEYWORD as
164.1200 -KEYWORD assert
164.1201 -KEYWORD break
164.1202 -KEYWORD class
164.1203 -KEYWORD continue
164.1204 -KEYWORD def
164.1205 -KEYWORD del
164.1206 -KEYWORD elif
164.1207 -KEYWORD else
164.1208 -KEYWORD except
164.1209 -KEYWORD exec
164.1210 -KEYWORD finally
164.1211 -KEYWORD for
164.1212 -KEYWORD from
164.1213 -KEYWORD global
164.1214 -KEYWORD if
164.1215 -KEYWORD import
164.1216 -KEYWORD in
164.1217 -KEYWORD is
164.1218 -KEYWORD lambda
164.1219 -KEYWORD not
164.1220 -KEYWORD or
164.1221 -KEYWORD pass
164.1222 -KEYWORD print
164.1223 -KEYWORD raise
164.1224 -KEYWORD return
164.1225 -KEYWORD try
164.1226 -KEYWORD while
164.1227 -KEYWORD with
164.1228 -KEYWORD yield
165.1 --- a/python.editor/test/unit/data/testfiles/compl.py.testObjMethodCompletion2.completion Sun Jan 04 13:11:53 2015 -0600
165.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
165.3 @@ -1,10 +0,0 @@
165.4 -Code completion result for source line:
165.5 -self.|mysupersupermethod()
165.6 -(QueryType=COMPLETION, NameKind=PREFIX)
165.7 -METHOD mymethod()
165.8 -METHOD mysupermethod()
165.9 -METHOD mysupersupermethod()
165.10 -------------------------------------
165.11 -ATTRIBUTE __dict__
165.12 -ATTRIBUTE ---__members__ ---
165.13 -ATTRIBUTE ---__methods__ ---
166.1 --- a/python.editor/test/unit/data/testfiles/compl2.py Sun Jan 04 13:11:53 2015 -0600
166.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
166.3 @@ -1,15 +0,0 @@
166.4 -import sys as whatever
166.5 -import os
166.6 -
166.7 -print whatever.r
166.8 -print os.r
166.9 -print sys.getfilesysteme
166.10 -
166.11 -myvar = file()
166.12 -myvar.close()
166.13 -
166.14 -myothervar = ZipFile()
166.15 -myothervar.x
166.16 -
166.17 -unknown.fai
166.18 -
167.1 --- a/python.editor/test/unit/data/testfiles/compl2.py.testObjMethodCompletion3.completion Sun Jan 04 13:11:53 2015 -0600
167.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
167.3 @@ -1,7 +0,0 @@
167.4 -Code completion result for source line:
167.5 -print w|hatever.r
167.6 -(QueryType=COMPLETION, NameKind=PREFIX)
167.7 -MODULE whatever
167.8 -------------------------------------
167.9 -KEYWORD while
167.10 -KEYWORD with
168.1 --- a/python.editor/test/unit/data/testfiles/compl2.py.testObjMethodCompletion4.completion Sun Jan 04 13:11:53 2015 -0600
168.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
168.3 @@ -1,58 +0,0 @@
168.4 -Code completion result for source line:
168.5 -print whatever.|r
168.6 -(QueryType=COMPLETION, NameKind=PREFIX)
168.7 -METHOD displayhook(value)
168.8 -METHOD exc_clear()
168.9 -METHOD exc_info()
168.10 -METHOD excepthook(type, value, traceb
168.11 -METHOD exit(arg)
168.12 -METHOD getcheckinterval()
168.13 -METHOD getdefaultencoding()
168.14 -METHOD getdlopenflags()
168.15 -METHOD getfilesystemencoding()
168.16 -METHOD getprofile()
168.17 -METHOD getrecursionlimit()
168.18 -METHOD getrefcount(object)
168.19 -METHOD getsizeof(object, default)
168.20 -METHOD gettrace()
168.21 -METHOD getwindowsversion()
168.22 -METHOD setcheckinterval(interval)
168.23 -METHOD setdefaultencoding(name)
168.24 -METHOD setdlopenflags(n)
168.25 -METHOD setprofile(profilefunc)
168.26 -METHOD setrecursionlimit(limit)
168.27 -METHOD settrace(tracefunc)
168.28 -METHOD settscdump(on_flag)
168.29 -VARIABLE __displayhook__
168.30 -VARIABLE __stdin__
168.31 -VARIABLE api_version
168.32 -VARIABLE argv
168.33 -VARIABLE builtin_module_names
168.34 -VARIABLE byteorder
168.35 -VARIABLE copyright
168.36 -VARIABLE dllhandle
168.37 -VARIABLE dont_write_bytecode
168.38 -VARIABLE ---exc_type ---
168.39 -VARIABLE exec_prefix
168.40 -VARIABLE executable
168.41 -VARIABLE ---exitfunc ---
168.42 -VARIABLE flags
168.43 -VARIABLE float_info
168.44 -VARIABLE hexversion
168.45 -VARIABLE last_type
168.46 -VARIABLE maxint
168.47 -VARIABLE maxsize
168.48 -VARIABLE maxunicode
168.49 -VARIABLE modules
168.50 -VARIABLE path
168.51 -VARIABLE platform
168.52 -VARIABLE prefix
168.53 -VARIABLE ps1
168.54 -VARIABLE py3kwarning
168.55 -VARIABLE stdin
168.56 -VARIABLE subversion
168.57 -VARIABLE tracebacklimit
168.58 -VARIABLE version
168.59 -VARIABLE version_info
168.60 -VARIABLE warnoptions
168.61 -VARIABLE winver
169.1 --- a/python.editor/test/unit/data/testfiles/compl2.py.testObjMethodCompletion5.completion Sun Jan 04 13:11:53 2015 -0600
169.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
169.3 @@ -1,492 +0,0 @@
169.4 -Code completion result for source line:
169.5 -print whatever.r|
169.6 -(QueryType=COMPLETION, NameKind=PREFIX)
169.7 -------------------------------------
169.8 -METHOD r_eval(code)
169.9 -METHOD r_exec(code)
169.10 -METHOD r_execfile(filename)
169.11 -METHOD r_import(modulename, globals,
169.12 -METHOD r_open(filename, mode, bufsize
169.13 -METHOD r_reload(module)
169.14 -METHOD r_unload(module)
169.15 -METHOD radiogroup(name, x, y, width,
169.16 -METHOD radix()
169.17 -METHOD radix()
169.18 -METHOD raise_exc(exc_class, message)
169.19 -METHOD raise_stmt(nodelist)
169.20 -METHOD randint(a, b)
169.21 -METHOD random()
169.22 -METHOD random()
169.23 -METHOD randrange(start, stop, step, i
169.24 -METHOD ratio()
169.25 -METHOD raw(sql, params, bindings, del
169.26 -METHOD raw_decode(s)
169.27 -METHOD raw_input(prompt)
169.28 -METHOD rawq_getchar()
169.29 -METHOD rcpt(recip, options)
169.30 -METHOD read()
169.31 -METHOD read()
169.32 -METHOD read()
169.33 -METHOD read(amt)
169.34 -METHOD read(args)
169.35 -METHOD ---read(f, n) ---
169.36 -METHOD read(filenames)
169.37 -METHOD read(n)
169.38 -METHOD read(n)
169.39 -METHOD read(n)
169.40 -METHOD read(n)
169.41 -METHOD read(n)
169.42 -METHOD read(n)
169.43 -METHOD read(n)
169.44 -METHOD read(name)
169.45 -METHOD read(nbytes)
169.46 -METHOD read(num)
169.47 -METHOD read(size)
169.48 -METHOD read(size)
169.49 -METHOD read(size)
169.50 -METHOD read(size)
169.51 -METHOD read(size)
169.52 -METHOD read(size)
169.53 -METHOD read(size)
169.54 -METHOD read(size)
169.55 -METHOD read1()
169.56 -METHOD read1(n)
169.57 -METHOD read_all()
169.58 -METHOD read_binary()
169.59 -METHOD read_byte()
169.60 -METHOD read_eager()
169.61 -METHOD read_file(filename, mode)
169.62 -METHOD read_lazy()
169.63 -METHOD read_lines()
169.64 -METHOD read_lines_to_eof()
169.65 -METHOD read_lines_to_outerboundary()
169.66 -METHOD read_manifest()
169.67 -METHOD read_module(modname, mode)
169.68 -METHOD read_multi(environ, keep_blank
169.69 -METHOD read_sb_data()
169.70 -METHOD read_single()
169.71 -METHOD read_some()
169.72 -METHOD read_template()
169.73 -METHOD read_token()
169.74 -METHOD read_until(match, timeout)
169.75 -METHOD read_urlencoded()
169.76 -METHOD read_very_eager()
169.77 -METHOD read_very_lazy()
169.78 -METHOD readable()
169.79 -METHOD readable()
169.80 -METHOD readable()
169.81 -METHOD readall()
169.82 -METHOD readall()
169.83 -METHOD readfp(fp, filename)
169.84 -METHOD readframes(n)
169.85 -METHOD readheaders()
169.86 -METHOD readinto(b)
169.87 -METHOD readinto(b)
169.88 -METHOD readline()
169.89 -METHOD readline()
169.90 -METHOD readline()
169.91 -METHOD readline()
169.92 -METHOD readline()
169.93 -METHOD readline()
169.94 -METHOD readline()
169.95 -METHOD readline()
169.96 -METHOD readline(length)
169.97 -METHOD readline(limit)
169.98 -METHOD readline(size)
169.99 -METHOD readline(size)
169.100 -METHOD readline(size)
169.101 -METHOD readlines()
169.102 -METHOD readlines()
169.103 -METHOD readlines()
169.104 -METHOD readlines(hint)
169.105 -METHOD readlines(size)
169.106 -METHOD readlines(sizehint)
169.107 -METHOD readlines(sizehint)
169.108 -METHOD readlines(sizehint)
169.109 -METHOD ready()
169.110 -METHOD real_quick_ratio()
169.111 -METHOD reccontrols()
169.112 -METHOD recent()
169.113 -METHOD recv()
169.114 -METHOD recv(args)
169.115 -METHOD recv(buffer_size)
169.116 -METHOD recv_bytes(maxlength)
169.117 -METHOD recv_bytes_into(buffer, offset
169.118 -METHOD redirect_internal(url, fp, err
169.119 -METHOD redirect_request(req, fp, code
169.120 -METHOD redrawln(beg, num)
169.121 -METHOD redrawwin()
169.122 -METHOD reduce_uri(uri, default_port)
169.123 -METHOD refilemessages(list, tofolder,
169.124 -METHOD refill_buffer()
169.125 -METHOD refresh(pminrow, pmincol, smin
169.126 -METHOD refuse_compilation(args, kwarg
169.127 -METHOD register(socket_object, mask)
169.128 -METHOD register(subclass)
169.129 -METHOD register(typeid, callable, pro
169.130 -METHOD register_function(function, na
169.131 -METHOD register_instance(instance, al
169.132 -METHOD register_introspection_functio
169.133 -METHOD register_multicall_functions()
169.134 -METHOD reinitialize_command(command,
169.135 -METHOD reinitialize_command(command,
169.136 -METHOD release()
169.137 -METHOD release()
169.138 -METHOD release()
169.139 -METHOD release()
169.140 -METHOD release_poll_object(pobj)
169.141 -METHOD reload(module)
169.142 -METHOD reload(module, path)
169.143 -METHOD remainder(a, b)
169.144 -METHOD remainder_near(a, b)
169.145 -METHOD remainder_near(other, context)
169.146 -METHOD remove()
169.147 -METHOD remove(elem)
169.148 -METHOD remove(element)
169.149 -METHOD remove(elt)
169.150 -METHOD remove(item)
169.151 -METHOD remove(key)
169.152 -METHOD remove(key)
169.153 -METHOD remove(key)
169.154 -METHOD remove(key)
169.155 -METHOD remove(x)
169.156 -METHOD removeAttribute(name)
169.157 -METHOD removeAttributeNS(namespaceURI
169.158 -METHOD removeAttributeNode(node)
169.159 -METHOD removeAttributeNodeNS(node)
169.160 -METHOD removeChild(oldChild)
169.161 -METHOD removeChild(oldChild)
169.162 -METHOD removeChild(oldChild)
169.163 -METHOD removeChild(oldChild)
169.164 -METHOD removeFilter(filter)
169.165 -METHOD removeHandler(hdlr)
169.166 -METHOD removeHandler(hdlr)
169.167 -METHOD removeNamedItem(name)
169.168 -METHOD removeNamedItem(name)
169.169 -METHOD removeNamedItem(name)
169.170 -METHOD removeNamedItemNS(namespaceURI
169.171 -METHOD removeNamedItemNS(namespaceURI
169.172 -METHOD removeNamedItemNS(namespaceURI
169.173 -METHOD remove_duplicates()
169.174 -METHOD remove_flag(flag)
169.175 -METHOD remove_folder(folder)
169.176 -METHOD remove_folder(folder)
169.177 -METHOD remove_label(label)
169.178 -METHOD remove_option(opt_str)
169.179 -METHOD remove_option(section, option)
169.180 -METHOD remove_pyc()
169.181 -METHOD remove_section(section)
169.182 -METHOD remove_sequence(sequence)
169.183 -METHOD removefromallsequences(list)
169.184 -METHOD removemessages(list)
169.185 -METHOD rename(fromname, toname)
169.186 -METHOD rename(oldmailbox, newmailbox)
169.187 -METHOD renameNode(n, namespaceURI, na
169.188 -METHOD repeat(repeat, number)
169.189 -METHOD replace(hour, minute, second,
169.190 -METHOD replace(hour, minute, second,
169.191 -METHOD replace(old, new)
169.192 -METHOD replace(old, new, count)
169.193 -METHOD replace(old, new, maxsplit)
169.194 -METHOD replace(win)
169.195 -METHOD replace(year, month, day)
169.196 -METHOD replace(year, month, day)
169.197 -METHOD replace(year, month, day, hour
169.198 -METHOD replaceChild(newChild, oldChil
169.199 -METHOD replaceChild(newChild, oldChil
169.200 -METHOD replaceChild(newChild, oldChil
169.201 -METHOD replaceData(offset, count, arg
169.202 -METHOD replaceWholeText(content)
169.203 -METHOD replace_header(_name, _value)
169.204 -METHOD replace_paths_in_code(co)
169.205 -METHOD report()
169.206 -METHOD report()
169.207 -METHOD report_404()
169.208 -METHOD report_failure(out, test, exam
169.209 -METHOD report_failure(out, test, exam
169.210 -METHOD report_full_closure()
169.211 -METHOD report_partial_closure()
169.212 -METHOD report_start(out, test, exampl
169.213 -METHOD report_success(out, test, exam
169.214 -METHOD report_unbalanced(tag)
169.215 -METHOD report_unexpected_exception(ou
169.216 -METHOD report_unexpected_exception(ou
169.217 -METHOD repr(object)
169.218 -METHOD repr(x)
169.219 -METHOD repr1(x, level)
169.220 -METHOD repr1(x, level)
169.221 -METHOD repr1(x, level)
169.222 -METHOD repr_array(x, level)
169.223 -METHOD repr_deque(x, level)
169.224 -METHOD repr_dict(x, level)
169.225 -METHOD repr_frozenset(x, level)
169.226 -METHOD repr_instance(x, level)
169.227 -METHOD repr_instance(x, level)
169.228 -METHOD repr_instance(x, level)
169.229 -METHOD repr_list(x, level)
169.230 -METHOD repr_long(x, level)
169.231 -METHOD repr_set(x, level)
169.232 -METHOD repr_str(x, level)
169.233 -METHOD repr_str(x, level)
169.234 -METHOD repr_str(x, level)
169.235 -METHOD repr_string(x, level)
169.236 -METHOD repr_string(x, level)
169.237 -METHOD repr_tuple(x, level)
169.238 -METHOD repr_unicode(x, level)
169.239 -METHOD request(host, handler, request
169.240 -METHOD request(method, url, body, hea
169.241 -METHOD reset()
169.242 -METHOD reset()
169.243 -METHOD reset()
169.244 -METHOD reset()
169.245 -METHOD reset()
169.246 -METHOD reset()
169.247 -METHOD reset()
169.248 -METHOD reset()
169.249 -METHOD reset()
169.250 -METHOD reset()
169.251 -METHOD reset()
169.252 -METHOD reset()
169.253 -METHOD reset()
169.254 -METHOD reset()
169.255 -METHOD reset()
169.256 -METHOD reset()
169.257 -METHOD reset()
169.258 -METHOD reset()
169.259 -METHOD reset(data)
169.260 -METHOD reset_retry_count()
169.261 -METHOD resetbuffer()
169.262 -METHOD resize(newsize)
169.263 -METHOD resolveEntity(pubId, sysId)
169.264 -METHOD resolveEntity(publicId, system
169.265 -METHOD resolveEntity(publicId, system
169.266 -METHOD resolveEntity(publicId, system
169.267 -METHOD resolveEntity(publicId, system
169.268 -METHOD response(code)
169.269 -METHOD result_is_file()
169.270 -METHOD results()
169.271 -METHOD retr(which)
169.272 -METHOD retrbinary(cmd, callback, bloc
169.273 -METHOD retrieve(url, filename, report
169.274 -METHOD retrlines(cmd, callback)
169.275 -METHOD retry_http_basic_auth(host, re
169.276 -METHOD retry_http_basic_auth(url, rea
169.277 -METHOD retry_http_digest_auth(req, au
169.278 -METHOD retry_https_basic_auth(url, re
169.279 -METHOD retry_proxy_http_basic_auth(ur
169.280 -METHOD retry_proxy_https_basic_auth(u
169.281 -METHOD return_ok(cookie, request)
169.282 -METHOD return_ok(cookie, request)
169.283 -METHOD return_ok_domain(cookie, reque
169.284 -METHOD return_ok_expires(cookie, requ
169.285 -METHOD return_ok_port(cookie, request
169.286 -METHOD return_ok_secure(cookie, reque
169.287 -METHOD return_ok_verifiability(cookie
169.288 -METHOD return_ok_version(cookie, requ
169.289 -METHOD return_stmt(nodelist)
169.290 -METHOD reverse()
169.291 -METHOD reverse()
169.292 -METHOD reverse()
169.293 -METHOD reverse_order()
169.294 -METHOD revert(filename, ignore_discar
169.295 -METHOD rewind()
169.296 -METHOD rewind()
169.297 -METHOD rewindbody()
169.298 -METHOD rfind(string, start, end)
169.299 -METHOD rfind(sub)
169.300 -METHOD rfind(sub, start, end)
169.301 -METHOD rfind(sub, start, end)
169.302 -METHOD rindex(sub)
169.303 -METHOD rindex(sub, start, end)
169.304 -METHOD rindex(sub, start, end)
169.305 -METHOD rjust(width)
169.306 -METHOD rjust(width, args)
169.307 -METHOD rjust(width, fillchar)
169.308 -METHOD rmd(dirname)
169.309 -METHOD rollback()
169.310 -METHOD rollback()
169.311 -METHOD rotate(a, b)
169.312 -METHOD rotate(other, context)
169.313 -METHOD rowxfer(line)
169.314 -METHOD rpartition(sep)
169.315 -METHOD rpartition(sep)
169.316 -METHOD rpartition(sep)
169.317 -METHOD rpop(user)
169.318 -METHOD rset()
169.319 -METHOD rset()
169.320 -METHOD rsplit()
169.321 -METHOD rsplit(sep, maxsplit)
169.322 -METHOD rsplit(sep, maxsplit)
169.323 -METHOD rstrip()
169.324 -METHOD rstrip(chars)
169.325 -METHOD rstrip(chars)
169.326 -METHOD run()
169.327 -METHOD run()
169.328 -METHOD run()
169.329 -METHOD run()
169.330 -METHOD run()
169.331 -METHOD run()
169.332 -METHOD run()
169.333 -METHOD run()
169.334 -METHOD run()
169.335 -METHOD run()
169.336 -METHOD run()
169.337 -METHOD run()
169.338 -METHOD run()
169.339 -METHOD run()
169.340 -METHOD run()
169.341 -METHOD run()
169.342 -METHOD run()
169.343 -METHOD run()
169.344 -METHOD run()
169.345 -METHOD run()
169.346 -METHOD run()
169.347 -METHOD run()
169.348 -METHOD run()
169.349 -METHOD run()
169.350 -METHOD run()
169.351 -METHOD run()
169.352 -METHOD run(application)
169.353 -METHOD run(callback, key, completer)
169.354 -METHOD run(cmd)
169.355 -METHOD run(cmd)
169.356 -METHOD run(cmd)
169.357 -METHOD run(cmd, globals, locals)
169.358 -METHOD run(result)
169.359 -METHOD run(result)
169.360 -METHOD run(test)
169.361 -METHOD run(test, compileflags, out, c
169.362 -METHOD run(test, compileflags, out, c
169.363 -METHOD runTest()
169.364 -METHOD run__test__(d, name)
169.365 -METHOD run_cgi()
169.366 -METHOD run_command(command)
169.367 -METHOD run_command(command)
169.368 -METHOD run_commands()
169.369 -METHOD run_script(pathname)
169.370 -METHOD runcall(func, *args, **keyword
169.371 -METHOD runcall(func, args, kw)
169.372 -METHOD runcall(func, args, kwds)
169.373 -METHOD runcode(code)
169.374 -METHOD runctx(cmd, globals, locals)
169.375 -METHOD runctx(cmd, globals, locals)
169.376 -METHOD runctx(cmd, globals, locals)
169.377 -METHOD runctx(cmd, globals, locals)
169.378 -METHOD rundict(d, name, module)
169.379 -METHOD rundoc(object, name, module)
169.380 -METHOD runeval(expr, globals, locals)
169.381 -METHOD runfunc(func, args, kw)
169.382 -METHOD runsource(source, filename, sy
169.383 -METHOD runstring(s, name)
169.384 -METHOD runtime_library_dir_option(dir
169.385 -METHOD runtime_library_dir_option(dir
169.386 -METHOD runtime_library_dir_option(dir
169.387 -METHOD runtime_library_dir_option(dir
169.388 -VARIABLE rargs
169.389 -VARIABLE raw
169.390 -VARIABLE raw_requestline
169.391 -VARIABLE raw_requestline
169.392 -VARIABLE rawdata
169.393 -VARIABLE rawdata
169.394 -VARIABLE rawdata
169.395 -VARIABLE rawq
169.396 -VARIABLE rbufsize
169.397 -VARIABLE rbufsize
169.398 -VARIABLE rc
169.399 -VARIABLE rcLines
169.400 -VARIABLE re_var
169.401 -VARIABLE read
169.402 -VARIABLE read
169.403 -VARIABLE read
169.404 -VARIABLE read
169.405 -VARIABLE read_func
169.406 -VARIABLE reader
169.407 -VARIABLE reader
169.408 -VARIABLE reader
169.409 -VARIABLE readfile
169.410 -VARIABLE readline
169.411 -VARIABLE readline
169.412 -VARIABLE readline
169.413 -VARIABLE readlines
169.414 -VARIABLE readlines
169.415 -VARIABLE realpos
169.416 -VARIABLE realsock
169.417 -VARIABLE reason
169.418 -VARIABLE reason
169.419 -VARIABLE recipients
169.420 -VARIABLE record
169.421 -VARIABLE records
169.422 -VARIABLE recv
169.423 -VARIABLE recvfrom
169.424 -VARIABLE reference
169.425 -VARIABLE relative
169.426 -VARIABLE relativeCreated
169.427 -VARIABLE release
169.428 -VARIABLE repeat
169.429 -VARIABLE replace_paths
169.430 -VARIABLE replace_whitespace
169.431 -VARIABLE repository
169.432 -VARIABLE repository
169.433 -VARIABLE repr
169.434 -VARIABLE request
169.435 -VARIABLE request_queue_size
169.436 -VARIABLE request_version
169.437 -VARIABLE requestline
169.438 -VARIABLE requires
169.439 -VARIABLE requires
169.440 -VARIABLE res_extension
169.441 -VARIABLE res_extension
169.442 -VARIABLE res_extension
169.443 -VARIABLE reserved
169.444 -VARIABLE response
169.445 -VARIABLE response_class
169.446 -VARIABLE responses
169.447 -VARIABLE restkey
169.448 -VARIABLE restval
169.449 -VARIABLE restype
169.450 -VARIABLE result
169.451 -VARIABLE results
169.452 -VARIABLE results
169.453 -VARIABLE retried
169.454 -VARIABLE retryFactor
169.455 -VARIABLE retryMax
169.456 -VARIABLE retryPeriod
169.457 -VARIABLE retryStart
169.458 -VARIABLE retryTime
169.459 -VARIABLE returncode
169.460 -VARIABLE returnframe
169.461 -VARIABLE rfc2109
169.462 -VARIABLE rfc2109_as_netscape
169.463 -VARIABLE rfc2965
169.464 -VARIABLE rfile
169.465 -VARIABLE right
169.466 -VARIABLE right
169.467 -VARIABLE right_list
169.468 -VARIABLE right_only
169.469 -VARIABLE rlen
169.470 -VARIABLE rng
169.471 -VARIABLE rng
169.472 -VARIABLE rolloverAt
169.473 -VARIABLE root
169.474 -VARIABLE root
169.475 -VARIABLE root
169.476 -VARIABLE root
169.477 -VARIABLE roots
169.478 -VARIABLE rounding
169.479 -VARIABLE row
169.480 -VARIABLE rows
169.481 -VARIABLE rpath
169.482 -VARIABLE rpc_paths
169.483 -VARIABLE rpm3_mode
169.484 -VARIABLE rpm_base
169.485 -VARIABLE rs
169.486 -VARIABLE rulelines
169.487 -VARIABLE ruler
169.488 -VARIABLE runtime_library_dirs
169.489 -VARIABLE runtime_library_dirs
169.490 -VARIABLE rx
169.491 -ATTRIBUTE real
169.492 -ATTRIBUTE real
169.493 -ATTRIBUTE restype
169.494 -ATTRIBUTE row_factory
169.495 -ATTRIBUTE rowcount
170.1 --- a/python.editor/test/unit/data/testfiles/compl2.py.testObjMethodCompletion6.completion Sun Jan 04 13:11:53 2015 -0600
170.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
170.3 @@ -1,5 +0,0 @@
170.4 -Code completion result for source line:
170.5 -print sys.getfile|systeme
170.6 -(QueryType=COMPLETION, NameKind=PREFIX)
170.7 -------------------------------------
170.8 -METHOD getfile()
171.1 --- a/python.editor/test/unit/data/testfiles/compl2.py.testObjMethodCompletion7.completion Sun Jan 04 13:11:53 2015 -0600
171.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
171.3 @@ -1,76 +0,0 @@
171.4 -Code completion result for source line:
171.5 -print os.|r
171.6 -(QueryType=COMPLETION, NameKind=PREFIX)
171.7 -MODULE altsep
171.8 -MODULE curdir
171.9 -MODULE defpath
171.10 -MODULE pardir
171.11 -MODULE path
171.12 -MODULE pathsep
171.13 -MODULE sep
171.14 -PACKAGE os.path
171.15 -CLASS stat_result
171.16 -METHOD access(path, mode)
171.17 -METHOD chdir(path)
171.18 -METHOD chmod(path, mode)
171.19 -METHOD close(fd)
171.20 -METHOD fdopen(fd, mode, bufsize)
171.21 -METHOD getcwd()
171.22 -METHOD getegid()
171.23 -METHOD getenv(key, default)
171.24 -METHOD geteuid()
171.25 -METHOD getgid()
171.26 -METHOD getlogin()
171.27 -METHOD getpgrp()
171.28 -METHOD getpid()
171.29 -METHOD getppid()
171.30 -METHOD getuid()
171.31 -METHOD isatty(fileno)
171.32 -METHOD listdir(path)
171.33 -METHOD lseek(fd, pos, how)
171.34 -METHOD lstat(path)
171.35 -METHOD makedirs(path, mode)
171.36 -METHOD mkdir(path, mode)
171.37 -METHOD open(filename, flag, mode)
171.38 -METHOD popen(args, kwargs)
171.39 -METHOD popen2(cmd, mode, bufsize)
171.40 -METHOD popen3(cmd, mode, bufsize)
171.41 -METHOD popen4(cmd, mode, bufsize)
171.42 -METHOD putenv(key, value)
171.43 -METHOD read(fd, buffersize)
171.44 -METHOD remove(path)
171.45 -METHOD removedirs(name)
171.46 -METHOD rename(path, newpath)
171.47 -METHOD renames(old, new)
171.48 -METHOD rmdir(path)
171.49 -METHOD setpgrp()
171.50 -METHOD setsid()
171.51 -METHOD stat(path)
171.52 -METHOD strerror(code)
171.53 -METHOD system(args, kwargs)
171.54 -METHOD unlink(path)
171.55 -METHOD unsetenv(key)
171.56 -METHOD utime(path, times)
171.57 -METHOD walk(top, topdown, onerror)
171.58 -METHOD write(fd, string)
171.59 -VARIABLE EX_OK
171.60 -VARIABLE F_OK
171.61 -VARIABLE O_APPEND
171.62 -VARIABLE O_CREAT
171.63 -VARIABLE O_EXCL
171.64 -VARIABLE O_RDONLY
171.65 -VARIABLE O_RDWR
171.66 -VARIABLE O_SYNC
171.67 -VARIABLE O_TRUNC
171.68 -VARIABLE O_WRONLY
171.69 -VARIABLE R_OK
171.70 -VARIABLE SEEK_CUR
171.71 -VARIABLE SEEK_END
171.72 -VARIABLE SEEK_SET
171.73 -VARIABLE W_OK
171.74 -VARIABLE X_OK
171.75 -VARIABLE __all__
171.76 -VARIABLE environ
171.77 -VARIABLE error
171.78 -VARIABLE linesep
171.79 -VARIABLE name
172.1 --- a/python.editor/test/unit/data/testfiles/compl2.py.testObjMethodConstructors1.completion Sun Jan 04 13:11:53 2015 -0600
172.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
172.3 @@ -1,28 +0,0 @@
172.4 -Code completion result for source line:
172.5 -myvar.|close()
172.6 -(QueryType=COMPLETION, NameKind=PREFIX)
172.7 -METHOD close()
172.8 -METHOD fileno()
172.9 -METHOD flush()
172.10 -METHOD isatty()
172.11 -METHOD next()
172.12 -METHOD read(size)
172.13 -METHOD readline(size)
172.14 -METHOD readlines(sizehint)
172.15 -METHOD seek(offset, whence)
172.16 -METHOD tell()
172.17 -METHOD truncate(size)
172.18 -METHOD write(str)
172.19 -METHOD writelines(sequence)
172.20 -METHOD ---xreadlines() ---
172.21 -ATTRIBUTE closed
172.22 -ATTRIBUTE encoding
172.23 -ATTRIBUTE errors
172.24 -ATTRIBUTE mode
172.25 -ATTRIBUTE name
172.26 -ATTRIBUTE newlines
172.27 -ATTRIBUTE softspace
172.28 -------------------------------------
172.29 -ATTRIBUTE __dict__
172.30 -ATTRIBUTE ---__members__ ---
172.31 -ATTRIBUTE ---__methods__ ---
173.1 --- a/python.editor/test/unit/data/testfiles/compl2.py.testObjMethodConstructors2.completion Sun Jan 04 13:11:53 2015 -0600
173.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
173.3 @@ -1,27 +0,0 @@
173.4 -Code completion result for source line:
173.5 -myothervar.|x
173.6 -(QueryType=COMPLETION, NameKind=PREFIX)
173.7 -METHOD close()
173.8 -METHOD getinfo(name)
173.9 -METHOD infolist()
173.10 -METHOD namelist()
173.11 -METHOD printdir()
173.12 -METHOD read(name)
173.13 -METHOD testzip()
173.14 -METHOD write(filename, arcname, compr
173.15 -METHOD writestr(zinfo_or_arcname, byt
173.16 -VARIABLE NameToInfo
173.17 -VARIABLE comment
173.18 -VARIABLE compression
173.19 -VARIABLE debug
173.20 -VARIABLE filelist
173.21 -VARIABLE filename
173.22 -VARIABLE fp
173.23 -VARIABLE mode
173.24 -VARIABLE start_dir
173.25 -------------------------------------
173.26 -CONSTRUCTO __init__(file, mode, compressi
173.27 -METHOD __del__()
173.28 -ATTRIBUTE __dict__
173.29 -ATTRIBUTE ---__members__ ---
173.30 -ATTRIBUTE ---__methods__ ---
174.1 --- a/python.editor/test/unit/data/testfiles/compl2.py.testObjMethodConstructors3.completion Sun Jan 04 13:11:53 2015 -0600
174.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
174.3 @@ -1,18 +0,0 @@
174.4 -Code completion result for source line:
174.5 -unknown.fai|
174.6 -(QueryType=COMPLETION, NameKind=PREFIX)
174.7 -OTHER Specify type of <code>unknown<
174.8 -------------------------------------
174.9 -METHOD fail(msg)
174.10 -METHOD fail(object, name, args)
174.11 -METHOD failIf(expr, msg)
174.12 -METHOD failIfAlmostEqual(first, secon
174.13 -METHOD failIfEqual(first, second, msg
174.14 -METHOD failUnless(expr, msg)
174.15 -METHOD failUnlessAlmostEqual(first, s
174.16 -METHOD failUnlessEqual(first, second,
174.17 -METHOD failUnlessRaises(excClass, cal
174.18 -VARIABLE fail
174.19 -VARIABLE failureException
174.20 -VARIABLE failures
174.21 -VARIABLE failures
175.1 --- a/python.editor/test/unit/data/testfiles/compl3.py Sun Jan 04 13:11:53 2015 -0600
175.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
175.3 @@ -1,59 +0,0 @@
175.4 -#!/usr/bin/env python
175.5 -# Testcase from http://www.amk.ca/files/simple/fingerd.txt
175.6 -
175.7 -# fingerd.py
175.8 -# By A.M. Kuchling (amk@amk.ca)
175.9 -#
175.10 -# This little program illustrates how easy it is to write network
175.11 -# servers using the classes in the SocketServer module.
175.12 -#
175.13 -# The finger protocol is a very simple TCP-based protocol; the client
175.14 -# sends a single line containing the name of the user whose
175.15 -# information is being requested, followed by a newline.
175.16 -# Information about the user should then be sent over the socket
175.17 -# connection to the client. In this implementation, the server simply
175.18 -# tells you who you've fingered; you'd probably want it to retrieve
175.19 -# information from the user's home directory or a database of some sort.
175.20 -#
175.21 -
175.22 -import SocketServer
175.23 -
175.24 -class FingerHandler(SocketServer.StreamRequestHandler):
175.25 - def handle(self):
175.26 - # Read a line of text, limiting it to 512 bytes.
175.27 - # This will prevent someone trying to crash the server machine
175.28 - # by sending megabytes of data.
175.29 - username=self.rfile.readline(512)
175.30 -
175.31 - # Remove any leading and trailing whitespace, including the
175.32 - # trailing newline.
175.33 - import string
175.34 - username=string.strip(username)
175.35 -
175.36 - # Call the method to get the user's information, and return it
175.37 - # to the client. The SocketServer classes make self.wfile
175.38 - # available to send data to the client.
175.39 - info = self.find_user_info(username)
175.40 - self.wfile.write(info)
175.41 -
175.42 - # The following method takes a string containing the username,
175.43 - # and returns another string containing whatever information is
175.44 - # desired. You can subclass the FingerHandler class and override
175.45 - # this method with your own to produce customized output.
175.46 -
175.47 - def find_user_info(self, username):
175.48 - "Return a string containing the desired user information."
175.49 - return "You fingered the user %s\n" % (repr(username),)
175.50 -
175.51 -# If this script is being run directly, it'll start acting as a finger
175.52 -# daemon. If someone's importing it in order to subclass
175.53 -# FingerHandler, that shouldn't be done. The following "if" statement
175.54 -# is the usual Python idiom for running code only in a script.
175.55 -
175.56 -if __name__=='__main__':
175.57 - # Create an instance of our server class
175.58 - server=SocketServer.TCPServer( ('', 79), FingerHandler)
175.59 -
175.60 - # Enter an infinite loop, waiting for requests and then servicing them.
175.61 - server.serve_forever()
175.62 -
176.1 --- a/python.editor/test/unit/data/testfiles/compl3.py.testObjMethodCompletion8.completion Sun Jan 04 13:11:53 2015 -0600
176.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
176.3 @@ -1,19 +0,0 @@
176.4 -Code completion result for source line:
176.5 -server=SocketServer.|TCPServer( ('', 79), FingerHandler)
176.6 -(QueryType=COMPLETION, NameKind=PREFIX)
176.7 -CLASS BaseRequestHandler
176.8 -CLASS DatagramRequestHandler
176.9 -CLASS ForkingMixIn
176.10 -CLASS ForkingTCPServer
176.11 -CLASS ForkingUDPServer
176.12 -CLASS StreamRequestHandler
176.13 -CLASS TCPServer
176.14 -CLASS ThreadingMixIn
176.15 -CLASS ThreadingTCPServer
176.16 -CLASS ThreadingUDPServer
176.17 -CLASS ThreadingUnixDatagramServer
176.18 -CLASS ThreadingUnixStreamServer
176.19 -CLASS UDPServer
176.20 -CLASS UnixDatagramServer
176.21 -CLASS UnixStreamServer
176.22 -VARIABLE __all__
177.1 --- a/python.editor/test/unit/data/testfiles/compl4.py Sun Jan 04 13:11:53 2015 -0600
177.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
177.3 @@ -1,3 +0,0 @@
177.4 -import sys as faen
177.5 -faen.e
177.6 -
178.1 --- a/python.editor/test/unit/data/testfiles/compl4.py.testObjMethodCompletion9.completion Sun Jan 04 13:11:53 2015 -0600
178.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
178.3 @@ -1,11 +0,0 @@
178.4 -Code completion result for source line:
178.5 -faen.e|
178.6 -(QueryType=COMPLETION, NameKind=PREFIX)
178.7 -METHOD exc_clear()
178.8 -METHOD exc_info()
178.9 -METHOD excepthook(type, value, traceb
178.10 -METHOD exit(arg)
178.11 -VARIABLE ---exc_type ---
178.12 -VARIABLE exec_prefix
178.13 -VARIABLE executable
178.14 -VARIABLE ---exitfunc ---
179.1 --- a/python.editor/test/unit/data/testfiles/compl5.py Sun Jan 04 13:11:53 2015 -0600
179.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
179.3 @@ -1,19 +0,0 @@
179.4 -import unittest
179.5 -
179.6 -class MyTest(unittest.TestCase):
179.7 -
179.8 - def f(self)
179.9 - self.assertAlmostEquals(1,2)
179.10 - pass
179.11 -
179.12 -x = MyTest()
179.13 -x.r
179.14 -
179.15 -# @type os2 str
179.16 -os2.x
179.17 -# @type os3 int
179.18 -os3.x
179.19 -# @type os4 list
179.20 -os4.x
179.21 -os5.xhd
179.22 -
180.1 --- a/python.editor/test/unit/data/testfiles/compl5.py.testDoc6.html Sun Jan 04 13:11:53 2015 -0600
180.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
180.3 @@ -1,18 +0,0 @@
180.4 -<html><body>
180.5 -<pre>Code completion result for source line:
180.6 -self.assertA|lmostEquals(1,2)
180.7 -(QueryType=COMPLETION, NameKind=PREFIX)
180.8 -METHOD assertAlmostEquals(first, seco unittest
180.9 -</pre><h2>Documentation:</h2><pre><i>unittest</i><br><b>assertAlmostEquals</b>(<font color="#808080">self, first, second, places, msg</font>)</pre>
180.10 -
180.11 -<hr>
180.12 -Fail if the two objects are unequal as determined by their
180.13 - difference rounded to the given number of decimal places
180.14 - (default 7) and comparing to zero.
180.15 -
180.16 -<br><br>
180.17 - Note that decimal places (from zero) are usually not the same
180.18 - as significant digits (measured from the most signficant digit).
180.19 -
180.20 -<br><br>
180.21 -</body></html>
181.1 --- a/python.editor/test/unit/data/testfiles/compl5.py.testObjMethodCompletion10.completion Sun Jan 04 13:11:53 2015 -0600
181.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
181.3 @@ -1,8 +0,0 @@
181.4 -Code completion result for source line:
181.5 -class MyTest(unittest.T|estCase):
181.6 -(QueryType=COMPLETION, NameKind=PREFIX)
181.7 -CLASS TestCase
181.8 -CLASS TestLoader
181.9 -CLASS TestResult
181.10 -CLASS TestSuite
181.11 -CLASS TextTestRunner
182.1 --- a/python.editor/test/unit/data/testfiles/compl5.py.testObjMethodCompletion11.completion Sun Jan 04 13:11:53 2015 -0600
182.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
182.3 @@ -1,41 +0,0 @@
182.4 -Code completion result for source line:
182.5 -x.|r
182.6 -(QueryType=COMPLETION, NameKind=PREFIX)
182.7 -METHOD assertAlmostEqual(first, secon
182.8 -METHOD assertAlmostEquals(first, seco
182.9 -METHOD assertEqual(first, second, msg
182.10 -METHOD assertEquals(first, second, ms
182.11 -METHOD assertFalse(expr, msg)
182.12 -METHOD assertNotAlmostEqual(first, se
182.13 -METHOD assertNotAlmostEquals(first, s
182.14 -METHOD assertNotEqual(first, second,
182.15 -METHOD assertNotEquals(first, second,
182.16 -METHOD assertRaises(excClass, callabl
182.17 -METHOD assertTrue(expr, msg)
182.18 -METHOD assert_(expr, msg)
182.19 -METHOD countTestCases()
182.20 -METHOD debug()
182.21 -METHOD defaultTestResult()
182.22 -METHOD f()
182.23 -METHOD fail(msg)
182.24 -METHOD failIf(expr, msg)
182.25 -METHOD failIfAlmostEqual(first, secon
182.26 -METHOD failIfEqual(first, second, msg
182.27 -METHOD failUnless(expr, msg)
182.28 -METHOD failUnlessAlmostEqual(first, s
182.29 -METHOD failUnlessEqual(first, second,
182.30 -METHOD failUnlessRaises(excClass, cal
182.31 -METHOD id()
182.32 -METHOD run(result)
182.33 -METHOD setUp()
182.34 -METHOD shortDescription()
182.35 -METHOD tearDown()
182.36 -VARIABLE failureException
182.37 -------------------------------------
182.38 -CONSTRUCTO __init__(methodName)
182.39 -METHOD __call__(args, kwds)
182.40 -METHOD __repr__()
182.41 -METHOD __str__()
182.42 -ATTRIBUTE __dict__
182.43 -ATTRIBUTE ---__members__ ---
182.44 -ATTRIBUTE ---__methods__ ---
183.1 --- a/python.editor/test/unit/data/testfiles/compl5.py.testOverride1.completion Sun Jan 04 13:11:53 2015 -0600
183.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
183.3 @@ -1,38 +0,0 @@
183.4 -Code completion result for source line:
183.5 -class MyTest(unittest.TestCase):
183.6 - |
183.7 - def f(self)
183.8 -(QueryType=COMPLETION, NameKind=PREFIX)
183.9 -CONSTRUCTO __init__(methodName) - overrid
183.10 -METHOD __call__(args, kwds) - overrid
183.11 -METHOD __repr__() - override
183.12 -METHOD __str__() - override
183.13 -METHOD _exc_info() - override [PRIVATE]
183.14 -METHOD assertAlmostEqual(first, secon
183.15 -METHOD assertAlmostEquals(first, seco
183.16 -METHOD assertEqual(first, second, msg
183.17 -METHOD assertEquals(first, second, ms
183.18 -METHOD assertFalse(expr, msg) - overr
183.19 -METHOD assertNotAlmostEqual(first, se
183.20 -METHOD assertNotAlmostEquals(first, s
183.21 -METHOD assertNotEqual(first, second,
183.22 -METHOD assertNotEquals(first, second,
183.23 -METHOD assertRaises(excClass, callabl
183.24 -METHOD assertTrue(expr, msg) - overri
183.25 -METHOD assert_(expr, msg) - override
183.26 -METHOD countTestCases() - override
183.27 -METHOD debug() - override
183.28 -METHOD defaultTestResult() - override
183.29 -METHOD fail(msg) - override
183.30 -METHOD failIf(expr, msg) - override
183.31 -METHOD failIfAlmostEqual(first, secon
183.32 -METHOD failIfEqual(first, second, msg
183.33 -METHOD failUnless(expr, msg) - overri
183.34 -METHOD failUnlessAlmostEqual(first, s
183.35 -METHOD failUnlessEqual(first, second,
183.36 -METHOD failUnlessRaises(excClass, cal
183.37 -METHOD id() - override
183.38 -METHOD run(result) - override
183.39 -METHOD setUp() - override
183.40 -METHOD shortDescription() - override
183.41 -METHOD tearDown() - override
184.1 --- a/python.editor/test/unit/data/testfiles/compl5.py.testOverride2.completion Sun Jan 04 13:11:53 2015 -0600
184.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
184.3 @@ -1,36 +0,0 @@
184.4 -Code completion result for source line:
184.5 -def |f(self)
184.6 -(QueryType=COMPLETION, NameKind=PREFIX)
184.7 -CONSTRUCTO __init__(methodName) - overrid
184.8 -METHOD __call__(args, kwds) - overrid
184.9 -METHOD __repr__() - override
184.10 -METHOD __str__() - override
184.11 -METHOD _exc_info() - override [PRIVATE]
184.12 -METHOD assertAlmostEqual(first, secon
184.13 -METHOD assertAlmostEquals(first, seco
184.14 -METHOD assertEqual(first, second, msg
184.15 -METHOD assertEquals(first, second, ms
184.16 -METHOD assertFalse(expr, msg) - overr
184.17 -METHOD assertNotAlmostEqual(first, se
184.18 -METHOD assertNotAlmostEquals(first, s
184.19 -METHOD assertNotEqual(first, second,
184.20 -METHOD assertNotEquals(first, second,
184.21 -METHOD assertRaises(excClass, callabl
184.22 -METHOD assertTrue(expr, msg) - overri
184.23 -METHOD assert_(expr, msg) - override
184.24 -METHOD countTestCases() - override
184.25 -METHOD debug() - override
184.26 -METHOD defaultTestResult() - override
184.27 -METHOD fail(msg) - override
184.28 -METHOD failIf(expr, msg) - override
184.29 -METHOD failIfAlmostEqual(first, secon
184.30 -METHOD failIfEqual(first, second, msg
184.31 -METHOD failUnless(expr, msg) - overri
184.32 -METHOD failUnlessAlmostEqual(first, s
184.33 -METHOD failUnlessEqual(first, second,
184.34 -METHOD failUnlessRaises(excClass, cal
184.35 -METHOD id() - override
184.36 -METHOD run(result) - override
184.37 -METHOD setUp() - override
184.38 -METHOD shortDescription() - override
184.39 -METHOD tearDown() - override
185.1 --- a/python.editor/test/unit/data/testfiles/compl5.py.testTypedVars1.completion Sun Jan 04 13:11:53 2015 -0600
185.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
185.3 @@ -1,77 +0,0 @@
185.4 -Code completion result for source line:
185.5 -os2.|x
185.6 -(QueryType=COMPLETION, NameKind=PREFIX)
185.7 -METHOD capitalize()
185.8 -METHOD center(width, fillchar)
185.9 -METHOD count(sub, start, end)
185.10 -METHOD decode(encoding, errors)
185.11 -METHOD encode(encoding, errors)
185.12 -METHOD endswith(suffix, start, end)
185.13 -METHOD expandtabs(tabsize)
185.14 -METHOD find(sub, start, end)
185.15 -METHOD format(format_string, *args, *
185.16 -METHOD index(a)
185.17 -METHOD index(sub, start, end)
185.18 -METHOD isalnum()
185.19 -METHOD isalpha()
185.20 -METHOD isdigit()
185.21 -METHOD islower()
185.22 -METHOD isspace()
185.23 -METHOD istitle()
185.24 -METHOD isupper()
185.25 -METHOD join(seq)
185.26 -METHOD ljust(width, fillchar)
185.27 -METHOD lower()
185.28 -METHOD lstrip(chars)
185.29 -METHOD partition(sep)
185.30 -METHOD replace(old, new, count)
185.31 -METHOD rfind(sub, start, end)
185.32 -METHOD rindex(sub, start, end)
185.33 -METHOD rjust(width, fillchar)
185.34 -METHOD rpartition(sep)
185.35 -METHOD rsplit(sep, maxsplit)
185.36 -METHOD rstrip(chars)
185.37 -METHOD split(sep, maxsplit)
185.38 -METHOD splitlines(keepends)
185.39 -METHOD startswith(prefix, start, end)
185.40 -METHOD strip(chars)
185.41 -METHOD swapcase()
185.42 -METHOD title()
185.43 -METHOD translate(table, deletechars)
185.44 -METHOD upper()
185.45 -METHOD zfill(width)
185.46 -------------------------------------
185.47 -CONSTRUCTO __init__()
185.48 -METHOD __add__(a, b)
185.49 -METHOD __contains__(a, b)
185.50 -METHOD __delattr__(name)
185.51 -METHOD __eq__(a, b)
185.52 -METHOD __format__(format_spec)
185.53 -METHOD __ge__(a, b)
185.54 -METHOD __getattribute__(name)
185.55 -METHOD __getitem__(a, b)
185.56 -METHOD __getnewargs__()
185.57 -METHOD __getslice__(a, b, c)
185.58 -METHOD __gt__(a, b)
185.59 -METHOD __hash__()
185.60 -METHOD __le__(a, b)
185.61 -METHOD __len__()
185.62 -METHOD __lt__(a, b)
185.63 -METHOD __mod__(a, b)
185.64 -METHOD __mul__(a, b)
185.65 -METHOD __ne__(a, b)
185.66 -METHOD __new__(S, ___)
185.67 -METHOD __reduce__()
185.68 -METHOD __reduce_ex__()
185.69 -METHOD __repr__()
185.70 -METHOD __rmod__(y)
185.71 -METHOD __rmul__(n)
185.72 -METHOD __setattr__(name, value)
185.73 -METHOD __sizeof__()
185.74 -METHOD __str__()
185.75 -METHOD __subclasshook__()
185.76 -ATTRIBUTE __class__
185.77 -ATTRIBUTE __dict__
185.78 -ATTRIBUTE __doc__
185.79 -ATTRIBUTE ---__members__ ---
185.80 -ATTRIBUTE ---__methods__ ---
186.1 --- a/python.editor/test/unit/data/testfiles/compl5.py.testTypedVars2.completion Sun Jan 04 13:11:53 2015 -0600
186.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
186.3 @@ -1,70 +0,0 @@
186.4 -Code completion result for source line:
186.5 -os3.|x
186.6 -(QueryType=COMPLETION, NameKind=PREFIX)
186.7 -METHOD conjugate()
186.8 -ATTRIBUTE denominator
186.9 -ATTRIBUTE imag
186.10 -ATTRIBUTE numerator
186.11 -ATTRIBUTE real
186.12 -------------------------------------
186.13 -CONSTRUCTO __init__()
186.14 -METHOD __abs__(obj)
186.15 -METHOD __add__(a, b)
186.16 -METHOD __and__(a, b)
186.17 -METHOD __cmp__(y)
186.18 -METHOD __coerce__(y)
186.19 -METHOD __delattr__(name)
186.20 -METHOD __div__(a, b)
186.21 -METHOD __divmod__(y)
186.22 -METHOD __float__()
186.23 -METHOD __floordiv__(a, b)
186.24 -METHOD __format__()
186.25 -METHOD __getattribute__(name)
186.26 -METHOD __getnewargs__()
186.27 -METHOD __hash__()
186.28 -METHOD __hex__()
186.29 -METHOD __index__(a)
186.30 -METHOD __int__()
186.31 -METHOD __invert__(obj)
186.32 -METHOD __long__()
186.33 -METHOD __lshift__(a, b)
186.34 -METHOD __mod__(a, b)
186.35 -METHOD __mul__(a, b)
186.36 -METHOD __neg__(obj)
186.37 -METHOD __new__(S, ___)
186.38 -METHOD __nonzero__()
186.39 -METHOD __oct__()
186.40 -METHOD __or__(a, b)
186.41 -METHOD __pos__(obj)
186.42 -METHOD __pow__(a, b)
186.43 -METHOD __radd__(y)
186.44 -METHOD __rand__(y)
186.45 -METHOD __rdiv__(y)
186.46 -METHOD __rdivmod__(y)
186.47 -METHOD __reduce__()
186.48 -METHOD __reduce_ex__()
186.49 -METHOD __repr__()
186.50 -METHOD __rfloordiv__(y)
186.51 -METHOD __rlshift__(y)
186.52 -METHOD __rmod__(y)
186.53 -METHOD __rmul__(y)
186.54 -METHOD __ror__(y)
186.55 -METHOD __rpow__(x)
186.56 -METHOD __rrshift__(y)
186.57 -METHOD __rshift__(a, b)
186.58 -METHOD __rsub__(y)
186.59 -METHOD __rtruediv__(y)
186.60 -METHOD __rxor__(y)
186.61 -METHOD __setattr__(name, value)
186.62 -METHOD __sizeof__()
186.63 -METHOD __str__()
186.64 -METHOD __sub__(a, b)
186.65 -METHOD __subclasshook__()
186.66 -METHOD __truediv__(a, b)
186.67 -METHOD __trunc__()
186.68 -METHOD __xor__(a, b)
186.69 -ATTRIBUTE __class__
186.70 -ATTRIBUTE __dict__
186.71 -ATTRIBUTE __doc__
186.72 -ATTRIBUTE ---__members__ ---
186.73 -ATTRIBUTE ---__methods__ ---
187.1 --- a/python.editor/test/unit/data/testfiles/compl5.py.testTypedVars3.completion Sun Jan 04 13:11:53 2015 -0600
187.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
187.3 @@ -1,52 +0,0 @@
187.4 -Code completion result for source line:
187.5 -os4.|x
187.6 -(QueryType=COMPLETION, NameKind=PREFIX)
187.7 -METHOD append()
187.8 -METHOD count(value)
187.9 -METHOD extend()
187.10 -METHOD index(a)
187.11 -METHOD insert()
187.12 -METHOD pop()
187.13 -METHOD remove()
187.14 -METHOD reverse()
187.15 -METHOD sort(cmp, key, reverse)
187.16 -------------------------------------
187.17 -CONSTRUCTO __init__()
187.18 -METHOD __add__(a, b)
187.19 -METHOD __contains__(a, b)
187.20 -METHOD __delattr__(name)
187.21 -METHOD __delitem__(a, b)
187.22 -METHOD __delslice__(a, b, c)
187.23 -METHOD __eq__(a, b)
187.24 -METHOD __format__()
187.25 -METHOD __ge__(a, b)
187.26 -METHOD __getattribute__(name)
187.27 -METHOD __getitem__(a, b)
187.28 -METHOD __getslice__(a, b, c)
187.29 -METHOD __gt__(a, b)
187.30 -METHOD __iadd__(a, b)
187.31 -METHOD __imul__(a, b)
187.32 -METHOD __iter__()
187.33 -METHOD __le__(a, b)
187.34 -METHOD __len__()
187.35 -METHOD __lt__(a, b)
187.36 -METHOD __mul__(a, b)
187.37 -METHOD __ne__(a, b)
187.38 -METHOD __new__(S, ___)
187.39 -METHOD __reduce__()
187.40 -METHOD __reduce_ex__()
187.41 -METHOD __repr__()
187.42 -METHOD __reversed__()
187.43 -METHOD __rmul__(n)
187.44 -METHOD __setattr__(name, value)
187.45 -METHOD __setitem__(a, b, c)
187.46 -METHOD __setslice__(a, b, c, v)
187.47 -METHOD __sizeof__()
187.48 -METHOD __str__()
187.49 -METHOD __subclasshook__()
187.50 -ATTRIBUTE __class__
187.51 -ATTRIBUTE __dict__
187.52 -ATTRIBUTE __doc__
187.53 -ATTRIBUTE __hash__
187.54 -ATTRIBUTE ---__members__ ---
187.55 -ATTRIBUTE ---__methods__ ---
188.1 --- a/python.editor/test/unit/data/testfiles/compl5.py.testTypedVars4.completion Sun Jan 04 13:11:53 2015 -0600
188.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
188.3 @@ -1,6 +0,0 @@
188.4 -Code completion result for source line:
188.5 -os5.xhd|
188.6 -(QueryType=COMPLETION, NameKind=PREFIX)
188.7 -OTHER Specify type of <code>os5</cod
188.8 -------------------------------------
188.9 -METHOD xhdr(hdr, str, file)
189.1 --- a/python.editor/test/unit/data/testfiles/complete-calls.py Sun Jan 04 13:11:53 2015 -0600
189.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
189.3 @@ -1,23 +0,0 @@
189.4 -
189.5 -class _MyLocal():
189.6 - def __init__(self):
189.7 - pass
189.8 -
189.9 - def foo(self, param3, default=5):
189.10 - pass
189.11 -
189.12 - def bar(self):
189.13 - pass
189.14 -
189.15 -
189.16 -def functionfoo(param1,param2):
189.17 - """This is my documentation"""
189.18 - pass
189.19 -
189.20 -
189.21 -functionfoo(foo, bar)
189.22 -functionfoo("foo", "bar", invalid)
189.23 -y = _MyLocal()
189.24 -y.foo(xyz)
189.25 -y.foo(xyz, baz)
189.26 -
190.1 --- a/python.editor/test/unit/data/testfiles/complete-calls.py.testParameters1.completion Sun Jan 04 13:11:53 2015 -0600
190.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
190.3 @@ -1,4 +0,0 @@
190.4 -Code completion result for source line:
190.5 -functionfoo(foo|, bar)
190.6 -(QueryType=COMPLETION, NameKind=PREFIX)
190.7 -CALL functionfoo(param1, ...)
191.1 --- a/python.editor/test/unit/data/testfiles/complete-calls.py.testParameters2.completion Sun Jan 04 13:11:53 2015 -0600
191.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
191.3 @@ -1,4 +0,0 @@
191.4 -Code completion result for source line:
191.5 -functionfoo(foo, bar|)
191.6 -(QueryType=COMPLETION, NameKind=PREFIX)
191.7 -CALL functionfoo(... , param2)
192.1 --- a/python.editor/test/unit/data/testfiles/complete-calls.py.testParameters3.completion Sun Jan 04 13:11:53 2015 -0600
192.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
192.3 @@ -1,6 +0,0 @@
192.4 -Code completion result for source line:
192.5 -y.foo(x|yz)
192.6 -(QueryType=COMPLETION, NameKind=PREFIX)
192.7 -CALL foo(param3, ...)
192.8 -------------------------------------
192.9 -METHOD xrange(start, stop, step)
193.1 --- a/python.editor/test/unit/data/testfiles/complete-calls.py.testParameters4.completion Sun Jan 04 13:11:53 2015 -0600
193.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
193.3 @@ -1,10 +0,0 @@
193.4 -Code completion result for source line:
193.5 -y.foo(xyz, b|az)
193.6 -(QueryType=COMPLETION, NameKind=PREFIX)
193.7 -CALL foo(... , param3, ...)
193.8 -------------------------------------
193.9 -METHOD basestring()
193.10 -METHOD bin(x)
193.11 -METHOD bool(x)
193.12 -METHOD buffer(object, offset, size)
193.13 -KEYWORD break
194.1 --- a/python.editor/test/unit/data/testfiles/complete-calls.py.testParameters5.completion Sun Jan 04 13:11:53 2015 -0600
194.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
194.3 @@ -1,4 +0,0 @@
194.4 -Code completion result for source line:
194.5 -functionfoo("foo", "bar", inval|id)
194.6 -(QueryType=COMPLETION, NameKind=PREFIX)
194.7 -CALL functionfoo(param2)
195.1 --- a/python.editor/test/unit/data/testfiles/create_docstring.py Sun Jan 04 13:11:53 2015 -0600
195.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
195.3 @@ -1,14 +0,0 @@
195.4 -
195.5 -class DatagramRequestHandler(BaseRequestHandler):
195.6 - def setup(self):
195.7 - pass
195.8 -
195.9 - def handle(self):
195.10 - pass
195.11 -
195.12 - def finish(self):
195.13 - pass
195.14 -
195.15 - def already(self):
195.16 - """Already commented"""
195.17 -
196.1 --- a/python.editor/test/unit/data/testfiles/create_docstring.py.testFix1.fixed Sun Jan 04 13:11:53 2015 -0600
196.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
196.3 @@ -1,15 +0,0 @@
196.4 -
196.5 -class DatagramRequestHandler(BaseRequestHandler):
196.6 - def setup(self):
196.7 - """"""
196.8 - pass
196.9 -
196.10 - def handle(self):
196.11 - pass
196.12 -
196.13 - def finish(self):
196.14 - pass
196.15 -
196.16 - def already(self):
196.17 - """Already commented"""
196.18 -
197.1 --- a/python.editor/test/unit/data/testfiles/create_docstring.py.testFix2.fixed Sun Jan 04 13:11:53 2015 -0600
197.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
197.3 @@ -1,17 +0,0 @@
197.4 -
197.5 -class DatagramRequestHandler(BaseRequestHandler):
197.6 - def setup(self):
197.7 - """
197.8 -
197.9 - """
197.10 - pass
197.11 -
197.12 - def handle(self):
197.13 - pass
197.14 -
197.15 - def finish(self):
197.16 - pass
197.17 -
197.18 - def already(self):
197.19 - """Already commented"""
197.20 -
198.1 --- a/python.editor/test/unit/data/testfiles/create_docstring.py.testFix3.fixed Sun Jan 04 13:11:53 2015 -0600
198.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
198.3 @@ -1,15 +0,0 @@
198.4 -
198.5 -class DatagramRequestHandler(BaseRequestHandler):
198.6 - """"""
198.7 - def setup(self):
198.8 - pass
198.9 -
198.10 - def handle(self):
198.11 - pass
198.12 -
198.13 - def finish(self):
198.14 - pass
198.15 -
198.16 - def already(self):
198.17 - """Already commented"""
198.18 -
199.1 --- a/python.editor/test/unit/data/testfiles/create_docstring.py.testFix4.fixed Sun Jan 04 13:11:53 2015 -0600
199.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
199.3 @@ -1,17 +0,0 @@
199.4 -
199.5 -class DatagramRequestHandler(BaseRequestHandler):
199.6 - """
199.7 -
199.8 - """
199.9 - def setup(self):
199.10 - pass
199.11 -
199.12 - def handle(self):
199.13 - pass
199.14 -
199.15 - def finish(self):
199.16 - pass
199.17 -
199.18 - def already(self):
199.19 - """Already commented"""
199.20 -
200.1 --- a/python.editor/test/unit/data/testfiles/create_docstring.py.testHint1.hints Sun Jan 04 13:11:53 2015 -0600
200.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
200.3 @@ -1,5 +0,0 @@
200.4 - def set^up(self):
200.5 - -----
200.6 -HINT:Create document comment
200.7 -FIX:Add a one-liner docstring
200.8 -FIX:Add a multi-line docstring
201.1 --- a/python.editor/test/unit/data/testfiles/create_docstring.py.testHint3.hints Sun Jan 04 13:11:53 2015 -0600
201.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
201.3 @@ -1,5 +0,0 @@
201.4 -class Datagram^RequestHandler(BaseRequestHandler):
201.5 - ----------------------
201.6 -HINT:Create document comment
201.7 -FIX:Add a multi-line docstring
201.8 -FIX:Add a one-liner docstring
202.1 --- a/python.editor/test/unit/data/testfiles/create_docstring2.py Sun Jan 04 13:11:53 2015 -0600
202.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
202.3 @@ -1,3 +0,0 @@
202.4 -class Foo
202.5 - def faen(self)
202.6 - print hei
203.1 --- a/python.editor/test/unit/data/testfiles/create_docstring2.py.testFix5.fixed Sun Jan 04 13:11:53 2015 -0600
203.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
203.3 @@ -1,3 +0,0 @@
203.4 -class Foo
203.5 - def faen(self)
203.6 - print hei
204.1 --- a/python.editor/test/unit/data/testfiles/create_docstring3.py Sun Jan 04 13:11:53 2015 -0600
204.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
204.3 @@ -1,3 +0,0 @@
204.4 -class Foo
204.5 - def faen(self):
204.6 - print hei
205.1 --- a/python.editor/test/unit/data/testfiles/create_docstring3.py.testFix6.fixed Sun Jan 04 13:11:53 2015 -0600
205.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
205.3 @@ -1,4 +0,0 @@
205.4 -class Foo
205.5 - def faen(self):
205.6 - """"""
205.7 - print hei
206.1 --- a/python.editor/test/unit/data/testfiles/create_docstring4.py Sun Jan 04 13:11:53 2015 -0600
206.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
206.3 @@ -1,10 +0,0 @@
206.4 -class Foo
206.5 - def faen(self):
206.6 - print hei
206.7 -
206.8 - def second(self):
206.9 - print hadet
206.10 -
206.11 - def ferdig(self):
206.12 - if true
206.13 -
207.1 --- a/python.editor/test/unit/data/testfiles/create_docstring4.py.testFix7.fixed Sun Jan 04 13:11:53 2015 -0600
207.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
207.3 @@ -1,11 +0,0 @@
207.4 -class Foo
207.5 - def faen(self):
207.6 - print hei
207.7 -
207.8 - def second(self):
207.9 - """"""
207.10 - print hadet
207.11 -
207.12 - def ferdig(self):
207.13 - if true
207.14 -
208.1 --- a/python.editor/test/unit/data/testfiles/datetime.py Sun Jan 04 13:11:53 2015 -0600
208.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
208.3 @@ -1,2008 +0,0 @@
208.4 -"""Concrete date/time and related types -- prototype implemented in Python.
208.5 -
208.6 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
208.7 -
208.8 -See also http://dir.yahoo.com/Reference/calendars/
208.9 -
208.10 -For a primer on DST, including many current DST rules, see
208.11 -http://webexhibits.org/daylightsaving/
208.12 -
208.13 -For more about DST than you ever wanted to know, see
208.14 -ftp://elsie.nci.nih.gov/pub/
208.15 -
208.16 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
208.17 -
208.18 -"""
208.19 -
208.20 -import time as _time
208.21 -import math as _math
208.22 -
208.23 -MINYEAR = 1
208.24 -MAXYEAR = 9999
208.25 -
208.26 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
208.27 -# also assumes the current Gregorian calendar indefinitely extended in
208.28 -# both directions. Difference: Dates.py calls January 1 of year 0 day
208.29 -# number 1. The code here calls January 1 of year 1 day number 1. This is
208.30 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
208.31 -# and Reingold's "Calendrical Calculations", where it's the base calendar
208.32 -# for all computations. See the book for algorithms for converting between
208.33 -# proleptic Gregorian ordinals and many other calendar systems.
208.34 -
208.35 -_DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
208.36 -
208.37 -_DAYS_BEFORE_MONTH = [None]
208.38 -dbm = 0
208.39 -for dim in _DAYS_IN_MONTH[1:]:
208.40 - _DAYS_BEFORE_MONTH.append(dbm)
208.41 - dbm += dim
208.42 -del dbm, dim
208.43 -
208.44 -def _is_leap(year):
208.45 - "year -> 1 if leap year, else 0."
208.46 - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
208.47 -
208.48 -def _days_in_year(year):
208.49 - "year -> number of days in year (366 if a leap year, else 365)."
208.50 - return 365 + _is_leap(year)
208.51 -
208.52 -def _days_before_year(year):
208.53 - "year -> number of days before January 1st of year."
208.54 - y = year - 1
208.55 - return y*365 + y//4 - y//100 + y//400
208.56 -
208.57 -def _days_in_month(year, month):
208.58 - "year, month -> number of days in that month in that year."
208.59 - assert 1 <= month <= 12, month
208.60 - if month == 2 and _is_leap(year):
208.61 - return 29
208.62 - return _DAYS_IN_MONTH[month]
208.63 -
208.64 -def _days_before_month(year, month):
208.65 - "year, month -> number of days in year preceeding first day of month."
208.66 - if not 1 <= month <= 12:
208.67 - raise ValueError('month must be in 1..12', month)
208.68 - return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
208.69 -
208.70 -def _ymd2ord(year, month, day):
208.71 - "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
208.72 - if not 1 <= month <= 12:
208.73 - raise ValueError('month must be in 1..12', month)
208.74 - dim = _days_in_month(year, month)
208.75 - if not 1 <= day <= dim:
208.76 - raise ValueError('day must be in 1..%d' % dim, day)
208.77 - return (_days_before_year(year) +
208.78 - _days_before_month(year, month) +
208.79 - day)
208.80 -
208.81 -_DI400Y = _days_before_year(401) # number of days in 400 years
208.82 -_DI100Y = _days_before_year(101) # " " " " 100 "
208.83 -_DI4Y = _days_before_year(5) # " " " " 4 "
208.84 -
208.85 -# A 4-year cycle has an extra leap day over what we'd get from pasting
208.86 -# together 4 single years.
208.87 -assert _DI4Y == 4 * 365 + 1
208.88 -
208.89 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
208.90 -# pasting together 4 100-year cycles.
208.91 -assert _DI400Y == 4 * _DI100Y + 1
208.92 -
208.93 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
208.94 -# pasting together 25 4-year cycles.
208.95 -assert _DI100Y == 25 * _DI4Y - 1
208.96 -
208.97 -def _ord2ymd(n):
208.98 - "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
208.99 -
208.100 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
208.101 - # repeats exactly every 400 years. The basic strategy is to find the
208.102 - # closest 400-year boundary at or before n, then work with the offset
208.103 - # from that boundary to n. Life is much clearer if we subtract 1 from
208.104 - # n first -- then the values of n at 400-year boundaries are exactly
208.105 - # those divisible by _DI400Y:
208.106 - #
208.107 - # D M Y n n-1
208.108 - # -- --- ---- ---------- ----------------
208.109 - # 31 Dec -400 -_DI400Y -_DI400Y -1
208.110 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
208.111 - # ...
208.112 - # 30 Dec 000 -1 -2
208.113 - # 31 Dec 000 0 -1
208.114 - # 1 Jan 001 1 0 400-year boundary
208.115 - # 2 Jan 001 2 1
208.116 - # 3 Jan 001 3 2
208.117 - # ...
208.118 - # 31 Dec 400 _DI400Y _DI400Y -1
208.119 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
208.120 - n -= 1
208.121 - n400, n = divmod(n, _DI400Y)
208.122 - year = n400 * 400 + 1 # ..., -399, 1, 401, ...
208.123 -
208.124 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
208.125 - # the desired date. Now compute how many 100-year cycles precede n.
208.126 - # Note that it's possible for n100 to equal 4! In that case 4 full
208.127 - # 100-year cycles precede the desired day, which implies the desired
208.128 - # day is December 31 at the end of a 400-year cycle.
208.129 - n100, n = divmod(n, _DI100Y)
208.130 -
208.131 - # Now compute how many 4-year cycles precede it.
208.132 - n4, n = divmod(n, _DI4Y)
208.133 -
208.134 - # And now how many single years. Again n1 can be 4, and again meaning
208.135 - # that the desired day is December 31 at the end of the 4-year cycle.
208.136 - n1, n = divmod(n, 365)
208.137 -
208.138 - year += n100 * 100 + n4 * 4 + n1
208.139 - if n1 == 4 or n100 == 4:
208.140 - assert n == 0
208.141 - return year-1, 12, 31
208.142 -
208.143 - # Now the year is correct, and n is the offset from January 1. We find
208.144 - # the month via an estimate that's either exact or one too large.
208.145 - leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
208.146 - assert leapyear == _is_leap(year)
208.147 - month = (n + 50) >> 5
208.148 - preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
208.149 - if preceding > n: # estimate is too large
208.150 - month -= 1
208.151 - preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
208.152 - n -= preceding
208.153 - assert 0 <= n < _days_in_month(year, month)
208.154 -
208.155 - # Now the year and month are correct, and n is the offset from the
208.156 - # start of that month: we're done!
208.157 - return year, month, n+1
208.158 -
208.159 -# Month and day names. For localized versions, see the calendar module.
208.160 -_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
208.161 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
208.162 -_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
208.163 -
208.164 -
208.165 -def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
208.166 - wday = (_ymd2ord(y, m, d) + 6) % 7
208.167 - dnum = _days_before_month(y, m) + d
208.168 - return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
208.169 -
208.170 -def _format_time(hh, mm, ss, us):
208.171 - # Skip trailing microseconds when us==0.
208.172 - result = "%02d:%02d:%02d" % (hh, mm, ss)
208.173 - if us:
208.174 - result += ".%06d" % us
208.175 - return result
208.176 -
208.177 -# Correctly substitute for %z and %Z escapes in strftime formats.
208.178 -def _wrap_strftime(object, format, timetuple):
208.179 - year = timetuple[0]
208.180 - if year < 1900:
208.181 - raise ValueError("year=%d is before 1900; the datetime strftime() "
208.182 - "methods require year >= 1900" % year)
208.183 - # Don't call _utcoffset() or tzname() unless actually needed.
208.184 - zreplace = None # the string to use for %z
208.185 - Zreplace = None # the string to use for %Z
208.186 -
208.187 - # Scan format for %z and %Z escapes, replacing as needed.
208.188 - newformat = []
208.189 - push = newformat.append
208.190 - i, n = 0, len(format)
208.191 - while i < n:
208.192 - ch = format[i]
208.193 - i += 1
208.194 - if ch == '%':
208.195 - if i < n:
208.196 - ch = format[i]
208.197 - i += 1
208.198 - if ch == 'z':
208.199 - if zreplace is None:
208.200 - zreplace = ""
208.201 - if hasattr(object, "_utcoffset"):
208.202 - offset = object._utcoffset()
208.203 - if offset is not None:
208.204 - sign = '+'
208.205 - if offset < 0:
208.206 - offset = -offset
208.207 - sign = '-'
208.208 - h, m = divmod(offset, 60)
208.209 - zreplace = '%c%02d%02d' % (sign, h, m)
208.210 - assert '%' not in zreplace
208.211 - newformat.append(zreplace)
208.212 - elif ch == 'Z':
208.213 - if Zreplace is None:
208.214 - Zreplace = ""
208.215 - if hasattr(object, "tzname"):
208.216 - s = object.tzname()
208.217 - if s is not None:
208.218 - # strftime is going to have at this: escape %
208.219 - Zreplace = s.replace('%', '%%')
208.220 - newformat.append(Zreplace)
208.221 - else:
208.222 - push('%')
208.223 - push(ch)
208.224 - else:
208.225 - push('%')
208.226 - else:
208.227 - push(ch)
208.228 - newformat = "".join(newformat)
208.229 - return _time.strftime(newformat, timetuple)
208.230 -
208.231 -def _call_tzinfo_method(tzinfo, methname, tzinfoarg):
208.232 - if tzinfo is None:
208.233 - return None
208.234 - return getattr(tzinfo, methname)(tzinfoarg)
208.235 -
208.236 -# Just raise TypeError if the arg isn't None or a string.
208.237 -def _check_tzname(name):
208.238 - if name is not None and not isinstance(name, str):
208.239 - raise TypeError("tzinfo.tzname() must return None or string, "
208.240 - "not '%s'" % type(name))
208.241 -
208.242 -# name is the offset-producing method, "utcoffset" or "dst".
208.243 -# offset is what it returned.
208.244 -# If offset isn't None or timedelta, raises TypeError.
208.245 -# If offset is None, returns None.
208.246 -# Else offset is checked for being in range, and a whole # of minutes.
208.247 -# If it is, its integer value is returned. Else ValueError is raised.
208.248 -def _check_utc_offset(name, offset):
208.249 - assert name in ("utcoffset", "dst")
208.250 - if offset is None:
208.251 - return None
208.252 - if not isinstance(offset, timedelta):
208.253 - raise TypeError("tzinfo.%s() must return None "
208.254 - "or timedelta, not '%s'" % (name, type(offset)))
208.255 - days = offset.days
208.256 - if days < -1 or days > 0:
208.257 - offset = 1440 # trigger out-of-range
208.258 - else:
208.259 - seconds = days * 86400 + offset.seconds
208.260 - minutes, seconds = divmod(seconds, 60)
208.261 - if seconds or offset.microseconds:
208.262 - raise ValueError("tzinfo.%s() must return a whole number "
208.263 - "of minutes" % name)
208.264 - offset = minutes
208.265 - if -1440 < offset < 1440:
208.266 - return offset
208.267 - raise ValueError("%s()=%d, must be in -1439..1439" % (name, offset))
208.268 -
208.269 -def _check_date_fields(year, month, day):
208.270 - if not MINYEAR <= year <= MAXYEAR:
208.271 - raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
208.272 - if not 1 <= month <= 12:
208.273 - raise ValueError('month must be in 1..12', month)
208.274 - dim = _days_in_month(year, month)
208.275 - if not 1 <= day <= dim:
208.276 - raise ValueError('day must be in 1..%d' % dim, day)
208.277 -
208.278 -def _check_time_fields(hour, minute, second, microsecond):
208.279 - if not 0 <= hour <= 23:
208.280 - raise ValueError('hour must be in 0..23', hour)
208.281 - if not 0 <= minute <= 59:
208.282 - raise ValueError('minute must be in 0..59', minute)
208.283 - if not 0 <= second <= 59:
208.284 - raise ValueError('second must be in 0..59', second)
208.285 - if not 0 <= microsecond <= 999999:
208.286 - raise ValueError('microsecond must be in 0..999999', microsecond)
208.287 -
208.288 -def _check_tzinfo_arg(tz):
208.289 - if tz is not None and not isinstance(tz, tzinfo):
208.290 - raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
208.291 -
208.292 -
208.293 -# Notes on comparison: In general, datetime module comparison operators raise
208.294 -# TypeError when they don't know how to do a comparison themself. If they
208.295 -# returned NotImplemented instead, comparison could (silently) fall back to
208.296 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
208.297 -# and that's not helpful. There are two exceptions:
208.298 -#
208.299 -# 1. For date and datetime, if the other object has a "timetuple" attr,
208.300 -# NotImplemented is returned. This is a hook to allow other kinds of
208.301 -# datetime-like objects a chance to intercept the comparison.
208.302 -#
208.303 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
208.304 -# so opertaions like
208.305 -#
208.306 -# x == y
208.307 -# x != y
208.308 -# x in sequence
208.309 -# x not in sequence
208.310 -# dict[x] = y
208.311 -#
208.312 -# don't raise annoying TypeErrors just because a datetime object
208.313 -# is part of a heterogeneous collection. If there's no known way to
208.314 -# compare X to a datetime, saying they're not equal is reasonable.
208.315 -
208.316 -def _cmperror(x, y):
208.317 - raise TypeError("can't compare '%s' to '%s'" % (
208.318 - type(x).__name__, type(y).__name__))
208.319 -
208.320 -# This is a start at a struct tm workalike. Goals:
208.321 -#
208.322 -# + Works the same way across platforms.
208.323 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
208.324 -#
208.325 -# Note: I suspect it's best if this flavor of tm does *not* try to
208.326 -# second-guess timezones or DST. Instead fold whatever adjustments you want
208.327 -# into the minutes argument (and the constructor will normalize).
208.328 -
208.329 -_ORD1970 = _ymd2ord(1970, 1, 1) # base ordinal for UNIX epoch
208.330 -
208.331 -class tmxxx:
208.332 -
208.333 - ordinal = None
208.334 -
208.335 - def __init__(self, year, month, day, hour=0, minute=0, second=0,
208.336 - microsecond=0):
208.337 - # Normalize all the inputs, and store the normalized values.
208.338 - if not 0 <= microsecond <= 999999:
208.339 - carry, microsecond = divmod(microsecond, 1000000)
208.340 - second += carry
208.341 - if not 0 <= second <= 59:
208.342 - carry, second = divmod(second, 60)
208.343 - minute += carry
208.344 - if not 0 <= minute <= 59:
208.345 - carry, minute = divmod(minute, 60)
208.346 - hour += carry
208.347 - if not 0 <= hour <= 23:
208.348 - carry, hour = divmod(hour, 24)
208.349 - day += carry
208.350 -
208.351 - # That was easy. Now it gets muddy: the proper range for day
208.352 - # can't be determined without knowing the correct month and year,
208.353 - # but if day is, e.g., plus or minus a million, the current month
208.354 - # and year values make no sense (and may also be out of bounds
208.355 - # themselves).
208.356 - # Saying 12 months == 1 year should be non-controversial.
208.357 - if not 1 <= month <= 12:
208.358 - carry, month = divmod(month-1, 12)
208.359 - year += carry
208.360 - month += 1
208.361 - assert 1 <= month <= 12
208.362 -
208.363 - # Now only day can be out of bounds (year may also be out of bounds
208.364 - # for a datetime object, but we don't care about that here).
208.365 - # If day is out of bounds, what to do is arguable, but at least the
208.366 - # method here is principled and explainable.
208.367 - dim = _days_in_month(year, month)
208.368 - if not 1 <= day <= dim:
208.369 - # Move day-1 days from the first of the month. First try to
208.370 - # get off cheap if we're only one day out of range (adjustments
208.371 - # for timezone alone can't be worse than that).
208.372 - if day == 0: # move back a day
208.373 - month -= 1
208.374 - if month > 0:
208.375 - day = _days_in_month(year, month)
208.376 - else:
208.377 - year, month, day = year-1, 12, 31
208.378 - elif day == dim + 1: # move forward a day
208.379 - month += 1
208.380 - day = 1
208.381 - if month > 12:
208.382 - month = 1
208.383 - year += 1
208.384 - else:
208.385 - self.ordinal = _ymd2ord(year, month, 1) + (day - 1)
208.386 - year, month, day = _ord2ymd(self.ordinal)
208.387 -
208.388 - self.year, self.month, self.day = year, month, day
208.389 - self.hour, self.minute, self.second = hour, minute, second
208.390 - self.microsecond = microsecond
208.391 -
208.392 - def toordinal(self):
208.393 - """Return proleptic Gregorian ordinal for the year, month and day.
208.394 -
208.395 - January 1 of year 1 is day 1. Only the year, month and day values
208.396 - contribute to the result.
208.397 - """
208.398 - if self.ordinal is None:
208.399 - self.ordinal = _ymd2ord(self.year, self.month, self.day)
208.400 - return self.ordinal
208.401 -
208.402 - def time(self):
208.403 - "Return Unixish timestamp, as a float (assuming UTC)."
208.404 - days = self.toordinal() - _ORD1970 # convert to UNIX epoch
208.405 - seconds = ((days * 24. + self.hour)*60. + self.minute)*60.
208.406 - return seconds + self.second + self.microsecond / 1e6
208.407 -
208.408 - def ctime(self):
208.409 - "Return ctime() style string."
208.410 - weekday = self.toordinal() % 7 or 7
208.411 - return "%s %s %2d %02d:%02d:%02d %04d" % (
208.412 - _DAYNAMES[weekday],
208.413 - _MONTHNAMES[self.month],
208.414 - self.day,
208.415 - self.hour, self.minute, self.second,
208.416 - self.year)
208.417 -
208.418 -class timedelta(object):
208.419 - """Represent the difference between two datetime objects.
208.420 -
208.421 - Supported operators:
208.422 -
208.423 - - add, subtract timedelta
208.424 - - unary plus, minus, abs
208.425 - - compare to timedelta
208.426 - - multiply, divide by int/long
208.427 -
208.428 - In addition, datetime supports subtraction of two datetime objects
208.429 - returning a timedelta, and addition or subtraction of a datetime
208.430 - and a timedelta giving a datetime.
208.431 -
208.432 - Representation: (days, seconds, microseconds). Why? Because I
208.433 - felt like it.
208.434 - """
208.435 -
208.436 - def __new__(cls, days=0, seconds=0, microseconds=0,
208.437 - # XXX The following should only be used as keyword args:
208.438 - milliseconds=0, minutes=0, hours=0, weeks=0):
208.439 - # Doing this efficiently and accurately in C is going to be difficult
208.440 - # and error-prone, due to ubiquitous overflow possibilities, and that
208.441 - # C double doesn't have enough bits of precision to represent
208.442 - # microseconds over 10K years faithfully. The code here tries to make
208.443 - # explicit where go-fast assumptions can be relied on, in order to
208.444 - # guide the C implementation; it's way more convoluted than speed-
208.445 - # ignoring auto-overflow-to-long idiomatic Python could be.
208.446 -
208.447 - # XXX Check that all inputs are ints, longs or floats.
208.448 -
208.449 - # Final values, all integer.
208.450 - # s and us fit in 32-bit signed ints; d isn't bounded.
208.451 - d = s = us = 0
208.452 -
208.453 - # Normalize everything to days, seconds, microseconds.
208.454 - days += weeks*7
208.455 - seconds += minutes*60 + hours*3600
208.456 - microseconds += milliseconds*1000
208.457 -
208.458 - # Get rid of all fractions, and normalize s and us.
208.459 - # Take a deep breath <wink>.
208.460 - if isinstance(days, float):
208.461 - dayfrac, days = _math.modf(days)
208.462 - daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
208.463 - assert daysecondswhole == int(daysecondswhole) # can't overflow
208.464 - s = int(daysecondswhole)
208.465 - assert days == long(days)
208.466 - d = long(days)
208.467 - else:
208.468 - daysecondsfrac = 0.0
208.469 - d = days
208.470 - assert isinstance(daysecondsfrac, float)
208.471 - assert abs(daysecondsfrac) <= 1.0
208.472 - assert isinstance(d, (int, long))
208.473 - assert abs(s) <= 24 * 3600
208.474 - # days isn't referenced again before redefinition
208.475 -
208.476 - if isinstance(seconds, float):
208.477 - secondsfrac, seconds = _math.modf(seconds)
208.478 - assert seconds == long(seconds)
208.479 - seconds = long(seconds)
208.480 - secondsfrac += daysecondsfrac
208.481 - assert abs(secondsfrac) <= 2.0
208.482 - else:
208.483 - secondsfrac = daysecondsfrac
208.484 - # daysecondsfrac isn't referenced again
208.485 - assert isinstance(secondsfrac, float)
208.486 - assert abs(secondsfrac) <= 2.0
208.487 -
208.488 - assert isinstance(seconds, (int, long))
208.489 - days, seconds = divmod(seconds, 24*3600)
208.490 - d += days
208.491 - s += int(seconds) # can't overflow
208.492 - assert isinstance(s, int)
208.493 - assert abs(s) <= 2 * 24 * 3600
208.494 - # seconds isn't referenced again before redefinition
208.495 -
208.496 - usdouble = secondsfrac * 1e6
208.497 - assert abs(usdouble) < 2.1e6 # exact value not critical
208.498 - # secondsfrac isn't referenced again
208.499 -
208.500 - if isinstance(microseconds, float):
208.501 - microseconds += usdouble
208.502 - microseconds = round(microseconds)
208.503 - seconds, microseconds = divmod(microseconds, 1e6)
208.504 - assert microseconds == int(microseconds)
208.505 - assert seconds == long(seconds)
208.506 - days, seconds = divmod(seconds, 24.*3600.)
208.507 - assert days == long(days)
208.508 - assert seconds == int(seconds)
208.509 - d += long(days)
208.510 - s += int(seconds) # can't overflow
208.511 - assert isinstance(s, int)
208.512 - assert abs(s) <= 3 * 24 * 3600
208.513 - else:
208.514 - seconds, microseconds = divmod(microseconds, 1000000)
208.515 - days, seconds = divmod(seconds, 24*3600)
208.516 - d += days
208.517 - s += int(seconds) # can't overflow
208.518 - assert isinstance(s, int)
208.519 - assert abs(s) <= 3 * 24 * 3600
208.520 - microseconds = float(microseconds)
208.521 - microseconds += usdouble
208.522 - microseconds = round(microseconds)
208.523 - assert abs(s) <= 3 * 24 * 3600
208.524 - assert abs(microseconds) < 3.1e6
208.525 -
208.526 - # Just a little bit of carrying possible for microseconds and seconds.
208.527 - assert isinstance(microseconds, float)
208.528 - assert int(microseconds) == microseconds
208.529 - us = int(microseconds)
208.530 - seconds, us = divmod(us, 1000000)
208.531 - s += seconds # cant't overflow
208.532 - assert isinstance(s, int)
208.533 - days, s = divmod(s, 24*3600)
208.534 - d += days
208.535 -
208.536 - assert isinstance(d, (int, long))
208.537 - assert isinstance(s, int) and 0 <= s < 24*3600
208.538 - assert isinstance(us, int) and 0 <= us < 1000000
208.539 -
208.540 - self = object.__new__(cls)
208.541 -
208.542 - self.__days = d
208.543 - self.__seconds = s
208.544 - self.__microseconds = us
208.545 - if abs(d) > 999999999:
208.546 - raise OverflowError("timedelta # of days is too large: %d" % d)
208.547 -
208.548 - return self
208.549 -
208.550 - def __repr__(self):
208.551 - if self.__microseconds:
208.552 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
208.553 - self.__days,
208.554 - self.__seconds,
208.555 - self.__microseconds)
208.556 - if self.__seconds:
208.557 - return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__,
208.558 - self.__days,
208.559 - self.__seconds)
208.560 - return "%s(%d)" % ('datetime.' + self.__class__.__name__, self.__days)
208.561 -
208.562 - def __str__(self):
208.563 - mm, ss = divmod(self.__seconds, 60)
208.564 - hh, mm = divmod(mm, 60)
208.565 - s = "%d:%02d:%02d" % (hh, mm, ss)
208.566 - if self.__days:
208.567 - def plural(n):
208.568 - return n, abs(n) != 1 and "s" or ""
208.569 - s = ("%d day%s, " % plural(self.__days)) + s
208.570 - if self.__microseconds:
208.571 - s = s + ".%06d" % self.__microseconds
208.572 - return s
208.573 -
208.574 - days = property(lambda self: self.__days, doc="days")
208.575 - seconds = property(lambda self: self.__seconds, doc="seconds")
208.576 - microseconds = property(lambda self: self.__microseconds,
208.577 - doc="microseconds")
208.578 -
208.579 - def __add__(self, other):
208.580 - if isinstance(other, timedelta):
208.581 - return timedelta(self.__days + other.__days,
208.582 - self.__seconds + other.__seconds,
208.583 - self.__microseconds + other.__microseconds)
208.584 - return NotImplemented
208.585 -
208.586 - __radd__ = __add__
208.587 -
208.588 - def __sub__(self, other):
208.589 - if isinstance(other, timedelta):
208.590 - return self + -other
208.591 - return NotImplemented
208.592 -
208.593 - def __rsub__(self, other):
208.594 - if isinstance(other, timedelta):
208.595 - return -self + other
208.596 - return NotImplemented
208.597 -
208.598 - def __neg__(self):
208.599 - return self.__class__(-self.__days,
208.600 - -self.__seconds,
208.601 - -self.__microseconds)
208.602 -
208.603 - def __pos__(self):
208.604 - return self
208.605 -
208.606 - def __abs__(self):
208.607 - if self.__days < 0:
208.608 - return -self
208.609 - else:
208.610 - return self
208.611 -
208.612 - def __mul__(self, other):
208.613 - if isinstance(other, (int, long)):
208.614 - return self.__class__(self.__days * other,
208.615 - self.__seconds * other,
208.616 - self.__microseconds * other)
208.617 - return NotImplemented
208.618 -
208.619 - __rmul__ = __mul__
208.620 -
208.621 - def __div__(self, other):
208.622 - if isinstance(other, (int, long)):
208.623 - usec = ((self.__days * (24*3600L) + self.__seconds) * 1000000 +
208.624 - self.__microseconds)
208.625 - return self.__class__(0, 0, usec // other)
208.626 - return NotImplemented
208.627 -
208.628 - __floordiv__ = __div__
208.629 -
208.630 - # Comparisons.
208.631 -
208.632 - def __eq__(self, other):
208.633 - if isinstance(other, timedelta):
208.634 - return self.__cmp(other) == 0
208.635 - else:
208.636 - return False
208.637 -
208.638 - def __ne__(self, other):
208.639 - if isinstance(other, timedelta):
208.640 - return self.__cmp(other) != 0
208.641 - else:
208.642 - return True
208.643 -
208.644 - def __le__(self, other):
208.645 - if isinstance(other, timedelta):
208.646 - return self.__cmp(other) <= 0
208.647 - else:
208.648 - _cmperror(self, other)
208.649 -
208.650 - def __lt__(self, other):
208.651 - if isinstance(other, timedelta):
208.652 - return self.__cmp(other) < 0
208.653 - else:
208.654 - _cmperror(self, other)
208.655 -
208.656 - def __ge__(self, other):
208.657 - if isinstance(other, timedelta):
208.658 - return self.__cmp(other) >= 0
208.659 - else:
208.660 - _cmperror(self, other)
208.661 -
208.662 - def __gt__(self, other):
208.663 - if isinstance(other, timedelta):
208.664 - return self.__cmp(other) > 0
208.665 - else:
208.666 - _cmperror(self, other)
208.667 -
208.668 - def __cmp(self, other):
208.669 - assert isinstance(other, timedelta)
208.670 - return cmp(self.__getstate(), other.__getstate())
208.671 -
208.672 - def __hash__(self):
208.673 - return hash(self.__getstate())
208.674 -
208.675 - def __nonzero__(self):
208.676 - return (self.__days != 0 or
208.677 - self.__seconds != 0 or
208.678 - self.__microseconds != 0)
208.679 -
208.680 - # Pickle support.
208.681 -
208.682 - __safe_for_unpickling__ = True # For Python 2.2
208.683 -
208.684 - def __getstate(self):
208.685 - return (self.__days, self.__seconds, self.__microseconds)
208.686 -
208.687 - def __reduce__(self):
208.688 - return (self.__class__, self.__getstate())
208.689 -
208.690 -timedelta.min = timedelta(-999999999)
208.691 -timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
208.692 - microseconds=999999)
208.693 -timedelta.resolution = timedelta(microseconds=1)
208.694 -
208.695 -class date(object):
208.696 - """Concrete date type.
208.697 -
208.698 - Constructors:
208.699 -
208.700 - __new__()
208.701 - fromtimestamp()
208.702 - today()
208.703 - fromordinal()
208.704 -
208.705 - Operators:
208.706 -
208.707 - __repr__, __str__
208.708 - __cmp__, __hash__
208.709 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
208.710 -
208.711 - Methods:
208.712 -
208.713 - timetuple()
208.714 - toordinal()
208.715 - weekday()
208.716 - isoweekday(), isocalendar(), isoformat()
208.717 - ctime()
208.718 - strftime()
208.719 -
208.720 - Properties (readonly):
208.721 - year, month, day
208.722 - """
208.723 -
208.724 - def __new__(cls, year, month=None, day=None):
208.725 - """Constructor.
208.726 -
208.727 - Arguments:
208.728 -
208.729 - year, month, day (required, base 1)
208.730 - """
208.731 - if isinstance(year, str):
208.732 - # Pickle support
208.733 - self = object.__new__(cls)
208.734 - self.__setstate((year,))
208.735 - return self
208.736 - _check_date_fields(year, month, day)
208.737 - self = object.__new__(cls)
208.738 - self.__year = year
208.739 - self.__month = month
208.740 - self.__day = day
208.741 - return self
208.742 -
208.743 - # Additional constructors
208.744 -
208.745 - def fromtimestamp(cls, t):
208.746 - "Construct a date from a POSIX timestamp (like time.time())."
208.747 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
208.748 - return cls(y, m, d)
208.749 - fromtimestamp = classmethod(fromtimestamp)
208.750 -
208.751 - def today(cls):
208.752 - "Construct a date from time.time()."
208.753 - t = _time.time()
208.754 - return cls.fromtimestamp(t)
208.755 - today = classmethod(today)
208.756 -
208.757 - def fromordinal(cls, n):
208.758 - """Contruct a date from a proleptic Gregorian ordinal.
208.759 -
208.760 - January 1 of year 1 is day 1. Only the year, month and day are
208.761 - non-zero in the result.
208.762 - """
208.763 - y, m, d = _ord2ymd(n)
208.764 - return cls(y, m, d)
208.765 - fromordinal = classmethod(fromordinal)
208.766 -
208.767 - # Conversions to string
208.768 -
208.769 - def __repr__(self):
208.770 - "Convert to formal string, for repr()."
208.771 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
208.772 - self.__year,
208.773 - self.__month,
208.774 - self.__day)
208.775 - # XXX These shouldn't depend on time.localtime(), because that
208.776 - # clips the usable dates to [1970 .. 2038). At least ctime() is
208.777 - # easily done without using strftime() -- that's better too because
208.778 - # strftime("%c", ...) is locale specific.
208.779 -
208.780 - def ctime(self):
208.781 - "Format a la ctime()."
208.782 - return tmxxx(self.__year, self.__month, self.__day).ctime()
208.783 -
208.784 - def strftime(self, fmt):
208.785 - "Format using strftime()."
208.786 - return _wrap_strftime(self, fmt, self.timetuple())
208.787 -
208.788 - def isoformat(self):
208.789 - """Return the date formatted according to ISO.
208.790 -
208.791 - This is 'YYYY-MM-DD'.
208.792 -
208.793 - References:
208.794 - - http://www.w3.org/TR/NOTE-datetime
208.795 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
208.796 - """
208.797 - return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day)
208.798 -
208.799 - __str__ = isoformat
208.800 -
208.801 - # Read-only field accessors
208.802 - year = property(lambda self: self.__year,
208.803 - doc="year (%d-%d)" % (MINYEAR, MAXYEAR))
208.804 - month = property(lambda self: self.__month, doc="month (1-12)")
208.805 - day = property(lambda self: self.__day, doc="day (1-31)")
208.806 -
208.807 - # Standard conversions, __cmp__, __hash__ (and helpers)
208.808 -
208.809 - def timetuple(self):
208.810 - "Return local time tuple compatible with time.localtime()."
208.811 - return _build_struct_time(self.__year, self.__month, self.__day,
208.812 - 0, 0, 0, -1)
208.813 -
208.814 - def toordinal(self):
208.815 - """Return proleptic Gregorian ordinal for the year, month and day.
208.816 -
208.817 - January 1 of year 1 is day 1. Only the year, month and day values
208.818 - contribute to the result.
208.819 - """
208.820 - return _ymd2ord(self.__year, self.__month, self.__day)
208.821 -
208.822 - def replace(self, year=None, month=None, day=None):
208.823 - """Return a new date with new values for the specified fields."""
208.824 - if year is None:
208.825 - year = self.__year
208.826 - if month is None:
208.827 - month = self.__month
208.828 - if day is None:
208.829 - day = self.__day
208.830 - _check_date_fields(year, month, day)
208.831 - return date(year, month, day)
208.832 -
208.833 - # Comparisons.
208.834 -
208.835 - def __eq__(self, other):
208.836 - if isinstance(other, date):
208.837 - return self.__cmp(other) == 0
208.838 - elif hasattr(other, "timetuple"):
208.839 - return NotImplemented
208.840 - else:
208.841 - return False
208.842 -
208.843 - def __ne__(self, other):
208.844 - if isinstance(other, date):
208.845 - return self.__cmp(other) != 0
208.846 - elif hasattr(other, "timetuple"):
208.847 - return NotImplemented
208.848 - else:
208.849 - return True
208.850 -
208.851 - def __le__(self, other):
208.852 - if isinstance(other, date):
208.853 - return self.__cmp(other) <= 0
208.854 - elif hasattr(other, "timetuple"):
208.855 - return NotImplemented
208.856 - else:
208.857 - _cmperror(self, other)
208.858 -
208.859 - def __lt__(self, other):
208.860 - if isinstance(other, date):
208.861 - return self.__cmp(other) < 0
208.862 - elif hasattr(other, "timetuple"):
208.863 - return NotImplemented
208.864 - else:
208.865 - _cmperror(self, other)
208.866 -
208.867 - def __ge__(self, other):
208.868 - if isinstance(other, date):
208.869 - return self.__cmp(other) >= 0
208.870 - elif hasattr(other, "timetuple"):
208.871 - return NotImplemented
208.872 - else:
208.873 - _cmperror(self, other)
208.874 -
208.875 - def __gt__(self, other):
208.876 - if isinstance(other, date):
208.877 - return self.__cmp(other) > 0
208.878 - elif hasattr(other, "timetuple"):
208.879 - return NotImplemented
208.880 - else:
208.881 - _cmperror(self, other)
208.882 -
208.883 - def __cmp(self, other):
208.884 - assert isinstance(other, date)
208.885 - y, m, d = self.__year, self.__month, self.__day
208.886 - y2, m2, d2 = other.__year, other.__month, other.__day
208.887 - return cmp((y, m, d), (y2, m2, d2))
208.888 -
208.889 - def __hash__(self):
208.890 - "Hash."
208.891 - return hash(self.__getstate())
208.892 -
208.893 - # Computations
208.894 -
208.895 - def _checkOverflow(self, year):
208.896 - if not MINYEAR <= year <= MAXYEAR:
208.897 - raise OverflowError("date +/-: result year %d not in %d..%d" %
208.898 - (year, MINYEAR, MAXYEAR))
208.899 -
208.900 - def __add__(self, other):
208.901 - "Add a date to a timedelta."
208.902 - if isinstance(other, timedelta):
208.903 - t = tmxxx(self.__year,
208.904 - self.__month,
208.905 - self.__day + other.days)
208.906 - self._checkOverflow(t.year)
208.907 - result = self.__class__(t.year, t.month, t.day)
208.908 - return result
208.909 - return NotImplemented
208.910 -
208.911 - __radd__ = __add__
208.912 -
208.913 - def __sub__(self, other):
208.914 - """Subtract two dates, or a date and a timedelta."""
208.915 - if isinstance(other, timedelta):
208.916 - return self + timedelta(-other.days)
208.917 - if isinstance(other, date):
208.918 - days1 = self.toordinal()
208.919 - days2 = other.toordinal()
208.920 - return timedelta(days1 - days2)
208.921 - return NotImplemented
208.922 -
208.923 - def weekday(self):
208.924 - "Return day of the week, where Monday == 0 ... Sunday == 6."
208.925 - return (self.toordinal() + 6) % 7
208.926 -
208.927 - # Day-of-the-week and week-of-the-year, according to ISO
208.928 -
208.929 - def isoweekday(self):
208.930 - "Return day of the week, where Monday == 1 ... Sunday == 7."
208.931 - # 1-Jan-0001 is a Monday
208.932 - return self.toordinal() % 7 or 7
208.933 -
208.934 - def isocalendar(self):
208.935 - """Return a 3-tuple containing ISO year, week number, and weekday.
208.936 -
208.937 - The first ISO week of the year is the (Mon-Sun) week
208.938 - containing the year's first Thursday; everything else derives
208.939 - from that.
208.940 -
208.941 - The first week is 1; Monday is 1 ... Sunday is 7.
208.942 -
208.943 - ISO calendar algorithm taken from
208.944 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
208.945 - """
208.946 - year = self.__year
208.947 - week1monday = _isoweek1monday(year)
208.948 - today = _ymd2ord(self.__year, self.__month, self.__day)
208.949 - # Internally, week and day have origin 0
208.950 - week, day = divmod(today - week1monday, 7)
208.951 - if week < 0:
208.952 - year -= 1
208.953 - week1monday = _isoweek1monday(year)
208.954 - week, day = divmod(today - week1monday, 7)
208.955 - elif week >= 52:
208.956 - if today >= _isoweek1monday(year+1):
208.957 - year += 1
208.958 - week = 0
208.959 - return year, week+1, day+1
208.960 -
208.961 - # Pickle support.
208.962 -
208.963 - __safe_for_unpickling__ = True # For Python 2.2
208.964 -
208.965 - def __getstate(self):
208.966 - yhi, ylo = divmod(self.__year, 256)
208.967 - return ("%c%c%c%c" % (yhi, ylo, self.__month, self.__day), )
208.968 -
208.969 - def __setstate(self, t):
208.970 - assert isinstance(t, tuple) and len(t) == 1, `t`
208.971 - string = t[0]
208.972 - assert len(string) == 4
208.973 - yhi, ylo, self.__month, self.__day = map(ord, string)
208.974 - self.__year = yhi * 256 + ylo
208.975 -
208.976 - def __reduce__(self):
208.977 - return (self.__class__, self.__getstate())
208.978 -
208.979 -_date_class = date # so functions w/ args named "date" can get at the class
208.980 -
208.981 -date.min = date(1, 1, 1)
208.982 -date.max = date(9999, 12, 31)
208.983 -date.resolution = timedelta(days=1)
208.984 -
208.985 -class tzinfo(object):
208.986 - """Abstract base class for time zone info classes.
208.987 -
208.988 - Subclasses must override the name(), utcoffset() and dst() methods.
208.989 - """
208.990 -
208.991 - def tzname(self, dt):
208.992 - "datetime -> string name of time zone."
208.993 - raise NotImplementedError("tzinfo subclass must override tzname()")
208.994 -
208.995 - def utcoffset(self, dt):
208.996 - "datetime -> minutes east of UTC (negative for west of UTC)"
208.997 - raise NotImplementedError("tzinfo subclass must override utcoffset()")
208.998 -
208.999 - def dst(self, dt):
208.1000 - """datetime -> DST offset in minutes east of UTC.
208.1001 -
208.1002 - Return 0 if DST not in effect. utcoffset() must include the DST
208.1003 - offset.
208.1004 - """
208.1005 - raise NotImplementedError("tzinfo subclass must override dst()")
208.1006 -
208.1007 - def fromutc(self, dt):
208.1008 - "datetime in UTC -> datetime in local time."
208.1009 -
208.1010 - if not isinstance(dt, datetime):
208.1011 - raise TypeError("fromutc() requires a datetime argument")
208.1012 - if dt.tzinfo is not self:
208.1013 - raise ValueError("dt.tzinfo is not self")
208.1014 -
208.1015 - dtoff = dt.utcoffset()
208.1016 - if dtoff is None:
208.1017 - raise ValueError("fromutc() requires a non-None utcoffset() "
208.1018 - "result")
208.1019 -
208.1020 - # See the long comment block at the end of this file for an
208.1021 - # explanation of this algorithm.
208.1022 - dtdst = dt.dst()
208.1023 - if dtdst is None:
208.1024 - raise ValueError("fromutc() requires a non-None dst() result")
208.1025 - delta = dtoff - dtdst
208.1026 - if delta:
208.1027 - dt += delta
208.1028 - dtdst = dt.dst()
208.1029 - if dtdst is None:
208.1030 - raise ValueError("fromutc(): dt.dst gave inconsistent "
208.1031 - "results; cannot convert")
208.1032 - if dtdst:
208.1033 - return dt + dtdst
208.1034 - else:
208.1035 - return dt
208.1036 -
208.1037 - # Pickle support.
208.1038 -
208.1039 - __safe_for_unpickling__ = True # For Python 2.2
208.1040 -
208.1041 - def __reduce__(self):
208.1042 - getinitargs = getattr(self, "__getinitargs__", None)
208.1043 - if getinitargs:
208.1044 - args = getinitargs()
208.1045 - else:
208.1046 - args = ()
208.1047 - getstate = getattr(self, "__getstate__", None)
208.1048 - if getstate:
208.1049 - state = getstate()
208.1050 - else:
208.1051 - state = getattr(self, "__dict__", None) or None
208.1052 - if state is None:
208.1053 - return (self.__class__, args)
208.1054 - else:
208.1055 - return (self.__class__, args, state)
208.1056 -
208.1057 -_tzinfo_class = tzinfo # so functions w/ args named "tinfo" can get at it
208.1058 -
208.1059 -class time(object):
208.1060 - """Time with time zone.
208.1061 -
208.1062 - Constructors:
208.1063 -
208.1064 - __new__()
208.1065 -
208.1066 - Operators:
208.1067 -
208.1068 - __repr__, __str__
208.1069 - __cmp__, __hash__
208.1070 -
208.1071 - Methods:
208.1072 -
208.1073 - strftime()
208.1074 - isoformat()
208.1075 - utcoffset()
208.1076 - tzname()
208.1077 - dst()
208.1078 -
208.1079 - Properties (readonly):
208.1080 - hour, minute, second, microsecond, tzinfo
208.1081 - """
208.1082 -
208.1083 - def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
208.1084 - """Constructor.
208.1085 -
208.1086 - Arguments:
208.1087 -
208.1088 - hour, minute (required)
208.1089 - second, microsecond (default to zero)
208.1090 - tzinfo (default to None)
208.1091 - """
208.1092 - self = object.__new__(cls)
208.1093 - if isinstance(hour, str):
208.1094 - # Pickle support
208.1095 - self.__setstate((hour, minute or None))
208.1096 - return self
208.1097 - _check_tzinfo_arg(tzinfo)
208.1098 - _check_time_fields(hour, minute, second, microsecond)
208.1099 - self.__hour = hour
208.1100 - self.__minute = minute
208.1101 - self.__second = second
208.1102 - self.__microsecond = microsecond
208.1103 - self._tzinfo = tzinfo
208.1104 - return self
208.1105 -
208.1106 - # Read-only field accessors
208.1107 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
208.1108 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
208.1109 - second = property(lambda self: self.__second, doc="second (0-59)")
208.1110 - microsecond = property(lambda self: self.__microsecond,
208.1111 - doc="microsecond (0-999999)")
208.1112 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
208.1113 -
208.1114 - # Standard conversions, __hash__ (and helpers)
208.1115 -
208.1116 - # Comparisons.
208.1117 -
208.1118 - def __eq__(self, other):
208.1119 - if isinstance(other, time):
208.1120 - return self.__cmp(other) == 0
208.1121 - else:
208.1122 - return False
208.1123 -
208.1124 - def __ne__(self, other):
208.1125 - if isinstance(other, time):
208.1126 - return self.__cmp(other) != 0
208.1127 - else:
208.1128 - return True
208.1129 -
208.1130 - def __le__(self, other):
208.1131 - if isinstance(other, time):
208.1132 - return self.__cmp(other) <= 0
208.1133 - else:
208.1134 - _cmperror(self, other)
208.1135 -
208.1136 - def __lt__(self, other):
208.1137 - if isinstance(other, time):
208.1138 - return self.__cmp(other) < 0
208.1139 - else:
208.1140 - _cmperror(self, other)
208.1141 -
208.1142 - def __ge__(self, other):
208.1143 - if isinstance(other, time):
208.1144 - return self.__cmp(other) >= 0
208.1145 - else:
208.1146 - _cmperror(self, other)
208.1147 -
208.1148 - def __gt__(self, other):
208.1149 - if isinstance(other, time):
208.1150 - return self.__cmp(other) > 0
208.1151 - else:
208.1152 - _cmperror(self, other)
208.1153 -
208.1154 - def __cmp(self, other):
208.1155 - assert isinstance(other, time)
208.1156 - mytz = self._tzinfo
208.1157 - ottz = other._tzinfo
208.1158 - myoff = otoff = None
208.1159 -
208.1160 - if mytz is ottz:
208.1161 - base_compare = True
208.1162 - else:
208.1163 - myoff = self._utcoffset()
208.1164 - otoff = other._utcoffset()
208.1165 - base_compare = myoff == otoff
208.1166 -
208.1167 - if base_compare:
208.1168 - return cmp((self.__hour, self.__minute, self.__second,
208.1169 - self.__microsecond),
208.1170 - (other.__hour, other.__minute, other.__second,
208.1171 - other.__microsecond))
208.1172 - if myoff is None or otoff is None:
208.1173 - # XXX Buggy in 2.2.2.
208.1174 - raise TypeError("cannot compare naive and aware times")
208.1175 - myhhmm = self.__hour * 60 + self.__minute - myoff
208.1176 - othhmm = other.__hour * 60 + other.__minute - otoff
208.1177 - return cmp((myhhmm, self.__second, self.__microsecond),
208.1178 - (othhmm, other.__second, other.__microsecond))
208.1179 -
208.1180 - def __hash__(self):
208.1181 - """Hash."""
208.1182 - tzoff = self._utcoffset()
208.1183 - if not tzoff: # zero or None
208.1184 - return hash(self.__getstate()[0])
208.1185 - h, m = divmod(self.hour * 60 + self.minute - tzoff, 60)
208.1186 - if 0 <= h < 24:
208.1187 - return hash(time(h, m, self.second, self.microsecond))
208.1188 - return hash((h, m, self.second, self.microsecond))
208.1189 -
208.1190 - # Conversion to string
208.1191 -
208.1192 - def _tzstr(self, sep=":"):
208.1193 - """Return formatted timezone offset (+xx:xx) or None."""
208.1194 - off = self._utcoffset()
208.1195 - if off is not None:
208.1196 - if off < 0:
208.1197 - sign = "-"
208.1198 - off = -off
208.1199 - else:
208.1200 - sign = "+"
208.1201 - hh, mm = divmod(off, 60)
208.1202 - assert 0 <= hh < 24
208.1203 - off = "%s%02d%s%02d" % (sign, hh, sep, mm)
208.1204 - return off
208.1205 -
208.1206 - def __repr__(self):
208.1207 - """Convert to formal string, for repr()."""
208.1208 - if self.__microsecond != 0:
208.1209 - s = ", %d, %d" % (self.__second, self.__microsecond)
208.1210 - elif self.__second != 0:
208.1211 - s = ", %d" % self.__second
208.1212 - else:
208.1213 - s = ""
208.1214 - s= "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__,
208.1215 - self.__hour, self.__minute, s)
208.1216 - if self._tzinfo is not None:
208.1217 - assert s[-1:] == ")"
208.1218 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
208.1219 - return s
208.1220 -
208.1221 - def isoformat(self):
208.1222 - """Return the time formatted according to ISO.
208.1223 -
208.1224 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
208.1225 - self.microsecond == 0.
208.1226 - """
208.1227 - s = _format_time(self.__hour, self.__minute, self.__second,
208.1228 - self.__microsecond)
208.1229 - tz = self._tzstr()
208.1230 - if tz:
208.1231 - s += tz
208.1232 - return s
208.1233 -
208.1234 - __str__ = isoformat
208.1235 -
208.1236 - def strftime(self, fmt):
208.1237 - """Format using strftime(). The date part of the timestamp passed
208.1238 - to underlying strftime should not be used.
208.1239 - """
208.1240 - # The year must be >= 1900 else Python's strftime implementation
208.1241 - # can raise a bogus exception.
208.1242 - timetuple = (1900, 1, 1,
208.1243 - self.__hour, self.__minute, self.__second,
208.1244 - 0, 1, -1)
208.1245 - return _wrap_strftime(self, fmt, timetuple)
208.1246 -
208.1247 - # Timezone functions
208.1248 -
208.1249 - def utcoffset(self):
208.1250 - """Return the timezone offset in minutes east of UTC (negative west of
208.1251 - UTC)."""
208.1252 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
208.1253 - offset = _check_utc_offset("utcoffset", offset)
208.1254 - if offset is not None:
208.1255 - offset = timedelta(minutes=offset)
208.1256 - return offset
208.1257 -
208.1258 - # Return an integer (or None) instead of a timedelta (or None).
208.1259 - def _utcoffset(self):
208.1260 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
208.1261 - offset = _check_utc_offset("utcoffset", offset)
208.1262 - return offset
208.1263 -
208.1264 - def tzname(self):
208.1265 - """Return the timezone name.
208.1266 -
208.1267 - Note that the name is 100% informational -- there's no requirement that
208.1268 - it mean anything in particular. For example, "GMT", "UTC", "-500",
208.1269 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
208.1270 - """
208.1271 - name = _call_tzinfo_method(self._tzinfo, "tzname", None)
208.1272 - _check_tzname(name)
208.1273 - return name
208.1274 -
208.1275 - def dst(self):
208.1276 - """Return 0 if DST is not in effect, or the DST offset (in minutes
208.1277 - eastward) if DST is in effect.
208.1278 -
208.1279 - This is purely informational; the DST offset has already been added to
208.1280 - the UTC offset returned by utcoffset() if applicable, so there's no
208.1281 - need to consult dst() unless you're interested in displaying the DST
208.1282 - info.
208.1283 - """
208.1284 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
208.1285 - offset = _check_utc_offset("dst", offset)
208.1286 - if offset is not None:
208.1287 - offset = timedelta(minutes=offset)
208.1288 - return offset
208.1289 -
208.1290 - def replace(self, hour=None, minute=None, second=None, microsecond=None,
208.1291 - tzinfo=True):
208.1292 - """Return a new time with new values for the specified fields."""
208.1293 - if hour is None:
208.1294 - hour = self.hour
208.1295 - if minute is None:
208.1296 - minute = self.minute
208.1297 - if second is None:
208.1298 - second = self.second
208.1299 - if microsecond is None:
208.1300 - microsecond = self.microsecond
208.1301 - if tzinfo is True:
208.1302 - tzinfo = self.tzinfo
208.1303 - _check_time_fields(hour, minute, second, microsecond)
208.1304 - _check_tzinfo_arg(tzinfo)
208.1305 - return time(hour, minute, second, microsecond, tzinfo)
208.1306 -
208.1307 - # Return an integer (or None) instead of a timedelta (or None).
208.1308 - def _dst(self):
208.1309 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
208.1310 - offset = _check_utc_offset("dst", offset)
208.1311 - return offset
208.1312 -
208.1313 - def __nonzero__(self):
208.1314 - if self.second or self.microsecond:
208.1315 - return 1
208.1316 - offset = self._utcoffset() or 0
208.1317 - return self.hour * 60 + self.minute - offset != 0
208.1318 -
208.1319 - # Pickle support.
208.1320 -
208.1321 - __safe_for_unpickling__ = True # For Python 2.2
208.1322 -
208.1323 - def __getstate(self):
208.1324 - us2, us3 = divmod(self.__microsecond, 256)
208.1325 - us1, us2 = divmod(us2, 256)
208.1326 - basestate = ("%c" * 6) % (self.__hour, self.__minute, self.__second,
208.1327 - us1, us2, us3)
208.1328 - if self._tzinfo is None:
208.1329 - return (basestate,)
208.1330 - else:
208.1331 - return (basestate, self._tzinfo)
208.1332 -
208.1333 - def __setstate(self, state):
208.1334 - assert isinstance(state, tuple)
208.1335 - assert 1 <= len(state) <= 2
208.1336 - string = state[0]
208.1337 - assert len(string) == 6
208.1338 - self.__hour, self.__minute, self.__second, us1, us2, us3 = \
208.1339 - map(ord, string)
208.1340 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
208.1341 - if len(state) == 1:
208.1342 - self._tzinfo = None
208.1343 - else:
208.1344 - self._tzinfo = state[1]
208.1345 -
208.1346 - def __reduce__(self):
208.1347 - return (self.__class__, self.__getstate())
208.1348 -
208.1349 -_time_class = time # so functions w/ args named "time" can get at the class
208.1350 -
208.1351 -time.min = time(0, 0, 0)
208.1352 -time.max = time(23, 59, 59, 999999)
208.1353 -time.resolution = timedelta(microseconds=1)
208.1354 -
208.1355 -class datetime(date):
208.1356 -
208.1357 - # XXX needs docstrings
208.1358 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
208.1359 -
208.1360 - def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
208.1361 - microsecond=0, tzinfo=None):
208.1362 - if isinstance(year, str):
208.1363 - # Pickle support
208.1364 - self = date.__new__(cls, year[:4])
208.1365 - self.__setstate((year, month))
208.1366 - return self
208.1367 - _check_tzinfo_arg(tzinfo)
208.1368 - _check_time_fields(hour, minute, second, microsecond)
208.1369 - self = date.__new__(cls, year, month, day)
208.1370 - # XXX This duplicates __year, __month, __day for convenience :-(
208.1371 - self.__year = year
208.1372 - self.__month = month
208.1373 - self.__day = day
208.1374 - self.__hour = hour
208.1375 - self.__minute = minute
208.1376 - self.__second = second
208.1377 - self.__microsecond = microsecond
208.1378 - self._tzinfo = tzinfo
208.1379 - return self
208.1380 -
208.1381 - # Read-only field accessors
208.1382 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
208.1383 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
208.1384 - second = property(lambda self: self.__second, doc="second (0-59)")
208.1385 - microsecond = property(lambda self: self.__microsecond,
208.1386 - doc="microsecond (0-999999)")
208.1387 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
208.1388 -
208.1389 - def fromtimestamp(cls, t, tz=None):
208.1390 - """Construct a datetime from a POSIX timestamp (like time.time()).
208.1391 -
208.1392 - A timezone info object may be passed in as well.
208.1393 - """
208.1394 -
208.1395 - _check_tzinfo_arg(tz)
208.1396 - if tz is None:
208.1397 - converter = _time.localtime
208.1398 - else:
208.1399 - converter = _time.gmtime
208.1400 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
208.1401 - us = int((t % 1.0) * 1000000)
208.1402 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
208.1403 - result = cls(y, m, d, hh, mm, ss, us, tz)
208.1404 - if tz is not None:
208.1405 - result = tz.fromutc(result)
208.1406 - return result
208.1407 - fromtimestamp = classmethod(fromtimestamp)
208.1408 -
208.1409 - def utcfromtimestamp(cls, t):
208.1410 - "Construct a UTC datetime from a POSIX timestamp (like time.time())."
208.1411 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
208.1412 - us = int((t % 1.0) * 1000000)
208.1413 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
208.1414 - return cls(y, m, d, hh, mm, ss, us)
208.1415 - utcfromtimestamp = classmethod(utcfromtimestamp)
208.1416 -
208.1417 - # XXX This is supposed to do better than we *can* do by using time.time(),
208.1418 - # XXX if the platform supports a more accurate way. The C implementation
208.1419 - # XXX uses gettimeofday on platforms that have it, but that isn't
208.1420 - # XXX available from Python. So now() may return different results
208.1421 - # XXX across the implementations.
208.1422 - def now(cls, tz=None):
208.1423 - "Construct a datetime from time.time() and optional time zone info."
208.1424 - t = _time.time()
208.1425 - return cls.fromtimestamp(t, tz)
208.1426 - now = classmethod(now)
208.1427 -
208.1428 - def utcnow(cls):
208.1429 - "Construct a UTC datetime from time.time()."
208.1430 - t = _time.time()
208.1431 - return cls.utcfromtimestamp(t)
208.1432 - utcnow = classmethod(utcnow)
208.1433 -
208.1434 - def combine(cls, date, time):
208.1435 - "Construct a datetime from a given date and a given time."
208.1436 - if not isinstance(date, _date_class):
208.1437 - raise TypeError("date argument must be a date instance")
208.1438 - if not isinstance(time, _time_class):
208.1439 - raise TypeError("time argument must be a time instance")
208.1440 - return cls(date.year, date.month, date.day,
208.1441 - time.hour, time.minute, time.second, time.microsecond,
208.1442 - time.tzinfo)
208.1443 - combine = classmethod(combine)
208.1444 -
208.1445 - def timetuple(self):
208.1446 - "Return local time tuple compatible with time.localtime()."
208.1447 - dst = self._dst()
208.1448 - if dst is None:
208.1449 - dst = -1
208.1450 - elif dst:
208.1451 - dst = 1
208.1452 - return _build_struct_time(self.year, self.month, self.day,
208.1453 - self.hour, self.minute, self.second,
208.1454 - dst)
208.1455 -
208.1456 - def utctimetuple(self):
208.1457 - "Return UTC time tuple compatible with time.gmtime()."
208.1458 - y, m, d = self.year, self.month, self.day
208.1459 - hh, mm, ss = self.hour, self.minute, self.second
208.1460 - offset = self._utcoffset()
208.1461 - if offset: # neither None nor 0
208.1462 - tm = tmxxx(y, m, d, hh, mm - offset)
208.1463 - y, m, d = tm.year, tm.month, tm.day
208.1464 - hh, mm = tm.hour, tm.minute
208.1465 - return _build_struct_time(y, m, d, hh, mm, ss, 0)
208.1466 -
208.1467 - def date(self):
208.1468 - "Return the date part."
208.1469 - return date(self.__year, self.__month, self.__day)
208.1470 -
208.1471 - def time(self):
208.1472 - "Return the time part, with tzinfo None."
208.1473 - return time(self.hour, self.minute, self.second, self.microsecond)
208.1474 -
208.1475 - def timetz(self):
208.1476 - "Return the time part, with same tzinfo."
208.1477 - return time(self.hour, self.minute, self.second, self.microsecond,
208.1478 - self._tzinfo)
208.1479 -
208.1480 - def replace(self, year=None, month=None, day=None, hour=None,
208.1481 - minute=None, second=None, microsecond=None, tzinfo=True):
208.1482 - """Return a new datetime with new values for the specified fields."""
208.1483 - if year is None:
208.1484 - year = self.year
208.1485 - if month is None:
208.1486 - month = self.month
208.1487 - if day is None:
208.1488 - day = self.day
208.1489 - if hour is None:
208.1490 - hour = self.hour
208.1491 - if minute is None:
208.1492 - minute = self.minute
208.1493 - if second is None:
208.1494 - second = self.second
208.1495 - if microsecond is None:
208.1496 - microsecond = self.microsecond
208.1497 - if tzinfo is True:
208.1498 - tzinfo = self.tzinfo
208.1499 - _check_date_fields(year, month, day)
208.1500 - _check_time_fields(hour, minute, second, microsecond)
208.1501 - _check_tzinfo_arg(tzinfo)
208.1502 - return datetime(year, month, day, hour, minute, second,
208.1503 - microsecond, tzinfo)
208.1504 -
208.1505 - def astimezone(self, tz):
208.1506 - if not isinstance(tz, tzinfo):
208.1507 - raise TypeError("tz argument must be an instance of tzinfo")
208.1508 -
208.1509 - mytz = self.tzinfo
208.1510 - if mytz is None:
208.1511 - raise ValueError("astimezone() requires an aware datetime")
208.1512 -
208.1513 - if tz is mytz:
208.1514 - return self
208.1515 -
208.1516 - # Convert self to UTC, and attach the new time zone object.
208.1517 - myoffset = self.utcoffset()
208.1518 - if myoffset is None:
208.1519 - raise ValuError("astimezone() requires an aware datetime")
208.1520 - utc = (self - myoffset).replace(tzinfo=tz)
208.1521 -
208.1522 - # Convert from UTC to tz's local time.
208.1523 - return tz.fromutc(utc)
208.1524 -
208.1525 - # Ways to produce a string.
208.1526 -
208.1527 - def ctime(self):
208.1528 - "Format a la ctime()."
208.1529 - t = tmxxx(self.__year, self.__month, self.__day, self.__hour,
208.1530 - self.__minute, self.__second)
208.1531 - return t.ctime()
208.1532 -
208.1533 - def isoformat(self, sep='T'):
208.1534 - """Return the time formatted according to ISO.
208.1535 -
208.1536 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
208.1537 - self.microsecond == 0.
208.1538 -
208.1539 - If self.tzinfo is not None, the UTC offset is also attached, giving
208.1540 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
208.1541 -
208.1542 - Optional argument sep specifies the separator between date and
208.1543 - time, default 'T'.
208.1544 - """
208.1545 - s = ("%04d-%02d-%02d%c" % (self.__year, self.__month, self.__day,
208.1546 - sep) +
208.1547 - _format_time(self.__hour, self.__minute, self.__second,
208.1548 - self.__microsecond))
208.1549 - off = self._utcoffset()
208.1550 - if off is not None:
208.1551 - if off < 0:
208.1552 - sign = "-"
208.1553 - off = -off
208.1554 - else:
208.1555 - sign = "+"
208.1556 - hh, mm = divmod(off, 60)
208.1557 - s += "%s%02d:%02d" % (sign, hh, mm)
208.1558 - return s
208.1559 -
208.1560 - def __repr__(self):
208.1561 - "Convert to formal string, for repr()."
208.1562 - L = [self.__year, self.__month, self.__day, # These are never zero
208.1563 - self.__hour, self.__minute, self.__second, self.__microsecond]
208.1564 - if L[-1] == 0:
208.1565 - del L[-1]
208.1566 - if L[-1] == 0:
208.1567 - del L[-1]
208.1568 - s = ", ".join(map(str, L))
208.1569 - s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s)
208.1570 - if self._tzinfo is not None:
208.1571 - assert s[-1:] == ")"
208.1572 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
208.1573 - return s
208.1574 -
208.1575 - def __str__(self):
208.1576 - "Convert to string, for str()."
208.1577 - return self.isoformat(sep=' ')
208.1578 -
208.1579 - def utcoffset(self):
208.1580 - """Return the timezone offset in minutes east of UTC (negative west of
208.1581 - UTC)."""
208.1582 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
208.1583 - offset = _check_utc_offset("utcoffset", offset)
208.1584 - if offset is not None:
208.1585 - offset = timedelta(minutes=offset)
208.1586 - return offset
208.1587 -
208.1588 - # Return an integer (or None) instead of a timedelta (or None).
208.1589 - def _utcoffset(self):
208.1590 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
208.1591 - offset = _check_utc_offset("utcoffset", offset)
208.1592 - return offset
208.1593 -
208.1594 - def tzname(self):
208.1595 - """Return the timezone name.
208.1596 -
208.1597 - Note that the name is 100% informational -- there's no requirement that
208.1598 - it mean anything in particular. For example, "GMT", "UTC", "-500",
208.1599 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
208.1600 - """
208.1601 - name = _call_tzinfo_method(self._tzinfo, "tzname", self)
208.1602 - _check_tzname(name)
208.1603 - return name
208.1604 -
208.1605 - def dst(self):
208.1606 - """Return 0 if DST is not in effect, or the DST offset (in minutes
208.1607 - eastward) if DST is in effect.
208.1608 -
208.1609 - This is purely informational; the DST offset has already been added to
208.1610 - the UTC offset returned by utcoffset() if applicable, so there's no
208.1611 - need to consult dst() unless you're interested in displaying the DST
208.1612 - info.
208.1613 - """
208.1614 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
208.1615 - offset = _check_utc_offset("dst", offset)
208.1616 - if offset is not None:
208.1617 - offset = timedelta(minutes=offset)
208.1618 - return offset
208.1619 -
208.1620 - # Return an integer (or None) instead of a timedelta (or None).1573
208.1621 - def _dst(self):
208.1622 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
208.1623 - offset = _check_utc_offset("dst", offset)
208.1624 - return offset
208.1625 -
208.1626 - # Comparisons.
208.1627 -
208.1628 - def __eq__(self, other):
208.1629 - if isinstance(other, datetime):
208.1630 - return self.__cmp(other) == 0
208.1631 - elif hasattr(other, "timetuple"):
208.1632 - return NotImplemented
208.1633 - else:
208.1634 - return False
208.1635 -
208.1636 - def __ne__(self, other):
208.1637 - if isinstance(other, datetime):
208.1638 - return self.__cmp(other) != 0
208.1639 - elif hasattr(other, "timetuple"):
208.1640 - return NotImplemented
208.1641 - else:
208.1642 - return True
208.1643 -
208.1644 - def __le__(self, other):
208.1645 - if isinstance(other, datetime):
208.1646 - return self.__cmp(other) <= 0
208.1647 - elif hasattr(other, "timetuple"):
208.1648 - return NotImplemented
208.1649 - else:
208.1650 - _cmperror(self, other)
208.1651 -
208.1652 - def __lt__(self, other):
208.1653 - if isinstance(other, datetime):
208.1654 - return self.__cmp(other) < 0
208.1655 - elif hasattr(other, "timetuple"):
208.1656 - return NotImplemented
208.1657 - else:
208.1658 - _cmperror(self, other)
208.1659 -
208.1660 - def __ge__(self, other):
208.1661 - if isinstance(other, datetime):
208.1662 - return self.__cmp(other) >= 0
208.1663 - elif hasattr(other, "timetuple"):
208.1664 - return NotImplemented
208.1665 - else:
208.1666 - _cmperror(self, other)
208.1667 -
208.1668 - def __gt__(self, other):
208.1669 - if isinstance(other, datetime):
208.1670 - return self.__cmp(other) > 0
208.1671 - elif hasattr(other, "timetuple"):
208.1672 - return NotImplemented
208.1673 - else:
208.1674 - _cmperror(self, other)
208.1675 -
208.1676 - def __cmp(self, other):
208.1677 - assert isinstance(other, datetime)
208.1678 - mytz = self._tzinfo
208.1679 - ottz = other._tzinfo
208.1680 - myoff = otoff = None
208.1681 -
208.1682 - if mytz is ottz:
208.1683 - base_compare = True
208.1684 - else:
208.1685 - if mytz is not None:
208.1686 - myoff = self._utcoffset()
208.1687 - if ottz is not None:
208.1688 - otoff = other._utcoffset()
208.1689 - base_compare = myoff == otoff
208.1690 -
208.1691 - if base_compare:
208.1692 - return cmp((self.__year, self.__month, self.__day,
208.1693 - self.__hour, self.__minute, self.__second,
208.1694 - self.__microsecond),
208.1695 - (other.__year, other.__month, other.__day,
208.1696 - other.__hour, other.__minute, other.__second,
208.1697 - other.__microsecond))
208.1698 - if myoff is None or otoff is None:
208.1699 - # XXX Buggy in 2.2.2.
208.1700 - raise TypeError("cannot compare naive and aware datetimes")
208.1701 - # XXX What follows could be done more efficiently...
208.1702 - diff = self - other # this will take offsets into account
208.1703 - if diff.days < 0:
208.1704 - return -1
208.1705 - return diff and 1 or 0
208.1706 -
208.1707 - def __add__(self, other):
208.1708 - "Add a datetime and a timedelta."
208.1709 - if not isinstance(other, timedelta):
208.1710 - return NotImplemented
208.1711 - t = tmxxx(self.__year,
208.1712 - self.__month,
208.1713 - self.__day + other.days,
208.1714 - self.__hour,
208.1715 - self.__minute,
208.1716 - self.__second + other.seconds,
208.1717 - self.__microsecond + other.microseconds)
208.1718 - self._checkOverflow(t.year)
208.1719 - result = self.__class__(t.year, t.month, t.day,
208.1720 - t.hour, t.minute, t.second,
208.1721 - t.microsecond, tzinfo=self._tzinfo)
208.1722 - return result
208.1723 -
208.1724 - __radd__ = __add__
208.1725 -
208.1726 - def __sub__(self, other):
208.1727 - "Subtract two datetimes, or a datetime and a timedelta."
208.1728 - if not isinstance(other, datetime):
208.1729 - if isinstance(other, timedelta):
208.1730 - return self + -other
208.1731 - return NotImplemented
208.1732 -
208.1733 - days1 = self.toordinal()
208.1734 - days2 = other.toordinal()
208.1735 - secs1 = self.__second + self.__minute * 60 + self.__hour * 3600
208.1736 - secs2 = other.__second + other.__minute * 60 + other.__hour * 3600
208.1737 - base = timedelta(days1 - days2,
208.1738 - secs1 - secs2,
208.1739 - self.__microsecond - other.__microsecond)
208.1740 - if self._tzinfo is other._tzinfo:
208.1741 - return base
208.1742 - myoff = self._utcoffset()
208.1743 - otoff = other._utcoffset()
208.1744 - if myoff == otoff:
208.1745 - return base
208.1746 - if myoff is None or otoff is None:
208.1747 - raise TypeError, "cannot mix naive and timezone-aware time"
208.1748 - return base + timedelta(minutes = otoff-myoff)
208.1749 -
208.1750 - def __hash__(self):
208.1751 - tzoff = self._utcoffset()
208.1752 - if tzoff is None:
208.1753 - return hash(self.__getstate()[0])
208.1754 - days = _ymd2ord(self.year, self.month, self.day)
208.1755 - seconds = self.hour * 3600 + (self.minute - tzoff) * 60 + self.second
208.1756 - return hash(timedelta(days, seconds, self.microsecond))
208.1757 -
208.1758 - # Pickle support.
208.1759 -
208.1760 - __safe_for_unpickling__ = True # For Python 2.2
208.1761 -
208.1762 - def __getstate(self):
208.1763 - yhi, ylo = divmod(self.__year, 256)
208.1764 - us2, us3 = divmod(self.__microsecond, 256)
208.1765 - us1, us2 = divmod(us2, 256)
208.1766 - basestate = ("%c" * 10) % (yhi, ylo, self.__month, self.__day,
208.1767 - self.__hour, self.__minute, self.__second,
208.1768 - us1, us2, us3)
208.1769 - if self._tzinfo is None:
208.1770 - return (basestate,)
208.1771 - else:
208.1772 - return (basestate, self._tzinfo)
208.1773 -
208.1774 - def __setstate(self, state):
208.1775 - assert isinstance(state, tuple)
208.1776 - assert 1 <= len(state) <= 2
208.1777 - string = state[0]
208.1778 - assert len(string) == 10
208.1779 - (yhi, ylo, self.__month, self.__day, self.__hour,
208.1780 - self.__minute, self.__second, us1, us2, us3) = map(ord, string)
208.1781 - self.__year = yhi * 256 + ylo
208.1782 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
208.1783 - if len(state) == 1:
208.1784 - self._tzinfo = None
208.1785 - else:
208.1786 - self._tzinfo = state[1]
208.1787 -
208.1788 - def __reduce__(self):
208.1789 - return (self.__class__, self.__getstate())
208.1790 -
208.1791 -
208.1792 -datetime.min = datetime(1, 1, 1)
208.1793 -datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
208.1794 -datetime.resolution = timedelta(microseconds=1)
208.1795 -
208.1796 -
208.1797 -def _isoweek1monday(year):
208.1798 - # Helper to calculate the day number of the Monday starting week 1
208.1799 - # XXX This could be done more efficiently
208.1800 - THURSDAY = 3
208.1801 - firstday = _ymd2ord(year, 1, 1)
208.1802 - firstweekday = (firstday + 6) % 7 # See weekday() above
208.1803 - week1monday = firstday - firstweekday
208.1804 - if firstweekday > THURSDAY:
208.1805 - week1monday += 7
208.1806 - return week1monday
208.1807 -
208.1808 -"""
208.1809 -Some time zone algebra. For a datetime x, let
208.1810 - x.n = x stripped of its timezone -- its naive time.
208.1811 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
208.1812 - return None
208.1813 - x.d = x.dst(), and assuming that doesn't raise an exception or
208.1814 - return None
208.1815 - x.s = x's standard offset, x.o - x.d
208.1816 -
208.1817 -Now some derived rules, where k is a duration (timedelta).
208.1818 -
208.1819 -1. x.o = x.s + x.d
208.1820 - This follows from the definition of x.s.
208.1821 -
208.1822 -2. If x and y have the same tzinfo member, x.s = y.s.
208.1823 - This is actually a requirement, an assumption we need to make about
208.1824 - sane tzinfo classes.
208.1825 -
208.1826 -3. The naive UTC time corresponding to x is x.n - x.o.
208.1827 - This is again a requirement for a sane tzinfo class.
208.1828 -
208.1829 -4. (x+k).s = x.s
208.1830 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
208.1831 -
208.1832 -5. (x+k).n = x.n + k
208.1833 - Again follows from how arithmetic is defined.
208.1834 -
208.1835 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
208.1836 -(meaning that the various tzinfo methods exist, and don't blow up or return
208.1837 -None when called).
208.1838 -
208.1839 -The function wants to return a datetime y with timezone tz, equivalent to x.
208.1840 -x is already in UTC.
208.1841 -
208.1842 -By #3, we want
208.1843 -
208.1844 - y.n - y.o = x.n [1]
208.1845 -
208.1846 -The algorithm starts by attaching tz to x.n, and calling that y. So
208.1847 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
208.1848 -becomes true; in effect, we want to solve [2] for k:
208.1849 -
208.1850 - (y+k).n - (y+k).o = x.n [2]
208.1851 -
208.1852 -By #1, this is the same as
208.1853 -
208.1854 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
208.1855 -
208.1856 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
208.1857 -Substituting that into [3],
208.1858 -
208.1859 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
208.1860 - k - (y+k).s - (y+k).d = 0; rearranging,
208.1861 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
208.1862 - k = y.s - (y+k).d
208.1863 -
208.1864 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
208.1865 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
208.1866 -very large, since all offset-returning methods return a duration of magnitude
208.1867 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
208.1868 -be 0, so ignoring it has no consequence then.
208.1869 -
208.1870 -In any case, the new value is
208.1871 -
208.1872 - z = y + y.s [4]
208.1873 -
208.1874 -It's helpful to step back at look at [4] from a higher level: it's simply
208.1875 -mapping from UTC to tz's standard time.
208.1876 -
208.1877 -At this point, if
208.1878 -
208.1879 - z.n - z.o = x.n [5]
208.1880 -
208.1881 -we have an equivalent time, and are almost done. The insecurity here is
208.1882 -at the start of daylight time. Picture US Eastern for concreteness. The wall
208.1883 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
208.1884 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
208.1885 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
208.1886 -on the day DST starts. We want to return the 1:MM EST spelling because that's
208.1887 -the only spelling that makes sense on the local wall clock.
208.1888 -
208.1889 -In fact, if [5] holds at this point, we do have the standard-time spelling,
208.1890 -but that takes a bit of proof. We first prove a stronger result. What's the
208.1891 -difference between the LHS and RHS of [5]? Let
208.1892 -
208.1893 - diff = x.n - (z.n - z.o) [6]
208.1894 -
208.1895 -Now
208.1896 - z.n = by [4]
208.1897 - (y + y.s).n = by #5
208.1898 - y.n + y.s = since y.n = x.n
208.1899 - x.n + y.s = since z and y are have the same tzinfo member,
208.1900 - y.s = z.s by #2
208.1901 - x.n + z.s
208.1902 -
208.1903 -Plugging that back into [6] gives
208.1904 -
208.1905 - diff =
208.1906 - x.n - ((x.n + z.s) - z.o) = expanding
208.1907 - x.n - x.n - z.s + z.o = cancelling
208.1908 - - z.s + z.o = by #2
208.1909 - z.d
208.1910 -
208.1911 -So diff = z.d.
208.1912 -
208.1913 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
208.1914 -spelling we wanted in the endcase described above. We're done. Contrarily,
208.1915 -if z.d = 0, then we have a UTC equivalent, and are also done.
208.1916 -
208.1917 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
208.1918 -add to z (in effect, z is in tz's standard time, and we need to shift the
208.1919 -local clock into tz's daylight time).
208.1920 -
208.1921 -Let
208.1922 -
208.1923 - z' = z + z.d = z + diff [7]
208.1924 -
208.1925 -and we can again ask whether
208.1926 -
208.1927 - z'.n - z'.o = x.n [8]
208.1928 -
208.1929 -If so, we're done. If not, the tzinfo class is insane, according to the
208.1930 -assumptions we've made. This also requires a bit of proof. As before, let's
208.1931 -compute the difference between the LHS and RHS of [8] (and skipping some of
208.1932 -the justifications for the kinds of substitutions we've done several times
208.1933 -already):
208.1934 -
208.1935 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
208.1936 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
208.1937 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
208.1938 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
208.1939 - - z.n + z.n - z.o + z'.o = cancel z.n
208.1940 - - z.o + z'.o = #1 twice
208.1941 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
208.1942 - z'.d - z.d
208.1943 -
208.1944 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
208.1945 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
208.1946 -return z', not bothering to compute z'.d.
208.1947 -
208.1948 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
208.1949 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
208.1950 -would have to change the result dst() returns: we start in DST, and moving
208.1951 -a little further into it takes us out of DST.
208.1952 -
208.1953 -There isn't a sane case where this can happen. The closest it gets is at
208.1954 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
208.1955 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
208.1956 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
208.1957 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
208.1958 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
208.1959 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
208.1960 -standard time. Since that's what the local clock *does*, we want to map both
208.1961 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
208.1962 -in local time, but so it goes -- it's the way the local clock works.
208.1963 -
208.1964 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
208.1965 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
208.1966 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
208.1967 -(correctly) concludes that z' is not UTC-equivalent to x.
208.1968 -
208.1969 -Because we know z.d said z was in daylight time (else [5] would have held and
208.1970 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
208.1971 -and we we have stopped then), and there are only 2 possible values dst() can
208.1972 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
208.1973 -but the reasoning doesn't depend on the example -- it depends on there being
208.1974 -two possible dst() outcomes, one zero and the other non-zero). Therefore
208.1975 -z' must be in standard time, and is the spelling we want in this case.
208.1976 -
208.1977 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
208.1978 -concerned (because it takes z' as being in standard time rather than the
208.1979 -daylight time we intend here), but returning it gives the real-life "local
208.1980 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
208.1981 -tz.
208.1982 -
208.1983 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
208.1984 -the 1:MM standard time spelling we want.
208.1985 -
208.1986 -So how can this break? One of the assumptions must be violated. Two
208.1987 -possibilities:
208.1988 -
208.1989 -1) [2] effectively says that y.s is invariant across all y belong to a given
208.1990 - time zone. This isn't true if, for political reasons or continental drift,
208.1991 - a region decides to change its base offset from UTC.
208.1992 -
208.1993 -2) There may be versions of "double daylight" time where the tail end of
208.1994 - the analysis gives up a step too early. I haven't thought about that
208.1995 - enough to say.
208.1996 -
208.1997 -In any case, it's clear that the default fromutc() is strong enough to handle
208.1998 -"almost all" time zones: so long as the standard offset is invariant, it
208.1999 -doesn't matter if daylight time transition points change from year to year, or
208.2000 -if daylight time is skipped in some years; it doesn't matter how large or
208.2001 -small dst() may get within its bounds; and it doesn't even matter if some
208.2002 -perverse time zone returns a negative dst()). So a breaking case must be
208.2003 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
208.2004 -"""
208.2005 -
208.2006 -def _test():
208.2007 - import test_datetime
208.2008 - test_datetime.test_main()
208.2009 -
208.2010 -if __name__ == "__main__":
208.2011 - _test()
209.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.folds Sun Jan 04 13:11:53 2015 -0600
209.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
209.3 @@ -1,2009 +0,0 @@
209.4 -+ """Concrete date/time and related types -- prototype implemented in Python.
209.5 -|
209.6 -| See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
209.7 -|
209.8 -| See also http://dir.yahoo.com/Reference/calendars/
209.9 -|
209.10 -| For a primer on DST, including many current DST rules, see
209.11 -| http://webexhibits.org/daylightsaving/
209.12 -|
209.13 -| For more about DST than you ever wanted to know, see
209.14 -| ftp://elsie.nci.nih.gov/pub/
209.15 -|
209.16 -| Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
209.17 -|
209.18 -- """
209.19 -
209.20 - import time as _time
209.21 - import math as _math
209.22 -
209.23 - MINYEAR = 1
209.24 - MAXYEAR = 9999
209.25 -
209.26 - # Utility functions, adapted from Python's Demo/classes/Dates.py, which
209.27 - # also assumes the current Gregorian calendar indefinitely extended in
209.28 - # both directions. Difference: Dates.py calls January 1 of year 0 day
209.29 - # number 1. The code here calls January 1 of year 1 day number 1. This is
209.30 - # to match the definition of the "proleptic Gregorian" calendar in Dershowitz
209.31 - # and Reingold's "Calendrical Calculations", where it's the base calendar
209.32 - # for all computations. See the book for algorithms for converting between
209.33 - # proleptic Gregorian ordinals and many other calendar systems.
209.34 -
209.35 - _DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
209.36 -
209.37 - _DAYS_BEFORE_MONTH = [None]
209.38 - dbm = 0
209.39 - for dim in _DAYS_IN_MONTH[1:]:
209.40 - _DAYS_BEFORE_MONTH.append(dbm)
209.41 - dbm += dim
209.42 - del dbm, dim
209.43 -
209.44 -+ def _is_leap(year):
209.45 -| "year -> 1 if leap year, else 0."
209.46 -| return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
209.47 --
209.48 -+ def _days_in_year(year):
209.49 -| "year -> number of days in year (366 if a leap year, else 365)."
209.50 -| return 365 + _is_leap(year)
209.51 --
209.52 -+ def _days_before_year(year):
209.53 -| "year -> number of days before January 1st of year."
209.54 -| y = year - 1
209.55 -| return y*365 + y//4 - y//100 + y//400
209.56 --
209.57 -+ def _days_in_month(year, month):
209.58 -| "year, month -> number of days in that month in that year."
209.59 -| assert 1 <= month <= 12, month
209.60 -| if month == 2 and _is_leap(year):
209.61 -| return 29
209.62 -| return _DAYS_IN_MONTH[month]
209.63 --
209.64 -+ def _days_before_month(year, month):
209.65 -| "year, month -> number of days in year preceeding first day of month."
209.66 -| if not 1 <= month <= 12:
209.67 -| raise ValueError('month must be in 1..12', month)
209.68 -| return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
209.69 --
209.70 -+ def _ymd2ord(year, month, day):
209.71 -| "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
209.72 -| if not 1 <= month <= 12:
209.73 -| raise ValueError('month must be in 1..12', month)
209.74 -| dim = _days_in_month(year, month)
209.75 -| if not 1 <= day <= dim:
209.76 -| raise ValueError('day must be in 1..%d' % dim, day)
209.77 -| return (_days_before_year(year) +
209.78 -| _days_before_month(year, month) +
209.79 -| day)
209.80 --
209.81 - _DI400Y = _days_before_year(401) # number of days in 400 years
209.82 - _DI100Y = _days_before_year(101) # " " " " 100 "
209.83 - _DI4Y = _days_before_year(5) # " " " " 4 "
209.84 -
209.85 - # A 4-year cycle has an extra leap day over what we'd get from pasting
209.86 - # together 4 single years.
209.87 - assert _DI4Y == 4 * 365 + 1
209.88 -
209.89 - # Similarly, a 400-year cycle has an extra leap day over what we'd get from
209.90 - # pasting together 4 100-year cycles.
209.91 - assert _DI400Y == 4 * _DI100Y + 1
209.92 -
209.93 - # OTOH, a 100-year cycle has one fewer leap day than we'd get from
209.94 - # pasting together 25 4-year cycles.
209.95 - assert _DI100Y == 25 * _DI4Y - 1
209.96 -
209.97 -+ def _ord2ymd(n):
209.98 -| "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
209.99 -|
209.100 -| # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
209.101 -| # repeats exactly every 400 years. The basic strategy is to find the
209.102 -| # closest 400-year boundary at or before n, then work with the offset
209.103 -| # from that boundary to n. Life is much clearer if we subtract 1 from
209.104 -| # n first -- then the values of n at 400-year boundaries are exactly
209.105 -| # those divisible by _DI400Y:
209.106 -| #
209.107 -| # D M Y n n-1
209.108 -| # -- --- ---- ---------- ----------------
209.109 -| # 31 Dec -400 -_DI400Y -_DI400Y -1
209.110 -| # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
209.111 -| # ...
209.112 -| # 30 Dec 000 -1 -2
209.113 -| # 31 Dec 000 0 -1
209.114 -| # 1 Jan 001 1 0 400-year boundary
209.115 -| # 2 Jan 001 2 1
209.116 -| # 3 Jan 001 3 2
209.117 -| # ...
209.118 -| # 31 Dec 400 _DI400Y _DI400Y -1
209.119 -| # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
209.120 -| n -= 1
209.121 -| n400, n = divmod(n, _DI400Y)
209.122 -| year = n400 * 400 + 1 # ..., -399, 1, 401, ...
209.123 -|
209.124 -| # Now n is the (non-negative) offset, in days, from January 1 of year, to
209.125 -| # the desired date. Now compute how many 100-year cycles precede n.
209.126 -| # Note that it's possible for n100 to equal 4! In that case 4 full
209.127 -| # 100-year cycles precede the desired day, which implies the desired
209.128 -| # day is December 31 at the end of a 400-year cycle.
209.129 -| n100, n = divmod(n, _DI100Y)
209.130 -|
209.131 -| # Now compute how many 4-year cycles precede it.
209.132 -| n4, n = divmod(n, _DI4Y)
209.133 -|
209.134 -| # And now how many single years. Again n1 can be 4, and again meaning
209.135 -| # that the desired day is December 31 at the end of the 4-year cycle.
209.136 -| n1, n = divmod(n, 365)
209.137 -|
209.138 -| year += n100 * 100 + n4 * 4 + n1
209.139 -| if n1 == 4 or n100 == 4:
209.140 -| assert n == 0
209.141 -| return year-1, 12, 31
209.142 -|
209.143 -| # Now the year is correct, and n is the offset from January 1. We find
209.144 -| # the month via an estimate that's either exact or one too large.
209.145 -| leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
209.146 -| assert leapyear == _is_leap(year)
209.147 -| month = (n + 50) >> 5
209.148 -| preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
209.149 -| if preceding > n: # estimate is too large
209.150 -| month -= 1
209.151 -| preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
209.152 -| n -= preceding
209.153 -| assert 0 <= n < _days_in_month(year, month)
209.154 -|
209.155 -| # Now the year and month are correct, and n is the offset from the
209.156 -| # start of that month: we're done!
209.157 -| return year, month, n+1
209.158 -|
209.159 -- # Month and day names. For localized versions, see the calendar module.
209.160 - _MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
209.161 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
209.162 - _DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
209.163 -
209.164 -
209.165 -+ def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
209.166 -| wday = (_ymd2ord(y, m, d) + 6) % 7
209.167 -| dnum = _days_before_month(y, m) + d
209.168 -| return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
209.169 --
209.170 -+ def _format_time(hh, mm, ss, us):
209.171 -| # Skip trailing microseconds when us==0.
209.172 -| result = "%02d:%02d:%02d" % (hh, mm, ss)
209.173 -| if us:
209.174 -| result += ".%06d" % us
209.175 -| return result
209.176 -|
209.177 -- # Correctly substitute for %z and %Z escapes in strftime formats.
209.178 -+ def _wrap_strftime(object, format, timetuple):
209.179 -| year = timetuple[0]
209.180 -| if year < 1900:
209.181 -+ raise ValueError("year=%d is before 1900; the datetime strftime() "
209.182 -| "methods require year >= 1900" % year)
209.183 -| # Don't call _utcoffset() or tzname() unless actually needed.
209.184 -| zreplace = None # the string to use for %z
209.185 -| Zreplace = None # the string to use for %Z
209.186 -|
209.187 -| # Scan format for %z and %Z escapes, replacing as needed.
209.188 -| newformat = []
209.189 -| push = newformat.append
209.190 -| i, n = 0, len(format)
209.191 -| while i < n:
209.192 -| ch = format[i]
209.193 -| i += 1
209.194 -| if ch == '%':
209.195 -| if i < n:
209.196 -| ch = format[i]
209.197 -| i += 1
209.198 -| if ch == 'z':
209.199 -| if zreplace is None:
209.200 -| zreplace = ""
209.201 -| if hasattr(object, "_utcoffset"):
209.202 -| offset = object._utcoffset()
209.203 -| if offset is not None:
209.204 -| sign = '+'
209.205 -| if offset < 0:
209.206 -| offset = -offset
209.207 -| sign = '-'
209.208 -| h, m = divmod(offset, 60)
209.209 -| zreplace = '%c%02d%02d' % (sign, h, m)
209.210 -| assert '%' not in zreplace
209.211 -| newformat.append(zreplace)
209.212 -| elif ch == 'Z':
209.213 -| if Zreplace is None:
209.214 -| Zreplace = ""
209.215 -| if hasattr(object, "tzname"):
209.216 -| s = object.tzname()
209.217 -| if s is not None:
209.218 -| # strftime is going to have at this: escape %
209.219 -| Zreplace = s.replace('%', '%%')
209.220 -| newformat.append(Zreplace)
209.221 -| else:
209.222 -| push('%')
209.223 -| push(ch)
209.224 -| else:
209.225 -| push('%')
209.226 -| else:
209.227 -| push(ch)
209.228 -| newformat = "".join(newformat)
209.229 -| return _time.strftime(newformat, timetuple)
209.230 --
209.231 -+ def _call_tzinfo_method(tzinfo, methname, tzinfoarg):
209.232 -| if tzinfo is None:
209.233 -| return None
209.234 -| return getattr(tzinfo, methname)(tzinfoarg)
209.235 -|
209.236 -- # Just raise TypeError if the arg isn't None or a string.
209.237 -+ def _check_tzname(name):
209.238 -| if name is not None and not isinstance(name, str):
209.239 -+ raise TypeError("tzinfo.tzname() must return None or string, "
209.240 -| "not '%s'" % type(name))
209.241 -|
209.242 -| # name is the offset-producing method, "utcoffset" or "dst".
209.243 -| # offset is what it returned.
209.244 -| # If offset isn't None or timedelta, raises TypeError.
209.245 -| # If offset is None, returns None.
209.246 -| # Else offset is checked for being in range, and a whole # of minutes.
209.247 -- # If it is, its integer value is returned. Else ValueError is raised.
209.248 -+ def _check_utc_offset(name, offset):
209.249 -| assert name in ("utcoffset", "dst")
209.250 -| if offset is None:
209.251 -| return None
209.252 -| if not isinstance(offset, timedelta):
209.253 -+ raise TypeError("tzinfo.%s() must return None "
209.254 -| "or timedelta, not '%s'" % (name, type(offset)))
209.255 -| days = offset.days
209.256 -| if days < -1 or days > 0:
209.257 -| offset = 1440 # trigger out-of-range
209.258 -| else:
209.259 -| seconds = days * 86400 + offset.seconds
209.260 -| minutes, seconds = divmod(seconds, 60)
209.261 -| if seconds or offset.microseconds:
209.262 -+ raise ValueError("tzinfo.%s() must return a whole number "
209.263 -| "of minutes" % name)
209.264 -| offset = minutes
209.265 -| if -1440 < offset < 1440:
209.266 -| return offset
209.267 -| raise ValueError("%s()=%d, must be in -1439..1439" % (name, offset))
209.268 --
209.269 -+ def _check_date_fields(year, month, day):
209.270 -| if not MINYEAR <= year <= MAXYEAR:
209.271 -| raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
209.272 -| if not 1 <= month <= 12:
209.273 -| raise ValueError('month must be in 1..12', month)
209.274 -| dim = _days_in_month(year, month)
209.275 -| if not 1 <= day <= dim:
209.276 -| raise ValueError('day must be in 1..%d' % dim, day)
209.277 --
209.278 -+ def _check_time_fields(hour, minute, second, microsecond):
209.279 -| if not 0 <= hour <= 23:
209.280 -| raise ValueError('hour must be in 0..23', hour)
209.281 -| if not 0 <= minute <= 59:
209.282 -| raise ValueError('minute must be in 0..59', minute)
209.283 -| if not 0 <= second <= 59:
209.284 -| raise ValueError('second must be in 0..59', second)
209.285 -| if not 0 <= microsecond <= 999999:
209.286 -| raise ValueError('microsecond must be in 0..999999', microsecond)
209.287 --
209.288 -+ def _check_tzinfo_arg(tz):
209.289 -| if tz is not None and not isinstance(tz, tzinfo):
209.290 -| raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
209.291 -|
209.292 -|
209.293 -| # Notes on comparison: In general, datetime module comparison operators raise
209.294 -| # TypeError when they don't know how to do a comparison themself. If they
209.295 -| # returned NotImplemented instead, comparison could (silently) fall back to
209.296 -| # the default compare-objects-by-comparing-their-memory-addresses strategy,
209.297 -| # and that's not helpful. There are two exceptions:
209.298 -| #
209.299 -| # 1. For date and datetime, if the other object has a "timetuple" attr,
209.300 -| # NotImplemented is returned. This is a hook to allow other kinds of
209.301 -| # datetime-like objects a chance to intercept the comparison.
209.302 -| #
209.303 -| # 2. Else __eq__ and __ne__ return False and True, respectively. This is
209.304 -| # so opertaions like
209.305 -| #
209.306 -| # x == y
209.307 -| # x != y
209.308 -| # x in sequence
209.309 -| # x not in sequence
209.310 -| # dict[x] = y
209.311 -| #
209.312 -| # don't raise annoying TypeErrors just because a datetime object
209.313 -| # is part of a heterogeneous collection. If there's no known way to
209.314 -| # compare X to a datetime, saying they're not equal is reasonable.
209.315 --
209.316 -+ def _cmperror(x, y):
209.317 -| raise TypeError("can't compare '%s' to '%s'" % (
209.318 -| type(x).__name__, type(y).__name__))
209.319 -|
209.320 -| # This is a start at a struct tm workalike. Goals:
209.321 -| #
209.322 -| # + Works the same way across platforms.
209.323 -| # + Handles all the fields datetime needs handled, without 1970-2038 glitches.
209.324 -| #
209.325 -| # Note: I suspect it's best if this flavor of tm does *not* try to
209.326 -| # second-guess timezones or DST. Instead fold whatever adjustments you want
209.327 -| # into the minutes argument (and the constructor will normalize).
209.328 --
209.329 - _ORD1970 = _ymd2ord(1970, 1, 1) # base ordinal for UNIX epoch
209.330 -
209.331 -+ class tmxxx:
209.332 -|
209.333 -| ordinal = None
209.334 -|
209.335 -+ def __init__(self, year, month, day, hour=0, minute=0, second=0,
209.336 -| microsecond=0):
209.337 -| # Normalize all the inputs, and store the normalized values.
209.338 -| if not 0 <= microsecond <= 999999:
209.339 -| carry, microsecond = divmod(microsecond, 1000000)
209.340 -| second += carry
209.341 -| if not 0 <= second <= 59:
209.342 -| carry, second = divmod(second, 60)
209.343 -| minute += carry
209.344 -| if not 0 <= minute <= 59:
209.345 -| carry, minute = divmod(minute, 60)
209.346 -| hour += carry
209.347 -| if not 0 <= hour <= 23:
209.348 -| carry, hour = divmod(hour, 24)
209.349 -| day += carry
209.350 -|
209.351 -| # That was easy. Now it gets muddy: the proper range for day
209.352 -| # can't be determined without knowing the correct month and year,
209.353 -| # but if day is, e.g., plus or minus a million, the current month
209.354 -| # and year values make no sense (and may also be out of bounds
209.355 -| # themselves).
209.356 -| # Saying 12 months == 1 year should be non-controversial.
209.357 -| if not 1 <= month <= 12:
209.358 -| carry, month = divmod(month-1, 12)
209.359 -| year += carry
209.360 -| month += 1
209.361 -| assert 1 <= month <= 12
209.362 -|
209.363 -| # Now only day can be out of bounds (year may also be out of bounds
209.364 -| # for a datetime object, but we don't care about that here).
209.365 -| # If day is out of bounds, what to do is arguable, but at least the
209.366 -| # method here is principled and explainable.
209.367 -| dim = _days_in_month(year, month)
209.368 -| if not 1 <= day <= dim:
209.369 -| # Move day-1 days from the first of the month. First try to
209.370 -| # get off cheap if we're only one day out of range (adjustments
209.371 -| # for timezone alone can't be worse than that).
209.372 -| if day == 0: # move back a day
209.373 -| month -= 1
209.374 -| if month > 0:
209.375 -| day = _days_in_month(year, month)
209.376 -| else:
209.377 -| year, month, day = year-1, 12, 31
209.378 -| elif day == dim + 1: # move forward a day
209.379 -| month += 1
209.380 -| day = 1
209.381 -| if month > 12:
209.382 -| month = 1
209.383 -| year += 1
209.384 -| else:
209.385 -| self.ordinal = _ymd2ord(year, month, 1) + (day - 1)
209.386 -| year, month, day = _ord2ymd(self.ordinal)
209.387 -|
209.388 -| self.year, self.month, self.day = year, month, day
209.389 -| self.hour, self.minute, self.second = hour, minute, second
209.390 -| self.microsecond = microsecond
209.391 --
209.392 -+ def toordinal(self):
209.393 -+ """Return proleptic Gregorian ordinal for the year, month and day.
209.394 -|
209.395 -| January 1 of year 1 is day 1. Only the year, month and day values
209.396 -| contribute to the result.
209.397 -- """
209.398 -| if self.ordinal is None:
209.399 -| self.ordinal = _ymd2ord(self.year, self.month, self.day)
209.400 -| return self.ordinal
209.401 --
209.402 -+ def time(self):
209.403 -| "Return Unixish timestamp, as a float (assuming UTC)."
209.404 -| days = self.toordinal() - _ORD1970 # convert to UNIX epoch
209.405 -| seconds = ((days * 24. + self.hour)*60. + self.minute)*60.
209.406 -| return seconds + self.second + self.microsecond / 1e6
209.407 --
209.408 -+ def ctime(self):
209.409 -| "Return ctime() style string."
209.410 -| weekday = self.toordinal() % 7 or 7
209.411 -| return "%s %s %2d %02d:%02d:%02d %04d" % (
209.412 -| _DAYNAMES[weekday],
209.413 -| _MONTHNAMES[self.month],
209.414 -| self.day,
209.415 -| self.hour, self.minute, self.second,
209.416 -| self.year)
209.417 --
209.418 -+ class timedelta(object):
209.419 -+ """Represent the difference between two datetime objects.
209.420 -|
209.421 -| Supported operators:
209.422 -|
209.423 -| - add, subtract timedelta
209.424 -| - unary plus, minus, abs
209.425 -| - compare to timedelta
209.426 -| - multiply, divide by int/long
209.427 -|
209.428 -| In addition, datetime supports subtraction of two datetime objects
209.429 -| returning a timedelta, and addition or subtraction of a datetime
209.430 -| and a timedelta giving a datetime.
209.431 -|
209.432 -| Representation: (days, seconds, microseconds). Why? Because I
209.433 -| felt like it.
209.434 -- """
209.435 -|
209.436 -+ def __new__(cls, days=0, seconds=0, microseconds=0,
209.437 -| # XXX The following should only be used as keyword args:
209.438 -| milliseconds=0, minutes=0, hours=0, weeks=0):
209.439 -| # Doing this efficiently and accurately in C is going to be difficult
209.440 -| # and error-prone, due to ubiquitous overflow possibilities, and that
209.441 -| # C double doesn't have enough bits of precision to represent
209.442 -| # microseconds over 10K years faithfully. The code here tries to make
209.443 -| # explicit where go-fast assumptions can be relied on, in order to
209.444 -| # guide the C implementation; it's way more convoluted than speed-
209.445 -| # ignoring auto-overflow-to-long idiomatic Python could be.
209.446 -|
209.447 -| # XXX Check that all inputs are ints, longs or floats.
209.448 -|
209.449 -| # Final values, all integer.
209.450 -| # s and us fit in 32-bit signed ints; d isn't bounded.
209.451 -| d = s = us = 0
209.452 -|
209.453 -| # Normalize everything to days, seconds, microseconds.
209.454 -| days += weeks*7
209.455 -| seconds += minutes*60 + hours*3600
209.456 -| microseconds += milliseconds*1000
209.457 -|
209.458 -| # Get rid of all fractions, and normalize s and us.
209.459 -| # Take a deep breath <wink>.
209.460 -| if isinstance(days, float):
209.461 -| dayfrac, days = _math.modf(days)
209.462 -| daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
209.463 -| assert daysecondswhole == int(daysecondswhole) # can't overflow
209.464 -| s = int(daysecondswhole)
209.465 -| assert days == long(days)
209.466 -| d = long(days)
209.467 -| else:
209.468 -| daysecondsfrac = 0.0
209.469 -| d = days
209.470 -| assert isinstance(daysecondsfrac, float)
209.471 -| assert abs(daysecondsfrac) <= 1.0
209.472 -| assert isinstance(d, (int, long))
209.473 -| assert abs(s) <= 24 * 3600
209.474 -| # days isn't referenced again before redefinition
209.475 -|
209.476 -| if isinstance(seconds, float):
209.477 -| secondsfrac, seconds = _math.modf(seconds)
209.478 -| assert seconds == long(seconds)
209.479 -| seconds = long(seconds)
209.480 -| secondsfrac += daysecondsfrac
209.481 -| assert abs(secondsfrac) <= 2.0
209.482 -| else:
209.483 -| secondsfrac = daysecondsfrac
209.484 -| # daysecondsfrac isn't referenced again
209.485 -| assert isinstance(secondsfrac, float)
209.486 -| assert abs(secondsfrac) <= 2.0
209.487 -|
209.488 -| assert isinstance(seconds, (int, long))
209.489 -| days, seconds = divmod(seconds, 24*3600)
209.490 -| d += days
209.491 -| s += int(seconds) # can't overflow
209.492 -| assert isinstance(s, int)
209.493 -| assert abs(s) <= 2 * 24 * 3600
209.494 -| # seconds isn't referenced again before redefinition
209.495 -|
209.496 -| usdouble = secondsfrac * 1e6
209.497 -| assert abs(usdouble) < 2.1e6 # exact value not critical
209.498 -| # secondsfrac isn't referenced again
209.499 -|
209.500 -| if isinstance(microseconds, float):
209.501 -| microseconds += usdouble
209.502 -| microseconds = round(microseconds)
209.503 -| seconds, microseconds = divmod(microseconds, 1e6)
209.504 -| assert microseconds == int(microseconds)
209.505 -| assert seconds == long(seconds)
209.506 -| days, seconds = divmod(seconds, 24.*3600.)
209.507 -| assert days == long(days)
209.508 -| assert seconds == int(seconds)
209.509 -| d += long(days)
209.510 -| s += int(seconds) # can't overflow
209.511 -| assert isinstance(s, int)
209.512 -| assert abs(s) <= 3 * 24 * 3600
209.513 -| else:
209.514 -| seconds, microseconds = divmod(microseconds, 1000000)
209.515 -| days, seconds = divmod(seconds, 24*3600)
209.516 -| d += days
209.517 -| s += int(seconds) # can't overflow
209.518 -| assert isinstance(s, int)
209.519 -| assert abs(s) <= 3 * 24 * 3600
209.520 -| microseconds = float(microseconds)
209.521 -| microseconds += usdouble
209.522 -| microseconds = round(microseconds)
209.523 -| assert abs(s) <= 3 * 24 * 3600
209.524 -| assert abs(microseconds) < 3.1e6
209.525 -|
209.526 -| # Just a little bit of carrying possible for microseconds and seconds.
209.527 -| assert isinstance(microseconds, float)
209.528 -| assert int(microseconds) == microseconds
209.529 -| us = int(microseconds)
209.530 -| seconds, us = divmod(us, 1000000)
209.531 -| s += seconds # cant't overflow
209.532 -| assert isinstance(s, int)
209.533 -| days, s = divmod(s, 24*3600)
209.534 -| d += days
209.535 -|
209.536 -| assert isinstance(d, (int, long))
209.537 -| assert isinstance(s, int) and 0 <= s < 24*3600
209.538 -| assert isinstance(us, int) and 0 <= us < 1000000
209.539 -|
209.540 -| self = object.__new__(cls)
209.541 -|
209.542 -| self.__days = d
209.543 -| self.__seconds = s
209.544 -| self.__microseconds = us
209.545 -| if abs(d) > 999999999:
209.546 -| raise OverflowError("timedelta # of days is too large: %d" % d)
209.547 -|
209.548 -| return self
209.549 --
209.550 -+ def __repr__(self):
209.551 -| if self.__microseconds:
209.552 -| return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
209.553 -| self.__days,
209.554 -| self.__seconds,
209.555 -| self.__microseconds)
209.556 -| if self.__seconds:
209.557 -| return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__,
209.558 -| self.__days,
209.559 -| self.__seconds)
209.560 -| return "%s(%d)" % ('datetime.' + self.__class__.__name__, self.__days)
209.561 --
209.562 -+ def __str__(self):
209.563 -| mm, ss = divmod(self.__seconds, 60)
209.564 -| hh, mm = divmod(mm, 60)
209.565 -| s = "%d:%02d:%02d" % (hh, mm, ss)
209.566 -| if self.__days:
209.567 -+ def plural(n):
209.568 -- return n, abs(n) != 1 and "s" or ""
209.569 -| s = ("%d day%s, " % plural(self.__days)) + s
209.570 -| if self.__microseconds:
209.571 -| s = s + ".%06d" % self.__microseconds
209.572 -| return s
209.573 --
209.574 -| days = property(lambda self: self.__days, doc="days")
209.575 -| seconds = property(lambda self: self.__seconds, doc="seconds")
209.576 -| microseconds = property(lambda self: self.__microseconds,
209.577 -| doc="microseconds")
209.578 -|
209.579 -+ def __add__(self, other):
209.580 -| if isinstance(other, timedelta):
209.581 -| return timedelta(self.__days + other.__days,
209.582 -| self.__seconds + other.__seconds,
209.583 -| self.__microseconds + other.__microseconds)
209.584 -| return NotImplemented
209.585 --
209.586 -| __radd__ = __add__
209.587 -|
209.588 -+ def __sub__(self, other):
209.589 -| if isinstance(other, timedelta):
209.590 -| return self + -other
209.591 -| return NotImplemented
209.592 --
209.593 -+ def __rsub__(self, other):
209.594 -| if isinstance(other, timedelta):
209.595 -| return -self + other
209.596 -| return NotImplemented
209.597 --
209.598 -+ def __neg__(self):
209.599 -| return self.__class__(-self.__days,
209.600 -| -self.__seconds,
209.601 -| -self.__microseconds)
209.602 --
209.603 -+ def __pos__(self):
209.604 -| return self
209.605 --
209.606 -+ def __abs__(self):
209.607 -| if self.__days < 0:
209.608 -| return -self
209.609 -| else:
209.610 -| return self
209.611 --
209.612 -+ def __mul__(self, other):
209.613 -| if isinstance(other, (int, long)):
209.614 -| return self.__class__(self.__days * other,
209.615 -| self.__seconds * other,
209.616 -| self.__microseconds * other)
209.617 -| return NotImplemented
209.618 --
209.619 -| __rmul__ = __mul__
209.620 -|
209.621 -+ def __div__(self, other):
209.622 -| if isinstance(other, (int, long)):
209.623 -| usec = ((self.__days * (24*3600L) + self.__seconds) * 1000000 +
209.624 -| self.__microseconds)
209.625 -| return self.__class__(0, 0, usec // other)
209.626 -| return NotImplemented
209.627 --
209.628 -| __floordiv__ = __div__
209.629 -|
209.630 -| # Comparisons.
209.631 -|
209.632 -+ def __eq__(self, other):
209.633 -| if isinstance(other, timedelta):
209.634 -| return self.__cmp(other) == 0
209.635 -| else:
209.636 -| return False
209.637 --
209.638 -+ def __ne__(self, other):
209.639 -| if isinstance(other, timedelta):
209.640 -| return self.__cmp(other) != 0
209.641 -| else:
209.642 -| return True
209.643 --
209.644 -+ def __le__(self, other):
209.645 -| if isinstance(other, timedelta):
209.646 -| return self.__cmp(other) <= 0
209.647 -| else:
209.648 -| _cmperror(self, other)
209.649 --
209.650 -+ def __lt__(self, other):
209.651 -| if isinstance(other, timedelta):
209.652 -| return self.__cmp(other) < 0
209.653 -| else:
209.654 -| _cmperror(self, other)
209.655 --
209.656 -+ def __ge__(self, other):
209.657 -| if isinstance(other, timedelta):
209.658 -| return self.__cmp(other) >= 0
209.659 -| else:
209.660 -| _cmperror(self, other)
209.661 --
209.662 -+ def __gt__(self, other):
209.663 -| if isinstance(other, timedelta):
209.664 -| return self.__cmp(other) > 0
209.665 -| else:
209.666 -| _cmperror(self, other)
209.667 --
209.668 -+ def __cmp(self, other):
209.669 -| assert isinstance(other, timedelta)
209.670 -| return cmp(self.__getstate(), other.__getstate())
209.671 --
209.672 -+ def __hash__(self):
209.673 -| return hash(self.__getstate())
209.674 --
209.675 -+ def __nonzero__(self):
209.676 -| return (self.__days != 0 or
209.677 -| self.__seconds != 0 or
209.678 -| self.__microseconds != 0)
209.679 -|
209.680 -| # Pickle support.
209.681 --
209.682 -| __safe_for_unpickling__ = True # For Python 2.2
209.683 -|
209.684 -+ def __getstate(self):
209.685 -| return (self.__days, self.__seconds, self.__microseconds)
209.686 --
209.687 -+ def __reduce__(self):
209.688 -| return (self.__class__, self.__getstate())
209.689 --
209.690 - timedelta.min = timedelta(-999999999)
209.691 - timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
209.692 - microseconds=999999)
209.693 - timedelta.resolution = timedelta(microseconds=1)
209.694 -
209.695 -+ class date(object):
209.696 -+ """Concrete date type.
209.697 -|
209.698 -| Constructors:
209.699 -|
209.700 -| __new__()
209.701 -| fromtimestamp()
209.702 -| today()
209.703 -| fromordinal()
209.704 -|
209.705 -| Operators:
209.706 -|
209.707 -| __repr__, __str__
209.708 -| __cmp__, __hash__
209.709 -| __add__, __radd__, __sub__ (add/radd only with timedelta arg)
209.710 -|
209.711 -| Methods:
209.712 -|
209.713 -| timetuple()
209.714 -| toordinal()
209.715 -| weekday()
209.716 -| isoweekday(), isocalendar(), isoformat()
209.717 -| ctime()
209.718 -| strftime()
209.719 -|
209.720 -| Properties (readonly):
209.721 -| year, month, day
209.722 -- """
209.723 -|
209.724 -+ def __new__(cls, year, month=None, day=None):
209.725 -+ """Constructor.
209.726 -|
209.727 -| Arguments:
209.728 -|
209.729 -| year, month, day (required, base 1)
209.730 -- """
209.731 -| if isinstance(year, str):
209.732 -| # Pickle support
209.733 -| self = object.__new__(cls)
209.734 -| self.__setstate((year,))
209.735 -| return self
209.736 -| _check_date_fields(year, month, day)
209.737 -| self = object.__new__(cls)
209.738 -| self.__year = year
209.739 -| self.__month = month
209.740 -| self.__day = day
209.741 -| return self
209.742 -|
209.743 -| # Additional constructors
209.744 --
209.745 -+ def fromtimestamp(cls, t):
209.746 -| "Construct a date from a POSIX timestamp (like time.time())."
209.747 -| y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
209.748 -- return cls(y, m, d)
209.749 -| fromtimestamp = classmethod(fromtimestamp)
209.750 -|
209.751 -+ def today(cls):
209.752 -| "Construct a date from time.time()."
209.753 -| t = _time.time()
209.754 -- return cls.fromtimestamp(t)
209.755 -| today = classmethod(today)
209.756 -|
209.757 -+ def fromordinal(cls, n):
209.758 -+ """Contruct a date from a proleptic Gregorian ordinal.
209.759 -|
209.760 -| January 1 of year 1 is day 1. Only the year, month and day are
209.761 -| non-zero in the result.
209.762 -- """
209.763 -| y, m, d = _ord2ymd(n)
209.764 -- return cls(y, m, d)
209.765 -| fromordinal = classmethod(fromordinal)
209.766 -|
209.767 -| # Conversions to string
209.768 -|
209.769 -+ def __repr__(self):
209.770 -| "Convert to formal string, for repr()."
209.771 -| return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
209.772 -| self.__year,
209.773 -| self.__month,
209.774 -| self.__day)
209.775 -| # XXX These shouldn't depend on time.localtime(), because that
209.776 -| # clips the usable dates to [1970 .. 2038). At least ctime() is
209.777 -| # easily done without using strftime() -- that's better too because
209.778 -| # strftime("%c", ...) is locale specific.
209.779 --
209.780 -+ def ctime(self):
209.781 -| "Format a la ctime()."
209.782 -| return tmxxx(self.__year, self.__month, self.__day).ctime()
209.783 --
209.784 -+ def strftime(self, fmt):
209.785 -| "Format using strftime()."
209.786 -| return _wrap_strftime(self, fmt, self.timetuple())
209.787 --
209.788 -+ def isoformat(self):
209.789 -+ """Return the date formatted according to ISO.
209.790 -|
209.791 -| This is 'YYYY-MM-DD'.
209.792 -|
209.793 -| References:
209.794 -| - http://www.w3.org/TR/NOTE-datetime
209.795 -| - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
209.796 -- """
209.797 -| return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day)
209.798 --
209.799 -| __str__ = isoformat
209.800 -|
209.801 -| # Read-only field accessors
209.802 -| year = property(lambda self: self.__year,
209.803 -| doc="year (%d-%d)" % (MINYEAR, MAXYEAR))
209.804 -| month = property(lambda self: self.__month, doc="month (1-12)")
209.805 -| day = property(lambda self: self.__day, doc="day (1-31)")
209.806 -|
209.807 -| # Standard conversions, __cmp__, __hash__ (and helpers)
209.808 -|
209.809 -+ def timetuple(self):
209.810 -| "Return local time tuple compatible with time.localtime()."
209.811 -| return _build_struct_time(self.__year, self.__month, self.__day,
209.812 -| 0, 0, 0, -1)
209.813 --
209.814 -+ def toordinal(self):
209.815 -+ """Return proleptic Gregorian ordinal for the year, month and day.
209.816 -|
209.817 -| January 1 of year 1 is day 1. Only the year, month and day values
209.818 -| contribute to the result.
209.819 -- """
209.820 -| return _ymd2ord(self.__year, self.__month, self.__day)
209.821 --
209.822 -+ def replace(self, year=None, month=None, day=None):
209.823 -| """Return a new date with new values for the specified fields."""
209.824 -| if year is None:
209.825 -| year = self.__year
209.826 -| if month is None:
209.827 -| month = self.__month
209.828 -| if day is None:
209.829 -| day = self.__day
209.830 -| _check_date_fields(year, month, day)
209.831 -| return date(year, month, day)
209.832 -|
209.833 -| # Comparisons.
209.834 --
209.835 -+ def __eq__(self, other):
209.836 -| if isinstance(other, date):
209.837 -| return self.__cmp(other) == 0
209.838 -| elif hasattr(other, "timetuple"):
209.839 -| return NotImplemented
209.840 -| else:
209.841 -| return False
209.842 --
209.843 -+ def __ne__(self, other):
209.844 -| if isinstance(other, date):
209.845 -| return self.__cmp(other) != 0
209.846 -| elif hasattr(other, "timetuple"):
209.847 -| return NotImplemented
209.848 -| else:
209.849 -| return True
209.850 --
209.851 -+ def __le__(self, other):
209.852 -| if isinstance(other, date):
209.853 -| return self.__cmp(other) <= 0
209.854 -| elif hasattr(other, "timetuple"):
209.855 -| return NotImplemented
209.856 -| else:
209.857 -| _cmperror(self, other)
209.858 --
209.859 -+ def __lt__(self, other):
209.860 -| if isinstance(other, date):
209.861 -| return self.__cmp(other) < 0
209.862 -| elif hasattr(other, "timetuple"):
209.863 -| return NotImplemented
209.864 -| else:
209.865 -| _cmperror(self, other)
209.866 --
209.867 -+ def __ge__(self, other):
209.868 -| if isinstance(other, date):
209.869 -| return self.__cmp(other) >= 0
209.870 -| elif hasattr(other, "timetuple"):
209.871 -| return NotImplemented
209.872 -| else:
209.873 -| _cmperror(self, other)
209.874 --
209.875 -+ def __gt__(self, other):
209.876 -| if isinstance(other, date):
209.877 -| return self.__cmp(other) > 0
209.878 -| elif hasattr(other, "timetuple"):
209.879 -| return NotImplemented
209.880 -| else:
209.881 -| _cmperror(self, other)
209.882 --
209.883 -+ def __cmp(self, other):
209.884 -| assert isinstance(other, date)
209.885 -| y, m, d = self.__year, self.__month, self.__day
209.886 -| y2, m2, d2 = other.__year, other.__month, other.__day
209.887 -| return cmp((y, m, d), (y2, m2, d2))
209.888 --
209.889 -+ def __hash__(self):
209.890 -| "Hash."
209.891 -| return hash(self.__getstate())
209.892 -|
209.893 -| # Computations
209.894 --
209.895 -+ def _checkOverflow(self, year):
209.896 -| if not MINYEAR <= year <= MAXYEAR:
209.897 -| raise OverflowError("date +/-: result year %d not in %d..%d" %
209.898 -| (year, MINYEAR, MAXYEAR))
209.899 --
209.900 -+ def __add__(self, other):
209.901 -| "Add a date to a timedelta."
209.902 -| if isinstance(other, timedelta):
209.903 -| t = tmxxx(self.__year,
209.904 -| self.__month,
209.905 -| self.__day + other.days)
209.906 -| self._checkOverflow(t.year)
209.907 -| result = self.__class__(t.year, t.month, t.day)
209.908 -| return result
209.909 -| return NotImplemented
209.910 --
209.911 -| __radd__ = __add__
209.912 -|
209.913 -+ def __sub__(self, other):
209.914 -| """Subtract two dates, or a date and a timedelta."""
209.915 -| if isinstance(other, timedelta):
209.916 -| return self + timedelta(-other.days)
209.917 -| if isinstance(other, date):
209.918 -| days1 = self.toordinal()
209.919 -| days2 = other.toordinal()
209.920 -| return timedelta(days1 - days2)
209.921 -| return NotImplemented
209.922 --
209.923 -+ def weekday(self):
209.924 -| "Return day of the week, where Monday == 0 ... Sunday == 6."
209.925 -| return (self.toordinal() + 6) % 7
209.926 -|
209.927 -| # Day-of-the-week and week-of-the-year, according to ISO
209.928 --
209.929 -+ def isoweekday(self):
209.930 -| "Return day of the week, where Monday == 1 ... Sunday == 7."
209.931 -| # 1-Jan-0001 is a Monday
209.932 -| return self.toordinal() % 7 or 7
209.933 --
209.934 -+ def isocalendar(self):
209.935 -+ """Return a 3-tuple containing ISO year, week number, and weekday.
209.936 -|
209.937 -| The first ISO week of the year is the (Mon-Sun) week
209.938 -| containing the year's first Thursday; everything else derives
209.939 -| from that.
209.940 -|
209.941 -| The first week is 1; Monday is 1 ... Sunday is 7.
209.942 -|
209.943 -| ISO calendar algorithm taken from
209.944 -| http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
209.945 -- """
209.946 -| year = self.__year
209.947 -| week1monday = _isoweek1monday(year)
209.948 -| today = _ymd2ord(self.__year, self.__month, self.__day)
209.949 -| # Internally, week and day have origin 0
209.950 -| week, day = divmod(today - week1monday, 7)
209.951 -| if week < 0:
209.952 -| year -= 1
209.953 -| week1monday = _isoweek1monday(year)
209.954 -| week, day = divmod(today - week1monday, 7)
209.955 -| elif week >= 52:
209.956 -| if today >= _isoweek1monday(year+1):
209.957 -| year += 1
209.958 -| week = 0
209.959 -| return year, week+1, day+1
209.960 -|
209.961 -| # Pickle support.
209.962 --
209.963 -| __safe_for_unpickling__ = True # For Python 2.2
209.964 -|
209.965 -+ def __getstate(self):
209.966 -| yhi, ylo = divmod(self.__year, 256)
209.967 -| return ("%c%c%c%c" % (yhi, ylo, self.__month, self.__day), )
209.968 --
209.969 -+ def __setstate(self, t):
209.970 -| assert isinstance(t, tuple) and len(t) == 1, `t`
209.971 -| string = t[0]
209.972 -| assert len(string) == 4
209.973 -| yhi, ylo, self.__month, self.__day = map(ord, string)
209.974 -| self.__year = yhi * 256 + ylo
209.975 --
209.976 -+ def __reduce__(self):
209.977 -| return (self.__class__, self.__getstate())
209.978 --
209.979 - _date_class = date # so functions w/ args named "date" can get at the class
209.980 -
209.981 - date.min = date(1, 1, 1)
209.982 - date.max = date(9999, 12, 31)
209.983 - date.resolution = timedelta(days=1)
209.984 -
209.985 -+ class tzinfo(object):
209.986 -+ """Abstract base class for time zone info classes.
209.987 -|
209.988 -| Subclasses must override the name(), utcoffset() and dst() methods.
209.989 -- """
209.990 -|
209.991 -+ def tzname(self, dt):
209.992 -| "datetime -> string name of time zone."
209.993 -| raise NotImplementedError("tzinfo subclass must override tzname()")
209.994 --
209.995 -+ def utcoffset(self, dt):
209.996 -| "datetime -> minutes east of UTC (negative for west of UTC)"
209.997 -| raise NotImplementedError("tzinfo subclass must override utcoffset()")
209.998 --
209.999 -+ def dst(self, dt):
209.1000 -+ """datetime -> DST offset in minutes east of UTC.
209.1001 -|
209.1002 -| Return 0 if DST not in effect. utcoffset() must include the DST
209.1003 -| offset.
209.1004 -- """
209.1005 -| raise NotImplementedError("tzinfo subclass must override dst()")
209.1006 --
209.1007 -+ def fromutc(self, dt):
209.1008 -| "datetime in UTC -> datetime in local time."
209.1009 -|
209.1010 -| if not isinstance(dt, datetime):
209.1011 -| raise TypeError("fromutc() requires a datetime argument")
209.1012 -| if dt.tzinfo is not self:
209.1013 -| raise ValueError("dt.tzinfo is not self")
209.1014 -|
209.1015 -| dtoff = dt.utcoffset()
209.1016 -| if dtoff is None:
209.1017 -+ raise ValueError("fromutc() requires a non-None utcoffset() "
209.1018 -| "result")
209.1019 -|
209.1020 -| # See the long comment block at the end of this file for an
209.1021 -| # explanation of this algorithm.
209.1022 -| dtdst = dt.dst()
209.1023 -| if dtdst is None:
209.1024 -| raise ValueError("fromutc() requires a non-None dst() result")
209.1025 -| delta = dtoff - dtdst
209.1026 -| if delta:
209.1027 -| dt += delta
209.1028 -| dtdst = dt.dst()
209.1029 -| if dtdst is None:
209.1030 -+ raise ValueError("fromutc(): dt.dst gave inconsistent "
209.1031 -| "results; cannot convert")
209.1032 -| if dtdst:
209.1033 -| return dt + dtdst
209.1034 -| else:
209.1035 -| return dt
209.1036 -|
209.1037 -| # Pickle support.
209.1038 --
209.1039 -| __safe_for_unpickling__ = True # For Python 2.2
209.1040 -|
209.1041 -+ def __reduce__(self):
209.1042 -| getinitargs = getattr(self, "__getinitargs__", None)
209.1043 -| if getinitargs:
209.1044 -| args = getinitargs()
209.1045 -| else:
209.1046 -| args = ()
209.1047 -| getstate = getattr(self, "__getstate__", None)
209.1048 -| if getstate:
209.1049 -| state = getstate()
209.1050 -| else:
209.1051 -| state = getattr(self, "__dict__", None) or None
209.1052 -| if state is None:
209.1053 -| return (self.__class__, args)
209.1054 -| else:
209.1055 -| return (self.__class__, args, state)
209.1056 --
209.1057 - _tzinfo_class = tzinfo # so functions w/ args named "tinfo" can get at it
209.1058 -
209.1059 -+ class time(object):
209.1060 -+ """Time with time zone.
209.1061 -|
209.1062 -| Constructors:
209.1063 -|
209.1064 -| __new__()
209.1065 -|
209.1066 -| Operators:
209.1067 -|
209.1068 -| __repr__, __str__
209.1069 -| __cmp__, __hash__
209.1070 -|
209.1071 -| Methods:
209.1072 -|
209.1073 -| strftime()
209.1074 -| isoformat()
209.1075 -| utcoffset()
209.1076 -| tzname()
209.1077 -| dst()
209.1078 -|
209.1079 -| Properties (readonly):
209.1080 -| hour, minute, second, microsecond, tzinfo
209.1081 -- """
209.1082 -|
209.1083 -+ def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
209.1084 -+ """Constructor.
209.1085 -|
209.1086 -| Arguments:
209.1087 -|
209.1088 -| hour, minute (required)
209.1089 -| second, microsecond (default to zero)
209.1090 -| tzinfo (default to None)
209.1091 -- """
209.1092 -| self = object.__new__(cls)
209.1093 -| if isinstance(hour, str):
209.1094 -| # Pickle support
209.1095 -| self.__setstate((hour, minute or None))
209.1096 -| return self
209.1097 -| _check_tzinfo_arg(tzinfo)
209.1098 -| _check_time_fields(hour, minute, second, microsecond)
209.1099 -| self.__hour = hour
209.1100 -| self.__minute = minute
209.1101 -| self.__second = second
209.1102 -| self.__microsecond = microsecond
209.1103 -| self._tzinfo = tzinfo
209.1104 -| return self
209.1105 -|
209.1106 -- # Read-only field accessors
209.1107 -| hour = property(lambda self: self.__hour, doc="hour (0-23)")
209.1108 -| minute = property(lambda self: self.__minute, doc="minute (0-59)")
209.1109 -| second = property(lambda self: self.__second, doc="second (0-59)")
209.1110 -| microsecond = property(lambda self: self.__microsecond,
209.1111 -| doc="microsecond (0-999999)")
209.1112 -| tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
209.1113 -|
209.1114 -| # Standard conversions, __hash__ (and helpers)
209.1115 -|
209.1116 -| # Comparisons.
209.1117 -|
209.1118 -+ def __eq__(self, other):
209.1119 -| if isinstance(other, time):
209.1120 -| return self.__cmp(other) == 0
209.1121 -| else:
209.1122 -| return False
209.1123 --
209.1124 -+ def __ne__(self, other):
209.1125 -| if isinstance(other, time):
209.1126 -| return self.__cmp(other) != 0
209.1127 -| else:
209.1128 -| return True
209.1129 --
209.1130 -+ def __le__(self, other):
209.1131 -| if isinstance(other, time):
209.1132 -| return self.__cmp(other) <= 0
209.1133 -| else:
209.1134 -| _cmperror(self, other)
209.1135 --
209.1136 -+ def __lt__(self, other):
209.1137 -| if isinstance(other, time):
209.1138 -| return self.__cmp(other) < 0
209.1139 -| else:
209.1140 -| _cmperror(self, other)
209.1141 --
209.1142 -+ def __ge__(self, other):
209.1143 -| if isinstance(other, time):
209.1144 -| return self.__cmp(other) >= 0
209.1145 -| else:
209.1146 -| _cmperror(self, other)
209.1147 --
209.1148 -+ def __gt__(self, other):
209.1149 -| if isinstance(other, time):
209.1150 -| return self.__cmp(other) > 0
209.1151 -| else:
209.1152 -| _cmperror(self, other)
209.1153 --
209.1154 -+ def __cmp(self, other):
209.1155 -| assert isinstance(other, time)
209.1156 -| mytz = self._tzinfo
209.1157 -| ottz = other._tzinfo
209.1158 -| myoff = otoff = None
209.1159 -|
209.1160 -| if mytz is ottz:
209.1161 -| base_compare = True
209.1162 -| else:
209.1163 -| myoff = self._utcoffset()
209.1164 -| otoff = other._utcoffset()
209.1165 -| base_compare = myoff == otoff
209.1166 -|
209.1167 -| if base_compare:
209.1168 -| return cmp((self.__hour, self.__minute, self.__second,
209.1169 -| self.__microsecond),
209.1170 -| (other.__hour, other.__minute, other.__second,
209.1171 -| other.__microsecond))
209.1172 -| if myoff is None or otoff is None:
209.1173 -| # XXX Buggy in 2.2.2.
209.1174 -| raise TypeError("cannot compare naive and aware times")
209.1175 -| myhhmm = self.__hour * 60 + self.__minute - myoff
209.1176 -| othhmm = other.__hour * 60 + other.__minute - otoff
209.1177 -| return cmp((myhhmm, self.__second, self.__microsecond),
209.1178 -| (othhmm, other.__second, other.__microsecond))
209.1179 --
209.1180 -+ def __hash__(self):
209.1181 -| """Hash."""
209.1182 -| tzoff = self._utcoffset()
209.1183 -| if not tzoff: # zero or None
209.1184 -| return hash(self.__getstate()[0])
209.1185 -| h, m = divmod(self.hour * 60 + self.minute - tzoff, 60)
209.1186 -| if 0 <= h < 24:
209.1187 -| return hash(time(h, m, self.second, self.microsecond))
209.1188 -| return hash((h, m, self.second, self.microsecond))
209.1189 -|
209.1190 -| # Conversion to string
209.1191 --
209.1192 -+ def _tzstr(self, sep=":"):
209.1193 -| """Return formatted timezone offset (+xx:xx) or None."""
209.1194 -| off = self._utcoffset()
209.1195 -| if off is not None:
209.1196 -| if off < 0:
209.1197 -| sign = "-"
209.1198 -| off = -off
209.1199 -| else:
209.1200 -| sign = "+"
209.1201 -| hh, mm = divmod(off, 60)
209.1202 -| assert 0 <= hh < 24
209.1203 -| off = "%s%02d%s%02d" % (sign, hh, sep, mm)
209.1204 -| return off
209.1205 --
209.1206 -+ def __repr__(self):
209.1207 -| """Convert to formal string, for repr()."""
209.1208 -| if self.__microsecond != 0:
209.1209 -| s = ", %d, %d" % (self.__second, self.__microsecond)
209.1210 -| elif self.__second != 0:
209.1211 -| s = ", %d" % self.__second
209.1212 -| else:
209.1213 -| s = ""
209.1214 -| s= "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__,
209.1215 -| self.__hour, self.__minute, s)
209.1216 -| if self._tzinfo is not None:
209.1217 -| assert s[-1:] == ")"
209.1218 -| s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
209.1219 -| return s
209.1220 --
209.1221 -+ def isoformat(self):
209.1222 -+ """Return the time formatted according to ISO.
209.1223 -|
209.1224 -| This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
209.1225 -| self.microsecond == 0.
209.1226 -- """
209.1227 -| s = _format_time(self.__hour, self.__minute, self.__second,
209.1228 -| self.__microsecond)
209.1229 -| tz = self._tzstr()
209.1230 -| if tz:
209.1231 -| s += tz
209.1232 -| return s
209.1233 --
209.1234 -| __str__ = isoformat
209.1235 -|
209.1236 -+ def strftime(self, fmt):
209.1237 -+ """Format using strftime(). The date part of the timestamp passed
209.1238 -| to underlying strftime should not be used.
209.1239 -- """
209.1240 -| # The year must be >= 1900 else Python's strftime implementation
209.1241 -| # can raise a bogus exception.
209.1242 -| timetuple = (1900, 1, 1,
209.1243 -| self.__hour, self.__minute, self.__second,
209.1244 -| 0, 1, -1)
209.1245 -| return _wrap_strftime(self, fmt, timetuple)
209.1246 -|
209.1247 -| # Timezone functions
209.1248 --
209.1249 -+ def utcoffset(self):
209.1250 -+ """Return the timezone offset in minutes east of UTC (negative west of
209.1251 -- UTC)."""
209.1252 -| offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
209.1253 -| offset = _check_utc_offset("utcoffset", offset)
209.1254 -| if offset is not None:
209.1255 -| offset = timedelta(minutes=offset)
209.1256 -| return offset
209.1257 -|
209.1258 -- # Return an integer (or None) instead of a timedelta (or None).
209.1259 -+ def _utcoffset(self):
209.1260 -| offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
209.1261 -| offset = _check_utc_offset("utcoffset", offset)
209.1262 -| return offset
209.1263 --
209.1264 -+ def tzname(self):
209.1265 -+ """Return the timezone name.
209.1266 -|
209.1267 -| Note that the name is 100% informational -- there's no requirement that
209.1268 -| it mean anything in particular. For example, "GMT", "UTC", "-500",
209.1269 -| "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
209.1270 -- """
209.1271 -| name = _call_tzinfo_method(self._tzinfo, "tzname", None)
209.1272 -| _check_tzname(name)
209.1273 -| return name
209.1274 --
209.1275 -+ def dst(self):
209.1276 -+ """Return 0 if DST is not in effect, or the DST offset (in minutes
209.1277 -| eastward) if DST is in effect.
209.1278 -|
209.1279 -| This is purely informational; the DST offset has already been added to
209.1280 -| the UTC offset returned by utcoffset() if applicable, so there's no
209.1281 -| need to consult dst() unless you're interested in displaying the DST
209.1282 -| info.
209.1283 -- """
209.1284 -| offset = _call_tzinfo_method(self._tzinfo, "dst", None)
209.1285 -| offset = _check_utc_offset("dst", offset)
209.1286 -| if offset is not None:
209.1287 -| offset = timedelta(minutes=offset)
209.1288 -| return offset
209.1289 --
209.1290 -+ def replace(self, hour=None, minute=None, second=None, microsecond=None,
209.1291 -| tzinfo=True):
209.1292 -| """Return a new time with new values for the specified fields."""
209.1293 -| if hour is None:
209.1294 -| hour = self.hour
209.1295 -| if minute is None:
209.1296 -| minute = self.minute
209.1297 -| if second is None:
209.1298 -| second = self.second
209.1299 -| if microsecond is None:
209.1300 -| microsecond = self.microsecond
209.1301 -| if tzinfo is True:
209.1302 -| tzinfo = self.tzinfo
209.1303 -| _check_time_fields(hour, minute, second, microsecond)
209.1304 -| _check_tzinfo_arg(tzinfo)
209.1305 -| return time(hour, minute, second, microsecond, tzinfo)
209.1306 -|
209.1307 -- # Return an integer (or None) instead of a timedelta (or None).
209.1308 -+ def _dst(self):
209.1309 -| offset = _call_tzinfo_method(self._tzinfo, "dst", None)
209.1310 -| offset = _check_utc_offset("dst", offset)
209.1311 -| return offset
209.1312 --
209.1313 -+ def __nonzero__(self):
209.1314 -| if self.second or self.microsecond:
209.1315 -| return 1
209.1316 -| offset = self._utcoffset() or 0
209.1317 -| return self.hour * 60 + self.minute - offset != 0
209.1318 -|
209.1319 -| # Pickle support.
209.1320 --
209.1321 -| __safe_for_unpickling__ = True # For Python 2.2
209.1322 -|
209.1323 -+ def __getstate(self):
209.1324 -| us2, us3 = divmod(self.__microsecond, 256)
209.1325 -| us1, us2 = divmod(us2, 256)
209.1326 -| basestate = ("%c" * 6) % (self.__hour, self.__minute, self.__second,
209.1327 -| us1, us2, us3)
209.1328 -| if self._tzinfo is None:
209.1329 -| return (basestate,)
209.1330 -| else:
209.1331 -| return (basestate, self._tzinfo)
209.1332 --
209.1333 -+ def __setstate(self, state):
209.1334 -| assert isinstance(state, tuple)
209.1335 -| assert 1 <= len(state) <= 2
209.1336 -| string = state[0]
209.1337 -| assert len(string) == 6
209.1338 -| self.__hour, self.__minute, self.__second, us1, us2, us3 = \
209.1339 -| map(ord, string)
209.1340 -| self.__microsecond = (((us1 << 8) | us2) << 8) | us3
209.1341 -| if len(state) == 1:
209.1342 -| self._tzinfo = None
209.1343 -| else:
209.1344 -| self._tzinfo = state[1]
209.1345 --
209.1346 -+ def __reduce__(self):
209.1347 -| return (self.__class__, self.__getstate())
209.1348 --
209.1349 - _time_class = time # so functions w/ args named "time" can get at the class
209.1350 -
209.1351 - time.min = time(0, 0, 0)
209.1352 - time.max = time(23, 59, 59, 999999)
209.1353 - time.resolution = timedelta(microseconds=1)
209.1354 -
209.1355 -+ class datetime(date):
209.1356 -|
209.1357 -| # XXX needs docstrings
209.1358 -| # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
209.1359 -|
209.1360 -+ def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
209.1361 -| microsecond=0, tzinfo=None):
209.1362 -| if isinstance(year, str):
209.1363 -| # Pickle support
209.1364 -| self = date.__new__(cls, year[:4])
209.1365 -| self.__setstate((year, month))
209.1366 -| return self
209.1367 -| _check_tzinfo_arg(tzinfo)
209.1368 -| _check_time_fields(hour, minute, second, microsecond)
209.1369 -| self = date.__new__(cls, year, month, day)
209.1370 -| # XXX This duplicates __year, __month, __day for convenience :-(
209.1371 -| self.__year = year
209.1372 -| self.__month = month
209.1373 -| self.__day = day
209.1374 -| self.__hour = hour
209.1375 -| self.__minute = minute
209.1376 -| self.__second = second
209.1377 -| self.__microsecond = microsecond
209.1378 -| self._tzinfo = tzinfo
209.1379 -| return self
209.1380 -|
209.1381 -- # Read-only field accessors
209.1382 -| hour = property(lambda self: self.__hour, doc="hour (0-23)")
209.1383 -| minute = property(lambda self: self.__minute, doc="minute (0-59)")
209.1384 -| second = property(lambda self: self.__second, doc="second (0-59)")
209.1385 -| microsecond = property(lambda self: self.__microsecond,
209.1386 -| doc="microsecond (0-999999)")
209.1387 -| tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
209.1388 -|
209.1389 -+ def fromtimestamp(cls, t, tz=None):
209.1390 -+ """Construct a datetime from a POSIX timestamp (like time.time()).
209.1391 -|
209.1392 -| A timezone info object may be passed in as well.
209.1393 -- """
209.1394 -|
209.1395 -| _check_tzinfo_arg(tz)
209.1396 -| if tz is None:
209.1397 -| converter = _time.localtime
209.1398 -| else:
209.1399 -| converter = _time.gmtime
209.1400 -| y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
209.1401 -| us = int((t % 1.0) * 1000000)
209.1402 -| ss = min(ss, 59) # clamp out leap seconds if the platform has them
209.1403 -| result = cls(y, m, d, hh, mm, ss, us, tz)
209.1404 -| if tz is not None:
209.1405 -| result = tz.fromutc(result)
209.1406 -- return result
209.1407 -| fromtimestamp = classmethod(fromtimestamp)
209.1408 -|
209.1409 -+ def utcfromtimestamp(cls, t):
209.1410 -| "Construct a UTC datetime from a POSIX timestamp (like time.time())."
209.1411 -| y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
209.1412 -| us = int((t % 1.0) * 1000000)
209.1413 -| ss = min(ss, 59) # clamp out leap seconds if the platform has them
209.1414 -- return cls(y, m, d, hh, mm, ss, us)
209.1415 -| utcfromtimestamp = classmethod(utcfromtimestamp)
209.1416 -|
209.1417 -| # XXX This is supposed to do better than we *can* do by using time.time(),
209.1418 -| # XXX if the platform supports a more accurate way. The C implementation
209.1419 -| # XXX uses gettimeofday on platforms that have it, but that isn't
209.1420 -| # XXX available from Python. So now() may return different results
209.1421 -| # XXX across the implementations.
209.1422 -+ def now(cls, tz=None):
209.1423 -| "Construct a datetime from time.time() and optional time zone info."
209.1424 -| t = _time.time()
209.1425 -- return cls.fromtimestamp(t, tz)
209.1426 -| now = classmethod(now)
209.1427 -|
209.1428 -+ def utcnow(cls):
209.1429 -| "Construct a UTC datetime from time.time()."
209.1430 -| t = _time.time()
209.1431 -- return cls.utcfromtimestamp(t)
209.1432 -| utcnow = classmethod(utcnow)
209.1433 -|
209.1434 -+ def combine(cls, date, time):
209.1435 -| "Construct a datetime from a given date and a given time."
209.1436 -| if not isinstance(date, _date_class):
209.1437 -| raise TypeError("date argument must be a date instance")
209.1438 -| if not isinstance(time, _time_class):
209.1439 -| raise TypeError("time argument must be a time instance")
209.1440 -| return cls(date.year, date.month, date.day,
209.1441 -| time.hour, time.minute, time.second, time.microsecond,
209.1442 -- time.tzinfo)
209.1443 -| combine = classmethod(combine)
209.1444 -|
209.1445 -+ def timetuple(self):
209.1446 -| "Return local time tuple compatible with time.localtime()."
209.1447 -| dst = self._dst()
209.1448 -| if dst is None:
209.1449 -| dst = -1
209.1450 -| elif dst:
209.1451 -| dst = 1
209.1452 -| return _build_struct_time(self.year, self.month, self.day,
209.1453 -| self.hour, self.minute, self.second,
209.1454 -| dst)
209.1455 --
209.1456 -+ def utctimetuple(self):
209.1457 -| "Return UTC time tuple compatible with time.gmtime()."
209.1458 -| y, m, d = self.year, self.month, self.day
209.1459 -| hh, mm, ss = self.hour, self.minute, self.second
209.1460 -| offset = self._utcoffset()
209.1461 -| if offset: # neither None nor 0
209.1462 -| tm = tmxxx(y, m, d, hh, mm - offset)
209.1463 -| y, m, d = tm.year, tm.month, tm.day
209.1464 -| hh, mm = tm.hour, tm.minute
209.1465 -| return _build_struct_time(y, m, d, hh, mm, ss, 0)
209.1466 --
209.1467 -+ def date(self):
209.1468 -| "Return the date part."
209.1469 -| return date(self.__year, self.__month, self.__day)
209.1470 --
209.1471 -+ def time(self):
209.1472 -| "Return the time part, with tzinfo None."
209.1473 -| return time(self.hour, self.minute, self.second, self.microsecond)
209.1474 --
209.1475 -+ def timetz(self):
209.1476 -| "Return the time part, with same tzinfo."
209.1477 -| return time(self.hour, self.minute, self.second, self.microsecond,
209.1478 -| self._tzinfo)
209.1479 --
209.1480 -+ def replace(self, year=None, month=None, day=None, hour=None,
209.1481 -| minute=None, second=None, microsecond=None, tzinfo=True):
209.1482 -| """Return a new datetime with new values for the specified fields."""
209.1483 -| if year is None:
209.1484 -| year = self.year
209.1485 -| if month is None:
209.1486 -| month = self.month
209.1487 -| if day is None:
209.1488 -| day = self.day
209.1489 -| if hour is None:
209.1490 -| hour = self.hour
209.1491 -| if minute is None:
209.1492 -| minute = self.minute
209.1493 -| if second is None:
209.1494 -| second = self.second
209.1495 -| if microsecond is None:
209.1496 -| microsecond = self.microsecond
209.1497 -| if tzinfo is True:
209.1498 -| tzinfo = self.tzinfo
209.1499 -| _check_date_fields(year, month, day)
209.1500 -| _check_time_fields(hour, minute, second, microsecond)
209.1501 -| _check_tzinfo_arg(tzinfo)
209.1502 -| return datetime(year, month, day, hour, minute, second,
209.1503 -| microsecond, tzinfo)
209.1504 --
209.1505 -+ def astimezone(self, tz):
209.1506 -| if not isinstance(tz, tzinfo):
209.1507 -| raise TypeError("tz argument must be an instance of tzinfo")
209.1508 -|
209.1509 -| mytz = self.tzinfo
209.1510 -| if mytz is None:
209.1511 -| raise ValueError("astimezone() requires an aware datetime")
209.1512 -|
209.1513 -| if tz is mytz:
209.1514 -| return self
209.1515 -|
209.1516 -| # Convert self to UTC, and attach the new time zone object.
209.1517 -| myoffset = self.utcoffset()
209.1518 -| if myoffset is None:
209.1519 -| raise ValuError("astimezone() requires an aware datetime")
209.1520 -| utc = (self - myoffset).replace(tzinfo=tz)
209.1521 -|
209.1522 -| # Convert from UTC to tz's local time.
209.1523 -| return tz.fromutc(utc)
209.1524 -|
209.1525 -| # Ways to produce a string.
209.1526 --
209.1527 -+ def ctime(self):
209.1528 -| "Format a la ctime()."
209.1529 -| t = tmxxx(self.__year, self.__month, self.__day, self.__hour,
209.1530 -| self.__minute, self.__second)
209.1531 -| return t.ctime()
209.1532 --
209.1533 -+ def isoformat(self, sep='T'):
209.1534 -+ """Return the time formatted according to ISO.
209.1535 -|
209.1536 -| This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
209.1537 -| self.microsecond == 0.
209.1538 -|
209.1539 -| If self.tzinfo is not None, the UTC offset is also attached, giving
209.1540 -| 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
209.1541 -|
209.1542 -| Optional argument sep specifies the separator between date and
209.1543 -| time, default 'T'.
209.1544 -- """
209.1545 -| s = ("%04d-%02d-%02d%c" % (self.__year, self.__month, self.__day,
209.1546 -| sep) +
209.1547 -| _format_time(self.__hour, self.__minute, self.__second,
209.1548 -| self.__microsecond))
209.1549 -| off = self._utcoffset()
209.1550 -| if off is not None:
209.1551 -| if off < 0:
209.1552 -| sign = "-"
209.1553 -| off = -off
209.1554 -| else:
209.1555 -| sign = "+"
209.1556 -| hh, mm = divmod(off, 60)
209.1557 -| s += "%s%02d:%02d" % (sign, hh, mm)
209.1558 -| return s
209.1559 --
209.1560 -+ def __repr__(self):
209.1561 -| "Convert to formal string, for repr()."
209.1562 -| L = [self.__year, self.__month, self.__day, # These are never zero
209.1563 -| self.__hour, self.__minute, self.__second, self.__microsecond]
209.1564 -| if L[-1] == 0:
209.1565 -| del L[-1]
209.1566 -| if L[-1] == 0:
209.1567 -| del L[-1]
209.1568 -| s = ", ".join(map(str, L))
209.1569 -| s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s)
209.1570 -| if self._tzinfo is not None:
209.1571 -| assert s[-1:] == ")"
209.1572 -| s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
209.1573 -| return s
209.1574 --
209.1575 -+ def __str__(self):
209.1576 -| "Convert to string, for str()."
209.1577 -| return self.isoformat(sep=' ')
209.1578 --
209.1579 -+ def utcoffset(self):
209.1580 -+ """Return the timezone offset in minutes east of UTC (negative west of
209.1581 -- UTC)."""
209.1582 -| offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
209.1583 -| offset = _check_utc_offset("utcoffset", offset)
209.1584 -| if offset is not None:
209.1585 -| offset = timedelta(minutes=offset)
209.1586 -| return offset
209.1587 -|
209.1588 -- # Return an integer (or None) instead of a timedelta (or None).
209.1589 -+ def _utcoffset(self):
209.1590 -| offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
209.1591 -| offset = _check_utc_offset("utcoffset", offset)
209.1592 -| return offset
209.1593 --
209.1594 -+ def tzname(self):
209.1595 -+ """Return the timezone name.
209.1596 -|
209.1597 -| Note that the name is 100% informational -- there's no requirement that
209.1598 -| it mean anything in particular. For example, "GMT", "UTC", "-500",
209.1599 -| "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
209.1600 -- """
209.1601 -| name = _call_tzinfo_method(self._tzinfo, "tzname", self)
209.1602 -| _check_tzname(name)
209.1603 -| return name
209.1604 --
209.1605 -+ def dst(self):
209.1606 -+ """Return 0 if DST is not in effect, or the DST offset (in minutes
209.1607 -| eastward) if DST is in effect.
209.1608 -|
209.1609 -| This is purely informational; the DST offset has already been added to
209.1610 -| the UTC offset returned by utcoffset() if applicable, so there's no
209.1611 -| need to consult dst() unless you're interested in displaying the DST
209.1612 -| info.
209.1613 -- """
209.1614 -| offset = _call_tzinfo_method(self._tzinfo, "dst", self)
209.1615 -| offset = _check_utc_offset("dst", offset)
209.1616 -| if offset is not None:
209.1617 -| offset = timedelta(minutes=offset)
209.1618 -| return offset
209.1619 -|
209.1620 -- # Return an integer (or None) instead of a timedelta (or None).1573
209.1621 -+ def _dst(self):
209.1622 -| offset = _call_tzinfo_method(self._tzinfo, "dst", self)
209.1623 -| offset = _check_utc_offset("dst", offset)
209.1624 -| return offset
209.1625 -|
209.1626 -| # Comparisons.
209.1627 --
209.1628 -+ def __eq__(self, other):
209.1629 -| if isinstance(other, datetime):
209.1630 -| return self.__cmp(other) == 0
209.1631 -| elif hasattr(other, "timetuple"):
209.1632 -| return NotImplemented
209.1633 -| else:
209.1634 -| return False
209.1635 --
209.1636 -+ def __ne__(self, other):
209.1637 -| if isinstance(other, datetime):
209.1638 -| return self.__cmp(other) != 0
209.1639 -| elif hasattr(other, "timetuple"):
209.1640 -| return NotImplemented
209.1641 -| else:
209.1642 -| return True
209.1643 --
209.1644 -+ def __le__(self, other):
209.1645 -| if isinstance(other, datetime):
209.1646 -| return self.__cmp(other) <= 0
209.1647 -| elif hasattr(other, "timetuple"):
209.1648 -| return NotImplemented
209.1649 -| else:
209.1650 -| _cmperror(self, other)
209.1651 --
209.1652 -+ def __lt__(self, other):
209.1653 -| if isinstance(other, datetime):
209.1654 -| return self.__cmp(other) < 0
209.1655 -| elif hasattr(other, "timetuple"):
209.1656 -| return NotImplemented
209.1657 -| else:
209.1658 -| _cmperror(self, other)
209.1659 --
209.1660 -+ def __ge__(self, other):
209.1661 -| if isinstance(other, datetime):
209.1662 -| return self.__cmp(other) >= 0
209.1663 -| elif hasattr(other, "timetuple"):
209.1664 -| return NotImplemented
209.1665 -| else:
209.1666 -| _cmperror(self, other)
209.1667 --
209.1668 -+ def __gt__(self, other):
209.1669 -| if isinstance(other, datetime):
209.1670 -| return self.__cmp(other) > 0
209.1671 -| elif hasattr(other, "timetuple"):
209.1672 -| return NotImplemented
209.1673 -| else:
209.1674 -| _cmperror(self, other)
209.1675 --
209.1676 -+ def __cmp(self, other):
209.1677 -| assert isinstance(other, datetime)
209.1678 -| mytz = self._tzinfo
209.1679 -| ottz = other._tzinfo
209.1680 -| myoff = otoff = None
209.1681 -|
209.1682 -| if mytz is ottz:
209.1683 -| base_compare = True
209.1684 -| else:
209.1685 -| if mytz is not None:
209.1686 -| myoff = self._utcoffset()
209.1687 -| if ottz is not None:
209.1688 -| otoff = other._utcoffset()
209.1689 -| base_compare = myoff == otoff
209.1690 -|
209.1691 -| if base_compare:
209.1692 -| return cmp((self.__year, self.__month, self.__day,
209.1693 -| self.__hour, self.__minute, self.__second,
209.1694 -| self.__microsecond),
209.1695 -| (other.__year, other.__month, other.__day,
209.1696 -| other.__hour, other.__minute, other.__second,
209.1697 -| other.__microsecond))
209.1698 -| if myoff is None or otoff is None:
209.1699 -| # XXX Buggy in 2.2.2.
209.1700 -| raise TypeError("cannot compare naive and aware datetimes")
209.1701 -| # XXX What follows could be done more efficiently...
209.1702 -| diff = self - other # this will take offsets into account
209.1703 -| if diff.days < 0:
209.1704 -| return -1
209.1705 -| return diff and 1 or 0
209.1706 --
209.1707 -+ def __add__(self, other):
209.1708 -| "Add a datetime and a timedelta."
209.1709 -| if not isinstance(other, timedelta):
209.1710 -| return NotImplemented
209.1711 -| t = tmxxx(self.__year,
209.1712 -| self.__month,
209.1713 -| self.__day + other.days,
209.1714 -| self.__hour,
209.1715 -| self.__minute,
209.1716 -| self.__second + other.seconds,
209.1717 -| self.__microsecond + other.microseconds)
209.1718 -| self._checkOverflow(t.year)
209.1719 -| result = self.__class__(t.year, t.month, t.day,
209.1720 -| t.hour, t.minute, t.second,
209.1721 -| t.microsecond, tzinfo=self._tzinfo)
209.1722 -| return result
209.1723 --
209.1724 -| __radd__ = __add__
209.1725 -|
209.1726 -+ def __sub__(self, other):
209.1727 -| "Subtract two datetimes, or a datetime and a timedelta."
209.1728 -| if not isinstance(other, datetime):
209.1729 -| if isinstance(other, timedelta):
209.1730 -| return self + -other
209.1731 -| return NotImplemented
209.1732 -|
209.1733 -| days1 = self.toordinal()
209.1734 -| days2 = other.toordinal()
209.1735 -| secs1 = self.__second + self.__minute * 60 + self.__hour * 3600
209.1736 -| secs2 = other.__second + other.__minute * 60 + other.__hour * 3600
209.1737 -| base = timedelta(days1 - days2,
209.1738 -| secs1 - secs2,
209.1739 -| self.__microsecond - other.__microsecond)
209.1740 -| if self._tzinfo is other._tzinfo:
209.1741 -| return base
209.1742 -| myoff = self._utcoffset()
209.1743 -| otoff = other._utcoffset()
209.1744 -| if myoff == otoff:
209.1745 -| return base
209.1746 -| if myoff is None or otoff is None:
209.1747 -| raise TypeError, "cannot mix naive and timezone-aware time"
209.1748 -| return base + timedelta(minutes = otoff-myoff)
209.1749 --
209.1750 -+ def __hash__(self):
209.1751 -| tzoff = self._utcoffset()
209.1752 -| if tzoff is None:
209.1753 -| return hash(self.__getstate()[0])
209.1754 -| days = _ymd2ord(self.year, self.month, self.day)
209.1755 -| seconds = self.hour * 3600 + (self.minute - tzoff) * 60 + self.second
209.1756 -| return hash(timedelta(days, seconds, self.microsecond))
209.1757 -|
209.1758 -| # Pickle support.
209.1759 --
209.1760 -| __safe_for_unpickling__ = True # For Python 2.2
209.1761 -|
209.1762 -+ def __getstate(self):
209.1763 -| yhi, ylo = divmod(self.__year, 256)
209.1764 -| us2, us3 = divmod(self.__microsecond, 256)
209.1765 -| us1, us2 = divmod(us2, 256)
209.1766 -| basestate = ("%c" * 10) % (yhi, ylo, self.__month, self.__day,
209.1767 -| self.__hour, self.__minute, self.__second,
209.1768 -| us1, us2, us3)
209.1769 -| if self._tzinfo is None:
209.1770 -| return (basestate,)
209.1771 -| else:
209.1772 -| return (basestate, self._tzinfo)
209.1773 --
209.1774 -+ def __setstate(self, state):
209.1775 -| assert isinstance(state, tuple)
209.1776 -| assert 1 <= len(state) <= 2
209.1777 -| string = state[0]
209.1778 -| assert len(string) == 10
209.1779 -| (yhi, ylo, self.__month, self.__day, self.__hour,
209.1780 -| self.__minute, self.__second, us1, us2, us3) = map(ord, string)
209.1781 -| self.__year = yhi * 256 + ylo
209.1782 -| self.__microsecond = (((us1 << 8) | us2) << 8) | us3
209.1783 -| if len(state) == 1:
209.1784 -| self._tzinfo = None
209.1785 -| else:
209.1786 -| self._tzinfo = state[1]
209.1787 --
209.1788 -+ def __reduce__(self):
209.1789 -| return (self.__class__, self.__getstate())
209.1790 -|
209.1791 --
209.1792 - datetime.min = datetime(1, 1, 1)
209.1793 - datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
209.1794 - datetime.resolution = timedelta(microseconds=1)
209.1795 -
209.1796 -
209.1797 -+ def _isoweek1monday(year):
209.1798 -| # Helper to calculate the day number of the Monday starting week 1
209.1799 -| # XXX This could be done more efficiently
209.1800 -| THURSDAY = 3
209.1801 -| firstday = _ymd2ord(year, 1, 1)
209.1802 -| firstweekday = (firstday + 6) % 7 # See weekday() above
209.1803 -| week1monday = firstday - firstweekday
209.1804 -| if firstweekday > THURSDAY:
209.1805 -| week1monday += 7
209.1806 -| return week1monday
209.1807 --
209.1808 -+ """
209.1809 -| Some time zone algebra. For a datetime x, let
209.1810 -| x.n = x stripped of its timezone -- its naive time.
209.1811 -| x.o = x.utcoffset(), and assuming that doesn't raise an exception or
209.1812 -| return None
209.1813 -| x.d = x.dst(), and assuming that doesn't raise an exception or
209.1814 -| return None
209.1815 -| x.s = x's standard offset, x.o - x.d
209.1816 -|
209.1817 -| Now some derived rules, where k is a duration (timedelta).
209.1818 -|
209.1819 -| 1. x.o = x.s + x.d
209.1820 -| This follows from the definition of x.s.
209.1821 -|
209.1822 -| 2. If x and y have the same tzinfo member, x.s = y.s.
209.1823 -| This is actually a requirement, an assumption we need to make about
209.1824 -| sane tzinfo classes.
209.1825 -|
209.1826 -| 3. The naive UTC time corresponding to x is x.n - x.o.
209.1827 -| This is again a requirement for a sane tzinfo class.
209.1828 -|
209.1829 -| 4. (x+k).s = x.s
209.1830 -| This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
209.1831 -|
209.1832 -| 5. (x+k).n = x.n + k
209.1833 -| Again follows from how arithmetic is defined.
209.1834 -|
209.1835 -| Now we can explain tz.fromutc(x). Let's assume it's an interesting case
209.1836 -| (meaning that the various tzinfo methods exist, and don't blow up or return
209.1837 -| None when called).
209.1838 -|
209.1839 -| The function wants to return a datetime y with timezone tz, equivalent to x.
209.1840 -| x is already in UTC.
209.1841 -|
209.1842 -| By #3, we want
209.1843 -|
209.1844 -| y.n - y.o = x.n [1]
209.1845 -|
209.1846 -| The algorithm starts by attaching tz to x.n, and calling that y. So
209.1847 -| x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
209.1848 -| becomes true; in effect, we want to solve [2] for k:
209.1849 -|
209.1850 -| (y+k).n - (y+k).o = x.n [2]
209.1851 -|
209.1852 -| By #1, this is the same as
209.1853 -|
209.1854 -| (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
209.1855 -|
209.1856 -| By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
209.1857 -| Substituting that into [3],
209.1858 -|
209.1859 -| x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
209.1860 -| k - (y+k).s - (y+k).d = 0; rearranging,
209.1861 -| k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
209.1862 -| k = y.s - (y+k).d
209.1863 -|
209.1864 -| On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
209.1865 -| approximate k by ignoring the (y+k).d term at first. Note that k can't be
209.1866 -| very large, since all offset-returning methods return a duration of magnitude
209.1867 -| less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
209.1868 -| be 0, so ignoring it has no consequence then.
209.1869 -|
209.1870 -| In any case, the new value is
209.1871 -|
209.1872 -| z = y + y.s [4]
209.1873 -|
209.1874 -| It's helpful to step back at look at [4] from a higher level: it's simply
209.1875 -| mapping from UTC to tz's standard time.
209.1876 -|
209.1877 -| At this point, if
209.1878 -|
209.1879 -| z.n - z.o = x.n [5]
209.1880 -|
209.1881 -| we have an equivalent time, and are almost done. The insecurity here is
209.1882 -| at the start of daylight time. Picture US Eastern for concreteness. The wall
209.1883 -| time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
209.1884 -| sense then. The docs ask that an Eastern tzinfo class consider such a time to
209.1885 -| be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
209.1886 -| on the day DST starts. We want to return the 1:MM EST spelling because that's
209.1887 -| the only spelling that makes sense on the local wall clock.
209.1888 -|
209.1889 -| In fact, if [5] holds at this point, we do have the standard-time spelling,
209.1890 -| but that takes a bit of proof. We first prove a stronger result. What's the
209.1891 -| difference between the LHS and RHS of [5]? Let
209.1892 -|
209.1893 -| diff = x.n - (z.n - z.o) [6]
209.1894 -|
209.1895 -| Now
209.1896 -| z.n = by [4]
209.1897 -| (y + y.s).n = by #5
209.1898 -| y.n + y.s = since y.n = x.n
209.1899 -| x.n + y.s = since z and y are have the same tzinfo member,
209.1900 -| y.s = z.s by #2
209.1901 -| x.n + z.s
209.1902 -|
209.1903 -| Plugging that back into [6] gives
209.1904 -|
209.1905 -| diff =
209.1906 -| x.n - ((x.n + z.s) - z.o) = expanding
209.1907 -| x.n - x.n - z.s + z.o = cancelling
209.1908 -| - z.s + z.o = by #2
209.1909 -| z.d
209.1910 -|
209.1911 -| So diff = z.d.
209.1912 -|
209.1913 -| If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
209.1914 -| spelling we wanted in the endcase described above. We're done. Contrarily,
209.1915 -| if z.d = 0, then we have a UTC equivalent, and are also done.
209.1916 -|
209.1917 -| If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
209.1918 -| add to z (in effect, z is in tz's standard time, and we need to shift the
209.1919 -| local clock into tz's daylight time).
209.1920 -|
209.1921 -| Let
209.1922 -|
209.1923 -| z' = z + z.d = z + diff [7]
209.1924 -|
209.1925 -| and we can again ask whether
209.1926 -|
209.1927 -| z'.n - z'.o = x.n [8]
209.1928 -|
209.1929 -| If so, we're done. If not, the tzinfo class is insane, according to the
209.1930 -| assumptions we've made. This also requires a bit of proof. As before, let's
209.1931 -| compute the difference between the LHS and RHS of [8] (and skipping some of
209.1932 -| the justifications for the kinds of substitutions we've done several times
209.1933 -| already):
209.1934 -|
209.1935 -| diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
209.1936 -| x.n - (z.n + diff - z'.o) = replacing diff via [6]
209.1937 -| x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
209.1938 -| x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
209.1939 -| - z.n + z.n - z.o + z'.o = cancel z.n
209.1940 -| - z.o + z'.o = #1 twice
209.1941 -| -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
209.1942 -| z'.d - z.d
209.1943 -|
209.1944 -| So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
209.1945 -| we've found the UTC-equivalent so are done. In fact, we stop with [7] and
209.1946 -| return z', not bothering to compute z'.d.
209.1947 -|
209.1948 -| How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
209.1949 -| a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
209.1950 -| would have to change the result dst() returns: we start in DST, and moving
209.1951 -| a little further into it takes us out of DST.
209.1952 -|
209.1953 -| There isn't a sane case where this can happen. The closest it gets is at
209.1954 -| the end of DST, where there's an hour in UTC with no spelling in a hybrid
209.1955 -| tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
209.1956 -| that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
209.1957 -| UTC) because the docs insist on that, but 0:MM is taken as being in daylight
209.1958 -| time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
209.1959 -| clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
209.1960 -| standard time. Since that's what the local clock *does*, we want to map both
209.1961 -| UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
209.1962 -| in local time, but so it goes -- it's the way the local clock works.
209.1963 -|
209.1964 -| When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
209.1965 -| so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
209.1966 -| z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
209.1967 -| (correctly) concludes that z' is not UTC-equivalent to x.
209.1968 -|
209.1969 -| Because we know z.d said z was in daylight time (else [5] would have held and
209.1970 -| we would have stopped then), and we know z.d != z'.d (else [8] would have held
209.1971 -| and we we have stopped then), and there are only 2 possible values dst() can
209.1972 -| return in Eastern, it follows that z'.d must be 0 (which it is in the example,
209.1973 -| but the reasoning doesn't depend on the example -- it depends on there being
209.1974 -| two possible dst() outcomes, one zero and the other non-zero). Therefore
209.1975 -| z' must be in standard time, and is the spelling we want in this case.
209.1976 -|
209.1977 -| Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
209.1978 -| concerned (because it takes z' as being in standard time rather than the
209.1979 -| daylight time we intend here), but returning it gives the real-life "local
209.1980 -| clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
209.1981 -| tz.
209.1982 -|
209.1983 -| When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
209.1984 -| the 1:MM standard time spelling we want.
209.1985 -|
209.1986 -| So how can this break? One of the assumptions must be violated. Two
209.1987 -| possibilities:
209.1988 -|
209.1989 -| 1) [2] effectively says that y.s is invariant across all y belong to a given
209.1990 -| time zone. This isn't true if, for political reasons or continental drift,
209.1991 -| a region decides to change its base offset from UTC.
209.1992 -|
209.1993 -| 2) There may be versions of "double daylight" time where the tail end of
209.1994 -| the analysis gives up a step too early. I haven't thought about that
209.1995 -| enough to say.
209.1996 -|
209.1997 -| In any case, it's clear that the default fromutc() is strong enough to handle
209.1998 -| "almost all" time zones: so long as the standard offset is invariant, it
209.1999 -| doesn't matter if daylight time transition points change from year to year, or
209.2000 -| if daylight time is skipped in some years; it doesn't matter how large or
209.2001 -| small dst() may get within its bounds; and it doesn't even matter if some
209.2002 -| perverse time zone returns a negative dst()). So a breaking case must be
209.2003 -| pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
209.2004 -- """
209.2005 -
209.2006 -+ def _test():
209.2007 -| import test_datetime
209.2008 -| test_datetime.test_main()
209.2009 --
209.2010 - if __name__ == "__main__":
209.2011 - _test()
209.2012 -
210.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.formatted Sun Jan 04 13:11:53 2015 -0600
210.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
210.3 @@ -1,2008 +0,0 @@
210.4 -"""Concrete date/time and related types -- prototype implemented in Python.
210.5 -
210.6 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
210.7 -
210.8 -See also http://dir.yahoo.com/Reference/calendars/
210.9 -
210.10 -For a primer on DST, including many current DST rules, see
210.11 -http://webexhibits.org/daylightsaving/
210.12 -
210.13 -For more about DST than you ever wanted to know, see
210.14 -ftp://elsie.nci.nih.gov/pub/
210.15 -
210.16 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
210.17 -
210.18 -"""
210.19 -
210.20 -import math as _math
210.21 -import time as _time
210.22 -
210.23 -MINYEAR = 1
210.24 -MAXYEAR = 9999
210.25 -
210.26 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
210.27 -# also assumes the current Gregorian calendar indefinitely extended in
210.28 -# both directions. Difference: Dates.py calls January 1 of year 0 day
210.29 -# number 1. The code here calls January 1 of year 1 day number 1. This is
210.30 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
210.31 -# and Reingold's "Calendrical Calculations", where it's the base calendar
210.32 -# for all computations. See the book for algorithms for converting between
210.33 -# proleptic Gregorian ordinals and many other calendar systems.
210.34 -
210.35 -_DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
210.36 -
210.37 -_DAYS_BEFORE_MONTH = [None]
210.38 -dbm = 0
210.39 -for dim in _DAYS_IN_MONTH[1:]:
210.40 - _DAYS_BEFORE_MONTH.append(dbm)
210.41 - dbm += dim
210.42 -del dbm, dim
210.43 -
210.44 -def _is_leap(year):
210.45 - "year -> 1 if leap year, else 0."
210.46 - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
210.47 -
210.48 -def _days_in_year(year):
210.49 - "year -> number of days in year (366 if a leap year, else 365)."
210.50 - return 365 + _is_leap(year)
210.51 -
210.52 -def _days_before_year(year):
210.53 - "year -> number of days before January 1st of year."
210.54 - y = year - 1
210.55 - return y * 365 + y // 4 - y // 100 + y // 400
210.56 -
210.57 -def _days_in_month(year, month):
210.58 - "year, month -> number of days in that month in that year."
210.59 - assert 1 <= month <= 12, month
210.60 - if month == 2 and _is_leap(year):
210.61 - return 29
210.62 - return _DAYS_IN_MONTH[month]
210.63 -
210.64 -def _days_before_month(year, month):
210.65 - "year, month -> number of days in year preceeding first day of month."
210.66 - if not 1 <= month <= 12:
210.67 - raise ValueError('month must be in 1..12', month)
210.68 - return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
210.69 -
210.70 -def _ymd2ord(year, month, day):
210.71 - "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
210.72 - if not 1 <= month <= 12:
210.73 - raise ValueError('month must be in 1..12', month)
210.74 - dim = _days_in_month(year, month)
210.75 - if not 1 <= day <= dim:
210.76 - raise ValueError('day must be in 1..%d' % dim, day)
210.77 - return (_days_before_year(year) +
210.78 - _days_before_month(year, month) +
210.79 - day)
210.80 -
210.81 -_DI400Y = _days_before_year(401) # number of days in 400 years
210.82 -_DI100Y = _days_before_year(101) # " " " " 100 "
210.83 -_DI4Y = _days_before_year(5) # " " " " 4 "
210.84 -
210.85 -# A 4-year cycle has an extra leap day over what we'd get from pasting
210.86 -# together 4 single years.
210.87 -assert _DI4Y == 4 * 365 + 1
210.88 -
210.89 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
210.90 -# pasting together 4 100-year cycles.
210.91 -assert _DI400Y == 4 * _DI100Y + 1
210.92 -
210.93 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
210.94 -# pasting together 25 4-year cycles.
210.95 -assert _DI100Y == 25 * _DI4Y - 1
210.96 -
210.97 -def _ord2ymd(n):
210.98 - "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
210.99 -
210.100 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
210.101 - # repeats exactly every 400 years. The basic strategy is to find the
210.102 - # closest 400-year boundary at or before n, then work with the offset
210.103 - # from that boundary to n. Life is much clearer if we subtract 1 from
210.104 - # n first -- then the values of n at 400-year boundaries are exactly
210.105 - # those divisible by _DI400Y:
210.106 - #
210.107 - # D M Y n n-1
210.108 - # -- --- ---- ---------- ----------------
210.109 - # 31 Dec -400 -_DI400Y -_DI400Y -1
210.110 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
210.111 - # ...
210.112 - # 30 Dec 000 -1 -2
210.113 - # 31 Dec 000 0 -1
210.114 - # 1 Jan 001 1 0 400-year boundary
210.115 - # 2 Jan 001 2 1
210.116 - # 3 Jan 001 3 2
210.117 - # ...
210.118 - # 31 Dec 400 _DI400Y _DI400Y -1
210.119 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
210.120 - n -= 1
210.121 - n400, n = divmod(n, _DI400Y)
210.122 - year = n400 * 400 + 1 # ..., -399, 1, 401, ...
210.123 -
210.124 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
210.125 - # the desired date. Now compute how many 100-year cycles precede n.
210.126 - # Note that it's possible for n100 to equal 4! In that case 4 full
210.127 - # 100-year cycles precede the desired day, which implies the desired
210.128 - # day is December 31 at the end of a 400-year cycle.
210.129 - n100, n = divmod(n, _DI100Y)
210.130 -
210.131 - # Now compute how many 4-year cycles precede it.
210.132 - n4, n = divmod(n, _DI4Y)
210.133 -
210.134 - # And now how many single years. Again n1 can be 4, and again meaning
210.135 - # that the desired day is December 31 at the end of the 4-year cycle.
210.136 - n1, n = divmod(n, 365)
210.137 -
210.138 - year += n100 * 100 + n4 * 4 + n1
210.139 - if n1 == 4 or n100 == 4:
210.140 - assert n == 0
210.141 - return year-1, 12, 31
210.142 -
210.143 - # Now the year is correct, and n is the offset from January 1. We find
210.144 - # the month via an estimate that's either exact or one too large.
210.145 - leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
210.146 - assert leapyear == _is_leap(year)
210.147 - month = (n + 50) >> 5
210.148 - preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
210.149 - if preceding > n: # estimate is too large
210.150 - month -= 1
210.151 - preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
210.152 - n -= preceding
210.153 - assert 0 <= n < _days_in_month(year, month)
210.154 -
210.155 - # Now the year and month are correct, and n is the offset from the
210.156 - # start of that month: we're done!
210.157 - return year, month, n + 1
210.158 -
210.159 -# Month and day names. For localized versions, see the calendar module.
210.160 -_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
210.161 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
210.162 -_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
210.163 -
210.164 -
210.165 -def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
210.166 - wday = (_ymd2ord(y, m, d) + 6) % 7
210.167 - dnum = _days_before_month(y, m) + d
210.168 - return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
210.169 -
210.170 -def _format_time(hh, mm, ss, us):
210.171 - # Skip trailing microseconds when us==0.
210.172 - result = "%02d:%02d:%02d" % (hh, mm, ss)
210.173 - if us:
210.174 - result += ".%06d" % us
210.175 - return result
210.176 -
210.177 -# Correctly substitute for %z and %Z escapes in strftime formats.
210.178 -def _wrap_strftime(object, format, timetuple):
210.179 - year = timetuple[0]
210.180 - if year < 1900:
210.181 - raise ValueError("year=%d is before 1900; the datetime strftime() "
210.182 - "methods require year >= 1900" % year)
210.183 - # Don't call _utcoffset() or tzname() unless actually needed.
210.184 - zreplace = None # the string to use for %z
210.185 - Zreplace = None # the string to use for %Z
210.186 -
210.187 - # Scan format for %z and %Z escapes, replacing as needed.
210.188 - newformat = []
210.189 - push = newformat.append
210.190 - i, n = 0, len(format)
210.191 - while i < n:
210.192 - ch = format[i]
210.193 - i += 1
210.194 - if ch == '%':
210.195 - if i < n:
210.196 - ch = format[i]
210.197 - i += 1
210.198 - if ch == 'z':
210.199 - if zreplace is None:
210.200 - zreplace = ""
210.201 - if hasattr(object, "_utcoffset"):
210.202 - offset = object._utcoffset()
210.203 - if offset is not None:
210.204 - sign = '+'
210.205 - if offset < 0:
210.206 - offset = -offset
210.207 - sign = '-'
210.208 - h, m = divmod(offset, 60)
210.209 - zreplace = '%c%02d%02d' % (sign, h, m)
210.210 - assert '%' not in zreplace
210.211 - newformat.append(zreplace)
210.212 - elif ch == 'Z':
210.213 - if Zreplace is None:
210.214 - Zreplace = ""
210.215 - if hasattr(object, "tzname"):
210.216 - s = object.tzname()
210.217 - if s is not None:
210.218 - # strftime is going to have at this: escape %
210.219 - Zreplace = s.replace('%', '%%')
210.220 - newformat.append(Zreplace)
210.221 - else:
210.222 - push('%')
210.223 - push(ch)
210.224 - else:
210.225 - push('%')
210.226 - else:
210.227 - push(ch)
210.228 - newformat = "".join(newformat)
210.229 - return _time.strftime(newformat, timetuple)
210.230 -
210.231 -def _call_tzinfo_method(tzinfo, methname, tzinfoarg):
210.232 - if tzinfo is None:
210.233 - return None
210.234 - return getattr(tzinfo, methname)(tzinfoarg)
210.235 -
210.236 -# Just raise TypeError if the arg isn't None or a string.
210.237 -def _check_tzname(name):
210.238 - if name is not None and not isinstance(name, str):
210.239 - raise TypeError("tzinfo.tzname() must return None or string, "
210.240 - "not '%s'" % type(name))
210.241 -
210.242 -# name is the offset-producing method, "utcoffset" or "dst".
210.243 -# offset is what it returned.
210.244 -# If offset isn't None or timedelta, raises TypeError.
210.245 -# If offset is None, returns None.
210.246 -# Else offset is checked for being in range, and a whole # of minutes.
210.247 -# If it is, its integer value is returned. Else ValueError is raised.
210.248 -def _check_utc_offset(name, offset):
210.249 - assert name in ("utcoffset", "dst")
210.250 - if offset is None:
210.251 - return None
210.252 - if not isinstance(offset, timedelta):
210.253 - raise TypeError("tzinfo.%s() must return None "
210.254 - "or timedelta, not '%s'" % (name, type(offset)))
210.255 - days = offset.days
210.256 - if days < -1 or days > 0:
210.257 - offset = 1440 # trigger out-of-range
210.258 - else:
210.259 - seconds = days * 86400 + offset.seconds
210.260 - minutes, seconds = divmod(seconds, 60)
210.261 - if seconds or offset.microseconds:
210.262 - raise ValueError("tzinfo.%s() must return a whole number "
210.263 - "of minutes" % name)
210.264 - offset = minutes
210.265 - if -1440 < offset < 1440:
210.266 - return offset
210.267 - raise ValueError("%s()=%d, must be in -1439..1439" % (name, offset))
210.268 -
210.269 -def _check_date_fields(year, month, day):
210.270 - if not MINYEAR <= year <= MAXYEAR:
210.271 - raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
210.272 - if not 1 <= month <= 12:
210.273 - raise ValueError('month must be in 1..12', month)
210.274 - dim = _days_in_month(year, month)
210.275 - if not 1 <= day <= dim:
210.276 - raise ValueError('day must be in 1..%d' % dim, day)
210.277 -
210.278 -def _check_time_fields(hour, minute, second, microsecond):
210.279 - if not 0 <= hour <= 23:
210.280 - raise ValueError('hour must be in 0..23', hour)
210.281 - if not 0 <= minute <= 59:
210.282 - raise ValueError('minute must be in 0..59', minute)
210.283 - if not 0 <= second <= 59:
210.284 - raise ValueError('second must be in 0..59', second)
210.285 - if not 0 <= microsecond <= 999999:
210.286 - raise ValueError('microsecond must be in 0..999999', microsecond)
210.287 -
210.288 -def _check_tzinfo_arg(tz):
210.289 - if tz is not None and not isinstance(tz, tzinfo):
210.290 - raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
210.291 -
210.292 -
210.293 -# Notes on comparison: In general, datetime module comparison operators raise
210.294 -# TypeError when they don't know how to do a comparison themself. If they
210.295 -# returned NotImplemented instead, comparison could (silently) fall back to
210.296 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
210.297 -# and that's not helpful. There are two exceptions:
210.298 -#
210.299 -# 1. For date and datetime, if the other object has a "timetuple" attr,
210.300 -# NotImplemented is returned. This is a hook to allow other kinds of
210.301 -# datetime-like objects a chance to intercept the comparison.
210.302 -#
210.303 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
210.304 -# so opertaions like
210.305 -#
210.306 -# x == y
210.307 -# x != y
210.308 -# x in sequence
210.309 -# x not in sequence
210.310 -# dict[x] = y
210.311 -#
210.312 -# don't raise annoying TypeErrors just because a datetime object
210.313 -# is part of a heterogeneous collection. If there's no known way to
210.314 -# compare X to a datetime, saying they're not equal is reasonable.
210.315 -
210.316 -def _cmperror(x, y):
210.317 - raise TypeError("can't compare '%s' to '%s'" % (
210.318 - type(x).__name__, type(y).__name__))
210.319 -
210.320 -# This is a start at a struct tm workalike. Goals:
210.321 -#
210.322 -# + Works the same way across platforms.
210.323 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
210.324 -#
210.325 -# Note: I suspect it's best if this flavor of tm does *not* try to
210.326 -# second-guess timezones or DST. Instead fold whatever adjustments you want
210.327 -# into the minutes argument (and the constructor will normalize).
210.328 -
210.329 -_ORD1970 = _ymd2ord(1970, 1, 1) # base ordinal for UNIX epoch
210.330 -
210.331 -class tmxxx:
210.332 -
210.333 - ordinal = None
210.334 -
210.335 - def __init__(self, year, month, day, hour=0, minute=0, second=0,
210.336 - microsecond=0):
210.337 - # Normalize all the inputs, and store the normalized values.
210.338 - if not 0 <= microsecond <= 999999:
210.339 - carry, microsecond = divmod(microsecond, 1000000)
210.340 - second += carry
210.341 - if not 0 <= second <= 59:
210.342 - carry, second = divmod(second, 60)
210.343 - minute += carry
210.344 - if not 0 <= minute <= 59:
210.345 - carry, minute = divmod(minute, 60)
210.346 - hour += carry
210.347 - if not 0 <= hour <= 23:
210.348 - carry, hour = divmod(hour, 24)
210.349 - day += carry
210.350 -
210.351 - # That was easy. Now it gets muddy: the proper range for day
210.352 - # can't be determined without knowing the correct month and year,
210.353 - # but if day is, e.g., plus or minus a million, the current month
210.354 - # and year values make no sense (and may also be out of bounds
210.355 - # themselves).
210.356 - # Saying 12 months == 1 year should be non-controversial.
210.357 - if not 1 <= month <= 12:
210.358 - carry, month = divmod(month-1, 12)
210.359 - year += carry
210.360 - month += 1
210.361 - assert 1 <= month <= 12
210.362 -
210.363 - # Now only day can be out of bounds (year may also be out of bounds
210.364 - # for a datetime object, but we don't care about that here).
210.365 - # If day is out of bounds, what to do is arguable, but at least the
210.366 - # method here is principled and explainable.
210.367 - dim = _days_in_month(year, month)
210.368 - if not 1 <= day <= dim:
210.369 - # Move day-1 days from the first of the month. First try to
210.370 - # get off cheap if we're only one day out of range (adjustments
210.371 - # for timezone alone can't be worse than that).
210.372 - if day == 0: # move back a day
210.373 - month -= 1
210.374 - if month > 0:
210.375 - day = _days_in_month(year, month)
210.376 - else:
210.377 - year, month, day = year-1, 12, 31
210.378 - elif day == dim + 1: # move forward a day
210.379 - month += 1
210.380 - day = 1
210.381 - if month > 12:
210.382 - month = 1
210.383 - year += 1
210.384 - else:
210.385 - self.ordinal = _ymd2ord(year, month, 1) + (day - 1)
210.386 - year, month, day = _ord2ymd(self.ordinal)
210.387 -
210.388 - self.year, self.month, self.day = year, month, day
210.389 - self.hour, self.minute, self.second = hour, minute, second
210.390 - self.microsecond = microsecond
210.391 -
210.392 - def toordinal(self):
210.393 - """Return proleptic Gregorian ordinal for the year, month and day.
210.394 -
210.395 - January 1 of year 1 is day 1. Only the year, month and day values
210.396 - contribute to the result.
210.397 - """
210.398 - if self.ordinal is None:
210.399 - self.ordinal = _ymd2ord(self.year, self.month, self.day)
210.400 - return self.ordinal
210.401 -
210.402 - def time(self):
210.403 - "Return Unixish timestamp, as a float (assuming UTC)."
210.404 - days = self.toordinal() - _ORD1970 # convert to UNIX epoch
210.405 - seconds = ((days * 24. + self.hour) * 60. + self.minute) * 60.
210.406 - return seconds + self.second + self.microsecond / 1e6
210.407 -
210.408 - def ctime(self):
210.409 - "Return ctime() style string."
210.410 - weekday = self.toordinal() % 7 or 7
210.411 - return "%s %s %2d %02d:%02d:%02d %04d" % (
210.412 - _DAYNAMES[weekday],
210.413 - _MONTHNAMES[self.month],
210.414 - self.day,
210.415 - self.hour, self.minute, self.second,
210.416 - self.year)
210.417 -
210.418 -class timedelta(object):
210.419 - """Represent the difference between two datetime objects.
210.420 -
210.421 - Supported operators:
210.422 -
210.423 - - add, subtract timedelta
210.424 - - unary plus, minus, abs
210.425 - - compare to timedelta
210.426 - - multiply, divide by int/long
210.427 -
210.428 - In addition, datetime supports subtraction of two datetime objects
210.429 - returning a timedelta, and addition or subtraction of a datetime
210.430 - and a timedelta giving a datetime.
210.431 -
210.432 - Representation: (days, seconds, microseconds). Why? Because I
210.433 - felt like it.
210.434 - """
210.435 -
210.436 - def __new__(cls, days=0, seconds=0, microseconds=0,
210.437 - # XXX The following should only be used as keyword args:
210.438 - milliseconds=0, minutes=0, hours=0, weeks=0):
210.439 - # Doing this efficiently and accurately in C is going to be difficult
210.440 - # and error-prone, due to ubiquitous overflow possibilities, and that
210.441 - # C double doesn't have enough bits of precision to represent
210.442 - # microseconds over 10K years faithfully. The code here tries to make
210.443 - # explicit where go-fast assumptions can be relied on, in order to
210.444 - # guide the C implementation; it's way more convoluted than speed-
210.445 - # ignoring auto-overflow-to-long idiomatic Python could be.
210.446 -
210.447 - # XXX Check that all inputs are ints, longs or floats.
210.448 -
210.449 - # Final values, all integer.
210.450 - # s and us fit in 32-bit signed ints; d isn't bounded.
210.451 - d = s = us = 0
210.452 -
210.453 - # Normalize everything to days, seconds, microseconds.
210.454 - days += weeks * 7
210.455 - seconds += minutes * 60 + hours * 3600
210.456 - microseconds += milliseconds * 1000
210.457 -
210.458 - # Get rid of all fractions, and normalize s and us.
210.459 - # Take a deep breath <wink>.
210.460 - if isinstance(days, float):
210.461 - dayfrac, days = _math.modf(days)
210.462 - daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24. * 3600.))
210.463 - assert daysecondswhole == int(daysecondswhole) # can't overflow
210.464 - s = int(daysecondswhole)
210.465 - assert days == long(days)
210.466 - d = long(days)
210.467 - else:
210.468 - daysecondsfrac = 0.0
210.469 - d = days
210.470 - assert isinstance(daysecondsfrac, float)
210.471 - assert abs(daysecondsfrac) <= 1.0
210.472 - assert isinstance(d, (int, long))
210.473 - assert abs(s) <= 24 * 3600
210.474 - # days isn't referenced again before redefinition
210.475 -
210.476 - if isinstance(seconds, float):
210.477 - secondsfrac, seconds = _math.modf(seconds)
210.478 - assert seconds == long(seconds)
210.479 - seconds = long(seconds)
210.480 - secondsfrac += daysecondsfrac
210.481 - assert abs(secondsfrac) <= 2.0
210.482 - else:
210.483 - secondsfrac = daysecondsfrac
210.484 - # daysecondsfrac isn't referenced again
210.485 - assert isinstance(secondsfrac, float)
210.486 - assert abs(secondsfrac) <= 2.0
210.487 -
210.488 - assert isinstance(seconds, (int, long))
210.489 - days, seconds = divmod(seconds, 24 * 3600)
210.490 - d += days
210.491 - s += int(seconds) # can't overflow
210.492 - assert isinstance(s, int)
210.493 - assert abs(s) <= 2 * 24 * 3600
210.494 - # seconds isn't referenced again before redefinition
210.495 -
210.496 - usdouble = secondsfrac * 1e6
210.497 - assert abs(usdouble) < 2.1e6 # exact value not critical
210.498 - # secondsfrac isn't referenced again
210.499 -
210.500 - if isinstance(microseconds, float):
210.501 - microseconds += usdouble
210.502 - microseconds = round(microseconds)
210.503 - seconds, microseconds = divmod(microseconds, 1e6)
210.504 - assert microseconds == int(microseconds)
210.505 - assert seconds == long(seconds)
210.506 - days, seconds = divmod(seconds, 24. * 3600.)
210.507 - assert days == long(days)
210.508 - assert seconds == int(seconds)
210.509 - d += long(days)
210.510 - s += int(seconds) # can't overflow
210.511 - assert isinstance(s, int)
210.512 - assert abs(s) <= 3 * 24 * 3600
210.513 - else:
210.514 - seconds, microseconds = divmod(microseconds, 1000000)
210.515 - days, seconds = divmod(seconds, 24 * 3600)
210.516 - d += days
210.517 - s += int(seconds) # can't overflow
210.518 - assert isinstance(s, int)
210.519 - assert abs(s) <= 3 * 24 * 3600
210.520 - microseconds = float(microseconds)
210.521 - microseconds += usdouble
210.522 - microseconds = round(microseconds)
210.523 - assert abs(s) <= 3 * 24 * 3600
210.524 - assert abs(microseconds) < 3.1e6
210.525 -
210.526 - # Just a little bit of carrying possible for microseconds and seconds.
210.527 - assert isinstance(microseconds, float)
210.528 - assert int(microseconds) == microseconds
210.529 - us = int(microseconds)
210.530 - seconds, us = divmod(us, 1000000)
210.531 - s += seconds # cant't overflow
210.532 - assert isinstance(s, int)
210.533 - days, s = divmod(s, 24 * 3600)
210.534 - d += days
210.535 -
210.536 - assert isinstance(d, (int, long))
210.537 - assert isinstance(s, int) and 0 <= s < 24 * 3600
210.538 - assert isinstance(us, int) and 0 <= us < 1000000
210.539 -
210.540 - self = object.__new__(cls)
210.541 -
210.542 - self.__days = d
210.543 - self.__seconds = s
210.544 - self.__microseconds = us
210.545 - if abs(d) > 999999999:
210.546 - raise OverflowError("timedelta # of days is too large: %d" % d)
210.547 -
210.548 - return self
210.549 -
210.550 - def __repr__(self):
210.551 - if self.__microseconds:
210.552 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
210.553 - self.__days,
210.554 - self.__seconds,
210.555 - self.__microseconds)
210.556 - if self.__seconds:
210.557 - return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__,
210.558 - self.__days,
210.559 - self.__seconds)
210.560 - return "%s(%d)" % ('datetime.' + self.__class__.__name__, self.__days)
210.561 -
210.562 - def __str__(self):
210.563 - mm, ss = divmod(self.__seconds, 60)
210.564 - hh, mm = divmod(mm, 60)
210.565 - s = "%d:%02d:%02d" % (hh, mm, ss)
210.566 - if self.__days:
210.567 - def plural(n):
210.568 - return n, abs(n) != 1 and "s" or ""
210.569 - s = ("%d day%s, " % plural(self.__days)) + s
210.570 - if self.__microseconds:
210.571 - s = s + ".%06d" % self.__microseconds
210.572 - return s
210.573 -
210.574 - days = property(lambda self: self.__days, doc="days")
210.575 - seconds = property(lambda self: self.__seconds, doc="seconds")
210.576 - microseconds = property(lambda self: self.__microseconds,
210.577 - doc="microseconds")
210.578 -
210.579 - def __add__(self, other):
210.580 - if isinstance(other, timedelta):
210.581 - return timedelta(self.__days + other.__days,
210.582 - self.__seconds + other.__seconds,
210.583 - self.__microseconds + other.__microseconds)
210.584 - return NotImplemented
210.585 -
210.586 - __radd__ = __add__
210.587 -
210.588 - def __sub__(self, other):
210.589 - if isinstance(other, timedelta):
210.590 - return self + -other
210.591 - return NotImplemented
210.592 -
210.593 - def __rsub__(self, other):
210.594 - if isinstance(other, timedelta):
210.595 - return -self + other
210.596 - return NotImplemented
210.597 -
210.598 - def __neg__(self):
210.599 - return self.__class__(-self.__days,
210.600 - -self.__seconds,
210.601 - -self.__microseconds)
210.602 -
210.603 - def __pos__(self):
210.604 - return self
210.605 -
210.606 - def __abs__(self):
210.607 - if self.__days < 0:
210.608 - return -self
210.609 - else:
210.610 - return self
210.611 -
210.612 - def __mul__(self, other):
210.613 - if isinstance(other, (int, long)):
210.614 - return self.__class__(self.__days * other,
210.615 - self.__seconds * other,
210.616 - self.__microseconds * other)
210.617 - return NotImplemented
210.618 -
210.619 - __rmul__ = __mul__
210.620 -
210.621 - def __div__(self, other):
210.622 - if isinstance(other, (int, long)):
210.623 - usec = ((self.__days * (24 * 3600L) + self.__seconds) * 1000000 +
210.624 - self.__microseconds)
210.625 - return self.__class__(0, 0, usec // other)
210.626 - return NotImplemented
210.627 -
210.628 - __floordiv__ = __div__
210.629 -
210.630 - # Comparisons.
210.631 -
210.632 - def __eq__(self, other):
210.633 - if isinstance(other, timedelta):
210.634 - return self.__cmp(other) == 0
210.635 - else:
210.636 - return False
210.637 -
210.638 - def __ne__(self, other):
210.639 - if isinstance(other, timedelta):
210.640 - return self.__cmp(other) != 0
210.641 - else:
210.642 - return True
210.643 -
210.644 - def __le__(self, other):
210.645 - if isinstance(other, timedelta):
210.646 - return self.__cmp(other) <= 0
210.647 - else:
210.648 - _cmperror(self, other)
210.649 -
210.650 - def __lt__(self, other):
210.651 - if isinstance(other, timedelta):
210.652 - return self.__cmp(other) < 0
210.653 - else:
210.654 - _cmperror(self, other)
210.655 -
210.656 - def __ge__(self, other):
210.657 - if isinstance(other, timedelta):
210.658 - return self.__cmp(other) >= 0
210.659 - else:
210.660 - _cmperror(self, other)
210.661 -
210.662 - def __gt__(self, other):
210.663 - if isinstance(other, timedelta):
210.664 - return self.__cmp(other) > 0
210.665 - else:
210.666 - _cmperror(self, other)
210.667 -
210.668 - def __cmp(self, other):
210.669 - assert isinstance(other, timedelta)
210.670 - return cmp(self.__getstate(), other.__getstate())
210.671 -
210.672 - def __hash__(self):
210.673 - return hash(self.__getstate())
210.674 -
210.675 - def __nonzero__(self):
210.676 - return (self.__days != 0 or
210.677 - self.__seconds != 0 or
210.678 - self.__microseconds != 0)
210.679 -
210.680 - # Pickle support.
210.681 -
210.682 - __safe_for_unpickling__ = True # For Python 2.2
210.683 -
210.684 - def __getstate(self):
210.685 - return (self.__days, self.__seconds, self.__microseconds)
210.686 -
210.687 - def __reduce__(self):
210.688 - return (self.__class__, self.__getstate())
210.689 -
210.690 -timedelta.min = timedelta(-999999999)
210.691 -timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
210.692 - microseconds=999999)
210.693 -timedelta.resolution = timedelta(microseconds=1)
210.694 -
210.695 -class date(object):
210.696 - """Concrete date type.
210.697 -
210.698 - Constructors:
210.699 -
210.700 - __new__()
210.701 - fromtimestamp()
210.702 - today()
210.703 - fromordinal()
210.704 -
210.705 - Operators:
210.706 -
210.707 - __repr__, __str__
210.708 - __cmp__, __hash__
210.709 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
210.710 -
210.711 - Methods:
210.712 -
210.713 - timetuple()
210.714 - toordinal()
210.715 - weekday()
210.716 - isoweekday(), isocalendar(), isoformat()
210.717 - ctime()
210.718 - strftime()
210.719 -
210.720 - Properties (readonly):
210.721 - year, month, day
210.722 - """
210.723 -
210.724 - def __new__(cls, year, month=None, day=None):
210.725 - """Constructor.
210.726 -
210.727 - Arguments:
210.728 -
210.729 - year, month, day (required, base 1)
210.730 - """
210.731 - if isinstance(year, str):
210.732 - # Pickle support
210.733 - self = object.__new__(cls)
210.734 - self.__setstate((year, ))
210.735 - return self
210.736 - _check_date_fields(year, month, day)
210.737 - self = object.__new__(cls)
210.738 - self.__year = year
210.739 - self.__month = month
210.740 - self.__day = day
210.741 - return self
210.742 -
210.743 - # Additional constructors
210.744 -
210.745 - def fromtimestamp(cls, t):
210.746 - "Construct a date from a POSIX timestamp (like time.time())."
210.747 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
210.748 - return cls(y, m, d)
210.749 - fromtimestamp = classmethod(fromtimestamp)
210.750 -
210.751 - def today(cls):
210.752 - "Construct a date from time.time()."
210.753 - t = _time.time()
210.754 - return cls.fromtimestamp(t)
210.755 - today = classmethod(today)
210.756 -
210.757 - def fromordinal(cls, n):
210.758 - """Contruct a date from a proleptic Gregorian ordinal.
210.759 -
210.760 - January 1 of year 1 is day 1. Only the year, month and day are
210.761 - non-zero in the result.
210.762 - """
210.763 - y, m, d = _ord2ymd(n)
210.764 - return cls(y, m, d)
210.765 - fromordinal = classmethod(fromordinal)
210.766 -
210.767 - # Conversions to string
210.768 -
210.769 - def __repr__(self):
210.770 - "Convert to formal string, for repr()."
210.771 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
210.772 - self.__year,
210.773 - self.__month,
210.774 - self.__day)
210.775 - # XXX These shouldn't depend on time.localtime(), because that
210.776 - # clips the usable dates to [1970 .. 2038). At least ctime() is
210.777 - # easily done without using strftime() -- that's better too because
210.778 - # strftime("%c", ...) is locale specific.
210.779 -
210.780 - def ctime(self):
210.781 - "Format a la ctime()."
210.782 - return tmxxx(self.__year, self.__month, self.__day).ctime()
210.783 -
210.784 - def strftime(self, fmt):
210.785 - "Format using strftime()."
210.786 - return _wrap_strftime(self, fmt, self.timetuple())
210.787 -
210.788 - def isoformat(self):
210.789 - """Return the date formatted according to ISO.
210.790 -
210.791 - This is 'YYYY-MM-DD'.
210.792 -
210.793 - References:
210.794 - - http://www.w3.org/TR/NOTE-datetime
210.795 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
210.796 - """
210.797 - return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day)
210.798 -
210.799 - __str__ = isoformat
210.800 -
210.801 - # Read-only field accessors
210.802 - year = property(lambda self: self.__year,
210.803 - doc="year (%d-%d)" % (MINYEAR, MAXYEAR))
210.804 - month = property(lambda self: self.__month, doc="month (1-12)")
210.805 - day = property(lambda self: self.__day, doc="day (1-31)")
210.806 -
210.807 - # Standard conversions, __cmp__, __hash__ (and helpers)
210.808 -
210.809 - def timetuple(self):
210.810 - "Return local time tuple compatible with time.localtime()."
210.811 - return _build_struct_time(self.__year, self.__month, self.__day,
210.812 - 0, 0, 0, -1)
210.813 -
210.814 - def toordinal(self):
210.815 - """Return proleptic Gregorian ordinal for the year, month and day.
210.816 -
210.817 - January 1 of year 1 is day 1. Only the year, month and day values
210.818 - contribute to the result.
210.819 - """
210.820 - return _ymd2ord(self.__year, self.__month, self.__day)
210.821 -
210.822 - def replace(self, year=None, month=None, day=None):
210.823 - """Return a new date with new values for the specified fields."""
210.824 - if year is None:
210.825 - year = self.__year
210.826 - if month is None:
210.827 - month = self.__month
210.828 - if day is None:
210.829 - day = self.__day
210.830 - _check_date_fields(year, month, day)
210.831 - return date(year, month, day)
210.832 -
210.833 - # Comparisons.
210.834 -
210.835 - def __eq__(self, other):
210.836 - if isinstance(other, date):
210.837 - return self.__cmp(other) == 0
210.838 - elif hasattr(other, "timetuple"):
210.839 - return NotImplemented
210.840 - else:
210.841 - return False
210.842 -
210.843 - def __ne__(self, other):
210.844 - if isinstance(other, date):
210.845 - return self.__cmp(other) != 0
210.846 - elif hasattr(other, "timetuple"):
210.847 - return NotImplemented
210.848 - else:
210.849 - return True
210.850 -
210.851 - def __le__(self, other):
210.852 - if isinstance(other, date):
210.853 - return self.__cmp(other) <= 0
210.854 - elif hasattr(other, "timetuple"):
210.855 - return NotImplemented
210.856 - else:
210.857 - _cmperror(self, other)
210.858 -
210.859 - def __lt__(self, other):
210.860 - if isinstance(other, date):
210.861 - return self.__cmp(other) < 0
210.862 - elif hasattr(other, "timetuple"):
210.863 - return NotImplemented
210.864 - else:
210.865 - _cmperror(self, other)
210.866 -
210.867 - def __ge__(self, other):
210.868 - if isinstance(other, date):
210.869 - return self.__cmp(other) >= 0
210.870 - elif hasattr(other, "timetuple"):
210.871 - return NotImplemented
210.872 - else:
210.873 - _cmperror(self, other)
210.874 -
210.875 - def __gt__(self, other):
210.876 - if isinstance(other, date):
210.877 - return self.__cmp(other) > 0
210.878 - elif hasattr(other, "timetuple"):
210.879 - return NotImplemented
210.880 - else:
210.881 - _cmperror(self, other)
210.882 -
210.883 - def __cmp(self, other):
210.884 - assert isinstance(other, date)
210.885 - y, m, d = self.__year, self.__month, self.__day
210.886 - y2, m2, d2 = other.__year, other.__month, other.__day
210.887 - return cmp((y, m, d), (y2, m2, d2))
210.888 -
210.889 - def __hash__(self):
210.890 - "Hash."
210.891 - return hash(self.__getstate())
210.892 -
210.893 - # Computations
210.894 -
210.895 - def _checkOverflow(self, year):
210.896 - if not MINYEAR <= year <= MAXYEAR:
210.897 - raise OverflowError("date +/-: result year %d not in %d..%d" %
210.898 - (year, MINYEAR, MAXYEAR))
210.899 -
210.900 - def __add__(self, other):
210.901 - "Add a date to a timedelta."
210.902 - if isinstance(other, timedelta):
210.903 - t = tmxxx(self.__year,
210.904 - self.__month,
210.905 - self.__day + other.days)
210.906 - self._checkOverflow(t.year)
210.907 - result = self.__class__(t.year, t.month, t.day)
210.908 - return result
210.909 - return NotImplemented
210.910 -
210.911 - __radd__ = __add__
210.912 -
210.913 - def __sub__(self, other):
210.914 - """Subtract two dates, or a date and a timedelta."""
210.915 - if isinstance(other, timedelta):
210.916 - return self + timedelta(-other.days)
210.917 - if isinstance(other, date):
210.918 - days1 = self.toordinal()
210.919 - days2 = other.toordinal()
210.920 - return timedelta(days1 - days2)
210.921 - return NotImplemented
210.922 -
210.923 - def weekday(self):
210.924 - "Return day of the week, where Monday == 0 ... Sunday == 6."
210.925 - return (self.toordinal() + 6) % 7
210.926 -
210.927 - # Day-of-the-week and week-of-the-year, according to ISO
210.928 -
210.929 - def isoweekday(self):
210.930 - "Return day of the week, where Monday == 1 ... Sunday == 7."
210.931 - # 1-Jan-0001 is a Monday
210.932 - return self.toordinal() % 7 or 7
210.933 -
210.934 - def isocalendar(self):
210.935 - """Return a 3-tuple containing ISO year, week number, and weekday.
210.936 -
210.937 - The first ISO week of the year is the (Mon-Sun) week
210.938 - containing the year's first Thursday; everything else derives
210.939 - from that.
210.940 -
210.941 - The first week is 1; Monday is 1 ... Sunday is 7.
210.942 -
210.943 - ISO calendar algorithm taken from
210.944 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
210.945 - """
210.946 - year = self.__year
210.947 - week1monday = _isoweek1monday(year)
210.948 - today = _ymd2ord(self.__year, self.__month, self.__day)
210.949 - # Internally, week and day have origin 0
210.950 - week, day = divmod(today - week1monday, 7)
210.951 - if week < 0:
210.952 - year -= 1
210.953 - week1monday = _isoweek1monday(year)
210.954 - week, day = divmod(today - week1monday, 7)
210.955 - elif week >= 52:
210.956 - if today >= _isoweek1monday(year + 1):
210.957 - year += 1
210.958 - week = 0
210.959 - return year, week + 1, day + 1
210.960 -
210.961 - # Pickle support.
210.962 -
210.963 - __safe_for_unpickling__ = True # For Python 2.2
210.964 -
210.965 - def __getstate(self):
210.966 - yhi, ylo = divmod(self.__year, 256)
210.967 - return ("%c%c%c%c" % (yhi, ylo, self.__month, self.__day),)
210.968 -
210.969 - def __setstate(self, t):
210.970 - assert isinstance(t, tuple) and len(t) == 1, `t`
210.971 - string = t[0]
210.972 - assert len(string) == 4
210.973 - yhi, ylo, self.__month, self.__day = map(ord, string)
210.974 - self.__year = yhi * 256 + ylo
210.975 -
210.976 - def __reduce__(self):
210.977 - return (self.__class__, self.__getstate())
210.978 -
210.979 -_date_class = date # so functions w/ args named "date" can get at the class
210.980 -
210.981 -date.min = date(1, 1, 1)
210.982 -date.max = date(9999, 12, 31)
210.983 -date.resolution = timedelta(days=1)
210.984 -
210.985 -class tzinfo(object):
210.986 - """Abstract base class for time zone info classes.
210.987 -
210.988 - Subclasses must override the name(), utcoffset() and dst() methods.
210.989 - """
210.990 -
210.991 - def tzname(self, dt):
210.992 - "datetime -> string name of time zone."
210.993 - raise NotImplementedError("tzinfo subclass must override tzname()")
210.994 -
210.995 - def utcoffset(self, dt):
210.996 - "datetime -> minutes east of UTC (negative for west of UTC)"
210.997 - raise NotImplementedError("tzinfo subclass must override utcoffset()")
210.998 -
210.999 - def dst(self, dt):
210.1000 - """datetime -> DST offset in minutes east of UTC.
210.1001 -
210.1002 - Return 0 if DST not in effect. utcoffset() must include the DST
210.1003 - offset.
210.1004 - """
210.1005 - raise NotImplementedError("tzinfo subclass must override dst()")
210.1006 -
210.1007 - def fromutc(self, dt):
210.1008 - "datetime in UTC -> datetime in local time."
210.1009 -
210.1010 - if not isinstance(dt, datetime):
210.1011 - raise TypeError("fromutc() requires a datetime argument")
210.1012 - if dt.tzinfo is not self:
210.1013 - raise ValueError("dt.tzinfo is not self")
210.1014 -
210.1015 - dtoff = dt.utcoffset()
210.1016 - if dtoff is None:
210.1017 - raise ValueError("fromutc() requires a non-None utcoffset() "
210.1018 - "result")
210.1019 -
210.1020 - # See the long comment block at the end of this file for an
210.1021 - # explanation of this algorithm.
210.1022 - dtdst = dt.dst()
210.1023 - if dtdst is None:
210.1024 - raise ValueError("fromutc() requires a non-None dst() result")
210.1025 - delta = dtoff - dtdst
210.1026 - if delta:
210.1027 - dt += delta
210.1028 - dtdst = dt.dst()
210.1029 - if dtdst is None:
210.1030 - raise ValueError("fromutc(): dt.dst gave inconsistent "
210.1031 - "results; cannot convert")
210.1032 - if dtdst:
210.1033 - return dt + dtdst
210.1034 - else:
210.1035 - return dt
210.1036 -
210.1037 - # Pickle support.
210.1038 -
210.1039 - __safe_for_unpickling__ = True # For Python 2.2
210.1040 -
210.1041 - def __reduce__(self):
210.1042 - getinitargs = getattr(self, "__getinitargs__", None)
210.1043 - if getinitargs:
210.1044 - args = getinitargs()
210.1045 - else:
210.1046 - args = ()
210.1047 - getstate = getattr(self, "__getstate__", None)
210.1048 - if getstate:
210.1049 - state = getstate()
210.1050 - else:
210.1051 - state = getattr(self, "__dict__", None) or None
210.1052 - if state is None:
210.1053 - return (self.__class__, args)
210.1054 - else:
210.1055 - return (self.__class__, args, state)
210.1056 -
210.1057 -_tzinfo_class = tzinfo # so functions w/ args named "tinfo" can get at it
210.1058 -
210.1059 -class time(object):
210.1060 - """Time with time zone.
210.1061 -
210.1062 - Constructors:
210.1063 -
210.1064 - __new__()
210.1065 -
210.1066 - Operators:
210.1067 -
210.1068 - __repr__, __str__
210.1069 - __cmp__, __hash__
210.1070 -
210.1071 - Methods:
210.1072 -
210.1073 - strftime()
210.1074 - isoformat()
210.1075 - utcoffset()
210.1076 - tzname()
210.1077 - dst()
210.1078 -
210.1079 - Properties (readonly):
210.1080 - hour, minute, second, microsecond, tzinfo
210.1081 - """
210.1082 -
210.1083 - def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
210.1084 - """Constructor.
210.1085 -
210.1086 - Arguments:
210.1087 -
210.1088 - hour, minute (required)
210.1089 - second, microsecond (default to zero)
210.1090 - tzinfo (default to None)
210.1091 - """
210.1092 - self = object.__new__(cls)
210.1093 - if isinstance(hour, str):
210.1094 - # Pickle support
210.1095 - self.__setstate((hour, minute or None))
210.1096 - return self
210.1097 - _check_tzinfo_arg(tzinfo)
210.1098 - _check_time_fields(hour, minute, second, microsecond)
210.1099 - self.__hour = hour
210.1100 - self.__minute = minute
210.1101 - self.__second = second
210.1102 - self.__microsecond = microsecond
210.1103 - self._tzinfo = tzinfo
210.1104 - return self
210.1105 -
210.1106 - # Read-only field accessors
210.1107 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
210.1108 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
210.1109 - second = property(lambda self: self.__second, doc="second (0-59)")
210.1110 - microsecond = property(lambda self: self.__microsecond,
210.1111 - doc="microsecond (0-999999)")
210.1112 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
210.1113 -
210.1114 - # Standard conversions, __hash__ (and helpers)
210.1115 -
210.1116 - # Comparisons.
210.1117 -
210.1118 - def __eq__(self, other):
210.1119 - if isinstance(other, time):
210.1120 - return self.__cmp(other) == 0
210.1121 - else:
210.1122 - return False
210.1123 -
210.1124 - def __ne__(self, other):
210.1125 - if isinstance(other, time):
210.1126 - return self.__cmp(other) != 0
210.1127 - else:
210.1128 - return True
210.1129 -
210.1130 - def __le__(self, other):
210.1131 - if isinstance(other, time):
210.1132 - return self.__cmp(other) <= 0
210.1133 - else:
210.1134 - _cmperror(self, other)
210.1135 -
210.1136 - def __lt__(self, other):
210.1137 - if isinstance(other, time):
210.1138 - return self.__cmp(other) < 0
210.1139 - else:
210.1140 - _cmperror(self, other)
210.1141 -
210.1142 - def __ge__(self, other):
210.1143 - if isinstance(other, time):
210.1144 - return self.__cmp(other) >= 0
210.1145 - else:
210.1146 - _cmperror(self, other)
210.1147 -
210.1148 - def __gt__(self, other):
210.1149 - if isinstance(other, time):
210.1150 - return self.__cmp(other) > 0
210.1151 - else:
210.1152 - _cmperror(self, other)
210.1153 -
210.1154 - def __cmp(self, other):
210.1155 - assert isinstance(other, time)
210.1156 - mytz = self._tzinfo
210.1157 - ottz = other._tzinfo
210.1158 - myoff = otoff = None
210.1159 -
210.1160 - if mytz is ottz:
210.1161 - base_compare = True
210.1162 - else:
210.1163 - myoff = self._utcoffset()
210.1164 - otoff = other._utcoffset()
210.1165 - base_compare = myoff == otoff
210.1166 -
210.1167 - if base_compare:
210.1168 - return cmp((self.__hour, self.__minute, self.__second,
210.1169 - self.__microsecond),
210.1170 - (other.__hour, other.__minute, other.__second,
210.1171 - other.__microsecond))
210.1172 - if myoff is None or otoff is None:
210.1173 - # XXX Buggy in 2.2.2.
210.1174 - raise TypeError("cannot compare naive and aware times")
210.1175 - myhhmm = self.__hour * 60 + self.__minute - myoff
210.1176 - othhmm = other.__hour * 60 + other.__minute - otoff
210.1177 - return cmp((myhhmm, self.__second, self.__microsecond),
210.1178 - (othhmm, other.__second, other.__microsecond))
210.1179 -
210.1180 - def __hash__(self):
210.1181 - """Hash."""
210.1182 - tzoff = self._utcoffset()
210.1183 - if not tzoff: # zero or None
210.1184 - return hash(self.__getstate()[0])
210.1185 - h, m = divmod(self.hour * 60 + self.minute - tzoff, 60)
210.1186 - if 0 <= h < 24:
210.1187 - return hash(time(h, m, self.second, self.microsecond))
210.1188 - return hash((h, m, self.second, self.microsecond))
210.1189 -
210.1190 - # Conversion to string
210.1191 -
210.1192 - def _tzstr(self, sep=":"):
210.1193 - """Return formatted timezone offset (+xx:xx) or None."""
210.1194 - off = self._utcoffset()
210.1195 - if off is not None:
210.1196 - if off < 0:
210.1197 - sign = "-"
210.1198 - off = -off
210.1199 - else:
210.1200 - sign = "+"
210.1201 - hh, mm = divmod(off, 60)
210.1202 - assert 0 <= hh < 24
210.1203 - off = "%s%02d%s%02d" % (sign, hh, sep, mm)
210.1204 - return off
210.1205 -
210.1206 - def __repr__(self):
210.1207 - """Convert to formal string, for repr()."""
210.1208 - if self.__microsecond != 0:
210.1209 - s = ", %d, %d" % (self.__second, self.__microsecond)
210.1210 - elif self.__second != 0:
210.1211 - s = ", %d" % self.__second
210.1212 - else:
210.1213 - s = ""
210.1214 - s = "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__,
210.1215 - self.__hour, self.__minute, s)
210.1216 - if self._tzinfo is not None:
210.1217 - assert s[-1:] == ")"
210.1218 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
210.1219 - return s
210.1220 -
210.1221 - def isoformat(self):
210.1222 - """Return the time formatted according to ISO.
210.1223 -
210.1224 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
210.1225 - self.microsecond == 0.
210.1226 - """
210.1227 - s = _format_time(self.__hour, self.__minute, self.__second,
210.1228 - self.__microsecond)
210.1229 - tz = self._tzstr()
210.1230 - if tz:
210.1231 - s += tz
210.1232 - return s
210.1233 -
210.1234 - __str__ = isoformat
210.1235 -
210.1236 - def strftime(self, fmt):
210.1237 - """Format using strftime(). The date part of the timestamp passed
210.1238 - to underlying strftime should not be used.
210.1239 - """
210.1240 - # The year must be >= 1900 else Python's strftime implementation
210.1241 - # can raise a bogus exception.
210.1242 - timetuple = (1900, 1, 1,
210.1243 - self.__hour, self.__minute, self.__second,
210.1244 - 0, 1, -1)
210.1245 - return _wrap_strftime(self, fmt, timetuple)
210.1246 -
210.1247 - # Timezone functions
210.1248 -
210.1249 - def utcoffset(self):
210.1250 - """Return the timezone offset in minutes east of UTC (negative west of
210.1251 - UTC)."""
210.1252 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
210.1253 - offset = _check_utc_offset("utcoffset", offset)
210.1254 - if offset is not None:
210.1255 - offset = timedelta(minutes=offset)
210.1256 - return offset
210.1257 -
210.1258 - # Return an integer (or None) instead of a timedelta (or None).
210.1259 - def _utcoffset(self):
210.1260 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
210.1261 - offset = _check_utc_offset("utcoffset", offset)
210.1262 - return offset
210.1263 -
210.1264 - def tzname(self):
210.1265 - """Return the timezone name.
210.1266 -
210.1267 - Note that the name is 100% informational -- there's no requirement that
210.1268 - it mean anything in particular. For example, "GMT", "UTC", "-500",
210.1269 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
210.1270 - """
210.1271 - name = _call_tzinfo_method(self._tzinfo, "tzname", None)
210.1272 - _check_tzname(name)
210.1273 - return name
210.1274 -
210.1275 - def dst(self):
210.1276 - """Return 0 if DST is not in effect, or the DST offset (in minutes
210.1277 - eastward) if DST is in effect.
210.1278 -
210.1279 - This is purely informational; the DST offset has already been added to
210.1280 - the UTC offset returned by utcoffset() if applicable, so there's no
210.1281 - need to consult dst() unless you're interested in displaying the DST
210.1282 - info.
210.1283 - """
210.1284 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
210.1285 - offset = _check_utc_offset("dst", offset)
210.1286 - if offset is not None:
210.1287 - offset = timedelta(minutes=offset)
210.1288 - return offset
210.1289 -
210.1290 - def replace(self, hour=None, minute=None, second=None, microsecond=None,
210.1291 - tzinfo=True):
210.1292 - """Return a new time with new values for the specified fields."""
210.1293 - if hour is None:
210.1294 - hour = self.hour
210.1295 - if minute is None:
210.1296 - minute = self.minute
210.1297 - if second is None:
210.1298 - second = self.second
210.1299 - if microsecond is None:
210.1300 - microsecond = self.microsecond
210.1301 - if tzinfo is True:
210.1302 - tzinfo = self.tzinfo
210.1303 - _check_time_fields(hour, minute, second, microsecond)
210.1304 - _check_tzinfo_arg(tzinfo)
210.1305 - return time(hour, minute, second, microsecond, tzinfo)
210.1306 -
210.1307 - # Return an integer (or None) instead of a timedelta (or None).
210.1308 - def _dst(self):
210.1309 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
210.1310 - offset = _check_utc_offset("dst", offset)
210.1311 - return offset
210.1312 -
210.1313 - def __nonzero__(self):
210.1314 - if self.second or self.microsecond:
210.1315 - return 1
210.1316 - offset = self._utcoffset() or 0
210.1317 - return self.hour * 60 + self.minute - offset != 0
210.1318 -
210.1319 - # Pickle support.
210.1320 -
210.1321 - __safe_for_unpickling__ = True # For Python 2.2
210.1322 -
210.1323 - def __getstate(self):
210.1324 - us2, us3 = divmod(self.__microsecond, 256)
210.1325 - us1, us2 = divmod(us2, 256)
210.1326 - basestate = ("%c" * 6) % (self.__hour, self.__minute, self.__second,
210.1327 - us1, us2, us3)
210.1328 - if self._tzinfo is None:
210.1329 - return (basestate, )
210.1330 - else:
210.1331 - return (basestate, self._tzinfo)
210.1332 -
210.1333 - def __setstate(self, state):
210.1334 - assert isinstance(state, tuple)
210.1335 - assert 1 <= len(state) <= 2
210.1336 - string = state[0]
210.1337 - assert len(string) == 6
210.1338 - self.__hour, self.__minute, self.__second, us1, us2, us3 = \
210.1339 - map(ord, string)
210.1340 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
210.1341 - if len(state) == 1:
210.1342 - self._tzinfo = None
210.1343 - else:
210.1344 - self._tzinfo = state[1]
210.1345 -
210.1346 - def __reduce__(self):
210.1347 - return (self.__class__, self.__getstate())
210.1348 -
210.1349 -_time_class = time # so functions w/ args named "time" can get at the class
210.1350 -
210.1351 -time.min = time(0, 0, 0)
210.1352 -time.max = time(23, 59, 59, 999999)
210.1353 -time.resolution = timedelta(microseconds=1)
210.1354 -
210.1355 -class datetime(date):
210.1356 -
210.1357 - # XXX needs docstrings
210.1358 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
210.1359 -
210.1360 - def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
210.1361 - microsecond=0, tzinfo=None):
210.1362 - if isinstance(year, str):
210.1363 - # Pickle support
210.1364 - self = date.__new__(cls, year[:4])
210.1365 - self.__setstate((year, month))
210.1366 - return self
210.1367 - _check_tzinfo_arg(tzinfo)
210.1368 - _check_time_fields(hour, minute, second, microsecond)
210.1369 - self = date.__new__(cls, year, month, day)
210.1370 - # XXX This duplicates __year, __month, __day for convenience :-(
210.1371 - self.__year = year
210.1372 - self.__month = month
210.1373 - self.__day = day
210.1374 - self.__hour = hour
210.1375 - self.__minute = minute
210.1376 - self.__second = second
210.1377 - self.__microsecond = microsecond
210.1378 - self._tzinfo = tzinfo
210.1379 - return self
210.1380 -
210.1381 - # Read-only field accessors
210.1382 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
210.1383 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
210.1384 - second = property(lambda self: self.__second, doc="second (0-59)")
210.1385 - microsecond = property(lambda self: self.__microsecond,
210.1386 - doc="microsecond (0-999999)")
210.1387 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
210.1388 -
210.1389 - def fromtimestamp(cls, t, tz=None):
210.1390 - """Construct a datetime from a POSIX timestamp (like time.time()).
210.1391 -
210.1392 - A timezone info object may be passed in as well.
210.1393 - """
210.1394 -
210.1395 - _check_tzinfo_arg(tz)
210.1396 - if tz is None:
210.1397 - converter = _time.localtime
210.1398 - else:
210.1399 - converter = _time.gmtime
210.1400 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
210.1401 - us = int((t % 1.0) * 1000000)
210.1402 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
210.1403 - result = cls(y, m, d, hh, mm, ss, us, tz)
210.1404 - if tz is not None:
210.1405 - result = tz.fromutc(result)
210.1406 - return result
210.1407 - fromtimestamp = classmethod(fromtimestamp)
210.1408 -
210.1409 - def utcfromtimestamp(cls, t):
210.1410 - "Construct a UTC datetime from a POSIX timestamp (like time.time())."
210.1411 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
210.1412 - us = int((t % 1.0) * 1000000)
210.1413 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
210.1414 - return cls(y, m, d, hh, mm, ss, us)
210.1415 - utcfromtimestamp = classmethod(utcfromtimestamp)
210.1416 -
210.1417 - # XXX This is supposed to do better than we *can* do by using time.time(),
210.1418 - # XXX if the platform supports a more accurate way. The C implementation
210.1419 - # XXX uses gettimeofday on platforms that have it, but that isn't
210.1420 - # XXX available from Python. So now() may return different results
210.1421 - # XXX across the implementations.
210.1422 - def now(cls, tz=None):
210.1423 - "Construct a datetime from time.time() and optional time zone info."
210.1424 - t = _time.time()
210.1425 - return cls.fromtimestamp(t, tz)
210.1426 - now = classmethod(now)
210.1427 -
210.1428 - def utcnow(cls):
210.1429 - "Construct a UTC datetime from time.time()."
210.1430 - t = _time.time()
210.1431 - return cls.utcfromtimestamp(t)
210.1432 - utcnow = classmethod(utcnow)
210.1433 -
210.1434 - def combine(cls, date, time):
210.1435 - "Construct a datetime from a given date and a given time."
210.1436 - if not isinstance(date, _date_class):
210.1437 - raise TypeError("date argument must be a date instance")
210.1438 - if not isinstance(time, _time_class):
210.1439 - raise TypeError("time argument must be a time instance")
210.1440 - return cls(date.year, date.month, date.day,
210.1441 - time.hour, time.minute, time.second, time.microsecond,
210.1442 - time.tzinfo)
210.1443 - combine = classmethod(combine)
210.1444 -
210.1445 - def timetuple(self):
210.1446 - "Return local time tuple compatible with time.localtime()."
210.1447 - dst = self._dst()
210.1448 - if dst is None:
210.1449 - dst = -1
210.1450 - elif dst:
210.1451 - dst = 1
210.1452 - return _build_struct_time(self.year, self.month, self.day,
210.1453 - self.hour, self.minute, self.second,
210.1454 - dst)
210.1455 -
210.1456 - def utctimetuple(self):
210.1457 - "Return UTC time tuple compatible with time.gmtime()."
210.1458 - y, m, d = self.year, self.month, self.day
210.1459 - hh, mm, ss = self.hour, self.minute, self.second
210.1460 - offset = self._utcoffset()
210.1461 - if offset: # neither None nor 0
210.1462 - tm = tmxxx(y, m, d, hh, mm - offset)
210.1463 - y, m, d = tm.year, tm.month, tm.day
210.1464 - hh, mm = tm.hour, tm.minute
210.1465 - return _build_struct_time(y, m, d, hh, mm, ss, 0)
210.1466 -
210.1467 - def date(self):
210.1468 - "Return the date part."
210.1469 - return date(self.__year, self.__month, self.__day)
210.1470 -
210.1471 - def time(self):
210.1472 - "Return the time part, with tzinfo None."
210.1473 - return time(self.hour, self.minute, self.second, self.microsecond)
210.1474 -
210.1475 - def timetz(self):
210.1476 - "Return the time part, with same tzinfo."
210.1477 - return time(self.hour, self.minute, self.second, self.microsecond,
210.1478 - self._tzinfo)
210.1479 -
210.1480 - def replace(self, year=None, month=None, day=None, hour=None,
210.1481 - minute=None, second=None, microsecond=None, tzinfo=True):
210.1482 - """Return a new datetime with new values for the specified fields."""
210.1483 - if year is None:
210.1484 - year = self.year
210.1485 - if month is None:
210.1486 - month = self.month
210.1487 - if day is None:
210.1488 - day = self.day
210.1489 - if hour is None:
210.1490 - hour = self.hour
210.1491 - if minute is None:
210.1492 - minute = self.minute
210.1493 - if second is None:
210.1494 - second = self.second
210.1495 - if microsecond is None:
210.1496 - microsecond = self.microsecond
210.1497 - if tzinfo is True:
210.1498 - tzinfo = self.tzinfo
210.1499 - _check_date_fields(year, month, day)
210.1500 - _check_time_fields(hour, minute, second, microsecond)
210.1501 - _check_tzinfo_arg(tzinfo)
210.1502 - return datetime(year, month, day, hour, minute, second,
210.1503 - microsecond, tzinfo)
210.1504 -
210.1505 - def astimezone(self, tz):
210.1506 - if not isinstance(tz, tzinfo):
210.1507 - raise TypeError("tz argument must be an instance of tzinfo")
210.1508 -
210.1509 - mytz = self.tzinfo
210.1510 - if mytz is None:
210.1511 - raise ValueError("astimezone() requires an aware datetime")
210.1512 -
210.1513 - if tz is mytz:
210.1514 - return self
210.1515 -
210.1516 - # Convert self to UTC, and attach the new time zone object.
210.1517 - myoffset = self.utcoffset()
210.1518 - if myoffset is None:
210.1519 - raise ValuError("astimezone() requires an aware datetime")
210.1520 - utc = (self - myoffset).replace(tzinfo=tz)
210.1521 -
210.1522 - # Convert from UTC to tz's local time.
210.1523 - return tz.fromutc(utc)
210.1524 -
210.1525 - # Ways to produce a string.
210.1526 -
210.1527 - def ctime(self):
210.1528 - "Format a la ctime()."
210.1529 - t = tmxxx(self.__year, self.__month, self.__day, self.__hour,
210.1530 - self.__minute, self.__second)
210.1531 - return t.ctime()
210.1532 -
210.1533 - def isoformat(self, sep='T'):
210.1534 - """Return the time formatted according to ISO.
210.1535 -
210.1536 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
210.1537 - self.microsecond == 0.
210.1538 -
210.1539 - If self.tzinfo is not None, the UTC offset is also attached, giving
210.1540 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
210.1541 -
210.1542 - Optional argument sep specifies the separator between date and
210.1543 - time, default 'T'.
210.1544 - """
210.1545 - s = ("%04d-%02d-%02d%c" % (self.__year, self.__month, self.__day,
210.1546 - sep) +
210.1547 - _format_time(self.__hour, self.__minute, self.__second,
210.1548 - self.__microsecond))
210.1549 - off = self._utcoffset()
210.1550 - if off is not None:
210.1551 - if off < 0:
210.1552 - sign = "-"
210.1553 - off = -off
210.1554 - else:
210.1555 - sign = "+"
210.1556 - hh, mm = divmod(off, 60)
210.1557 - s += "%s%02d:%02d" % (sign, hh, mm)
210.1558 - return s
210.1559 -
210.1560 - def __repr__(self):
210.1561 - "Convert to formal string, for repr()."
210.1562 - L = [self.__year, self.__month, self.__day, # These are never zero
210.1563 - self.__hour, self.__minute, self.__second, self.__microsecond]
210.1564 - if L[-1] == 0:
210.1565 - del L[-1]
210.1566 - if L[-1] == 0:
210.1567 - del L[-1]
210.1568 - s = ", ".join(map(str, L))
210.1569 - s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s)
210.1570 - if self._tzinfo is not None:
210.1571 - assert s[-1:] == ")"
210.1572 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
210.1573 - return s
210.1574 -
210.1575 - def __str__(self):
210.1576 - "Convert to string, for str()."
210.1577 - return self.isoformat(sep=' ')
210.1578 -
210.1579 - def utcoffset(self):
210.1580 - """Return the timezone offset in minutes east of UTC (negative west of
210.1581 - UTC)."""
210.1582 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
210.1583 - offset = _check_utc_offset("utcoffset", offset)
210.1584 - if offset is not None:
210.1585 - offset = timedelta(minutes=offset)
210.1586 - return offset
210.1587 -
210.1588 - # Return an integer (or None) instead of a timedelta (or None).
210.1589 - def _utcoffset(self):
210.1590 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
210.1591 - offset = _check_utc_offset("utcoffset", offset)
210.1592 - return offset
210.1593 -
210.1594 - def tzname(self):
210.1595 - """Return the timezone name.
210.1596 -
210.1597 - Note that the name is 100% informational -- there's no requirement that
210.1598 - it mean anything in particular. For example, "GMT", "UTC", "-500",
210.1599 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
210.1600 - """
210.1601 - name = _call_tzinfo_method(self._tzinfo, "tzname", self)
210.1602 - _check_tzname(name)
210.1603 - return name
210.1604 -
210.1605 - def dst(self):
210.1606 - """Return 0 if DST is not in effect, or the DST offset (in minutes
210.1607 - eastward) if DST is in effect.
210.1608 -
210.1609 - This is purely informational; the DST offset has already been added to
210.1610 - the UTC offset returned by utcoffset() if applicable, so there's no
210.1611 - need to consult dst() unless you're interested in displaying the DST
210.1612 - info.
210.1613 - """
210.1614 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
210.1615 - offset = _check_utc_offset("dst", offset)
210.1616 - if offset is not None:
210.1617 - offset = timedelta(minutes=offset)
210.1618 - return offset
210.1619 -
210.1620 - # Return an integer (or None) instead of a timedelta (or None).1573
210.1621 - def _dst(self):
210.1622 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
210.1623 - offset = _check_utc_offset("dst", offset)
210.1624 - return offset
210.1625 -
210.1626 - # Comparisons.
210.1627 -
210.1628 - def __eq__(self, other):
210.1629 - if isinstance(other, datetime):
210.1630 - return self.__cmp(other) == 0
210.1631 - elif hasattr(other, "timetuple"):
210.1632 - return NotImplemented
210.1633 - else:
210.1634 - return False
210.1635 -
210.1636 - def __ne__(self, other):
210.1637 - if isinstance(other, datetime):
210.1638 - return self.__cmp(other) != 0
210.1639 - elif hasattr(other, "timetuple"):
210.1640 - return NotImplemented
210.1641 - else:
210.1642 - return True
210.1643 -
210.1644 - def __le__(self, other):
210.1645 - if isinstance(other, datetime):
210.1646 - return self.__cmp(other) <= 0
210.1647 - elif hasattr(other, "timetuple"):
210.1648 - return NotImplemented
210.1649 - else:
210.1650 - _cmperror(self, other)
210.1651 -
210.1652 - def __lt__(self, other):
210.1653 - if isinstance(other, datetime):
210.1654 - return self.__cmp(other) < 0
210.1655 - elif hasattr(other, "timetuple"):
210.1656 - return NotImplemented
210.1657 - else:
210.1658 - _cmperror(self, other)
210.1659 -
210.1660 - def __ge__(self, other):
210.1661 - if isinstance(other, datetime):
210.1662 - return self.__cmp(other) >= 0
210.1663 - elif hasattr(other, "timetuple"):
210.1664 - return NotImplemented
210.1665 - else:
210.1666 - _cmperror(self, other)
210.1667 -
210.1668 - def __gt__(self, other):
210.1669 - if isinstance(other, datetime):
210.1670 - return self.__cmp(other) > 0
210.1671 - elif hasattr(other, "timetuple"):
210.1672 - return NotImplemented
210.1673 - else:
210.1674 - _cmperror(self, other)
210.1675 -
210.1676 - def __cmp(self, other):
210.1677 - assert isinstance(other, datetime)
210.1678 - mytz = self._tzinfo
210.1679 - ottz = other._tzinfo
210.1680 - myoff = otoff = None
210.1681 -
210.1682 - if mytz is ottz:
210.1683 - base_compare = True
210.1684 - else:
210.1685 - if mytz is not None:
210.1686 - myoff = self._utcoffset()
210.1687 - if ottz is not None:
210.1688 - otoff = other._utcoffset()
210.1689 - base_compare = myoff == otoff
210.1690 -
210.1691 - if base_compare:
210.1692 - return cmp((self.__year, self.__month, self.__day,
210.1693 - self.__hour, self.__minute, self.__second,
210.1694 - self.__microsecond),
210.1695 - (other.__year, other.__month, other.__day,
210.1696 - other.__hour, other.__minute, other.__second,
210.1697 - other.__microsecond))
210.1698 - if myoff is None or otoff is None:
210.1699 - # XXX Buggy in 2.2.2.
210.1700 - raise TypeError("cannot compare naive and aware datetimes")
210.1701 - # XXX What follows could be done more efficiently...
210.1702 - diff = self - other # this will take offsets into account
210.1703 - if diff.days < 0:
210.1704 - return -1
210.1705 - return diff and 1 or 0
210.1706 -
210.1707 - def __add__(self, other):
210.1708 - "Add a datetime and a timedelta."
210.1709 - if not isinstance(other, timedelta):
210.1710 - return NotImplemented
210.1711 - t = tmxxx(self.__year,
210.1712 - self.__month,
210.1713 - self.__day + other.days,
210.1714 - self.__hour,
210.1715 - self.__minute,
210.1716 - self.__second + other.seconds,
210.1717 - self.__microsecond + other.microseconds)
210.1718 - self._checkOverflow(t.year)
210.1719 - result = self.__class__(t.year, t.month, t.day,
210.1720 - t.hour, t.minute, t.second,
210.1721 - t.microsecond, tzinfo=self._tzinfo)
210.1722 - return result
210.1723 -
210.1724 - __radd__ = __add__
210.1725 -
210.1726 - def __sub__(self, other):
210.1727 - "Subtract two datetimes, or a datetime and a timedelta."
210.1728 - if not isinstance(other, datetime):
210.1729 - if isinstance(other, timedelta):
210.1730 - return self + -other
210.1731 - return NotImplemented
210.1732 -
210.1733 - days1 = self.toordinal()
210.1734 - days2 = other.toordinal()
210.1735 - secs1 = self.__second + self.__minute * 60 + self.__hour * 3600
210.1736 - secs2 = other.__second + other.__minute * 60 + other.__hour * 3600
210.1737 - base = timedelta(days1 - days2,
210.1738 - secs1 - secs2,
210.1739 - self.__microsecond - other.__microsecond)
210.1740 - if self._tzinfo is other._tzinfo:
210.1741 - return base
210.1742 - myoff = self._utcoffset()
210.1743 - otoff = other._utcoffset()
210.1744 - if myoff == otoff:
210.1745 - return base
210.1746 - if myoff is None or otoff is None:
210.1747 - raise TypeError, "cannot mix naive and timezone-aware time"
210.1748 - return base + timedelta(minutes=otoff-myoff)
210.1749 -
210.1750 - def __hash__(self):
210.1751 - tzoff = self._utcoffset()
210.1752 - if tzoff is None:
210.1753 - return hash(self.__getstate()[0])
210.1754 - days = _ymd2ord(self.year, self.month, self.day)
210.1755 - seconds = self.hour * 3600 + (self.minute - tzoff) * 60 + self.second
210.1756 - return hash(timedelta(days, seconds, self.microsecond))
210.1757 -
210.1758 - # Pickle support.
210.1759 -
210.1760 - __safe_for_unpickling__ = True # For Python 2.2
210.1761 -
210.1762 - def __getstate(self):
210.1763 - yhi, ylo = divmod(self.__year, 256)
210.1764 - us2, us3 = divmod(self.__microsecond, 256)
210.1765 - us1, us2 = divmod(us2, 256)
210.1766 - basestate = ("%c" * 10) % (yhi, ylo, self.__month, self.__day,
210.1767 - self.__hour, self.__minute, self.__second,
210.1768 - us1, us2, us3)
210.1769 - if self._tzinfo is None:
210.1770 - return (basestate, )
210.1771 - else:
210.1772 - return (basestate, self._tzinfo)
210.1773 -
210.1774 - def __setstate(self, state):
210.1775 - assert isinstance(state, tuple)
210.1776 - assert 1 <= len(state) <= 2
210.1777 - string = state[0]
210.1778 - assert len(string) == 10
210.1779 - (yhi, ylo, self.__month, self.__day, self.__hour,
210.1780 - self.__minute, self.__second, us1, us2, us3) = map(ord, string)
210.1781 - self.__year = yhi * 256 + ylo
210.1782 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
210.1783 - if len(state) == 1:
210.1784 - self._tzinfo = None
210.1785 - else:
210.1786 - self._tzinfo = state[1]
210.1787 -
210.1788 - def __reduce__(self):
210.1789 - return (self.__class__, self.__getstate())
210.1790 -
210.1791 -
210.1792 -datetime.min = datetime(1, 1, 1)
210.1793 -datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
210.1794 -datetime.resolution = timedelta(microseconds=1)
210.1795 -
210.1796 -
210.1797 -def _isoweek1monday(year):
210.1798 - # Helper to calculate the day number of the Monday starting week 1
210.1799 - # XXX This could be done more efficiently
210.1800 - THURSDAY = 3
210.1801 - firstday = _ymd2ord(year, 1, 1)
210.1802 - firstweekday = (firstday + 6) % 7 # See weekday() above
210.1803 - week1monday = firstday - firstweekday
210.1804 - if firstweekday > THURSDAY:
210.1805 - week1monday += 7
210.1806 - return week1monday
210.1807 -
210.1808 -"""
210.1809 -Some time zone algebra. For a datetime x, let
210.1810 - x.n = x stripped of its timezone -- its naive time.
210.1811 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
210.1812 - return None
210.1813 - x.d = x.dst(), and assuming that doesn't raise an exception or
210.1814 - return None
210.1815 - x.s = x's standard offset, x.o - x.d
210.1816 -
210.1817 -Now some derived rules, where k is a duration (timedelta).
210.1818 -
210.1819 -1. x.o = x.s + x.d
210.1820 - This follows from the definition of x.s.
210.1821 -
210.1822 -2. If x and y have the same tzinfo member, x.s = y.s.
210.1823 - This is actually a requirement, an assumption we need to make about
210.1824 - sane tzinfo classes.
210.1825 -
210.1826 -3. The naive UTC time corresponding to x is x.n - x.o.
210.1827 - This is again a requirement for a sane tzinfo class.
210.1828 -
210.1829 -4. (x+k).s = x.s
210.1830 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
210.1831 -
210.1832 -5. (x+k).n = x.n + k
210.1833 - Again follows from how arithmetic is defined.
210.1834 -
210.1835 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
210.1836 -(meaning that the various tzinfo methods exist, and don't blow up or return
210.1837 -None when called).
210.1838 -
210.1839 -The function wants to return a datetime y with timezone tz, equivalent to x.
210.1840 -x is already in UTC.
210.1841 -
210.1842 -By #3, we want
210.1843 -
210.1844 - y.n - y.o = x.n [1]
210.1845 -
210.1846 -The algorithm starts by attaching tz to x.n, and calling that y. So
210.1847 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
210.1848 -becomes true; in effect, we want to solve [2] for k:
210.1849 -
210.1850 - (y+k).n - (y+k).o = x.n [2]
210.1851 -
210.1852 -By #1, this is the same as
210.1853 -
210.1854 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
210.1855 -
210.1856 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
210.1857 -Substituting that into [3],
210.1858 -
210.1859 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
210.1860 - k - (y+k).s - (y+k).d = 0; rearranging,
210.1861 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
210.1862 - k = y.s - (y+k).d
210.1863 -
210.1864 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
210.1865 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
210.1866 -very large, since all offset-returning methods return a duration of magnitude
210.1867 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
210.1868 -be 0, so ignoring it has no consequence then.
210.1869 -
210.1870 -In any case, the new value is
210.1871 -
210.1872 - z = y + y.s [4]
210.1873 -
210.1874 -It's helpful to step back at look at [4] from a higher level: it's simply
210.1875 -mapping from UTC to tz's standard time.
210.1876 -
210.1877 -At this point, if
210.1878 -
210.1879 - z.n - z.o = x.n [5]
210.1880 -
210.1881 -we have an equivalent time, and are almost done. The insecurity here is
210.1882 -at the start of daylight time. Picture US Eastern for concreteness. The wall
210.1883 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
210.1884 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
210.1885 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
210.1886 -on the day DST starts. We want to return the 1:MM EST spelling because that's
210.1887 -the only spelling that makes sense on the local wall clock.
210.1888 -
210.1889 -In fact, if [5] holds at this point, we do have the standard-time spelling,
210.1890 -but that takes a bit of proof. We first prove a stronger result. What's the
210.1891 -difference between the LHS and RHS of [5]? Let
210.1892 -
210.1893 - diff = x.n - (z.n - z.o) [6]
210.1894 -
210.1895 -Now
210.1896 - z.n = by [4]
210.1897 - (y + y.s).n = by #5
210.1898 - y.n + y.s = since y.n = x.n
210.1899 - x.n + y.s = since z and y are have the same tzinfo member,
210.1900 - y.s = z.s by #2
210.1901 - x.n + z.s
210.1902 -
210.1903 -Plugging that back into [6] gives
210.1904 -
210.1905 - diff =
210.1906 - x.n - ((x.n + z.s) - z.o) = expanding
210.1907 - x.n - x.n - z.s + z.o = cancelling
210.1908 - - z.s + z.o = by #2
210.1909 - z.d
210.1910 -
210.1911 -So diff = z.d.
210.1912 -
210.1913 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
210.1914 -spelling we wanted in the endcase described above. We're done. Contrarily,
210.1915 -if z.d = 0, then we have a UTC equivalent, and are also done.
210.1916 -
210.1917 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
210.1918 -add to z (in effect, z is in tz's standard time, and we need to shift the
210.1919 -local clock into tz's daylight time).
210.1920 -
210.1921 -Let
210.1922 -
210.1923 - z' = z + z.d = z + diff [7]
210.1924 -
210.1925 -and we can again ask whether
210.1926 -
210.1927 - z'.n - z'.o = x.n [8]
210.1928 -
210.1929 -If so, we're done. If not, the tzinfo class is insane, according to the
210.1930 -assumptions we've made. This also requires a bit of proof. As before, let's
210.1931 -compute the difference between the LHS and RHS of [8] (and skipping some of
210.1932 -the justifications for the kinds of substitutions we've done several times
210.1933 -already):
210.1934 -
210.1935 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
210.1936 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
210.1937 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
210.1938 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
210.1939 - - z.n + z.n - z.o + z'.o = cancel z.n
210.1940 - - z.o + z'.o = #1 twice
210.1941 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
210.1942 - z'.d - z.d
210.1943 -
210.1944 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
210.1945 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
210.1946 -return z', not bothering to compute z'.d.
210.1947 -
210.1948 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
210.1949 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
210.1950 -would have to change the result dst() returns: we start in DST, and moving
210.1951 -a little further into it takes us out of DST.
210.1952 -
210.1953 -There isn't a sane case where this can happen. The closest it gets is at
210.1954 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
210.1955 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
210.1956 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
210.1957 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
210.1958 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
210.1959 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
210.1960 -standard time. Since that's what the local clock *does*, we want to map both
210.1961 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
210.1962 -in local time, but so it goes -- it's the way the local clock works.
210.1963 -
210.1964 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
210.1965 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
210.1966 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
210.1967 -(correctly) concludes that z' is not UTC-equivalent to x.
210.1968 -
210.1969 -Because we know z.d said z was in daylight time (else [5] would have held and
210.1970 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
210.1971 -and we we have stopped then), and there are only 2 possible values dst() can
210.1972 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
210.1973 -but the reasoning doesn't depend on the example -- it depends on there being
210.1974 -two possible dst() outcomes, one zero and the other non-zero). Therefore
210.1975 -z' must be in standard time, and is the spelling we want in this case.
210.1976 -
210.1977 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
210.1978 -concerned (because it takes z' as being in standard time rather than the
210.1979 -daylight time we intend here), but returning it gives the real-life "local
210.1980 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
210.1981 -tz.
210.1982 -
210.1983 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
210.1984 -the 1:MM standard time spelling we want.
210.1985 -
210.1986 -So how can this break? One of the assumptions must be violated. Two
210.1987 -possibilities:
210.1988 -
210.1989 -1) [2] effectively says that y.s is invariant across all y belong to a given
210.1990 - time zone. This isn't true if, for political reasons or continental drift,
210.1991 - a region decides to change its base offset from UTC.
210.1992 -
210.1993 -2) There may be versions of "double daylight" time where the tail end of
210.1994 - the analysis gives up a step too early. I haven't thought about that
210.1995 - enough to say.
210.1996 -
210.1997 -In any case, it's clear that the default fromutc() is strong enough to handle
210.1998 -"almost all" time zones: so long as the standard offset is invariant, it
210.1999 -doesn't matter if daylight time transition points change from year to year, or
210.2000 -if daylight time is skipped in some years; it doesn't matter how large or
210.2001 -small dst() may get within its bounds; and it doesn't even matter if some
210.2002 -perverse time zone returns a negative dst()). So a breaking case must be
210.2003 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
210.2004 -"""
210.2005 -
210.2006 -def _test():
210.2007 - import test_datetime
210.2008 - test_datetime.test_main()
210.2009 -
210.2010 -if __name__ == "__main__":
210.2011 - _test()
211.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.indexed Sun Jan 04 13:11:53 2015 -0600
211.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
211.3 @@ -1,392 +0,0 @@
211.4 -
211.5 -
211.6 -Document 0
211.7 -Searchable Keys:
211.8 - class : _date_class
211.9 - class-ig : _date_class
211.10 - extends : object
211.11 - in : datetime
211.12 - member : __add__;F;;self,other;
211.13 - member : __cmp;F;|PRIVATE|;self,other;
211.14 - member : __day;D;|PRIVATE|;
211.15 - member : __eq__;F;;self,other;
211.16 - member : __ge__;F;;self,other;
211.17 - member : __getstate;F;|PRIVATE|;self;
211.18 - member : __gt__;F;;self,other;
211.19 - member : __hash__;F;;self;
211.20 - member : __le__;F;;self,other;
211.21 - member : __lt__;F;;self,other;
211.22 - member : __month;D;|PRIVATE|;
211.23 - member : __ne__;F;;self,other;
211.24 - member : __new__;F;;cls,year,month,day;
211.25 - member : __radd__;F;;self,other;
211.26 - member : __reduce__;F;;self;
211.27 - member : __repr__;F;;self;
211.28 - member : __safe_for_unpickling__;D;;
211.29 - member : __setstate;F;|PRIVATE|;self,t;
211.30 - member : __str__;F;;self;
211.31 - member : __sub__;F;;self,other;
211.32 - member : __year;D;|PRIVATE|;
211.33 - member : _checkOverflow;F;|PRIVATE|;self,year;
211.34 - member : ctime;F;;self;
211.35 - member : day;D;;
211.36 - member : fromordinal;F;;cls,n;
211.37 - member : fromtimestamp;F;;cls,t;
211.38 - member : isocalendar;F;;self;
211.39 - member : isoformat;F;;self;
211.40 - member : isoweekday;F;;self;
211.41 - member : month;D;;
211.42 - member : replace;F;;self,year,month,day;
211.43 - member : strftime;F;;self,fmt;
211.44 - member : timetuple;F;;self;
211.45 - member : today;F;;cls;
211.46 - member : toordinal;F;;self;
211.47 - member : weekday;F;;self;
211.48 - member : year;D;;
211.49 -
211.50 -Not Searchable Keys:
211.51 - clzattrs : ;|PRIVATE|;
211.52 -
211.53 -
211.54 -Document 1
211.55 -Searchable Keys:
211.56 - class : _time_class
211.57 - class-ig : _time_class
211.58 - extends : object
211.59 - in : datetime
211.60 - member : __cmp;F;|PRIVATE|;self,other;
211.61 - member : __eq__;F;;self,other;
211.62 - member : __ge__;F;;self,other;
211.63 - member : __getstate;F;|PRIVATE|;self;
211.64 - member : __gt__;F;;self,other;
211.65 - member : __hash__;F;;self;
211.66 - member : __hour;D;|PRIVATE|;
211.67 - member : __le__;F;;self,other;
211.68 - member : __lt__;F;;self,other;
211.69 - member : __microsecond;D;|PRIVATE|;
211.70 - member : __minute;D;|PRIVATE|;
211.71 - member : __ne__;F;;self,other;
211.72 - member : __new__;F;;cls,hour,minute,second,microsecond,tzinfo;
211.73 - member : __nonzero__;F;;self;
211.74 - member : __reduce__;F;;self;
211.75 - member : __repr__;F;;self;
211.76 - member : __safe_for_unpickling__;D;;
211.77 - member : __second;D;|PRIVATE|;
211.78 - member : __setstate;F;|PRIVATE|;self,state;
211.79 - member : __str__;F;;self;
211.80 - member : _dst;F;|PRIVATE|;self;
211.81 - member : _tzinfo;D;|PRIVATE|;
211.82 - member : _tzstr;F;|PRIVATE|;self,sep;
211.83 - member : _utcoffset;F;|PRIVATE|;self;
211.84 - member : dst;F;;self;
211.85 - member : hour;D;;
211.86 - member : isoformat;F;;self;
211.87 - member : microsecond;D;;
211.88 - member : minute;D;;
211.89 - member : replace;F;;self,hour,minute,second,microsecond,tzinfo;
211.90 - member : second;D;;
211.91 - member : strftime;F;;self,fmt;
211.92 - member : tzinfo;D;;
211.93 - member : tzname;F;;self;
211.94 - member : utcoffset;F;;self;
211.95 -
211.96 -Not Searchable Keys:
211.97 - clzattrs : ;|PRIVATE|;
211.98 -
211.99 -
211.100 -Document 2
211.101 -Searchable Keys:
211.102 - class : _tzinfo_class
211.103 - class-ig : _tzinfo_class
211.104 - extends : object
211.105 - in : datetime
211.106 - member : __reduce__;F;;self;
211.107 - member : __safe_for_unpickling__;D;;
211.108 - member : dst;F;;self,dt;
211.109 - member : fromutc;F;;self,dt;
211.110 - member : tzname;F;;self,dt;
211.111 - member : utcoffset;F;;self,dt;
211.112 -
211.113 -Not Searchable Keys:
211.114 - clzattrs : ;|PRIVATE|;
211.115 -
211.116 -
211.117 -Document 3
211.118 -Searchable Keys:
211.119 - class : date
211.120 - class-ig : date
211.121 - extends : object
211.122 - in : datetime
211.123 - member : __add__;F;;self,other;
211.124 - member : __cmp;F;|PRIVATE|;self,other;
211.125 - member : __day;D;|PRIVATE|;
211.126 - member : __eq__;F;;self,other;
211.127 - member : __ge__;F;;self,other;
211.128 - member : __getstate;F;|PRIVATE|;self;
211.129 - member : __gt__;F;;self,other;
211.130 - member : __hash__;F;;self;
211.131 - member : __le__;F;;self,other;
211.132 - member : __lt__;F;;self,other;
211.133 - member : __month;D;|PRIVATE|;
211.134 - member : __ne__;F;;self,other;
211.135 - member : __new__;F;;cls,year,month,day;
211.136 - member : __radd__;F;;self,other;
211.137 - member : __reduce__;F;;self;
211.138 - member : __repr__;F;;self;
211.139 - member : __safe_for_unpickling__;D;;
211.140 - member : __setstate;F;|PRIVATE|;self,t;
211.141 - member : __str__;F;;self;
211.142 - member : __sub__;F;;self,other;
211.143 - member : __year;D;|PRIVATE|;
211.144 - member : _checkOverflow;F;|PRIVATE|;self,year;
211.145 - member : ctime;F;;self;
211.146 - member : day;D;;
211.147 - member : fromordinal;F;;cls,n;
211.148 - member : fromtimestamp;F;;cls,t;
211.149 - member : isocalendar;F;;self;
211.150 - member : isoformat;F;;self;
211.151 - member : isoweekday;F;;self;
211.152 - member : month;D;;
211.153 - member : replace;F;;self,year,month,day;
211.154 - member : strftime;F;;self,fmt;
211.155 - member : timetuple;F;;self;
211.156 - member : today;F;;cls;
211.157 - member : toordinal;F;;self;
211.158 - member : weekday;F;;self;
211.159 - member : year;D;;
211.160 -
211.161 -Not Searchable Keys:
211.162 -
211.163 -
211.164 -Document 4
211.165 -Searchable Keys:
211.166 - class : datetime
211.167 - class-ig : datetime
211.168 - extends : date
211.169 - in : datetime
211.170 - member : __add__;F;;self,other;
211.171 - member : __cmp;F;|PRIVATE|;self,other;
211.172 - member : __day;D;|PRIVATE|;
211.173 - member : __eq__;F;;self,other;
211.174 - member : __ge__;F;;self,other;
211.175 - member : __getstate;F;|PRIVATE|;self;
211.176 - member : __gt__;F;;self,other;
211.177 - member : __hash__;F;;self;
211.178 - member : __hour;D;|PRIVATE|;
211.179 - member : __le__;F;;self,other;
211.180 - member : __lt__;F;;self,other;
211.181 - member : __microsecond;D;|PRIVATE|;
211.182 - member : __minute;D;|PRIVATE|;
211.183 - member : __month;D;|PRIVATE|;
211.184 - member : __ne__;F;;self,other;
211.185 - member : __new__;F;;cls,year,month,day,hour,minute,second,microsecond,tzinfo;
211.186 - member : __radd__;F;;self,other;
211.187 - member : __reduce__;F;;self;
211.188 - member : __repr__;F;;self;
211.189 - member : __safe_for_unpickling__;D;;
211.190 - member : __second;D;|PRIVATE|;
211.191 - member : __setstate;F;|PRIVATE|;self,state;
211.192 - member : __str__;F;;self;
211.193 - member : __sub__;F;;self,other;
211.194 - member : __year;D;|PRIVATE|;
211.195 - member : _dst;F;|PRIVATE|;self;
211.196 - member : _tzinfo;D;|PRIVATE|;
211.197 - member : _utcoffset;F;|PRIVATE|;self;
211.198 - member : astimezone;F;;self,tz;
211.199 - member : combine;F;;cls,date,time;
211.200 - member : ctime;F;;self;
211.201 - member : date;F;;self;
211.202 - member : dst;F;;self;
211.203 - member : fromtimestamp;F;;cls,t,tz;
211.204 - member : hour;D;;
211.205 - member : isoformat;F;;self,sep;
211.206 - member : microsecond;D;;
211.207 - member : minute;D;;
211.208 - member : now;F;;cls,tz;
211.209 - member : replace;F;;self,year,month,day,hour,minute,second,microsecond,tzinfo;
211.210 - member : second;D;;
211.211 - member : time;F;;self;
211.212 - member : timetuple;F;;self;
211.213 - member : timetz;F;;self;
211.214 - member : tzinfo;D;;
211.215 - member : tzname;F;;self;
211.216 - member : utcfromtimestamp;F;;cls,t;
211.217 - member : utcnow;F;;cls;
211.218 - member : utcoffset;F;;self;
211.219 - member : utctimetuple;F;;self;
211.220 -
211.221 -Not Searchable Keys:
211.222 -
211.223 -
211.224 -Document 5
211.225 -Searchable Keys:
211.226 - class : time
211.227 - class-ig : time
211.228 - extends : object
211.229 - in : datetime
211.230 - member : __cmp;F;|PRIVATE|;self,other;
211.231 - member : __eq__;F;;self,other;
211.232 - member : __ge__;F;;self,other;
211.233 - member : __getstate;F;|PRIVATE|;self;
211.234 - member : __gt__;F;;self,other;
211.235 - member : __hash__;F;;self;
211.236 - member : __hour;D;|PRIVATE|;
211.237 - member : __le__;F;;self,other;
211.238 - member : __lt__;F;;self,other;
211.239 - member : __microsecond;D;|PRIVATE|;
211.240 - member : __minute;D;|PRIVATE|;
211.241 - member : __ne__;F;;self,other;
211.242 - member : __new__;F;;cls,hour,minute,second,microsecond,tzinfo;
211.243 - member : __nonzero__;F;;self;
211.244 - member : __reduce__;F;;self;
211.245 - member : __repr__;F;;self;
211.246 - member : __safe_for_unpickling__;D;;
211.247 - member : __second;D;|PRIVATE|;
211.248 - member : __setstate;F;|PRIVATE|;self,state;
211.249 - member : __str__;F;;self;
211.250 - member : _dst;F;|PRIVATE|;self;
211.251 - member : _tzinfo;D;|PRIVATE|;
211.252 - member : _tzstr;F;|PRIVATE|;self,sep;
211.253 - member : _utcoffset;F;|PRIVATE|;self;
211.254 - member : dst;F;;self;
211.255 - member : hour;D;;
211.256 - member : isoformat;F;;self;
211.257 - member : microsecond;D;;
211.258 - member : minute;D;;
211.259 - member : replace;F;;self,hour,minute,second,microsecond,tzinfo;
211.260 - member : second;D;;
211.261 - member : strftime;F;;self,fmt;
211.262 - member : tzinfo;D;;
211.263 - member : tzname;F;;self;
211.264 - member : utcoffset;F;;self;
211.265 -
211.266 -Not Searchable Keys:
211.267 -
211.268 -
211.269 -Document 6
211.270 -Searchable Keys:
211.271 - class : timedelta
211.272 - class-ig : timedelta
211.273 - extends : object
211.274 - in : datetime
211.275 - member : __abs__;F;;self;
211.276 - member : __add__;F;;self,other;
211.277 - member : __cmp;F;|PRIVATE|;self,other;
211.278 - member : __days;D;|PRIVATE|;
211.279 - member : __div__;F;;self,other;
211.280 - member : __eq__;F;;self,other;
211.281 - member : __floordiv__;F;;self,other;
211.282 - member : __ge__;F;;self,other;
211.283 - member : __getstate;F;|PRIVATE|;self;
211.284 - member : __gt__;F;;self,other;
211.285 - member : __hash__;F;;self;
211.286 - member : __le__;F;;self,other;
211.287 - member : __lt__;F;;self,other;
211.288 - member : __microseconds;D;|PRIVATE|;
211.289 - member : __mul__;F;;self,other;
211.290 - member : __ne__;F;;self,other;
211.291 - member : __neg__;F;;self;
211.292 - member : __new__;F;;cls,days,seconds,microseconds,milliseconds,minutes,hours,weeks;
211.293 - member : __nonzero__;F;;self;
211.294 - member : __pos__;F;;self;
211.295 - member : __radd__;F;;self,other;
211.296 - member : __reduce__;F;;self;
211.297 - member : __repr__;F;;self;
211.298 - member : __rmul__;F;;self,other;
211.299 - member : __rsub__;F;;self,other;
211.300 - member : __safe_for_unpickling__;D;;
211.301 - member : __seconds;D;|PRIVATE|;
211.302 - member : __str__;F;;self;
211.303 - member : __sub__;F;;self,other;
211.304 - member : days;D;;
211.305 - member : microseconds;D;;
211.306 - member : seconds;D;;
211.307 -
211.308 -Not Searchable Keys:
211.309 -
211.310 -
211.311 -Document 7
211.312 -Searchable Keys:
211.313 - class : tmxxx
211.314 - class-ig : tmxxx
211.315 - in : datetime
211.316 - member : __init__;c;|CONSTRUCTOR|;self,year,month,day,hour,minute,second,microsecond;
211.317 - member : ctime;F;;self;
211.318 - member : day;D;;
211.319 - member : hour;D;;
211.320 - member : microsecond;D;;
211.321 - member : minute;D;;
211.322 - member : month;D;;
211.323 - member : ordinal;D;;
211.324 - member : ordinal;D;;
211.325 - member : second;D;;
211.326 - member : time;F;;self;
211.327 - member : toordinal;F;;self;
211.328 - member : year;D;;
211.329 -
211.330 -Not Searchable Keys:
211.331 -
211.332 -
211.333 -Document 8
211.334 -Searchable Keys:
211.335 - class : tzinfo
211.336 - class-ig : tzinfo
211.337 - extends : object
211.338 - in : datetime
211.339 - member : __reduce__;F;;self;
211.340 - member : __safe_for_unpickling__;D;;
211.341 - member : dst;F;;self,dt;
211.342 - member : fromutc;F;;self,dt;
211.343 - member : tzname;F;;self,dt;
211.344 - member : utcoffset;F;;self,dt;
211.345 -
211.346 -Not Searchable Keys:
211.347 -
211.348 -
211.349 -Document 9
211.350 -Searchable Keys:
211.351 - item : MAXYEAR;D;;
211.352 - item : MINYEAR;D;;
211.353 - item : _DAYNAMES;D;|PRIVATE|;
211.354 - item : _DAYS_BEFORE_MONTH;D;|PRIVATE|;
211.355 - item : _DAYS_IN_MONTH;D;|PRIVATE|;
211.356 - item : _DI100Y;D;|PRIVATE|;
211.357 - item : _DI400Y;D;|PRIVATE|;
211.358 - item : _DI4Y;D;|PRIVATE|;
211.359 - item : _MONTHNAMES;D;|PRIVATE|;
211.360 - item : _ORD1970;D;|PRIVATE|;
211.361 - item : _build_struct_time;F;|PRIVATE|;y,m,d,hh,mm,ss,dstflag;
211.362 - item : _call_tzinfo_method;F;|PRIVATE|;tzinfo,methname,tzinfoarg;
211.363 - item : _check_date_fields;F;|PRIVATE|;year,month,day;
211.364 - item : _check_time_fields;F;|PRIVATE|;hour,minute,second,microsecond;
211.365 - item : _check_tzinfo_arg;F;|PRIVATE|;tz;
211.366 - item : _check_tzname;F;|PRIVATE|;name;
211.367 - item : _check_utc_offset;F;|PRIVATE|;name,offset;
211.368 - item : _cmperror;F;|PRIVATE|;x,y;
211.369 - item : _date_class;C;|PRIVATE|;
211.370 - item : _days_before_month;F;|PRIVATE|;year,month;
211.371 - item : _days_before_year;F;|PRIVATE|;year;
211.372 - item : _days_in_month;F;|PRIVATE|;year,month;
211.373 - item : _days_in_year;F;|PRIVATE|;year;
211.374 - item : _format_time;F;|PRIVATE|;hh,mm,ss,us;
211.375 - item : _is_leap;F;|PRIVATE|;year;
211.376 - item : _isoweek1monday;F;|PRIVATE|;year;
211.377 - item : _math;I;|PRIVATE|;
211.378 - item : _ord2ymd;F;|PRIVATE|;n;
211.379 - item : _test;F;|PRIVATE|;;
211.380 - item : _time;I;|PRIVATE|;
211.381 - item : _time_class;C;|PRIVATE|;
211.382 - item : _tzinfo_class;C;|PRIVATE|;
211.383 - item : _wrap_strftime;F;|PRIVATE|;object,format,timetuple;
211.384 - item : _ymd2ord;F;|PRIVATE|;year,month,day;
211.385 - item : date;C;;
211.386 - item : datetime;C;;
211.387 - item : dbm;D;;
211.388 - item : dim;D;;
211.389 - item : time;C;;
211.390 - item : timedelta;C;;
211.391 - item : tmxxx;C;;
211.392 - item : tzinfo;C;;
211.393 - module : datetime
211.394 -
211.395 -Not Searchable Keys:
212.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.nameoffsets Sun Jan 04 13:11:53 2015 -0600
212.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
212.3 @@ -1,2009 +0,0 @@
212.4 -
212.5 -"""Concrete date/time and related types -- prototype implemented in Python.
212.6 -
212.7 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
212.8 -
212.9 -See also http://dir.yahoo.com/Reference/calendars/
212.10 -
212.11 -For a primer on DST, including many current DST rules, see
212.12 -http://webexhibits.org/daylightsaving/
212.13 -
212.14 -For more about DST than you ever wanted to know, see
212.15 -ftp://elsie.nci.nih.gov/pub/
212.16 -
212.17 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
212.18 -
212.19 -"""
212.20 -
212.21 -import time as _time
212.22 -import math as _math
212.23 -
212.24 -<Name>MINYEAR</Name> = 1
212.25 -<Name>MAXYEAR</Name> = 9999
212.26 -
212.27 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
212.28 -# also assumes the current Gregorian calendar indefinitely extended in
212.29 -# both directions. Difference: Dates.py calls January 1 of year 0 day
212.30 -# number 1. The code here calls January 1 of year 1 day number 1. This is
212.31 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
212.32 -# and Reingold's "Calendrical Calculations", where it's the base calendar
212.33 -# for all computations. See the book for algorithms for converting between
212.34 -# proleptic Gregorian ordinals and many other calendar systems.
212.35 -
212.36 -<Name>_DAYS_IN_MONTH</Name> = [<Name>None</Name>, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
212.37 -
212.38 -<Name>_DAYS_BEFORE_MONTH</Name> = [<Name>None</Name>]
212.39 -<Name>dbm</Name> = 0
212.40 -for <Name>dim</Name> in <Name>_DAYS_IN_MONTH</Name>[1:]:
212.41 - <Attribute><Name>_DAYS_BEFORE_MONTH</Name></Attribute>.<Call>append</Call>(<Name>dbm</Name>)
212.42 - <Name>dbm</Name> += <Name>dim</Name>
212.43 -del <Name>dbm</Name>, <Name>dim</Name>
212.44 -
212.45 -def <FunctionDef>_is_leap</FunctionDef>(<Name>year</Name>):
212.46 - "year -> 1 if leap year, else 0."
212.47 - return <Name>year</Name> % 4 == 0 and (<Name>year</Name> % 100 != 0 or <Name>year</Name> % 400 == 0)
212.48 -
212.49 -def <FunctionDef>_days_in_year</FunctionDef>(<Name>year</Name>):
212.50 - "year -> number of days in year (366 if a leap year, else 365)."
212.51 - return 365 + <Call><Name>_is_leap</Name></Call>(<Name>year</Name>)
212.52 -
212.53 -def <FunctionDef>_days_before_year</FunctionDef>(<Name>year</Name>):
212.54 - "year -> number of days before January 1st of year."
212.55 - <Name>y</Name> = <Name>year</Name> - 1
212.56 - return <Name>y</Name>*365 + <Name>y</Name>//4 - <Name>y</Name>//100 + <Name>y</Name>//400
212.57 -
212.58 -def <FunctionDef>_days_in_month</FunctionDef>(<Name>year</Name>, <Name>month</Name>):
212.59 - "year, month -> number of days in that month in that year."
212.60 - assert 1 <= <Name>month</Name> <= 12, <Name>month</Name>
212.61 - if <Name>month</Name> == 2 and <Call><Name>_is_leap</Name></Call>(<Name>year</Name>):
212.62 - return 29
212.63 - return <Name>_DAYS_IN_MONTH</Name>[<Name>month</Name>]
212.64 -
212.65 -def <FunctionDef>_days_before_month</FunctionDef>(<Name>year</Name>, <Name>month</Name>):
212.66 - "year, month -> number of days in year preceeding first day of month."
212.67 - if not 1 <= <Name>month</Name> <= 12:
212.68 - raise <Call><Name>ValueError</Name></Call>('month must be in 1..12', <Name>month</Name>)
212.69 - return <Name>_DAYS_BEFORE_MONTH</Name>[<Name>month</Name>] + (<Name>month</Name> > 2 and <Call><Name>_is_leap</Name></Call>(<Name>year</Name>))
212.70 -
212.71 -def <FunctionDef>_ymd2ord</FunctionDef>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>):
212.72 - "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
212.73 - if not 1 <= <Name>month</Name> <= 12:
212.74 - raise <Call><Name>ValueError</Name></Call>('month must be in 1..12', <Name>month</Name>)
212.75 - <Name>dim</Name> = <Call><Name>_days_in_month</Name></Call>(<Name>year</Name>, <Name>month</Name>)
212.76 - if not 1 <= <Name>day</Name> <= <Name>dim</Name>:
212.77 - raise <Call><Name>ValueError</Name></Call>('day must be in 1..%d' % <Name>dim</Name>, <Name>day</Name>)
212.78 - return (<Call><Name>_days_before_year</Name></Call>(<Name>year</Name>) +
212.79 - <Call><Name>_days_before_month</Name></Call>(<Name>year</Name>, <Name>month</Name>) +
212.80 - <Name>day</Name>)
212.81 -
212.82 -<Name>_DI400Y</Name> = <Call><Name>_days_before_year</Name></Call>(401) # number of days in 400 years
212.83 -<Name>_DI100Y</Name> = <Call><Name>_days_before_year</Name></Call>(101) # " " " " 100 "
212.84 -<Name>_DI4Y</Name> = <Call><Name>_days_before_year</Name></Call>(5) # " " " " 4 "
212.85 -
212.86 -# A 4-year cycle has an extra leap day over what we'd get from pasting
212.87 -# together 4 single years.
212.88 -assert <Name>_DI4Y</Name> == 4 * 365 + 1
212.89 -
212.90 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
212.91 -# pasting together 4 100-year cycles.
212.92 -assert <Name>_DI400Y</Name> == 4 * <Name>_DI100Y</Name> + 1
212.93 -
212.94 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
212.95 -# pasting together 25 4-year cycles.
212.96 -assert <Name>_DI100Y</Name> == 25 * <Name>_DI4Y</Name> - 1
212.97 -
212.98 -def <FunctionDef>_ord2ymd</FunctionDef>(<Name>n</Name>):
212.99 - "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
212.100 -
212.101 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
212.102 - # repeats exactly every 400 years. The basic strategy is to find the
212.103 - # closest 400-year boundary at or before n, then work with the offset
212.104 - # from that boundary to n. Life is much clearer if we subtract 1 from
212.105 - # n first -- then the values of n at 400-year boundaries are exactly
212.106 - # those divisible by _DI400Y:
212.107 - #
212.108 - # D M Y n n-1
212.109 - # -- --- ---- ---------- ----------------
212.110 - # 31 Dec -400 -_DI400Y -_DI400Y -1
212.111 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
212.112 - # ...
212.113 - # 30 Dec 000 -1 -2
212.114 - # 31 Dec 000 0 -1
212.115 - # 1 Jan 001 1 0 400-year boundary
212.116 - # 2 Jan 001 2 1
212.117 - # 3 Jan 001 3 2
212.118 - # ...
212.119 - # 31 Dec 400 _DI400Y _DI400Y -1
212.120 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
212.121 - <Name>n</Name> -= 1
212.122 - <Name>n400</Name>, <Name>n</Name> = <Call><Name>divmod</Name></Call>(<Name>n</Name>, <Name>_DI400Y</Name>)
212.123 - <Name>year</Name> = <Name>n400</Name> * 400 + 1 # ..., -399, 1, 401, ...
212.124 -
212.125 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
212.126 - # the desired date. Now compute how many 100-year cycles precede n.
212.127 - # Note that it's possible for n100 to equal 4! In that case 4 full
212.128 - # 100-year cycles precede the desired day, which implies the desired
212.129 - # day is December 31 at the end of a 400-year cycle.
212.130 - <Name>n100</Name>, <Name>n</Name> = <Call><Name>divmod</Name></Call>(<Name>n</Name>, <Name>_DI100Y</Name>)
212.131 -
212.132 - # Now compute how many 4-year cycles precede it.
212.133 - <Name>n4</Name>, <Name>n</Name> = <Call><Name>divmod</Name></Call>(<Name>n</Name>, <Name>_DI4Y</Name>)
212.134 -
212.135 - # And now how many single years. Again n1 can be 4, and again meaning
212.136 - # that the desired day is December 31 at the end of the 4-year cycle.
212.137 - <Name>n1</Name>, <Name>n</Name> = <Call><Name>divmod</Name></Call>(<Name>n</Name>, 365)
212.138 -
212.139 - <Name>year</Name> += <Name>n100</Name> * 100 + <Name>n4</Name> * 4 + <Name>n1</Name>
212.140 - if <Name>n1</Name> == 4 or <Name>n100</Name> == 4:
212.141 - assert <Name>n</Name> == 0
212.142 - return <Name>year</Name>-1, 12, 31
212.143 -
212.144 - # Now the year is correct, and n is the offset from January 1. We find
212.145 - # the month via an estimate that's either exact or one too large.
212.146 - <Name>leapyear</Name> = <Name>n1</Name> == 3 and (<Name>n4</Name> != 24 or <Name>n100</Name> == 3)
212.147 - assert <Name>leapyear</Name> == <Call><Name>_is_leap</Name></Call>(<Name>year</Name>)
212.148 - <Name>month</Name> = (<Name>n</Name> + 50) >> 5
212.149 - <Name>preceding</Name> = <Name>_DAYS_BEFORE_MONTH</Name>[<Name>month</Name>] + (<Name>month</Name> > 2 and <Name>leapyear</Name>)
212.150 - if <Name>preceding</Name> > <Name>n</Name>: # estimate is too large
212.151 - <Name>month</Name> -= 1
212.152 - <Name>preceding</Name> -= <Name>_DAYS_IN_MONTH</Name>[<Name>month</Name>] + (<Name>month</Name> == 2 and <Name>leapyear</Name>)
212.153 - <Name>n</Name> -= <Name>preceding</Name>
212.154 - assert 0 <= <Name>n</Name> < <Call><Name>_days_in_month</Name></Call>(<Name>year</Name>, <Name>month</Name>)
212.155 -
212.156 - # Now the year and month are correct, and n is the offset from the
212.157 - # start of that month: we're done!
212.158 - return <Name>year</Name>, <Name>month</Name>, <Name>n</Name>+1
212.159 -
212.160 -# Month and day names. For localized versions, see the calendar module.
212.161 -<Name>_MONTHNAMES</Name> = [<Name>None</Name>, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
212.162 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
212.163 -<Name>_DAYNAMES</Name> = [<Name>None</Name>, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
212.164 -
212.165 -
212.166 -def <FunctionDef>_build_struct_time</FunctionDef>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>, <Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Name>dstflag</Name>):
212.167 - <Name>wday</Name> = (<Call><Name>_ymd2ord</Name></Call>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>) + 6) % 7
212.168 - <Name>dnum</Name> = <Call><Name>_days_before_month</Name></Call>(<Name>y</Name>, <Name>m</Name>) + <Name>d</Name>
212.169 - return <Attribute><Name>_time</Name></Attribute>.<Call>struct_time</Call>((<Name>y</Name>, <Name>m</Name>, <Name>d</Name>, <Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Name>wday</Name>, <Name>dnum</Name>, <Name>dstflag</Name>))
212.170 -
212.171 -def <FunctionDef>_format_time</FunctionDef>(<Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Name>us</Name>):
212.172 - # Skip trailing microseconds when us==0.
212.173 - <Name>result</Name> = "%02d:%02d:%02d" % (<Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>)
212.174 - if <Name>us</Name>:
212.175 - <Name>result</Name> += ".%06d" % <Name>us</Name>
212.176 - return <Name>result</Name>
212.177 -
212.178 -# Correctly substitute for %z and %Z escapes in strftime formats.
212.179 -def <FunctionDef>_wrap_strftime</FunctionDef>(<Name>object</Name>, <Name>format</Name>, <Name>timetuple</Name>):
212.180 - <Name>year</Name> = <Name>timetuple</Name>[0]
212.181 - if <Name>year</Name> < 1900:
212.182 - raise <Call><Name>ValueError</Name></Call>("year=%d is before 1900; the datetime strftime() "
212.183 - "methods require year >= 1900" % <Name>year</Name>)
212.184 - # Don't call _utcoffset() or tzname() unless actually needed.
212.185 - <Name>zreplace</Name> = <Name>None</Name> # the string to use for %z
212.186 - <Name>Zreplace</Name> = <Name>None</Name> # the string to use for %Z
212.187 -
212.188 - # Scan format for %z and %Z escapes, replacing as needed.
212.189 - <Name>newformat</Name> = []
212.190 - <Name>push</Name> = <Attribute><Name>newformat</Name></Attribute>.append
212.191 - <Name>i</Name>, <Name>n</Name> = 0, <Call><Name>len</Name></Call>(<Name>format</Name>)
212.192 - while <Name>i</Name> < <Name>n</Name>:
212.193 - <Name>ch</Name> = <Name>format</Name>[<Name>i</Name>]
212.194 - <Name>i</Name> += 1
212.195 - if <Name>ch</Name> == '%':
212.196 - if <Name>i</Name> < <Name>n</Name>:
212.197 - <Name>ch</Name> = <Name>format</Name>[<Name>i</Name>]
212.198 - <Name>i</Name> += 1
212.199 - if <Name>ch</Name> == 'z':
212.200 - if <Name>zreplace</Name> is <Name>None</Name>:
212.201 - <Name>zreplace</Name> = ""
212.202 - if <Call><Name>hasattr</Name></Call>(<Name>object</Name>, "_utcoffset"):
212.203 - <Name>offset</Name> = <Attribute><Name>object</Name></Attribute>.<Call>_utcoffset</Call>()
212.204 - if <Name>offset</Name> is not <Name>None</Name>:
212.205 - <Name>sign</Name> = '+'
212.206 - if <Name>offset</Name> < 0:
212.207 - <Name>offset</Name> = -<Name>offset</Name>
212.208 - <Name>sign</Name> = '-'
212.209 - <Name>h</Name>, <Name>m</Name> = <Call><Name>divmod</Name></Call>(<Name>offset</Name>, 60)
212.210 - <Name>zreplace</Name> = '%c%02d%02d' % (<Name>sign</Name>, <Name>h</Name>, <Name>m</Name>)
212.211 - assert '%' not in <Name>zreplace</Name>
212.212 - <Attribute><Name>newformat</Name></Attribute>.<Call>append</Call>(<Name>zreplace</Name>)
212.213 - elif <Name>ch</Name> == 'Z':
212.214 - if <Name>Zreplace</Name> is <Name>None</Name>:
212.215 - <Name>Zreplace</Name> = ""
212.216 - if <Call><Name>hasattr</Name></Call>(<Name>object</Name>, "tzname"):
212.217 - <Name>s</Name> = <Attribute><Name>object</Name></Attribute>.<Call>tzname</Call>()
212.218 - if <Name>s</Name> is not <Name>None</Name>:
212.219 - # strftime is going to have at this: escape %
212.220 - <Name>Zreplace</Name> = <Attribute><Name>s</Name></Attribute>.<Call>replace</Call>('%', '%%')
212.221 - <Attribute><Name>newformat</Name></Attribute>.<Call>append</Call>(<Name>Zreplace</Name>)
212.222 - else:
212.223 - <Call><Name>push</Name></Call>('%')
212.224 - <Call><Name>push</Name></Call>(<Name>ch</Name>)
212.225 - else:
212.226 - <Call><Name>push</Name></Call>('%')
212.227 - else:
212.228 - <Call><Name>push</Name></Call>(<Name>ch</Name>)
212.229 - <Name>newformat</Name> = <Attribute>""</Attribute>.<Call>join</Call>(<Name>newformat</Name>)
212.230 - return <Attribute><Name>_time</Name></Attribute>.<Call>strftime</Call>(<Name>newformat</Name>, <Name>timetuple</Name>)
212.231 -
212.232 -def <FunctionDef>_call_tzinfo_method</FunctionDef>(<Name>tzinfo</Name>, <Name>methname</Name>, <Name>tzinfoarg</Name>):
212.233 - if <Name>tzinfo</Name> is <Name>None</Name>:
212.234 - return <Name>None</Name>
212.235 - return <Call><Call><Name>getattr</Name></Call></Call>(<Name>tzinfo</Name>, <Name>methname</Name>)(<Name>tzinfoarg</Name>)
212.236 -
212.237 -# Just raise TypeError if the arg isn't None or a string.
212.238 -def <FunctionDef>_check_tzname</FunctionDef>(<Name>name</Name>):
212.239 - if <Name>name</Name> is not <Name>None</Name> and not <Call><Name>isinstance</Name></Call>(<Name>name</Name>, <Name>str</Name>):
212.240 - raise <Call><Name>TypeError</Name></Call>("tzinfo.tzname() must return None or string, "
212.241 - "not '%s'" % <Call><Name>type</Name></Call>(<Name>name</Name>))
212.242 -
212.243 -# name is the offset-producing method, "utcoffset" or "dst".
212.244 -# offset is what it returned.
212.245 -# If offset isn't None or timedelta, raises TypeError.
212.246 -# If offset is None, returns None.
212.247 -# Else offset is checked for being in range, and a whole # of minutes.
212.248 -# If it is, its integer value is returned. Else ValueError is raised.
212.249 -def <FunctionDef>_check_utc_offset</FunctionDef>(<Name>name</Name>, <Name>offset</Name>):
212.250 - assert <Name>name</Name> in ("utcoffset", "dst")
212.251 - if <Name>offset</Name> is <Name>None</Name>:
212.252 - return <Name>None</Name>
212.253 - if not <Call><Name>isinstance</Name></Call>(<Name>offset</Name>, <Name>timedelta</Name>):
212.254 - raise <Call><Name>TypeError</Name></Call>("tzinfo.%s() must return None "
212.255 - "or timedelta, not '%s'" % (<Name>name</Name>, <Call><Name>type</Name></Call>(<Name>offset</Name>)))
212.256 - <Name>days</Name> = <Attribute><Name>offset</Name></Attribute>.days
212.257 - if <Name>days</Name> < -1 or <Name>days</Name> > 0:
212.258 - <Name>offset</Name> = 1440 # trigger out-of-range
212.259 - else:
212.260 - <Name>seconds</Name> = <Name>days</Name> * 86400 + <Attribute><Name>offset</Name></Attribute>.seconds
212.261 - <Name>minutes</Name>, <Name>seconds</Name> = <Call><Name>divmod</Name></Call>(<Name>seconds</Name>, 60)
212.262 - if <Name>seconds</Name> or <Attribute><Name>offset</Name></Attribute>.microseconds:
212.263 - raise <Call><Name>ValueError</Name></Call>("tzinfo.%s() must return a whole number "
212.264 - "of minutes" % <Name>name</Name>)
212.265 - <Name>offset</Name> = <Name>minutes</Name>
212.266 - if -1440 < <Name>offset</Name> < 1440:
212.267 - return <Name>offset</Name>
212.268 - raise <Call><Name>ValueError</Name></Call>("%s()=%d, must be in -1439..1439" % (<Name>name</Name>, <Name>offset</Name>))
212.269 -
212.270 -def <FunctionDef>_check_date_fields</FunctionDef>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>):
212.271 - if not <Name>MINYEAR</Name> <= <Name>year</Name> <= <Name>MAXYEAR</Name>:
212.272 - raise <Call><Name>ValueError</Name></Call>('year must be in %d..%d' % (<Name>MINYEAR</Name>, <Name>MAXYEAR</Name>), <Name>year</Name>)
212.273 - if not 1 <= <Name>month</Name> <= 12:
212.274 - raise <Call><Name>ValueError</Name></Call>('month must be in 1..12', <Name>month</Name>)
212.275 - <Name>dim</Name> = <Call><Name>_days_in_month</Name></Call>(<Name>year</Name>, <Name>month</Name>)
212.276 - if not 1 <= <Name>day</Name> <= <Name>dim</Name>:
212.277 - raise <Call><Name>ValueError</Name></Call>('day must be in 1..%d' % <Name>dim</Name>, <Name>day</Name>)
212.278 -
212.279 -def <FunctionDef>_check_time_fields</FunctionDef>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>):
212.280 - if not 0 <= <Name>hour</Name> <= 23:
212.281 - raise <Call><Name>ValueError</Name></Call>('hour must be in 0..23', <Name>hour</Name>)
212.282 - if not 0 <= <Name>minute</Name> <= 59:
212.283 - raise <Call><Name>ValueError</Name></Call>('minute must be in 0..59', <Name>minute</Name>)
212.284 - if not 0 <= <Name>second</Name> <= 59:
212.285 - raise <Call><Name>ValueError</Name></Call>('second must be in 0..59', <Name>second</Name>)
212.286 - if not 0 <= <Name>microsecond</Name> <= 999999:
212.287 - raise <Call><Name>ValueError</Name></Call>('microsecond must be in 0..999999', <Name>microsecond</Name>)
212.288 -
212.289 -def <FunctionDef>_check_tzinfo_arg</FunctionDef>(<Name>tz</Name>):
212.290 - if <Name>tz</Name> is not <Name>None</Name> and not <Call><Name>isinstance</Name></Call>(<Name>tz</Name>, <Name>tzinfo</Name>):
212.291 - raise <Call><Name>TypeError</Name></Call>("tzinfo argument must be None or of a tzinfo subclass")
212.292 -
212.293 -
212.294 -# Notes on comparison: In general, datetime module comparison operators raise
212.295 -# TypeError when they don't know how to do a comparison themself. If they
212.296 -# returned NotImplemented instead, comparison could (silently) fall back to
212.297 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
212.298 -# and that's not helpful. There are two exceptions:
212.299 -#
212.300 -# 1. For date and datetime, if the other object has a "timetuple" attr,
212.301 -# NotImplemented is returned. This is a hook to allow other kinds of
212.302 -# datetime-like objects a chance to intercept the comparison.
212.303 -#
212.304 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
212.305 -# so opertaions like
212.306 -#
212.307 -# x == y
212.308 -# x != y
212.309 -# x in sequence
212.310 -# x not in sequence
212.311 -# dict[x] = y
212.312 -#
212.313 -# don't raise annoying TypeErrors just because a datetime object
212.314 -# is part of a heterogeneous collection. If there's no known way to
212.315 -# compare X to a datetime, saying they're not equal is reasonable.
212.316 -
212.317 -def <FunctionDef>_cmperror</FunctionDef>(<Name>x</Name>, <Name>y</Name>):
212.318 - raise <Call><Name>TypeError</Name></Call>("can't compare '%s' to '%s'" % (
212.319 - <Attribute><Call><Name>type</Name></Call></Attribute>(<Name>x</Name>).__name__, <Attribute><Call><Name>type</Name></Call></Attribute>(<Name>y</Name>).__name__))
212.320 -
212.321 -# This is a start at a struct tm workalike. Goals:
212.322 -#
212.323 -# + Works the same way across platforms.
212.324 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
212.325 -#
212.326 -# Note: I suspect it's best if this flavor of tm does *not* try to
212.327 -# second-guess timezones or DST. Instead fold whatever adjustments you want
212.328 -# into the minutes argument (and the constructor will normalize).
212.329 -
212.330 -<Name>_ORD1970</Name> = <Call><Name>_ymd2ord</Name></Call>(1970, 1, 1) # base ordinal for UNIX epoch
212.331 -
212.332 -class <ClassDef>tmxxx</ClassDef>:
212.333 -
212.334 - <Name>ordinal</Name> = <Name>None</Name>
212.335 -
212.336 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>year</Name>, <Name>month</Name>, <Name>day</Name>, <Name>hour</Name>=0, <Name>minute</Name>=0, <Name>second</Name>=0,
212.337 - <Name>microsecond</Name>=0):
212.338 - # Normalize all the inputs, and store the normalized values.
212.339 - if not 0 <= <Name>microsecond</Name> <= 999999:
212.340 - <Name>carry</Name>, <Name>microsecond</Name> = <Call><Name>divmod</Name></Call>(<Name>microsecond</Name>, 1000000)
212.341 - <Name>second</Name> += <Name>carry</Name>
212.342 - if not 0 <= <Name>second</Name> <= 59:
212.343 - <Name>carry</Name>, <Name>second</Name> = <Call><Name>divmod</Name></Call>(<Name>second</Name>, 60)
212.344 - <Name>minute</Name> += <Name>carry</Name>
212.345 - if not 0 <= <Name>minute</Name> <= 59:
212.346 - <Name>carry</Name>, <Name>minute</Name> = <Call><Name>divmod</Name></Call>(<Name>minute</Name>, 60)
212.347 - <Name>hour</Name> += <Name>carry</Name>
212.348 - if not 0 <= <Name>hour</Name> <= 23:
212.349 - <Name>carry</Name>, <Name>hour</Name> = <Call><Name>divmod</Name></Call>(<Name>hour</Name>, 24)
212.350 - <Name>day</Name> += <Name>carry</Name>
212.351 -
212.352 - # That was easy. Now it gets muddy: the proper range for day
212.353 - # can't be determined without knowing the correct month and year,
212.354 - # but if day is, e.g., plus or minus a million, the current month
212.355 - # and year values make no sense (and may also be out of bounds
212.356 - # themselves).
212.357 - # Saying 12 months == 1 year should be non-controversial.
212.358 - if not 1 <= <Name>month</Name> <= 12:
212.359 - <Name>carry</Name>, <Name>month</Name> = <Call><Name>divmod</Name></Call>(<Name>month</Name>-1, 12)
212.360 - <Name>year</Name> += <Name>carry</Name>
212.361 - <Name>month</Name> += 1
212.362 - assert 1 <= <Name>month</Name> <= 12
212.363 -
212.364 - # Now only day can be out of bounds (year may also be out of bounds
212.365 - # for a datetime object, but we don't care about that here).
212.366 - # If day is out of bounds, what to do is arguable, but at least the
212.367 - # method here is principled and explainable.
212.368 - <Name>dim</Name> = <Call><Name>_days_in_month</Name></Call>(<Name>year</Name>, <Name>month</Name>)
212.369 - if not 1 <= <Name>day</Name> <= <Name>dim</Name>:
212.370 - # Move day-1 days from the first of the month. First try to
212.371 - # get off cheap if we're only one day out of range (adjustments
212.372 - # for timezone alone can't be worse than that).
212.373 - if <Name>day</Name> == 0: # move back a day
212.374 - <Name>month</Name> -= 1
212.375 - if <Name>month</Name> > 0:
212.376 - <Name>day</Name> = <Call><Name>_days_in_month</Name></Call>(<Name>year</Name>, <Name>month</Name>)
212.377 - else:
212.378 - <Name>year</Name>, <Name>month</Name>, <Name>day</Name> = <Name>year</Name>-1, 12, 31
212.379 - elif <Name>day</Name> == <Name>dim</Name> + 1: # move forward a day
212.380 - <Name>month</Name> += 1
212.381 - <Name>day</Name> = 1
212.382 - if <Name>month</Name> > 12:
212.383 - <Name>month</Name> = 1
212.384 - <Name>year</Name> += 1
212.385 - else:
212.386 - <Attribute><Name>self</Name></Attribute>.ordinal = <Call><Name>_ymd2ord</Name></Call>(<Name>year</Name>, <Name>month</Name>, 1) + (<Name>day</Name> - 1)
212.387 - <Name>year</Name>, <Name>month</Name>, <Name>day</Name> = <Call><Name>_ord2ymd</Name></Call>(<Attribute><Name>self</Name></Attribute>.ordinal)
212.388 -
212.389 - <Attribute><Name>self</Name></Attribute>.year, <Attribute><Name>self</Name></Attribute>.month, <Attribute><Name>self</Name></Attribute>.day = <Name>year</Name>, <Name>month</Name>, <Name>day</Name>
212.390 - <Attribute><Name>self</Name></Attribute>.hour, <Attribute><Name>self</Name></Attribute>.minute, <Attribute><Name>self</Name></Attribute>.second = <Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>
212.391 - <Attribute><Name>self</Name></Attribute>.microsecond = <Name>microsecond</Name>
212.392 -
212.393 - def <FunctionDef>toordinal</FunctionDef>(<Name>self</Name>):
212.394 - """Return proleptic Gregorian ordinal for the year, month and day.
212.395 -
212.396 - January 1 of year 1 is day 1. Only the year, month and day values
212.397 - contribute to the result.
212.398 - """
212.399 - if <Attribute><Name>self</Name></Attribute>.ordinal is <Name>None</Name>:
212.400 - <Attribute><Name>self</Name></Attribute>.ordinal = <Call><Name>_ymd2ord</Name></Call>(<Attribute><Name>self</Name></Attribute>.year, <Attribute><Name>self</Name></Attribute>.month, <Attribute><Name>self</Name></Attribute>.day)
212.401 - return <Attribute><Name>self</Name></Attribute>.ordinal
212.402 -
212.403 - def <FunctionDef>time</FunctionDef>(<Name>self</Name>):
212.404 - "Return Unixish timestamp, as a float (assuming UTC)."
212.405 - <Name>days</Name> = <Attribute><Name>self</Name></Attribute>.<Call>toordinal</Call>() - <Name>_ORD1970</Name> # convert to UNIX epoch
212.406 - <Name>seconds</Name> = ((<Name>days</Name> * 24. + <Attribute><Name>self</Name></Attribute>.hour)*60. + <Attribute><Name>self</Name></Attribute>.minute)*60.
212.407 - return <Name>seconds</Name> + <Attribute><Name>self</Name></Attribute>.second + <Attribute><Name>self</Name></Attribute>.microsecond / 1e6
212.408 -
212.409 - def <FunctionDef>ctime</FunctionDef>(<Name>self</Name>):
212.410 - "Return ctime() style string."
212.411 - <Name>weekday</Name> = <Attribute><Name>self</Name></Attribute>.<Call>toordinal</Call>() % 7 or 7
212.412 - return "%s %s %2d %02d:%02d:%02d %04d" % (
212.413 - <Name>_DAYNAMES</Name>[<Name>weekday</Name>],
212.414 - <Name>_MONTHNAMES</Name>[<Attribute><Name>self</Name></Attribute>.month],
212.415 - <Attribute><Name>self</Name></Attribute>.day,
212.416 - <Attribute><Name>self</Name></Attribute>.hour, <Attribute><Name>self</Name></Attribute>.minute, <Attribute><Name>self</Name></Attribute>.second,
212.417 - <Attribute><Name>self</Name></Attribute>.year)
212.418 -
212.419 -class <ClassDef>timedelta</ClassDef>(<Name>object</Name>):
212.420 - """Represent the difference between two datetime objects.
212.421 -
212.422 - Supported operators:
212.423 -
212.424 - - add, subtract timedelta
212.425 - - unary plus, minus, abs
212.426 - - compare to timedelta
212.427 - - multiply, divide by int/long
212.428 -
212.429 - In addition, datetime supports subtraction of two datetime objects
212.430 - returning a timedelta, and addition or subtraction of a datetime
212.431 - and a timedelta giving a datetime.
212.432 -
212.433 - Representation: (days, seconds, microseconds). Why? Because I
212.434 - felt like it.
212.435 - """
212.436 -
212.437 - def <FunctionDef>__new__</FunctionDef>(<Name>cls</Name>, <Name>days</Name>=0, <Name>seconds</Name>=0, <Name>microseconds</Name>=0,
212.438 - # XXX The following should only be used as keyword args:
212.439 - <Name>milliseconds</Name>=0, <Name>minutes</Name>=0, <Name>hours</Name>=0, <Name>weeks</Name>=0):
212.440 - # Doing this efficiently and accurately in C is going to be difficult
212.441 - # and error-prone, due to ubiquitous overflow possibilities, and that
212.442 - # C double doesn't have enough bits of precision to represent
212.443 - # microseconds over 10K years faithfully. The code here tries to make
212.444 - # explicit where go-fast assumptions can be relied on, in order to
212.445 - # guide the C implementation; it's way more convoluted than speed-
212.446 - # ignoring auto-overflow-to-long idiomatic Python could be.
212.447 -
212.448 - # XXX Check that all inputs are ints, longs or floats.
212.449 -
212.450 - # Final values, all integer.
212.451 - # s and us fit in 32-bit signed ints; d isn't bounded.
212.452 - <Name>d</Name> = <Name>s</Name> = <Name>us</Name> = 0
212.453 -
212.454 - # Normalize everything to days, seconds, microseconds.
212.455 - <Name>days</Name> += <Name>weeks</Name>*7
212.456 - <Name>seconds</Name> += <Name>minutes</Name>*60 + <Name>hours</Name>*3600
212.457 - <Name>microseconds</Name> += <Name>milliseconds</Name>*1000
212.458 -
212.459 - # Get rid of all fractions, and normalize s and us.
212.460 - # Take a deep breath <wink>.
212.461 - if <Call><Name>isinstance</Name></Call>(<Name>days</Name>, <Name>float</Name>):
212.462 - <Name>dayfrac</Name>, <Name>days</Name> = <Attribute><Name>_math</Name></Attribute>.<Call>modf</Call>(<Name>days</Name>)
212.463 - <Name>daysecondsfrac</Name>, <Name>daysecondswhole</Name> = <Attribute><Name>_math</Name></Attribute>.<Call>modf</Call>(<Name>dayfrac</Name> * (24.*3600.))
212.464 - assert <Name>daysecondswhole</Name> == <Call><Name>int</Name></Call>(<Name>daysecondswhole</Name>) # can't overflow
212.465 - <Name>s</Name> = <Call><Name>int</Name></Call>(<Name>daysecondswhole</Name>)
212.466 - assert <Name>days</Name> == <Call><Name>long</Name></Call>(<Name>days</Name>)
212.467 - <Name>d</Name> = <Call><Name>long</Name></Call>(<Name>days</Name>)
212.468 - else:
212.469 - <Name>daysecondsfrac</Name> = 0.0
212.470 - <Name>d</Name> = <Name>days</Name>
212.471 - assert <Call><Name>isinstance</Name></Call>(<Name>daysecondsfrac</Name>, <Name>float</Name>)
212.472 - assert <Call><Name>abs</Name></Call>(<Name>daysecondsfrac</Name>) <= 1.0
212.473 - assert <Call><Name>isinstance</Name></Call>(<Name>d</Name>, (<Name>int</Name>, <Name>long</Name>))
212.474 - assert <Call><Name>abs</Name></Call>(<Name>s</Name>) <= 24 * 3600
212.475 - # days isn't referenced again before redefinition
212.476 -
212.477 - if <Call><Name>isinstance</Name></Call>(<Name>seconds</Name>, <Name>float</Name>):
212.478 - <Name>secondsfrac</Name>, <Name>seconds</Name> = <Attribute><Name>_math</Name></Attribute>.<Call>modf</Call>(<Name>seconds</Name>)
212.479 - assert <Name>seconds</Name> == <Call><Name>long</Name></Call>(<Name>seconds</Name>)
212.480 - <Name>seconds</Name> = <Call><Name>long</Name></Call>(<Name>seconds</Name>)
212.481 - <Name>secondsfrac</Name> += <Name>daysecondsfrac</Name>
212.482 - assert <Call><Name>abs</Name></Call>(<Name>secondsfrac</Name>) <= 2.0
212.483 - else:
212.484 - <Name>secondsfrac</Name> = <Name>daysecondsfrac</Name>
212.485 - # daysecondsfrac isn't referenced again
212.486 - assert <Call><Name>isinstance</Name></Call>(<Name>secondsfrac</Name>, <Name>float</Name>)
212.487 - assert <Call><Name>abs</Name></Call>(<Name>secondsfrac</Name>) <= 2.0
212.488 -
212.489 - assert <Call><Name>isinstance</Name></Call>(<Name>seconds</Name>, (<Name>int</Name>, <Name>long</Name>))
212.490 - <Name>days</Name>, <Name>seconds</Name> = <Call><Name>divmod</Name></Call>(<Name>seconds</Name>, 24*3600)
212.491 - <Name>d</Name> += <Name>days</Name>
212.492 - <Name>s</Name> += <Call><Name>int</Name></Call>(<Name>seconds</Name>) # can't overflow
212.493 - assert <Call><Name>isinstance</Name></Call>(<Name>s</Name>, <Name>int</Name>)
212.494 - assert <Call><Name>abs</Name></Call>(<Name>s</Name>) <= 2 * 24 * 3600
212.495 - # seconds isn't referenced again before redefinition
212.496 -
212.497 - <Name>usdouble</Name> = <Name>secondsfrac</Name> * 1e6
212.498 - assert <Call><Name>abs</Name></Call>(<Name>usdouble</Name>) < 2.1e6 # exact value not critical
212.499 - # secondsfrac isn't referenced again
212.500 -
212.501 - if <Call><Name>isinstance</Name></Call>(<Name>microseconds</Name>, <Name>float</Name>):
212.502 - <Name>microseconds</Name> += <Name>usdouble</Name>
212.503 - <Name>microseconds</Name> = <Call><Name>round</Name></Call>(<Name>microseconds</Name>)
212.504 - <Name>seconds</Name>, <Name>microseconds</Name> = <Call><Name>divmod</Name></Call>(<Name>microseconds</Name>, 1e6)
212.505 - assert <Name>microseconds</Name> == <Call><Name>int</Name></Call>(<Name>microseconds</Name>)
212.506 - assert <Name>seconds</Name> == <Call><Name>long</Name></Call>(<Name>seconds</Name>)
212.507 - <Name>days</Name>, <Name>seconds</Name> = <Call><Name>divmod</Name></Call>(<Name>seconds</Name>, 24.*3600.)
212.508 - assert <Name>days</Name> == <Call><Name>long</Name></Call>(<Name>days</Name>)
212.509 - assert <Name>seconds</Name> == <Call><Name>int</Name></Call>(<Name>seconds</Name>)
212.510 - <Name>d</Name> += <Call><Name>long</Name></Call>(<Name>days</Name>)
212.511 - <Name>s</Name> += <Call><Name>int</Name></Call>(<Name>seconds</Name>) # can't overflow
212.512 - assert <Call><Name>isinstance</Name></Call>(<Name>s</Name>, <Name>int</Name>)
212.513 - assert <Call><Name>abs</Name></Call>(<Name>s</Name>) <= 3 * 24 * 3600
212.514 - else:
212.515 - <Name>seconds</Name>, <Name>microseconds</Name> = <Call><Name>divmod</Name></Call>(<Name>microseconds</Name>, 1000000)
212.516 - <Name>days</Name>, <Name>seconds</Name> = <Call><Name>divmod</Name></Call>(<Name>seconds</Name>, 24*3600)
212.517 - <Name>d</Name> += <Name>days</Name>
212.518 - <Name>s</Name> += <Call><Name>int</Name></Call>(<Name>seconds</Name>) # can't overflow
212.519 - assert <Call><Name>isinstance</Name></Call>(<Name>s</Name>, <Name>int</Name>)
212.520 - assert <Call><Name>abs</Name></Call>(<Name>s</Name>) <= 3 * 24 * 3600
212.521 - <Name>microseconds</Name> = <Call><Name>float</Name></Call>(<Name>microseconds</Name>)
212.522 - <Name>microseconds</Name> += <Name>usdouble</Name>
212.523 - <Name>microseconds</Name> = <Call><Name>round</Name></Call>(<Name>microseconds</Name>)
212.524 - assert <Call><Name>abs</Name></Call>(<Name>s</Name>) <= 3 * 24 * 3600
212.525 - assert <Call><Name>abs</Name></Call>(<Name>microseconds</Name>) < 3.1e6
212.526 -
212.527 - # Just a little bit of carrying possible for microseconds and seconds.
212.528 - assert <Call><Name>isinstance</Name></Call>(<Name>microseconds</Name>, <Name>float</Name>)
212.529 - assert <Call><Name>int</Name></Call>(<Name>microseconds</Name>) == <Name>microseconds</Name>
212.530 - <Name>us</Name> = <Call><Name>int</Name></Call>(<Name>microseconds</Name>)
212.531 - <Name>seconds</Name>, <Name>us</Name> = <Call><Name>divmod</Name></Call>(<Name>us</Name>, 1000000)
212.532 - <Name>s</Name> += <Name>seconds</Name> # cant't overflow
212.533 - assert <Call><Name>isinstance</Name></Call>(<Name>s</Name>, <Name>int</Name>)
212.534 - <Name>days</Name>, <Name>s</Name> = <Call><Name>divmod</Name></Call>(<Name>s</Name>, 24*3600)
212.535 - <Name>d</Name> += <Name>days</Name>
212.536 -
212.537 - assert <Call><Name>isinstance</Name></Call>(<Name>d</Name>, (<Name>int</Name>, <Name>long</Name>))
212.538 - assert <Call><Name>isinstance</Name></Call>(<Name>s</Name>, <Name>int</Name>) and 0 <= <Name>s</Name> < 24*3600
212.539 - assert <Call><Name>isinstance</Name></Call>(<Name>us</Name>, <Name>int</Name>) and 0 <= <Name>us</Name> < 1000000
212.540 -
212.541 - <Name>self</Name> = <Attribute><Name>object</Name></Attribute>.<Call>__new__</Call>(<Name>cls</Name>)
212.542 -
212.543 - <Attribute><Name>self</Name></Attribute>.__days = <Name>d</Name>
212.544 - <Attribute><Name>self</Name></Attribute>.__seconds = <Name>s</Name>
212.545 - <Attribute><Name>self</Name></Attribute>.__microseconds = <Name>us</Name>
212.546 - if <Call><Name>abs</Name></Call>(<Name>d</Name>) > 999999999:
212.547 - raise <Call><Name>OverflowError</Name></Call>("timedelta # of days is too large: %d" % <Name>d</Name>)
212.548 -
212.549 - return <Name>self</Name>
212.550 -
212.551 - def <FunctionDef>__repr__</FunctionDef>(<Name>self</Name>):
212.552 - if <Attribute><Name>self</Name></Attribute>.__microseconds:
212.553 - return "%s(%d, %d, %d)" % ('datetime.' + <Attribute><Attribute><Name>self</Name></Attribute></Attribute>.__class__.__name__,
212.554 - <Attribute><Name>self</Name></Attribute>.__days,
212.555 - <Attribute><Name>self</Name></Attribute>.__seconds,
212.556 - <Attribute><Name>self</Name></Attribute>.__microseconds)
212.557 - if <Attribute><Name>self</Name></Attribute>.__seconds:
212.558 - return "%s(%d, %d)" % ('datetime.' + <Attribute><Attribute><Name>self</Name></Attribute></Attribute>.__class__.__name__,
212.559 - <Attribute><Name>self</Name></Attribute>.__days,
212.560 - <Attribute><Name>self</Name></Attribute>.__seconds)
212.561 - return "%s(%d)" % ('datetime.' + <Attribute><Attribute><Name>self</Name></Attribute></Attribute>.__class__.__name__, <Attribute><Name>self</Name></Attribute>.__days)
212.562 -
212.563 - def <FunctionDef>__str__</FunctionDef>(<Name>self</Name>):
212.564 - <Name>mm</Name>, <Name>ss</Name> = <Call><Name>divmod</Name></Call>(<Attribute><Name>self</Name></Attribute>.__seconds, 60)
212.565 - <Name>hh</Name>, <Name>mm</Name> = <Call><Name>divmod</Name></Call>(<Name>mm</Name>, 60)
212.566 - <Name>s</Name> = "%d:%02d:%02d" % (<Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>)
212.567 - if <Attribute><Name>self</Name></Attribute>.__days:
212.568 - def <FunctionDef>plural</FunctionDef>(<Name>n</Name>):
212.569 - return <Name>n</Name>, <Call><Name>abs</Name></Call>(<Name>n</Name>) != 1 and "s" or ""
212.570 - <Name>s</Name> = ("%d day%s, " % <Call><Name>plural</Name></Call>(<Attribute><Name>self</Name></Attribute>.__days)) + <Name>s</Name>
212.571 - if <Attribute><Name>self</Name></Attribute>.__microseconds:
212.572 - <Name>s</Name> = <Name>s</Name> + ".%06d" % <Attribute><Name>self</Name></Attribute>.__microseconds
212.573 - return <Name>s</Name>
212.574 -
212.575 - <Name>days</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__days, doc="days")
212.576 - <Name>seconds</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__seconds, doc="seconds")
212.577 - <Name>microseconds</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__microseconds,
212.578 - doc="microseconds")
212.579 -
212.580 - def <FunctionDef>__add__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.581 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
212.582 - return <Call><Name>timedelta</Name></Call>(<Attribute><Name>self</Name></Attribute>.__days + <Attribute><Name>other</Name></Attribute>.__days,
212.583 - <Attribute><Name>self</Name></Attribute>.__seconds + <Attribute><Name>other</Name></Attribute>.__seconds,
212.584 - <Attribute><Name>self</Name></Attribute>.__microseconds + <Attribute><Name>other</Name></Attribute>.__microseconds)
212.585 - return <Name>NotImplemented</Name>
212.586 -
212.587 - <Name>__radd__</Name> = <Name>__add__</Name>
212.588 -
212.589 - def <FunctionDef>__sub__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.590 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
212.591 - return <Name>self</Name> + -<Name>other</Name>
212.592 - return <Name>NotImplemented</Name>
212.593 -
212.594 - def <FunctionDef>__rsub__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.595 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
212.596 - return -<Name>self</Name> + <Name>other</Name>
212.597 - return <Name>NotImplemented</Name>
212.598 -
212.599 - def <FunctionDef>__neg__</FunctionDef>(<Name>self</Name>):
212.600 - return <Attribute><Name>self</Name></Attribute>.<Call>__class__</Call>(-<Attribute><Name>self</Name></Attribute>.__days,
212.601 - -<Attribute><Name>self</Name></Attribute>.__seconds,
212.602 - -<Attribute><Name>self</Name></Attribute>.__microseconds)
212.603 -
212.604 - def <FunctionDef>__pos__</FunctionDef>(<Name>self</Name>):
212.605 - return <Name>self</Name>
212.606 -
212.607 - def <FunctionDef>__abs__</FunctionDef>(<Name>self</Name>):
212.608 - if <Attribute><Name>self</Name></Attribute>.__days < 0:
212.609 - return -<Name>self</Name>
212.610 - else:
212.611 - return <Name>self</Name>
212.612 -
212.613 - def <FunctionDef>__mul__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.614 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, (<Name>int</Name>, <Name>long</Name>)):
212.615 - return <Attribute><Name>self</Name></Attribute>.<Call>__class__</Call>(<Attribute><Name>self</Name></Attribute>.__days * <Name>other</Name>,
212.616 - <Attribute><Name>self</Name></Attribute>.__seconds * <Name>other</Name>,
212.617 - <Attribute><Name>self</Name></Attribute>.__microseconds * <Name>other</Name>)
212.618 - return <Name>NotImplemented</Name>
212.619 -
212.620 - <Name>__rmul__</Name> = <Name>__mul__</Name>
212.621 -
212.622 - def <FunctionDef>__div__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.623 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, (<Name>int</Name>, <Name>long</Name>)):
212.624 - <Name>usec</Name> = ((<Attribute><Name>self</Name></Attribute>.__days * (24*3600L) + <Attribute><Name>self</Name></Attribute>.__seconds) * 1000000 +
212.625 - <Attribute><Name>self</Name></Attribute>.__microseconds)
212.626 - return <Attribute><Name>self</Name></Attribute>.<Call>__class__</Call>(0, 0, <Name>usec</Name> // <Name>other</Name>)
212.627 - return <Name>NotImplemented</Name>
212.628 -
212.629 - <Name>__floordiv__</Name> = <Name>__div__</Name>
212.630 -
212.631 - # Comparisons.
212.632 -
212.633 - def <FunctionDef>__eq__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.634 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
212.635 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) == 0
212.636 - else:
212.637 - return <Name>False</Name>
212.638 -
212.639 - def <FunctionDef>__ne__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.640 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
212.641 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) != 0
212.642 - else:
212.643 - return <Name>True</Name>
212.644 -
212.645 - def <FunctionDef>__le__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.646 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
212.647 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) <= 0
212.648 - else:
212.649 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
212.650 -
212.651 - def <FunctionDef>__lt__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.652 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
212.653 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) < 0
212.654 - else:
212.655 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
212.656 -
212.657 - def <FunctionDef>__ge__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.658 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
212.659 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) >= 0
212.660 - else:
212.661 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
212.662 -
212.663 - def <FunctionDef>__gt__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.664 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
212.665 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) > 0
212.666 - else:
212.667 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
212.668 -
212.669 - def <FunctionDef>__cmp</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.670 - assert <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>)
212.671 - return <Call><Name>cmp</Name></Call>(<Attribute><Name>self</Name></Attribute>.<Call>__getstate</Call>(), <Attribute><Name>other</Name></Attribute>.<Call>__getstate</Call>())
212.672 -
212.673 - def <FunctionDef>__hash__</FunctionDef>(<Name>self</Name>):
212.674 - return <Call><Name>hash</Name></Call>(<Attribute><Name>self</Name></Attribute>.<Call>__getstate</Call>())
212.675 -
212.676 - def <FunctionDef>__nonzero__</FunctionDef>(<Name>self</Name>):
212.677 - return (<Attribute><Name>self</Name></Attribute>.__days != 0 or
212.678 - <Attribute><Name>self</Name></Attribute>.__seconds != 0 or
212.679 - <Attribute><Name>self</Name></Attribute>.__microseconds != 0)
212.680 -
212.681 - # Pickle support.
212.682 -
212.683 - <Name>__safe_for_unpickling__</Name> = <Name>True</Name> # For Python 2.2
212.684 -
212.685 - def <FunctionDef>__getstate</FunctionDef>(<Name>self</Name>):
212.686 - return (<Attribute><Name>self</Name></Attribute>.__days, <Attribute><Name>self</Name></Attribute>.__seconds, <Attribute><Name>self</Name></Attribute>.__microseconds)
212.687 -
212.688 - def <FunctionDef>__reduce__</FunctionDef>(<Name>self</Name>):
212.689 - return (<Attribute><Name>self</Name></Attribute>.__class__, <Attribute><Name>self</Name></Attribute>.<Call>__getstate</Call>())
212.690 -
212.691 -<Attribute><Name>timedelta</Name></Attribute>.min = <Call><Name>timedelta</Name></Call>(-999999999)
212.692 -<Attribute><Name>timedelta</Name></Attribute>.max = <Call><Name>timedelta</Name></Call>(days=999999999, hours=23, minutes=59, seconds=59,
212.693 - microseconds=999999)
212.694 -<Attribute><Name>timedelta</Name></Attribute>.resolution = <Call><Name>timedelta</Name></Call>(microseconds=1)
212.695 -
212.696 -class <ClassDef>date</ClassDef>(<Name>object</Name>):
212.697 - """Concrete date type.
212.698 -
212.699 - Constructors:
212.700 -
212.701 - __new__()
212.702 - fromtimestamp()
212.703 - today()
212.704 - fromordinal()
212.705 -
212.706 - Operators:
212.707 -
212.708 - __repr__, __str__
212.709 - __cmp__, __hash__
212.710 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
212.711 -
212.712 - Methods:
212.713 -
212.714 - timetuple()
212.715 - toordinal()
212.716 - weekday()
212.717 - isoweekday(), isocalendar(), isoformat()
212.718 - ctime()
212.719 - strftime()
212.720 -
212.721 - Properties (readonly):
212.722 - year, month, day
212.723 - """
212.724 -
212.725 - def <FunctionDef>__new__</FunctionDef>(<Name>cls</Name>, <Name>year</Name>, <Name>month</Name>=<Name>None</Name>, <Name>day</Name>=<Name>None</Name>):
212.726 - """Constructor.
212.727 -
212.728 - Arguments:
212.729 -
212.730 - year, month, day (required, base 1)
212.731 - """
212.732 - if <Call><Name>isinstance</Name></Call>(<Name>year</Name>, <Name>str</Name>):
212.733 - # Pickle support
212.734 - <Name>self</Name> = <Attribute><Name>object</Name></Attribute>.<Call>__new__</Call>(<Name>cls</Name>)
212.735 - <Attribute><Name>self</Name></Attribute>.<Call>__setstate</Call>((<Name>year</Name>,))
212.736 - return <Name>self</Name>
212.737 - <Call><Name>_check_date_fields</Name></Call>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>)
212.738 - <Name>self</Name> = <Attribute><Name>object</Name></Attribute>.<Call>__new__</Call>(<Name>cls</Name>)
212.739 - <Attribute><Name>self</Name></Attribute>.__year = <Name>year</Name>
212.740 - <Attribute><Name>self</Name></Attribute>.__month = <Name>month</Name>
212.741 - <Attribute><Name>self</Name></Attribute>.__day = <Name>day</Name>
212.742 - return <Name>self</Name>
212.743 -
212.744 - # Additional constructors
212.745 -
212.746 - def <FunctionDef>fromtimestamp</FunctionDef>(<Name>cls</Name>, <Name>t</Name>):
212.747 - "Construct a date from a POSIX timestamp (like time.time())."
212.748 - <Name>y</Name>, <Name>m</Name>, <Name>d</Name>, <Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Name>weekday</Name>, <Name>jday</Name>, <Name>dst</Name> = <Attribute><Name>_time</Name></Attribute>.<Call>localtime</Call>(<Name>t</Name>)
212.749 - return <Call><Name>cls</Name></Call>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>)
212.750 - <Name>fromtimestamp</Name> = <Call><Name>classmethod</Name></Call>(<Name>fromtimestamp</Name>)
212.751 -
212.752 - def <FunctionDef>today</FunctionDef>(<Name>cls</Name>):
212.753 - "Construct a date from time.time()."
212.754 - <Name>t</Name> = <Attribute><Name>_time</Name></Attribute>.<Call>time</Call>()
212.755 - return <Attribute><Name>cls</Name></Attribute>.<Call>fromtimestamp</Call>(<Name>t</Name>)
212.756 - <Name>today</Name> = <Call><Name>classmethod</Name></Call>(<Name>today</Name>)
212.757 -
212.758 - def <FunctionDef>fromordinal</FunctionDef>(<Name>cls</Name>, <Name>n</Name>):
212.759 - """Contruct a date from a proleptic Gregorian ordinal.
212.760 -
212.761 - January 1 of year 1 is day 1. Only the year, month and day are
212.762 - non-zero in the result.
212.763 - """
212.764 - <Name>y</Name>, <Name>m</Name>, <Name>d</Name> = <Call><Name>_ord2ymd</Name></Call>(<Name>n</Name>)
212.765 - return <Call><Name>cls</Name></Call>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>)
212.766 - <Name>fromordinal</Name> = <Call><Name>classmethod</Name></Call>(<Name>fromordinal</Name>)
212.767 -
212.768 - # Conversions to string
212.769 -
212.770 - def <FunctionDef>__repr__</FunctionDef>(<Name>self</Name>):
212.771 - "Convert to formal string, for repr()."
212.772 - return "%s(%d, %d, %d)" % ('datetime.' + <Attribute><Attribute><Name>self</Name></Attribute></Attribute>.__class__.__name__,
212.773 - <Attribute><Name>self</Name></Attribute>.__year,
212.774 - <Attribute><Name>self</Name></Attribute>.__month,
212.775 - <Attribute><Name>self</Name></Attribute>.__day)
212.776 - # XXX These shouldn't depend on time.localtime(), because that
212.777 - # clips the usable dates to [1970 .. 2038). At least ctime() is
212.778 - # easily done without using strftime() -- that's better too because
212.779 - # strftime("%c", ...) is locale specific.
212.780 -
212.781 - def <FunctionDef>ctime</FunctionDef>(<Name>self</Name>):
212.782 - "Format a la ctime()."
212.783 - return <Attribute><Call><Name>tmxxx</Name></Call></Attribute>(<Attribute><Name>self</Name></Attribute>.__year, <Attribute><Name>self</Name></Attribute>.__month, <Attribute><Name>self</Name></Attribute>.__day).<Call>ctime</Call>()
212.784 -
212.785 - def <FunctionDef>strftime</FunctionDef>(<Name>self</Name>, <Name>fmt</Name>):
212.786 - "Format using strftime()."
212.787 - return <Call><Name>_wrap_strftime</Name></Call>(<Name>self</Name>, <Name>fmt</Name>, <Attribute><Name>self</Name></Attribute>.<Call>timetuple</Call>())
212.788 -
212.789 - def <FunctionDef>isoformat</FunctionDef>(<Name>self</Name>):
212.790 - """Return the date formatted according to ISO.
212.791 -
212.792 - This is 'YYYY-MM-DD'.
212.793 -
212.794 - References:
212.795 - - http://www.w3.org/TR/NOTE-datetime
212.796 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
212.797 - """
212.798 - return "%04d-%02d-%02d" % (<Attribute><Name>self</Name></Attribute>.__year, <Attribute><Name>self</Name></Attribute>.__month, <Attribute><Name>self</Name></Attribute>.__day)
212.799 -
212.800 - <Name>__str__</Name> = <Name>isoformat</Name>
212.801 -
212.802 - # Read-only field accessors
212.803 - <Name>year</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__year,
212.804 - doc="year (%d-%d)" % (<Name>MINYEAR</Name>, <Name>MAXYEAR</Name>))
212.805 - <Name>month</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__month, doc="month (1-12)")
212.806 - <Name>day</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__day, doc="day (1-31)")
212.807 -
212.808 - # Standard conversions, __cmp__, __hash__ (and helpers)
212.809 -
212.810 - def <FunctionDef>timetuple</FunctionDef>(<Name>self</Name>):
212.811 - "Return local time tuple compatible with time.localtime()."
212.812 - return <Call><Name>_build_struct_time</Name></Call>(<Attribute><Name>self</Name></Attribute>.__year, <Attribute><Name>self</Name></Attribute>.__month, <Attribute><Name>self</Name></Attribute>.__day,
212.813 - 0, 0, 0, -1)
212.814 -
212.815 - def <FunctionDef>toordinal</FunctionDef>(<Name>self</Name>):
212.816 - """Return proleptic Gregorian ordinal for the year, month and day.
212.817 -
212.818 - January 1 of year 1 is day 1. Only the year, month and day values
212.819 - contribute to the result.
212.820 - """
212.821 - return <Call><Name>_ymd2ord</Name></Call>(<Attribute><Name>self</Name></Attribute>.__year, <Attribute><Name>self</Name></Attribute>.__month, <Attribute><Name>self</Name></Attribute>.__day)
212.822 -
212.823 - def <FunctionDef>replace</FunctionDef>(<Name>self</Name>, <Name>year</Name>=<Name>None</Name>, <Name>month</Name>=<Name>None</Name>, <Name>day</Name>=<Name>None</Name>):
212.824 - """Return a new date with new values for the specified fields."""
212.825 - if <Name>year</Name> is <Name>None</Name>:
212.826 - <Name>year</Name> = <Attribute><Name>self</Name></Attribute>.__year
212.827 - if <Name>month</Name> is <Name>None</Name>:
212.828 - <Name>month</Name> = <Attribute><Name>self</Name></Attribute>.__month
212.829 - if <Name>day</Name> is <Name>None</Name>:
212.830 - <Name>day</Name> = <Attribute><Name>self</Name></Attribute>.__day
212.831 - <Call><Name>_check_date_fields</Name></Call>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>)
212.832 - return <Call><Name>date</Name></Call>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>)
212.833 -
212.834 - # Comparisons.
212.835 -
212.836 - def <FunctionDef>__eq__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.837 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>date</Name>):
212.838 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) == 0
212.839 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
212.840 - return <Name>NotImplemented</Name>
212.841 - else:
212.842 - return <Name>False</Name>
212.843 -
212.844 - def <FunctionDef>__ne__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.845 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>date</Name>):
212.846 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) != 0
212.847 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
212.848 - return <Name>NotImplemented</Name>
212.849 - else:
212.850 - return <Name>True</Name>
212.851 -
212.852 - def <FunctionDef>__le__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.853 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>date</Name>):
212.854 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) <= 0
212.855 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
212.856 - return <Name>NotImplemented</Name>
212.857 - else:
212.858 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
212.859 -
212.860 - def <FunctionDef>__lt__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.861 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>date</Name>):
212.862 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) < 0
212.863 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
212.864 - return <Name>NotImplemented</Name>
212.865 - else:
212.866 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
212.867 -
212.868 - def <FunctionDef>__ge__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.869 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>date</Name>):
212.870 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) >= 0
212.871 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
212.872 - return <Name>NotImplemented</Name>
212.873 - else:
212.874 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
212.875 -
212.876 - def <FunctionDef>__gt__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.877 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>date</Name>):
212.878 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) > 0
212.879 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
212.880 - return <Name>NotImplemented</Name>
212.881 - else:
212.882 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
212.883 -
212.884 - def <FunctionDef>__cmp</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.885 - assert <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>date</Name>)
212.886 - <Name>y</Name>, <Name>m</Name>, <Name>d</Name> = <Attribute><Name>self</Name></Attribute>.__year, <Attribute><Name>self</Name></Attribute>.__month, <Attribute><Name>self</Name></Attribute>.__day
212.887 - <Name>y2</Name>, <Name>m2</Name>, <Name>d2</Name> = <Attribute><Name>other</Name></Attribute>.__year, <Attribute><Name>other</Name></Attribute>.__month, <Attribute><Name>other</Name></Attribute>.__day
212.888 - return <Call><Name>cmp</Name></Call>((<Name>y</Name>, <Name>m</Name>, <Name>d</Name>), (<Name>y2</Name>, <Name>m2</Name>, <Name>d2</Name>))
212.889 -
212.890 - def <FunctionDef>__hash__</FunctionDef>(<Name>self</Name>):
212.891 - "Hash."
212.892 - return <Call><Name>hash</Name></Call>(<Attribute><Name>self</Name></Attribute>.<Call>__getstate</Call>())
212.893 -
212.894 - # Computations
212.895 -
212.896 - def <FunctionDef>_checkOverflow</FunctionDef>(<Name>self</Name>, <Name>year</Name>):
212.897 - if not <Name>MINYEAR</Name> <= <Name>year</Name> <= <Name>MAXYEAR</Name>:
212.898 - raise <Call><Name>OverflowError</Name></Call>("date +/-: result year %d not in %d..%d" %
212.899 - (<Name>year</Name>, <Name>MINYEAR</Name>, <Name>MAXYEAR</Name>))
212.900 -
212.901 - def <FunctionDef>__add__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.902 - "Add a date to a timedelta."
212.903 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
212.904 - <Name>t</Name> = <Call><Name>tmxxx</Name></Call>(<Attribute><Name>self</Name></Attribute>.__year,
212.905 - <Attribute><Name>self</Name></Attribute>.__month,
212.906 - <Attribute><Name>self</Name></Attribute>.__day + <Attribute><Name>other</Name></Attribute>.days)
212.907 - <Attribute><Name>self</Name></Attribute>.<Call>_checkOverflow</Call>(<Attribute><Name>t</Name></Attribute>.year)
212.908 - <Name>result</Name> = <Attribute><Name>self</Name></Attribute>.<Call>__class__</Call>(<Attribute><Name>t</Name></Attribute>.year, <Attribute><Name>t</Name></Attribute>.month, <Attribute><Name>t</Name></Attribute>.day)
212.909 - return <Name>result</Name>
212.910 - return <Name>NotImplemented</Name>
212.911 -
212.912 - <Name>__radd__</Name> = <Name>__add__</Name>
212.913 -
212.914 - def <FunctionDef>__sub__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.915 - """Subtract two dates, or a date and a timedelta."""
212.916 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
212.917 - return <Name>self</Name> + <Call><Name>timedelta</Name></Call>(-<Attribute><Name>other</Name></Attribute>.days)
212.918 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>date</Name>):
212.919 - <Name>days1</Name> = <Attribute><Name>self</Name></Attribute>.<Call>toordinal</Call>()
212.920 - <Name>days2</Name> = <Attribute><Name>other</Name></Attribute>.<Call>toordinal</Call>()
212.921 - return <Call><Name>timedelta</Name></Call>(<Name>days1</Name> - <Name>days2</Name>)
212.922 - return <Name>NotImplemented</Name>
212.923 -
212.924 - def <FunctionDef>weekday</FunctionDef>(<Name>self</Name>):
212.925 - "Return day of the week, where Monday == 0 ... Sunday == 6."
212.926 - return (<Attribute><Name>self</Name></Attribute>.<Call>toordinal</Call>() + 6) % 7
212.927 -
212.928 - # Day-of-the-week and week-of-the-year, according to ISO
212.929 -
212.930 - def <FunctionDef>isoweekday</FunctionDef>(<Name>self</Name>):
212.931 - "Return day of the week, where Monday == 1 ... Sunday == 7."
212.932 - # 1-Jan-0001 is a Monday
212.933 - return <Attribute><Name>self</Name></Attribute>.<Call>toordinal</Call>() % 7 or 7
212.934 -
212.935 - def <FunctionDef>isocalendar</FunctionDef>(<Name>self</Name>):
212.936 - """Return a 3-tuple containing ISO year, week number, and weekday.
212.937 -
212.938 - The first ISO week of the year is the (Mon-Sun) week
212.939 - containing the year's first Thursday; everything else derives
212.940 - from that.
212.941 -
212.942 - The first week is 1; Monday is 1 ... Sunday is 7.
212.943 -
212.944 - ISO calendar algorithm taken from
212.945 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
212.946 - """
212.947 - <Name>year</Name> = <Attribute><Name>self</Name></Attribute>.__year
212.948 - <Name>week1monday</Name> = <Call><Name>_isoweek1monday</Name></Call>(<Name>year</Name>)
212.949 - <Name>today</Name> = <Call><Name>_ymd2ord</Name></Call>(<Attribute><Name>self</Name></Attribute>.__year, <Attribute><Name>self</Name></Attribute>.__month, <Attribute><Name>self</Name></Attribute>.__day)
212.950 - # Internally, week and day have origin 0
212.951 - <Name>week</Name>, <Name>day</Name> = <Call><Name>divmod</Name></Call>(<Name>today</Name> - <Name>week1monday</Name>, 7)
212.952 - if <Name>week</Name> < 0:
212.953 - <Name>year</Name> -= 1
212.954 - <Name>week1monday</Name> = <Call><Name>_isoweek1monday</Name></Call>(<Name>year</Name>)
212.955 - <Name>week</Name>, <Name>day</Name> = <Call><Name>divmod</Name></Call>(<Name>today</Name> - <Name>week1monday</Name>, 7)
212.956 - elif <Name>week</Name> >= 52:
212.957 - if <Name>today</Name> >= <Call><Name>_isoweek1monday</Name></Call>(<Name>year</Name>+1):
212.958 - <Name>year</Name> += 1
212.959 - <Name>week</Name> = 0
212.960 - return <Name>year</Name>, <Name>week</Name>+1, <Name>day</Name>+1
212.961 -
212.962 - # Pickle support.
212.963 -
212.964 - <Name>__safe_for_unpickling__</Name> = <Name>True</Name> # For Python 2.2
212.965 -
212.966 - def <FunctionDef>__getstate</FunctionDef>(<Name>self</Name>):
212.967 - <Name>yhi</Name>, <Name>ylo</Name> = <Call><Name>divmod</Name></Call>(<Attribute><Name>self</Name></Attribute>.__year, 256)
212.968 - return ("%c%c%c%c" % (<Name>yhi</Name>, <Name>ylo</Name>, <Attribute><Name>self</Name></Attribute>.__month, <Attribute><Name>self</Name></Attribute>.__day), )
212.969 -
212.970 - def <FunctionDef>__setstate</FunctionDef>(<Name>self</Name>, <Name>t</Name>):
212.971 - assert <Call><Name>isinstance</Name></Call>(<Name>t</Name>, <Name>tuple</Name>) and <Call><Name>len</Name></Call>(<Name>t</Name>) == 1, `<Name>t</Name>`
212.972 - <Name>string</Name> = <Name>t</Name>[0]
212.973 - assert <Call><Name>len</Name></Call>(<Name>string</Name>) == 4
212.974 - <Name>yhi</Name>, <Name>ylo</Name>, <Attribute><Name>self</Name></Attribute>.__month, <Attribute><Name>self</Name></Attribute>.__day = <Call><Name>map</Name></Call>(<Name>ord</Name>, <Name>string</Name>)
212.975 - <Attribute><Name>self</Name></Attribute>.__year = <Name>yhi</Name> * 256 + <Name>ylo</Name>
212.976 -
212.977 - def <FunctionDef>__reduce__</FunctionDef>(<Name>self</Name>):
212.978 - return (<Attribute><Name>self</Name></Attribute>.__class__, <Attribute><Name>self</Name></Attribute>.<Call>__getstate</Call>())
212.979 -
212.980 -<Name>_date_class</Name> = <Name>date</Name> # so functions w/ args named "date" can get at the class
212.981 -
212.982 -<Attribute><Name>date</Name></Attribute>.min = <Call><Name>date</Name></Call>(1, 1, 1)
212.983 -<Attribute><Name>date</Name></Attribute>.max = <Call><Name>date</Name></Call>(9999, 12, 31)
212.984 -<Attribute><Name>date</Name></Attribute>.resolution = <Call><Name>timedelta</Name></Call>(days=1)
212.985 -
212.986 -class <ClassDef>tzinfo</ClassDef>(<Name>object</Name>):
212.987 - """Abstract base class for time zone info classes.
212.988 -
212.989 - Subclasses must override the name(), utcoffset() and dst() methods.
212.990 - """
212.991 -
212.992 - def <FunctionDef>tzname</FunctionDef>(<Name>self</Name>, <Name>dt</Name>):
212.993 - "datetime -> string name of time zone."
212.994 - raise <Call><Name>NotImplementedError</Name></Call>("tzinfo subclass must override tzname()")
212.995 -
212.996 - def <FunctionDef>utcoffset</FunctionDef>(<Name>self</Name>, <Name>dt</Name>):
212.997 - "datetime -> minutes east of UTC (negative for west of UTC)"
212.998 - raise <Call><Name>NotImplementedError</Name></Call>("tzinfo subclass must override utcoffset()")
212.999 -
212.1000 - def <FunctionDef>dst</FunctionDef>(<Name>self</Name>, <Name>dt</Name>):
212.1001 - """datetime -> DST offset in minutes east of UTC.
212.1002 -
212.1003 - Return 0 if DST not in effect. utcoffset() must include the DST
212.1004 - offset.
212.1005 - """
212.1006 - raise <Call><Name>NotImplementedError</Name></Call>("tzinfo subclass must override dst()")
212.1007 -
212.1008 - def <FunctionDef>fromutc</FunctionDef>(<Name>self</Name>, <Name>dt</Name>):
212.1009 - "datetime in UTC -> datetime in local time."
212.1010 -
212.1011 - if not <Call><Name>isinstance</Name></Call>(<Name>dt</Name>, <Name>datetime</Name>):
212.1012 - raise <Call><Name>TypeError</Name></Call>("fromutc() requires a datetime argument")
212.1013 - if <Attribute><Name>dt</Name></Attribute>.tzinfo is not <Name>self</Name>:
212.1014 - raise <Call><Name>ValueError</Name></Call>("dt.tzinfo is not self")
212.1015 -
212.1016 - <Name>dtoff</Name> = <Attribute><Name>dt</Name></Attribute>.<Call>utcoffset</Call>()
212.1017 - if <Name>dtoff</Name> is <Name>None</Name>:
212.1018 - raise <Call><Name>ValueError</Name></Call>("fromutc() requires a non-None utcoffset() "
212.1019 - "result")
212.1020 -
212.1021 - # See the long comment block at the end of this file for an
212.1022 - # explanation of this algorithm.
212.1023 - <Name>dtdst</Name> = <Attribute><Name>dt</Name></Attribute>.<Call>dst</Call>()
212.1024 - if <Name>dtdst</Name> is <Name>None</Name>:
212.1025 - raise <Call><Name>ValueError</Name></Call>("fromutc() requires a non-None dst() result")
212.1026 - <Name>delta</Name> = <Name>dtoff</Name> - <Name>dtdst</Name>
212.1027 - if <Name>delta</Name>:
212.1028 - <Name>dt</Name> += <Name>delta</Name>
212.1029 - <Name>dtdst</Name> = <Attribute><Name>dt</Name></Attribute>.<Call>dst</Call>()
212.1030 - if <Name>dtdst</Name> is <Name>None</Name>:
212.1031 - raise <Call><Name>ValueError</Name></Call>("fromutc(): dt.dst gave inconsistent "
212.1032 - "results; cannot convert")
212.1033 - if <Name>dtdst</Name>:
212.1034 - return <Name>dt</Name> + <Name>dtdst</Name>
212.1035 - else:
212.1036 - return <Name>dt</Name>
212.1037 -
212.1038 - # Pickle support.
212.1039 -
212.1040 - <Name>__safe_for_unpickling__</Name> = <Name>True</Name> # For Python 2.2
212.1041 -
212.1042 - def <FunctionDef>__reduce__</FunctionDef>(<Name>self</Name>):
212.1043 - <Name>getinitargs</Name> = <Call><Name>getattr</Name></Call>(<Name>self</Name>, "__getinitargs__", <Name>None</Name>)
212.1044 - if <Name>getinitargs</Name>:
212.1045 - <Name>args</Name> = <Call><Name>getinitargs</Name></Call>()
212.1046 - else:
212.1047 - <Name>args</Name> = ()
212.1048 - <Name>getstate</Name> = <Call><Name>getattr</Name></Call>(<Name>self</Name>, "__getstate__", <Name>None</Name>)
212.1049 - if <Name>getstate</Name>:
212.1050 - <Name>state</Name> = <Call><Name>getstate</Name></Call>()
212.1051 - else:
212.1052 - <Name>state</Name> = <Call><Name>getattr</Name></Call>(<Name>self</Name>, "__dict__", <Name>None</Name>) or <Name>None</Name>
212.1053 - if <Name>state</Name> is <Name>None</Name>:
212.1054 - return (<Attribute><Name>self</Name></Attribute>.__class__, <Name>args</Name>)
212.1055 - else:
212.1056 - return (<Attribute><Name>self</Name></Attribute>.__class__, <Name>args</Name>, <Name>state</Name>)
212.1057 -
212.1058 -<Name>_tzinfo_class</Name> = <Name>tzinfo</Name> # so functions w/ args named "tinfo" can get at it
212.1059 -
212.1060 -class <ClassDef>time</ClassDef>(<Name>object</Name>):
212.1061 - """Time with time zone.
212.1062 -
212.1063 - Constructors:
212.1064 -
212.1065 - __new__()
212.1066 -
212.1067 - Operators:
212.1068 -
212.1069 - __repr__, __str__
212.1070 - __cmp__, __hash__
212.1071 -
212.1072 - Methods:
212.1073 -
212.1074 - strftime()
212.1075 - isoformat()
212.1076 - utcoffset()
212.1077 - tzname()
212.1078 - dst()
212.1079 -
212.1080 - Properties (readonly):
212.1081 - hour, minute, second, microsecond, tzinfo
212.1082 - """
212.1083 -
212.1084 - def <FunctionDef>__new__</FunctionDef>(<Name>cls</Name>, <Name>hour</Name>=0, <Name>minute</Name>=0, <Name>second</Name>=0, <Name>microsecond</Name>=0, <Name>tzinfo</Name>=<Name>None</Name>):
212.1085 - """Constructor.
212.1086 -
212.1087 - Arguments:
212.1088 -
212.1089 - hour, minute (required)
212.1090 - second, microsecond (default to zero)
212.1091 - tzinfo (default to None)
212.1092 - """
212.1093 - <Name>self</Name> = <Attribute><Name>object</Name></Attribute>.<Call>__new__</Call>(<Name>cls</Name>)
212.1094 - if <Call><Name>isinstance</Name></Call>(<Name>hour</Name>, <Name>str</Name>):
212.1095 - # Pickle support
212.1096 - <Attribute><Name>self</Name></Attribute>.<Call>__setstate</Call>((<Name>hour</Name>, <Name>minute</Name> or <Name>None</Name>))
212.1097 - return <Name>self</Name>
212.1098 - <Call><Name>_check_tzinfo_arg</Name></Call>(<Name>tzinfo</Name>)
212.1099 - <Call><Name>_check_time_fields</Name></Call>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>)
212.1100 - <Attribute><Name>self</Name></Attribute>.__hour = <Name>hour</Name>
212.1101 - <Attribute><Name>self</Name></Attribute>.__minute = <Name>minute</Name>
212.1102 - <Attribute><Name>self</Name></Attribute>.__second = <Name>second</Name>
212.1103 - <Attribute><Name>self</Name></Attribute>.__microsecond = <Name>microsecond</Name>
212.1104 - <Attribute><Name>self</Name></Attribute>._tzinfo = <Name>tzinfo</Name>
212.1105 - return <Name>self</Name>
212.1106 -
212.1107 - # Read-only field accessors
212.1108 - <Name>hour</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__hour, doc="hour (0-23)")
212.1109 - <Name>minute</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__minute, doc="minute (0-59)")
212.1110 - <Name>second</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__second, doc="second (0-59)")
212.1111 - <Name>microsecond</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__microsecond,
212.1112 - doc="microsecond (0-999999)")
212.1113 - <Name>tzinfo</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>._tzinfo, doc="timezone info object")
212.1114 -
212.1115 - # Standard conversions, __hash__ (and helpers)
212.1116 -
212.1117 - # Comparisons.
212.1118 -
212.1119 - def <FunctionDef>__eq__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.1120 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>time</Name>):
212.1121 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) == 0
212.1122 - else:
212.1123 - return <Name>False</Name>
212.1124 -
212.1125 - def <FunctionDef>__ne__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.1126 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>time</Name>):
212.1127 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) != 0
212.1128 - else:
212.1129 - return <Name>True</Name>
212.1130 -
212.1131 - def <FunctionDef>__le__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.1132 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>time</Name>):
212.1133 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) <= 0
212.1134 - else:
212.1135 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
212.1136 -
212.1137 - def <FunctionDef>__lt__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.1138 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>time</Name>):
212.1139 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) < 0
212.1140 - else:
212.1141 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
212.1142 -
212.1143 - def <FunctionDef>__ge__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.1144 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>time</Name>):
212.1145 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) >= 0
212.1146 - else:
212.1147 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
212.1148 -
212.1149 - def <FunctionDef>__gt__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.1150 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>time</Name>):
212.1151 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) > 0
212.1152 - else:
212.1153 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
212.1154 -
212.1155 - def <FunctionDef>__cmp</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.1156 - assert <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>time</Name>)
212.1157 - <Name>mytz</Name> = <Attribute><Name>self</Name></Attribute>._tzinfo
212.1158 - <Name>ottz</Name> = <Attribute><Name>other</Name></Attribute>._tzinfo
212.1159 - <Name>myoff</Name> = <Name>otoff</Name> = <Name>None</Name>
212.1160 -
212.1161 - if <Name>mytz</Name> is <Name>ottz</Name>:
212.1162 - <Name>base_compare</Name> = <Name>True</Name>
212.1163 - else:
212.1164 - <Name>myoff</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_utcoffset</Call>()
212.1165 - <Name>otoff</Name> = <Attribute><Name>other</Name></Attribute>.<Call>_utcoffset</Call>()
212.1166 - <Name>base_compare</Name> = <Name>myoff</Name> == <Name>otoff</Name>
212.1167 -
212.1168 - if <Name>base_compare</Name>:
212.1169 - return <Call><Name>cmp</Name></Call>((<Attribute><Name>self</Name></Attribute>.__hour, <Attribute><Name>self</Name></Attribute>.__minute, <Attribute><Name>self</Name></Attribute>.__second,
212.1170 - <Attribute><Name>self</Name></Attribute>.__microsecond),
212.1171 - (<Attribute><Name>other</Name></Attribute>.__hour, <Attribute><Name>other</Name></Attribute>.__minute, <Attribute><Name>other</Name></Attribute>.__second,
212.1172 - <Attribute><Name>other</Name></Attribute>.__microsecond))
212.1173 - if <Name>myoff</Name> is <Name>None</Name> or <Name>otoff</Name> is <Name>None</Name>:
212.1174 - # XXX Buggy in 2.2.2.
212.1175 - raise <Call><Name>TypeError</Name></Call>("cannot compare naive and aware times")
212.1176 - <Name>myhhmm</Name> = <Attribute><Name>self</Name></Attribute>.__hour * 60 + <Attribute><Name>self</Name></Attribute>.__minute - <Name>myoff</Name>
212.1177 - <Name>othhmm</Name> = <Attribute><Name>other</Name></Attribute>.__hour * 60 + <Attribute><Name>other</Name></Attribute>.__minute - <Name>otoff</Name>
212.1178 - return <Call><Name>cmp</Name></Call>((<Name>myhhmm</Name>, <Attribute><Name>self</Name></Attribute>.__second, <Attribute><Name>self</Name></Attribute>.__microsecond),
212.1179 - (<Name>othhmm</Name>, <Attribute><Name>other</Name></Attribute>.__second, <Attribute><Name>other</Name></Attribute>.__microsecond))
212.1180 -
212.1181 - def <FunctionDef>__hash__</FunctionDef>(<Name>self</Name>):
212.1182 - """Hash."""
212.1183 - <Name>tzoff</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_utcoffset</Call>()
212.1184 - if not <Name>tzoff</Name>: # zero or None
212.1185 - return <Call><Name>hash</Name></Call>(<Attribute><Name>self</Name></Attribute>.<Call>__getstate</Call>()[0])
212.1186 - <Name>h</Name>, <Name>m</Name> = <Call><Name>divmod</Name></Call>(<Attribute><Name>self</Name></Attribute>.hour * 60 + <Attribute><Name>self</Name></Attribute>.minute - <Name>tzoff</Name>, 60)
212.1187 - if 0 <= <Name>h</Name> < 24:
212.1188 - return <Call><Name>hash</Name></Call>(<Call><Name>time</Name></Call>(<Name>h</Name>, <Name>m</Name>, <Attribute><Name>self</Name></Attribute>.second, <Attribute><Name>self</Name></Attribute>.microsecond))
212.1189 - return <Call><Name>hash</Name></Call>((<Name>h</Name>, <Name>m</Name>, <Attribute><Name>self</Name></Attribute>.second, <Attribute><Name>self</Name></Attribute>.microsecond))
212.1190 -
212.1191 - # Conversion to string
212.1192 -
212.1193 - def <FunctionDef>_tzstr</FunctionDef>(<Name>self</Name>, <Name>sep</Name>=":"):
212.1194 - """Return formatted timezone offset (+xx:xx) or None."""
212.1195 - <Name>off</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_utcoffset</Call>()
212.1196 - if <Name>off</Name> is not <Name>None</Name>:
212.1197 - if <Name>off</Name> < 0:
212.1198 - <Name>sign</Name> = "-"
212.1199 - <Name>off</Name> = -<Name>off</Name>
212.1200 - else:
212.1201 - <Name>sign</Name> = "+"
212.1202 - <Name>hh</Name>, <Name>mm</Name> = <Call><Name>divmod</Name></Call>(<Name>off</Name>, 60)
212.1203 - assert 0 <= <Name>hh</Name> < 24
212.1204 - <Name>off</Name> = "%s%02d%s%02d" % (<Name>sign</Name>, <Name>hh</Name>, <Name>sep</Name>, <Name>mm</Name>)
212.1205 - return <Name>off</Name>
212.1206 -
212.1207 - def <FunctionDef>__repr__</FunctionDef>(<Name>self</Name>):
212.1208 - """Convert to formal string, for repr()."""
212.1209 - if <Attribute><Name>self</Name></Attribute>.__microsecond != 0:
212.1210 - <Name>s</Name> = ", %d, %d" % (<Attribute><Name>self</Name></Attribute>.__second, <Attribute><Name>self</Name></Attribute>.__microsecond)
212.1211 - elif <Attribute><Name>self</Name></Attribute>.__second != 0:
212.1212 - <Name>s</Name> = ", %d" % <Attribute><Name>self</Name></Attribute>.__second
212.1213 - else:
212.1214 - <Name>s</Name> = ""
212.1215 - <Name>s</Name>= "%s(%d, %d%s)" % ('datetime.' + <Attribute><Attribute><Name>self</Name></Attribute></Attribute>.__class__.__name__,
212.1216 - <Attribute><Name>self</Name></Attribute>.__hour, <Attribute><Name>self</Name></Attribute>.__minute, <Name>s</Name>)
212.1217 - if <Attribute><Name>self</Name></Attribute>._tzinfo is not <Name>None</Name>:
212.1218 - assert <Name>s</Name>[-1:] == ")"
212.1219 - <Name>s</Name> = <Name>s</Name>[:-1] + ", tzinfo=%r" % <Attribute><Name>self</Name></Attribute>._tzinfo + ")"
212.1220 - return <Name>s</Name>
212.1221 -
212.1222 - def <FunctionDef>isoformat</FunctionDef>(<Name>self</Name>):
212.1223 - """Return the time formatted according to ISO.
212.1224 -
212.1225 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
212.1226 - self.microsecond == 0.
212.1227 - """
212.1228 - <Name>s</Name> = <Call><Name>_format_time</Name></Call>(<Attribute><Name>self</Name></Attribute>.__hour, <Attribute><Name>self</Name></Attribute>.__minute, <Attribute><Name>self</Name></Attribute>.__second,
212.1229 - <Attribute><Name>self</Name></Attribute>.__microsecond)
212.1230 - <Name>tz</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_tzstr</Call>()
212.1231 - if <Name>tz</Name>:
212.1232 - <Name>s</Name> += <Name>tz</Name>
212.1233 - return <Name>s</Name>
212.1234 -
212.1235 - <Name>__str__</Name> = <Name>isoformat</Name>
212.1236 -
212.1237 - def <FunctionDef>strftime</FunctionDef>(<Name>self</Name>, <Name>fmt</Name>):
212.1238 - """Format using strftime(). The date part of the timestamp passed
212.1239 - to underlying strftime should not be used.
212.1240 - """
212.1241 - # The year must be >= 1900 else Python's strftime implementation
212.1242 - # can raise a bogus exception.
212.1243 - <Name>timetuple</Name> = (1900, 1, 1,
212.1244 - <Attribute><Name>self</Name></Attribute>.__hour, <Attribute><Name>self</Name></Attribute>.__minute, <Attribute><Name>self</Name></Attribute>.__second,
212.1245 - 0, 1, -1)
212.1246 - return <Call><Name>_wrap_strftime</Name></Call>(<Name>self</Name>, <Name>fmt</Name>, <Name>timetuple</Name>)
212.1247 -
212.1248 - # Timezone functions
212.1249 -
212.1250 - def <FunctionDef>utcoffset</FunctionDef>(<Name>self</Name>):
212.1251 - """Return the timezone offset in minutes east of UTC (negative west of
212.1252 - UTC)."""
212.1253 - <Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "utcoffset", <Name>None</Name>)
212.1254 - <Name>offset</Name> = <Call><Name>_check_utc_offset</Name></Call>("utcoffset", <Name>offset</Name>)
212.1255 - if <Name>offset</Name> is not <Name>None</Name>:
212.1256 - <Name>offset</Name> = <Call><Name>timedelta</Name></Call>(minutes=<Name>offset</Name>)
212.1257 - return <Name>offset</Name>
212.1258 -
212.1259 - # Return an integer (or None) instead of a timedelta (or None).
212.1260 - def <FunctionDef>_utcoffset</FunctionDef>(<Name>self</Name>):
212.1261 - <Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "utcoffset", <Name>None</Name>)
212.1262 - <Name>offset</Name> = <Call><Name>_check_utc_offset</Name></Call>("utcoffset", <Name>offset</Name>)
212.1263 - return <Name>offset</Name>
212.1264 -
212.1265 - def <FunctionDef>tzname</FunctionDef>(<Name>self</Name>):
212.1266 - """Return the timezone name.
212.1267 -
212.1268 - Note that the name is 100% informational -- there's no requirement that
212.1269 - it mean anything in particular. For example, "GMT", "UTC", "-500",
212.1270 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
212.1271 - """
212.1272 - <Name>name</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "tzname", <Name>None</Name>)
212.1273 - <Call><Name>_check_tzname</Name></Call>(<Name>name</Name>)
212.1274 - return <Name>name</Name>
212.1275 -
212.1276 - def <FunctionDef>dst</FunctionDef>(<Name>self</Name>):
212.1277 - """Return 0 if DST is not in effect, or the DST offset (in minutes
212.1278 - eastward) if DST is in effect.
212.1279 -
212.1280 - This is purely informational; the DST offset has already been added to
212.1281 - the UTC offset returned by utcoffset() if applicable, so there's no
212.1282 - need to consult dst() unless you're interested in displaying the DST
212.1283 - info.
212.1284 - """
212.1285 - <Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "dst", <Name>None</Name>)
212.1286 - <Name>offset</Name> = <Call><Name>_check_utc_offset</Name></Call>("dst", <Name>offset</Name>)
212.1287 - if <Name>offset</Name> is not <Name>None</Name>:
212.1288 - <Name>offset</Name> = <Call><Name>timedelta</Name></Call>(minutes=<Name>offset</Name>)
212.1289 - return <Name>offset</Name>
212.1290 -
212.1291 - def <FunctionDef>replace</FunctionDef>(<Name>self</Name>, <Name>hour</Name>=<Name>None</Name>, <Name>minute</Name>=<Name>None</Name>, <Name>second</Name>=<Name>None</Name>, <Name>microsecond</Name>=<Name>None</Name>,
212.1292 - <Name>tzinfo</Name>=<Name>True</Name>):
212.1293 - """Return a new time with new values for the specified fields."""
212.1294 - if <Name>hour</Name> is <Name>None</Name>:
212.1295 - <Name>hour</Name> = <Attribute><Name>self</Name></Attribute>.hour
212.1296 - if <Name>minute</Name> is <Name>None</Name>:
212.1297 - <Name>minute</Name> = <Attribute><Name>self</Name></Attribute>.minute
212.1298 - if <Name>second</Name> is <Name>None</Name>:
212.1299 - <Name>second</Name> = <Attribute><Name>self</Name></Attribute>.second
212.1300 - if <Name>microsecond</Name> is <Name>None</Name>:
212.1301 - <Name>microsecond</Name> = <Attribute><Name>self</Name></Attribute>.microsecond
212.1302 - if <Name>tzinfo</Name> is <Name>True</Name>:
212.1303 - <Name>tzinfo</Name> = <Attribute><Name>self</Name></Attribute>.tzinfo
212.1304 - <Call><Name>_check_time_fields</Name></Call>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>)
212.1305 - <Call><Name>_check_tzinfo_arg</Name></Call>(<Name>tzinfo</Name>)
212.1306 - return <Call><Name>time</Name></Call>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>, <Name>tzinfo</Name>)
212.1307 -
212.1308 - # Return an integer (or None) instead of a timedelta (or None).
212.1309 - def <FunctionDef>_dst</FunctionDef>(<Name>self</Name>):
212.1310 - <Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "dst", <Name>None</Name>)
212.1311 - <Name>offset</Name> = <Call><Name>_check_utc_offset</Name></Call>("dst", <Name>offset</Name>)
212.1312 - return <Name>offset</Name>
212.1313 -
212.1314 - def <FunctionDef>__nonzero__</FunctionDef>(<Name>self</Name>):
212.1315 - if <Attribute><Name>self</Name></Attribute>.second or <Attribute><Name>self</Name></Attribute>.microsecond:
212.1316 - return 1
212.1317 - <Name>offset</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_utcoffset</Call>() or 0
212.1318 - return <Attribute><Name>self</Name></Attribute>.hour * 60 + <Attribute><Name>self</Name></Attribute>.minute - <Name>offset</Name> != 0
212.1319 -
212.1320 - # Pickle support.
212.1321 -
212.1322 - <Name>__safe_for_unpickling__</Name> = <Name>True</Name> # For Python 2.2
212.1323 -
212.1324 - def <FunctionDef>__getstate</FunctionDef>(<Name>self</Name>):
212.1325 - <Name>us2</Name>, <Name>us3</Name> = <Call><Name>divmod</Name></Call>(<Attribute><Name>self</Name></Attribute>.__microsecond, 256)
212.1326 - <Name>us1</Name>, <Name>us2</Name> = <Call><Name>divmod</Name></Call>(<Name>us2</Name>, 256)
212.1327 - <Name>basestate</Name> = ("%c" * 6) % (<Attribute><Name>self</Name></Attribute>.__hour, <Attribute><Name>self</Name></Attribute>.__minute, <Attribute><Name>self</Name></Attribute>.__second,
212.1328 - <Name>us1</Name>, <Name>us2</Name>, <Name>us3</Name>)
212.1329 - if <Attribute><Name>self</Name></Attribute>._tzinfo is <Name>None</Name>:
212.1330 - return (<Name>basestate</Name>,)
212.1331 - else:
212.1332 - return (<Name>basestate</Name>, <Attribute><Name>self</Name></Attribute>._tzinfo)
212.1333 -
212.1334 - def <FunctionDef>__setstate</FunctionDef>(<Name>self</Name>, <Name>state</Name>):
212.1335 - assert <Call><Name>isinstance</Name></Call>(<Name>state</Name>, <Name>tuple</Name>)
212.1336 - assert 1 <= <Call><Name>len</Name></Call>(<Name>state</Name>) <= 2
212.1337 - <Name>string</Name> = <Name>state</Name>[0]
212.1338 - assert <Call><Name>len</Name></Call>(<Name>string</Name>) == 6
212.1339 - <Attribute><Name>self</Name></Attribute>.__hour, <Attribute><Name>self</Name></Attribute>.__minute, <Attribute><Name>self</Name></Attribute>.__second, <Name>us1</Name>, <Name>us2</Name>, <Name>us3</Name> = \
212.1340 - <Call><Name>map</Name></Call>(<Name>ord</Name>, <Name>string</Name>)
212.1341 - <Attribute><Name>self</Name></Attribute>.__microsecond = (((<Name>us1</Name> << 8) | <Name>us2</Name>) << 8) | <Name>us3</Name>
212.1342 - if <Call><Name>len</Name></Call>(<Name>state</Name>) == 1:
212.1343 - <Attribute><Name>self</Name></Attribute>._tzinfo = <Name>None</Name>
212.1344 - else:
212.1345 - <Attribute><Name>self</Name></Attribute>._tzinfo = <Name>state</Name>[1]
212.1346 -
212.1347 - def <FunctionDef>__reduce__</FunctionDef>(<Name>self</Name>):
212.1348 - return (<Attribute><Name>self</Name></Attribute>.__class__, <Attribute><Name>self</Name></Attribute>.<Call>__getstate</Call>())
212.1349 -
212.1350 -<Name>_time_class</Name> = <Name>time</Name> # so functions w/ args named "time" can get at the class
212.1351 -
212.1352 -<Attribute><Name>time</Name></Attribute>.min = <Call><Name>time</Name></Call>(0, 0, 0)
212.1353 -<Attribute><Name>time</Name></Attribute>.max = <Call><Name>time</Name></Call>(23, 59, 59, 999999)
212.1354 -<Attribute><Name>time</Name></Attribute>.resolution = <Call><Name>timedelta</Name></Call>(microseconds=1)
212.1355 -
212.1356 -class <ClassDef>datetime</ClassDef>(<Name>date</Name>):
212.1357 -
212.1358 - # XXX needs docstrings
212.1359 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
212.1360 -
212.1361 - def <FunctionDef>__new__</FunctionDef>(<Name>cls</Name>, <Name>year</Name>, <Name>month</Name>=<Name>None</Name>, <Name>day</Name>=<Name>None</Name>, <Name>hour</Name>=0, <Name>minute</Name>=0, <Name>second</Name>=0,
212.1362 - <Name>microsecond</Name>=0, <Name>tzinfo</Name>=<Name>None</Name>):
212.1363 - if <Call><Name>isinstance</Name></Call>(<Name>year</Name>, <Name>str</Name>):
212.1364 - # Pickle support
212.1365 - <Name>self</Name> = <Attribute><Name>date</Name></Attribute>.<Call>__new__</Call>(<Name>cls</Name>, <Name>year</Name>[:4])
212.1366 - <Attribute><Name>self</Name></Attribute>.<Call>__setstate</Call>((<Name>year</Name>, <Name>month</Name>))
212.1367 - return <Name>self</Name>
212.1368 - <Call><Name>_check_tzinfo_arg</Name></Call>(<Name>tzinfo</Name>)
212.1369 - <Call><Name>_check_time_fields</Name></Call>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>)
212.1370 - <Name>self</Name> = <Attribute><Name>date</Name></Attribute>.<Call>__new__</Call>(<Name>cls</Name>, <Name>year</Name>, <Name>month</Name>, <Name>day</Name>)
212.1371 - # XXX This duplicates __year, __month, __day for convenience :-(
212.1372 - <Attribute><Name>self</Name></Attribute>.__year = <Name>year</Name>
212.1373 - <Attribute><Name>self</Name></Attribute>.__month = <Name>month</Name>
212.1374 - <Attribute><Name>self</Name></Attribute>.__day = <Name>day</Name>
212.1375 - <Attribute><Name>self</Name></Attribute>.__hour = <Name>hour</Name>
212.1376 - <Attribute><Name>self</Name></Attribute>.__minute = <Name>minute</Name>
212.1377 - <Attribute><Name>self</Name></Attribute>.__second = <Name>second</Name>
212.1378 - <Attribute><Name>self</Name></Attribute>.__microsecond = <Name>microsecond</Name>
212.1379 - <Attribute><Name>self</Name></Attribute>._tzinfo = <Name>tzinfo</Name>
212.1380 - return <Name>self</Name>
212.1381 -
212.1382 - # Read-only field accessors
212.1383 - <Name>hour</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__hour, doc="hour (0-23)")
212.1384 - <Name>minute</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__minute, doc="minute (0-59)")
212.1385 - <Name>second</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__second, doc="second (0-59)")
212.1386 - <Name>microsecond</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>.__microsecond,
212.1387 - doc="microsecond (0-999999)")
212.1388 - <Name>tzinfo</Name> = <Call><Name>property</Name></Call>(lambda <Name>self</Name>: <Attribute><Name>self</Name></Attribute>._tzinfo, doc="timezone info object")
212.1389 -
212.1390 - def <FunctionDef>fromtimestamp</FunctionDef>(<Name>cls</Name>, <Name>t</Name>, <Name>tz</Name>=<Name>None</Name>):
212.1391 - """Construct a datetime from a POSIX timestamp (like time.time()).
212.1392 -
212.1393 - A timezone info object may be passed in as well.
212.1394 - """
212.1395 -
212.1396 - <Call><Name>_check_tzinfo_arg</Name></Call>(<Name>tz</Name>)
212.1397 - if <Name>tz</Name> is <Name>None</Name>:
212.1398 - <Name>converter</Name> = <Attribute><Name>_time</Name></Attribute>.localtime
212.1399 - else:
212.1400 - <Name>converter</Name> = <Attribute><Name>_time</Name></Attribute>.gmtime
212.1401 - <Name>y</Name>, <Name>m</Name>, <Name>d</Name>, <Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Name>weekday</Name>, <Name>jday</Name>, <Name>dst</Name> = <Call><Name>converter</Name></Call>(<Name>t</Name>)
212.1402 - <Name>us</Name> = <Call><Name>int</Name></Call>((<Name>t</Name> % 1.0) * 1000000)
212.1403 - <Name>ss</Name> = <Call><Name>min</Name></Call>(<Name>ss</Name>, 59) # clamp out leap seconds if the platform has them
212.1404 - <Name>result</Name> = <Call><Name>cls</Name></Call>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>, <Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Name>us</Name>, <Name>tz</Name>)
212.1405 - if <Name>tz</Name> is not <Name>None</Name>:
212.1406 - <Name>result</Name> = <Attribute><Name>tz</Name></Attribute>.<Call>fromutc</Call>(<Name>result</Name>)
212.1407 - return <Name>result</Name>
212.1408 - <Name>fromtimestamp</Name> = <Call><Name>classmethod</Name></Call>(<Name>fromtimestamp</Name>)
212.1409 -
212.1410 - def <FunctionDef>utcfromtimestamp</FunctionDef>(<Name>cls</Name>, <Name>t</Name>):
212.1411 - "Construct a UTC datetime from a POSIX timestamp (like time.time())."
212.1412 - <Name>y</Name>, <Name>m</Name>, <Name>d</Name>, <Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Name>weekday</Name>, <Name>jday</Name>, <Name>dst</Name> = <Attribute><Name>_time</Name></Attribute>.<Call>gmtime</Call>(<Name>t</Name>)
212.1413 - <Name>us</Name> = <Call><Name>int</Name></Call>((<Name>t</Name> % 1.0) * 1000000)
212.1414 - <Name>ss</Name> = <Call><Name>min</Name></Call>(<Name>ss</Name>, 59) # clamp out leap seconds if the platform has them
212.1415 - return <Call><Name>cls</Name></Call>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>, <Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Name>us</Name>)
212.1416 - <Name>utcfromtimestamp</Name> = <Call><Name>classmethod</Name></Call>(<Name>utcfromtimestamp</Name>)
212.1417 -
212.1418 - # XXX This is supposed to do better than we *can* do by using time.time(),
212.1419 - # XXX if the platform supports a more accurate way. The C implementation
212.1420 - # XXX uses gettimeofday on platforms that have it, but that isn't
212.1421 - # XXX available from Python. So now() may return different results
212.1422 - # XXX across the implementations.
212.1423 - def <FunctionDef>now</FunctionDef>(<Name>cls</Name>, <Name>tz</Name>=<Name>None</Name>):
212.1424 - "Construct a datetime from time.time() and optional time zone info."
212.1425 - <Name>t</Name> = <Attribute><Name>_time</Name></Attribute>.<Call>time</Call>()
212.1426 - return <Attribute><Name>cls</Name></Attribute>.<Call>fromtimestamp</Call>(<Name>t</Name>, <Name>tz</Name>)
212.1427 - <Name>now</Name> = <Call><Name>classmethod</Name></Call>(<Name>now</Name>)
212.1428 -
212.1429 - def <FunctionDef>utcnow</FunctionDef>(<Name>cls</Name>):
212.1430 - "Construct a UTC datetime from time.time()."
212.1431 - <Name>t</Name> = <Attribute><Name>_time</Name></Attribute>.<Call>time</Call>()
212.1432 - return <Attribute><Name>cls</Name></Attribute>.<Call>utcfromtimestamp</Call>(<Name>t</Name>)
212.1433 - <Name>utcnow</Name> = <Call><Name>classmethod</Name></Call>(<Name>utcnow</Name>)
212.1434 -
212.1435 - def <FunctionDef>combine</FunctionDef>(<Name>cls</Name>, <Name>date</Name>, <Name>time</Name>):
212.1436 - "Construct a datetime from a given date and a given time."
212.1437 - if not <Call><Name>isinstance</Name></Call>(<Name>date</Name>, <Name>_date_class</Name>):
212.1438 - raise <Call><Name>TypeError</Name></Call>("date argument must be a date instance")
212.1439 - if not <Call><Name>isinstance</Name></Call>(<Name>time</Name>, <Name>_time_class</Name>):
212.1440 - raise <Call><Name>TypeError</Name></Call>("time argument must be a time instance")
212.1441 - return <Call><Name>cls</Name></Call>(<Attribute><Name>date</Name></Attribute>.year, <Attribute><Name>date</Name></Attribute>.month, <Attribute><Name>date</Name></Attribute>.day,
212.1442 - <Attribute><Name>time</Name></Attribute>.hour, <Attribute><Name>time</Name></Attribute>.minute, <Attribute><Name>time</Name></Attribute>.second, <Attribute><Name>time</Name></Attribute>.microsecond,
212.1443 - <Attribute><Name>time</Name></Attribute>.tzinfo)
212.1444 - <Name>combine</Name> = <Call><Name>classmethod</Name></Call>(<Name>combine</Name>)
212.1445 -
212.1446 - def <FunctionDef>timetuple</FunctionDef>(<Name>self</Name>):
212.1447 - "Return local time tuple compatible with time.localtime()."
212.1448 - <Name>dst</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_dst</Call>()
212.1449 - if <Name>dst</Name> is <Name>None</Name>:
212.1450 - <Name>dst</Name> = -1
212.1451 - elif <Name>dst</Name>:
212.1452 - <Name>dst</Name> = 1
212.1453 - return <Call><Name>_build_struct_time</Name></Call>(<Attribute><Name>self</Name></Attribute>.year, <Attribute><Name>self</Name></Attribute>.month, <Attribute><Name>self</Name></Attribute>.day,
212.1454 - <Attribute><Name>self</Name></Attribute>.hour, <Attribute><Name>self</Name></Attribute>.minute, <Attribute><Name>self</Name></Attribute>.second,
212.1455 - <Name>dst</Name>)
212.1456 -
212.1457 - def <FunctionDef>utctimetuple</FunctionDef>(<Name>self</Name>):
212.1458 - "Return UTC time tuple compatible with time.gmtime()."
212.1459 - <Name>y</Name>, <Name>m</Name>, <Name>d</Name> = <Attribute><Name>self</Name></Attribute>.year, <Attribute><Name>self</Name></Attribute>.month, <Attribute><Name>self</Name></Attribute>.day
212.1460 - <Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name> = <Attribute><Name>self</Name></Attribute>.hour, <Attribute><Name>self</Name></Attribute>.minute, <Attribute><Name>self</Name></Attribute>.second
212.1461 - <Name>offset</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_utcoffset</Call>()
212.1462 - if <Name>offset</Name>: # neither None nor 0
212.1463 - <Name>tm</Name> = <Call><Name>tmxxx</Name></Call>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>, <Name>hh</Name>, <Name>mm</Name> - <Name>offset</Name>)
212.1464 - <Name>y</Name>, <Name>m</Name>, <Name>d</Name> = <Attribute><Name>tm</Name></Attribute>.year, <Attribute><Name>tm</Name></Attribute>.month, <Attribute><Name>tm</Name></Attribute>.day
212.1465 - <Name>hh</Name>, <Name>mm</Name> = <Attribute><Name>tm</Name></Attribute>.hour, <Attribute><Name>tm</Name></Attribute>.minute
212.1466 - return <Call><Name>_build_struct_time</Name></Call>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>, <Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, 0)
212.1467 -
212.1468 - def <FunctionDef>date</FunctionDef>(<Name>self</Name>):
212.1469 - "Return the date part."
212.1470 - return <Call><Name>date</Name></Call>(<Attribute><Name>self</Name></Attribute>.__year, <Attribute><Name>self</Name></Attribute>.__month, <Attribute><Name>self</Name></Attribute>.__day)
212.1471 -
212.1472 - def <FunctionDef>time</FunctionDef>(<Name>self</Name>):
212.1473 - "Return the time part, with tzinfo None."
212.1474 - return <Call><Name>time</Name></Call>(<Attribute><Name>self</Name></Attribute>.hour, <Attribute><Name>self</Name></Attribute>.minute, <Attribute><Name>self</Name></Attribute>.second, <Attribute><Name>self</Name></Attribute>.microsecond)
212.1475 -
212.1476 - def <FunctionDef>timetz</FunctionDef>(<Name>self</Name>):
212.1477 - "Return the time part, with same tzinfo."
212.1478 - return <Call><Name>time</Name></Call>(<Attribute><Name>self</Name></Attribute>.hour, <Attribute><Name>self</Name></Attribute>.minute, <Attribute><Name>self</Name></Attribute>.second, <Attribute><Name>self</Name></Attribute>.microsecond,
212.1479 - <Attribute><Name>self</Name></Attribute>._tzinfo)
212.1480 -
212.1481 - def <FunctionDef>replace</FunctionDef>(<Name>self</Name>, <Name>year</Name>=<Name>None</Name>, <Name>month</Name>=<Name>None</Name>, <Name>day</Name>=<Name>None</Name>, <Name>hour</Name>=<Name>None</Name>,
212.1482 - <Name>minute</Name>=<Name>None</Name>, <Name>second</Name>=<Name>None</Name>, <Name>microsecond</Name>=<Name>None</Name>, <Name>tzinfo</Name>=<Name>True</Name>):
212.1483 - """Return a new datetime with new values for the specified fields."""
212.1484 - if <Name>year</Name> is <Name>None</Name>:
212.1485 - <Name>year</Name> = <Attribute><Name>self</Name></Attribute>.year
212.1486 - if <Name>month</Name> is <Name>None</Name>:
212.1487 - <Name>month</Name> = <Attribute><Name>self</Name></Attribute>.month
212.1488 - if <Name>day</Name> is <Name>None</Name>:
212.1489 - <Name>day</Name> = <Attribute><Name>self</Name></Attribute>.day
212.1490 - if <Name>hour</Name> is <Name>None</Name>:
212.1491 - <Name>hour</Name> = <Attribute><Name>self</Name></Attribute>.hour
212.1492 - if <Name>minute</Name> is <Name>None</Name>:
212.1493 - <Name>minute</Name> = <Attribute><Name>self</Name></Attribute>.minute
212.1494 - if <Name>second</Name> is <Name>None</Name>:
212.1495 - <Name>second</Name> = <Attribute><Name>self</Name></Attribute>.second
212.1496 - if <Name>microsecond</Name> is <Name>None</Name>:
212.1497 - <Name>microsecond</Name> = <Attribute><Name>self</Name></Attribute>.microsecond
212.1498 - if <Name>tzinfo</Name> is <Name>True</Name>:
212.1499 - <Name>tzinfo</Name> = <Attribute><Name>self</Name></Attribute>.tzinfo
212.1500 - <Call><Name>_check_date_fields</Name></Call>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>)
212.1501 - <Call><Name>_check_time_fields</Name></Call>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>)
212.1502 - <Call><Name>_check_tzinfo_arg</Name></Call>(<Name>tzinfo</Name>)
212.1503 - return <Call><Name>datetime</Name></Call>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>, <Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>,
212.1504 - <Name>microsecond</Name>, <Name>tzinfo</Name>)
212.1505 -
212.1506 - def <FunctionDef>astimezone</FunctionDef>(<Name>self</Name>, <Name>tz</Name>):
212.1507 - if not <Call><Name>isinstance</Name></Call>(<Name>tz</Name>, <Name>tzinfo</Name>):
212.1508 - raise <Call><Name>TypeError</Name></Call>("tz argument must be an instance of tzinfo")
212.1509 -
212.1510 - <Name>mytz</Name> = <Attribute><Name>self</Name></Attribute>.tzinfo
212.1511 - if <Name>mytz</Name> is <Name>None</Name>:
212.1512 - raise <Call><Name>ValueError</Name></Call>("astimezone() requires an aware datetime")
212.1513 -
212.1514 - if <Name>tz</Name> is <Name>mytz</Name>:
212.1515 - return <Name>self</Name>
212.1516 -
212.1517 - # Convert self to UTC, and attach the new time zone object.
212.1518 - <Name>myoffset</Name> = <Attribute><Name>self</Name></Attribute>.<Call>utcoffset</Call>()
212.1519 - if <Name>myoffset</Name> is <Name>None</Name>:
212.1520 - raise <Call><Name>ValuError</Name></Call>("astimezone() requires an aware datetime")
212.1521 - <Name>utc</Name> = <Attribute>(<Name>self</Name> - <Name>myoffset</Name>)</Attribute>.<Call>replace</Call>(tzinfo=<Name>tz</Name>)
212.1522 -
212.1523 - # Convert from UTC to tz's local time.
212.1524 - return <Attribute><Name>tz</Name></Attribute>.<Call>fromutc</Call>(<Name>utc</Name>)
212.1525 -
212.1526 - # Ways to produce a string.
212.1527 -
212.1528 - def <FunctionDef>ctime</FunctionDef>(<Name>self</Name>):
212.1529 - "Format a la ctime()."
212.1530 - <Name>t</Name> = <Call><Name>tmxxx</Name></Call>(<Attribute><Name>self</Name></Attribute>.__year, <Attribute><Name>self</Name></Attribute>.__month, <Attribute><Name>self</Name></Attribute>.__day, <Attribute><Name>self</Name></Attribute>.__hour,
212.1531 - <Attribute><Name>self</Name></Attribute>.__minute, <Attribute><Name>self</Name></Attribute>.__second)
212.1532 - return <Attribute><Name>t</Name></Attribute>.<Call>ctime</Call>()
212.1533 -
212.1534 - def <FunctionDef>isoformat</FunctionDef>(<Name>self</Name>, <Name>sep</Name>='T'):
212.1535 - """Return the time formatted according to ISO.
212.1536 -
212.1537 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
212.1538 - self.microsecond == 0.
212.1539 -
212.1540 - If self.tzinfo is not None, the UTC offset is also attached, giving
212.1541 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
212.1542 -
212.1543 - Optional argument sep specifies the separator between date and
212.1544 - time, default 'T'.
212.1545 - """
212.1546 - <Name>s</Name> = ("%04d-%02d-%02d%c" % (<Attribute><Name>self</Name></Attribute>.__year, <Attribute><Name>self</Name></Attribute>.__month, <Attribute><Name>self</Name></Attribute>.__day,
212.1547 - <Name>sep</Name>) +
212.1548 - <Call><Name>_format_time</Name></Call>(<Attribute><Name>self</Name></Attribute>.__hour, <Attribute><Name>self</Name></Attribute>.__minute, <Attribute><Name>self</Name></Attribute>.__second,
212.1549 - <Attribute><Name>self</Name></Attribute>.__microsecond))
212.1550 - <Name>off</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_utcoffset</Call>()
212.1551 - if <Name>off</Name> is not <Name>None</Name>:
212.1552 - if <Name>off</Name> < 0:
212.1553 - <Name>sign</Name> = "-"
212.1554 - <Name>off</Name> = -<Name>off</Name>
212.1555 - else:
212.1556 - <Name>sign</Name> = "+"
212.1557 - <Name>hh</Name>, <Name>mm</Name> = <Call><Name>divmod</Name></Call>(<Name>off</Name>, 60)
212.1558 - <Name>s</Name> += "%s%02d:%02d" % (<Name>sign</Name>, <Name>hh</Name>, <Name>mm</Name>)
212.1559 - return <Name>s</Name>
212.1560 -
212.1561 - def <FunctionDef>__repr__</FunctionDef>(<Name>self</Name>):
212.1562 - "Convert to formal string, for repr()."
212.1563 - <Name>L</Name> = [<Attribute><Name>self</Name></Attribute>.__year, <Attribute><Name>self</Name></Attribute>.__month, <Attribute><Name>self</Name></Attribute>.__day, # These are never zero
212.1564 - <Attribute><Name>self</Name></Attribute>.__hour, <Attribute><Name>self</Name></Attribute>.__minute, <Attribute><Name>self</Name></Attribute>.__second, <Attribute><Name>self</Name></Attribute>.__microsecond]
212.1565 - if <Name>L</Name>[-1] == 0:
212.1566 - del <Name>L</Name>[-1]
212.1567 - if <Name>L</Name>[-1] == 0:
212.1568 - del <Name>L</Name>[-1]
212.1569 - <Name>s</Name> = <Attribute>", "</Attribute>.<Call>join</Call>(<Call><Name>map</Name></Call>(<Name>str</Name>, <Name>L</Name>))
212.1570 - <Name>s</Name> = "%s(%s)" % ('datetime.' + <Attribute><Attribute><Name>self</Name></Attribute></Attribute>.__class__.__name__, <Name>s</Name>)
212.1571 - if <Attribute><Name>self</Name></Attribute>._tzinfo is not <Name>None</Name>:
212.1572 - assert <Name>s</Name>[-1:] == ")"
212.1573 - <Name>s</Name> = <Name>s</Name>[:-1] + ", tzinfo=%r" % <Attribute><Name>self</Name></Attribute>._tzinfo + ")"
212.1574 - return <Name>s</Name>
212.1575 -
212.1576 - def <FunctionDef>__str__</FunctionDef>(<Name>self</Name>):
212.1577 - "Convert to string, for str()."
212.1578 - return <Attribute><Name>self</Name></Attribute>.<Call>isoformat</Call>(sep=' ')
212.1579 -
212.1580 - def <FunctionDef>utcoffset</FunctionDef>(<Name>self</Name>):
212.1581 - """Return the timezone offset in minutes east of UTC (negative west of
212.1582 - UTC)."""
212.1583 - <Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "utcoffset", <Name>self</Name>)
212.1584 - <Name>offset</Name> = <Call><Name>_check_utc_offset</Name></Call>("utcoffset", <Name>offset</Name>)
212.1585 - if <Name>offset</Name> is not <Name>None</Name>:
212.1586 - <Name>offset</Name> = <Call><Name>timedelta</Name></Call>(minutes=<Name>offset</Name>)
212.1587 - return <Name>offset</Name>
212.1588 -
212.1589 - # Return an integer (or None) instead of a timedelta (or None).
212.1590 - def <FunctionDef>_utcoffset</FunctionDef>(<Name>self</Name>):
212.1591 - <Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "utcoffset", <Name>self</Name>)
212.1592 - <Name>offset</Name> = <Call><Name>_check_utc_offset</Name></Call>("utcoffset", <Name>offset</Name>)
212.1593 - return <Name>offset</Name>
212.1594 -
212.1595 - def <FunctionDef>tzname</FunctionDef>(<Name>self</Name>):
212.1596 - """Return the timezone name.
212.1597 -
212.1598 - Note that the name is 100% informational -- there's no requirement that
212.1599 - it mean anything in particular. For example, "GMT", "UTC", "-500",
212.1600 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
212.1601 - """
212.1602 - <Name>name</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "tzname", <Name>self</Name>)
212.1603 - <Call><Name>_check_tzname</Name></Call>(<Name>name</Name>)
212.1604 - return <Name>name</Name>
212.1605 -
212.1606 - def <FunctionDef>dst</FunctionDef>(<Name>self</Name>):
212.1607 - """Return 0 if DST is not in effect, or the DST offset (in minutes
212.1608 - eastward) if DST is in effect.
212.1609 -
212.1610 - This is purely informational; the DST offset has already been added to
212.1611 - the UTC offset returned by utcoffset() if applicable, so there's no
212.1612 - need to consult dst() unless you're interested in displaying the DST
212.1613 - info.
212.1614 - """
212.1615 - <Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "dst", <Name>self</Name>)
212.1616 - <Name>offset</Name> = <Call><Name>_check_utc_offset</Name></Call>("dst", <Name>offset</Name>)
212.1617 - if <Name>offset</Name> is not <Name>None</Name>:
212.1618 - <Name>offset</Name> = <Call><Name>timedelta</Name></Call>(minutes=<Name>offset</Name>)
212.1619 - return <Name>offset</Name>
212.1620 -
212.1621 - # Return an integer (or None) instead of a timedelta (or None).1573
212.1622 - def <FunctionDef>_dst</FunctionDef>(<Name>self</Name>):
212.1623 - <Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name></Call>(<Attribute><Name>self</Name></Attribute>._tzinfo, "dst", <Name>self</Name>)
212.1624 - <Name>offset</Name> = <Call><Name>_check_utc_offset</Name></Call>("dst", <Name>offset</Name>)
212.1625 - return <Name>offset</Name>
212.1626 -
212.1627 - # Comparisons.
212.1628 -
212.1629 - def <FunctionDef>__eq__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.1630 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>datetime</Name>):
212.1631 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) == 0
212.1632 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
212.1633 - return <Name>NotImplemented</Name>
212.1634 - else:
212.1635 - return <Name>False</Name>
212.1636 -
212.1637 - def <FunctionDef>__ne__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.1638 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>datetime</Name>):
212.1639 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) != 0
212.1640 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
212.1641 - return <Name>NotImplemented</Name>
212.1642 - else:
212.1643 - return <Name>True</Name>
212.1644 -
212.1645 - def <FunctionDef>__le__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.1646 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>datetime</Name>):
212.1647 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) <= 0
212.1648 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
212.1649 - return <Name>NotImplemented</Name>
212.1650 - else:
212.1651 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
212.1652 -
212.1653 - def <FunctionDef>__lt__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.1654 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>datetime</Name>):
212.1655 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) < 0
212.1656 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
212.1657 - return <Name>NotImplemented</Name>
212.1658 - else:
212.1659 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
212.1660 -
212.1661 - def <FunctionDef>__ge__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.1662 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>datetime</Name>):
212.1663 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) >= 0
212.1664 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
212.1665 - return <Name>NotImplemented</Name>
212.1666 - else:
212.1667 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
212.1668 -
212.1669 - def <FunctionDef>__gt__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.1670 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>datetime</Name>):
212.1671 - return <Attribute><Name>self</Name></Attribute>.<Call>__cmp</Call>(<Name>other</Name>) > 0
212.1672 - elif <Call><Name>hasattr</Name></Call>(<Name>other</Name>, "timetuple"):
212.1673 - return <Name>NotImplemented</Name>
212.1674 - else:
212.1675 - <Call><Name>_cmperror</Name></Call>(<Name>self</Name>, <Name>other</Name>)
212.1676 -
212.1677 - def <FunctionDef>__cmp</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.1678 - assert <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>datetime</Name>)
212.1679 - <Name>mytz</Name> = <Attribute><Name>self</Name></Attribute>._tzinfo
212.1680 - <Name>ottz</Name> = <Attribute><Name>other</Name></Attribute>._tzinfo
212.1681 - <Name>myoff</Name> = <Name>otoff</Name> = <Name>None</Name>
212.1682 -
212.1683 - if <Name>mytz</Name> is <Name>ottz</Name>:
212.1684 - <Name>base_compare</Name> = <Name>True</Name>
212.1685 - else:
212.1686 - if <Name>mytz</Name> is not <Name>None</Name>:
212.1687 - <Name>myoff</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_utcoffset</Call>()
212.1688 - if <Name>ottz</Name> is not <Name>None</Name>:
212.1689 - <Name>otoff</Name> = <Attribute><Name>other</Name></Attribute>.<Call>_utcoffset</Call>()
212.1690 - <Name>base_compare</Name> = <Name>myoff</Name> == <Name>otoff</Name>
212.1691 -
212.1692 - if <Name>base_compare</Name>:
212.1693 - return <Call><Name>cmp</Name></Call>((<Attribute><Name>self</Name></Attribute>.__year, <Attribute><Name>self</Name></Attribute>.__month, <Attribute><Name>self</Name></Attribute>.__day,
212.1694 - <Attribute><Name>self</Name></Attribute>.__hour, <Attribute><Name>self</Name></Attribute>.__minute, <Attribute><Name>self</Name></Attribute>.__second,
212.1695 - <Attribute><Name>self</Name></Attribute>.__microsecond),
212.1696 - (<Attribute><Name>other</Name></Attribute>.__year, <Attribute><Name>other</Name></Attribute>.__month, <Attribute><Name>other</Name></Attribute>.__day,
212.1697 - <Attribute><Name>other</Name></Attribute>.__hour, <Attribute><Name>other</Name></Attribute>.__minute, <Attribute><Name>other</Name></Attribute>.__second,
212.1698 - <Attribute><Name>other</Name></Attribute>.__microsecond))
212.1699 - if <Name>myoff</Name> is <Name>None</Name> or <Name>otoff</Name> is <Name>None</Name>:
212.1700 - # XXX Buggy in 2.2.2.
212.1701 - raise <Call><Name>TypeError</Name></Call>("cannot compare naive and aware datetimes")
212.1702 - # XXX What follows could be done more efficiently...
212.1703 - <Name>diff</Name> = <Name>self</Name> - <Name>other</Name> # this will take offsets into account
212.1704 - if <Attribute><Name>diff</Name></Attribute>.days < 0:
212.1705 - return -1
212.1706 - return <Name>diff</Name> and 1 or 0
212.1707 -
212.1708 - def <FunctionDef>__add__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.1709 - "Add a datetime and a timedelta."
212.1710 - if not <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
212.1711 - return <Name>NotImplemented</Name>
212.1712 - <Name>t</Name> = <Call><Name>tmxxx</Name></Call>(<Attribute><Name>self</Name></Attribute>.__year,
212.1713 - <Attribute><Name>self</Name></Attribute>.__month,
212.1714 - <Attribute><Name>self</Name></Attribute>.__day + <Attribute><Name>other</Name></Attribute>.days,
212.1715 - <Attribute><Name>self</Name></Attribute>.__hour,
212.1716 - <Attribute><Name>self</Name></Attribute>.__minute,
212.1717 - <Attribute><Name>self</Name></Attribute>.__second + <Attribute><Name>other</Name></Attribute>.seconds,
212.1718 - <Attribute><Name>self</Name></Attribute>.__microsecond + <Attribute><Name>other</Name></Attribute>.microseconds)
212.1719 - <Attribute><Name>self</Name></Attribute>.<Call>_checkOverflow</Call>(<Attribute><Name>t</Name></Attribute>.year)
212.1720 - <Name>result</Name> = <Attribute><Name>self</Name></Attribute>.<Call>__class__</Call>(<Attribute><Name>t</Name></Attribute>.year, <Attribute><Name>t</Name></Attribute>.month, <Attribute><Name>t</Name></Attribute>.day,
212.1721 - <Attribute><Name>t</Name></Attribute>.hour, <Attribute><Name>t</Name></Attribute>.minute, <Attribute><Name>t</Name></Attribute>.second,
212.1722 - <Attribute><Name>t</Name></Attribute>.microsecond, tzinfo=<Attribute><Name>self</Name></Attribute>._tzinfo)
212.1723 - return <Name>result</Name>
212.1724 -
212.1725 - <Name>__radd__</Name> = <Name>__add__</Name>
212.1726 -
212.1727 - def <FunctionDef>__sub__</FunctionDef>(<Name>self</Name>, <Name>other</Name>):
212.1728 - "Subtract two datetimes, or a datetime and a timedelta."
212.1729 - if not <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>datetime</Name>):
212.1730 - if <Call><Name>isinstance</Name></Call>(<Name>other</Name>, <Name>timedelta</Name>):
212.1731 - return <Name>self</Name> + -<Name>other</Name>
212.1732 - return <Name>NotImplemented</Name>
212.1733 -
212.1734 - <Name>days1</Name> = <Attribute><Name>self</Name></Attribute>.<Call>toordinal</Call>()
212.1735 - <Name>days2</Name> = <Attribute><Name>other</Name></Attribute>.<Call>toordinal</Call>()
212.1736 - <Name>secs1</Name> = <Attribute><Name>self</Name></Attribute>.__second + <Attribute><Name>self</Name></Attribute>.__minute * 60 + <Attribute><Name>self</Name></Attribute>.__hour * 3600
212.1737 - <Name>secs2</Name> = <Attribute><Name>other</Name></Attribute>.__second + <Attribute><Name>other</Name></Attribute>.__minute * 60 + <Attribute><Name>other</Name></Attribute>.__hour * 3600
212.1738 - <Name>base</Name> = <Call><Name>timedelta</Name></Call>(<Name>days1</Name> - <Name>days2</Name>,
212.1739 - <Name>secs1</Name> - <Name>secs2</Name>,
212.1740 - <Attribute><Name>self</Name></Attribute>.__microsecond - <Attribute><Name>other</Name></Attribute>.__microsecond)
212.1741 - if <Attribute><Name>self</Name></Attribute>._tzinfo is <Attribute><Name>other</Name></Attribute>._tzinfo:
212.1742 - return <Name>base</Name>
212.1743 - <Name>myoff</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_utcoffset</Call>()
212.1744 - <Name>otoff</Name> = <Attribute><Name>other</Name></Attribute>.<Call>_utcoffset</Call>()
212.1745 - if <Name>myoff</Name> == <Name>otoff</Name>:
212.1746 - return <Name>base</Name>
212.1747 - if <Name>myoff</Name> is <Name>None</Name> or <Name>otoff</Name> is <Name>None</Name>:
212.1748 - raise <Name>TypeError</Name>, "cannot mix naive and timezone-aware time"
212.1749 - return <Name>base</Name> + <Call><Name>timedelta</Name></Call>(minutes = <Name>otoff</Name>-<Name>myoff</Name>)
212.1750 -
212.1751 - def <FunctionDef>__hash__</FunctionDef>(<Name>self</Name>):
212.1752 - <Name>tzoff</Name> = <Attribute><Name>self</Name></Attribute>.<Call>_utcoffset</Call>()
212.1753 - if <Name>tzoff</Name> is <Name>None</Name>:
212.1754 - return <Call><Name>hash</Name></Call>(<Attribute><Name>self</Name></Attribute>.<Call>__getstate</Call>()[0])
212.1755 - <Name>days</Name> = <Call><Name>_ymd2ord</Name></Call>(<Attribute><Name>self</Name></Attribute>.year, <Attribute><Name>self</Name></Attribute>.month, <Attribute><Name>self</Name></Attribute>.day)
212.1756 - <Name>seconds</Name> = <Attribute><Name>self</Name></Attribute>.hour * 3600 + (<Attribute><Name>self</Name></Attribute>.minute - <Name>tzoff</Name>) * 60 + <Attribute><Name>self</Name></Attribute>.second
212.1757 - return <Call><Name>hash</Name></Call>(<Call><Name>timedelta</Name></Call>(<Name>days</Name>, <Name>seconds</Name>, <Attribute><Name>self</Name></Attribute>.microsecond))
212.1758 -
212.1759 - # Pickle support.
212.1760 -
212.1761 - <Name>__safe_for_unpickling__</Name> = <Name>True</Name> # For Python 2.2
212.1762 -
212.1763 - def <FunctionDef>__getstate</FunctionDef>(<Name>self</Name>):
212.1764 - <Name>yhi</Name>, <Name>ylo</Name> = <Call><Name>divmod</Name></Call>(<Attribute><Name>self</Name></Attribute>.__year, 256)
212.1765 - <Name>us2</Name>, <Name>us3</Name> = <Call><Name>divmod</Name></Call>(<Attribute><Name>self</Name></Attribute>.__microsecond, 256)
212.1766 - <Name>us1</Name>, <Name>us2</Name> = <Call><Name>divmod</Name></Call>(<Name>us2</Name>, 256)
212.1767 - <Name>basestate</Name> = ("%c" * 10) % (<Name>yhi</Name>, <Name>ylo</Name>, <Attribute><Name>self</Name></Attribute>.__month, <Attribute><Name>self</Name></Attribute>.__day,
212.1768 - <Attribute><Name>self</Name></Attribute>.__hour, <Attribute><Name>self</Name></Attribute>.__minute, <Attribute><Name>self</Name></Attribute>.__second,
212.1769 - <Name>us1</Name>, <Name>us2</Name>, <Name>us3</Name>)
212.1770 - if <Attribute><Name>self</Name></Attribute>._tzinfo is <Name>None</Name>:
212.1771 - return (<Name>basestate</Name>,)
212.1772 - else:
212.1773 - return (<Name>basestate</Name>, <Attribute><Name>self</Name></Attribute>._tzinfo)
212.1774 -
212.1775 - def <FunctionDef>__setstate</FunctionDef>(<Name>self</Name>, <Name>state</Name>):
212.1776 - assert <Call><Name>isinstance</Name></Call>(<Name>state</Name>, <Name>tuple</Name>)
212.1777 - assert 1 <= <Call><Name>len</Name></Call>(<Name>state</Name>) <= 2
212.1778 - <Name>string</Name> = <Name>state</Name>[0]
212.1779 - assert <Call><Name>len</Name></Call>(<Name>string</Name>) == 10
212.1780 - (<Name>yhi</Name>, <Name>ylo</Name>, <Attribute><Name>self</Name></Attribute>.__month, <Attribute><Name>self</Name></Attribute>.__day, <Attribute><Name>self</Name></Attribute>.__hour,
212.1781 - <Attribute><Name>self</Name></Attribute>.__minute, <Attribute><Name>self</Name></Attribute>.__second, <Name>us1</Name>, <Name>us2</Name>, <Name>us3</Name>) = <Call><Name>map</Name></Call>(<Name>ord</Name>, <Name>string</Name>)
212.1782 - <Attribute><Name>self</Name></Attribute>.__year = <Name>yhi</Name> * 256 + <Name>ylo</Name>
212.1783 - <Attribute><Name>self</Name></Attribute>.__microsecond = (((<Name>us1</Name> << 8) | <Name>us2</Name>) << 8) | <Name>us3</Name>
212.1784 - if <Call><Name>len</Name></Call>(<Name>state</Name>) == 1:
212.1785 - <Attribute><Name>self</Name></Attribute>._tzinfo = <Name>None</Name>
212.1786 - else:
212.1787 - <Attribute><Name>self</Name></Attribute>._tzinfo = <Name>state</Name>[1]
212.1788 -
212.1789 - def <FunctionDef>__reduce__</FunctionDef>(<Name>self</Name>):
212.1790 - return (<Attribute><Name>self</Name></Attribute>.__class__, <Attribute><Name>self</Name></Attribute>.<Call>__getstate</Call>())
212.1791 -
212.1792 -
212.1793 -<Attribute><Name>datetime</Name></Attribute>.min = <Call><Name>datetime</Name></Call>(1, 1, 1)
212.1794 -<Attribute><Name>datetime</Name></Attribute>.max = <Call><Name>datetime</Name></Call>(9999, 12, 31, 23, 59, 59, 999999)
212.1795 -<Attribute><Name>datetime</Name></Attribute>.resolution = <Call><Name>timedelta</Name></Call>(microseconds=1)
212.1796 -
212.1797 -
212.1798 -def <FunctionDef>_isoweek1monday</FunctionDef>(<Name>year</Name>):
212.1799 - # Helper to calculate the day number of the Monday starting week 1
212.1800 - # XXX This could be done more efficiently
212.1801 - <Name>THURSDAY</Name> = 3
212.1802 - <Name>firstday</Name> = <Call><Name>_ymd2ord</Name></Call>(<Name>year</Name>, 1, 1)
212.1803 - <Name>firstweekday</Name> = (<Name>firstday</Name> + 6) % 7 # See weekday() above
212.1804 - <Name>week1monday</Name> = <Name>firstday</Name> - <Name>firstweekday</Name>
212.1805 - if <Name>firstweekday</Name> > <Name>THURSDAY</Name>:
212.1806 - <Name>week1monday</Name> += 7
212.1807 - return <Name>week1monday</Name>
212.1808 -
212.1809 -"""
212.1810 -Some time zone algebra. For a datetime x, let
212.1811 - x.n = x stripped of its timezone -- its naive time.
212.1812 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
212.1813 - return None
212.1814 - x.d = x.dst(), and assuming that doesn't raise an exception or
212.1815 - return None
212.1816 - x.s = x's standard offset, x.o - x.d
212.1817 -
212.1818 -Now some derived rules, where k is a duration (timedelta).
212.1819 -
212.1820 -1. x.o = x.s + x.d
212.1821 - This follows from the definition of x.s.
212.1822 -
212.1823 -2. If x and y have the same tzinfo member, x.s = y.s.
212.1824 - This is actually a requirement, an assumption we need to make about
212.1825 - sane tzinfo classes.
212.1826 -
212.1827 -3. The naive UTC time corresponding to x is x.n - x.o.
212.1828 - This is again a requirement for a sane tzinfo class.
212.1829 -
212.1830 -4. (x+k).s = x.s
212.1831 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
212.1832 -
212.1833 -5. (x+k).n = x.n + k
212.1834 - Again follows from how arithmetic is defined.
212.1835 -
212.1836 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
212.1837 -(meaning that the various tzinfo methods exist, and don't blow up or return
212.1838 -None when called).
212.1839 -
212.1840 -The function wants to return a datetime y with timezone tz, equivalent to x.
212.1841 -x is already in UTC.
212.1842 -
212.1843 -By #3, we want
212.1844 -
212.1845 - y.n - y.o = x.n [1]
212.1846 -
212.1847 -The algorithm starts by attaching tz to x.n, and calling that y. So
212.1848 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
212.1849 -becomes true; in effect, we want to solve [2] for k:
212.1850 -
212.1851 - (y+k).n - (y+k).o = x.n [2]
212.1852 -
212.1853 -By #1, this is the same as
212.1854 -
212.1855 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
212.1856 -
212.1857 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
212.1858 -Substituting that into [3],
212.1859 -
212.1860 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
212.1861 - k - (y+k).s - (y+k).d = 0; rearranging,
212.1862 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
212.1863 - k = y.s - (y+k).d
212.1864 -
212.1865 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
212.1866 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
212.1867 -very large, since all offset-returning methods return a duration of magnitude
212.1868 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
212.1869 -be 0, so ignoring it has no consequence then.
212.1870 -
212.1871 -In any case, the new value is
212.1872 -
212.1873 - z = y + y.s [4]
212.1874 -
212.1875 -It's helpful to step back at look at [4] from a higher level: it's simply
212.1876 -mapping from UTC to tz's standard time.
212.1877 -
212.1878 -At this point, if
212.1879 -
212.1880 - z.n - z.o = x.n [5]
212.1881 -
212.1882 -we have an equivalent time, and are almost done. The insecurity here is
212.1883 -at the start of daylight time. Picture US Eastern for concreteness. The wall
212.1884 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
212.1885 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
212.1886 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
212.1887 -on the day DST starts. We want to return the 1:MM EST spelling because that's
212.1888 -the only spelling that makes sense on the local wall clock.
212.1889 -
212.1890 -In fact, if [5] holds at this point, we do have the standard-time spelling,
212.1891 -but that takes a bit of proof. We first prove a stronger result. What's the
212.1892 -difference between the LHS and RHS of [5]? Let
212.1893 -
212.1894 - diff = x.n - (z.n - z.o) [6]
212.1895 -
212.1896 -Now
212.1897 - z.n = by [4]
212.1898 - (y + y.s).n = by #5
212.1899 - y.n + y.s = since y.n = x.n
212.1900 - x.n + y.s = since z and y are have the same tzinfo member,
212.1901 - y.s = z.s by #2
212.1902 - x.n + z.s
212.1903 -
212.1904 -Plugging that back into [6] gives
212.1905 -
212.1906 - diff =
212.1907 - x.n - ((x.n + z.s) - z.o) = expanding
212.1908 - x.n - x.n - z.s + z.o = cancelling
212.1909 - - z.s + z.o = by #2
212.1910 - z.d
212.1911 -
212.1912 -So diff = z.d.
212.1913 -
212.1914 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
212.1915 -spelling we wanted in the endcase described above. We're done. Contrarily,
212.1916 -if z.d = 0, then we have a UTC equivalent, and are also done.
212.1917 -
212.1918 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
212.1919 -add to z (in effect, z is in tz's standard time, and we need to shift the
212.1920 -local clock into tz's daylight time).
212.1921 -
212.1922 -Let
212.1923 -
212.1924 - z' = z + z.d = z + diff [7]
212.1925 -
212.1926 -and we can again ask whether
212.1927 -
212.1928 - z'.n - z'.o = x.n [8]
212.1929 -
212.1930 -If so, we're done. If not, the tzinfo class is insane, according to the
212.1931 -assumptions we've made. This also requires a bit of proof. As before, let's
212.1932 -compute the difference between the LHS and RHS of [8] (and skipping some of
212.1933 -the justifications for the kinds of substitutions we've done several times
212.1934 -already):
212.1935 -
212.1936 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
212.1937 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
212.1938 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
212.1939 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
212.1940 - - z.n + z.n - z.o + z'.o = cancel z.n
212.1941 - - z.o + z'.o = #1 twice
212.1942 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
212.1943 - z'.d - z.d
212.1944 -
212.1945 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
212.1946 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
212.1947 -return z', not bothering to compute z'.d.
212.1948 -
212.1949 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
212.1950 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
212.1951 -would have to change the result dst() returns: we start in DST, and moving
212.1952 -a little further into it takes us out of DST.
212.1953 -
212.1954 -There isn't a sane case where this can happen. The closest it gets is at
212.1955 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
212.1956 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
212.1957 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
212.1958 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
212.1959 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
212.1960 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
212.1961 -standard time. Since that's what the local clock *does*, we want to map both
212.1962 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
212.1963 -in local time, but so it goes -- it's the way the local clock works.
212.1964 -
212.1965 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
212.1966 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
212.1967 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
212.1968 -(correctly) concludes that z' is not UTC-equivalent to x.
212.1969 -
212.1970 -Because we know z.d said z was in daylight time (else [5] would have held and
212.1971 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
212.1972 -and we we have stopped then), and there are only 2 possible values dst() can
212.1973 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
212.1974 -but the reasoning doesn't depend on the example -- it depends on there being
212.1975 -two possible dst() outcomes, one zero and the other non-zero). Therefore
212.1976 -z' must be in standard time, and is the spelling we want in this case.
212.1977 -
212.1978 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
212.1979 -concerned (because it takes z' as being in standard time rather than the
212.1980 -daylight time we intend here), but returning it gives the real-life "local
212.1981 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
212.1982 -tz.
212.1983 -
212.1984 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
212.1985 -the 1:MM standard time spelling we want.
212.1986 -
212.1987 -So how can this break? One of the assumptions must be violated. Two
212.1988 -possibilities:
212.1989 -
212.1990 -1) [2] effectively says that y.s is invariant across all y belong to a given
212.1991 - time zone. This isn't true if, for political reasons or continental drift,
212.1992 - a region decides to change its base offset from UTC.
212.1993 -
212.1994 -2) There may be versions of "double daylight" time where the tail end of
212.1995 - the analysis gives up a step too early. I haven't thought about that
212.1996 - enough to say.
212.1997 -
212.1998 -In any case, it's clear that the default fromutc() is strong enough to handle
212.1999 -"almost all" time zones: so long as the standard offset is invariant, it
212.2000 -doesn't matter if daylight time transition points change from year to year, or
212.2001 -if daylight time is skipped in some years; it doesn't matter how large or
212.2002 -small dst() may get within its bounds; and it doesn't even matter if some
212.2003 -perverse time zone returns a negative dst()). So a breaking case must be
212.2004 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
212.2005 -"""
212.2006 -
212.2007 -def <FunctionDef>_test</FunctionDef>():
212.2008 - import test_datetime
212.2009 - <Attribute><Name>test_datetime</Name></Attribute>.<Call>test_main</Call>()
212.2010 -
212.2011 -if <Name>__name__</Name> == "__main__":
212.2012 - <Call><Name>_test</Name></Call>()
213.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.offsets Sun Jan 04 13:11:53 2015 -0600
213.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
213.3 @@ -1,2009 +0,0 @@
213.4 -
213.5 -<Module><Expr><Str>"""Concrete date/time and related types -- prototype implemented in Python.
213.6 -
213.7 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
213.8 -
213.9 -See also http://dir.yahoo.com/Reference/calendars/
213.10 -
213.11 -For a primer on DST, including many current DST rules, see
213.12 -http://webexhibits.org/daylightsaving/
213.13 -
213.14 -For more about DST than you ever wanted to know, see
213.15 -ftp://elsie.nci.nih.gov/pub/
213.16 -
213.17 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
213.18 -
213.19 -"""</Str></Expr>
213.20 -
213.21 -<Import>import time as _time</Import>
213.22 -<Import>import math as _math</Import>
213.23 -
213.24 -<Assign><Name>MINYEAR</Name> = <Num>1</Num></Assign>
213.25 -<Assign><Name>MAXYEAR</Name> = <Num>9999</Num></Assign>
213.26 -
213.27 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
213.28 -# also assumes the current Gregorian calendar indefinitely extended in
213.29 -# both directions. Difference: Dates.py calls January 1 of year 0 day
213.30 -# number 1. The code here calls January 1 of year 1 day number 1. This is
213.31 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
213.32 -# and Reingold's "Calendrical Calculations", where it's the base calendar
213.33 -# for all computations. See the book for algorithms for converting between
213.34 -# proleptic Gregorian ordinals and many other calendar systems.
213.35 -
213.36 -<Assign><Name>_DAYS_IN_MONTH</Name> = <List>[<Name>None</Name>, <Num>31</Num>, <Num>28</Num>, <Num>31</Num>, <Num>30</Num>, <Num>31</Num>, <Num>30</Num>, <Num>31</Num>, <Num>31</Num>, <Num>30</Num>, <Num>31</Num>, <Num>30</Num>, <Num>31</Num>]</List></Assign>
213.37 -
213.38 -<Assign><Name>_DAYS_BEFORE_MONTH</Name> = <List>[<Name>None</Name>]</List></Assign>
213.39 -<Assign><Name>dbm</Name> = <Num>0</Num></Assign>
213.40 -<For>for <Name>dim</Name> in <Subscript><Name>_DAYS_IN_MONTH</Name>[<Slice><Num>1</Num>:</Slice>]</Subscript>:
213.41 - <Expr><Call><Attribute><Name>_DAYS_BEFORE_MONTH</Name>.append</Attribute>(<Name>dbm</Name>)</Call></Expr>
213.42 - <AugAssign><Name>dbm</Name> += <Name>dim</Name></AugAssign>
213.43 -</For><Delete>del <Name>dbm</Name>, <Name>dim</Name></Delete>
213.44 -
213.45 -<FunctionDef>def _is_leap(<Name>year</Name>):
213.46 - <Expr><Str>"year -> 1 if leap year, else 0."</Str></Expr>
213.47 - <Return>return <BoolOp><Compare><BinOp><Name>year</Name> % <Num>4</Num></BinOp> == <Num>0</Num></Compare> and <BoolOp>(<Compare><BinOp><Name>year</Name> % <Num>100</Num></BinOp> != <Num>0</Num></Compare> or <Compare><BinOp><Name>year</Name> % <Num>400</Num></BinOp> == <Num>0</Num></Compare>)</BoolOp></BoolOp></Return>
213.48 -
213.49 -</FunctionDef><FunctionDef>def _days_in_year(<Name>year</Name>):
213.50 - <Expr><Str>"year -> number of days in year (366 if a leap year, else 365)."</Str></Expr>
213.51 - <Return>return <BinOp><Num>365</Num> + <Call><Name>_is_leap</Name>(<Name>year</Name>)</Call></BinOp></Return>
213.52 -
213.53 -</FunctionDef><FunctionDef>def _days_before_year(<Name>year</Name>):
213.54 - <Expr><Str>"year -> number of days before January 1st of year."</Str></Expr>
213.55 - <Assign><Name>y</Name> = <BinOp><Name>year</Name> - <Num>1</Num></BinOp></Assign>
213.56 - <Return>return <BinOp><BinOp><BinOp><BinOp><Name>y</Name></BinOp></BinOp></BinOp>*<Num>365</Num> + <BinOp><Name>y</Name></BinOp>//<Num>4</Num> - <BinOp><Name>y</Name></BinOp>//<Num>100</Num> + <BinOp><Name>y</Name></BinOp>//<Num>400</Num></BinOp></Return>
213.57 -
213.58 -</FunctionDef><FunctionDef>def _days_in_month(<Name>year</Name>, <Name>month</Name>):
213.59 - <Expr><Str>"year, month -> number of days in that month in that year."</Str></Expr>
213.60 - <Assert>assert <Compare><Num>1</Num> <= <Name>month</Name> <= <Num>12</Num></Compare>, <Name>month</Name></Assert>
213.61 - <If>if <BoolOp><Compare><Name>month</Name> == <Num>2</Num></Compare> and <Call><Name>_is_leap</Name>(<Name>year</Name>)</Call></BoolOp>:
213.62 - <Return>return <Num>29</Num></Return>
213.63 - </If> <Return>return <Subscript><Name>_DAYS_IN_MONTH</Name>[<Index><Name>month</Name></Index>]</Subscript></Return>
213.64 -
213.65 -</FunctionDef><FunctionDef>def _days_before_month(<Name>year</Name>, <Name>month</Name>):
213.66 - <Expr><Str>"year, month -> number of days in year preceeding first day of month."</Str></Expr>
213.67 - <If>if <UnaryOp>not <Compare><Num>1</Num> <= <Name>month</Name> <= <Num>12</Num></Compare></UnaryOp>:
213.68 - <Raise>raise <Call><Name>ValueError</Name>(<Str>'month must be in 1..12'</Str>, <Name>month</Name>)</Call></Raise>
213.69 - </If> <Return>return <BinOp><Subscript><Name>_DAYS_BEFORE_MONTH</Name>[<Index><Name>month</Name></Index>]</Subscript> + <BoolOp>(<Compare><Name>month</Name> > <Num>2</Num></Compare> and <Call><Name>_is_leap</Name>(<Name>year</Name>)</Call>)</BoolOp></BinOp></Return>
213.70 -
213.71 -</FunctionDef><FunctionDef>def _ymd2ord(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>):
213.72 - <Expr><Str>"year, month, day -> ordinal, considering 01-Jan-0001 as day 1."</Str></Expr>
213.73 - <If>if <UnaryOp>not <Compare><Num>1</Num> <= <Name>month</Name> <= <Num>12</Num></Compare></UnaryOp>:
213.74 - <Raise>raise <Call><Name>ValueError</Name>(<Str>'month must be in 1..12'</Str>, <Name>month</Name>)</Call></Raise>
213.75 - </If> <Assign><Name>dim</Name> = <Call><Name>_days_in_month</Name>(<Name>year</Name>, <Name>month</Name>)</Call></Assign>
213.76 - <If>if <UnaryOp>not <Compare><Num>1</Num> <= <Name>day</Name> <= <Name>dim</Name></Compare></UnaryOp>:
213.77 - <Raise>raise <Call><Name>ValueError</Name>(<BinOp><Str>'day must be in 1..%d'</Str> % <Name>dim</Name></BinOp>, <Name>day</Name>)</Call></Raise>
213.78 - </If> <Return>return <BinOp>(<BinOp><Call><Name>_days_before_year</Name>(<Name>year</Name>)</Call></BinOp> +
213.79 - <Call><Name>_days_before_month</Name>(<Name>year</Name>, <Name>month</Name>)</Call> +
213.80 - <Name>day</Name>)</BinOp></Return>
213.81 -
213.82 -</FunctionDef><Assign><Name>_DI400Y</Name> = <Call><Name>_days_before_year</Name>(<Num>401</Num>)</Call></Assign> # number of days in 400 years
213.83 -<Assign><Name>_DI100Y</Name> = <Call><Name>_days_before_year</Name>(<Num>101</Num>)</Call></Assign> # " " " " 100 "
213.84 -<Assign><Name>_DI4Y</Name> = <Call><Name>_days_before_year</Name>(<Num>5</Num>)</Call></Assign> # " " " " 4 "
213.85 -
213.86 -# A 4-year cycle has an extra leap day over what we'd get from pasting
213.87 -# together 4 single years.
213.88 -<Assert>assert <Compare><Name>_DI4Y</Name> == <BinOp><BinOp><Num>4</Num></BinOp> * <Num>365</Num> + <Num>1</Num></BinOp></Compare></Assert>
213.89 -
213.90 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
213.91 -# pasting together 4 100-year cycles.
213.92 -<Assert>assert <Compare><Name>_DI400Y</Name> == <BinOp><BinOp><Num>4</Num></BinOp> * <Name>_DI100Y</Name> + <Num>1</Num></BinOp></Compare></Assert>
213.93 -
213.94 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
213.95 -# pasting together 25 4-year cycles.
213.96 -<Assert>assert <Compare><Name>_DI100Y</Name> == <BinOp><BinOp><Num>25</Num></BinOp> * <Name>_DI4Y</Name> - <Num>1</Num></BinOp></Compare></Assert>
213.97 -
213.98 -<FunctionDef>def _ord2ymd(<Name>n</Name>):
213.99 - <Expr><Str>"ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."</Str></Expr>
213.100 -
213.101 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
213.102 - # repeats exactly every 400 years. The basic strategy is to find the
213.103 - # closest 400-year boundary at or before n, then work with the offset
213.104 - # from that boundary to n. Life is much clearer if we subtract 1 from
213.105 - # n first -- then the values of n at 400-year boundaries are exactly
213.106 - # those divisible by _DI400Y:
213.107 - #
213.108 - # D M Y n n-1
213.109 - # -- --- ---- ---------- ----------------
213.110 - # 31 Dec -400 -_DI400Y -_DI400Y -1
213.111 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
213.112 - # ...
213.113 - # 30 Dec 000 -1 -2
213.114 - # 31 Dec 000 0 -1
213.115 - # 1 Jan 001 1 0 400-year boundary
213.116 - # 2 Jan 001 2 1
213.117 - # 3 Jan 001 3 2
213.118 - # ...
213.119 - # 31 Dec 400 _DI400Y _DI400Y -1
213.120 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
213.121 - <AugAssign><Name>n</Name> -= <Num>1</Num></AugAssign>
213.122 - <Assign><Tuple><Name>n400</Name>, <Name>n</Name></Tuple> = <Call><Name>divmod</Name>(<Name>n</Name>, <Name>_DI400Y</Name>)</Call></Assign>
213.123 - <Assign><Name>year</Name> = <BinOp><BinOp><Name>n400</Name></BinOp> * <Num>400</Num> + <Num>1</Num></BinOp></Assign> # ..., -399, 1, 401, ...
213.124 -
213.125 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
213.126 - # the desired date. Now compute how many 100-year cycles precede n.
213.127 - # Note that it's possible for n100 to equal 4! In that case 4 full
213.128 - # 100-year cycles precede the desired day, which implies the desired
213.129 - # day is December 31 at the end of a 400-year cycle.
213.130 - <Assign><Tuple><Name>n100</Name>, <Name>n</Name></Tuple> = <Call><Name>divmod</Name>(<Name>n</Name>, <Name>_DI100Y</Name>)</Call></Assign>
213.131 -
213.132 - # Now compute how many 4-year cycles precede it.
213.133 - <Assign><Tuple><Name>n4</Name>, <Name>n</Name></Tuple> = <Call><Name>divmod</Name>(<Name>n</Name>, <Name>_DI4Y</Name>)</Call></Assign>
213.134 -
213.135 - # And now how many single years. Again n1 can be 4, and again meaning
213.136 - # that the desired day is December 31 at the end of the 4-year cycle.
213.137 - <Assign><Tuple><Name>n1</Name>, <Name>n</Name></Tuple> = <Call><Name>divmod</Name>(<Name>n</Name>, <Num>365</Num>)</Call></Assign>
213.138 -
213.139 - <AugAssign><Name>year</Name> += <BinOp><BinOp><BinOp><Name>n100</Name></BinOp></BinOp> * <Num>100</Num> + <BinOp><Name>n4</Name></BinOp> * <Num>4</Num> + <Name>n1</Name></BinOp></AugAssign>
213.140 - <If>if <BoolOp><Compare><Name>n1</Name> == <Num>4</Num></Compare> or <Compare><Name>n100</Name> == <Num>4</Num></Compare></BoolOp>:
213.141 - <Assert>assert <Compare><Name>n</Name> == <Num>0</Num></Compare></Assert>
213.142 - <Return>return <Tuple><BinOp><Name>year</Name>-<Num>1</Num></BinOp>, <Num>12</Num>, <Num>31</Num></Tuple></Return>
213.143 -
213.144 - # Now the year is correct, and n is the offset from January 1. We find
213.145 - # the month via an estimate that's either exact or one too large.
213.146 - </If> <Assign><Name>leapyear</Name> = <BoolOp><Compare><Name>n1</Name> == <Num>3</Num></Compare> and <BoolOp>(<Compare><Name>n4</Name> != <Num>24</Num></Compare> or <Compare><Name>n100</Name> == <Num>3</Num></Compare>)</BoolOp></BoolOp></Assign>
213.147 - <Assert>assert <Compare><Name>leapyear</Name> == <Call><Name>_is_leap</Name>(<Name>year</Name>)</Call></Compare></Assert>
213.148 - <Assign><Name>month</Name> = <BinOp><BinOp>(<Name>n</Name> + <Num>50</Num>)</BinOp> >> <Num>5</Num></BinOp></Assign>
213.149 - <Assign><Name>preceding</Name> = <BinOp><Subscript><Name>_DAYS_BEFORE_MONTH</Name>[<Index><Name>month</Name></Index>]</Subscript> + <BoolOp>(<Compare><Name>month</Name> > <Num>2</Num></Compare> and <Name>leapyear</Name>)</BoolOp></BinOp></Assign>
213.150 - <If>if <Compare><Name>preceding</Name> > <Name>n</Name></Compare>: # estimate is too large
213.151 - <AugAssign><Name>month</Name> -= <Num>1</Num></AugAssign>
213.152 - <AugAssign><Name>preceding</Name> -= <BinOp><Subscript><Name>_DAYS_IN_MONTH</Name>[<Index><Name>month</Name></Index>]</Subscript> + <BoolOp>(<Compare><Name>month</Name> == <Num>2</Num></Compare> and <Name>leapyear</Name>)</BoolOp></BinOp></AugAssign>
213.153 - </If> <AugAssign><Name>n</Name> -= <Name>preceding</Name></AugAssign>
213.154 - <Assert>assert <Compare><Num>0</Num> <= <Name>n</Name> < <Call><Name>_days_in_month</Name>(<Name>year</Name>, <Name>month</Name>)</Call></Compare></Assert>
213.155 -
213.156 - # Now the year and month are correct, and n is the offset from the
213.157 - # start of that month: we're done!
213.158 - <Return>return <Tuple><Name>year</Name>, <Name>month</Name>, <BinOp><Name>n</Name>+<Num>1</Num></BinOp></Tuple></Return>
213.159 -
213.160 -# Month and day names. For localized versions, see the calendar module.
213.161 -</FunctionDef><Assign><Name>_MONTHNAMES</Name> = <List>[<Name>None</Name>, <Str>"Jan"</Str>, <Str>"Feb"</Str>, <Str>"Mar"</Str>, <Str>"Apr"</Str>, <Str>"May"</Str>, <Str>"Jun"</Str>,
213.162 - <Str>"Jul"</Str>, <Str>"Aug"</Str>, <Str>"Sep"</Str>, <Str>"Oct"</Str>, <Str>"Nov"</Str>, <Str>"Dec"</Str>]</List></Assign>
213.163 -<Assign><Name>_DAYNAMES</Name> = <List>[<Name>None</Name>, <Str>"Mon"</Str>, <Str>"Tue"</Str>, <Str>"Wed"</Str>, <Str>"Thu"</Str>, <Str>"Fri"</Str>, <Str>"Sat"</Str>, <Str>"Sun"</Str>]</List></Assign>
213.164 -
213.165 -
213.166 -<FunctionDef>def _build_struct_time(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>, <Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Name>dstflag</Name>):
213.167 - <Assign><Name>wday</Name> = <BinOp><BinOp>(<Call><Name>_ymd2ord</Name>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>)</Call> + <Num>6</Num>)</BinOp> % <Num>7</Num></BinOp></Assign>
213.168 - <Assign><Name>dnum</Name> = <BinOp><Call><Name>_days_before_month</Name>(<Name>y</Name>, <Name>m</Name>)</Call> + <Name>d</Name></BinOp></Assign>
213.169 - <Return>return <Call><Attribute><Name>_time</Name>.struct_time</Attribute>(<Tuple>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>, <Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Name>wday</Name>, <Name>dnum</Name>, <Name>dstflag</Name>)</Tuple>)</Call></Return>
213.170 -
213.171 -</FunctionDef><FunctionDef>def _format_time(<Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Name>us</Name>):
213.172 - # Skip trailing microseconds when us==0.
213.173 - <Assign><Name>result</Name> = <BinOp><Str>"%02d:%02d:%02d"</Str> % <Tuple>(<Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>)</Tuple></BinOp></Assign>
213.174 - <If>if <Name>us</Name>:
213.175 - <AugAssign><Name>result</Name> += <BinOp><Str>".%06d"</Str> % <Name>us</Name></BinOp></AugAssign>
213.176 - </If> <Return>return <Name>result</Name></Return>
213.177 -
213.178 -# Correctly substitute for %z and %Z escapes in strftime formats.
213.179 -</FunctionDef><FunctionDef>def _wrap_strftime(<Name>object</Name>, <Name>format</Name>, <Name>timetuple</Name>):
213.180 - <Assign><Name>year</Name> = <Subscript><Name>timetuple</Name>[<Index><Num>0</Num></Index>]</Subscript></Assign>
213.181 - <If>if <Compare><Name>year</Name> < <Num>1900</Num></Compare>:
213.182 - <Raise>raise <Call><Name>ValueError</Name>(<BinOp><Str>"year=%d is before 1900; the datetime strftime() "
213.183 - "methods require year >= 1900"</Str> % <Name>year</Name></BinOp>)</Call></Raise>
213.184 - # Don't call _utcoffset() or tzname() unless actually needed.
213.185 - </If> <Assign><Name>zreplace</Name> = <Name>None</Name></Assign> # the string to use for %z
213.186 - <Assign><Name>Zreplace</Name> = <Name>None</Name></Assign> # the string to use for %Z
213.187 -
213.188 - # Scan format for %z and %Z escapes, replacing as needed.
213.189 - <Assign><Name>newformat</Name> = <List>[]</List></Assign>
213.190 - <Assign><Name>push</Name> = <Attribute><Name>newformat</Name>.append</Attribute></Assign>
213.191 - <Assign><Tuple><Name>i</Name>, <Name>n</Name></Tuple> = <Tuple><Num>0</Num>, <Call><Name>len</Name>(<Name>format</Name>)</Call></Tuple></Assign>
213.192 - <While>while <Compare><Name>i</Name> < <Name>n</Name></Compare>:
213.193 - <Assign><Name>ch</Name> = <Subscript><Name>format</Name>[<Index><Name>i</Name></Index>]</Subscript></Assign>
213.194 - <AugAssign><Name>i</Name> += <Num>1</Num></AugAssign>
213.195 - <If>if <Compare><Name>ch</Name> == <Str>'%'</Str></Compare>:
213.196 - <If>if <Compare><Name>i</Name> < <Name>n</Name></Compare>:
213.197 - <Assign><Name>ch</Name> = <Subscript><Name>format</Name>[<Index><Name>i</Name></Index>]</Subscript></Assign>
213.198 - <AugAssign><Name>i</Name> += <Num>1</Num></AugAssign>
213.199 - <If>if <Compare><Name>ch</Name> == <Str>'z'</Str></Compare>:
213.200 - <If>if <Compare><Name>zreplace</Name> is <Name>None</Name></Compare>:
213.201 - <Assign><Name>zreplace</Name> = <Str>""</Str></Assign>
213.202 - <If>if <Call><Name>hasattr</Name>(<Name>object</Name>, <Str>"_utcoffset"</Str>)</Call>:
213.203 - <Assign><Name>offset</Name> = <Call><Attribute><Name>object</Name>._utcoffset</Attribute>()</Call></Assign>
213.204 - <If>if <Compare><Name>offset</Name> is not <Name>None</Name></Compare>:
213.205 - <Assign><Name>sign</Name> = <Str>'+'</Str></Assign>
213.206 - <If>if <Compare><Name>offset</Name> < <Num>0</Num></Compare>:
213.207 - <Assign><Name>offset</Name> = <UnaryOp>-<Name>offset</Name></UnaryOp></Assign>
213.208 - <Assign><Name>sign</Name> = <Str>'-'</Str></Assign>
213.209 - </If> <Assign><Tuple><Name>h</Name>, <Name>m</Name></Tuple> = <Call><Name>divmod</Name>(<Name>offset</Name>, <Num>60</Num>)</Call></Assign>
213.210 - <Assign><Name>zreplace</Name> = <BinOp><Str>'%c%02d%02d'</Str> % <Tuple>(<Name>sign</Name>, <Name>h</Name>, <Name>m</Name>)</Tuple></BinOp></Assign>
213.211 - </If></If></If> <Assert>assert <Compare><Str>'%'</Str> not in <Name>zreplace</Name></Compare></Assert>
213.212 - <Expr><Call><Attribute><Name>newformat</Name>.append</Attribute>(<Name>zreplace</Name>)</Call></Expr>
213.213 - <If>elif <Compare><Name>ch</Name> == <Str>'Z'</Str></Compare>:
213.214 - <If>if <Compare><Name>Zreplace</Name> is <Name>None</Name></Compare>:
213.215 - <Assign><Name>Zreplace</Name> = <Str>""</Str></Assign>
213.216 - <If>if <Call><Name>hasattr</Name>(<Name>object</Name>, <Str>"tzname"</Str>)</Call>:
213.217 - <Assign><Name>s</Name> = <Call><Attribute><Name>object</Name>.tzname</Attribute>()</Call></Assign>
213.218 - <If>if <Compare><Name>s</Name> is not <Name>None</Name></Compare>:
213.219 - # strftime is going to have at this: escape %
213.220 - <Assign><Name>Zreplace</Name> = <Call><Attribute><Name>s</Name>.replace</Attribute>(<Str>'%'</Str>, <Str>'%%'</Str>)</Call></Assign>
213.221 - </If></If></If> <Expr><Call><Attribute><Name>newformat</Name>.append</Attribute>(<Name>Zreplace</Name>)</Call></Expr>
213.222 - else:
213.223 - <Expr><Call><Name>push</Name>(<Str>'%'</Str>)</Call></Expr>
213.224 - <Expr><Call><Name>push</Name>(<Name>ch</Name>)</Call></Expr>
213.225 - </If></If> else:
213.226 - <Expr><Call><Name>push</Name>(<Str>'%'</Str>)</Call></Expr>
213.227 - </If> else:
213.228 - <Expr><Call><Name>push</Name>(<Name>ch</Name>)</Call></Expr>
213.229 - </If></While> <Assign><Name>newformat</Name> = <Call><Attribute><Str>""</Str>.join</Attribute>(<Name>newformat</Name>)</Call></Assign>
213.230 - <Return>return <Call><Attribute><Name>_time</Name>.strftime</Attribute>(<Name>newformat</Name>, <Name>timetuple</Name>)</Call></Return>
213.231 -
213.232 -</FunctionDef><FunctionDef>def _call_tzinfo_method(<Name>tzinfo</Name>, <Name>methname</Name>, <Name>tzinfoarg</Name>):
213.233 - <If>if <Compare><Name>tzinfo</Name> is <Name>None</Name></Compare>:
213.234 - <Return>return <Name>None</Name></Return>
213.235 - </If> <Return>return <Call><Name>getattr</Name><Call>(<Name>tzinfo</Name>, <Name>methname</Name>)</Call>(<Name>tzinfoarg</Name>)</Call></Return>
213.236 -
213.237 -# Just raise TypeError if the arg isn't None or a string.
213.238 -</FunctionDef><FunctionDef>def _check_tzname(<Name>name</Name>):
213.239 - <If>if <BoolOp><Compare><Name>name</Name> is not <Name>None</Name></Compare> and <UnaryOp>not <Call><Name>isinstance</Name>(<Name>name</Name>, <Name>str</Name>)</Call></UnaryOp></BoolOp>:
213.240 - <Raise>raise <Call><Name>TypeError</Name>(<BinOp><Str>"tzinfo.tzname() must return None or string, "
213.241 - "not '%s'"</Str> % <Call><Name>type</Name>(<Name>name</Name>)</Call></BinOp>)</Call></Raise>
213.242 -
213.243 -# name is the offset-producing method, "utcoffset" or "dst".
213.244 -# offset is what it returned.
213.245 -# If offset isn't None or timedelta, raises TypeError.
213.246 -# If offset is None, returns None.
213.247 -# Else offset is checked for being in range, and a whole # of minutes.
213.248 -# If it is, its integer value is returned. Else ValueError is raised.
213.249 -</If></FunctionDef><FunctionDef>def _check_utc_offset(<Name>name</Name>, <Name>offset</Name>):
213.250 - <Assert>assert <Compare><Name>name</Name> in <Tuple>(<Str>"utcoffset"</Str>, <Str>"dst"</Str>)</Tuple></Compare></Assert>
213.251 - <If>if <Compare><Name>offset</Name> is <Name>None</Name></Compare>:
213.252 - <Return>return <Name>None</Name></Return>
213.253 - </If> <If>if <UnaryOp>not <Call><Name>isinstance</Name>(<Name>offset</Name>, <Name>timedelta</Name>)</Call></UnaryOp>:
213.254 - <Raise>raise <Call><Name>TypeError</Name>(<BinOp><Str>"tzinfo.%s() must return None "
213.255 - "or timedelta, not '%s'"</Str> % <Tuple>(<Name>name</Name>, <Call><Name>type</Name>(<Name>offset</Name>)</Call>)</Tuple></BinOp>)</Call></Raise>
213.256 - </If> <Assign><Name>days</Name> = <Attribute><Name>offset</Name>.days</Attribute></Assign>
213.257 - <If>if <BoolOp><Compare><Name>days</Name> < <Num>-1</Num></Compare> or <Compare><Name>days</Name> > <Num>0</Num></Compare></BoolOp>:
213.258 - <Assign><Name>offset</Name> = <Num>1440</Num></Assign> # trigger out-of-range
213.259 - else:
213.260 - <Assign><Name>seconds</Name> = <BinOp><BinOp><Name>days</Name></BinOp> * <Num>86400</Num> + <Attribute><Name>offset</Name>.seconds</Attribute></BinOp></Assign>
213.261 - <Assign><Tuple><Name>minutes</Name>, <Name>seconds</Name></Tuple> = <Call><Name>divmod</Name>(<Name>seconds</Name>, <Num>60</Num>)</Call></Assign>
213.262 - <If>if <BoolOp><Name>seconds</Name> or <Attribute><Name>offset</Name>.microseconds</Attribute></BoolOp>:
213.263 - <Raise>raise <Call><Name>ValueError</Name>(<BinOp><Str>"tzinfo.%s() must return a whole number "
213.264 - "of minutes"</Str> % <Name>name</Name></BinOp>)</Call></Raise>
213.265 - </If> <Assign><Name>offset</Name> = <Name>minutes</Name></Assign>
213.266 - </If> <If>if <Compare><Num>-1440</Num> < <Name>offset</Name> < <Num>1440</Num></Compare>:
213.267 - <Return>return <Name>offset</Name></Return>
213.268 - </If> <Raise>raise <Call><Name>ValueError</Name>(<BinOp><Str>"%s()=%d, must be in -1439..1439"</Str> % <Tuple>(<Name>name</Name>, <Name>offset</Name>)</Tuple></BinOp>)</Call></Raise>
213.269 -
213.270 -</FunctionDef><FunctionDef>def _check_date_fields(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>):
213.271 - <If>if <UnaryOp>not <Compare><Name>MINYEAR</Name> <= <Name>year</Name> <= <Name>MAXYEAR</Name></Compare></UnaryOp>:
213.272 - <Raise>raise <Call><Name>ValueError</Name>(<BinOp><Str>'year must be in %d..%d'</Str> % <Tuple>(<Name>MINYEAR</Name>, <Name>MAXYEAR</Name>)</Tuple></BinOp>, <Name>year</Name>)</Call></Raise>
213.273 - </If> <If>if <UnaryOp>not <Compare><Num>1</Num> <= <Name>month</Name> <= <Num>12</Num></Compare></UnaryOp>:
213.274 - <Raise>raise <Call><Name>ValueError</Name>(<Str>'month must be in 1..12'</Str>, <Name>month</Name>)</Call></Raise>
213.275 - </If> <Assign><Name>dim</Name> = <Call><Name>_days_in_month</Name>(<Name>year</Name>, <Name>month</Name>)</Call></Assign>
213.276 - <If>if <UnaryOp>not <Compare><Num>1</Num> <= <Name>day</Name> <= <Name>dim</Name></Compare></UnaryOp>:
213.277 - <Raise>raise <Call><Name>ValueError</Name>(<BinOp><Str>'day must be in 1..%d'</Str> % <Name>dim</Name></BinOp>, <Name>day</Name>)</Call></Raise>
213.278 -
213.279 -</If></FunctionDef><FunctionDef>def _check_time_fields(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>):
213.280 - <If>if <UnaryOp>not <Compare><Num>0</Num> <= <Name>hour</Name> <= <Num>23</Num></Compare></UnaryOp>:
213.281 - <Raise>raise <Call><Name>ValueError</Name>(<Str>'hour must be in 0..23'</Str>, <Name>hour</Name>)</Call></Raise>
213.282 - </If> <If>if <UnaryOp>not <Compare><Num>0</Num> <= <Name>minute</Name> <= <Num>59</Num></Compare></UnaryOp>:
213.283 - <Raise>raise <Call><Name>ValueError</Name>(<Str>'minute must be in 0..59'</Str>, <Name>minute</Name>)</Call></Raise>
213.284 - </If> <If>if <UnaryOp>not <Compare><Num>0</Num> <= <Name>second</Name> <= <Num>59</Num></Compare></UnaryOp>:
213.285 - <Raise>raise <Call><Name>ValueError</Name>(<Str>'second must be in 0..59'</Str>, <Name>second</Name>)</Call></Raise>
213.286 - </If> <If>if <UnaryOp>not <Compare><Num>0</Num> <= <Name>microsecond</Name> <= <Num>999999</Num></Compare></UnaryOp>:
213.287 - <Raise>raise <Call><Name>ValueError</Name>(<Str>'microsecond must be in 0..999999'</Str>, <Name>microsecond</Name>)</Call></Raise>
213.288 -
213.289 -</If></FunctionDef><FunctionDef>def _check_tzinfo_arg(<Name>tz</Name>):
213.290 - <If>if <BoolOp><Compare><Name>tz</Name> is not <Name>None</Name></Compare> and <UnaryOp>not <Call><Name>isinstance</Name>(<Name>tz</Name>, <Name>tzinfo</Name>)</Call></UnaryOp></BoolOp>:
213.291 - <Raise>raise <Call><Name>TypeError</Name>(<Str>"tzinfo argument must be None or of a tzinfo subclass"</Str>)</Call></Raise>
213.292 -
213.293 -
213.294 -# Notes on comparison: In general, datetime module comparison operators raise
213.295 -# TypeError when they don't know how to do a comparison themself. If they
213.296 -# returned NotImplemented instead, comparison could (silently) fall back to
213.297 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
213.298 -# and that's not helpful. There are two exceptions:
213.299 -#
213.300 -# 1. For date and datetime, if the other object has a "timetuple" attr,
213.301 -# NotImplemented is returned. This is a hook to allow other kinds of
213.302 -# datetime-like objects a chance to intercept the comparison.
213.303 -#
213.304 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
213.305 -# so opertaions like
213.306 -#
213.307 -# x == y
213.308 -# x != y
213.309 -# x in sequence
213.310 -# x not in sequence
213.311 -# dict[x] = y
213.312 -#
213.313 -# don't raise annoying TypeErrors just because a datetime object
213.314 -# is part of a heterogeneous collection. If there's no known way to
213.315 -# compare X to a datetime, saying they're not equal is reasonable.
213.316 -
213.317 -</If></FunctionDef><FunctionDef>def _cmperror(<Name>x</Name>, <Name>y</Name>):
213.318 - <Raise>raise <Call><Name>TypeError</Name>(<BinOp><Str>"can't compare '%s' to '%s'"</Str> % <Tuple>(
213.319 - <Attribute><Name>type</Name><Call>(<Name>x</Name>)</Call>.__name__</Attribute>, <Attribute><Name>type</Name><Call>(<Name>y</Name>)</Call>.__name__</Attribute>)</Tuple></BinOp>)</Call></Raise>
213.320 -
213.321 -# This is a start at a struct tm workalike. Goals:
213.322 -#
213.323 -# + Works the same way across platforms.
213.324 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
213.325 -#
213.326 -# Note: I suspect it's best if this flavor of tm does *not* try to
213.327 -# second-guess timezones or DST. Instead fold whatever adjustments you want
213.328 -# into the minutes argument (and the constructor will normalize).
213.329 -
213.330 -</FunctionDef><Assign><Name>_ORD1970</Name> = <Call><Name>_ymd2ord</Name>(<Num>1970</Num>, <Num>1</Num>, <Num>1</Num>)</Call></Assign> # base ordinal for UNIX epoch
213.331 -
213.332 -<ClassDef>class tmxxx:
213.333 -
213.334 - <Assign><Name>ordinal</Name> = <Name>None</Name></Assign>
213.335 -
213.336 - <FunctionDef>def __init__(<Name>self</Name>, <Name>year</Name>, <Name>month</Name>, <Name>day</Name>, <Name>hour</Name>=<Num>0</Num>, <Name>minute</Name>=<Num>0</Num>, <Name>second</Name>=<Num>0</Num>,
213.337 - <Name>microsecond</Name>=<Num>0</Num>):
213.338 - # Normalize all the inputs, and store the normalized values.
213.339 - <If>if <UnaryOp>not <Compare><Num>0</Num> <= <Name>microsecond</Name> <= <Num>999999</Num></Compare></UnaryOp>:
213.340 - <Assign><Tuple><Name>carry</Name>, <Name>microsecond</Name></Tuple> = <Call><Name>divmod</Name>(<Name>microsecond</Name>, <Num>1000000</Num>)</Call></Assign>
213.341 - <AugAssign><Name>second</Name> += <Name>carry</Name></AugAssign>
213.342 - </If> <If>if <UnaryOp>not <Compare><Num>0</Num> <= <Name>second</Name> <= <Num>59</Num></Compare></UnaryOp>:
213.343 - <Assign><Tuple><Name>carry</Name>, <Name>second</Name></Tuple> = <Call><Name>divmod</Name>(<Name>second</Name>, <Num>60</Num>)</Call></Assign>
213.344 - <AugAssign><Name>minute</Name> += <Name>carry</Name></AugAssign>
213.345 - </If> <If>if <UnaryOp>not <Compare><Num>0</Num> <= <Name>minute</Name> <= <Num>59</Num></Compare></UnaryOp>:
213.346 - <Assign><Tuple><Name>carry</Name>, <Name>minute</Name></Tuple> = <Call><Name>divmod</Name>(<Name>minute</Name>, <Num>60</Num>)</Call></Assign>
213.347 - <AugAssign><Name>hour</Name> += <Name>carry</Name></AugAssign>
213.348 - </If> <If>if <UnaryOp>not <Compare><Num>0</Num> <= <Name>hour</Name> <= <Num>23</Num></Compare></UnaryOp>:
213.349 - <Assign><Tuple><Name>carry</Name>, <Name>hour</Name></Tuple> = <Call><Name>divmod</Name>(<Name>hour</Name>, <Num>24</Num>)</Call></Assign>
213.350 - <AugAssign><Name>day</Name> += <Name>carry</Name></AugAssign>
213.351 -
213.352 - # That was easy. Now it gets muddy: the proper range for day
213.353 - # can't be determined without knowing the correct month and year,
213.354 - # but if day is, e.g., plus or minus a million, the current month
213.355 - # and year values make no sense (and may also be out of bounds
213.356 - # themselves).
213.357 - # Saying 12 months == 1 year should be non-controversial.
213.358 - </If> <If>if <UnaryOp>not <Compare><Num>1</Num> <= <Name>month</Name> <= <Num>12</Num></Compare></UnaryOp>:
213.359 - <Assign><Tuple><Name>carry</Name>, <Name>month</Name></Tuple> = <Call><Name>divmod</Name>(<BinOp><Name>month</Name>-<Num>1</Num></BinOp>, <Num>12</Num>)</Call></Assign>
213.360 - <AugAssign><Name>year</Name> += <Name>carry</Name></AugAssign>
213.361 - <AugAssign><Name>month</Name> += <Num>1</Num></AugAssign>
213.362 - <Assert>assert <Compare><Num>1</Num> <= <Name>month</Name> <= <Num>12</Num></Compare></Assert>
213.363 -
213.364 - # Now only day can be out of bounds (year may also be out of bounds
213.365 - # for a datetime object, but we don't care about that here).
213.366 - # If day is out of bounds, what to do is arguable, but at least the
213.367 - # method here is principled and explainable.
213.368 - </If> <Assign><Name>dim</Name> = <Call><Name>_days_in_month</Name>(<Name>year</Name>, <Name>month</Name>)</Call></Assign>
213.369 - <If>if <UnaryOp>not <Compare><Num>1</Num> <= <Name>day</Name> <= <Name>dim</Name></Compare></UnaryOp>:
213.370 - # Move day-1 days from the first of the month. First try to
213.371 - # get off cheap if we're only one day out of range (adjustments
213.372 - # for timezone alone can't be worse than that).
213.373 - <If>if <Compare><Name>day</Name> == <Num>0</Num></Compare>: # move back a day
213.374 - <AugAssign><Name>month</Name> -= <Num>1</Num></AugAssign>
213.375 - <If>if <Compare><Name>month</Name> > <Num>0</Num></Compare>:
213.376 - <Assign><Name>day</Name> = <Call><Name>_days_in_month</Name>(<Name>year</Name>, <Name>month</Name>)</Call></Assign>
213.377 - else:
213.378 - <Assign><Tuple><Name>year</Name>, <Name>month</Name>, <Name>day</Name></Tuple> = <Tuple><BinOp><Name>year</Name>-<Num>1</Num></BinOp>, <Num>12</Num>, <Num>31</Num></Tuple></Assign>
213.379 - </If> <If>elif <Compare><Name>day</Name> == <BinOp><Name>dim</Name> + <Num>1</Num></BinOp></Compare>: # move forward a day
213.380 - <AugAssign><Name>month</Name> += <Num>1</Num></AugAssign>
213.381 - <Assign><Name>day</Name> = <Num>1</Num></Assign>
213.382 - <If>if <Compare><Name>month</Name> > <Num>12</Num></Compare>:
213.383 - <Assign><Name>month</Name> = <Num>1</Num></Assign>
213.384 - <AugAssign><Name>year</Name> += <Num>1</Num></AugAssign>
213.385 - </If> else:
213.386 - <Assign><Attribute><Name>self</Name>.ordinal</Attribute> = <BinOp><Call><Name>_ymd2ord</Name>(<Name>year</Name>, <Name>month</Name>, <Num>1</Num>)</Call> + <BinOp>(<Name>day</Name> - <Num>1</Num>)</BinOp></BinOp></Assign>
213.387 - <Assign><Tuple><Name>year</Name>, <Name>month</Name>, <Name>day</Name></Tuple> = <Call><Name>_ord2ymd</Name>(<Attribute><Name>self</Name>.ordinal</Attribute>)</Call></Assign>
213.388 -
213.389 - </If></If></If> <Assign><Tuple><Attribute><Name>self</Name>.year</Attribute>, <Attribute><Name>self</Name>.month</Attribute>, <Attribute><Name>self</Name>.day</Attribute></Tuple> = <Tuple><Name>year</Name>, <Name>month</Name>, <Name>day</Name></Tuple></Assign>
213.390 - <Assign><Tuple><Attribute><Name>self</Name>.hour</Attribute>, <Attribute><Name>self</Name>.minute</Attribute>, <Attribute><Name>self</Name>.second</Attribute></Tuple> = <Tuple><Name>hour</Name>, <Name>minute</Name>, <Name>second</Name></Tuple></Assign>
213.391 - <Assign><Attribute><Name>self</Name>.microsecond</Attribute> = <Name>microsecond</Name></Assign>
213.392 -
213.393 - </FunctionDef> <FunctionDef>def toordinal(<Name>self</Name>):
213.394 - <Expr><Str>"""Return proleptic Gregorian ordinal for the year, month and day.
213.395 -
213.396 - January 1 of year 1 is day 1. Only the year, month and day values
213.397 - contribute to the result.
213.398 - """</Str></Expr>
213.399 - <If>if <Compare><Attribute><Name>self</Name>.ordinal</Attribute> is <Name>None</Name></Compare>:
213.400 - <Assign><Attribute><Name>self</Name>.ordinal</Attribute> = <Call><Name>_ymd2ord</Name>(<Attribute><Name>self</Name>.year</Attribute>, <Attribute><Name>self</Name>.month</Attribute>, <Attribute><Name>self</Name>.day</Attribute>)</Call></Assign>
213.401 - </If> <Return>return <Attribute><Name>self</Name>.ordinal</Attribute></Return>
213.402 -
213.403 - </FunctionDef> <FunctionDef>def time(<Name>self</Name>):
213.404 - <Expr><Str>"Return Unixish timestamp, as a float (assuming UTC)."</Str></Expr>
213.405 - <Assign><Name>days</Name> = <BinOp><Call><Attribute><Name>self</Name>.toordinal</Attribute>()</Call> - <Name>_ORD1970</Name></BinOp></Assign> # convert to UNIX epoch
213.406 - <Assign><Name>seconds</Name> = <BinOp><BinOp>(<BinOp><BinOp>(<BinOp><Name>days</Name></BinOp> * <Num>24.</Num> + <Attribute><Name>self</Name>.hour</Attribute>)</BinOp></BinOp>*<Num>60.</Num> + <Attribute><Name>self</Name>.minute</Attribute>)</BinOp>*<Num>60.</Num></BinOp></Assign>
213.407 - <Return>return <BinOp><BinOp><Name>seconds</Name></BinOp> + <Attribute><Name>self</Name>.second</Attribute> + <BinOp><Attribute><Name>self</Name>.microsecond</Attribute></BinOp> / <Num>1e6</Num></BinOp></Return>
213.408 -
213.409 - </FunctionDef> <FunctionDef>def ctime(<Name>self</Name>):
213.410 - <Expr><Str>"Return ctime() style string."</Str></Expr>
213.411 - <Assign><Name>weekday</Name> = <BoolOp><BinOp><Call><Attribute><Name>self</Name>.toordinal</Attribute>()</Call> % <Num>7</Num></BinOp> or <Num>7</Num></BoolOp></Assign>
213.412 - <Return>return <BinOp><Str>"%s %s %2d %02d:%02d:%02d %04d"</Str> % <Tuple>(
213.413 - <Subscript><Name>_DAYNAMES</Name>[<Index><Name>weekday</Name></Index>]</Subscript>,
213.414 - <Subscript><Name>_MONTHNAMES</Name>[<Index><Attribute><Name>self</Name>.month</Attribute></Index>]</Subscript>,
213.415 - <Attribute><Name>self</Name>.day</Attribute>,
213.416 - <Attribute><Name>self</Name>.hour</Attribute>, <Attribute><Name>self</Name>.minute</Attribute>, <Attribute><Name>self</Name>.second</Attribute>,
213.417 - <Attribute><Name>self</Name>.year</Attribute>)</Tuple></BinOp></Return>
213.418 -
213.419 -</FunctionDef></ClassDef><ClassDef>class timedelta(<Name>object</Name>):
213.420 - <Expr><Str>"""Represent the difference between two datetime objects.
213.421 -
213.422 - Supported operators:
213.423 -
213.424 - - add, subtract timedelta
213.425 - - unary plus, minus, abs
213.426 - - compare to timedelta
213.427 - - multiply, divide by int/long
213.428 -
213.429 - In addition, datetime supports subtraction of two datetime objects
213.430 - returning a timedelta, and addition or subtraction of a datetime
213.431 - and a timedelta giving a datetime.
213.432 -
213.433 - Representation: (days, seconds, microseconds). Why? Because I
213.434 - felt like it.
213.435 - """</Str></Expr>
213.436 -
213.437 - <FunctionDef>def __new__(<Name>cls</Name>, <Name>days</Name>=<Num>0</Num>, <Name>seconds</Name>=<Num>0</Num>, <Name>microseconds</Name>=<Num>0</Num>,
213.438 - # XXX The following should only be used as keyword args:
213.439 - <Name>milliseconds</Name>=<Num>0</Num>, <Name>minutes</Name>=<Num>0</Num>, <Name>hours</Name>=<Num>0</Num>, <Name>weeks</Name>=<Num>0</Num>):
213.440 - # Doing this efficiently and accurately in C is going to be difficult
213.441 - # and error-prone, due to ubiquitous overflow possibilities, and that
213.442 - # C double doesn't have enough bits of precision to represent
213.443 - # microseconds over 10K years faithfully. The code here tries to make
213.444 - # explicit where go-fast assumptions can be relied on, in order to
213.445 - # guide the C implementation; it's way more convoluted than speed-
213.446 - # ignoring auto-overflow-to-long idiomatic Python could be.
213.447 -
213.448 - # XXX Check that all inputs are ints, longs or floats.
213.449 -
213.450 - # Final values, all integer.
213.451 - # s and us fit in 32-bit signed ints; d isn't bounded.
213.452 - <Assign><Name>d</Name> = <Name>s</Name> = <Name>us</Name> = <Num>0</Num></Assign>
213.453 -
213.454 - # Normalize everything to days, seconds, microseconds.
213.455 - <AugAssign><Name>days</Name> += <BinOp><Name>weeks</Name>*<Num>7</Num></BinOp></AugAssign>
213.456 - <AugAssign><Name>seconds</Name> += <BinOp><BinOp><Name>minutes</Name></BinOp>*<Num>60</Num> + <BinOp><Name>hours</Name></BinOp>*<Num>3600</Num></BinOp></AugAssign>
213.457 - <AugAssign><Name>microseconds</Name> += <BinOp><Name>milliseconds</Name>*<Num>1000</Num></BinOp></AugAssign>
213.458 -
213.459 - # Get rid of all fractions, and normalize s and us.
213.460 - # Take a deep breath <wink>.
213.461 - <If>if <Call><Name>isinstance</Name>(<Name>days</Name>, <Name>float</Name>)</Call>:
213.462 - <Assign><Tuple><Name>dayfrac</Name>, <Name>days</Name></Tuple> = <Call><Attribute><Name>_math</Name>.modf</Attribute>(<Name>days</Name>)</Call></Assign>
213.463 - <Assign><Tuple><Name>daysecondsfrac</Name>, <Name>daysecondswhole</Name></Tuple> = <Call><Attribute><Name>_math</Name>.modf</Attribute>(<BinOp><Name>dayfrac</Name> * <BinOp>(<Num>24.</Num>*<Num>3600.</Num>)</BinOp></BinOp>)</Call></Assign>
213.464 - <Assert>assert <Compare><Name>daysecondswhole</Name> == <Call><Name>int</Name>(<Name>daysecondswhole</Name>)</Call></Compare></Assert> # can't overflow
213.465 - <Assign><Name>s</Name> = <Call><Name>int</Name>(<Name>daysecondswhole</Name>)</Call></Assign>
213.466 - <Assert>assert <Compare><Name>days</Name> == <Call><Name>long</Name>(<Name>days</Name>)</Call></Compare></Assert>
213.467 - <Assign><Name>d</Name> = <Call><Name>long</Name>(<Name>days</Name>)</Call></Assign>
213.468 - else:
213.469 - <Assign><Name>daysecondsfrac</Name> = <Num>0.0</Num></Assign>
213.470 - <Assign><Name>d</Name> = <Name>days</Name></Assign>
213.471 - </If> <Assert>assert <Call><Name>isinstance</Name>(<Name>daysecondsfrac</Name>, <Name>float</Name>)</Call></Assert>
213.472 - <Assert>assert <Compare><Call><Name>abs</Name>(<Name>daysecondsfrac</Name>)</Call> <= <Num>1.0</Num></Compare></Assert>
213.473 - <Assert>assert <Call><Name>isinstance</Name>(<Name>d</Name>, <Tuple>(<Name>int</Name>, <Name>long</Name>)</Tuple>)</Call></Assert>
213.474 - <Assert>assert <Compare><Call><Name>abs</Name>(<Name>s</Name>)</Call> <= <BinOp><Num>24</Num> * <Num>3600</Num></BinOp></Compare></Assert>
213.475 - # days isn't referenced again before redefinition
213.476 -
213.477 - <If>if <Call><Name>isinstance</Name>(<Name>seconds</Name>, <Name>float</Name>)</Call>:
213.478 - <Assign><Tuple><Name>secondsfrac</Name>, <Name>seconds</Name></Tuple> = <Call><Attribute><Name>_math</Name>.modf</Attribute>(<Name>seconds</Name>)</Call></Assign>
213.479 - <Assert>assert <Compare><Name>seconds</Name> == <Call><Name>long</Name>(<Name>seconds</Name>)</Call></Compare></Assert>
213.480 - <Assign><Name>seconds</Name> = <Call><Name>long</Name>(<Name>seconds</Name>)</Call></Assign>
213.481 - <AugAssign><Name>secondsfrac</Name> += <Name>daysecondsfrac</Name></AugAssign>
213.482 - <Assert>assert <Compare><Call><Name>abs</Name>(<Name>secondsfrac</Name>)</Call> <= <Num>2.0</Num></Compare></Assert>
213.483 - else:
213.484 - <Assign><Name>secondsfrac</Name> = <Name>daysecondsfrac</Name></Assign>
213.485 - # daysecondsfrac isn't referenced again
213.486 - </If> <Assert>assert <Call><Name>isinstance</Name>(<Name>secondsfrac</Name>, <Name>float</Name>)</Call></Assert>
213.487 - <Assert>assert <Compare><Call><Name>abs</Name>(<Name>secondsfrac</Name>)</Call> <= <Num>2.0</Num></Compare></Assert>
213.488 -
213.489 - <Assert>assert <Call><Name>isinstance</Name>(<Name>seconds</Name>, <Tuple>(<Name>int</Name>, <Name>long</Name>)</Tuple>)</Call></Assert>
213.490 - <Assign><Tuple><Name>days</Name>, <Name>seconds</Name></Tuple> = <Call><Name>divmod</Name>(<Name>seconds</Name>, <BinOp><Num>24</Num>*<Num>3600</Num></BinOp>)</Call></Assign>
213.491 - <AugAssign><Name>d</Name> += <Name>days</Name></AugAssign>
213.492 - <AugAssign><Name>s</Name> += <Call><Name>int</Name>(<Name>seconds</Name>)</Call></AugAssign> # can't overflow
213.493 - <Assert>assert <Call><Name>isinstance</Name>(<Name>s</Name>, <Name>int</Name>)</Call></Assert>
213.494 - <Assert>assert <Compare><Call><Name>abs</Name>(<Name>s</Name>)</Call> <= <BinOp><BinOp><Num>2</Num></BinOp> * <Num>24</Num> * <Num>3600</Num></BinOp></Compare></Assert>
213.495 - # seconds isn't referenced again before redefinition
213.496 -
213.497 - <Assign><Name>usdouble</Name> = <BinOp><Name>secondsfrac</Name> * <Num>1e6</Num></BinOp></Assign>
213.498 - <Assert>assert <Compare><Call><Name>abs</Name>(<Name>usdouble</Name>)</Call> < <Num>2.1e6</Num></Compare></Assert> # exact value not critical
213.499 - # secondsfrac isn't referenced again
213.500 -
213.501 - <If>if <Call><Name>isinstance</Name>(<Name>microseconds</Name>, <Name>float</Name>)</Call>:
213.502 - <AugAssign><Name>microseconds</Name> += <Name>usdouble</Name></AugAssign>
213.503 - <Assign><Name>microseconds</Name> = <Call><Name>round</Name>(<Name>microseconds</Name>)</Call></Assign>
213.504 - <Assign><Tuple><Name>seconds</Name>, <Name>microseconds</Name></Tuple> = <Call><Name>divmod</Name>(<Name>microseconds</Name>, <Num>1e6</Num>)</Call></Assign>
213.505 - <Assert>assert <Compare><Name>microseconds</Name> == <Call><Name>int</Name>(<Name>microseconds</Name>)</Call></Compare></Assert>
213.506 - <Assert>assert <Compare><Name>seconds</Name> == <Call><Name>long</Name>(<Name>seconds</Name>)</Call></Compare></Assert>
213.507 - <Assign><Tuple><Name>days</Name>, <Name>seconds</Name></Tuple> = <Call><Name>divmod</Name>(<Name>seconds</Name>, <BinOp><Num>24.</Num>*<Num>3600.</Num></BinOp>)</Call></Assign>
213.508 - <Assert>assert <Compare><Name>days</Name> == <Call><Name>long</Name>(<Name>days</Name>)</Call></Compare></Assert>
213.509 - <Assert>assert <Compare><Name>seconds</Name> == <Call><Name>int</Name>(<Name>seconds</Name>)</Call></Compare></Assert>
213.510 - <AugAssign><Name>d</Name> += <Call><Name>long</Name>(<Name>days</Name>)</Call></AugAssign>
213.511 - <AugAssign><Name>s</Name> += <Call><Name>int</Name>(<Name>seconds</Name>)</Call></AugAssign> # can't overflow
213.512 - <Assert>assert <Call><Name>isinstance</Name>(<Name>s</Name>, <Name>int</Name>)</Call></Assert>
213.513 - <Assert>assert <Compare><Call><Name>abs</Name>(<Name>s</Name>)</Call> <= <BinOp><BinOp><Num>3</Num></BinOp> * <Num>24</Num> * <Num>3600</Num></BinOp></Compare></Assert>
213.514 - else:
213.515 - <Assign><Tuple><Name>seconds</Name>, <Name>microseconds</Name></Tuple> = <Call><Name>divmod</Name>(<Name>microseconds</Name>, <Num>1000000</Num>)</Call></Assign>
213.516 - <Assign><Tuple><Name>days</Name>, <Name>seconds</Name></Tuple> = <Call><Name>divmod</Name>(<Name>seconds</Name>, <BinOp><Num>24</Num>*<Num>3600</Num></BinOp>)</Call></Assign>
213.517 - <AugAssign><Name>d</Name> += <Name>days</Name></AugAssign>
213.518 - <AugAssign><Name>s</Name> += <Call><Name>int</Name>(<Name>seconds</Name>)</Call></AugAssign> # can't overflow
213.519 - <Assert>assert <Call><Name>isinstance</Name>(<Name>s</Name>, <Name>int</Name>)</Call></Assert>
213.520 - <Assert>assert <Compare><Call><Name>abs</Name>(<Name>s</Name>)</Call> <= <BinOp><BinOp><Num>3</Num></BinOp> * <Num>24</Num> * <Num>3600</Num></BinOp></Compare></Assert>
213.521 - <Assign><Name>microseconds</Name> = <Call><Name>float</Name>(<Name>microseconds</Name>)</Call></Assign>
213.522 - <AugAssign><Name>microseconds</Name> += <Name>usdouble</Name></AugAssign>
213.523 - <Assign><Name>microseconds</Name> = <Call><Name>round</Name>(<Name>microseconds</Name>)</Call></Assign>
213.524 - </If> <Assert>assert <Compare><Call><Name>abs</Name>(<Name>s</Name>)</Call> <= <BinOp><BinOp><Num>3</Num></BinOp> * <Num>24</Num> * <Num>3600</Num></BinOp></Compare></Assert>
213.525 - <Assert>assert <Compare><Call><Name>abs</Name>(<Name>microseconds</Name>)</Call> < <Num>3.1e6</Num></Compare></Assert>
213.526 -
213.527 - # Just a little bit of carrying possible for microseconds and seconds.
213.528 - <Assert>assert <Call><Name>isinstance</Name>(<Name>microseconds</Name>, <Name>float</Name>)</Call></Assert>
213.529 - <Assert>assert <Compare><Call><Name>int</Name>(<Name>microseconds</Name>)</Call> == <Name>microseconds</Name></Compare></Assert>
213.530 - <Assign><Name>us</Name> = <Call><Name>int</Name>(<Name>microseconds</Name>)</Call></Assign>
213.531 - <Assign><Tuple><Name>seconds</Name>, <Name>us</Name></Tuple> = <Call><Name>divmod</Name>(<Name>us</Name>, <Num>1000000</Num>)</Call></Assign>
213.532 - <AugAssign><Name>s</Name> += <Name>seconds</Name></AugAssign> # cant't overflow
213.533 - <Assert>assert <Call><Name>isinstance</Name>(<Name>s</Name>, <Name>int</Name>)</Call></Assert>
213.534 - <Assign><Tuple><Name>days</Name>, <Name>s</Name></Tuple> = <Call><Name>divmod</Name>(<Name>s</Name>, <BinOp><Num>24</Num>*<Num>3600</Num></BinOp>)</Call></Assign>
213.535 - <AugAssign><Name>d</Name> += <Name>days</Name></AugAssign>
213.536 -
213.537 - <Assert>assert <Call><Name>isinstance</Name>(<Name>d</Name>, <Tuple>(<Name>int</Name>, <Name>long</Name>)</Tuple>)</Call></Assert>
213.538 - <Assert>assert <BoolOp><Call><Name>isinstance</Name>(<Name>s</Name>, <Name>int</Name>)</Call> and <Compare><Num>0</Num> <= <Name>s</Name> < <BinOp><Num>24</Num>*<Num>3600</Num></BinOp></Compare></BoolOp></Assert>
213.539 - <Assert>assert <BoolOp><Call><Name>isinstance</Name>(<Name>us</Name>, <Name>int</Name>)</Call> and <Compare><Num>0</Num> <= <Name>us</Name> < <Num>1000000</Num></Compare></BoolOp></Assert>
213.540 -
213.541 - <Assign><Name>self</Name> = <Call><Attribute><Name>object</Name>.__new__</Attribute>(<Name>cls</Name>)</Call></Assign>
213.542 -
213.543 - <Assign><Attribute><Name>self</Name>.__days</Attribute> = <Name>d</Name></Assign>
213.544 - <Assign><Attribute><Name>self</Name>.__seconds</Attribute> = <Name>s</Name></Assign>
213.545 - <Assign><Attribute><Name>self</Name>.__microseconds</Attribute> = <Name>us</Name></Assign>
213.546 - <If>if <Compare><Call><Name>abs</Name>(<Name>d</Name>)</Call> > <Num>999999999</Num></Compare>:
213.547 - <Raise>raise <Call><Name>OverflowError</Name>(<BinOp><Str>"timedelta # of days is too large: %d"</Str> % <Name>d</Name></BinOp>)</Call></Raise>
213.548 -
213.549 - </If> <Return>return <Name>self</Name></Return>
213.550 -
213.551 - </FunctionDef> <FunctionDef>def __repr__(<Name>self</Name>):
213.552 - <If>if <Attribute><Name>self</Name>.__microseconds</Attribute>:
213.553 - <Return>return <BinOp><Str>"%s(%d, %d, %d)"</Str> % <Tuple>(<BinOp><Str>'datetime.'</Str> + <Attribute><Attribute><Name>self</Name>.__class__</Attribute>.__name__</Attribute></BinOp>,
213.554 - <Attribute><Name>self</Name>.__days</Attribute>,
213.555 - <Attribute><Name>self</Name>.__seconds</Attribute>,
213.556 - <Attribute><Name>self</Name>.__microseconds</Attribute>)</Tuple></BinOp></Return>
213.557 - </If> <If>if <Attribute><Name>self</Name>.__seconds</Attribute>:
213.558 - <Return>return <BinOp><Str>"%s(%d, %d)"</Str> % <Tuple>(<BinOp><Str>'datetime.'</Str> + <Attribute><Attribute><Name>self</Name>.__class__</Attribute>.__name__</Attribute></BinOp>,
213.559 - <Attribute><Name>self</Name>.__days</Attribute>,
213.560 - <Attribute><Name>self</Name>.__seconds</Attribute>)</Tuple></BinOp></Return>
213.561 - </If> <Return>return <BinOp><Str>"%s(%d)"</Str> % <Tuple>(<BinOp><Str>'datetime.'</Str> + <Attribute><Attribute><Name>self</Name>.__class__</Attribute>.__name__</Attribute></BinOp>, <Attribute><Name>self</Name>.__days</Attribute>)</Tuple></BinOp></Return>
213.562 -
213.563 - </FunctionDef> <FunctionDef>def __str__(<Name>self</Name>):
213.564 - <Assign><Tuple><Name>mm</Name>, <Name>ss</Name></Tuple> = <Call><Name>divmod</Name>(<Attribute><Name>self</Name>.__seconds</Attribute>, <Num>60</Num>)</Call></Assign>
213.565 - <Assign><Tuple><Name>hh</Name>, <Name>mm</Name></Tuple> = <Call><Name>divmod</Name>(<Name>mm</Name>, <Num>60</Num>)</Call></Assign>
213.566 - <Assign><Name>s</Name> = <BinOp><Str>"%d:%02d:%02d"</Str> % <Tuple>(<Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>)</Tuple></BinOp></Assign>
213.567 - <If>if <Attribute><Name>self</Name>.__days</Attribute>:
213.568 - <FunctionDef>def plural(<Name>n</Name>):
213.569 - <Return>return <Tuple><Name>n</Name>, <BoolOp><BoolOp><Compare><Call><Name>abs</Name>(<Name>n</Name>)</Call> != <Num>1</Num></Compare></BoolOp> and <Str>"s"</Str> or <Str>""</Str></BoolOp></Tuple></Return>
213.570 - </FunctionDef> <Assign><Name>s</Name> = <BinOp><BinOp>(<Str>"%d day%s, "</Str> % <Call><Name>plural</Name>(<Attribute><Name>self</Name>.__days</Attribute>)</Call>)</BinOp> + <Name>s</Name></BinOp></Assign>
213.571 - </If> <If>if <Attribute><Name>self</Name>.__microseconds</Attribute>:
213.572 - <Assign><Name>s</Name> = <BinOp><Name>s</Name> + <BinOp><Str>".%06d"</Str></BinOp> % <Attribute><Name>self</Name>.__microseconds</Attribute></BinOp></Assign>
213.573 - </If> <Return>return <Name>s</Name></Return>
213.574 -
213.575 - </FunctionDef> <Assign><Name>days</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>.__days</Attribute></Lambda>, doc=<Str>"days"</Str>)</Call></Assign>
213.576 - <Assign><Name>seconds</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>.__seconds</Attribute></Lambda>, doc=<Str>"seconds"</Str>)</Call></Assign>
213.577 - <Assign><Name>microseconds</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>.__microseconds</Attribute></Lambda>,
213.578 - doc=<Str>"microseconds"</Str>)</Call></Assign>
213.579 -
213.580 - <FunctionDef>def __add__(<Name>self</Name>, <Name>other</Name>):
213.581 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
213.582 - <Return>return <Call><Name>timedelta</Name>(<BinOp><Attribute><Name>self</Name>.__days</Attribute> + <Attribute><Name>other</Name>.__days</Attribute></BinOp>,
213.583 - <BinOp><Attribute><Name>self</Name>.__seconds</Attribute> + <Attribute><Name>other</Name>.__seconds</Attribute></BinOp>,
213.584 - <BinOp><Attribute><Name>self</Name>.__microseconds</Attribute> + <Attribute><Name>other</Name>.__microseconds</Attribute></BinOp>)</Call></Return>
213.585 - </If> <Return>return <Name>NotImplemented</Name></Return>
213.586 -
213.587 - </FunctionDef> <Assign><Name>__radd__</Name> = <Name>__add__</Name></Assign>
213.588 -
213.589 - <FunctionDef>def __sub__(<Name>self</Name>, <Name>other</Name>):
213.590 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
213.591 - <Return>return <BinOp><Name>self</Name> + <UnaryOp>-<Name>other</Name></UnaryOp></BinOp></Return>
213.592 - </If> <Return>return <Name>NotImplemented</Name></Return>
213.593 -
213.594 - </FunctionDef> <FunctionDef>def __rsub__(<Name>self</Name>, <Name>other</Name>):
213.595 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
213.596 - <Return>return <BinOp><UnaryOp>-<Name>self</Name></UnaryOp> + <Name>other</Name></BinOp></Return>
213.597 - </If> <Return>return <Name>NotImplemented</Name></Return>
213.598 -
213.599 - </FunctionDef> <FunctionDef>def __neg__(<Name>self</Name>):
213.600 - <Return>return <Call><Attribute><Name>self</Name>.__class__</Attribute>(<UnaryOp>-<Attribute><Name>self</Name>.__days</Attribute></UnaryOp>,
213.601 - <UnaryOp>-<Attribute><Name>self</Name>.__seconds</Attribute></UnaryOp>,
213.602 - <UnaryOp>-<Attribute><Name>self</Name>.__microseconds</Attribute></UnaryOp>)</Call></Return>
213.603 -
213.604 - </FunctionDef> <FunctionDef>def __pos__(<Name>self</Name>):
213.605 - <Return>return <Name>self</Name></Return>
213.606 -
213.607 - </FunctionDef> <FunctionDef>def __abs__(<Name>self</Name>):
213.608 - <If>if <Compare><Attribute><Name>self</Name>.__days</Attribute> < <Num>0</Num></Compare>:
213.609 - <Return>return <UnaryOp>-<Name>self</Name></UnaryOp></Return>
213.610 - else:
213.611 - <Return>return <Name>self</Name></Return>
213.612 -
213.613 - </If></FunctionDef> <FunctionDef>def __mul__(<Name>self</Name>, <Name>other</Name>):
213.614 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Tuple>(<Name>int</Name>, <Name>long</Name>)</Tuple>)</Call>:
213.615 - <Return>return <Call><Attribute><Name>self</Name>.__class__</Attribute>(<BinOp><Attribute><Name>self</Name>.__days</Attribute> * <Name>other</Name></BinOp>,
213.616 - <BinOp><Attribute><Name>self</Name>.__seconds</Attribute> * <Name>other</Name></BinOp>,
213.617 - <BinOp><Attribute><Name>self</Name>.__microseconds</Attribute> * <Name>other</Name></BinOp>)</Call></Return>
213.618 - </If> <Return>return <Name>NotImplemented</Name></Return>
213.619 -
213.620 - </FunctionDef> <Assign><Name>__rmul__</Name> = <Name>__mul__</Name></Assign>
213.621 -
213.622 - <FunctionDef>def __div__(<Name>self</Name>, <Name>other</Name>):
213.623 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Tuple>(<Name>int</Name>, <Name>long</Name>)</Tuple>)</Call>:
213.624 - <Assign><Name>usec</Name> = <BinOp>(<BinOp><BinOp>(<BinOp><Attribute><Name>self</Name>.__days</Attribute></BinOp> * <BinOp>(<Num>24</Num>*<Num>3600L</Num>)</BinOp> + <Attribute><Name>self</Name>.__seconds</Attribute>)</BinOp></BinOp> * <Num>1000000</Num> +
213.625 - <Attribute><Name>self</Name>.__microseconds</Attribute>)</BinOp></Assign>
213.626 - <Return>return <Call><Attribute><Name>self</Name>.__class__</Attribute>(<Num>0</Num>, <Num>0</Num>, <BinOp><Name>usec</Name> // <Name>other</Name></BinOp>)</Call></Return>
213.627 - </If> <Return>return <Name>NotImplemented</Name></Return>
213.628 -
213.629 - </FunctionDef> <Assign><Name>__floordiv__</Name> = <Name>__div__</Name></Assign>
213.630 -
213.631 - # Comparisons.
213.632 -
213.633 - <FunctionDef>def __eq__(<Name>self</Name>, <Name>other</Name>):
213.634 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
213.635 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> == <Num>0</Num></Compare></Return>
213.636 - else:
213.637 - <Return>return <Name>False</Name></Return>
213.638 -
213.639 - </If></FunctionDef> <FunctionDef>def __ne__(<Name>self</Name>, <Name>other</Name>):
213.640 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
213.641 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> != <Num>0</Num></Compare></Return>
213.642 - else:
213.643 - <Return>return <Name>True</Name></Return>
213.644 -
213.645 - </If></FunctionDef> <FunctionDef>def __le__(<Name>self</Name>, <Name>other</Name>):
213.646 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
213.647 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> <= <Num>0</Num></Compare></Return>
213.648 - else:
213.649 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
213.650 -
213.651 - </If></FunctionDef> <FunctionDef>def __lt__(<Name>self</Name>, <Name>other</Name>):
213.652 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
213.653 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> < <Num>0</Num></Compare></Return>
213.654 - else:
213.655 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
213.656 -
213.657 - </If></FunctionDef> <FunctionDef>def __ge__(<Name>self</Name>, <Name>other</Name>):
213.658 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
213.659 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> >= <Num>0</Num></Compare></Return>
213.660 - else:
213.661 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
213.662 -
213.663 - </If></FunctionDef> <FunctionDef>def __gt__(<Name>self</Name>, <Name>other</Name>):
213.664 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
213.665 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> > <Num>0</Num></Compare></Return>
213.666 - else:
213.667 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
213.668 -
213.669 - </If></FunctionDef> <FunctionDef>def __cmp(<Name>self</Name>, <Name>other</Name>):
213.670 - <Assert>assert <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call></Assert>
213.671 - <Return>return <Call><Name>cmp</Name>(<Call><Attribute><Name>self</Name>.__getstate</Attribute>()</Call>, <Call><Attribute><Name>other</Name>.__getstate</Attribute>()</Call>)</Call></Return>
213.672 -
213.673 - </FunctionDef> <FunctionDef>def __hash__(<Name>self</Name>):
213.674 - <Return>return <Call><Name>hash</Name>(<Call><Attribute><Name>self</Name>.__getstate</Attribute>()</Call>)</Call></Return>
213.675 -
213.676 - </FunctionDef> <FunctionDef>def __nonzero__(<Name>self</Name>):
213.677 - <Return>return <BoolOp>(<Compare><Attribute><Name>self</Name>.__days</Attribute> != <Num>0</Num></Compare> or
213.678 - <Compare><Attribute><Name>self</Name>.__seconds</Attribute> != <Num>0</Num></Compare> or
213.679 - <Compare><Attribute><Name>self</Name>.__microseconds</Attribute> != <Num>0</Num></Compare>)</BoolOp></Return>
213.680 -
213.681 - # Pickle support.
213.682 -
213.683 - </FunctionDef> <Assign><Name>__safe_for_unpickling__</Name> = <Name>True</Name></Assign> # For Python 2.2
213.684 -
213.685 - <FunctionDef>def __getstate(<Name>self</Name>):
213.686 - <Return>return <Tuple>(<Attribute><Name>self</Name>.__days</Attribute>, <Attribute><Name>self</Name>.__seconds</Attribute>, <Attribute><Name>self</Name>.__microseconds</Attribute>)</Tuple></Return>
213.687 -
213.688 - </FunctionDef> <FunctionDef>def __reduce__(<Name>self</Name>):
213.689 - <Return>return <Tuple>(<Attribute><Name>self</Name>.__class__</Attribute>, <Call><Attribute><Name>self</Name>.__getstate</Attribute>()</Call>)</Tuple></Return>
213.690 -
213.691 -</FunctionDef></ClassDef><Assign><Attribute><Name>timedelta</Name>.min</Attribute> = <Call><Name>timedelta</Name>(<Num>-999999999</Num>)</Call></Assign>
213.692 -<Assign><Attribute><Name>timedelta</Name>.max</Attribute> = <Call><Name>timedelta</Name>(days=<Num>999999999</Num>, hours=<Num>23</Num>, minutes=<Num>59</Num>, seconds=<Num>59</Num>,
213.693 - microseconds=<Num>999999</Num>)</Call></Assign>
213.694 -<Assign><Attribute><Name>timedelta</Name>.resolution</Attribute> = <Call><Name>timedelta</Name>(microseconds=<Num>1</Num>)</Call></Assign>
213.695 -
213.696 -<ClassDef>class date(<Name>object</Name>):
213.697 - <Expr><Str>"""Concrete date type.
213.698 -
213.699 - Constructors:
213.700 -
213.701 - __new__()
213.702 - fromtimestamp()
213.703 - today()
213.704 - fromordinal()
213.705 -
213.706 - Operators:
213.707 -
213.708 - __repr__, __str__
213.709 - __cmp__, __hash__
213.710 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
213.711 -
213.712 - Methods:
213.713 -
213.714 - timetuple()
213.715 - toordinal()
213.716 - weekday()
213.717 - isoweekday(), isocalendar(), isoformat()
213.718 - ctime()
213.719 - strftime()
213.720 -
213.721 - Properties (readonly):
213.722 - year, month, day
213.723 - """</Str></Expr>
213.724 -
213.725 - <FunctionDef>def __new__(<Name>cls</Name>, <Name>year</Name>, <Name>month</Name>=<Name>None</Name>, <Name>day</Name>=<Name>None</Name>):
213.726 - <Expr><Str>"""Constructor.
213.727 -
213.728 - Arguments:
213.729 -
213.730 - year, month, day (required, base 1)
213.731 - """</Str></Expr>
213.732 - <If>if <Call><Name>isinstance</Name>(<Name>year</Name>, <Name>str</Name>)</Call>:
213.733 - # Pickle support
213.734 - <Assign><Name>self</Name> = <Call><Attribute><Name>object</Name>.__new__</Attribute>(<Name>cls</Name>)</Call></Assign>
213.735 - <Expr><Call><Attribute><Name>self</Name>.__setstate</Attribute>(<Tuple>(<Name>year</Name>,)</Tuple>)</Call></Expr>
213.736 - <Return>return <Name>self</Name></Return>
213.737 - </If> <Expr><Call><Name>_check_date_fields</Name>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>)</Call></Expr>
213.738 - <Assign><Name>self</Name> = <Call><Attribute><Name>object</Name>.__new__</Attribute>(<Name>cls</Name>)</Call></Assign>
213.739 - <Assign><Attribute><Name>self</Name>.__year</Attribute> = <Name>year</Name></Assign>
213.740 - <Assign><Attribute><Name>self</Name>.__month</Attribute> = <Name>month</Name></Assign>
213.741 - <Assign><Attribute><Name>self</Name>.__day</Attribute> = <Name>day</Name></Assign>
213.742 - <Return>return <Name>self</Name></Return>
213.743 -
213.744 - # Additional constructors
213.745 -
213.746 - </FunctionDef> <FunctionDef>def fromtimestamp(<Name>cls</Name>, <Name>t</Name>):
213.747 - <Expr><Str>"Construct a date from a POSIX timestamp (like time.time())."</Str></Expr>
213.748 - <Assign><Tuple><Name>y</Name>, <Name>m</Name>, <Name>d</Name>, <Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Name>weekday</Name>, <Name>jday</Name>, <Name>dst</Name></Tuple> = <Call><Attribute><Name>_time</Name>.localtime</Attribute>(<Name>t</Name>)</Call></Assign>
213.749 - <Return>return <Call><Name>cls</Name>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>)</Call></Return>
213.750 - </FunctionDef> <Assign><Name>fromtimestamp</Name> = <Call><Name>classmethod</Name>(<Name>fromtimestamp</Name>)</Call></Assign>
213.751 -
213.752 - <FunctionDef>def today(<Name>cls</Name>):
213.753 - <Expr><Str>"Construct a date from time.time()."</Str></Expr>
213.754 - <Assign><Name>t</Name> = <Call><Attribute><Name>_time</Name>.time</Attribute>()</Call></Assign>
213.755 - <Return>return <Call><Attribute><Name>cls</Name>.fromtimestamp</Attribute>(<Name>t</Name>)</Call></Return>
213.756 - </FunctionDef> <Assign><Name>today</Name> = <Call><Name>classmethod</Name>(<Name>today</Name>)</Call></Assign>
213.757 -
213.758 - <FunctionDef>def fromordinal(<Name>cls</Name>, <Name>n</Name>):
213.759 - <Expr><Str>"""Contruct a date from a proleptic Gregorian ordinal.
213.760 -
213.761 - January 1 of year 1 is day 1. Only the year, month and day are
213.762 - non-zero in the result.
213.763 - """</Str></Expr>
213.764 - <Assign><Tuple><Name>y</Name>, <Name>m</Name>, <Name>d</Name></Tuple> = <Call><Name>_ord2ymd</Name>(<Name>n</Name>)</Call></Assign>
213.765 - <Return>return <Call><Name>cls</Name>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>)</Call></Return>
213.766 - </FunctionDef> <Assign><Name>fromordinal</Name> = <Call><Name>classmethod</Name>(<Name>fromordinal</Name>)</Call></Assign>
213.767 -
213.768 - # Conversions to string
213.769 -
213.770 - <FunctionDef>def __repr__(<Name>self</Name>):
213.771 - <Expr><Str>"Convert to formal string, for repr()."</Str></Expr>
213.772 - <Return>return <BinOp><Str>"%s(%d, %d, %d)"</Str> % <Tuple>(<BinOp><Str>'datetime.'</Str> + <Attribute><Attribute><Name>self</Name>.__class__</Attribute>.__name__</Attribute></BinOp>,
213.773 - <Attribute><Name>self</Name>.__year</Attribute>,
213.774 - <Attribute><Name>self</Name>.__month</Attribute>,
213.775 - <Attribute><Name>self</Name>.__day</Attribute>)</Tuple></BinOp></Return>
213.776 - # XXX These shouldn't depend on time.localtime(), because that
213.777 - # clips the usable dates to [1970 .. 2038). At least ctime() is
213.778 - # easily done without using strftime() -- that's better too because
213.779 - # strftime("%c", ...) is locale specific.
213.780 -
213.781 - </FunctionDef> <FunctionDef>def ctime(<Name>self</Name>):
213.782 - <Expr><Str>"Format a la ctime()."</Str></Expr>
213.783 - <Return>return <Call><Name>tmxxx</Name><Attribute><Call>(<Attribute><Name>self</Name>.__year</Attribute>, <Attribute><Name>self</Name>.__month</Attribute>, <Attribute><Name>self</Name>.__day</Attribute>)</Call>.ctime</Attribute>()</Call></Return>
213.784 -
213.785 - </FunctionDef> <FunctionDef>def strftime(<Name>self</Name>, <Name>fmt</Name>):
213.786 - <Expr><Str>"Format using strftime()."</Str></Expr>
213.787 - <Return>return <Call><Name>_wrap_strftime</Name>(<Name>self</Name>, <Name>fmt</Name>, <Call><Attribute><Name>self</Name>.timetuple</Attribute>()</Call>)</Call></Return>
213.788 -
213.789 - </FunctionDef> <FunctionDef>def isoformat(<Name>self</Name>):
213.790 - <Expr><Str>"""Return the date formatted according to ISO.
213.791 -
213.792 - This is 'YYYY-MM-DD'.
213.793 -
213.794 - References:
213.795 - - http://www.w3.org/TR/NOTE-datetime
213.796 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
213.797 - """</Str></Expr>
213.798 - <Return>return <BinOp><Str>"%04d-%02d-%02d"</Str> % <Tuple>(<Attribute><Name>self</Name>.__year</Attribute>, <Attribute><Name>self</Name>.__month</Attribute>, <Attribute><Name>self</Name>.__day</Attribute>)</Tuple></BinOp></Return>
213.799 -
213.800 - </FunctionDef> <Assign><Name>__str__</Name> = <Name>isoformat</Name></Assign>
213.801 -
213.802 - # Read-only field accessors
213.803 - <Assign><Name>year</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>.__year</Attribute></Lambda>,
213.804 - doc=<BinOp><Str>"year (%d-%d)"</Str> % <Tuple>(<Name>MINYEAR</Name>, <Name>MAXYEAR</Name>)</Tuple></BinOp>)</Call></Assign>
213.805 - <Assign><Name>month</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>.__month</Attribute></Lambda>, doc=<Str>"month (1-12)"</Str>)</Call></Assign>
213.806 - <Assign><Name>day</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>.__day</Attribute></Lambda>, doc=<Str>"day (1-31)"</Str>)</Call></Assign>
213.807 -
213.808 - # Standard conversions, __cmp__, __hash__ (and helpers)
213.809 -
213.810 - <FunctionDef>def timetuple(<Name>self</Name>):
213.811 - <Expr><Str>"Return local time tuple compatible with time.localtime()."</Str></Expr>
213.812 - <Return>return <Call><Name>_build_struct_time</Name>(<Attribute><Name>self</Name>.__year</Attribute>, <Attribute><Name>self</Name>.__month</Attribute>, <Attribute><Name>self</Name>.__day</Attribute>,
213.813 - <Num>0</Num>, <Num>0</Num>, <Num>0</Num>, <Num>-1</Num>)</Call></Return>
213.814 -
213.815 - </FunctionDef> <FunctionDef>def toordinal(<Name>self</Name>):
213.816 - <Expr><Str>"""Return proleptic Gregorian ordinal for the year, month and day.
213.817 -
213.818 - January 1 of year 1 is day 1. Only the year, month and day values
213.819 - contribute to the result.
213.820 - """</Str></Expr>
213.821 - <Return>return <Call><Name>_ymd2ord</Name>(<Attribute><Name>self</Name>.__year</Attribute>, <Attribute><Name>self</Name>.__month</Attribute>, <Attribute><Name>self</Name>.__day</Attribute>)</Call></Return>
213.822 -
213.823 - </FunctionDef> <FunctionDef>def replace(<Name>self</Name>, <Name>year</Name>=<Name>None</Name>, <Name>month</Name>=<Name>None</Name>, <Name>day</Name>=<Name>None</Name>):
213.824 - <Expr><Str>"""Return a new date with new values for the specified fields."""</Str></Expr>
213.825 - <If>if <Compare><Name>year</Name> is <Name>None</Name></Compare>:
213.826 - <Assign><Name>year</Name> = <Attribute><Name>self</Name>.__year</Attribute></Assign>
213.827 - </If> <If>if <Compare><Name>month</Name> is <Name>None</Name></Compare>:
213.828 - <Assign><Name>month</Name> = <Attribute><Name>self</Name>.__month</Attribute></Assign>
213.829 - </If> <If>if <Compare><Name>day</Name> is <Name>None</Name></Compare>:
213.830 - <Assign><Name>day</Name> = <Attribute><Name>self</Name>.__day</Attribute></Assign>
213.831 - </If> <Expr><Call><Name>_check_date_fields</Name>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>)</Call></Expr>
213.832 - <Return>return <Call><Name>date</Name>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>)</Call></Return>
213.833 -
213.834 - # Comparisons.
213.835 -
213.836 - </FunctionDef> <FunctionDef>def __eq__(<Name>self</Name>, <Name>other</Name>):
213.837 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>date</Name>)</Call>:
213.838 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> == <Num>0</Num></Compare></Return>
213.839 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
213.840 - <Return>return <Name>NotImplemented</Name></Return>
213.841 - else:
213.842 - <Return>return <Name>False</Name></Return>
213.843 -
213.844 - </If></If></FunctionDef> <FunctionDef>def __ne__(<Name>self</Name>, <Name>other</Name>):
213.845 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>date</Name>)</Call>:
213.846 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> != <Num>0</Num></Compare></Return>
213.847 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
213.848 - <Return>return <Name>NotImplemented</Name></Return>
213.849 - else:
213.850 - <Return>return <Name>True</Name></Return>
213.851 -
213.852 - </If></If></FunctionDef> <FunctionDef>def __le__(<Name>self</Name>, <Name>other</Name>):
213.853 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>date</Name>)</Call>:
213.854 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> <= <Num>0</Num></Compare></Return>
213.855 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
213.856 - <Return>return <Name>NotImplemented</Name></Return>
213.857 - else:
213.858 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
213.859 -
213.860 - </If></If></FunctionDef> <FunctionDef>def __lt__(<Name>self</Name>, <Name>other</Name>):
213.861 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>date</Name>)</Call>:
213.862 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> < <Num>0</Num></Compare></Return>
213.863 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
213.864 - <Return>return <Name>NotImplemented</Name></Return>
213.865 - else:
213.866 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
213.867 -
213.868 - </If></If></FunctionDef> <FunctionDef>def __ge__(<Name>self</Name>, <Name>other</Name>):
213.869 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>date</Name>)</Call>:
213.870 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> >= <Num>0</Num></Compare></Return>
213.871 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
213.872 - <Return>return <Name>NotImplemented</Name></Return>
213.873 - else:
213.874 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
213.875 -
213.876 - </If></If></FunctionDef> <FunctionDef>def __gt__(<Name>self</Name>, <Name>other</Name>):
213.877 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>date</Name>)</Call>:
213.878 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> > <Num>0</Num></Compare></Return>
213.879 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
213.880 - <Return>return <Name>NotImplemented</Name></Return>
213.881 - else:
213.882 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
213.883 -
213.884 - </If></If></FunctionDef> <FunctionDef>def __cmp(<Name>self</Name>, <Name>other</Name>):
213.885 - <Assert>assert <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>date</Name>)</Call></Assert>
213.886 - <Assign><Tuple><Name>y</Name>, <Name>m</Name>, <Name>d</Name></Tuple> = <Tuple><Attribute><Name>self</Name>.__year</Attribute>, <Attribute><Name>self</Name>.__month</Attribute>, <Attribute><Name>self</Name>.__day</Attribute></Tuple></Assign>
213.887 - <Assign><Tuple><Name>y2</Name>, <Name>m2</Name>, <Name>d2</Name></Tuple> = <Tuple><Attribute><Name>other</Name>.__year</Attribute>, <Attribute><Name>other</Name>.__month</Attribute>, <Attribute><Name>other</Name>.__day</Attribute></Tuple></Assign>
213.888 - <Return>return <Call><Name>cmp</Name>(<Tuple>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>)</Tuple>, <Tuple>(<Name>y2</Name>, <Name>m2</Name>, <Name>d2</Name>)</Tuple>)</Call></Return>
213.889 -
213.890 - </FunctionDef> <FunctionDef>def __hash__(<Name>self</Name>):
213.891 - <Expr><Str>"Hash."</Str></Expr>
213.892 - <Return>return <Call><Name>hash</Name>(<Call><Attribute><Name>self</Name>.__getstate</Attribute>()</Call>)</Call></Return>
213.893 -
213.894 - # Computations
213.895 -
213.896 - </FunctionDef> <FunctionDef>def _checkOverflow(<Name>self</Name>, <Name>year</Name>):
213.897 - <If>if <UnaryOp>not <Compare><Name>MINYEAR</Name> <= <Name>year</Name> <= <Name>MAXYEAR</Name></Compare></UnaryOp>:
213.898 - <Raise>raise <Call><Name>OverflowError</Name>(<BinOp><Str>"date +/-: result year %d not in %d..%d"</Str> %
213.899 - <Tuple>(<Name>year</Name>, <Name>MINYEAR</Name>, <Name>MAXYEAR</Name>)</Tuple></BinOp>)</Call></Raise>
213.900 -
213.901 - </If></FunctionDef> <FunctionDef>def __add__(<Name>self</Name>, <Name>other</Name>):
213.902 - <Expr><Str>"Add a date to a timedelta."</Str></Expr>
213.903 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
213.904 - <Assign><Name>t</Name> = <Call><Name>tmxxx</Name>(<Attribute><Name>self</Name>.__year</Attribute>,
213.905 - <Attribute><Name>self</Name>.__month</Attribute>,
213.906 - <BinOp><Attribute><Name>self</Name>.__day</Attribute> + <Attribute><Name>other</Name>.days</Attribute></BinOp>)</Call></Assign>
213.907 - <Expr><Call><Attribute><Name>self</Name>._checkOverflow</Attribute>(<Attribute><Name>t</Name>.year</Attribute>)</Call></Expr>
213.908 - <Assign><Name>result</Name> = <Call><Attribute><Name>self</Name>.__class__</Attribute>(<Attribute><Name>t</Name>.year</Attribute>, <Attribute><Name>t</Name>.month</Attribute>, <Attribute><Name>t</Name>.day</Attribute>)</Call></Assign>
213.909 - <Return>return <Name>result</Name></Return>
213.910 - </If> <Return>return <Name>NotImplemented</Name></Return>
213.911 -
213.912 - </FunctionDef> <Assign><Name>__radd__</Name> = <Name>__add__</Name></Assign>
213.913 -
213.914 - <FunctionDef>def __sub__(<Name>self</Name>, <Name>other</Name>):
213.915 - <Expr><Str>"""Subtract two dates, or a date and a timedelta."""</Str></Expr>
213.916 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
213.917 - <Return>return <BinOp><Name>self</Name> + <Call><Name>timedelta</Name>(<UnaryOp>-<Attribute><Name>other</Name>.days</Attribute></UnaryOp>)</Call></BinOp></Return>
213.918 - </If> <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>date</Name>)</Call>:
213.919 - <Assign><Name>days1</Name> = <Call><Attribute><Name>self</Name>.toordinal</Attribute>()</Call></Assign>
213.920 - <Assign><Name>days2</Name> = <Call><Attribute><Name>other</Name>.toordinal</Attribute>()</Call></Assign>
213.921 - <Return>return <Call><Name>timedelta</Name>(<BinOp><Name>days1</Name> - <Name>days2</Name></BinOp>)</Call></Return>
213.922 - </If> <Return>return <Name>NotImplemented</Name></Return>
213.923 -
213.924 - </FunctionDef> <FunctionDef>def weekday(<Name>self</Name>):
213.925 - <Expr><Str>"Return day of the week, where Monday == 0 ... Sunday == 6."</Str></Expr>
213.926 - <Return>return <BinOp><BinOp>(<Call><Attribute><Name>self</Name>.toordinal</Attribute>()</Call> + <Num>6</Num>)</BinOp> % <Num>7</Num></BinOp></Return>
213.927 -
213.928 - # Day-of-the-week and week-of-the-year, according to ISO
213.929 -
213.930 - </FunctionDef> <FunctionDef>def isoweekday(<Name>self</Name>):
213.931 - <Expr><Str>"Return day of the week, where Monday == 1 ... Sunday == 7."</Str></Expr>
213.932 - # 1-Jan-0001 is a Monday
213.933 - <Return>return <BoolOp><BinOp><Call><Attribute><Name>self</Name>.toordinal</Attribute>()</Call> % <Num>7</Num></BinOp> or <Num>7</Num></BoolOp></Return>
213.934 -
213.935 - </FunctionDef> <FunctionDef>def isocalendar(<Name>self</Name>):
213.936 - <Expr><Str>"""Return a 3-tuple containing ISO year, week number, and weekday.
213.937 -
213.938 - The first ISO week of the year is the (Mon-Sun) week
213.939 - containing the year's first Thursday; everything else derives
213.940 - from that.
213.941 -
213.942 - The first week is 1; Monday is 1 ... Sunday is 7.
213.943 -
213.944 - ISO calendar algorithm taken from
213.945 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
213.946 - """</Str></Expr>
213.947 - <Assign><Name>year</Name> = <Attribute><Name>self</Name>.__year</Attribute></Assign>
213.948 - <Assign><Name>week1monday</Name> = <Call><Name>_isoweek1monday</Name>(<Name>year</Name>)</Call></Assign>
213.949 - <Assign><Name>today</Name> = <Call><Name>_ymd2ord</Name>(<Attribute><Name>self</Name>.__year</Attribute>, <Attribute><Name>self</Name>.__month</Attribute>, <Attribute><Name>self</Name>.__day</Attribute>)</Call></Assign>
213.950 - # Internally, week and day have origin 0
213.951 - <Assign><Tuple><Name>week</Name>, <Name>day</Name></Tuple> = <Call><Name>divmod</Name>(<BinOp><Name>today</Name> - <Name>week1monday</Name></BinOp>, <Num>7</Num>)</Call></Assign>
213.952 - <If>if <Compare><Name>week</Name> < <Num>0</Num></Compare>:
213.953 - <AugAssign><Name>year</Name> -= <Num>1</Num></AugAssign>
213.954 - <Assign><Name>week1monday</Name> = <Call><Name>_isoweek1monday</Name>(<Name>year</Name>)</Call></Assign>
213.955 - <Assign><Tuple><Name>week</Name>, <Name>day</Name></Tuple> = <Call><Name>divmod</Name>(<BinOp><Name>today</Name> - <Name>week1monday</Name></BinOp>, <Num>7</Num>)</Call></Assign>
213.956 - <If>elif <Compare><Name>week</Name> >= <Num>52</Num></Compare>:
213.957 - <If>if <Compare><Name>today</Name> >= <Call><Name>_isoweek1monday</Name>(<BinOp><Name>year</Name>+<Num>1</Num></BinOp>)</Call></Compare>:
213.958 - <AugAssign><Name>year</Name> += <Num>1</Num></AugAssign>
213.959 - <Assign><Name>week</Name> = <Num>0</Num></Assign>
213.960 - </If></If></If> <Return>return <Tuple><Name>year</Name>, <BinOp><Name>week</Name>+<Num>1</Num></BinOp>, <BinOp><Name>day</Name>+<Num>1</Num></BinOp></Tuple></Return>
213.961 -
213.962 - # Pickle support.
213.963 -
213.964 - </FunctionDef> <Assign><Name>__safe_for_unpickling__</Name> = <Name>True</Name></Assign> # For Python 2.2
213.965 -
213.966 - <FunctionDef>def __getstate(<Name>self</Name>):
213.967 - <Assign><Tuple><Name>yhi</Name>, <Name>ylo</Name></Tuple> = <Call><Name>divmod</Name>(<Attribute><Name>self</Name>.__year</Attribute>, <Num>256</Num>)</Call></Assign>
213.968 - <Return>return <Tuple>(<BinOp><Str>"%c%c%c%c"</Str> % <Tuple>(<Name>yhi</Name>, <Name>ylo</Name>, <Attribute><Name>self</Name>.__month</Attribute>, <Attribute><Name>self</Name>.__day</Attribute>)</Tuple></BinOp>, )</Tuple></Return>
213.969 -
213.970 - </FunctionDef> <FunctionDef>def __setstate(<Name>self</Name>, <Name>t</Name>):
213.971 - <Assert>assert <BoolOp><Call><Name>isinstance</Name>(<Name>t</Name>, <Name>tuple</Name>)</Call> and <Compare><Call><Name>len</Name>(<Name>t</Name>)</Call> == <Num>1</Num></Compare></BoolOp>, <Repr>`<Name>t</Name>`</Repr></Assert>
213.972 - <Assign><Name>string</Name> = <Subscript><Name>t</Name>[<Index><Num>0</Num></Index>]</Subscript></Assign>
213.973 - <Assert>assert <Compare><Call><Name>len</Name>(<Name>string</Name>)</Call> == <Num>4</Num></Compare></Assert>
213.974 - <Assign><Tuple><Name>yhi</Name>, <Name>ylo</Name>, <Attribute><Name>self</Name>.__month</Attribute>, <Attribute><Name>self</Name>.__day</Attribute></Tuple> = <Call><Name>map</Name>(<Name>ord</Name>, <Name>string</Name>)</Call></Assign>
213.975 - <Assign><Attribute><Name>self</Name>.__year</Attribute> = <BinOp><BinOp><Name>yhi</Name></BinOp> * <Num>256</Num> + <Name>ylo</Name></BinOp></Assign>
213.976 -
213.977 - </FunctionDef> <FunctionDef>def __reduce__(<Name>self</Name>):
213.978 - <Return>return <Tuple>(<Attribute><Name>self</Name>.__class__</Attribute>, <Call><Attribute><Name>self</Name>.__getstate</Attribute>()</Call>)</Tuple></Return>
213.979 -
213.980 -</FunctionDef></ClassDef><Assign><Name>_date_class</Name> = <Name>date</Name></Assign> # so functions w/ args named "date" can get at the class
213.981 -
213.982 -<Assign><Attribute><Name>date</Name>.min</Attribute> = <Call><Name>date</Name>(<Num>1</Num>, <Num>1</Num>, <Num>1</Num>)</Call></Assign>
213.983 -<Assign><Attribute><Name>date</Name>.max</Attribute> = <Call><Name>date</Name>(<Num>9999</Num>, <Num>12</Num>, <Num>31</Num>)</Call></Assign>
213.984 -<Assign><Attribute><Name>date</Name>.resolution</Attribute> = <Call><Name>timedelta</Name>(days=<Num>1</Num>)</Call></Assign>
213.985 -
213.986 -<ClassDef>class tzinfo(<Name>object</Name>):
213.987 - <Expr><Str>"""Abstract base class for time zone info classes.
213.988 -
213.989 - Subclasses must override the name(), utcoffset() and dst() methods.
213.990 - """</Str></Expr>
213.991 -
213.992 - <FunctionDef>def tzname(<Name>self</Name>, <Name>dt</Name>):
213.993 - <Expr><Str>"datetime -> string name of time zone."</Str></Expr>
213.994 - <Raise>raise <Call><Name>NotImplementedError</Name>(<Str>"tzinfo subclass must override tzname()"</Str>)</Call></Raise>
213.995 -
213.996 - </FunctionDef> <FunctionDef>def utcoffset(<Name>self</Name>, <Name>dt</Name>):
213.997 - <Expr><Str>"datetime -> minutes east of UTC (negative for west of UTC)"</Str></Expr>
213.998 - <Raise>raise <Call><Name>NotImplementedError</Name>(<Str>"tzinfo subclass must override utcoffset()"</Str>)</Call></Raise>
213.999 -
213.1000 - </FunctionDef> <FunctionDef>def dst(<Name>self</Name>, <Name>dt</Name>):
213.1001 - <Expr><Str>"""datetime -> DST offset in minutes east of UTC.
213.1002 -
213.1003 - Return 0 if DST not in effect. utcoffset() must include the DST
213.1004 - offset.
213.1005 - """</Str></Expr>
213.1006 - <Raise>raise <Call><Name>NotImplementedError</Name>(<Str>"tzinfo subclass must override dst()"</Str>)</Call></Raise>
213.1007 -
213.1008 - </FunctionDef> <FunctionDef>def fromutc(<Name>self</Name>, <Name>dt</Name>):
213.1009 - <Expr><Str>"datetime in UTC -> datetime in local time."</Str></Expr>
213.1010 -
213.1011 - <If>if <UnaryOp>not <Call><Name>isinstance</Name>(<Name>dt</Name>, <Name>datetime</Name>)</Call></UnaryOp>:
213.1012 - <Raise>raise <Call><Name>TypeError</Name>(<Str>"fromutc() requires a datetime argument"</Str>)</Call></Raise>
213.1013 - </If> <If>if <Compare><Attribute><Name>dt</Name>.tzinfo</Attribute> is not <Name>self</Name></Compare>:
213.1014 - <Raise>raise <Call><Name>ValueError</Name>(<Str>"dt.tzinfo is not self"</Str>)</Call></Raise>
213.1015 -
213.1016 - </If> <Assign><Name>dtoff</Name> = <Call><Attribute><Name>dt</Name>.utcoffset</Attribute>()</Call></Assign>
213.1017 - <If>if <Compare><Name>dtoff</Name> is <Name>None</Name></Compare>:
213.1018 - <Raise>raise <Call><Name>ValueError</Name>(<Str>"fromutc() requires a non-None utcoffset() "
213.1019 - "result"</Str>)</Call></Raise>
213.1020 -
213.1021 - # See the long comment block at the end of this file for an
213.1022 - # explanation of this algorithm.
213.1023 - </If> <Assign><Name>dtdst</Name> = <Call><Attribute><Name>dt</Name>.dst</Attribute>()</Call></Assign>
213.1024 - <If>if <Compare><Name>dtdst</Name> is <Name>None</Name></Compare>:
213.1025 - <Raise>raise <Call><Name>ValueError</Name>(<Str>"fromutc() requires a non-None dst() result"</Str>)</Call></Raise>
213.1026 - </If> <Assign><Name>delta</Name> = <BinOp><Name>dtoff</Name> - <Name>dtdst</Name></BinOp></Assign>
213.1027 - <If>if <Name>delta</Name>:
213.1028 - <AugAssign><Name>dt</Name> += <Name>delta</Name></AugAssign>
213.1029 - <Assign><Name>dtdst</Name> = <Call><Attribute><Name>dt</Name>.dst</Attribute>()</Call></Assign>
213.1030 - <If>if <Compare><Name>dtdst</Name> is <Name>None</Name></Compare>:
213.1031 - <Raise>raise <Call><Name>ValueError</Name>(<Str>"fromutc(): dt.dst gave inconsistent "
213.1032 - "results; cannot convert"</Str>)</Call></Raise>
213.1033 - </If></If> <If>if <Name>dtdst</Name>:
213.1034 - <Return>return <BinOp><Name>dt</Name> + <Name>dtdst</Name></BinOp></Return>
213.1035 - else:
213.1036 - <Return>return <Name>dt</Name></Return>
213.1037 -
213.1038 - # Pickle support.
213.1039 -
213.1040 - </If></FunctionDef> <Assign><Name>__safe_for_unpickling__</Name> = <Name>True</Name></Assign> # For Python 2.2
213.1041 -
213.1042 - <FunctionDef>def __reduce__(<Name>self</Name>):
213.1043 - <Assign><Name>getinitargs</Name> = <Call><Name>getattr</Name>(<Name>self</Name>, <Str>"__getinitargs__"</Str>, <Name>None</Name>)</Call></Assign>
213.1044 - <If>if <Name>getinitargs</Name>:
213.1045 - <Assign><Name>args</Name> = <Call><Name>getinitargs</Name>()</Call></Assign>
213.1046 - else:
213.1047 - <Assign><Name>args</Name> = <Tuple>()</Tuple></Assign>
213.1048 - </If> <Assign><Name>getstate</Name> = <Call><Name>getattr</Name>(<Name>self</Name>, <Str>"__getstate__"</Str>, <Name>None</Name>)</Call></Assign>
213.1049 - <If>if <Name>getstate</Name>:
213.1050 - <Assign><Name>state</Name> = <Call><Name>getstate</Name>()</Call></Assign>
213.1051 - else:
213.1052 - <Assign><Name>state</Name> = <BoolOp><Call><Name>getattr</Name>(<Name>self</Name>, <Str>"__dict__"</Str>, <Name>None</Name>)</Call> or <Name>None</Name></BoolOp></Assign>
213.1053 - </If> <If>if <Compare><Name>state</Name> is <Name>None</Name></Compare>:
213.1054 - <Return>return <Tuple>(<Attribute><Name>self</Name>.__class__</Attribute>, <Name>args</Name>)</Tuple></Return>
213.1055 - else:
213.1056 - <Return>return <Tuple>(<Attribute><Name>self</Name>.__class__</Attribute>, <Name>args</Name>, <Name>state</Name>)</Tuple></Return>
213.1057 -
213.1058 -</If></FunctionDef></ClassDef><Assign><Name>_tzinfo_class</Name> = <Name>tzinfo</Name></Assign> # so functions w/ args named "tinfo" can get at it
213.1059 -
213.1060 -<ClassDef>class time(<Name>object</Name>):
213.1061 - <Expr><Str>"""Time with time zone.
213.1062 -
213.1063 - Constructors:
213.1064 -
213.1065 - __new__()
213.1066 -
213.1067 - Operators:
213.1068 -
213.1069 - __repr__, __str__
213.1070 - __cmp__, __hash__
213.1071 -
213.1072 - Methods:
213.1073 -
213.1074 - strftime()
213.1075 - isoformat()
213.1076 - utcoffset()
213.1077 - tzname()
213.1078 - dst()
213.1079 -
213.1080 - Properties (readonly):
213.1081 - hour, minute, second, microsecond, tzinfo
213.1082 - """</Str></Expr>
213.1083 -
213.1084 - <FunctionDef>def __new__(<Name>cls</Name>, <Name>hour</Name>=<Num>0</Num>, <Name>minute</Name>=<Num>0</Num>, <Name>second</Name>=<Num>0</Num>, <Name>microsecond</Name>=<Num>0</Num>, <Name>tzinfo</Name>=<Name>None</Name>):
213.1085 - <Expr><Str>"""Constructor.
213.1086 -
213.1087 - Arguments:
213.1088 -
213.1089 - hour, minute (required)
213.1090 - second, microsecond (default to zero)
213.1091 - tzinfo (default to None)
213.1092 - """</Str></Expr>
213.1093 - <Assign><Name>self</Name> = <Call><Attribute><Name>object</Name>.__new__</Attribute>(<Name>cls</Name>)</Call></Assign>
213.1094 - <If>if <Call><Name>isinstance</Name>(<Name>hour</Name>, <Name>str</Name>)</Call>:
213.1095 - # Pickle support
213.1096 - <Expr><Call><Attribute><Name>self</Name>.__setstate</Attribute>(<Tuple>(<Name>hour</Name>, <BoolOp><Name>minute</Name> or <Name>None</Name></BoolOp>)</Tuple>)</Call></Expr>
213.1097 - <Return>return <Name>self</Name></Return>
213.1098 - </If> <Expr><Call><Name>_check_tzinfo_arg</Name>(<Name>tzinfo</Name>)</Call></Expr>
213.1099 - <Expr><Call><Name>_check_time_fields</Name>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>)</Call></Expr>
213.1100 - <Assign><Attribute><Name>self</Name>.__hour</Attribute> = <Name>hour</Name></Assign>
213.1101 - <Assign><Attribute><Name>self</Name>.__minute</Attribute> = <Name>minute</Name></Assign>
213.1102 - <Assign><Attribute><Name>self</Name>.__second</Attribute> = <Name>second</Name></Assign>
213.1103 - <Assign><Attribute><Name>self</Name>.__microsecond</Attribute> = <Name>microsecond</Name></Assign>
213.1104 - <Assign><Attribute><Name>self</Name>._tzinfo</Attribute> = <Name>tzinfo</Name></Assign>
213.1105 - <Return>return <Name>self</Name></Return>
213.1106 -
213.1107 - # Read-only field accessors
213.1108 - </FunctionDef> <Assign><Name>hour</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>.__hour</Attribute></Lambda>, doc=<Str>"hour (0-23)"</Str>)</Call></Assign>
213.1109 - <Assign><Name>minute</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>.__minute</Attribute></Lambda>, doc=<Str>"minute (0-59)"</Str>)</Call></Assign>
213.1110 - <Assign><Name>second</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>.__second</Attribute></Lambda>, doc=<Str>"second (0-59)"</Str>)</Call></Assign>
213.1111 - <Assign><Name>microsecond</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>.__microsecond</Attribute></Lambda>,
213.1112 - doc=<Str>"microsecond (0-999999)"</Str>)</Call></Assign>
213.1113 - <Assign><Name>tzinfo</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>._tzinfo</Attribute></Lambda>, doc=<Str>"timezone info object"</Str>)</Call></Assign>
213.1114 -
213.1115 - # Standard conversions, __hash__ (and helpers)
213.1116 -
213.1117 - # Comparisons.
213.1118 -
213.1119 - <FunctionDef>def __eq__(<Name>self</Name>, <Name>other</Name>):
213.1120 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>time</Name>)</Call>:
213.1121 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> == <Num>0</Num></Compare></Return>
213.1122 - else:
213.1123 - <Return>return <Name>False</Name></Return>
213.1124 -
213.1125 - </If></FunctionDef> <FunctionDef>def __ne__(<Name>self</Name>, <Name>other</Name>):
213.1126 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>time</Name>)</Call>:
213.1127 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> != <Num>0</Num></Compare></Return>
213.1128 - else:
213.1129 - <Return>return <Name>True</Name></Return>
213.1130 -
213.1131 - </If></FunctionDef> <FunctionDef>def __le__(<Name>self</Name>, <Name>other</Name>):
213.1132 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>time</Name>)</Call>:
213.1133 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> <= <Num>0</Num></Compare></Return>
213.1134 - else:
213.1135 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
213.1136 -
213.1137 - </If></FunctionDef> <FunctionDef>def __lt__(<Name>self</Name>, <Name>other</Name>):
213.1138 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>time</Name>)</Call>:
213.1139 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> < <Num>0</Num></Compare></Return>
213.1140 - else:
213.1141 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
213.1142 -
213.1143 - </If></FunctionDef> <FunctionDef>def __ge__(<Name>self</Name>, <Name>other</Name>):
213.1144 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>time</Name>)</Call>:
213.1145 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> >= <Num>0</Num></Compare></Return>
213.1146 - else:
213.1147 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
213.1148 -
213.1149 - </If></FunctionDef> <FunctionDef>def __gt__(<Name>self</Name>, <Name>other</Name>):
213.1150 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>time</Name>)</Call>:
213.1151 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> > <Num>0</Num></Compare></Return>
213.1152 - else:
213.1153 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
213.1154 -
213.1155 - </If></FunctionDef> <FunctionDef>def __cmp(<Name>self</Name>, <Name>other</Name>):
213.1156 - <Assert>assert <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>time</Name>)</Call></Assert>
213.1157 - <Assign><Name>mytz</Name> = <Attribute><Name>self</Name>._tzinfo</Attribute></Assign>
213.1158 - <Assign><Name>ottz</Name> = <Attribute><Name>other</Name>._tzinfo</Attribute></Assign>
213.1159 - <Assign><Name>myoff</Name> = <Name>otoff</Name> = <Name>None</Name></Assign>
213.1160 -
213.1161 - <If>if <Compare><Name>mytz</Name> is <Name>ottz</Name></Compare>:
213.1162 - <Assign><Name>base_compare</Name> = <Name>True</Name></Assign>
213.1163 - else:
213.1164 - <Assign><Name>myoff</Name> = <Call><Attribute><Name>self</Name>._utcoffset</Attribute>()</Call></Assign>
213.1165 - <Assign><Name>otoff</Name> = <Call><Attribute><Name>other</Name>._utcoffset</Attribute>()</Call></Assign>
213.1166 - <Assign><Name>base_compare</Name> = <Compare><Name>myoff</Name> == <Name>otoff</Name></Compare></Assign>
213.1167 -
213.1168 - </If> <If>if <Name>base_compare</Name>:
213.1169 - <Return>return <Call><Name>cmp</Name>(<Tuple>(<Attribute><Name>self</Name>.__hour</Attribute>, <Attribute><Name>self</Name>.__minute</Attribute>, <Attribute><Name>self</Name>.__second</Attribute>,
213.1170 - <Attribute><Name>self</Name>.__microsecond</Attribute>)</Tuple>,
213.1171 - <Tuple>(<Attribute><Name>other</Name>.__hour</Attribute>, <Attribute><Name>other</Name>.__minute</Attribute>, <Attribute><Name>other</Name>.__second</Attribute>,
213.1172 - <Attribute><Name>other</Name>.__microsecond</Attribute>)</Tuple>)</Call></Return>
213.1173 - </If> <If>if <BoolOp><Compare><Name>myoff</Name> is <Name>None</Name></Compare> or <Compare><Name>otoff</Name> is <Name>None</Name></Compare></BoolOp>:
213.1174 - # XXX Buggy in 2.2.2.
213.1175 - <Raise>raise <Call><Name>TypeError</Name>(<Str>"cannot compare naive and aware times"</Str>)</Call></Raise>
213.1176 - </If> <Assign><Name>myhhmm</Name> = <BinOp><BinOp><BinOp><Attribute><Name>self</Name>.__hour</Attribute></BinOp></BinOp> * <Num>60</Num> + <Attribute><Name>self</Name>.__minute</Attribute> - <Name>myoff</Name></BinOp></Assign>
213.1177 - <Assign><Name>othhmm</Name> = <BinOp><BinOp><BinOp><Attribute><Name>other</Name>.__hour</Attribute></BinOp></BinOp> * <Num>60</Num> + <Attribute><Name>other</Name>.__minute</Attribute> - <Name>otoff</Name></BinOp></Assign>
213.1178 - <Return>return <Call><Name>cmp</Name>(<Tuple>(<Name>myhhmm</Name>, <Attribute><Name>self</Name>.__second</Attribute>, <Attribute><Name>self</Name>.__microsecond</Attribute>)</Tuple>,
213.1179 - <Tuple>(<Name>othhmm</Name>, <Attribute><Name>other</Name>.__second</Attribute>, <Attribute><Name>other</Name>.__microsecond</Attribute>)</Tuple>)</Call></Return>
213.1180 -
213.1181 - </FunctionDef> <FunctionDef>def __hash__(<Name>self</Name>):
213.1182 - <Expr><Str>"""Hash."""</Str></Expr>
213.1183 - <Assign><Name>tzoff</Name> = <Call><Attribute><Name>self</Name>._utcoffset</Attribute>()</Call></Assign>
213.1184 - <If>if <UnaryOp>not <Name>tzoff</Name></UnaryOp>: # zero or None
213.1185 - <Return>return <Call><Name>hash</Name>(<Subscript><Attribute><Name>self</Name>.__getstate</Attribute><Call>()</Call>[<Index><Num>0</Num></Index>]</Subscript>)</Call></Return>
213.1186 - </If> <Assign><Tuple><Name>h</Name>, <Name>m</Name></Tuple> = <Call><Name>divmod</Name>(<BinOp><BinOp><BinOp><Attribute><Name>self</Name>.hour</Attribute></BinOp></BinOp> * <Num>60</Num> + <Attribute><Name>self</Name>.minute</Attribute> - <Name>tzoff</Name></BinOp>, <Num>60</Num>)</Call></Assign>
213.1187 - <If>if <Compare><Num>0</Num> <= <Name>h</Name> < <Num>24</Num></Compare>:
213.1188 - <Return>return <Call><Name>hash</Name>(<Call><Name>time</Name>(<Name>h</Name>, <Name>m</Name>, <Attribute><Name>self</Name>.second</Attribute>, <Attribute><Name>self</Name>.microsecond</Attribute>)</Call>)</Call></Return>
213.1189 - </If> <Return>return <Call><Name>hash</Name>(<Tuple>(<Name>h</Name>, <Name>m</Name>, <Attribute><Name>self</Name>.second</Attribute>, <Attribute><Name>self</Name>.microsecond</Attribute>)</Tuple>)</Call></Return>
213.1190 -
213.1191 - # Conversion to string
213.1192 -
213.1193 - </FunctionDef> <FunctionDef>def _tzstr(<Name>self</Name>, <Name>sep</Name>=<Str>":"</Str>):
213.1194 - <Expr><Str>"""Return formatted timezone offset (+xx:xx) or None."""</Str></Expr>
213.1195 - <Assign><Name>off</Name> = <Call><Attribute><Name>self</Name>._utcoffset</Attribute>()</Call></Assign>
213.1196 - <If>if <Compare><Name>off</Name> is not <Name>None</Name></Compare>:
213.1197 - <If>if <Compare><Name>off</Name> < <Num>0</Num></Compare>:
213.1198 - <Assign><Name>sign</Name> = <Str>"-"</Str></Assign>
213.1199 - <Assign><Name>off</Name> = <UnaryOp>-<Name>off</Name></UnaryOp></Assign>
213.1200 - else:
213.1201 - <Assign><Name>sign</Name> = <Str>"+"</Str></Assign>
213.1202 - </If> <Assign><Tuple><Name>hh</Name>, <Name>mm</Name></Tuple> = <Call><Name>divmod</Name>(<Name>off</Name>, <Num>60</Num>)</Call></Assign>
213.1203 - <Assert>assert <Compare><Num>0</Num> <= <Name>hh</Name> < <Num>24</Num></Compare></Assert>
213.1204 - <Assign><Name>off</Name> = <BinOp><Str>"%s%02d%s%02d"</Str> % <Tuple>(<Name>sign</Name>, <Name>hh</Name>, <Name>sep</Name>, <Name>mm</Name>)</Tuple></BinOp></Assign>
213.1205 - </If> <Return>return <Name>off</Name></Return>
213.1206 -
213.1207 - </FunctionDef> <FunctionDef>def __repr__(<Name>self</Name>):
213.1208 - <Expr><Str>"""Convert to formal string, for repr()."""</Str></Expr>
213.1209 - <If>if <Compare><Attribute><Name>self</Name>.__microsecond</Attribute> != <Num>0</Num></Compare>:
213.1210 - <Assign><Name>s</Name> = <BinOp><Str>", %d, %d"</Str> % <Tuple>(<Attribute><Name>self</Name>.__second</Attribute>, <Attribute><Name>self</Name>.__microsecond</Attribute>)</Tuple></BinOp></Assign>
213.1211 - <If>elif <Compare><Attribute><Name>self</Name>.__second</Attribute> != <Num>0</Num></Compare>:
213.1212 - <Assign><Name>s</Name> = <BinOp><Str>", %d"</Str> % <Attribute><Name>self</Name>.__second</Attribute></BinOp></Assign>
213.1213 - else:
213.1214 - <Assign><Name>s</Name> = <Str>""</Str></Assign>
213.1215 - </If></If> <Assign><Name>s</Name>= <BinOp><Str>"%s(%d, %d%s)"</Str> % <Tuple>(<BinOp><Str>'datetime.'</Str> + <Attribute><Attribute><Name>self</Name>.__class__</Attribute>.__name__</Attribute></BinOp>,
213.1216 - <Attribute><Name>self</Name>.__hour</Attribute>, <Attribute><Name>self</Name>.__minute</Attribute>, <Name>s</Name>)</Tuple></BinOp></Assign>
213.1217 - <If>if <Compare><Attribute><Name>self</Name>._tzinfo</Attribute> is not <Name>None</Name></Compare>:
213.1218 - <Assert>assert <Compare><Subscript><Name>s</Name>[<Slice><Num>-1</Num>:</Slice>]</Subscript> == <Str>")"</Str></Compare></Assert>
213.1219 - <Assign><Name>s</Name> = <BinOp><BinOp><Subscript><Name>s</Name>[<Slice>:<Num>-1</Num></Slice>]</Subscript></BinOp> + <BinOp><Str>", tzinfo=%r"</Str></BinOp> % <Attribute><Name>self</Name>._tzinfo</Attribute> + <Str>")"</Str></BinOp></Assign>
213.1220 - </If> <Return>return <Name>s</Name></Return>
213.1221 -
213.1222 - </FunctionDef> <FunctionDef>def isoformat(<Name>self</Name>):
213.1223 - <Expr><Str>"""Return the time formatted according to ISO.
213.1224 -
213.1225 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
213.1226 - self.microsecond == 0.
213.1227 - """</Str></Expr>
213.1228 - <Assign><Name>s</Name> = <Call><Name>_format_time</Name>(<Attribute><Name>self</Name>.__hour</Attribute>, <Attribute><Name>self</Name>.__minute</Attribute>, <Attribute><Name>self</Name>.__second</Attribute>,
213.1229 - <Attribute><Name>self</Name>.__microsecond</Attribute>)</Call></Assign>
213.1230 - <Assign><Name>tz</Name> = <Call><Attribute><Name>self</Name>._tzstr</Attribute>()</Call></Assign>
213.1231 - <If>if <Name>tz</Name>:
213.1232 - <AugAssign><Name>s</Name> += <Name>tz</Name></AugAssign>
213.1233 - </If> <Return>return <Name>s</Name></Return>
213.1234 -
213.1235 - </FunctionDef> <Assign><Name>__str__</Name> = <Name>isoformat</Name></Assign>
213.1236 -
213.1237 - <FunctionDef>def strftime(<Name>self</Name>, <Name>fmt</Name>):
213.1238 - <Expr><Str>"""Format using strftime(). The date part of the timestamp passed
213.1239 - to underlying strftime should not be used.
213.1240 - """</Str></Expr>
213.1241 - # The year must be >= 1900 else Python's strftime implementation
213.1242 - # can raise a bogus exception.
213.1243 - <Assign><Name>timetuple</Name> = <Tuple>(<Num>1900</Num>, <Num>1</Num>, <Num>1</Num>,
213.1244 - <Attribute><Name>self</Name>.__hour</Attribute>, <Attribute><Name>self</Name>.__minute</Attribute>, <Attribute><Name>self</Name>.__second</Attribute>,
213.1245 - <Num>0</Num>, <Num>1</Num>, <Num>-1</Num>)</Tuple></Assign>
213.1246 - <Return>return <Call><Name>_wrap_strftime</Name>(<Name>self</Name>, <Name>fmt</Name>, <Name>timetuple</Name>)</Call></Return>
213.1247 -
213.1248 - # Timezone functions
213.1249 -
213.1250 - </FunctionDef> <FunctionDef>def utcoffset(<Name>self</Name>):
213.1251 - <Expr><Str>"""Return the timezone offset in minutes east of UTC (negative west of
213.1252 - UTC)."""</Str></Expr>
213.1253 - <Assign><Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name>(<Attribute><Name>self</Name>._tzinfo</Attribute>, <Str>"utcoffset"</Str>, <Name>None</Name>)</Call></Assign>
213.1254 - <Assign><Name>offset</Name> = <Call><Name>_check_utc_offset</Name>(<Str>"utcoffset"</Str>, <Name>offset</Name>)</Call></Assign>
213.1255 - <If>if <Compare><Name>offset</Name> is not <Name>None</Name></Compare>:
213.1256 - <Assign><Name>offset</Name> = <Call><Name>timedelta</Name>(minutes=<Name>offset</Name>)</Call></Assign>
213.1257 - </If> <Return>return <Name>offset</Name></Return>
213.1258 -
213.1259 - # Return an integer (or None) instead of a timedelta (or None).
213.1260 - </FunctionDef> <FunctionDef>def _utcoffset(<Name>self</Name>):
213.1261 - <Assign><Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name>(<Attribute><Name>self</Name>._tzinfo</Attribute>, <Str>"utcoffset"</Str>, <Name>None</Name>)</Call></Assign>
213.1262 - <Assign><Name>offset</Name> = <Call><Name>_check_utc_offset</Name>(<Str>"utcoffset"</Str>, <Name>offset</Name>)</Call></Assign>
213.1263 - <Return>return <Name>offset</Name></Return>
213.1264 -
213.1265 - </FunctionDef> <FunctionDef>def tzname(<Name>self</Name>):
213.1266 - <Expr><Str>"""Return the timezone name.
213.1267 -
213.1268 - Note that the name is 100% informational -- there's no requirement that
213.1269 - it mean anything in particular. For example, "GMT", "UTC", "-500",
213.1270 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
213.1271 - """</Str></Expr>
213.1272 - <Assign><Name>name</Name> = <Call><Name>_call_tzinfo_method</Name>(<Attribute><Name>self</Name>._tzinfo</Attribute>, <Str>"tzname"</Str>, <Name>None</Name>)</Call></Assign>
213.1273 - <Expr><Call><Name>_check_tzname</Name>(<Name>name</Name>)</Call></Expr>
213.1274 - <Return>return <Name>name</Name></Return>
213.1275 -
213.1276 - </FunctionDef> <FunctionDef>def dst(<Name>self</Name>):
213.1277 - <Expr><Str>"""Return 0 if DST is not in effect, or the DST offset (in minutes
213.1278 - eastward) if DST is in effect.
213.1279 -
213.1280 - This is purely informational; the DST offset has already been added to
213.1281 - the UTC offset returned by utcoffset() if applicable, so there's no
213.1282 - need to consult dst() unless you're interested in displaying the DST
213.1283 - info.
213.1284 - """</Str></Expr>
213.1285 - <Assign><Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name>(<Attribute><Name>self</Name>._tzinfo</Attribute>, <Str>"dst"</Str>, <Name>None</Name>)</Call></Assign>
213.1286 - <Assign><Name>offset</Name> = <Call><Name>_check_utc_offset</Name>(<Str>"dst"</Str>, <Name>offset</Name>)</Call></Assign>
213.1287 - <If>if <Compare><Name>offset</Name> is not <Name>None</Name></Compare>:
213.1288 - <Assign><Name>offset</Name> = <Call><Name>timedelta</Name>(minutes=<Name>offset</Name>)</Call></Assign>
213.1289 - </If> <Return>return <Name>offset</Name></Return>
213.1290 -
213.1291 - </FunctionDef> <FunctionDef>def replace(<Name>self</Name>, <Name>hour</Name>=<Name>None</Name>, <Name>minute</Name>=<Name>None</Name>, <Name>second</Name>=<Name>None</Name>, <Name>microsecond</Name>=<Name>None</Name>,
213.1292 - <Name>tzinfo</Name>=<Name>True</Name>):
213.1293 - <Expr><Str>"""Return a new time with new values for the specified fields."""</Str></Expr>
213.1294 - <If>if <Compare><Name>hour</Name> is <Name>None</Name></Compare>:
213.1295 - <Assign><Name>hour</Name> = <Attribute><Name>self</Name>.hour</Attribute></Assign>
213.1296 - </If> <If>if <Compare><Name>minute</Name> is <Name>None</Name></Compare>:
213.1297 - <Assign><Name>minute</Name> = <Attribute><Name>self</Name>.minute</Attribute></Assign>
213.1298 - </If> <If>if <Compare><Name>second</Name> is <Name>None</Name></Compare>:
213.1299 - <Assign><Name>second</Name> = <Attribute><Name>self</Name>.second</Attribute></Assign>
213.1300 - </If> <If>if <Compare><Name>microsecond</Name> is <Name>None</Name></Compare>:
213.1301 - <Assign><Name>microsecond</Name> = <Attribute><Name>self</Name>.microsecond</Attribute></Assign>
213.1302 - </If> <If>if <Compare><Name>tzinfo</Name> is <Name>True</Name></Compare>:
213.1303 - <Assign><Name>tzinfo</Name> = <Attribute><Name>self</Name>.tzinfo</Attribute></Assign>
213.1304 - </If> <Expr><Call><Name>_check_time_fields</Name>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>)</Call></Expr>
213.1305 - <Expr><Call><Name>_check_tzinfo_arg</Name>(<Name>tzinfo</Name>)</Call></Expr>
213.1306 - <Return>return <Call><Name>time</Name>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>, <Name>tzinfo</Name>)</Call></Return>
213.1307 -
213.1308 - # Return an integer (or None) instead of a timedelta (or None).
213.1309 - </FunctionDef> <FunctionDef>def _dst(<Name>self</Name>):
213.1310 - <Assign><Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name>(<Attribute><Name>self</Name>._tzinfo</Attribute>, <Str>"dst"</Str>, <Name>None</Name>)</Call></Assign>
213.1311 - <Assign><Name>offset</Name> = <Call><Name>_check_utc_offset</Name>(<Str>"dst"</Str>, <Name>offset</Name>)</Call></Assign>
213.1312 - <Return>return <Name>offset</Name></Return>
213.1313 -
213.1314 - </FunctionDef> <FunctionDef>def __nonzero__(<Name>self</Name>):
213.1315 - <If>if <BoolOp><Attribute><Name>self</Name>.second</Attribute> or <Attribute><Name>self</Name>.microsecond</Attribute></BoolOp>:
213.1316 - <Return>return <Num>1</Num></Return>
213.1317 - </If> <Assign><Name>offset</Name> = <BoolOp><Call><Attribute><Name>self</Name>._utcoffset</Attribute>()</Call> or <Num>0</Num></BoolOp></Assign>
213.1318 - <Return>return <Compare><BinOp><BinOp><BinOp><Attribute><Name>self</Name>.hour</Attribute></BinOp></BinOp> * <Num>60</Num> + <Attribute><Name>self</Name>.minute</Attribute> - <Name>offset</Name></BinOp> != <Num>0</Num></Compare></Return>
213.1319 -
213.1320 - # Pickle support.
213.1321 -
213.1322 - </FunctionDef> <Assign><Name>__safe_for_unpickling__</Name> = <Name>True</Name></Assign> # For Python 2.2
213.1323 -
213.1324 - <FunctionDef>def __getstate(<Name>self</Name>):
213.1325 - <Assign><Tuple><Name>us2</Name>, <Name>us3</Name></Tuple> = <Call><Name>divmod</Name>(<Attribute><Name>self</Name>.__microsecond</Attribute>, <Num>256</Num>)</Call></Assign>
213.1326 - <Assign><Tuple><Name>us1</Name>, <Name>us2</Name></Tuple> = <Call><Name>divmod</Name>(<Name>us2</Name>, <Num>256</Num>)</Call></Assign>
213.1327 - <Assign><Name>basestate</Name> = <BinOp><BinOp>(<Str>"%c"</Str> * <Num>6</Num>)</BinOp> % <Tuple>(<Attribute><Name>self</Name>.__hour</Attribute>, <Attribute><Name>self</Name>.__minute</Attribute>, <Attribute><Name>self</Name>.__second</Attribute>,
213.1328 - <Name>us1</Name>, <Name>us2</Name>, <Name>us3</Name>)</Tuple></BinOp></Assign>
213.1329 - <If>if <Compare><Attribute><Name>self</Name>._tzinfo</Attribute> is <Name>None</Name></Compare>:
213.1330 - <Return>return <Tuple>(<Name>basestate</Name>,)</Tuple></Return>
213.1331 - else:
213.1332 - <Return>return <Tuple>(<Name>basestate</Name>, <Attribute><Name>self</Name>._tzinfo</Attribute>)</Tuple></Return>
213.1333 -
213.1334 - </If></FunctionDef> <FunctionDef>def __setstate(<Name>self</Name>, <Name>state</Name>):
213.1335 - <Assert>assert <Call><Name>isinstance</Name>(<Name>state</Name>, <Name>tuple</Name>)</Call></Assert>
213.1336 - <Assert>assert <Compare><Num>1</Num> <= <Call><Name>len</Name>(<Name>state</Name>)</Call> <= <Num>2</Num></Compare></Assert>
213.1337 - <Assign><Name>string</Name> = <Subscript><Name>state</Name>[<Index><Num>0</Num></Index>]</Subscript></Assign>
213.1338 - <Assert>assert <Compare><Call><Name>len</Name>(<Name>string</Name>)</Call> == <Num>6</Num></Compare></Assert>
213.1339 - <Assign><Tuple><Attribute><Name>self</Name>.__hour</Attribute>, <Attribute><Name>self</Name>.__minute</Attribute>, <Attribute><Name>self</Name>.__second</Attribute>, <Name>us1</Name>, <Name>us2</Name>, <Name>us3</Name></Tuple> = \
213.1340 - <Call><Name>map</Name>(<Name>ord</Name>, <Name>string</Name>)</Call></Assign>
213.1341 - <Assign><Attribute><Name>self</Name>.__microsecond</Attribute> = <BinOp><BinOp>(<BinOp>(<BinOp>(<Name>us1</Name> << <Num>8</Num>)</BinOp> | <Name>us2</Name>)</BinOp> << <Num>8</Num>)</BinOp> | <Name>us3</Name></BinOp></Assign>
213.1342 - <If>if <Compare><Call><Name>len</Name>(<Name>state</Name>)</Call> == <Num>1</Num></Compare>:
213.1343 - <Assign><Attribute><Name>self</Name>._tzinfo</Attribute> = <Name>None</Name></Assign>
213.1344 - else:
213.1345 - <Assign><Attribute><Name>self</Name>._tzinfo</Attribute> = <Subscript><Name>state</Name>[<Index><Num>1</Num></Index>]</Subscript></Assign>
213.1346 -
213.1347 - </If></FunctionDef> <FunctionDef>def __reduce__(<Name>self</Name>):
213.1348 - <Return>return <Tuple>(<Attribute><Name>self</Name>.__class__</Attribute>, <Call><Attribute><Name>self</Name>.__getstate</Attribute>()</Call>)</Tuple></Return>
213.1349 -
213.1350 -</FunctionDef></ClassDef><Assign><Name>_time_class</Name> = <Name>time</Name></Assign> # so functions w/ args named "time" can get at the class
213.1351 -
213.1352 -<Assign><Attribute><Name>time</Name>.min</Attribute> = <Call><Name>time</Name>(<Num>0</Num>, <Num>0</Num>, <Num>0</Num>)</Call></Assign>
213.1353 -<Assign><Attribute><Name>time</Name>.max</Attribute> = <Call><Name>time</Name>(<Num>23</Num>, <Num>59</Num>, <Num>59</Num>, <Num>999999</Num>)</Call></Assign>
213.1354 -<Assign><Attribute><Name>time</Name>.resolution</Attribute> = <Call><Name>timedelta</Name>(microseconds=<Num>1</Num>)</Call></Assign>
213.1355 -
213.1356 -<ClassDef>class datetime(<Name>date</Name>):
213.1357 -
213.1358 - # XXX needs docstrings
213.1359 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
213.1360 -
213.1361 - <FunctionDef>def __new__(<Name>cls</Name>, <Name>year</Name>, <Name>month</Name>=<Name>None</Name>, <Name>day</Name>=<Name>None</Name>, <Name>hour</Name>=<Num>0</Num>, <Name>minute</Name>=<Num>0</Num>, <Name>second</Name>=<Num>0</Num>,
213.1362 - <Name>microsecond</Name>=<Num>0</Num>, <Name>tzinfo</Name>=<Name>None</Name>):
213.1363 - <If>if <Call><Name>isinstance</Name>(<Name>year</Name>, <Name>str</Name>)</Call>:
213.1364 - # Pickle support
213.1365 - <Assign><Name>self</Name> = <Call><Attribute><Name>date</Name>.__new__</Attribute>(<Name>cls</Name>, <Subscript><Name>year</Name>[<Slice>:<Num>4</Num></Slice>]</Subscript>)</Call></Assign>
213.1366 - <Expr><Call><Attribute><Name>self</Name>.__setstate</Attribute>(<Tuple>(<Name>year</Name>, <Name>month</Name>)</Tuple>)</Call></Expr>
213.1367 - <Return>return <Name>self</Name></Return>
213.1368 - </If> <Expr><Call><Name>_check_tzinfo_arg</Name>(<Name>tzinfo</Name>)</Call></Expr>
213.1369 - <Expr><Call><Name>_check_time_fields</Name>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>)</Call></Expr>
213.1370 - <Assign><Name>self</Name> = <Call><Attribute><Name>date</Name>.__new__</Attribute>(<Name>cls</Name>, <Name>year</Name>, <Name>month</Name>, <Name>day</Name>)</Call></Assign>
213.1371 - # XXX This duplicates __year, __month, __day for convenience :-(
213.1372 - <Assign><Attribute><Name>self</Name>.__year</Attribute> = <Name>year</Name></Assign>
213.1373 - <Assign><Attribute><Name>self</Name>.__month</Attribute> = <Name>month</Name></Assign>
213.1374 - <Assign><Attribute><Name>self</Name>.__day</Attribute> = <Name>day</Name></Assign>
213.1375 - <Assign><Attribute><Name>self</Name>.__hour</Attribute> = <Name>hour</Name></Assign>
213.1376 - <Assign><Attribute><Name>self</Name>.__minute</Attribute> = <Name>minute</Name></Assign>
213.1377 - <Assign><Attribute><Name>self</Name>.__second</Attribute> = <Name>second</Name></Assign>
213.1378 - <Assign><Attribute><Name>self</Name>.__microsecond</Attribute> = <Name>microsecond</Name></Assign>
213.1379 - <Assign><Attribute><Name>self</Name>._tzinfo</Attribute> = <Name>tzinfo</Name></Assign>
213.1380 - <Return>return <Name>self</Name></Return>
213.1381 -
213.1382 - # Read-only field accessors
213.1383 - </FunctionDef> <Assign><Name>hour</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>.__hour</Attribute></Lambda>, doc=<Str>"hour (0-23)"</Str>)</Call></Assign>
213.1384 - <Assign><Name>minute</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>.__minute</Attribute></Lambda>, doc=<Str>"minute (0-59)"</Str>)</Call></Assign>
213.1385 - <Assign><Name>second</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>.__second</Attribute></Lambda>, doc=<Str>"second (0-59)"</Str>)</Call></Assign>
213.1386 - <Assign><Name>microsecond</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>.__microsecond</Attribute></Lambda>,
213.1387 - doc=<Str>"microsecond (0-999999)"</Str>)</Call></Assign>
213.1388 - <Assign><Name>tzinfo</Name> = <Call><Name>property</Name>(<Lambda>lambda <Name>self</Name>: <Attribute><Name>self</Name>._tzinfo</Attribute></Lambda>, doc=<Str>"timezone info object"</Str>)</Call></Assign>
213.1389 -
213.1390 - <FunctionDef>def fromtimestamp(<Name>cls</Name>, <Name>t</Name>, <Name>tz</Name>=<Name>None</Name>):
213.1391 - <Expr><Str>"""Construct a datetime from a POSIX timestamp (like time.time()).
213.1392 -
213.1393 - A timezone info object may be passed in as well.
213.1394 - """</Str></Expr>
213.1395 -
213.1396 - <Expr><Call><Name>_check_tzinfo_arg</Name>(<Name>tz</Name>)</Call></Expr>
213.1397 - <If>if <Compare><Name>tz</Name> is <Name>None</Name></Compare>:
213.1398 - <Assign><Name>converter</Name> = <Attribute><Name>_time</Name>.localtime</Attribute></Assign>
213.1399 - else:
213.1400 - <Assign><Name>converter</Name> = <Attribute><Name>_time</Name>.gmtime</Attribute></Assign>
213.1401 - </If> <Assign><Tuple><Name>y</Name>, <Name>m</Name>, <Name>d</Name>, <Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Name>weekday</Name>, <Name>jday</Name>, <Name>dst</Name></Tuple> = <Call><Name>converter</Name>(<Name>t</Name>)</Call></Assign>
213.1402 - <Assign><Name>us</Name> = <Call><Name>int</Name>(<BinOp><BinOp>(<Name>t</Name> % <Num>1.0</Num>)</BinOp> * <Num>1000000</Num></BinOp>)</Call></Assign>
213.1403 - <Assign><Name>ss</Name> = <Call><Name>min</Name>(<Name>ss</Name>, <Num>59</Num>)</Call></Assign> # clamp out leap seconds if the platform has them
213.1404 - <Assign><Name>result</Name> = <Call><Name>cls</Name>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>, <Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Name>us</Name>, <Name>tz</Name>)</Call></Assign>
213.1405 - <If>if <Compare><Name>tz</Name> is not <Name>None</Name></Compare>:
213.1406 - <Assign><Name>result</Name> = <Call><Attribute><Name>tz</Name>.fromutc</Attribute>(<Name>result</Name>)</Call></Assign>
213.1407 - </If> <Return>return <Name>result</Name></Return>
213.1408 - </FunctionDef> <Assign><Name>fromtimestamp</Name> = <Call><Name>classmethod</Name>(<Name>fromtimestamp</Name>)</Call></Assign>
213.1409 -
213.1410 - <FunctionDef>def utcfromtimestamp(<Name>cls</Name>, <Name>t</Name>):
213.1411 - <Expr><Str>"Construct a UTC datetime from a POSIX timestamp (like time.time())."</Str></Expr>
213.1412 - <Assign><Tuple><Name>y</Name>, <Name>m</Name>, <Name>d</Name>, <Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Name>weekday</Name>, <Name>jday</Name>, <Name>dst</Name></Tuple> = <Call><Attribute><Name>_time</Name>.gmtime</Attribute>(<Name>t</Name>)</Call></Assign>
213.1413 - <Assign><Name>us</Name> = <Call><Name>int</Name>(<BinOp><BinOp>(<Name>t</Name> % <Num>1.0</Num>)</BinOp> * <Num>1000000</Num></BinOp>)</Call></Assign>
213.1414 - <Assign><Name>ss</Name> = <Call><Name>min</Name>(<Name>ss</Name>, <Num>59</Num>)</Call></Assign> # clamp out leap seconds if the platform has them
213.1415 - <Return>return <Call><Name>cls</Name>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>, <Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Name>us</Name>)</Call></Return>
213.1416 - </FunctionDef> <Assign><Name>utcfromtimestamp</Name> = <Call><Name>classmethod</Name>(<Name>utcfromtimestamp</Name>)</Call></Assign>
213.1417 -
213.1418 - # XXX This is supposed to do better than we *can* do by using time.time(),
213.1419 - # XXX if the platform supports a more accurate way. The C implementation
213.1420 - # XXX uses gettimeofday on platforms that have it, but that isn't
213.1421 - # XXX available from Python. So now() may return different results
213.1422 - # XXX across the implementations.
213.1423 - <FunctionDef>def now(<Name>cls</Name>, <Name>tz</Name>=<Name>None</Name>):
213.1424 - <Expr><Str>"Construct a datetime from time.time() and optional time zone info."</Str></Expr>
213.1425 - <Assign><Name>t</Name> = <Call><Attribute><Name>_time</Name>.time</Attribute>()</Call></Assign>
213.1426 - <Return>return <Call><Attribute><Name>cls</Name>.fromtimestamp</Attribute>(<Name>t</Name>, <Name>tz</Name>)</Call></Return>
213.1427 - </FunctionDef> <Assign><Name>now</Name> = <Call><Name>classmethod</Name>(<Name>now</Name>)</Call></Assign>
213.1428 -
213.1429 - <FunctionDef>def utcnow(<Name>cls</Name>):
213.1430 - <Expr><Str>"Construct a UTC datetime from time.time()."</Str></Expr>
213.1431 - <Assign><Name>t</Name> = <Call><Attribute><Name>_time</Name>.time</Attribute>()</Call></Assign>
213.1432 - <Return>return <Call><Attribute><Name>cls</Name>.utcfromtimestamp</Attribute>(<Name>t</Name>)</Call></Return>
213.1433 - </FunctionDef> <Assign><Name>utcnow</Name> = <Call><Name>classmethod</Name>(<Name>utcnow</Name>)</Call></Assign>
213.1434 -
213.1435 - <FunctionDef>def combine(<Name>cls</Name>, <Name>date</Name>, <Name>time</Name>):
213.1436 - <Expr><Str>"Construct a datetime from a given date and a given time."</Str></Expr>
213.1437 - <If>if <UnaryOp>not <Call><Name>isinstance</Name>(<Name>date</Name>, <Name>_date_class</Name>)</Call></UnaryOp>:
213.1438 - <Raise>raise <Call><Name>TypeError</Name>(<Str>"date argument must be a date instance"</Str>)</Call></Raise>
213.1439 - </If> <If>if <UnaryOp>not <Call><Name>isinstance</Name>(<Name>time</Name>, <Name>_time_class</Name>)</Call></UnaryOp>:
213.1440 - <Raise>raise <Call><Name>TypeError</Name>(<Str>"time argument must be a time instance"</Str>)</Call></Raise>
213.1441 - </If> <Return>return <Call><Name>cls</Name>(<Attribute><Name>date</Name>.year</Attribute>, <Attribute><Name>date</Name>.month</Attribute>, <Attribute><Name>date</Name>.day</Attribute>,
213.1442 - <Attribute><Name>time</Name>.hour</Attribute>, <Attribute><Name>time</Name>.minute</Attribute>, <Attribute><Name>time</Name>.second</Attribute>, <Attribute><Name>time</Name>.microsecond</Attribute>,
213.1443 - <Attribute><Name>time</Name>.tzinfo</Attribute>)</Call></Return>
213.1444 - </FunctionDef> <Assign><Name>combine</Name> = <Call><Name>classmethod</Name>(<Name>combine</Name>)</Call></Assign>
213.1445 -
213.1446 - <FunctionDef>def timetuple(<Name>self</Name>):
213.1447 - <Expr><Str>"Return local time tuple compatible with time.localtime()."</Str></Expr>
213.1448 - <Assign><Name>dst</Name> = <Call><Attribute><Name>self</Name>._dst</Attribute>()</Call></Assign>
213.1449 - <If>if <Compare><Name>dst</Name> is <Name>None</Name></Compare>:
213.1450 - <Assign><Name>dst</Name> = <Num>-1</Num></Assign>
213.1451 - <If>elif <Name>dst</Name>:
213.1452 - <Assign><Name>dst</Name> = <Num>1</Num></Assign>
213.1453 - </If></If> <Return>return <Call><Name>_build_struct_time</Name>(<Attribute><Name>self</Name>.year</Attribute>, <Attribute><Name>self</Name>.month</Attribute>, <Attribute><Name>self</Name>.day</Attribute>,
213.1454 - <Attribute><Name>self</Name>.hour</Attribute>, <Attribute><Name>self</Name>.minute</Attribute>, <Attribute><Name>self</Name>.second</Attribute>,
213.1455 - <Name>dst</Name>)</Call></Return>
213.1456 -
213.1457 - </FunctionDef> <FunctionDef>def utctimetuple(<Name>self</Name>):
213.1458 - <Expr><Str>"Return UTC time tuple compatible with time.gmtime()."</Str></Expr>
213.1459 - <Assign><Tuple><Name>y</Name>, <Name>m</Name>, <Name>d</Name></Tuple> = <Tuple><Attribute><Name>self</Name>.year</Attribute>, <Attribute><Name>self</Name>.month</Attribute>, <Attribute><Name>self</Name>.day</Attribute></Tuple></Assign>
213.1460 - <Assign><Tuple><Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name></Tuple> = <Tuple><Attribute><Name>self</Name>.hour</Attribute>, <Attribute><Name>self</Name>.minute</Attribute>, <Attribute><Name>self</Name>.second</Attribute></Tuple></Assign>
213.1461 - <Assign><Name>offset</Name> = <Call><Attribute><Name>self</Name>._utcoffset</Attribute>()</Call></Assign>
213.1462 - <If>if <Name>offset</Name>: # neither None nor 0
213.1463 - <Assign><Name>tm</Name> = <Call><Name>tmxxx</Name>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>, <Name>hh</Name>, <BinOp><Name>mm</Name> - <Name>offset</Name></BinOp>)</Call></Assign>
213.1464 - <Assign><Tuple><Name>y</Name>, <Name>m</Name>, <Name>d</Name></Tuple> = <Tuple><Attribute><Name>tm</Name>.year</Attribute>, <Attribute><Name>tm</Name>.month</Attribute>, <Attribute><Name>tm</Name>.day</Attribute></Tuple></Assign>
213.1465 - <Assign><Tuple><Name>hh</Name>, <Name>mm</Name></Tuple> = <Tuple><Attribute><Name>tm</Name>.hour</Attribute>, <Attribute><Name>tm</Name>.minute</Attribute></Tuple></Assign>
213.1466 - </If> <Return>return <Call><Name>_build_struct_time</Name>(<Name>y</Name>, <Name>m</Name>, <Name>d</Name>, <Name>hh</Name>, <Name>mm</Name>, <Name>ss</Name>, <Num>0</Num>)</Call></Return>
213.1467 -
213.1468 - </FunctionDef> <FunctionDef>def date(<Name>self</Name>):
213.1469 - <Expr><Str>"Return the date part."</Str></Expr>
213.1470 - <Return>return <Call><Name>date</Name>(<Attribute><Name>self</Name>.__year</Attribute>, <Attribute><Name>self</Name>.__month</Attribute>, <Attribute><Name>self</Name>.__day</Attribute>)</Call></Return>
213.1471 -
213.1472 - </FunctionDef> <FunctionDef>def time(<Name>self</Name>):
213.1473 - <Expr><Str>"Return the time part, with tzinfo None."</Str></Expr>
213.1474 - <Return>return <Call><Name>time</Name>(<Attribute><Name>self</Name>.hour</Attribute>, <Attribute><Name>self</Name>.minute</Attribute>, <Attribute><Name>self</Name>.second</Attribute>, <Attribute><Name>self</Name>.microsecond</Attribute>)</Call></Return>
213.1475 -
213.1476 - </FunctionDef> <FunctionDef>def timetz(<Name>self</Name>):
213.1477 - <Expr><Str>"Return the time part, with same tzinfo."</Str></Expr>
213.1478 - <Return>return <Call><Name>time</Name>(<Attribute><Name>self</Name>.hour</Attribute>, <Attribute><Name>self</Name>.minute</Attribute>, <Attribute><Name>self</Name>.second</Attribute>, <Attribute><Name>self</Name>.microsecond</Attribute>,
213.1479 - <Attribute><Name>self</Name>._tzinfo</Attribute>)</Call></Return>
213.1480 -
213.1481 - </FunctionDef> <FunctionDef>def replace(<Name>self</Name>, <Name>year</Name>=<Name>None</Name>, <Name>month</Name>=<Name>None</Name>, <Name>day</Name>=<Name>None</Name>, <Name>hour</Name>=<Name>None</Name>,
213.1482 - <Name>minute</Name>=<Name>None</Name>, <Name>second</Name>=<Name>None</Name>, <Name>microsecond</Name>=<Name>None</Name>, <Name>tzinfo</Name>=<Name>True</Name>):
213.1483 - <Expr><Str>"""Return a new datetime with new values for the specified fields."""</Str></Expr>
213.1484 - <If>if <Compare><Name>year</Name> is <Name>None</Name></Compare>:
213.1485 - <Assign><Name>year</Name> = <Attribute><Name>self</Name>.year</Attribute></Assign>
213.1486 - </If> <If>if <Compare><Name>month</Name> is <Name>None</Name></Compare>:
213.1487 - <Assign><Name>month</Name> = <Attribute><Name>self</Name>.month</Attribute></Assign>
213.1488 - </If> <If>if <Compare><Name>day</Name> is <Name>None</Name></Compare>:
213.1489 - <Assign><Name>day</Name> = <Attribute><Name>self</Name>.day</Attribute></Assign>
213.1490 - </If> <If>if <Compare><Name>hour</Name> is <Name>None</Name></Compare>:
213.1491 - <Assign><Name>hour</Name> = <Attribute><Name>self</Name>.hour</Attribute></Assign>
213.1492 - </If> <If>if <Compare><Name>minute</Name> is <Name>None</Name></Compare>:
213.1493 - <Assign><Name>minute</Name> = <Attribute><Name>self</Name>.minute</Attribute></Assign>
213.1494 - </If> <If>if <Compare><Name>second</Name> is <Name>None</Name></Compare>:
213.1495 - <Assign><Name>second</Name> = <Attribute><Name>self</Name>.second</Attribute></Assign>
213.1496 - </If> <If>if <Compare><Name>microsecond</Name> is <Name>None</Name></Compare>:
213.1497 - <Assign><Name>microsecond</Name> = <Attribute><Name>self</Name>.microsecond</Attribute></Assign>
213.1498 - </If> <If>if <Compare><Name>tzinfo</Name> is <Name>True</Name></Compare>:
213.1499 - <Assign><Name>tzinfo</Name> = <Attribute><Name>self</Name>.tzinfo</Attribute></Assign>
213.1500 - </If> <Expr><Call><Name>_check_date_fields</Name>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>)</Call></Expr>
213.1501 - <Expr><Call><Name>_check_time_fields</Name>(<Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>, <Name>microsecond</Name>)</Call></Expr>
213.1502 - <Expr><Call><Name>_check_tzinfo_arg</Name>(<Name>tzinfo</Name>)</Call></Expr>
213.1503 - <Return>return <Call><Name>datetime</Name>(<Name>year</Name>, <Name>month</Name>, <Name>day</Name>, <Name>hour</Name>, <Name>minute</Name>, <Name>second</Name>,
213.1504 - <Name>microsecond</Name>, <Name>tzinfo</Name>)</Call></Return>
213.1505 -
213.1506 - </FunctionDef> <FunctionDef>def astimezone(<Name>self</Name>, <Name>tz</Name>):
213.1507 - <If>if <UnaryOp>not <Call><Name>isinstance</Name>(<Name>tz</Name>, <Name>tzinfo</Name>)</Call></UnaryOp>:
213.1508 - <Raise>raise <Call><Name>TypeError</Name>(<Str>"tz argument must be an instance of tzinfo"</Str>)</Call></Raise>
213.1509 -
213.1510 - </If> <Assign><Name>mytz</Name> = <Attribute><Name>self</Name>.tzinfo</Attribute></Assign>
213.1511 - <If>if <Compare><Name>mytz</Name> is <Name>None</Name></Compare>:
213.1512 - <Raise>raise <Call><Name>ValueError</Name>(<Str>"astimezone() requires an aware datetime"</Str>)</Call></Raise>
213.1513 -
213.1514 - </If> <If>if <Compare><Name>tz</Name> is <Name>mytz</Name></Compare>:
213.1515 - <Return>return <Name>self</Name></Return>
213.1516 -
213.1517 - # Convert self to UTC, and attach the new time zone object.
213.1518 - </If> <Assign><Name>myoffset</Name> = <Call><Attribute><Name>self</Name>.utcoffset</Attribute>()</Call></Assign>
213.1519 - <If>if <Compare><Name>myoffset</Name> is <Name>None</Name></Compare>:
213.1520 - <Raise>raise <Call><Name>ValuError</Name>(<Str>"astimezone() requires an aware datetime"</Str>)</Call></Raise>
213.1521 - </If> <Assign><Name>utc</Name> = <Call><Attribute><BinOp>(<Name>self</Name> - <Name>myoffset</Name>)</BinOp>.replace</Attribute>(tzinfo=<Name>tz</Name>)</Call></Assign>
213.1522 -
213.1523 - # Convert from UTC to tz's local time.
213.1524 - <Return>return <Call><Attribute><Name>tz</Name>.fromutc</Attribute>(<Name>utc</Name>)</Call></Return>
213.1525 -
213.1526 - # Ways to produce a string.
213.1527 -
213.1528 - </FunctionDef> <FunctionDef>def ctime(<Name>self</Name>):
213.1529 - <Expr><Str>"Format a la ctime()."</Str></Expr>
213.1530 - <Assign><Name>t</Name> = <Call><Name>tmxxx</Name>(<Attribute><Name>self</Name>.__year</Attribute>, <Attribute><Name>self</Name>.__month</Attribute>, <Attribute><Name>self</Name>.__day</Attribute>, <Attribute><Name>self</Name>.__hour</Attribute>,
213.1531 - <Attribute><Name>self</Name>.__minute</Attribute>, <Attribute><Name>self</Name>.__second</Attribute>)</Call></Assign>
213.1532 - <Return>return <Call><Attribute><Name>t</Name>.ctime</Attribute>()</Call></Return>
213.1533 -
213.1534 - </FunctionDef> <FunctionDef>def isoformat(<Name>self</Name>, <Name>sep</Name>=<Str>'T'</Str>):
213.1535 - <Expr><Str>"""Return the time formatted according to ISO.
213.1536 -
213.1537 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
213.1538 - self.microsecond == 0.
213.1539 -
213.1540 - If self.tzinfo is not None, the UTC offset is also attached, giving
213.1541 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
213.1542 -
213.1543 - Optional argument sep specifies the separator between date and
213.1544 - time, default 'T'.
213.1545 - """</Str></Expr>
213.1546 - <Assign><Name>s</Name> = <BinOp>(<BinOp><Str>"%04d-%02d-%02d%c"</Str></BinOp> % <Tuple>(<Attribute><Name>self</Name>.__year</Attribute>, <Attribute><Name>self</Name>.__month</Attribute>, <Attribute><Name>self</Name>.__day</Attribute>,
213.1547 - <Name>sep</Name>)</Tuple> +
213.1548 - <Call><Name>_format_time</Name>(<Attribute><Name>self</Name>.__hour</Attribute>, <Attribute><Name>self</Name>.__minute</Attribute>, <Attribute><Name>self</Name>.__second</Attribute>,
213.1549 - <Attribute><Name>self</Name>.__microsecond</Attribute>)</Call>)</BinOp></Assign>
213.1550 - <Assign><Name>off</Name> = <Call><Attribute><Name>self</Name>._utcoffset</Attribute>()</Call></Assign>
213.1551 - <If>if <Compare><Name>off</Name> is not <Name>None</Name></Compare>:
213.1552 - <If>if <Compare><Name>off</Name> < <Num>0</Num></Compare>:
213.1553 - <Assign><Name>sign</Name> = <Str>"-"</Str></Assign>
213.1554 - <Assign><Name>off</Name> = <UnaryOp>-<Name>off</Name></UnaryOp></Assign>
213.1555 - else:
213.1556 - <Assign><Name>sign</Name> = <Str>"+"</Str></Assign>
213.1557 - </If> <Assign><Tuple><Name>hh</Name>, <Name>mm</Name></Tuple> = <Call><Name>divmod</Name>(<Name>off</Name>, <Num>60</Num>)</Call></Assign>
213.1558 - <AugAssign><Name>s</Name> += <BinOp><Str>"%s%02d:%02d"</Str> % <Tuple>(<Name>sign</Name>, <Name>hh</Name>, <Name>mm</Name>)</Tuple></BinOp></AugAssign>
213.1559 - </If> <Return>return <Name>s</Name></Return>
213.1560 -
213.1561 - </FunctionDef> <FunctionDef>def __repr__(<Name>self</Name>):
213.1562 - <Expr><Str>"Convert to formal string, for repr()."</Str></Expr>
213.1563 - <Assign><Name>L</Name> = <List>[<Attribute><Name>self</Name>.__year</Attribute>, <Attribute><Name>self</Name>.__month</Attribute>, <Attribute><Name>self</Name>.__day</Attribute>, # These are never zero
213.1564 - <Attribute><Name>self</Name>.__hour</Attribute>, <Attribute><Name>self</Name>.__minute</Attribute>, <Attribute><Name>self</Name>.__second</Attribute>, <Attribute><Name>self</Name>.__microsecond</Attribute>]</List></Assign>
213.1565 - <If>if <Compare><Subscript><Name>L</Name>[<Index><Num>-1</Num></Index>]</Subscript> == <Num>0</Num></Compare>:
213.1566 - <Delete>del <Subscript><Name>L</Name>[<Index><Num>-1</Num></Index>]</Subscript></Delete>
213.1567 - </If> <If>if <Compare><Subscript><Name>L</Name>[<Index><Num>-1</Num></Index>]</Subscript> == <Num>0</Num></Compare>:
213.1568 - <Delete>del <Subscript><Name>L</Name>[<Index><Num>-1</Num></Index>]</Subscript></Delete>
213.1569 - </If> <Assign><Name>s</Name> = <Call><Attribute><Str>", "</Str>.join</Attribute>(<Call><Name>map</Name>(<Name>str</Name>, <Name>L</Name>)</Call>)</Call></Assign>
213.1570 - <Assign><Name>s</Name> = <BinOp><Str>"%s(%s)"</Str> % <Tuple>(<BinOp><Str>'datetime.'</Str> + <Attribute><Attribute><Name>self</Name>.__class__</Attribute>.__name__</Attribute></BinOp>, <Name>s</Name>)</Tuple></BinOp></Assign>
213.1571 - <If>if <Compare><Attribute><Name>self</Name>._tzinfo</Attribute> is not <Name>None</Name></Compare>:
213.1572 - <Assert>assert <Compare><Subscript><Name>s</Name>[<Slice><Num>-1</Num>:</Slice>]</Subscript> == <Str>")"</Str></Compare></Assert>
213.1573 - <Assign><Name>s</Name> = <BinOp><BinOp><Subscript><Name>s</Name>[<Slice>:<Num>-1</Num></Slice>]</Subscript></BinOp> + <BinOp><Str>", tzinfo=%r"</Str></BinOp> % <Attribute><Name>self</Name>._tzinfo</Attribute> + <Str>")"</Str></BinOp></Assign>
213.1574 - </If> <Return>return <Name>s</Name></Return>
213.1575 -
213.1576 - </FunctionDef> <FunctionDef>def __str__(<Name>self</Name>):
213.1577 - <Expr><Str>"Convert to string, for str()."</Str></Expr>
213.1578 - <Return>return <Call><Attribute><Name>self</Name>.isoformat</Attribute>(sep=<Str>' '</Str>)</Call></Return>
213.1579 -
213.1580 - </FunctionDef> <FunctionDef>def utcoffset(<Name>self</Name>):
213.1581 - <Expr><Str>"""Return the timezone offset in minutes east of UTC (negative west of
213.1582 - UTC)."""</Str></Expr>
213.1583 - <Assign><Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name>(<Attribute><Name>self</Name>._tzinfo</Attribute>, <Str>"utcoffset"</Str>, <Name>self</Name>)</Call></Assign>
213.1584 - <Assign><Name>offset</Name> = <Call><Name>_check_utc_offset</Name>(<Str>"utcoffset"</Str>, <Name>offset</Name>)</Call></Assign>
213.1585 - <If>if <Compare><Name>offset</Name> is not <Name>None</Name></Compare>:
213.1586 - <Assign><Name>offset</Name> = <Call><Name>timedelta</Name>(minutes=<Name>offset</Name>)</Call></Assign>
213.1587 - </If> <Return>return <Name>offset</Name></Return>
213.1588 -
213.1589 - # Return an integer (or None) instead of a timedelta (or None).
213.1590 - </FunctionDef> <FunctionDef>def _utcoffset(<Name>self</Name>):
213.1591 - <Assign><Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name>(<Attribute><Name>self</Name>._tzinfo</Attribute>, <Str>"utcoffset"</Str>, <Name>self</Name>)</Call></Assign>
213.1592 - <Assign><Name>offset</Name> = <Call><Name>_check_utc_offset</Name>(<Str>"utcoffset"</Str>, <Name>offset</Name>)</Call></Assign>
213.1593 - <Return>return <Name>offset</Name></Return>
213.1594 -
213.1595 - </FunctionDef> <FunctionDef>def tzname(<Name>self</Name>):
213.1596 - <Expr><Str>"""Return the timezone name.
213.1597 -
213.1598 - Note that the name is 100% informational -- there's no requirement that
213.1599 - it mean anything in particular. For example, "GMT", "UTC", "-500",
213.1600 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
213.1601 - """</Str></Expr>
213.1602 - <Assign><Name>name</Name> = <Call><Name>_call_tzinfo_method</Name>(<Attribute><Name>self</Name>._tzinfo</Attribute>, <Str>"tzname"</Str>, <Name>self</Name>)</Call></Assign>
213.1603 - <Expr><Call><Name>_check_tzname</Name>(<Name>name</Name>)</Call></Expr>
213.1604 - <Return>return <Name>name</Name></Return>
213.1605 -
213.1606 - </FunctionDef> <FunctionDef>def dst(<Name>self</Name>):
213.1607 - <Expr><Str>"""Return 0 if DST is not in effect, or the DST offset (in minutes
213.1608 - eastward) if DST is in effect.
213.1609 -
213.1610 - This is purely informational; the DST offset has already been added to
213.1611 - the UTC offset returned by utcoffset() if applicable, so there's no
213.1612 - need to consult dst() unless you're interested in displaying the DST
213.1613 - info.
213.1614 - """</Str></Expr>
213.1615 - <Assign><Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name>(<Attribute><Name>self</Name>._tzinfo</Attribute>, <Str>"dst"</Str>, <Name>self</Name>)</Call></Assign>
213.1616 - <Assign><Name>offset</Name> = <Call><Name>_check_utc_offset</Name>(<Str>"dst"</Str>, <Name>offset</Name>)</Call></Assign>
213.1617 - <If>if <Compare><Name>offset</Name> is not <Name>None</Name></Compare>:
213.1618 - <Assign><Name>offset</Name> = <Call><Name>timedelta</Name>(minutes=<Name>offset</Name>)</Call></Assign>
213.1619 - </If> <Return>return <Name>offset</Name></Return>
213.1620 -
213.1621 - # Return an integer (or None) instead of a timedelta (or None).1573
213.1622 - </FunctionDef> <FunctionDef>def _dst(<Name>self</Name>):
213.1623 - <Assign><Name>offset</Name> = <Call><Name>_call_tzinfo_method</Name>(<Attribute><Name>self</Name>._tzinfo</Attribute>, <Str>"dst"</Str>, <Name>self</Name>)</Call></Assign>
213.1624 - <Assign><Name>offset</Name> = <Call><Name>_check_utc_offset</Name>(<Str>"dst"</Str>, <Name>offset</Name>)</Call></Assign>
213.1625 - <Return>return <Name>offset</Name></Return>
213.1626 -
213.1627 - # Comparisons.
213.1628 -
213.1629 - </FunctionDef> <FunctionDef>def __eq__(<Name>self</Name>, <Name>other</Name>):
213.1630 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>datetime</Name>)</Call>:
213.1631 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> == <Num>0</Num></Compare></Return>
213.1632 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
213.1633 - <Return>return <Name>NotImplemented</Name></Return>
213.1634 - else:
213.1635 - <Return>return <Name>False</Name></Return>
213.1636 -
213.1637 - </If></If></FunctionDef> <FunctionDef>def __ne__(<Name>self</Name>, <Name>other</Name>):
213.1638 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>datetime</Name>)</Call>:
213.1639 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> != <Num>0</Num></Compare></Return>
213.1640 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
213.1641 - <Return>return <Name>NotImplemented</Name></Return>
213.1642 - else:
213.1643 - <Return>return <Name>True</Name></Return>
213.1644 -
213.1645 - </If></If></FunctionDef> <FunctionDef>def __le__(<Name>self</Name>, <Name>other</Name>):
213.1646 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>datetime</Name>)</Call>:
213.1647 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> <= <Num>0</Num></Compare></Return>
213.1648 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
213.1649 - <Return>return <Name>NotImplemented</Name></Return>
213.1650 - else:
213.1651 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
213.1652 -
213.1653 - </If></If></FunctionDef> <FunctionDef>def __lt__(<Name>self</Name>, <Name>other</Name>):
213.1654 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>datetime</Name>)</Call>:
213.1655 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> < <Num>0</Num></Compare></Return>
213.1656 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
213.1657 - <Return>return <Name>NotImplemented</Name></Return>
213.1658 - else:
213.1659 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
213.1660 -
213.1661 - </If></If></FunctionDef> <FunctionDef>def __ge__(<Name>self</Name>, <Name>other</Name>):
213.1662 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>datetime</Name>)</Call>:
213.1663 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> >= <Num>0</Num></Compare></Return>
213.1664 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
213.1665 - <Return>return <Name>NotImplemented</Name></Return>
213.1666 - else:
213.1667 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
213.1668 -
213.1669 - </If></If></FunctionDef> <FunctionDef>def __gt__(<Name>self</Name>, <Name>other</Name>):
213.1670 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>datetime</Name>)</Call>:
213.1671 - <Return>return <Compare><Call><Attribute><Name>self</Name>.__cmp</Attribute>(<Name>other</Name>)</Call> > <Num>0</Num></Compare></Return>
213.1672 - <If>elif <Call><Name>hasattr</Name>(<Name>other</Name>, <Str>"timetuple"</Str>)</Call>:
213.1673 - <Return>return <Name>NotImplemented</Name></Return>
213.1674 - else:
213.1675 - <Expr><Call><Name>_cmperror</Name>(<Name>self</Name>, <Name>other</Name>)</Call></Expr>
213.1676 -
213.1677 - </If></If></FunctionDef> <FunctionDef>def __cmp(<Name>self</Name>, <Name>other</Name>):
213.1678 - <Assert>assert <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>datetime</Name>)</Call></Assert>
213.1679 - <Assign><Name>mytz</Name> = <Attribute><Name>self</Name>._tzinfo</Attribute></Assign>
213.1680 - <Assign><Name>ottz</Name> = <Attribute><Name>other</Name>._tzinfo</Attribute></Assign>
213.1681 - <Assign><Name>myoff</Name> = <Name>otoff</Name> = <Name>None</Name></Assign>
213.1682 -
213.1683 - <If>if <Compare><Name>mytz</Name> is <Name>ottz</Name></Compare>:
213.1684 - <Assign><Name>base_compare</Name> = <Name>True</Name></Assign>
213.1685 - else:
213.1686 - <If>if <Compare><Name>mytz</Name> is not <Name>None</Name></Compare>:
213.1687 - <Assign><Name>myoff</Name> = <Call><Attribute><Name>self</Name>._utcoffset</Attribute>()</Call></Assign>
213.1688 - </If> <If>if <Compare><Name>ottz</Name> is not <Name>None</Name></Compare>:
213.1689 - <Assign><Name>otoff</Name> = <Call><Attribute><Name>other</Name>._utcoffset</Attribute>()</Call></Assign>
213.1690 - </If> <Assign><Name>base_compare</Name> = <Compare><Name>myoff</Name> == <Name>otoff</Name></Compare></Assign>
213.1691 -
213.1692 - </If> <If>if <Name>base_compare</Name>:
213.1693 - <Return>return <Call><Name>cmp</Name>(<Tuple>(<Attribute><Name>self</Name>.__year</Attribute>, <Attribute><Name>self</Name>.__month</Attribute>, <Attribute><Name>self</Name>.__day</Attribute>,
213.1694 - <Attribute><Name>self</Name>.__hour</Attribute>, <Attribute><Name>self</Name>.__minute</Attribute>, <Attribute><Name>self</Name>.__second</Attribute>,
213.1695 - <Attribute><Name>self</Name>.__microsecond</Attribute>)</Tuple>,
213.1696 - <Tuple>(<Attribute><Name>other</Name>.__year</Attribute>, <Attribute><Name>other</Name>.__month</Attribute>, <Attribute><Name>other</Name>.__day</Attribute>,
213.1697 - <Attribute><Name>other</Name>.__hour</Attribute>, <Attribute><Name>other</Name>.__minute</Attribute>, <Attribute><Name>other</Name>.__second</Attribute>,
213.1698 - <Attribute><Name>other</Name>.__microsecond</Attribute>)</Tuple>)</Call></Return>
213.1699 - </If> <If>if <BoolOp><Compare><Name>myoff</Name> is <Name>None</Name></Compare> or <Compare><Name>otoff</Name> is <Name>None</Name></Compare></BoolOp>:
213.1700 - # XXX Buggy in 2.2.2.
213.1701 - <Raise>raise <Call><Name>TypeError</Name>(<Str>"cannot compare naive and aware datetimes"</Str>)</Call></Raise>
213.1702 - # XXX What follows could be done more efficiently...
213.1703 - </If> <Assign><Name>diff</Name> = <BinOp><Name>self</Name> - <Name>other</Name></BinOp></Assign> # this will take offsets into account
213.1704 - <If>if <Compare><Attribute><Name>diff</Name>.days</Attribute> < <Num>0</Num></Compare>:
213.1705 - <Return>return <Num>-1</Num></Return>
213.1706 - </If> <Return>return <BoolOp><BoolOp><Name>diff</Name></BoolOp> and <Num>1</Num> or <Num>0</Num></BoolOp></Return>
213.1707 -
213.1708 - </FunctionDef> <FunctionDef>def __add__(<Name>self</Name>, <Name>other</Name>):
213.1709 - <Expr><Str>"Add a datetime and a timedelta."</Str></Expr>
213.1710 - <If>if <UnaryOp>not <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call></UnaryOp>:
213.1711 - <Return>return <Name>NotImplemented</Name></Return>
213.1712 - </If> <Assign><Name>t</Name> = <Call><Name>tmxxx</Name>(<Attribute><Name>self</Name>.__year</Attribute>,
213.1713 - <Attribute><Name>self</Name>.__month</Attribute>,
213.1714 - <BinOp><Attribute><Name>self</Name>.__day</Attribute> + <Attribute><Name>other</Name>.days</Attribute></BinOp>,
213.1715 - <Attribute><Name>self</Name>.__hour</Attribute>,
213.1716 - <Attribute><Name>self</Name>.__minute</Attribute>,
213.1717 - <BinOp><Attribute><Name>self</Name>.__second</Attribute> + <Attribute><Name>other</Name>.seconds</Attribute></BinOp>,
213.1718 - <BinOp><Attribute><Name>self</Name>.__microsecond</Attribute> + <Attribute><Name>other</Name>.microseconds</Attribute></BinOp>)</Call></Assign>
213.1719 - <Expr><Call><Attribute><Name>self</Name>._checkOverflow</Attribute>(<Attribute><Name>t</Name>.year</Attribute>)</Call></Expr>
213.1720 - <Assign><Name>result</Name> = <Call><Attribute><Name>self</Name>.__class__</Attribute>(<Attribute><Name>t</Name>.year</Attribute>, <Attribute><Name>t</Name>.month</Attribute>, <Attribute><Name>t</Name>.day</Attribute>,
213.1721 - <Attribute><Name>t</Name>.hour</Attribute>, <Attribute><Name>t</Name>.minute</Attribute>, <Attribute><Name>t</Name>.second</Attribute>,
213.1722 - <Attribute><Name>t</Name>.microsecond</Attribute>, tzinfo=<Attribute><Name>self</Name>._tzinfo</Attribute>)</Call></Assign>
213.1723 - <Return>return <Name>result</Name></Return>
213.1724 -
213.1725 - </FunctionDef> <Assign><Name>__radd__</Name> = <Name>__add__</Name></Assign>
213.1726 -
213.1727 - <FunctionDef>def __sub__(<Name>self</Name>, <Name>other</Name>):
213.1728 - <Expr><Str>"Subtract two datetimes, or a datetime and a timedelta."</Str></Expr>
213.1729 - <If>if <UnaryOp>not <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>datetime</Name>)</Call></UnaryOp>:
213.1730 - <If>if <Call><Name>isinstance</Name>(<Name>other</Name>, <Name>timedelta</Name>)</Call>:
213.1731 - <Return>return <BinOp><Name>self</Name> + <UnaryOp>-<Name>other</Name></UnaryOp></BinOp></Return>
213.1732 - </If> <Return>return <Name>NotImplemented</Name></Return>
213.1733 -
213.1734 - </If> <Assign><Name>days1</Name> = <Call><Attribute><Name>self</Name>.toordinal</Attribute>()</Call></Assign>
213.1735 - <Assign><Name>days2</Name> = <Call><Attribute><Name>other</Name>.toordinal</Attribute>()</Call></Assign>
213.1736 - <Assign><Name>secs1</Name> = <BinOp><BinOp><Attribute><Name>self</Name>.__second</Attribute></BinOp> + <BinOp><Attribute><Name>self</Name>.__minute</Attribute></BinOp> * <Num>60</Num> + <BinOp><Attribute><Name>self</Name>.__hour</Attribute></BinOp> * <Num>3600</Num></BinOp></Assign>
213.1737 - <Assign><Name>secs2</Name> = <BinOp><BinOp><Attribute><Name>other</Name>.__second</Attribute></BinOp> + <BinOp><Attribute><Name>other</Name>.__minute</Attribute></BinOp> * <Num>60</Num> + <BinOp><Attribute><Name>other</Name>.__hour</Attribute></BinOp> * <Num>3600</Num></BinOp></Assign>
213.1738 - <Assign><Name>base</Name> = <Call><Name>timedelta</Name>(<BinOp><Name>days1</Name> - <Name>days2</Name></BinOp>,
213.1739 - <BinOp><Name>secs1</Name> - <Name>secs2</Name></BinOp>,
213.1740 - <BinOp><Attribute><Name>self</Name>.__microsecond</Attribute> - <Attribute><Name>other</Name>.__microsecond</Attribute></BinOp>)</Call></Assign>
213.1741 - <If>if <Compare><Attribute><Name>self</Name>._tzinfo</Attribute> is <Attribute><Name>other</Name>._tzinfo</Attribute></Compare>:
213.1742 - <Return>return <Name>base</Name></Return>
213.1743 - </If> <Assign><Name>myoff</Name> = <Call><Attribute><Name>self</Name>._utcoffset</Attribute>()</Call></Assign>
213.1744 - <Assign><Name>otoff</Name> = <Call><Attribute><Name>other</Name>._utcoffset</Attribute>()</Call></Assign>
213.1745 - <If>if <Compare><Name>myoff</Name> == <Name>otoff</Name></Compare>:
213.1746 - <Return>return <Name>base</Name></Return>
213.1747 - </If> <If>if <BoolOp><Compare><Name>myoff</Name> is <Name>None</Name></Compare> or <Compare><Name>otoff</Name> is <Name>None</Name></Compare></BoolOp>:
213.1748 - <Raise>raise <Name>TypeError</Name>, <Str>"cannot mix naive and timezone-aware time"</Str></Raise>
213.1749 - </If> <Return>return <BinOp><Name>base</Name> + <Call><Name>timedelta</Name>(minutes = <BinOp><Name>otoff</Name>-<Name>myoff</Name></BinOp>)</Call></BinOp></Return>
213.1750 -
213.1751 - </FunctionDef> <FunctionDef>def __hash__(<Name>self</Name>):
213.1752 - <Assign><Name>tzoff</Name> = <Call><Attribute><Name>self</Name>._utcoffset</Attribute>()</Call></Assign>
213.1753 - <If>if <Compare><Name>tzoff</Name> is <Name>None</Name></Compare>:
213.1754 - <Return>return <Call><Name>hash</Name>(<Subscript><Attribute><Name>self</Name>.__getstate</Attribute><Call>()</Call>[<Index><Num>0</Num></Index>]</Subscript>)</Call></Return>
213.1755 - </If> <Assign><Name>days</Name> = <Call><Name>_ymd2ord</Name>(<Attribute><Name>self</Name>.year</Attribute>, <Attribute><Name>self</Name>.month</Attribute>, <Attribute><Name>self</Name>.day</Attribute>)</Call></Assign>
213.1756 - <Assign><Name>seconds</Name> = <BinOp><BinOp><BinOp><Attribute><Name>self</Name>.hour</Attribute></BinOp></BinOp> * <Num>3600</Num> + <BinOp><BinOp>(<Attribute><Name>self</Name>.minute</Attribute> - <Name>tzoff</Name>)</BinOp></BinOp> * <Num>60</Num> + <Attribute><Name>self</Name>.second</Attribute></BinOp></Assign>
213.1757 - <Return>return <Call><Name>hash</Name>(<Call><Name>timedelta</Name>(<Name>days</Name>, <Name>seconds</Name>, <Attribute><Name>self</Name>.microsecond</Attribute>)</Call>)</Call></Return>
213.1758 -
213.1759 - # Pickle support.
213.1760 -
213.1761 - </FunctionDef> <Assign><Name>__safe_for_unpickling__</Name> = <Name>True</Name></Assign> # For Python 2.2
213.1762 -
213.1763 - <FunctionDef>def __getstate(<Name>self</Name>):
213.1764 - <Assign><Tuple><Name>yhi</Name>, <Name>ylo</Name></Tuple> = <Call><Name>divmod</Name>(<Attribute><Name>self</Name>.__year</Attribute>, <Num>256</Num>)</Call></Assign>
213.1765 - <Assign><Tuple><Name>us2</Name>, <Name>us3</Name></Tuple> = <Call><Name>divmod</Name>(<Attribute><Name>self</Name>.__microsecond</Attribute>, <Num>256</Num>)</Call></Assign>
213.1766 - <Assign><Tuple><Name>us1</Name>, <Name>us2</Name></Tuple> = <Call><Name>divmod</Name>(<Name>us2</Name>, <Num>256</Num>)</Call></Assign>
213.1767 - <Assign><Name>basestate</Name> = <BinOp><BinOp>(<Str>"%c"</Str> * <Num>10</Num>)</BinOp> % <Tuple>(<Name>yhi</Name>, <Name>ylo</Name>, <Attribute><Name>self</Name>.__month</Attribute>, <Attribute><Name>self</Name>.__day</Attribute>,
213.1768 - <Attribute><Name>self</Name>.__hour</Attribute>, <Attribute><Name>self</Name>.__minute</Attribute>, <Attribute><Name>self</Name>.__second</Attribute>,
213.1769 - <Name>us1</Name>, <Name>us2</Name>, <Name>us3</Name>)</Tuple></BinOp></Assign>
213.1770 - <If>if <Compare><Attribute><Name>self</Name>._tzinfo</Attribute> is <Name>None</Name></Compare>:
213.1771 - <Return>return <Tuple>(<Name>basestate</Name>,)</Tuple></Return>
213.1772 - else:
213.1773 - <Return>return <Tuple>(<Name>basestate</Name>, <Attribute><Name>self</Name>._tzinfo</Attribute>)</Tuple></Return>
213.1774 -
213.1775 - </If></FunctionDef> <FunctionDef>def __setstate(<Name>self</Name>, <Name>state</Name>):
213.1776 - <Assert>assert <Call><Name>isinstance</Name>(<Name>state</Name>, <Name>tuple</Name>)</Call></Assert>
213.1777 - <Assert>assert <Compare><Num>1</Num> <= <Call><Name>len</Name>(<Name>state</Name>)</Call> <= <Num>2</Num></Compare></Assert>
213.1778 - <Assign><Name>string</Name> = <Subscript><Name>state</Name>[<Index><Num>0</Num></Index>]</Subscript></Assign>
213.1779 - <Assert>assert <Compare><Call><Name>len</Name>(<Name>string</Name>)</Call> == <Num>10</Num></Compare></Assert>
213.1780 - <Assign><Tuple>(<Name>yhi</Name>, <Name>ylo</Name>, <Attribute><Name>self</Name>.__month</Attribute>, <Attribute><Name>self</Name>.__day</Attribute>, <Attribute><Name>self</Name>.__hour</Attribute>,
213.1781 - <Attribute><Name>self</Name>.__minute</Attribute>, <Attribute><Name>self</Name>.__second</Attribute>, <Name>us1</Name>, <Name>us2</Name>, <Name>us3</Name>)</Tuple> = <Call><Name>map</Name>(<Name>ord</Name>, <Name>string</Name>)</Call></Assign>
213.1782 - <Assign><Attribute><Name>self</Name>.__year</Attribute> = <BinOp><BinOp><Name>yhi</Name></BinOp> * <Num>256</Num> + <Name>ylo</Name></BinOp></Assign>
213.1783 - <Assign><Attribute><Name>self</Name>.__microsecond</Attribute> = <BinOp><BinOp>(<BinOp>(<BinOp>(<Name>us1</Name> << <Num>8</Num>)</BinOp> | <Name>us2</Name>)</BinOp> << <Num>8</Num>)</BinOp> | <Name>us3</Name></BinOp></Assign>
213.1784 - <If>if <Compare><Call><Name>len</Name>(<Name>state</Name>)</Call> == <Num>1</Num></Compare>:
213.1785 - <Assign><Attribute><Name>self</Name>._tzinfo</Attribute> = <Name>None</Name></Assign>
213.1786 - else:
213.1787 - <Assign><Attribute><Name>self</Name>._tzinfo</Attribute> = <Subscript><Name>state</Name>[<Index><Num>1</Num></Index>]</Subscript></Assign>
213.1788 -
213.1789 - </If></FunctionDef> <FunctionDef>def __reduce__(<Name>self</Name>):
213.1790 - <Return>return <Tuple>(<Attribute><Name>self</Name>.__class__</Attribute>, <Call><Attribute><Name>self</Name>.__getstate</Attribute>()</Call>)</Tuple></Return>
213.1791 -
213.1792 -
213.1793 -</FunctionDef></ClassDef><Assign><Attribute><Name>datetime</Name>.min</Attribute> = <Call><Name>datetime</Name>(<Num>1</Num>, <Num>1</Num>, <Num>1</Num>)</Call></Assign>
213.1794 -<Assign><Attribute><Name>datetime</Name>.max</Attribute> = <Call><Name>datetime</Name>(<Num>9999</Num>, <Num>12</Num>, <Num>31</Num>, <Num>23</Num>, <Num>59</Num>, <Num>59</Num>, <Num>999999</Num>)</Call></Assign>
213.1795 -<Assign><Attribute><Name>datetime</Name>.resolution</Attribute> = <Call><Name>timedelta</Name>(microseconds=<Num>1</Num>)</Call></Assign>
213.1796 -
213.1797 -
213.1798 -<FunctionDef>def _isoweek1monday(<Name>year</Name>):
213.1799 - # Helper to calculate the day number of the Monday starting week 1
213.1800 - # XXX This could be done more efficiently
213.1801 - <Assign><Name>THURSDAY</Name> = <Num>3</Num></Assign>
213.1802 - <Assign><Name>firstday</Name> = <Call><Name>_ymd2ord</Name>(<Name>year</Name>, <Num>1</Num>, <Num>1</Num>)</Call></Assign>
213.1803 - <Assign><Name>firstweekday</Name> = <BinOp><BinOp>(<Name>firstday</Name> + <Num>6</Num>)</BinOp> % <Num>7</Num></BinOp></Assign> # See weekday() above
213.1804 - <Assign><Name>week1monday</Name> = <BinOp><Name>firstday</Name> - <Name>firstweekday</Name></BinOp></Assign>
213.1805 - <If>if <Compare><Name>firstweekday</Name> > <Name>THURSDAY</Name></Compare>:
213.1806 - <AugAssign><Name>week1monday</Name> += <Num>7</Num></AugAssign>
213.1807 - </If> <Return>return <Name>week1monday</Name></Return>
213.1808 -
213.1809 -</FunctionDef><Expr><Str>"""
213.1810 -Some time zone algebra. For a datetime x, let
213.1811 - x.n = x stripped of its timezone -- its naive time.
213.1812 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
213.1813 - return None
213.1814 - x.d = x.dst(), and assuming that doesn't raise an exception or
213.1815 - return None
213.1816 - x.s = x's standard offset, x.o - x.d
213.1817 -
213.1818 -Now some derived rules, where k is a duration (timedelta).
213.1819 -
213.1820 -1. x.o = x.s + x.d
213.1821 - This follows from the definition of x.s.
213.1822 -
213.1823 -2. If x and y have the same tzinfo member, x.s = y.s.
213.1824 - This is actually a requirement, an assumption we need to make about
213.1825 - sane tzinfo classes.
213.1826 -
213.1827 -3. The naive UTC time corresponding to x is x.n - x.o.
213.1828 - This is again a requirement for a sane tzinfo class.
213.1829 -
213.1830 -4. (x+k).s = x.s
213.1831 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
213.1832 -
213.1833 -5. (x+k).n = x.n + k
213.1834 - Again follows from how arithmetic is defined.
213.1835 -
213.1836 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
213.1837 -(meaning that the various tzinfo methods exist, and don't blow up or return
213.1838 -None when called).
213.1839 -
213.1840 -The function wants to return a datetime y with timezone tz, equivalent to x.
213.1841 -x is already in UTC.
213.1842 -
213.1843 -By #3, we want
213.1844 -
213.1845 - y.n - y.o = x.n [1]
213.1846 -
213.1847 -The algorithm starts by attaching tz to x.n, and calling that y. So
213.1848 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
213.1849 -becomes true; in effect, we want to solve [2] for k:
213.1850 -
213.1851 - (y+k).n - (y+k).o = x.n [2]
213.1852 -
213.1853 -By #1, this is the same as
213.1854 -
213.1855 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
213.1856 -
213.1857 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
213.1858 -Substituting that into [3],
213.1859 -
213.1860 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
213.1861 - k - (y+k).s - (y+k).d = 0; rearranging,
213.1862 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
213.1863 - k = y.s - (y+k).d
213.1864 -
213.1865 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
213.1866 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
213.1867 -very large, since all offset-returning methods return a duration of magnitude
213.1868 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
213.1869 -be 0, so ignoring it has no consequence then.
213.1870 -
213.1871 -In any case, the new value is
213.1872 -
213.1873 - z = y + y.s [4]
213.1874 -
213.1875 -It's helpful to step back at look at [4] from a higher level: it's simply
213.1876 -mapping from UTC to tz's standard time.
213.1877 -
213.1878 -At this point, if
213.1879 -
213.1880 - z.n - z.o = x.n [5]
213.1881 -
213.1882 -we have an equivalent time, and are almost done. The insecurity here is
213.1883 -at the start of daylight time. Picture US Eastern for concreteness. The wall
213.1884 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
213.1885 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
213.1886 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
213.1887 -on the day DST starts. We want to return the 1:MM EST spelling because that's
213.1888 -the only spelling that makes sense on the local wall clock.
213.1889 -
213.1890 -In fact, if [5] holds at this point, we do have the standard-time spelling,
213.1891 -but that takes a bit of proof. We first prove a stronger result. What's the
213.1892 -difference between the LHS and RHS of [5]? Let
213.1893 -
213.1894 - diff = x.n - (z.n - z.o) [6]
213.1895 -
213.1896 -Now
213.1897 - z.n = by [4]
213.1898 - (y + y.s).n = by #5
213.1899 - y.n + y.s = since y.n = x.n
213.1900 - x.n + y.s = since z and y are have the same tzinfo member,
213.1901 - y.s = z.s by #2
213.1902 - x.n + z.s
213.1903 -
213.1904 -Plugging that back into [6] gives
213.1905 -
213.1906 - diff =
213.1907 - x.n - ((x.n + z.s) - z.o) = expanding
213.1908 - x.n - x.n - z.s + z.o = cancelling
213.1909 - - z.s + z.o = by #2
213.1910 - z.d
213.1911 -
213.1912 -So diff = z.d.
213.1913 -
213.1914 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
213.1915 -spelling we wanted in the endcase described above. We're done. Contrarily,
213.1916 -if z.d = 0, then we have a UTC equivalent, and are also done.
213.1917 -
213.1918 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
213.1919 -add to z (in effect, z is in tz's standard time, and we need to shift the
213.1920 -local clock into tz's daylight time).
213.1921 -
213.1922 -Let
213.1923 -
213.1924 - z' = z + z.d = z + diff [7]
213.1925 -
213.1926 -and we can again ask whether
213.1927 -
213.1928 - z'.n - z'.o = x.n [8]
213.1929 -
213.1930 -If so, we're done. If not, the tzinfo class is insane, according to the
213.1931 -assumptions we've made. This also requires a bit of proof. As before, let's
213.1932 -compute the difference between the LHS and RHS of [8] (and skipping some of
213.1933 -the justifications for the kinds of substitutions we've done several times
213.1934 -already):
213.1935 -
213.1936 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
213.1937 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
213.1938 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
213.1939 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
213.1940 - - z.n + z.n - z.o + z'.o = cancel z.n
213.1941 - - z.o + z'.o = #1 twice
213.1942 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
213.1943 - z'.d - z.d
213.1944 -
213.1945 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
213.1946 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
213.1947 -return z', not bothering to compute z'.d.
213.1948 -
213.1949 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
213.1950 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
213.1951 -would have to change the result dst() returns: we start in DST, and moving
213.1952 -a little further into it takes us out of DST.
213.1953 -
213.1954 -There isn't a sane case where this can happen. The closest it gets is at
213.1955 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
213.1956 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
213.1957 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
213.1958 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
213.1959 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
213.1960 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
213.1961 -standard time. Since that's what the local clock *does*, we want to map both
213.1962 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
213.1963 -in local time, but so it goes -- it's the way the local clock works.
213.1964 -
213.1965 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
213.1966 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
213.1967 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
213.1968 -(correctly) concludes that z' is not UTC-equivalent to x.
213.1969 -
213.1970 -Because we know z.d said z was in daylight time (else [5] would have held and
213.1971 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
213.1972 -and we we have stopped then), and there are only 2 possible values dst() can
213.1973 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
213.1974 -but the reasoning doesn't depend on the example -- it depends on there being
213.1975 -two possible dst() outcomes, one zero and the other non-zero). Therefore
213.1976 -z' must be in standard time, and is the spelling we want in this case.
213.1977 -
213.1978 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
213.1979 -concerned (because it takes z' as being in standard time rather than the
213.1980 -daylight time we intend here), but returning it gives the real-life "local
213.1981 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
213.1982 -tz.
213.1983 -
213.1984 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
213.1985 -the 1:MM standard time spelling we want.
213.1986 -
213.1987 -So how can this break? One of the assumptions must be violated. Two
213.1988 -possibilities:
213.1989 -
213.1990 -1) [2] effectively says that y.s is invariant across all y belong to a given
213.1991 - time zone. This isn't true if, for political reasons or continental drift,
213.1992 - a region decides to change its base offset from UTC.
213.1993 -
213.1994 -2) There may be versions of "double daylight" time where the tail end of
213.1995 - the analysis gives up a step too early. I haven't thought about that
213.1996 - enough to say.
213.1997 -
213.1998 -In any case, it's clear that the default fromutc() is strong enough to handle
213.1999 -"almost all" time zones: so long as the standard offset is invariant, it
213.2000 -doesn't matter if daylight time transition points change from year to year, or
213.2001 -if daylight time is skipped in some years; it doesn't matter how large or
213.2002 -small dst() may get within its bounds; and it doesn't even matter if some
213.2003 -perverse time zone returns a negative dst()). So a breaking case must be
213.2004 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
213.2005 -"""</Str></Expr>
213.2006 -
213.2007 -<FunctionDef>def _test():
213.2008 - <Import>import test_datetime</Import>
213.2009 - <Expr><Call><Attribute><Name>test_datetime</Name>.test_main</Attribute>()</Call></Expr>
213.2010 -
213.2011 -</FunctionDef><If>if <Compare><Name>__name__</Name> == <Str>"__main__"</Str></Compare>:
213.2012 - <Expr><Call><Name>_test</Name>()</Call></Expr></If></Module>
214.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.scopes Sun Jan 04 13:11:53 2015 -0600
214.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
214.3 @@ -1,1967 +0,0 @@
214.4 -=============================================
214.5 -<file-top>: Module : OffsetRange[0,71801>
214.6 -MAXYEAR [bound][data][read][node=Name]
214.7 -MINYEAR [bound][data][read][node=Name]
214.8 -None [read][UNRESOLVED][node=Name]
214.9 -_DAYNAMES [bound][private][data][read][node=Name]
214.10 -_DAYS_BEFORE_MONTH [bound][private][data][read][node=Name]
214.11 -_DAYS_IN_MONTH [bound][private][data][read][node=Name]
214.12 -_DI100Y [bound][private][data][read][node=Name]
214.13 -_DI400Y [bound][private][data][read][node=Name]
214.14 -_DI4Y [bound][private][data][read][node=Name]
214.15 -_MONTHNAMES [bound][private][data][read][node=Name]
214.16 -_ORD1970 [bound][private][data][read][node=Name]
214.17 -__name__ [read][UNRESOLVED][node=Name]
214.18 -_build_struct_time [bound][private][function][def][read][called][node=FunctionDef]
214.19 -_call_tzinfo_method [bound][private][function][def][read][called][node=FunctionDef]
214.20 -_check_date_fields [bound][private][function][def][read][called][node=FunctionDef]
214.21 -_check_time_fields [bound][private][function][def][read][called][node=FunctionDef]
214.22 -_check_tzinfo_arg [bound][private][function][def][read][called][node=FunctionDef]
214.23 -_check_tzname [bound][private][function][def][read][called][node=FunctionDef]
214.24 -_check_utc_offset [bound][private][function][def][read][called][node=FunctionDef]
214.25 -_cmperror [bound][private][function][def][read][called][node=FunctionDef]
214.26 -_date_class [bound][private][class][read][alias][node=ClassDef]
214.27 -_days_before_month [bound][private][function][def][read][called][node=FunctionDef]
214.28 -_days_before_year [bound][private][function][def][read][called][node=FunctionDef]
214.29 -_days_in_month [bound][private][function][def][read][called][node=FunctionDef]
214.30 -_days_in_year [bound][private][function][def][node=FunctionDef]
214.31 -_format_time [bound][private][function][def][read][called][node=FunctionDef]
214.32 -_is_leap [bound][private][function][def][read][called][node=FunctionDef]
214.33 -_isoweek1monday [bound][private][function][def][node=FunctionDef]
214.34 -_math [bound][imported][private][data][read][node=Import]
214.35 -_ord2ymd [bound][private][function][def][read][called][node=FunctionDef]
214.36 -_test [bound][private][function][def][read][called][node=FunctionDef]
214.37 -_time [bound][imported][private][data][read][node=Import]
214.38 -_time_class [bound][private][class][read][alias][node=ClassDef]
214.39 -_tzinfo_class [bound][private][class][alias][node=ClassDef]
214.40 -_wrap_strftime [bound][private][function][def][read][called][node=FunctionDef]
214.41 -_ymd2ord [bound][private][function][def][read][called][node=FunctionDef]
214.42 -date [bound][class][def][read][called][node=ClassDef]
214.43 -datetime [bound][class][def][read][called][node=ClassDef]
214.44 -dbm [bound][data][read][node=Name]
214.45 -dim [bound][data][read][node=Name]
214.46 -object [read][UNRESOLVED][node=Name]
214.47 -time [bound][class][def][read][called][node=ClassDef]
214.48 -timedelta [bound][class][def][read][called][node=ClassDef]
214.49 -tmxxx [bound][class][def][read][called][node=ClassDef]
214.50 -tzinfo [bound][class][def][read][node=ClassDef]
214.51 -
214.52 - =============================================
214.53 - _is_leap: FunctionDef : OffsetRange[1313,1438>
214.54 - year [bound][param][data][read][node=Name]
214.55 -
214.56 - =============================================
214.57 - _days_in_year: FunctionDef : OffsetRange[1438,1565>
214.58 - _is_leap [free][read][called][node=Name]
214.59 - year [bound][param][data][read][node=Name]
214.60 -
214.61 - =============================================
214.62 - _days_before_year: FunctionDef : OffsetRange[1565,1711>
214.63 - y [bound][data][read][node=Name]
214.64 - year [bound][param][data][read][node=Name]
214.65 -
214.66 - =============================================
214.67 - _days_in_month: FunctionDef : OffsetRange[1711,1933>
214.68 - _DAYS_IN_MONTH [free][read][node=Name]
214.69 - _is_leap [free][read][called][node=Name]
214.70 - month [bound][param][data][read][node=Name]
214.71 - year [bound][param][data][read][node=Name]
214.72 -
214.73 - =============================================
214.74 - _days_before_month: FunctionDef : OffsetRange[1933,2203>
214.75 - ValueError [free][read][called][node=Name]
214.76 - _DAYS_BEFORE_MONTH [free][read][node=Name]
214.77 - _is_leap [free][read][called][node=Name]
214.78 - month [bound][param][data][read][node=Name]
214.79 - year [bound][param][data][read][node=Name]
214.80 -
214.81 - =============================================
214.82 - _ymd2ord: FunctionDef : OffsetRange[2203,2619>
214.83 - ValueError [free][read][called][node=Name]
214.84 - _days_before_month [free][read][called][node=Name]
214.85 - _days_before_year [free][read][called][node=Name]
214.86 - _days_in_month [free][read][called][node=Name]
214.87 - day [bound][param][data][read][node=Name]
214.88 - dim [bound][data][read][node=Name]
214.89 - month [bound][param][data][read][node=Name]
214.90 - year [bound][param][data][read][node=Name]
214.91 -
214.92 - =============================================
214.93 - _ord2ymd: FunctionDef : OffsetRange[3228,6007>
214.94 - _DAYS_BEFORE_MONTH [free][read][node=Name]
214.95 - _DAYS_IN_MONTH [free][read][node=Name]
214.96 - _DI100Y [free][read][node=Name]
214.97 - _DI400Y [free][read][node=Name]
214.98 - _DI4Y [free][read][node=Name]
214.99 - _days_in_month [free][read][called][node=Name]
214.100 - _is_leap [free][read][called][node=Name]
214.101 - divmod [free][read][called][node=Name]
214.102 - leapyear [bound][data][read][node=Name]
214.103 - month [bound][data][read][node=Name]
214.104 - n [bound][param][data][read][node=Name]
214.105 - n1 [bound][data][read][node=Name]
214.106 - n100 [bound][data][read][node=Name]
214.107 - n4 [bound][data][read][node=Name]
214.108 - n400 [bound][data][read][node=Name]
214.109 - preceding [bound][data][read][node=Name]
214.110 - year [bound][data][read][node=Name]
214.111 -
214.112 - =============================================
214.113 - _build_struct_time: FunctionDef : OffsetRange[6203,6410>
214.114 - _days_before_month [free][read][called][node=Name]
214.115 - _time [free][read][node=Name]
214.116 - _ymd2ord [free][read][called][node=Name]
214.117 - d [bound][param][data][read][node=Name]
214.118 - dnum [bound][data][read][node=Name]
214.119 - dstflag [bound][param][data][read][node=Name]
214.120 - hh [bound][param][data][read][node=Name]
214.121 - m [bound][param][data][read][node=Name]
214.122 - mm [bound][param][data][read][node=Name]
214.123 - ss [bound][param][data][read][node=Name]
214.124 - wday [bound][data][read][node=Name]
214.125 - y [bound][param][data][read][node=Name]
214.126 -
214.127 - =============================================
214.128 - _format_time: FunctionDef : OffsetRange[6410,6661>
214.129 - hh [bound][param][data][read][node=Name]
214.130 - mm [bound][param][data][read][node=Name]
214.131 - result [bound][data][read][node=Name]
214.132 - ss [bound][param][data][read][node=Name]
214.133 - us [bound][param][data][read][node=Name]
214.134 -
214.135 - =============================================
214.136 - _wrap_strftime: FunctionDef : OffsetRange[6661,8721>
214.137 - None [free][read][node=Name]
214.138 - ValueError [free][read][called][node=Name]
214.139 - Zreplace [bound][data][read][node=Name]
214.140 - _time [free][read][node=Name]
214.141 - ch [bound][data][read][node=Name]
214.142 - divmod [free][read][called][node=Name]
214.143 - format [bound][param][data][read][node=Name]
214.144 - h [bound][data][read][node=Name]
214.145 - hasattr [free][read][called][node=Name]
214.146 - i [bound][data][read][node=Name]
214.147 - len [free][read][called][node=Name]
214.148 - m [bound][data][read][node=Name]
214.149 - n [bound][data][read][node=Name]
214.150 - newformat [bound][data][read][node=Name]
214.151 - object [bound][param][data][read][node=Name]
214.152 - offset [bound][data][read][node=Name]
214.153 - push [bound][data][read][called][node=Name]
214.154 - s [bound][data][read][node=Name]
214.155 - sign [bound][data][read][node=Name]
214.156 - timetuple [bound][param][data][read][node=Name]
214.157 - year [bound][data][read][node=Name]
214.158 - zreplace [bound][data][read][node=Name]
214.159 -
214.160 - =============================================
214.161 - _call_tzinfo_method: FunctionDef : OffsetRange[8721,8925>
214.162 - None [free][read][node=Name]
214.163 - getattr [free][read][called][node=Name]
214.164 - methname [bound][param][data][read][node=Name]
214.165 - tzinfo [bound][param][data][read][node=Name]
214.166 - tzinfoarg [bound][param][data][read][node=Name]
214.167 -
214.168 - =============================================
214.169 - _check_tzname: FunctionDef : OffsetRange[8925,9449>
214.170 - None [free][read][node=Name]
214.171 - TypeError [free][read][called][node=Name]
214.172 - isinstance [free][read][called][node=Name]
214.173 - name [bound][param][data][read][node=Name]
214.174 - str [free][read][node=Name]
214.175 - type [free][read][called][node=Name]
214.176 -
214.177 - =============================================
214.178 - _check_utc_offset: FunctionDef : OffsetRange[9449,10259>
214.179 - None [free][read][node=Name]
214.180 - TypeError [free][read][called][node=Name]
214.181 - ValueError [free][read][called][node=Name]
214.182 - days [bound][data][read][node=Name]
214.183 - divmod [free][read][called][node=Name]
214.184 - isinstance [free][read][called][node=Name]
214.185 - minutes [bound][data][read][node=Name]
214.186 - name [bound][param][data][read][node=Name]
214.187 - offset [bound][param][data][read][node=Name]
214.188 - seconds [bound][data][read][node=Name]
214.189 - timedelta [free][read][node=Name]
214.190 - type [free][read][called][node=Name]
214.191 -
214.192 - =============================================
214.193 - _check_date_fields: FunctionDef : OffsetRange[10259,10632>
214.194 - MAXYEAR [free][read][node=Name]
214.195 - MINYEAR [free][read][node=Name]
214.196 - ValueError [free][read][called][node=Name]
214.197 - _days_in_month [free][read][called][node=Name]
214.198 - day [bound][param][data][read][node=Name]
214.199 - dim [bound][data][read][node=Name]
214.200 - month [bound][param][data][read][node=Name]
214.201 - year [bound][param][data][read][node=Name]
214.202 -
214.203 - =============================================
214.204 - _check_time_fields: FunctionDef : OffsetRange[10632,11069>
214.205 - ValueError [free][read][called][node=Name]
214.206 - hour [bound][param][data][read][node=Name]
214.207 - microsecond [bound][param][data][read][node=Name]
214.208 - minute [bound][param][data][read][node=Name]
214.209 - second [bound][param][data][read][node=Name]
214.210 -
214.211 - =============================================
214.212 - _check_tzinfo_arg: FunctionDef : OffsetRange[11069,12221>
214.213 - None [free][read][node=Name]
214.214 - TypeError [free][read][called][node=Name]
214.215 - isinstance [free][read][called][node=Name]
214.216 - tz [bound][param][data][read][node=Name]
214.217 - tzinfo [free][read][node=Name]
214.218 -
214.219 - =============================================
214.220 - _cmperror: FunctionDef : OffsetRange[12221,12741>
214.221 - TypeError [free][read][called][node=Name]
214.222 - type [free][read][called][node=Name]
214.223 - x [bound][param][data][read][node=Name]
214.224 - y [bound][param][data][read][node=Name]
214.225 -
214.226 - =============================================
214.227 - class tmxxx: ClassDef : OffsetRange[12804,16258>
214.228 - None [free][read][node=Name]
214.229 - __init__ [bound][function][def][node=FunctionDef]
214.230 - ctime [bound][function][def][node=FunctionDef]
214.231 - ordinal [bound][data][node=Name]
214.232 - time [bound][function][def][node=FunctionDef]
214.233 - toordinal [bound][function][def][node=FunctionDef]
214.234 - ------ Attributes ---------------------------------------
214.235 - day : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.236 - hour : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.237 - microsecond : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.238 - minute : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.239 - month : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.240 - ordinal : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.241 - second : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.242 - year : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.243 -
214.244 - =============================================
214.245 - __init__: FunctionDef : OffsetRange[12842,15307>
214.246 - _days_in_month [free][read][called][node=Name]
214.247 - _ord2ymd [free][read][called][node=Name]
214.248 - _ymd2ord [free][read][called][node=Name]
214.249 - carry [bound][data][read][node=Name]
214.250 - day [bound][param][data][read][node=Name]
214.251 - dim [bound][data][read][node=Name]
214.252 - divmod [free][read][called][node=Name]
214.253 - hour [bound][param][data][read][node=Name]
214.254 - microsecond [bound][param][data][read][node=Name]
214.255 - minute [bound][param][data][read][node=Name]
214.256 - month [bound][param][data][read][node=Name]
214.257 - second [bound][param][data][read][node=Name]
214.258 - self [bound][param][data][read][node=Name]
214.259 - year [bound][param][data][read][node=Name]
214.260 - ------ Attributes ---------------------------------------
214.261 - ordinal : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.262 -
214.263 - =============================================
214.264 - toordinal: FunctionDef : OffsetRange[15308,15660>
214.265 - None [free][read][node=Name]
214.266 - _ymd2ord [free][read][called][node=Name]
214.267 - self [bound][param][data][read][node=Name]
214.268 - ------ Attributes ---------------------------------------
214.269 - day : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.270 - month : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.271 - ordinal : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.272 - year : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.273 -
214.274 - =============================================
214.275 - time: FunctionDef : OffsetRange[15661,15942>
214.276 - _ORD1970 [free][read][node=Name]
214.277 - days [bound][data][read][node=Name]
214.278 - seconds [bound][data][read][node=Name]
214.279 - self [bound][param][data][read][node=Name]
214.280 - ------ Attributes ---------------------------------------
214.281 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.282 - microsecond : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.283 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.284 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.285 - toordinal : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
214.286 -
214.287 - =============================================
214.288 - ctime: FunctionDef : OffsetRange[15943,16258>
214.289 - _DAYNAMES [free][read][node=Name]
214.290 - _MONTHNAMES [free][read][node=Name]
214.291 - self [bound][param][data][read][node=Name]
214.292 - weekday [bound][data][read][node=Name]
214.293 - ------ Attributes ---------------------------------------
214.294 - day : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.295 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.296 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.297 - month : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.298 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.299 - toordinal : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
214.300 - year : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.301 -
214.302 - =============================================
214.303 - class timedelta: ClassDef : OffsetRange[16258,25637>
214.304 - True [free][read][node=Name]
214.305 - __abs__ [bound][function][def][node=FunctionDef]
214.306 - __add__ [bound][function][def][read][node=FunctionDef]
214.307 - __cmp [bound][private][function][def][node=FunctionDef]
214.308 - __div__ [bound][function][def][read][node=FunctionDef]
214.309 - __eq__ [bound][function][def][node=FunctionDef]
214.310 - __floordiv__ [bound][function][alias][node=FunctionDef]
214.311 - __ge__ [bound][function][def][node=FunctionDef]
214.312 - __getstate [bound][private][function][def][node=FunctionDef]
214.313 - __gt__ [bound][function][def][node=FunctionDef]
214.314 - __hash__ [bound][function][def][node=FunctionDef]
214.315 - __le__ [bound][function][def][node=FunctionDef]
214.316 - __lt__ [bound][function][def][node=FunctionDef]
214.317 - __mul__ [bound][function][def][read][node=FunctionDef]
214.318 - __ne__ [bound][function][def][node=FunctionDef]
214.319 - __neg__ [bound][function][def][node=FunctionDef]
214.320 - __new__ [bound][function][def][node=FunctionDef]
214.321 - __nonzero__ [bound][function][def][node=FunctionDef]
214.322 - __pos__ [bound][function][def][node=FunctionDef]
214.323 - __radd__ [bound][function][alias][node=FunctionDef]
214.324 - __reduce__ [bound][function][def][node=FunctionDef]
214.325 - __repr__ [bound][function][def][node=FunctionDef]
214.326 - __rmul__ [bound][function][alias][node=FunctionDef]
214.327 - __rsub__ [bound][function][def][node=FunctionDef]
214.328 - __safe_for_unpickling__ [bound][data][node=Name]
214.329 - __str__ [bound][function][def][node=FunctionDef]
214.330 - __sub__ [bound][function][def][node=FunctionDef]
214.331 - days [bound][data][node=Name]
214.332 - microseconds [bound][data][node=Name]
214.333 - property [free][read][called][node=Name]
214.334 - seconds [bound][data][node=Name]
214.335 - ------ Attributes ---------------------------------------
214.336 - __days : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.337 - __microseconds : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.338 - __seconds : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.339 -
214.340 - =============================================
214.341 - __new__: FunctionDef : OffsetRange[16773,21337>
214.342 - OverflowError [free][read][called][node=Name]
214.343 - _math [free][read][node=Name]
214.344 - abs [free][read][called][node=Name]
214.345 - cls [bound][param][data][read][node=Name]
214.346 - d [bound][data][read][node=Name]
214.347 - dayfrac [bound][data][read][node=Name]
214.348 - days [bound][param][data][read][node=Name]
214.349 - daysecondsfrac [bound][data][read][node=Name]
214.350 - daysecondswhole [bound][data][read][node=Name]
214.351 - divmod [free][read][called][node=Name]
214.352 - float [free][read][called][node=Name]
214.353 - hours [bound][param][data][read][node=Name]
214.354 - int [free][read][called][node=Name]
214.355 - isinstance [free][read][called][node=Name]
214.356 - long [free][read][called][node=Name]
214.357 - microseconds [bound][param][data][read][node=Name]
214.358 - milliseconds [bound][param][data][read][node=Name]
214.359 - minutes [bound][param][data][read][node=Name]
214.360 - object [free][read][node=Name]
214.361 - round [free][read][called][node=Name]
214.362 - s [bound][data][read][node=Name]
214.363 - seconds [bound][param][data][read][node=Name]
214.364 - secondsfrac [bound][data][read][node=Name]
214.365 - self [bound][data][read][node=Name]
214.366 - us [bound][data][read][node=Name]
214.367 - usdouble [bound][data][read][node=Name]
214.368 - weeks [bound][param][data][read][node=Name]
214.369 - ------ Attributes ---------------------------------------
214.370 - __new__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
214.371 -
214.372 - =============================================
214.373 - __repr__: FunctionDef : OffsetRange[21338,21918>
214.374 - self [bound][param][data][read][node=Name]
214.375 - ------ Attributes ---------------------------------------
214.376 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.377 - __days : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.378 - __microseconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.379 - __seconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.380 -
214.381 - =============================================
214.382 - __str__: FunctionDef : OffsetRange[21919,22319>
214.383 - abs [free][node=null]
214.384 - divmod [free][read][called][node=Name]
214.385 - hh [bound][data][read][node=Name]
214.386 - mm [bound][data][read][node=Name]
214.387 - plural [bound][function][def][read][called][node=FunctionDef]
214.388 - s [bound][data][read][node=Name]
214.389 - self [bound][param][data][read][node=Name]
214.390 - ss [bound][data][read][node=Name]
214.391 - ---------------------------------------------
214.392 - inner_free: {abs=PRESENT}
214.393 - ------ Attributes ---------------------------------------
214.394 - __days : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.395 - __microseconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.396 - __seconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.397 -
214.398 - =============================================
214.399 - plural: FunctionDef : OffsetRange[22092,22170>
214.400 - abs [free][read][called][node=Name]
214.401 - n [bound][param][data][read][node=Name]
214.402 -
214.403 - =============================================
214.404 - <lambda>: Lambda : OffsetRange[22336,22360>
214.405 - self [bound][param][data][read][node=Name]
214.406 -
214.407 - =============================================
214.408 - <lambda>: Lambda : OffsetRange[22397,22424>
214.409 - self [bound][param][data][read][node=Name]
214.410 -
214.411 - =============================================
214.412 - <lambda>: Lambda : OffsetRange[22469,22501>
214.413 - self [bound][param][data][read][node=Name]
214.414 -
214.415 - =============================================
214.416 - __add__: FunctionDef : OffsetRange[22556,22850>
214.417 - NotImplemented [free][read][node=Name]
214.418 - isinstance [free][read][called][node=Name]
214.419 - other [bound][param][data][read][node=Name]
214.420 - self [bound][param][data][read][node=Name]
214.421 - timedelta [free][read][called][node=Name]
214.422 - ------ Attributes ---------------------------------------
214.423 - __days : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.424 - __microseconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.425 - __seconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.426 -
214.427 - =============================================
214.428 - __sub__: FunctionDef : OffsetRange[22875,23009>
214.429 - NotImplemented [free][read][node=Name]
214.430 - isinstance [free][read][called][node=Name]
214.431 - other [bound][param][data][read][node=Name]
214.432 - self [bound][param][data][read][node=Name]
214.433 - timedelta [free][read][node=Name]
214.434 -
214.435 - =============================================
214.436 - __rsub__: FunctionDef : OffsetRange[23010,23145>
214.437 - NotImplemented [free][read][node=Name]
214.438 - isinstance [free][read][called][node=Name]
214.439 - other [bound][param][data][read][node=Name]
214.440 - self [bound][param][data][read][node=Name]
214.441 - timedelta [free][read][node=Name]
214.442 -
214.443 - =============================================
214.444 - __neg__: FunctionDef : OffsetRange[23146,23312>
214.445 - self [bound][param][data][read][node=Name]
214.446 - ------ Attributes ---------------------------------------
214.447 - __class__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
214.448 - __days : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.449 - __microseconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.450 - __seconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.451 -
214.452 - =============================================
214.453 - __pos__: FunctionDef : OffsetRange[23313,23356>
214.454 - self [bound][param][data][read][node=Name]
214.455 -
214.456 - =============================================
214.457 - __abs__: FunctionDef : OffsetRange[23357,23471>
214.458 - self [bound][param][data][read][node=Name]
214.459 - ------ Attributes ---------------------------------------
214.460 - __days : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.461 -
214.462 - =============================================
214.463 - __mul__: FunctionDef : OffsetRange[23472,23751>
214.464 - NotImplemented [free][read][node=Name]
214.465 - int [free][read][node=Name]
214.466 - isinstance [free][read][called][node=Name]
214.467 - long [free][read][node=Name]
214.468 - other [bound][param][data][read][node=Name]
214.469 - self [bound][param][data][read][node=Name]
214.470 - ------ Attributes ---------------------------------------
214.471 - __class__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
214.472 - __days : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.473 - __microseconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.474 - __seconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.475 -
214.476 - =============================================
214.477 - __div__: FunctionDef : OffsetRange[23776,24051>
214.478 - NotImplemented [free][read][node=Name]
214.479 - int [free][read][node=Name]
214.480 - isinstance [free][read][called][node=Name]
214.481 - long [free][read][node=Name]
214.482 - other [bound][param][data][read][node=Name]
214.483 - self [bound][param][data][read][node=Name]
214.484 - usec [bound][data][read][node=Name]
214.485 - ------ Attributes ---------------------------------------
214.486 - __class__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
214.487 - __days : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.488 - __microseconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.489 - __seconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.490 -
214.491 - =============================================
214.492 - __eq__: FunctionDef : OffsetRange[24100,24251>
214.493 - False [free][read][node=Name]
214.494 - isinstance [free][read][called][node=Name]
214.495 - other [bound][param][data][read][node=Name]
214.496 - self [bound][param][data][read][node=Name]
214.497 - timedelta [free][read][node=Name]
214.498 - ------ Attributes ---------------------------------------
214.499 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.500 -
214.501 - =============================================
214.502 - __ne__: FunctionDef : OffsetRange[24252,24402>
214.503 - True [free][read][node=Name]
214.504 - isinstance [free][read][called][node=Name]
214.505 - other [bound][param][data][read][node=Name]
214.506 - self [bound][param][data][read][node=Name]
214.507 - timedelta [free][read][node=Name]
214.508 - ------ Attributes ---------------------------------------
214.509 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.510 -
214.511 - =============================================
214.512 - __le__: FunctionDef : OffsetRange[24403,24564>
214.513 - _cmperror [free][read][called][node=Name]
214.514 - isinstance [free][read][called][node=Name]
214.515 - other [bound][param][data][read][node=Name]
214.516 - self [bound][param][data][read][node=Name]
214.517 - timedelta [free][read][node=Name]
214.518 - ------ Attributes ---------------------------------------
214.519 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.520 -
214.521 - =============================================
214.522 - __lt__: FunctionDef : OffsetRange[24565,24725>
214.523 - _cmperror [free][read][called][node=Name]
214.524 - isinstance [free][read][called][node=Name]
214.525 - other [bound][param][data][read][node=Name]
214.526 - self [bound][param][data][read][node=Name]
214.527 - timedelta [free][read][node=Name]
214.528 - ------ Attributes ---------------------------------------
214.529 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.530 -
214.531 - =============================================
214.532 - __ge__: FunctionDef : OffsetRange[24726,24887>
214.533 - _cmperror [free][read][called][node=Name]
214.534 - isinstance [free][read][called][node=Name]
214.535 - other [bound][param][data][read][node=Name]
214.536 - self [bound][param][data][read][node=Name]
214.537 - timedelta [free][read][node=Name]
214.538 - ------ Attributes ---------------------------------------
214.539 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.540 -
214.541 - =============================================
214.542 - __gt__: FunctionDef : OffsetRange[24888,25048>
214.543 - _cmperror [free][read][called][node=Name]
214.544 - isinstance [free][read][called][node=Name]
214.545 - other [bound][param][data][read][node=Name]
214.546 - self [bound][param][data][read][node=Name]
214.547 - timedelta [free][read][node=Name]
214.548 - ------ Attributes ---------------------------------------
214.549 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.550 -
214.551 - =============================================
214.552 - __cmp: FunctionDef : OffsetRange[25049,25179>
214.553 - cmp [free][read][called][node=Name]
214.554 - isinstance [free][read][called][node=Name]
214.555 - other [bound][param][data][read][node=Name]
214.556 - self [bound][param][data][read][node=Name]
214.557 - timedelta [free][read][node=Name]
214.558 - ------ Attributes ---------------------------------------
214.559 - __getstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.560 -
214.561 - =============================================
214.562 - __hash__: FunctionDef : OffsetRange[25180,25243>
214.563 - hash [free][read][called][node=Name]
214.564 - self [bound][param][data][read][node=Name]
214.565 - ------ Attributes ---------------------------------------
214.566 - __getstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.567 -
214.568 - =============================================
214.569 - __nonzero__: FunctionDef : OffsetRange[25244,25411>
214.570 - self [bound][param][data][read][node=Name]
214.571 - ------ Attributes ---------------------------------------
214.572 - __days : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.573 - __microseconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.574 - __seconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.575 -
214.576 - =============================================
214.577 - __getstate: FunctionDef : OffsetRange[25470,25562>
214.578 - self [bound][param][data][read][node=Name]
214.579 - ------ Attributes ---------------------------------------
214.580 - __days : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.581 - __microseconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.582 - __seconds : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.583 -
214.584 - =============================================
214.585 - __reduce__: FunctionDef : OffsetRange[25563,25637>
214.586 - self [bound][param][data][read][node=Name]
214.587 - ------ Attributes ---------------------------------------
214.588 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.589 - __getstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.590 -
214.591 - =============================================
214.592 - class date: ClassDef : OffsetRange[25848,34505>
214.593 - MAXYEAR [free][read][node=Name]
214.594 - MINYEAR [free][read][node=Name]
214.595 - None [free][read][node=Name]
214.596 - True [free][read][node=Name]
214.597 - __add__ [bound][function][def][read][node=FunctionDef]
214.598 - __cmp [bound][private][function][def][node=FunctionDef]
214.599 - __eq__ [bound][function][def][node=FunctionDef]
214.600 - __ge__ [bound][function][def][node=FunctionDef]
214.601 - __getstate [bound][private][function][def][node=FunctionDef]
214.602 - __gt__ [bound][function][def][node=FunctionDef]
214.603 - __hash__ [bound][function][def][node=FunctionDef]
214.604 - __le__ [bound][function][def][node=FunctionDef]
214.605 - __lt__ [bound][function][def][node=FunctionDef]
214.606 - __ne__ [bound][function][def][node=FunctionDef]
214.607 - __new__ [bound][function][def][node=FunctionDef]
214.608 - __radd__ [bound][function][alias][node=FunctionDef]
214.609 - __reduce__ [bound][function][def][node=FunctionDef]
214.610 - __repr__ [bound][function][def][node=FunctionDef]
214.611 - __safe_for_unpickling__ [bound][data][node=Name]
214.612 - __setstate [bound][private][function][def][node=FunctionDef]
214.613 - __str__ [bound][function][alias][node=FunctionDef]
214.614 - __sub__ [bound][function][def][node=FunctionDef]
214.615 - _checkOverflow [bound][private][function][def][node=FunctionDef]
214.616 - classmethod [free][read][called][node=Name]
214.617 - ctime [bound][function][def][node=FunctionDef]
214.618 - day [bound][data][node=Name]
214.619 - fromordinal [bound][function][def][read][node=FunctionDef]
214.620 - fromtimestamp [bound][function][def][read][node=FunctionDef]
214.621 - isocalendar [bound][function][def][node=FunctionDef]
214.622 - isoformat [bound][function][def][read][node=FunctionDef]
214.623 - isoweekday [bound][function][def][node=FunctionDef]
214.624 - month [bound][data][node=Name]
214.625 - property [free][read][called][node=Name]
214.626 - replace [bound][function][def][node=FunctionDef]
214.627 - strftime [bound][function][def][node=FunctionDef]
214.628 - timetuple [bound][function][def][node=FunctionDef]
214.629 - today [bound][function][def][read][node=FunctionDef]
214.630 - toordinal [bound][function][def][node=FunctionDef]
214.631 - weekday [bound][function][def][node=FunctionDef]
214.632 - year [bound][data][node=Name]
214.633 - ------ Attributes ---------------------------------------
214.634 - __day : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.635 - __month : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.636 - __year : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.637 -
214.638 - =============================================
214.639 - __new__: FunctionDef : OffsetRange[26301,26827>
214.640 - _check_date_fields [free][read][called][node=Name]
214.641 - cls [bound][param][data][read][node=Name]
214.642 - day [bound][param][data][read][node=Name]
214.643 - isinstance [free][read][called][node=Name]
214.644 - month [bound][param][data][read][node=Name]
214.645 - object [free][read][node=Name]
214.646 - self [bound][data][read][node=Name]
214.647 - str [free][read][node=Name]
214.648 - year [bound][param][data][read][node=Name]
214.649 - ------ Attributes ---------------------------------------
214.650 - __new__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
214.651 - __setstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.652 -
214.653 - =============================================
214.654 - fromtimestamp: FunctionDef : OffsetRange[26828,27025>
214.655 - _time [free][read][node=Name]
214.656 - cls [bound][param][data][read][called][node=Name]
214.657 - d [bound][data][read][node=Name]
214.658 - dst [bound][data][unused][node=Name]
214.659 - hh [bound][data][unused][node=Name]
214.660 - jday [bound][data][unused][node=Name]
214.661 - m [bound][data][read][node=Name]
214.662 - mm [bound][data][unused][node=Name]
214.663 - ss [bound][data][unused][node=Name]
214.664 - t [bound][param][data][read][node=Name]
214.665 - weekday [bound][data][unused][node=Name]
214.666 - y [bound][data][read][node=Name]
214.667 -
214.668 - =============================================
214.669 - today: FunctionDef : OffsetRange[27074,27199>
214.670 - _time [free][read][node=Name]
214.671 - cls [bound][param][data][read][node=Name]
214.672 - t [bound][data][read][node=Name]
214.673 -
214.674 - =============================================
214.675 - fromordinal: FunctionDef : OffsetRange[27232,27498>
214.676 - _ord2ymd [free][read][called][node=Name]
214.677 - cls [bound][param][data][read][called][node=Name]
214.678 - d [bound][data][read][node=Name]
214.679 - m [bound][data][read][node=Name]
214.680 - n [bound][param][data][read][node=Name]
214.681 - y [bound][data][read][node=Name]
214.682 -
214.683 - =============================================
214.684 - __repr__: FunctionDef : OffsetRange[27572,28116>
214.685 - self [bound][param][data][read][node=Name]
214.686 - ------ Attributes ---------------------------------------
214.687 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.688 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.689 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.690 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.691 -
214.692 - =============================================
214.693 - ctime: FunctionDef : OffsetRange[28117,28237>
214.694 - self [bound][param][data][read][node=Name]
214.695 - tmxxx [free][read][called][node=Name]
214.696 - ------ Attributes ---------------------------------------
214.697 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.698 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.699 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.700 -
214.701 - =============================================
214.702 - strftime: FunctionDef : OffsetRange[28238,28361>
214.703 - _wrap_strftime [free][read][called][node=Name]
214.704 - fmt [bound][param][data][read][node=Name]
214.705 - self [bound][param][data][read][node=Name]
214.706 - ------ Attributes ---------------------------------------
214.707 - timetuple : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
214.708 -
214.709 - =============================================
214.710 - isoformat: FunctionDef : OffsetRange[28362,28680>
214.711 - self [bound][param][data][read][node=Name]
214.712 - ------ Attributes ---------------------------------------
214.713 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.714 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.715 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.716 -
214.717 - =============================================
214.718 - <lambda>: Lambda : OffsetRange[28754,28778>
214.719 - self [bound][param][data][read][node=Name]
214.720 -
214.721 - =============================================
214.722 - <lambda>: Lambda : OffsetRange[28862,28887>
214.723 - self [bound][param][data][read][node=Name]
214.724 -
214.725 - =============================================
214.726 - <lambda>: Lambda : OffsetRange[28928,28951>
214.727 - self [bound][param][data][read][node=Name]
214.728 -
214.729 - =============================================
214.730 - timetuple: FunctionDef : OffsetRange[29037,29250>
214.731 - _build_struct_time [free][read][called][node=Name]
214.732 - self [bound][param][data][read][node=Name]
214.733 - ------ Attributes ---------------------------------------
214.734 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.735 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.736 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.737 -
214.738 - =============================================
214.739 - toordinal: FunctionDef : OffsetRange[29251,29536>
214.740 - _ymd2ord [free][read][called][node=Name]
214.741 - self [bound][param][data][read][node=Name]
214.742 - ------ Attributes ---------------------------------------
214.743 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.744 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.745 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.746 -
214.747 - =============================================
214.748 - replace: FunctionDef : OffsetRange[29537,29938>
214.749 - None [free][read][node=Name]
214.750 - _check_date_fields [free][read][called][node=Name]
214.751 - date [free][read][called][node=Name]
214.752 - day [bound][param][data][read][node=Name]
214.753 - month [bound][param][data][read][node=Name]
214.754 - self [bound][param][data][read][node=Name]
214.755 - year [bound][param][data][read][node=Name]
214.756 - ------ Attributes ---------------------------------------
214.757 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.758 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.759 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.760 -
214.761 - =============================================
214.762 - __eq__: FunctionDef : OffsetRange[29939,30161>
214.763 - False [free][read][node=Name]
214.764 - NotImplemented [free][read][node=Name]
214.765 - date [free][read][node=Name]
214.766 - hasattr [free][read][called][node=Name]
214.767 - isinstance [free][read][called][node=Name]
214.768 - other [bound][param][data][read][node=Name]
214.769 - self [bound][param][data][read][node=Name]
214.770 - ------ Attributes ---------------------------------------
214.771 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.772 -
214.773 - =============================================
214.774 - __ne__: FunctionDef : OffsetRange[30162,30383>
214.775 - NotImplemented [free][read][node=Name]
214.776 - True [free][read][node=Name]
214.777 - date [free][read][node=Name]
214.778 - hasattr [free][read][called][node=Name]
214.779 - isinstance [free][read][called][node=Name]
214.780 - other [bound][param][data][read][node=Name]
214.781 - self [bound][param][data][read][node=Name]
214.782 - ------ Attributes ---------------------------------------
214.783 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.784 -
214.785 - =============================================
214.786 - __le__: FunctionDef : OffsetRange[30384,30616>
214.787 - NotImplemented [free][read][node=Name]
214.788 - _cmperror [free][read][called][node=Name]
214.789 - date [free][read][node=Name]
214.790 - hasattr [free][read][called][node=Name]
214.791 - isinstance [free][read][called][node=Name]
214.792 - other [bound][param][data][read][node=Name]
214.793 - self [bound][param][data][read][node=Name]
214.794 - ------ Attributes ---------------------------------------
214.795 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.796 -
214.797 - =============================================
214.798 - __lt__: FunctionDef : OffsetRange[30617,30848>
214.799 - NotImplemented [free][read][node=Name]
214.800 - _cmperror [free][read][called][node=Name]
214.801 - date [free][read][node=Name]
214.802 - hasattr [free][read][called][node=Name]
214.803 - isinstance [free][read][called][node=Name]
214.804 - other [bound][param][data][read][node=Name]
214.805 - self [bound][param][data][read][node=Name]
214.806 - ------ Attributes ---------------------------------------
214.807 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.808 -
214.809 - =============================================
214.810 - __ge__: FunctionDef : OffsetRange[30849,31081>
214.811 - NotImplemented [free][read][node=Name]
214.812 - _cmperror [free][read][called][node=Name]
214.813 - date [free][read][node=Name]
214.814 - hasattr [free][read][called][node=Name]
214.815 - isinstance [free][read][called][node=Name]
214.816 - other [bound][param][data][read][node=Name]
214.817 - self [bound][param][data][read][node=Name]
214.818 - ------ Attributes ---------------------------------------
214.819 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.820 -
214.821 - =============================================
214.822 - __gt__: FunctionDef : OffsetRange[31082,31313>
214.823 - NotImplemented [free][read][node=Name]
214.824 - _cmperror [free][read][called][node=Name]
214.825 - date [free][read][node=Name]
214.826 - hasattr [free][read][called][node=Name]
214.827 - isinstance [free][read][called][node=Name]
214.828 - other [bound][param][data][read][node=Name]
214.829 - self [bound][param][data][read][node=Name]
214.830 - ------ Attributes ---------------------------------------
214.831 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.832 -
214.833 - =============================================
214.834 - __cmp: FunctionDef : OffsetRange[31314,31543>
214.835 - cmp [free][read][called][node=Name]
214.836 - d [bound][data][read][node=Name]
214.837 - d2 [bound][data][read][node=Name]
214.838 - date [free][read][node=Name]
214.839 - isinstance [free][read][called][node=Name]
214.840 - m [bound][data][read][node=Name]
214.841 - m2 [bound][data][read][node=Name]
214.842 - other [bound][param][data][read][node=Name]
214.843 - self [bound][param][data][read][node=Name]
214.844 - y [bound][data][read][node=Name]
214.845 - y2 [bound][data][read][node=Name]
214.846 - ------ Attributes ---------------------------------------
214.847 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.848 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.849 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.850 -
214.851 - =============================================
214.852 - __hash__: FunctionDef : OffsetRange[31544,31643>
214.853 - hash [free][read][called][node=Name]
214.854 - self [bound][param][data][read][node=Name]
214.855 - ------ Attributes ---------------------------------------
214.856 - __getstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.857 -
214.858 - =============================================
214.859 - _checkOverflow: FunctionDef : OffsetRange[31644,31856>
214.860 - MAXYEAR [free][read][node=Name]
214.861 - MINYEAR [free][read][node=Name]
214.862 - OverflowError [free][read][called][node=Name]
214.863 - self [bound][param][data][unused][node=Name]
214.864 - year [bound][param][data][read][node=Name]
214.865 -
214.866 - =============================================
214.867 - __add__: FunctionDef : OffsetRange[31857,32239>
214.868 - NotImplemented [free][read][node=Name]
214.869 - isinstance [free][read][called][node=Name]
214.870 - other [bound][param][data][read][node=Name]
214.871 - result [bound][data][read][node=Name]
214.872 - self [bound][param][data][read][node=Name]
214.873 - t [bound][data][read][node=Name]
214.874 - timedelta [free][read][node=Name]
214.875 - tmxxx [free][read][called][node=Name]
214.876 - ------ Attributes ---------------------------------------
214.877 - __class__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
214.878 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.879 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.880 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.881 - _checkOverflow : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.882 -
214.883 - =============================================
214.884 - __sub__: FunctionDef : OffsetRange[32264,32630>
214.885 - NotImplemented [free][read][node=Name]
214.886 - date [free][read][node=Name]
214.887 - days1 [bound][data][read][node=Name]
214.888 - days2 [bound][data][read][node=Name]
214.889 - isinstance [free][read][called][node=Name]
214.890 - other [bound][param][data][read][node=Name]
214.891 - self [bound][param][data][read][node=Name]
214.892 - timedelta [free][read][called][node=Name]
214.893 - ------ Attributes ---------------------------------------
214.894 - toordinal : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
214.895 -
214.896 - =============================================
214.897 - weekday: FunctionDef : OffsetRange[32631,32827>
214.898 - self [bound][param][data][read][node=Name]
214.899 - ------ Attributes ---------------------------------------
214.900 - toordinal : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
214.901 -
214.902 - =============================================
214.903 - isoweekday: FunctionDef : OffsetRange[32828,32997>
214.904 - self [bound][param][data][read][node=Name]
214.905 - ------ Attributes ---------------------------------------
214.906 - toordinal : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
214.907 -
214.908 - =============================================
214.909 - isocalendar: FunctionDef : OffsetRange[32998,33991>
214.910 - _isoweek1monday [free][read][called][node=Name]
214.911 - _ymd2ord [free][read][called][node=Name]
214.912 - day [bound][data][read][node=Name]
214.913 - divmod [free][read][called][node=Name]
214.914 - self [bound][param][data][read][node=Name]
214.915 - today [bound][data][read][node=Name]
214.916 - week [bound][data][read][node=Name]
214.917 - week1monday [bound][data][read][node=Name]
214.918 - year [bound][data][read][node=Name]
214.919 - ------ Attributes ---------------------------------------
214.920 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.921 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.922 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.923 -
214.924 - =============================================
214.925 - __getstate: FunctionDef : OffsetRange[34050,34189>
214.926 - divmod [free][read][called][node=Name]
214.927 - self [bound][param][data][read][node=Name]
214.928 - yhi [bound][data][read][node=Name]
214.929 - ylo [bound][data][read][node=Name]
214.930 - ------ Attributes ---------------------------------------
214.931 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.932 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.933 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.934 -
214.935 - =============================================
214.936 - __setstate: FunctionDef : OffsetRange[34190,34430>
214.937 - isinstance [free][read][called][node=Name]
214.938 - len [free][read][called][node=Name]
214.939 - map [free][read][called][node=Name]
214.940 - ord [free][read][node=Name]
214.941 - self [bound][param][data][read][node=Name]
214.942 - string [bound][data][read][node=Name]
214.943 - t [bound][param][data][read][node=Name]
214.944 - tuple [free][read][node=Name]
214.945 - yhi [bound][data][read][node=Name]
214.946 - ylo [bound][data][read][node=Name]
214.947 -
214.948 - =============================================
214.949 - __reduce__: FunctionDef : OffsetRange[34431,34505>
214.950 - self [bound][param][data][read][node=Name]
214.951 - ------ Attributes ---------------------------------------
214.952 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.953 - __getstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.954 -
214.955 - =============================================
214.956 - class tzinfo: ClassDef : OffsetRange[34675,37029>
214.957 - True [free][read][node=Name]
214.958 - __reduce__ [bound][function][def][node=FunctionDef]
214.959 - __safe_for_unpickling__ [bound][data][node=Name]
214.960 - dst [bound][function][def][node=FunctionDef]
214.961 - fromutc [bound][function][def][node=FunctionDef]
214.962 - tzname [bound][function][def][node=FunctionDef]
214.963 - utcoffset [bound][function][def][node=FunctionDef]
214.964 -
214.965 - =============================================
214.966 - tzname: FunctionDef : OffsetRange[34838,34988>
214.967 - NotImplementedError [free][read][called][node=Name]
214.968 - dt [bound][param][data][unused][node=Name]
214.969 - self [bound][param][data][unused][node=Name]
214.970 -
214.971 - =============================================
214.972 - utcoffset: FunctionDef : OffsetRange[34989,35166>
214.973 - NotImplementedError [free][read][called][node=Name]
214.974 - dt [bound][param][data][unused][node=Name]
214.975 - self [bound][param][data][unused][node=Name]
214.976 -
214.977 - =============================================
214.978 - dst: FunctionDef : OffsetRange[35167,35423>
214.979 - NotImplementedError [free][read][called][node=Name]
214.980 - dt [bound][param][data][unused][node=Name]
214.981 - self [bound][param][data][unused][node=Name]
214.982 -
214.983 - =============================================
214.984 - fromutc: FunctionDef : OffsetRange[35424,36481>
214.985 - None [free][read][node=Name]
214.986 - TypeError [free][read][called][node=Name]
214.987 - ValueError [free][read][called][node=Name]
214.988 - datetime [free][read][node=Name]
214.989 - delta [bound][data][read][node=Name]
214.990 - dt [bound][param][data][read][node=Name]
214.991 - dtdst [bound][data][read][node=Name]
214.992 - dtoff [bound][data][read][node=Name]
214.993 - isinstance [free][read][called][node=Name]
214.994 - self [bound][param][data][read][node=Name]
214.995 -
214.996 - =============================================
214.997 - __reduce__: FunctionDef : OffsetRange[36540,37029>
214.998 - None [free][read][node=Name]
214.999 - args [bound][data][read][node=Name]
214.1000 - getattr [free][read][called][node=Name]
214.1001 - getinitargs [bound][data][read][called][node=Name]
214.1002 - getstate [bound][data][read][called][node=Name]
214.1003 - self [bound][param][data][read][node=Name]
214.1004 - state [bound][data][read][node=Name]
214.1005 - ------ Attributes ---------------------------------------
214.1006 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1007 -
214.1008 - =============================================
214.1009 - class time: ClassDef : OffsetRange[37106,46501>
214.1010 - None [free][read][node=Name]
214.1011 - True [free][read][node=Name]
214.1012 - __cmp [bound][private][function][def][node=FunctionDef]
214.1013 - __eq__ [bound][function][def][node=FunctionDef]
214.1014 - __ge__ [bound][function][def][node=FunctionDef]
214.1015 - __getstate [bound][private][function][def][node=FunctionDef]
214.1016 - __gt__ [bound][function][def][node=FunctionDef]
214.1017 - __hash__ [bound][function][def][node=FunctionDef]
214.1018 - __le__ [bound][function][def][node=FunctionDef]
214.1019 - __lt__ [bound][function][def][node=FunctionDef]
214.1020 - __ne__ [bound][function][def][node=FunctionDef]
214.1021 - __new__ [bound][function][def][node=FunctionDef]
214.1022 - __nonzero__ [bound][function][def][node=FunctionDef]
214.1023 - __reduce__ [bound][function][def][node=FunctionDef]
214.1024 - __repr__ [bound][function][def][node=FunctionDef]
214.1025 - __safe_for_unpickling__ [bound][data][node=Name]
214.1026 - __setstate [bound][private][function][def][node=FunctionDef]
214.1027 - __str__ [bound][function][alias][node=FunctionDef]
214.1028 - _dst [bound][private][function][def][node=FunctionDef]
214.1029 - _tzstr [bound][private][function][def][node=FunctionDef]
214.1030 - _utcoffset [bound][private][function][def][node=FunctionDef]
214.1031 - dst [bound][function][def][node=FunctionDef]
214.1032 - hour [bound][data][node=Name]
214.1033 - isoformat [bound][function][def][read][node=FunctionDef]
214.1034 - microsecond [bound][data][node=Name]
214.1035 - minute [bound][data][node=Name]
214.1036 - property [free][read][called][node=Name]
214.1037 - replace [bound][function][def][node=FunctionDef]
214.1038 - second [bound][data][node=Name]
214.1039 - strftime [bound][function][def][node=FunctionDef]
214.1040 - tzinfo [bound][data][node=Name]
214.1041 - tzname [bound][function][def][node=FunctionDef]
214.1042 - utcoffset [bound][function][def][node=FunctionDef]
214.1043 - ------ Attributes ---------------------------------------
214.1044 - __hour : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.1045 - __microsecond : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.1046 - __minute : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.1047 - __second : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.1048 - _tzinfo : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.1049 -
214.1050 - =============================================
214.1051 - __new__: FunctionDef : OffsetRange[37421,38149>
214.1052 - None [free][read][node=Name]
214.1053 - _check_time_fields [free][read][called][node=Name]
214.1054 - _check_tzinfo_arg [free][read][called][node=Name]
214.1055 - cls [bound][param][data][read][node=Name]
214.1056 - hour [bound][param][data][read][node=Name]
214.1057 - isinstance [free][read][called][node=Name]
214.1058 - microsecond [bound][param][data][read][node=Name]
214.1059 - minute [bound][param][data][read][node=Name]
214.1060 - object [free][read][node=Name]
214.1061 - second [bound][param][data][read][node=Name]
214.1062 - self [bound][data][read][node=Name]
214.1063 - str [free][read][node=Name]
214.1064 - tzinfo [bound][param][data][read][node=Name]
214.1065 - ------ Attributes ---------------------------------------
214.1066 - __new__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
214.1067 - __setstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1068 -
214.1069 - =============================================
214.1070 - <lambda>: Lambda : OffsetRange[38166,38190>
214.1071 - self [bound][param][data][read][node=Name]
214.1072 -
214.1073 - =============================================
214.1074 - <lambda>: Lambda : OffsetRange[38233,38259>
214.1075 - self [bound][param][data][read][node=Name]
214.1076 -
214.1077 - =============================================
214.1078 - <lambda>: Lambda : OffsetRange[38304,38330>
214.1079 - self [bound][param][data][read][node=Name]
214.1080 -
214.1081 - =============================================
214.1082 - <lambda>: Lambda : OffsetRange[38380,38411>
214.1083 - self [bound][param][data][read][node=Name]
214.1084 -
214.1085 - =============================================
214.1086 - <lambda>: Lambda : OffsetRange[38492,38517>
214.1087 - self [bound][param][data][read][node=Name]
214.1088 -
214.1089 - =============================================
214.1090 - __eq__: FunctionDef : OffsetRange[38624,38770>
214.1091 - False [free][read][node=Name]
214.1092 - isinstance [free][read][called][node=Name]
214.1093 - other [bound][param][data][read][node=Name]
214.1094 - self [bound][param][data][read][node=Name]
214.1095 - time [free][read][node=Name]
214.1096 - ------ Attributes ---------------------------------------
214.1097 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1098 -
214.1099 - =============================================
214.1100 - __ne__: FunctionDef : OffsetRange[38771,38916>
214.1101 - True [free][read][node=Name]
214.1102 - isinstance [free][read][called][node=Name]
214.1103 - other [bound][param][data][read][node=Name]
214.1104 - self [bound][param][data][read][node=Name]
214.1105 - time [free][read][node=Name]
214.1106 - ------ Attributes ---------------------------------------
214.1107 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1108 -
214.1109 - =============================================
214.1110 - __le__: FunctionDef : OffsetRange[38917,39073>
214.1111 - _cmperror [free][read][called][node=Name]
214.1112 - isinstance [free][read][called][node=Name]
214.1113 - other [bound][param][data][read][node=Name]
214.1114 - self [bound][param][data][read][node=Name]
214.1115 - time [free][read][node=Name]
214.1116 - ------ Attributes ---------------------------------------
214.1117 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1118 -
214.1119 - =============================================
214.1120 - __lt__: FunctionDef : OffsetRange[39074,39229>
214.1121 - _cmperror [free][read][called][node=Name]
214.1122 - isinstance [free][read][called][node=Name]
214.1123 - other [bound][param][data][read][node=Name]
214.1124 - self [bound][param][data][read][node=Name]
214.1125 - time [free][read][node=Name]
214.1126 - ------ Attributes ---------------------------------------
214.1127 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1128 -
214.1129 - =============================================
214.1130 - __ge__: FunctionDef : OffsetRange[39230,39386>
214.1131 - _cmperror [free][read][called][node=Name]
214.1132 - isinstance [free][read][called][node=Name]
214.1133 - other [bound][param][data][read][node=Name]
214.1134 - self [bound][param][data][read][node=Name]
214.1135 - time [free][read][node=Name]
214.1136 - ------ Attributes ---------------------------------------
214.1137 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1138 -
214.1139 - =============================================
214.1140 - __gt__: FunctionDef : OffsetRange[39387,39542>
214.1141 - _cmperror [free][read][called][node=Name]
214.1142 - isinstance [free][read][called][node=Name]
214.1143 - other [bound][param][data][read][node=Name]
214.1144 - self [bound][param][data][read][node=Name]
214.1145 - time [free][read][node=Name]
214.1146 - ------ Attributes ---------------------------------------
214.1147 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1148 -
214.1149 - =============================================
214.1150 - __cmp: FunctionDef : OffsetRange[39543,40534>
214.1151 - None [free][read][node=Name]
214.1152 - True [free][read][node=Name]
214.1153 - TypeError [free][read][called][node=Name]
214.1154 - base_compare [bound][data][read][node=Name]
214.1155 - cmp [free][read][called][node=Name]
214.1156 - isinstance [free][read][called][node=Name]
214.1157 - myhhmm [bound][data][read][node=Name]
214.1158 - myoff [bound][data][read][node=Name]
214.1159 - mytz [bound][data][read][node=Name]
214.1160 - other [bound][param][data][read][node=Name]
214.1161 - othhmm [bound][data][read][node=Name]
214.1162 - otoff [bound][data][read][node=Name]
214.1163 - ottz [bound][data][read][node=Name]
214.1164 - self [bound][param][data][read][node=Name]
214.1165 - time [free][read][node=Name]
214.1166 - ------ Attributes ---------------------------------------
214.1167 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1168 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1169 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1170 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1171 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1172 - _utcoffset : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1173 -
214.1174 - =============================================
214.1175 - __hash__: FunctionDef : OffsetRange[40535,40938>
214.1176 - divmod [free][read][called][node=Name]
214.1177 - h [bound][data][read][node=Name]
214.1178 - hash [free][read][called][node=Name]
214.1179 - m [bound][data][read][node=Name]
214.1180 - self [bound][param][data][read][node=Name]
214.1181 - time [free][read][called][node=Name]
214.1182 - tzoff [bound][data][read][node=Name]
214.1183 - ------ Attributes ---------------------------------------
214.1184 - __getstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1185 - _utcoffset : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1186 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1187 - microsecond : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1188 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1189 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1190 -
214.1191 - =============================================
214.1192 - _tzstr: FunctionDef : OffsetRange[40939,41361>
214.1193 - None [free][read][node=Name]
214.1194 - divmod [free][read][called][node=Name]
214.1195 - hh [bound][data][read][node=Name]
214.1196 - mm [bound][data][read][node=Name]
214.1197 - off [bound][data][read][node=Name]
214.1198 - self [bound][param][data][read][node=Name]
214.1199 - sep [bound][param][data][read][node=Name]
214.1200 - sign [bound][data][read][node=Name]
214.1201 - ------ Attributes ---------------------------------------
214.1202 - _utcoffset : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1203 -
214.1204 - =============================================
214.1205 - __repr__: FunctionDef : OffsetRange[41362,41919>
214.1206 - None [free][read][node=Name]
214.1207 - s [bound][data][read][node=Name]
214.1208 - self [bound][param][data][read][node=Name]
214.1209 - ------ Attributes ---------------------------------------
214.1210 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1211 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1212 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1213 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1214 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1215 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1216 -
214.1217 - =============================================
214.1218 - isoformat: FunctionDef : OffsetRange[41920,42300>
214.1219 - _format_time [free][read][called][node=Name]
214.1220 - s [bound][data][read][node=Name]
214.1221 - self [bound][param][data][read][node=Name]
214.1222 - tz [bound][data][read][node=Name]
214.1223 - ------ Attributes ---------------------------------------
214.1224 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1225 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1226 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1227 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1228 - _tzstr : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1229 -
214.1230 - =============================================
214.1231 - strftime: FunctionDef : OffsetRange[42326,42811>
214.1232 - _wrap_strftime [free][read][called][node=Name]
214.1233 - fmt [bound][param][data][read][node=Name]
214.1234 - self [bound][param][data][read][node=Name]
214.1235 - timetuple [bound][data][read][node=Name]
214.1236 - ------ Attributes ---------------------------------------
214.1237 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1238 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1239 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1240 -
214.1241 - =============================================
214.1242 - utcoffset: FunctionDef : OffsetRange[42812,43227>
214.1243 - None [free][read][node=Name]
214.1244 - _call_tzinfo_method [free][read][called][node=Name]
214.1245 - _check_utc_offset [free][read][called][node=Name]
214.1246 - offset [bound][data][read][node=Name]
214.1247 - self [bound][param][data][read][node=Name]
214.1248 - timedelta [free][read][called][node=Name]
214.1249 - ------ Attributes ---------------------------------------
214.1250 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1251 -
214.1252 - =============================================
214.1253 - _utcoffset: FunctionDef : OffsetRange[43228,43402>
214.1254 - None [free][read][node=Name]
214.1255 - _call_tzinfo_method [free][read][called][node=Name]
214.1256 - _check_utc_offset [free][read][called][node=Name]
214.1257 - offset [bound][data][read][node=Name]
214.1258 - self [bound][param][data][read][node=Name]
214.1259 - ------ Attributes ---------------------------------------
214.1260 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1261 -
214.1262 - =============================================
214.1263 - tzname: FunctionDef : OffsetRange[43403,43823>
214.1264 - None [free][read][node=Name]
214.1265 - _call_tzinfo_method [free][read][called][node=Name]
214.1266 - _check_tzname [free][read][called][node=Name]
214.1267 - name [bound][data][read][node=Name]
214.1268 - self [bound][param][data][read][node=Name]
214.1269 - ------ Attributes ---------------------------------------
214.1270 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1271 -
214.1272 - =============================================
214.1273 - dst: FunctionDef : OffsetRange[43824,44430>
214.1274 - None [free][read][node=Name]
214.1275 - _call_tzinfo_method [free][read][called][node=Name]
214.1276 - _check_utc_offset [free][read][called][node=Name]
214.1277 - offset [bound][data][read][node=Name]
214.1278 - self [bound][param][data][read][node=Name]
214.1279 - timedelta [free][read][called][node=Name]
214.1280 - ------ Attributes ---------------------------------------
214.1281 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1282 -
214.1283 - =============================================
214.1284 - replace: FunctionDef : OffsetRange[44431,45148>
214.1285 - None [free][read][node=Name]
214.1286 - True [free][read][node=Name]
214.1287 - _check_time_fields [free][read][called][node=Name]
214.1288 - _check_tzinfo_arg [free][read][called][node=Name]
214.1289 - hour [bound][param][data][read][node=Name]
214.1290 - microsecond [bound][param][data][read][node=Name]
214.1291 - minute [bound][param][data][read][node=Name]
214.1292 - second [bound][param][data][read][node=Name]
214.1293 - self [bound][param][data][read][node=Name]
214.1294 - time [free][read][called][node=Name]
214.1295 - tzinfo [bound][param][data][read][node=Name]
214.1296 - ------ Attributes ---------------------------------------
214.1297 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1298 - microsecond : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1299 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1300 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1301 - tzinfo : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1302 -
214.1303 - =============================================
214.1304 - _dst: FunctionDef : OffsetRange[45149,45305>
214.1305 - None [free][read][node=Name]
214.1306 - _call_tzinfo_method [free][read][called][node=Name]
214.1307 - _check_utc_offset [free][read][called][node=Name]
214.1308 - offset [bound][data][read][node=Name]
214.1309 - self [bound][param][data][read][node=Name]
214.1310 - ------ Attributes ---------------------------------------
214.1311 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1312 -
214.1313 - =============================================
214.1314 - __nonzero__: FunctionDef : OffsetRange[45306,45519>
214.1315 - offset [bound][data][read][node=Name]
214.1316 - self [bound][param][data][read][node=Name]
214.1317 - ------ Attributes ---------------------------------------
214.1318 - _utcoffset : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1319 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1320 - microsecond : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1321 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1322 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1323 -
214.1324 - =============================================
214.1325 - __getstate: FunctionDef : OffsetRange[45578,45941>
214.1326 - None [free][read][node=Name]
214.1327 - basestate [bound][data][read][node=Name]
214.1328 - divmod [free][read][called][node=Name]
214.1329 - self [bound][param][data][read][node=Name]
214.1330 - us1 [bound][data][read][node=Name]
214.1331 - us2 [bound][data][read][node=Name]
214.1332 - us3 [bound][data][read][node=Name]
214.1333 - ------ Attributes ---------------------------------------
214.1334 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1335 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1336 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1337 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1338 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1339 -
214.1340 - =============================================
214.1341 - __setstate: FunctionDef : OffsetRange[45942,46426>
214.1342 - None [free][read][node=Name]
214.1343 - isinstance [free][read][called][node=Name]
214.1344 - len [free][read][called][node=Name]
214.1345 - map [free][read][called][node=Name]
214.1346 - ord [free][read][node=Name]
214.1347 - self [bound][param][data][read][node=Name]
214.1348 - state [bound][param][data][read][node=Name]
214.1349 - string [bound][data][read][node=Name]
214.1350 - tuple [free][read][node=Name]
214.1351 - us1 [bound][data][read][node=Name]
214.1352 - us2 [bound][data][read][node=Name]
214.1353 - us3 [bound][data][read][node=Name]
214.1354 -
214.1355 - =============================================
214.1356 - __reduce__: FunctionDef : OffsetRange[46427,46501>
214.1357 - self [bound][param][data][read][node=Name]
214.1358 - ------ Attributes ---------------------------------------
214.1359 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1360 - __getstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1361 -
214.1362 - =============================================
214.1363 - class datetime: ClassDef : OffsetRange[46685,62681>
214.1364 - None [free][read][node=Name]
214.1365 - True [free][read][node=Name]
214.1366 - __add__ [bound][function][def][read][node=FunctionDef]
214.1367 - __cmp [bound][private][function][def][node=FunctionDef]
214.1368 - __eq__ [bound][function][def][node=FunctionDef]
214.1369 - __ge__ [bound][function][def][node=FunctionDef]
214.1370 - __getstate [bound][private][function][def][node=FunctionDef]
214.1371 - __gt__ [bound][function][def][node=FunctionDef]
214.1372 - __hash__ [bound][function][def][node=FunctionDef]
214.1373 - __le__ [bound][function][def][node=FunctionDef]
214.1374 - __lt__ [bound][function][def][node=FunctionDef]
214.1375 - __ne__ [bound][function][def][node=FunctionDef]
214.1376 - __new__ [bound][function][def][node=FunctionDef]
214.1377 - __radd__ [bound][function][alias][node=FunctionDef]
214.1378 - __reduce__ [bound][function][def][node=FunctionDef]
214.1379 - __repr__ [bound][function][def][node=FunctionDef]
214.1380 - __safe_for_unpickling__ [bound][data][node=Name]
214.1381 - __setstate [bound][private][function][def][node=FunctionDef]
214.1382 - __str__ [bound][function][def][node=FunctionDef]
214.1383 - __sub__ [bound][function][def][node=FunctionDef]
214.1384 - _dst [bound][private][function][def][node=FunctionDef]
214.1385 - _utcoffset [bound][private][function][def][node=FunctionDef]
214.1386 - astimezone [bound][function][def][node=FunctionDef]
214.1387 - classmethod [free][read][called][node=Name]
214.1388 - combine [bound][function][def][read][node=FunctionDef]
214.1389 - ctime [bound][function][def][node=FunctionDef]
214.1390 - date [bound][function][def][node=FunctionDef]
214.1391 - dst [bound][function][def][node=FunctionDef]
214.1392 - fromtimestamp [bound][function][def][read][node=FunctionDef]
214.1393 - hour [bound][data][node=Name]
214.1394 - isoformat [bound][function][def][node=FunctionDef]
214.1395 - microsecond [bound][data][node=Name]
214.1396 - minute [bound][data][node=Name]
214.1397 - now [bound][function][def][read][node=FunctionDef]
214.1398 - property [free][read][called][node=Name]
214.1399 - replace [bound][function][def][node=FunctionDef]
214.1400 - second [bound][data][node=Name]
214.1401 - time [bound][function][def][node=FunctionDef]
214.1402 - timetuple [bound][function][def][node=FunctionDef]
214.1403 - timetz [bound][function][def][node=FunctionDef]
214.1404 - tzinfo [bound][data][node=Name]
214.1405 - tzname [bound][function][def][node=FunctionDef]
214.1406 - utcfromtimestamp [bound][function][def][read][node=FunctionDef]
214.1407 - utcnow [bound][function][def][read][node=FunctionDef]
214.1408 - utcoffset [bound][function][def][node=FunctionDef]
214.1409 - utctimetuple [bound][function][def][node=FunctionDef]
214.1410 - ------ Attributes ---------------------------------------
214.1411 - __day : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.1412 - __hour : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.1413 - __microsecond : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.1414 - __minute : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.1415 - __month : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.1416 - __second : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.1417 - __year : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.1418 - _tzinfo : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
214.1419 -
214.1420 - =============================================
214.1421 - __new__: FunctionDef : OffsetRange[46811,47623>
214.1422 - _check_time_fields [free][read][called][node=Name]
214.1423 - _check_tzinfo_arg [free][read][called][node=Name]
214.1424 - cls [bound][param][data][read][node=Name]
214.1425 - date [free][read][node=Name]
214.1426 - day [bound][param][data][read][node=Name]
214.1427 - hour [bound][param][data][read][node=Name]
214.1428 - isinstance [free][read][called][node=Name]
214.1429 - microsecond [bound][param][data][read][node=Name]
214.1430 - minute [bound][param][data][read][node=Name]
214.1431 - month [bound][param][data][read][node=Name]
214.1432 - second [bound][param][data][read][node=Name]
214.1433 - self [bound][data][read][node=Name]
214.1434 - str [free][read][node=Name]
214.1435 - tzinfo [bound][param][data][read][node=Name]
214.1436 - year [bound][param][data][read][node=Name]
214.1437 - ------ Attributes ---------------------------------------
214.1438 - __new__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
214.1439 - __setstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1440 -
214.1441 - =============================================
214.1442 - <lambda>: Lambda : OffsetRange[47640,47664>
214.1443 - self [bound][param][data][read][node=Name]
214.1444 -
214.1445 - =============================================
214.1446 - <lambda>: Lambda : OffsetRange[47707,47733>
214.1447 - self [bound][param][data][read][node=Name]
214.1448 -
214.1449 - =============================================
214.1450 - <lambda>: Lambda : OffsetRange[47778,47804>
214.1451 - self [bound][param][data][read][node=Name]
214.1452 -
214.1453 - =============================================
214.1454 - <lambda>: Lambda : OffsetRange[47854,47885>
214.1455 - self [bound][param][data][read][node=Name]
214.1456 -
214.1457 - =============================================
214.1458 - <lambda>: Lambda : OffsetRange[47966,47991>
214.1459 - self [bound][param][data][read][node=Name]
214.1460 -
214.1461 - =============================================
214.1462 - fromtimestamp: FunctionDef : OffsetRange[48026,48673>
214.1463 - None [free][read][node=Name]
214.1464 - _check_tzinfo_arg [free][read][called][node=Name]
214.1465 - _time [free][read][node=Name]
214.1466 - cls [bound][param][data][read][called][node=Name]
214.1467 - converter [bound][data][read][called][node=Name]
214.1468 - d [bound][data][read][node=Name]
214.1469 - dst [bound][data][unused][node=Name]
214.1470 - hh [bound][data][read][node=Name]
214.1471 - int [free][read][called][node=Name]
214.1472 - jday [bound][data][unused][node=Name]
214.1473 - m [bound][data][read][node=Name]
214.1474 - min [free][read][called][node=Name]
214.1475 - mm [bound][data][read][node=Name]
214.1476 - result [bound][data][read][node=Name]
214.1477 - ss [bound][data][read][node=Name]
214.1478 - t [bound][param][data][read][node=Name]
214.1479 - tz [bound][param][data][read][node=Name]
214.1480 - us [bound][data][read][node=Name]
214.1481 - weekday [bound][data][unused][node=Name]
214.1482 - y [bound][data][read][node=Name]
214.1483 -
214.1484 - =============================================
214.1485 - utcfromtimestamp: FunctionDef : OffsetRange[48722,49059>
214.1486 - _time [free][read][node=Name]
214.1487 - cls [bound][param][data][read][called][node=Name]
214.1488 - d [bound][data][read][node=Name]
214.1489 - dst [bound][data][unused][node=Name]
214.1490 - hh [bound][data][read][node=Name]
214.1491 - int [free][read][called][node=Name]
214.1492 - jday [bound][data][unused][node=Name]
214.1493 - m [bound][data][read][node=Name]
214.1494 - min [free][read][called][node=Name]
214.1495 - mm [bound][data][read][node=Name]
214.1496 - ss [bound][data][read][node=Name]
214.1497 - t [bound][param][data][read][node=Name]
214.1498 - us [bound][data][read][node=Name]
214.1499 - weekday [bound][data][unused][node=Name]
214.1500 - y [bound][data][read][node=Name]
214.1501 -
214.1502 - =============================================
214.1503 - now: FunctionDef : OffsetRange[49451,49619>
214.1504 - _time [free][read][node=Name]
214.1505 - cls [bound][param][data][read][node=Name]
214.1506 - t [bound][data][read][node=Name]
214.1507 - tz [bound][param][data][read][node=Name]
214.1508 -
214.1509 - =============================================
214.1510 - utcnow: FunctionDef : OffsetRange[49648,49785>
214.1511 - _time [free][read][node=Name]
214.1512 - cls [bound][param][data][read][node=Name]
214.1513 - t [bound][data][read][node=Name]
214.1514 -
214.1515 - =============================================
214.1516 - combine: FunctionDef : OffsetRange[49820,50308>
214.1517 - TypeError [free][read][called][node=Name]
214.1518 - _date_class [free][read][node=Name]
214.1519 - _time_class [free][read][node=Name]
214.1520 - cls [bound][param][data][read][called][node=Name]
214.1521 - date [bound][param][data][read][node=Name]
214.1522 - isinstance [free][read][called][node=Name]
214.1523 - time [bound][param][data][read][node=Name]
214.1524 -
214.1525 - =============================================
214.1526 - timetuple: FunctionDef : OffsetRange[50345,50724>
214.1527 - None [free][read][node=Name]
214.1528 - _build_struct_time [free][read][called][node=Name]
214.1529 - dst [bound][data][read][node=Name]
214.1530 - self [bound][param][data][read][node=Name]
214.1531 - ------ Attributes ---------------------------------------
214.1532 - _dst : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1533 - day : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1534 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1535 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1536 - month : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1537 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1538 - year : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1539 -
214.1540 - =============================================
214.1541 - utctimetuple: FunctionDef : OffsetRange[50725,51194>
214.1542 - _build_struct_time [free][read][called][node=Name]
214.1543 - d [bound][data][read][node=Name]
214.1544 - hh [bound][data][read][node=Name]
214.1545 - m [bound][data][read][node=Name]
214.1546 - mm [bound][data][read][node=Name]
214.1547 - offset [bound][data][read][node=Name]
214.1548 - self [bound][param][data][read][node=Name]
214.1549 - ss [bound][data][read][node=Name]
214.1550 - tm [bound][data][read][node=Name]
214.1551 - tmxxx [free][read][called][node=Name]
214.1552 - y [bound][data][read][node=Name]
214.1553 - ------ Attributes ---------------------------------------
214.1554 - _utcoffset : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1555 - day : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1556 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1557 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1558 - month : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1559 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1560 - year : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1561 -
214.1562 - =============================================
214.1563 - date: FunctionDef : OffsetRange[51195,51306>
214.1564 - date [free][read][called][node=Name]
214.1565 - self [bound][param][data][read][node=Name]
214.1566 - ------ Attributes ---------------------------------------
214.1567 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1568 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1569 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1570 -
214.1571 - =============================================
214.1572 - time: FunctionDef : OffsetRange[51307,51452>
214.1573 - self [bound][param][data][read][node=Name]
214.1574 - time [free][read][called][node=Name]
214.1575 - ------ Attributes ---------------------------------------
214.1576 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1577 - microsecond : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1578 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1579 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1580 -
214.1581 - =============================================
214.1582 - timetz: FunctionDef : OffsetRange[51453,51634>
214.1583 - self [bound][param][data][read][node=Name]
214.1584 - time [free][read][called][node=Name]
214.1585 - ------ Attributes ---------------------------------------
214.1586 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1587 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1588 - microsecond : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1589 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1590 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1591 -
214.1592 - =============================================
214.1593 - replace: FunctionDef : OffsetRange[51635,52576>
214.1594 - None [free][read][node=Name]
214.1595 - True [free][read][node=Name]
214.1596 - _check_date_fields [free][read][called][node=Name]
214.1597 - _check_time_fields [free][read][called][node=Name]
214.1598 - _check_tzinfo_arg [free][read][called][node=Name]
214.1599 - datetime [free][read][called][node=Name]
214.1600 - day [bound][param][data][read][node=Name]
214.1601 - hour [bound][param][data][read][node=Name]
214.1602 - microsecond [bound][param][data][read][node=Name]
214.1603 - minute [bound][param][data][read][node=Name]
214.1604 - month [bound][param][data][read][node=Name]
214.1605 - second [bound][param][data][read][node=Name]
214.1606 - self [bound][param][data][read][node=Name]
214.1607 - tzinfo [bound][param][data][read][node=Name]
214.1608 - year [bound][param][data][read][node=Name]
214.1609 - ------ Attributes ---------------------------------------
214.1610 - day : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1611 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1612 - microsecond : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1613 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1614 - month : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1615 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1616 - tzinfo : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1617 - year : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1618 -
214.1619 - =============================================
214.1620 - astimezone: FunctionDef : OffsetRange[52577,53260>
214.1621 - None [free][read][node=Name]
214.1622 - TypeError [free][read][called][node=Name]
214.1623 - ValuError [free][read][called][node=Name]
214.1624 - ValueError [free][read][called][node=Name]
214.1625 - isinstance [free][read][called][node=Name]
214.1626 - myoffset [bound][data][read][node=Name]
214.1627 - mytz [bound][data][read][node=Name]
214.1628 - self [bound][param][data][read][node=Name]
214.1629 - tz [bound][param][data][read][node=Name]
214.1630 - tzinfo [free][read][node=Name]
214.1631 - utc [bound][data][read][node=Name]
214.1632 - ------ Attributes ---------------------------------------
214.1633 - tzinfo : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1634 - utcoffset : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
214.1635 -
214.1636 - =============================================
214.1637 - ctime: FunctionDef : OffsetRange[53261,53456>
214.1638 - self [bound][param][data][read][node=Name]
214.1639 - t [bound][data][read][node=Name]
214.1640 - tmxxx [free][read][called][node=Name]
214.1641 - ------ Attributes ---------------------------------------
214.1642 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1643 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1644 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1645 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1646 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1647 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1648 -
214.1649 - =============================================
214.1650 - isoformat: FunctionDef : OffsetRange[53457,54437>
214.1651 - None [free][read][node=Name]
214.1652 - _format_time [free][read][called][node=Name]
214.1653 - divmod [free][read][called][node=Name]
214.1654 - hh [bound][data][read][node=Name]
214.1655 - mm [bound][data][read][node=Name]
214.1656 - off [bound][data][read][node=Name]
214.1657 - s [bound][data][read][node=Name]
214.1658 - self [bound][param][data][read][node=Name]
214.1659 - sep [bound][param][data][read][node=Name]
214.1660 - sign [bound][data][read][node=Name]
214.1661 - ------ Attributes ---------------------------------------
214.1662 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1663 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1664 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1665 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1666 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1667 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1668 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1669 - _utcoffset : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1670 -
214.1671 - =============================================
214.1672 - __repr__: FunctionDef : OffsetRange[54438,54999>
214.1673 - L [bound][data][read][node=Name]
214.1674 - None [free][read][node=Name]
214.1675 - map [free][read][called][node=Name]
214.1676 - s [bound][data][read][node=Name]
214.1677 - self [bound][param][data][read][node=Name]
214.1678 - str [free][read][node=Name]
214.1679 - ------ Attributes ---------------------------------------
214.1680 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1681 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1682 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1683 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1684 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1685 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1686 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1687 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1688 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1689 -
214.1690 - =============================================
214.1691 - __str__: FunctionDef : OffsetRange[55000,55102>
214.1692 - self [bound][param][data][read][node=Name]
214.1693 - ------ Attributes ---------------------------------------
214.1694 - isoformat : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
214.1695 -
214.1696 - =============================================
214.1697 - utcoffset: FunctionDef : OffsetRange[55103,55518>
214.1698 - None [free][read][node=Name]
214.1699 - _call_tzinfo_method [free][read][called][node=Name]
214.1700 - _check_utc_offset [free][read][called][node=Name]
214.1701 - offset [bound][data][read][node=Name]
214.1702 - self [bound][param][data][read][node=Name]
214.1703 - timedelta [free][read][called][node=Name]
214.1704 - ------ Attributes ---------------------------------------
214.1705 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1706 -
214.1707 - =============================================
214.1708 - _utcoffset: FunctionDef : OffsetRange[55519,55693>
214.1709 - _call_tzinfo_method [free][read][called][node=Name]
214.1710 - _check_utc_offset [free][read][called][node=Name]
214.1711 - offset [bound][data][read][node=Name]
214.1712 - self [bound][param][data][read][node=Name]
214.1713 - ------ Attributes ---------------------------------------
214.1714 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1715 -
214.1716 - =============================================
214.1717 - tzname: FunctionDef : OffsetRange[55694,56114>
214.1718 - _call_tzinfo_method [free][read][called][node=Name]
214.1719 - _check_tzname [free][read][called][node=Name]
214.1720 - name [bound][data][read][node=Name]
214.1721 - self [bound][param][data][read][node=Name]
214.1722 - ------ Attributes ---------------------------------------
214.1723 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1724 -
214.1725 - =============================================
214.1726 - dst: FunctionDef : OffsetRange[56115,56793>
214.1727 - None [free][read][node=Name]
214.1728 - _call_tzinfo_method [free][read][called][node=Name]
214.1729 - _check_utc_offset [free][read][called][node=Name]
214.1730 - offset [bound][data][read][node=Name]
214.1731 - self [bound][param][data][read][node=Name]
214.1732 - timedelta [free][read][called][node=Name]
214.1733 - ------ Attributes ---------------------------------------
214.1734 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1735 -
214.1736 - =============================================
214.1737 - _dst: FunctionDef : OffsetRange[56794,56970>
214.1738 - _call_tzinfo_method [free][read][called][node=Name]
214.1739 - _check_utc_offset [free][read][called][node=Name]
214.1740 - offset [bound][data][read][node=Name]
214.1741 - self [bound][param][data][read][node=Name]
214.1742 - ------ Attributes ---------------------------------------
214.1743 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1744 -
214.1745 - =============================================
214.1746 - __eq__: FunctionDef : OffsetRange[56971,57197>
214.1747 - False [free][read][node=Name]
214.1748 - NotImplemented [free][read][node=Name]
214.1749 - datetime [free][read][node=Name]
214.1750 - hasattr [free][read][called][node=Name]
214.1751 - isinstance [free][read][called][node=Name]
214.1752 - other [bound][param][data][read][node=Name]
214.1753 - self [bound][param][data][read][node=Name]
214.1754 - ------ Attributes ---------------------------------------
214.1755 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1756 -
214.1757 - =============================================
214.1758 - __ne__: FunctionDef : OffsetRange[57198,57423>
214.1759 - NotImplemented [free][read][node=Name]
214.1760 - True [free][read][node=Name]
214.1761 - datetime [free][read][node=Name]
214.1762 - hasattr [free][read][called][node=Name]
214.1763 - isinstance [free][read][called][node=Name]
214.1764 - other [bound][param][data][read][node=Name]
214.1765 - self [bound][param][data][read][node=Name]
214.1766 - ------ Attributes ---------------------------------------
214.1767 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1768 -
214.1769 - =============================================
214.1770 - __le__: FunctionDef : OffsetRange[57424,57660>
214.1771 - NotImplemented [free][read][node=Name]
214.1772 - _cmperror [free][read][called][node=Name]
214.1773 - datetime [free][read][node=Name]
214.1774 - hasattr [free][read][called][node=Name]
214.1775 - isinstance [free][read][called][node=Name]
214.1776 - other [bound][param][data][read][node=Name]
214.1777 - self [bound][param][data][read][node=Name]
214.1778 - ------ Attributes ---------------------------------------
214.1779 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1780 -
214.1781 - =============================================
214.1782 - __lt__: FunctionDef : OffsetRange[57661,57896>
214.1783 - NotImplemented [free][read][node=Name]
214.1784 - _cmperror [free][read][called][node=Name]
214.1785 - datetime [free][read][node=Name]
214.1786 - hasattr [free][read][called][node=Name]
214.1787 - isinstance [free][read][called][node=Name]
214.1788 - other [bound][param][data][read][node=Name]
214.1789 - self [bound][param][data][read][node=Name]
214.1790 - ------ Attributes ---------------------------------------
214.1791 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1792 -
214.1793 - =============================================
214.1794 - __ge__: FunctionDef : OffsetRange[57897,58133>
214.1795 - NotImplemented [free][read][node=Name]
214.1796 - _cmperror [free][read][called][node=Name]
214.1797 - datetime [free][read][node=Name]
214.1798 - hasattr [free][read][called][node=Name]
214.1799 - isinstance [free][read][called][node=Name]
214.1800 - other [bound][param][data][read][node=Name]
214.1801 - self [bound][param][data][read][node=Name]
214.1802 - ------ Attributes ---------------------------------------
214.1803 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1804 -
214.1805 - =============================================
214.1806 - __gt__: FunctionDef : OffsetRange[58134,58369>
214.1807 - NotImplemented [free][read][node=Name]
214.1808 - _cmperror [free][read][called][node=Name]
214.1809 - datetime [free][read][node=Name]
214.1810 - hasattr [free][read][called][node=Name]
214.1811 - isinstance [free][read][called][node=Name]
214.1812 - other [bound][param][data][read][node=Name]
214.1813 - self [bound][param][data][read][node=Name]
214.1814 - ------ Attributes ---------------------------------------
214.1815 - __cmp : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1816 -
214.1817 - =============================================
214.1818 - __cmp: FunctionDef : OffsetRange[58370,59534>
214.1819 - None [free][read][node=Name]
214.1820 - True [free][read][node=Name]
214.1821 - TypeError [free][read][called][node=Name]
214.1822 - base_compare [bound][data][read][node=Name]
214.1823 - cmp [free][read][called][node=Name]
214.1824 - datetime [free][read][node=Name]
214.1825 - diff [bound][data][read][node=Name]
214.1826 - isinstance [free][read][called][node=Name]
214.1827 - myoff [bound][data][read][node=Name]
214.1828 - mytz [bound][data][read][node=Name]
214.1829 - other [bound][param][data][read][node=Name]
214.1830 - otoff [bound][data][read][node=Name]
214.1831 - ottz [bound][data][read][node=Name]
214.1832 - self [bound][param][data][read][node=Name]
214.1833 - ------ Attributes ---------------------------------------
214.1834 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1835 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1836 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1837 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1838 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1839 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1840 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1841 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1842 - _utcoffset : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1843 -
214.1844 - =============================================
214.1845 - __add__: FunctionDef : OffsetRange[59535,60206>
214.1846 - NotImplemented [free][read][node=Name]
214.1847 - isinstance [free][read][called][node=Name]
214.1848 - other [bound][param][data][read][node=Name]
214.1849 - result [bound][data][read][node=Name]
214.1850 - self [bound][param][data][read][node=Name]
214.1851 - t [bound][data][read][node=Name]
214.1852 - timedelta [free][read][node=Name]
214.1853 - tmxxx [free][read][called][node=Name]
214.1854 - ------ Attributes ---------------------------------------
214.1855 - __class__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
214.1856 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1857 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1858 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1859 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1860 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1861 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1862 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1863 - _checkOverflow : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1864 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1865 -
214.1866 - =============================================
214.1867 - __sub__: FunctionDef : OffsetRange[60231,61204>
214.1868 - None [free][read][node=Name]
214.1869 - NotImplemented [free][read][node=Name]
214.1870 - TypeError [free][read][node=Name]
214.1871 - base [bound][data][read][node=Name]
214.1872 - datetime [free][read][node=Name]
214.1873 - days1 [bound][data][read][node=Name]
214.1874 - days2 [bound][data][read][node=Name]
214.1875 - isinstance [free][read][called][node=Name]
214.1876 - myoff [bound][data][read][node=Name]
214.1877 - other [bound][param][data][read][node=Name]
214.1878 - otoff [bound][data][read][node=Name]
214.1879 - secs1 [bound][data][read][node=Name]
214.1880 - secs2 [bound][data][read][node=Name]
214.1881 - self [bound][param][data][read][node=Name]
214.1882 - timedelta [free][read][called][node=Name]
214.1883 - ------ Attributes ---------------------------------------
214.1884 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1885 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1886 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1887 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1888 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1889 - _utcoffset : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1890 - toordinal : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
214.1891 -
214.1892 - =============================================
214.1893 - __hash__: FunctionDef : OffsetRange[61205,61557>
214.1894 - None [free][read][node=Name]
214.1895 - _ymd2ord [free][read][called][node=Name]
214.1896 - days [bound][data][read][node=Name]
214.1897 - hash [free][read][called][node=Name]
214.1898 - seconds [bound][data][read][node=Name]
214.1899 - self [bound][param][data][read][node=Name]
214.1900 - timedelta [free][read][called][node=Name]
214.1901 - tzoff [bound][data][read][node=Name]
214.1902 - ------ Attributes ---------------------------------------
214.1903 - __getstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1904 - _utcoffset : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1905 - day : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1906 - hour : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1907 - microsecond : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1908 - minute : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1909 - month : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1910 - second : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1911 - year : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1912 -
214.1913 - =============================================
214.1914 - __getstate: FunctionDef : OffsetRange[61616,62096>
214.1915 - None [free][read][node=Name]
214.1916 - basestate [bound][data][read][node=Name]
214.1917 - divmod [free][read][called][node=Name]
214.1918 - self [bound][param][data][read][node=Name]
214.1919 - us1 [bound][data][read][node=Name]
214.1920 - us2 [bound][data][read][node=Name]
214.1921 - us3 [bound][data][read][node=Name]
214.1922 - yhi [bound][data][read][node=Name]
214.1923 - ylo [bound][data][read][node=Name]
214.1924 - ------ Attributes ---------------------------------------
214.1925 - __day : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1926 - __hour : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1927 - __microsecond : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1928 - __minute : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1929 - __month : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1930 - __second : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1931 - __year : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1932 - _tzinfo : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
214.1933 -
214.1934 - =============================================
214.1935 - __setstate: FunctionDef : OffsetRange[62097,62605>
214.1936 - None [free][read][node=Name]
214.1937 - isinstance [free][read][called][node=Name]
214.1938 - len [free][read][called][node=Name]
214.1939 - map [free][read][called][node=Name]
214.1940 - ord [free][read][node=Name]
214.1941 - self [bound][param][data][read][node=Name]
214.1942 - state [bound][param][data][read][node=Name]
214.1943 - string [bound][data][read][node=Name]
214.1944 - tuple [free][read][node=Name]
214.1945 - us1 [bound][data][read][node=Name]
214.1946 - us2 [bound][data][read][node=Name]
214.1947 - us3 [bound][data][read][node=Name]
214.1948 - yhi [bound][data][read][node=Name]
214.1949 - ylo [bound][data][read][node=Name]
214.1950 -
214.1951 - =============================================
214.1952 - __reduce__: FunctionDef : OffsetRange[62606,62681>
214.1953 - self [bound][param][data][read][node=Name]
214.1954 - ------ Attributes ---------------------------------------
214.1955 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
214.1956 - __getstate : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
214.1957 -
214.1958 - =============================================
214.1959 - _isoweek1monday: FunctionDef : OffsetRange[62822,63202>
214.1960 - THURSDAY [bound][data][read][node=Name]
214.1961 - _ymd2ord [free][read][called][node=Name]
214.1962 - firstday [bound][data][read][node=Name]
214.1963 - firstweekday [bound][data][read][node=Name]
214.1964 - week1monday [bound][data][read][node=Name]
214.1965 - year [bound][param][data][read][node=Name]
214.1966 -
214.1967 - =============================================
214.1968 - _test: FunctionDef : OffsetRange[71694,71763>
214.1969 - test_datetime [bound][imported][data][read][node=Import]
214.1970 -
215.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.semantic Sun Jan 04 13:11:53 2015 -0600
215.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
215.3 @@ -1,2008 +0,0 @@
215.4 -"""Concrete date/time and related types -- prototype implemented in Python.
215.5 -
215.6 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
215.7 -
215.8 -See also http://dir.yahoo.com/Reference/calendars/
215.9 -
215.10 -For a primer on DST, including many current DST rules, see
215.11 -http://webexhibits.org/daylightsaving/
215.12 -
215.13 -For more about DST than you ever wanted to know, see
215.14 -ftp://elsie.nci.nih.gov/pub/
215.15 -
215.16 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
215.17 -
215.18 -"""
215.19 -
215.20 -import time as _time
215.21 -import math as _math
215.22 -
215.23 -MINYEAR = 1
215.24 -MAXYEAR = 9999
215.25 -
215.26 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
215.27 -# also assumes the current Gregorian calendar indefinitely extended in
215.28 -# both directions. Difference: Dates.py calls January 1 of year 0 day
215.29 -# number 1. The code here calls January 1 of year 1 day number 1. This is
215.30 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
215.31 -# and Reingold's "Calendrical Calculations", where it's the base calendar
215.32 -# for all computations. See the book for algorithms for converting between
215.33 -# proleptic Gregorian ordinals and many other calendar systems.
215.34 -
215.35 -_DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
215.36 -
215.37 -_DAYS_BEFORE_MONTH = [None]
215.38 -dbm = 0
215.39 -for dim in _DAYS_IN_MONTH[1:]:
215.40 - _DAYS_BEFORE_MONTH.append(dbm)
215.41 - dbm += dim
215.42 -del dbm, dim
215.43 -
215.44 -def |>METHOD:_is_leap<|(|>PARAMETER:year<|):
215.45 - "year -> 1 if leap year, else 0."
215.46 - return |>PARAMETER:year<| % 4 == 0 and (|>PARAMETER:year<| % 100 != 0 or |>PARAMETER:year<| % 400 == 0)
215.47 -
215.48 -def |>METHOD:_days_in_year<|(|>PARAMETER:year<|):
215.49 - "year -> number of days in year (366 if a leap year, else 365)."
215.50 - return 365 + _is_leap(|>PARAMETER:year<|)
215.51 -
215.52 -def |>METHOD:_days_before_year<|(|>PARAMETER:year<|):
215.53 - "year -> number of days before January 1st of year."
215.54 - y = |>PARAMETER:year<| - 1
215.55 - return y*365 + y//4 - y//100 + y//400
215.56 -
215.57 -def |>METHOD:_days_in_month<|(|>PARAMETER:year<|, |>PARAMETER:month<|):
215.58 - "year, month -> number of days in that month in that year."
215.59 - assert 1 <= |>PARAMETER:month<| <= 12, |>PARAMETER:month<|
215.60 - if |>PARAMETER:month<| == 2 and _is_leap(|>PARAMETER:year<|):
215.61 - return 29
215.62 - return _DAYS_IN_MONTH[|>PARAMETER:month<|]
215.63 -
215.64 -def |>METHOD:_days_before_month<|(|>PARAMETER:year<|, |>PARAMETER:month<|):
215.65 - "year, month -> number of days in year preceeding first day of month."
215.66 - if not 1 <= |>PARAMETER:month<| <= 12:
215.67 - raise ValueError('month must be in 1..12', |>PARAMETER:month<|)
215.68 - return _DAYS_BEFORE_MONTH[|>PARAMETER:month<|] + (|>PARAMETER:month<| > 2 and _is_leap(|>PARAMETER:year<|))
215.69 -
215.70 -def |>METHOD:_ymd2ord<|(|>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|):
215.71 - "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
215.72 - if not 1 <= |>PARAMETER:month<| <= 12:
215.73 - raise ValueError('month must be in 1..12', |>PARAMETER:month<|)
215.74 - dim = _days_in_month(|>PARAMETER:year<|, |>PARAMETER:month<|)
215.75 - if not 1 <= |>PARAMETER:day<| <= dim:
215.76 - raise ValueError('day must be in 1..%d' % dim, |>PARAMETER:day<|)
215.77 - return (_days_before_year(|>PARAMETER:year<|) +
215.78 - _days_before_month(|>PARAMETER:year<|, |>PARAMETER:month<|) +
215.79 - |>PARAMETER:day<|)
215.80 -
215.81 -_DI400Y = _days_before_year(401) # number of days in 400 years
215.82 -_DI100Y = _days_before_year(101) # " " " " 100 "
215.83 -_DI4Y = _days_before_year(5) # " " " " 4 "
215.84 -
215.85 -# A 4-year cycle has an extra leap day over what we'd get from pasting
215.86 -# together 4 single years.
215.87 -assert _DI4Y == 4 * 365 + 1
215.88 -
215.89 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
215.90 -# pasting together 4 100-year cycles.
215.91 -assert _DI400Y == 4 * _DI100Y + 1
215.92 -
215.93 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
215.94 -# pasting together 25 4-year cycles.
215.95 -assert _DI100Y == 25 * _DI4Y - 1
215.96 -
215.97 -def |>METHOD:_ord2ymd<|(|>PARAMETER:n<|):
215.98 - "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
215.99 -
215.100 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
215.101 - # repeats exactly every 400 years. The basic strategy is to find the
215.102 - # closest 400-year boundary at or before n, then work with the offset
215.103 - # from that boundary to n. Life is much clearer if we subtract 1 from
215.104 - # n first -- then the values of n at 400-year boundaries are exactly
215.105 - # those divisible by _DI400Y:
215.106 - #
215.107 - # D M Y n n-1
215.108 - # -- --- ---- ---------- ----------------
215.109 - # 31 Dec -400 -_DI400Y -_DI400Y -1
215.110 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
215.111 - # ...
215.112 - # 30 Dec 000 -1 -2
215.113 - # 31 Dec 000 0 -1
215.114 - # 1 Jan 001 1 0 400-year boundary
215.115 - # 2 Jan 001 2 1
215.116 - # 3 Jan 001 3 2
215.117 - # ...
215.118 - # 31 Dec 400 _DI400Y _DI400Y -1
215.119 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
215.120 - |>PARAMETER:n<| -= 1
215.121 - n400, |>PARAMETER:n<| = divmod(|>PARAMETER:n<|, _DI400Y)
215.122 - year = n400 * 400 + 1 # ..., -399, 1, 401, ...
215.123 -
215.124 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
215.125 - # the desired date. Now compute how many 100-year cycles precede n.
215.126 - # Note that it's possible for n100 to equal 4! In that case 4 full
215.127 - # 100-year cycles precede the desired day, which implies the desired
215.128 - # day is December 31 at the end of a 400-year cycle.
215.129 - n100, |>PARAMETER:n<| = divmod(|>PARAMETER:n<|, _DI100Y)
215.130 -
215.131 - # Now compute how many 4-year cycles precede it.
215.132 - n4, |>PARAMETER:n<| = divmod(|>PARAMETER:n<|, _DI4Y)
215.133 -
215.134 - # And now how many single years. Again n1 can be 4, and again meaning
215.135 - # that the desired day is December 31 at the end of the 4-year cycle.
215.136 - n1, |>PARAMETER:n<| = divmod(|>PARAMETER:n<|, 365)
215.137 -
215.138 - year += n100 * 100 + n4 * 4 + n1
215.139 - if n1 == 4 or n100 == 4:
215.140 - assert |>PARAMETER:n<| == 0
215.141 - return year-1, 12, 31
215.142 -
215.143 - # Now the year is correct, and n is the offset from January 1. We find
215.144 - # the month via an estimate that's either exact or one too large.
215.145 - leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
215.146 - assert leapyear == _is_leap(year)
215.147 - month = (|>PARAMETER:n<| + 50) >> 5
215.148 - preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
215.149 - if preceding > |>PARAMETER:n<|: # estimate is too large
215.150 - month -= 1
215.151 - preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
215.152 - |>PARAMETER:n<| -= preceding
215.153 - assert 0 <= |>PARAMETER:n<| < _days_in_month(year, month)
215.154 -
215.155 - # Now the year and month are correct, and n is the offset from the
215.156 - # start of that month: we're done!
215.157 - return year, month, |>PARAMETER:n<|+1
215.158 -
215.159 -# Month and day names. For localized versions, see the calendar module.
215.160 -_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
215.161 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
215.162 -_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
215.163 -
215.164 -
215.165 -def |>METHOD:_build_struct_time<|(|>PARAMETER:y<|, |>PARAMETER:m<|, |>PARAMETER:d<|, |>PARAMETER:hh<|, |>PARAMETER:mm<|, |>PARAMETER:ss<|, |>PARAMETER:dstflag<|):
215.166 - wday = (_ymd2ord(|>PARAMETER:y<|, |>PARAMETER:m<|, |>PARAMETER:d<|) + 6) % 7
215.167 - dnum = _days_before_month(|>PARAMETER:y<|, |>PARAMETER:m<|) + |>PARAMETER:d<|
215.168 - return _time.struct_time((|>PARAMETER:y<|, |>PARAMETER:m<|, |>PARAMETER:d<|, |>PARAMETER:hh<|, |>PARAMETER:mm<|, |>PARAMETER:ss<|, wday, dnum, |>PARAMETER:dstflag<|))
215.169 -
215.170 -def |>METHOD:_format_time<|(|>PARAMETER:hh<|, |>PARAMETER:mm<|, |>PARAMETER:ss<|, |>PARAMETER:us<|):
215.171 - # Skip trailing microseconds when us==0.
215.172 - result = "%02d:%02d:%02d" % (|>PARAMETER:hh<|, |>PARAMETER:mm<|, |>PARAMETER:ss<|)
215.173 - if |>PARAMETER:us<|:
215.174 - result += ".%06d" % |>PARAMETER:us<|
215.175 - return result
215.176 -
215.177 -# Correctly substitute for %z and %Z escapes in strftime formats.
215.178 -def |>METHOD:_wrap_strftime<|(|>PARAMETER:object<|, |>PARAMETER:format<|, |>PARAMETER:timetuple<|):
215.179 - year = |>PARAMETER:timetuple<|[0]
215.180 - if year < 1900:
215.181 - raise ValueError("year=%d is before 1900; the datetime strftime() "
215.182 - "methods require year >= 1900" % year)
215.183 - # Don't call _utcoffset() or tzname() unless actually needed.
215.184 - zreplace = None # the string to use for %z
215.185 - Zreplace = None # the string to use for %Z
215.186 -
215.187 - # Scan format for %z and %Z escapes, replacing as needed.
215.188 - newformat = []
215.189 - push = newformat.append
215.190 - i, n = 0, len(|>PARAMETER:format<|)
215.191 - while i < n:
215.192 - ch = |>PARAMETER:format<|[i]
215.193 - i += 1
215.194 - if ch == '%':
215.195 - if i < n:
215.196 - ch = |>PARAMETER:format<|[i]
215.197 - i += 1
215.198 - if ch == 'z':
215.199 - if zreplace is None:
215.200 - zreplace = ""
215.201 - if hasattr(|>PARAMETER:object<|, "_utcoffset"):
215.202 - offset = |>PARAMETER:object<|._utcoffset()
215.203 - if offset is not None:
215.204 - sign = '+'
215.205 - if offset < 0:
215.206 - offset = -offset
215.207 - sign = '-'
215.208 - h, m = divmod(offset, 60)
215.209 - zreplace = '%c%02d%02d' % (sign, h, m)
215.210 - assert '%' not in zreplace
215.211 - newformat.append(zreplace)
215.212 - elif ch == 'Z':
215.213 - if Zreplace is None:
215.214 - Zreplace = ""
215.215 - if hasattr(|>PARAMETER:object<|, "tzname"):
215.216 - s = |>PARAMETER:object<|.tzname()
215.217 - if s is not None:
215.218 - # strftime is going to have at this: escape %
215.219 - Zreplace = s.replace('%', '%%')
215.220 - newformat.append(Zreplace)
215.221 - else:
215.222 - push('%')
215.223 - push(ch)
215.224 - else:
215.225 - push('%')
215.226 - else:
215.227 - push(ch)
215.228 - newformat = "".join(newformat)
215.229 - return _time.strftime(newformat, |>PARAMETER:timetuple<|)
215.230 -
215.231 -def |>METHOD:_call_tzinfo_method<|(|>PARAMETER:tzinfo<|, |>PARAMETER:methname<|, |>PARAMETER:tzinfoarg<|):
215.232 - if |>PARAMETER:tzinfo<| is None:
215.233 - return None
215.234 - return getattr(|>PARAMETER:tzinfo<|, |>PARAMETER:methname<|)(|>PARAMETER:tzinfoarg<|)
215.235 -
215.236 -# Just raise TypeError if the arg isn't None or a string.
215.237 -def |>METHOD:_check_tzname<|(|>PARAMETER:name<|):
215.238 - if |>PARAMETER:name<| is not None and not isinstance(|>PARAMETER:name<|, str):
215.239 - raise TypeError("tzinfo.tzname() must return None or string, "
215.240 - "not '%s'" % type(|>PARAMETER:name<|))
215.241 -
215.242 -# name is the offset-producing method, "utcoffset" or "dst".
215.243 -# offset is what it returned.
215.244 -# If offset isn't None or timedelta, raises TypeError.
215.245 -# If offset is None, returns None.
215.246 -# Else offset is checked for being in range, and a whole # of minutes.
215.247 -# If it is, its integer value is returned. Else ValueError is raised.
215.248 -def |>METHOD:_check_utc_offset<|(|>PARAMETER:name<|, |>PARAMETER:offset<|):
215.249 - assert |>PARAMETER:name<| in ("utcoffset", "dst")
215.250 - if |>PARAMETER:offset<| is None:
215.251 - return None
215.252 - if not isinstance(|>PARAMETER:offset<|, timedelta):
215.253 - raise TypeError("tzinfo.%s() must return None "
215.254 - "or timedelta, not '%s'" % (|>PARAMETER:name<|, type(|>PARAMETER:offset<|)))
215.255 - days = |>PARAMETER:offset<|.days
215.256 - if days < -1 or days > 0:
215.257 - |>PARAMETER:offset<| = 1440 # trigger out-of-range
215.258 - else:
215.259 - seconds = days * 86400 + |>PARAMETER:offset<|.seconds
215.260 - minutes, seconds = divmod(seconds, 60)
215.261 - if seconds or |>PARAMETER:offset<|.microseconds:
215.262 - raise ValueError("tzinfo.%s() must return a whole number "
215.263 - "of minutes" % |>PARAMETER:name<|)
215.264 - |>PARAMETER:offset<| = minutes
215.265 - if -1440 < |>PARAMETER:offset<| < 1440:
215.266 - return |>PARAMETER:offset<|
215.267 - raise ValueError("%s()=%d, must be in -1439..1439" % (|>PARAMETER:name<|, |>PARAMETER:offset<|))
215.268 -
215.269 -def |>METHOD:_check_date_fields<|(|>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|):
215.270 - if not MINYEAR <= |>PARAMETER:year<| <= MAXYEAR:
215.271 - raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), |>PARAMETER:year<|)
215.272 - if not 1 <= |>PARAMETER:month<| <= 12:
215.273 - raise ValueError('month must be in 1..12', |>PARAMETER:month<|)
215.274 - dim = _days_in_month(|>PARAMETER:year<|, |>PARAMETER:month<|)
215.275 - if not 1 <= |>PARAMETER:day<| <= dim:
215.276 - raise ValueError('day must be in 1..%d' % dim, |>PARAMETER:day<|)
215.277 -
215.278 -def |>METHOD:_check_time_fields<|(|>PARAMETER:hour<|, |>PARAMETER:minute<|, |>PARAMETER:second<|, |>PARAMETER:microsecond<|):
215.279 - if not 0 <= |>PARAMETER:hour<| <= 23:
215.280 - raise ValueError('hour must be in 0..23', |>PARAMETER:hour<|)
215.281 - if not 0 <= |>PARAMETER:minute<| <= 59:
215.282 - raise ValueError('minute must be in 0..59', |>PARAMETER:minute<|)
215.283 - if not 0 <= |>PARAMETER:second<| <= 59:
215.284 - raise ValueError('second must be in 0..59', |>PARAMETER:second<|)
215.285 - if not 0 <= |>PARAMETER:microsecond<| <= 999999:
215.286 - raise ValueError('microsecond must be in 0..999999', |>PARAMETER:microsecond<|)
215.287 -
215.288 -def |>METHOD:_check_tzinfo_arg<|(|>PARAMETER:tz<|):
215.289 - if |>PARAMETER:tz<| is not None and not isinstance(|>PARAMETER:tz<|, tzinfo):
215.290 - raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
215.291 -
215.292 -
215.293 -# Notes on comparison: In general, datetime module comparison operators raise
215.294 -# TypeError when they don't know how to do a comparison themself. If they
215.295 -# returned NotImplemented instead, comparison could (silently) fall back to
215.296 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
215.297 -# and that's not helpful. There are two exceptions:
215.298 -#
215.299 -# 1. For date and datetime, if the other object has a "timetuple" attr,
215.300 -# NotImplemented is returned. This is a hook to allow other kinds of
215.301 -# datetime-like objects a chance to intercept the comparison.
215.302 -#
215.303 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
215.304 -# so opertaions like
215.305 -#
215.306 -# x == y
215.307 -# x != y
215.308 -# x in sequence
215.309 -# x not in sequence
215.310 -# dict[x] = y
215.311 -#
215.312 -# don't raise annoying TypeErrors just because a datetime object
215.313 -# is part of a heterogeneous collection. If there's no known way to
215.314 -# compare X to a datetime, saying they're not equal is reasonable.
215.315 -
215.316 -def |>METHOD:_cmperror<|(|>PARAMETER:x<|, |>PARAMETER:y<|):
215.317 - raise TypeError("can't compare '%s' to '%s'" % (
215.318 - type(|>PARAMETER:x<|).__name__, type(|>PARAMETER:y<|).__name__))
215.319 -
215.320 -# This is a start at a struct tm workalike. Goals:
215.321 -#
215.322 -# + Works the same way across platforms.
215.323 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
215.324 -#
215.325 -# Note: I suspect it's best if this flavor of tm does *not* try to
215.326 -# second-guess timezones or DST. Instead fold whatever adjustments you want
215.327 -# into the minutes argument (and the constructor will normalize).
215.328 -
215.329 -_ORD1970 = _ymd2ord(1970, 1, 1) # base ordinal for UNIX epoch
215.330 -
215.331 -class tmxxx:
215.332 -
215.333 - ordinal = None
215.334 -
215.335 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|, |>PARAMETER:hour<|=0, |>PARAMETER:minute<|=0, |>PARAMETER:second<|=0,
215.336 - |>PARAMETER:microsecond<|=0):
215.337 - # Normalize all the inputs, and store the normalized values.
215.338 - if not 0 <= |>PARAMETER:microsecond<| <= 999999:
215.339 - carry, |>PARAMETER:microsecond<| = divmod(|>PARAMETER:microsecond<|, 1000000)
215.340 - |>PARAMETER:second<| += carry
215.341 - if not 0 <= |>PARAMETER:second<| <= 59:
215.342 - carry, |>PARAMETER:second<| = divmod(|>PARAMETER:second<|, 60)
215.343 - |>PARAMETER:minute<| += carry
215.344 - if not 0 <= |>PARAMETER:minute<| <= 59:
215.345 - carry, |>PARAMETER:minute<| = divmod(|>PARAMETER:minute<|, 60)
215.346 - |>PARAMETER:hour<| += carry
215.347 - if not 0 <= |>PARAMETER:hour<| <= 23:
215.348 - carry, |>PARAMETER:hour<| = divmod(|>PARAMETER:hour<|, 24)
215.349 - |>PARAMETER:day<| += carry
215.350 -
215.351 - # That was easy. Now it gets muddy: the proper range for day
215.352 - # can't be determined without knowing the correct month and year,
215.353 - # but if day is, e.g., plus or minus a million, the current month
215.354 - # and year values make no sense (and may also be out of bounds
215.355 - # themselves).
215.356 - # Saying 12 months == 1 year should be non-controversial.
215.357 - if not 1 <= |>PARAMETER:month<| <= 12:
215.358 - carry, |>PARAMETER:month<| = divmod(|>PARAMETER:month<|-1, 12)
215.359 - |>PARAMETER:year<| += carry
215.360 - |>PARAMETER:month<| += 1
215.361 - assert 1 <= |>PARAMETER:month<| <= 12
215.362 -
215.363 - # Now only day can be out of bounds (year may also be out of bounds
215.364 - # for a datetime object, but we don't care about that here).
215.365 - # If day is out of bounds, what to do is arguable, but at least the
215.366 - # method here is principled and explainable.
215.367 - dim = _days_in_month(|>PARAMETER:year<|, |>PARAMETER:month<|)
215.368 - if not 1 <= |>PARAMETER:day<| <= dim:
215.369 - # Move day-1 days from the first of the month. First try to
215.370 - # get off cheap if we're only one day out of range (adjustments
215.371 - # for timezone alone can't be worse than that).
215.372 - if |>PARAMETER:day<| == 0: # move back a day
215.373 - |>PARAMETER:month<| -= 1
215.374 - if |>PARAMETER:month<| > 0:
215.375 - |>PARAMETER:day<| = _days_in_month(|>PARAMETER:year<|, |>PARAMETER:month<|)
215.376 - else:
215.377 - |>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<| = |>PARAMETER:year<|-1, 12, 31
215.378 - elif |>PARAMETER:day<| == dim + 1: # move forward a day
215.379 - |>PARAMETER:month<| += 1
215.380 - |>PARAMETER:day<| = 1
215.381 - if |>PARAMETER:month<| > 12:
215.382 - |>PARAMETER:month<| = 1
215.383 - |>PARAMETER:year<| += 1
215.384 - else:
215.385 - |>PARAMETER:self<|.ordinal = _ymd2ord(|>PARAMETER:year<|, |>PARAMETER:month<|, 1) + (|>PARAMETER:day<| - 1)
215.386 - |>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<| = _ord2ymd(|>PARAMETER:self<|.ordinal)
215.387 -
215.388 - |>PARAMETER:self<|.year, |>PARAMETER:self<|.month, |>PARAMETER:self<|.day = |>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|
215.389 - |>PARAMETER:self<|.hour, |>PARAMETER:self<|.minute, |>PARAMETER:self<|.second = |>PARAMETER:hour<|, |>PARAMETER:minute<|, |>PARAMETER:second<|
215.390 - |>PARAMETER:self<|.microsecond = |>PARAMETER:microsecond<|
215.391 -
215.392 - def |>METHOD:toordinal<|(|>PARAMETER:self<|):
215.393 - """Return proleptic Gregorian ordinal for the year, month and day.
215.394 -
215.395 - January 1 of year 1 is day 1. Only the year, month and day values
215.396 - contribute to the result.
215.397 - """
215.398 - if |>PARAMETER:self<|.ordinal is None:
215.399 - |>PARAMETER:self<|.ordinal = _ymd2ord(|>PARAMETER:self<|.year, |>PARAMETER:self<|.month, |>PARAMETER:self<|.day)
215.400 - return |>PARAMETER:self<|.ordinal
215.401 -
215.402 - def |>METHOD:time<|(|>PARAMETER:self<|):
215.403 - "Return Unixish timestamp, as a float (assuming UTC)."
215.404 - days = |>PARAMETER:self<|.toordinal() - _ORD1970 # convert to UNIX epoch
215.405 - seconds = ((days * 24. + |>PARAMETER:self<|.hour)*60. + |>PARAMETER:self<|.minute)*60.
215.406 - return seconds + |>PARAMETER:self<|.second + |>PARAMETER:self<|.microsecond / 1e6
215.407 -
215.408 - def |>METHOD:ctime<|(|>PARAMETER:self<|):
215.409 - "Return ctime() style string."
215.410 - weekday = |>PARAMETER:self<|.toordinal() % 7 or 7
215.411 - return "%s %s %2d %02d:%02d:%02d %04d" % (
215.412 - _DAYNAMES[weekday],
215.413 - _MONTHNAMES[|>PARAMETER:self<|.month],
215.414 - |>PARAMETER:self<|.day,
215.415 - |>PARAMETER:self<|.hour, |>PARAMETER:self<|.minute, |>PARAMETER:self<|.second,
215.416 - |>PARAMETER:self<|.year)
215.417 -
215.418 -class timedelta(object):
215.419 - """Represent the difference between two datetime objects.
215.420 -
215.421 - Supported operators:
215.422 -
215.423 - - add, subtract timedelta
215.424 - - unary plus, minus, abs
215.425 - - compare to timedelta
215.426 - - multiply, divide by int/long
215.427 -
215.428 - In addition, datetime supports subtraction of two datetime objects
215.429 - returning a timedelta, and addition or subtraction of a datetime
215.430 - and a timedelta giving a datetime.
215.431 -
215.432 - Representation: (days, seconds, microseconds). Why? Because I
215.433 - felt like it.
215.434 - """
215.435 -
215.436 - def |>METHOD:__new__<|(|>PARAMETER:cls<|, |>PARAMETER:days<|=0, |>PARAMETER:seconds<|=0, |>PARAMETER:microseconds<|=0,
215.437 - # XXX The following should only be used as keyword args:
215.438 - |>PARAMETER:milliseconds<|=0, |>PARAMETER:minutes<|=0, |>PARAMETER:hours<|=0, |>PARAMETER:weeks<|=0):
215.439 - # Doing this efficiently and accurately in C is going to be difficult
215.440 - # and error-prone, due to ubiquitous overflow possibilities, and that
215.441 - # C double doesn't have enough bits of precision to represent
215.442 - # microseconds over 10K years faithfully. The code here tries to make
215.443 - # explicit where go-fast assumptions can be relied on, in order to
215.444 - # guide the C implementation; it's way more convoluted than speed-
215.445 - # ignoring auto-overflow-to-long idiomatic Python could be.
215.446 -
215.447 - # XXX Check that all inputs are ints, longs or floats.
215.448 -
215.449 - # Final values, all integer.
215.450 - # s and us fit in 32-bit signed ints; d isn't bounded.
215.451 - d = s = us = 0
215.452 -
215.453 - # Normalize everything to days, seconds, microseconds.
215.454 - |>PARAMETER:days<| += |>PARAMETER:weeks<|*7
215.455 - |>PARAMETER:seconds<| += |>PARAMETER:minutes<|*60 + |>PARAMETER:hours<|*3600
215.456 - |>PARAMETER:microseconds<| += |>PARAMETER:milliseconds<|*1000
215.457 -
215.458 - # Get rid of all fractions, and normalize s and us.
215.459 - # Take a deep breath <wink>.
215.460 - if isinstance(|>PARAMETER:days<|, float):
215.461 - dayfrac, |>PARAMETER:days<| = _math.modf(|>PARAMETER:days<|)
215.462 - daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
215.463 - assert daysecondswhole == int(daysecondswhole) # can't overflow
215.464 - s = int(daysecondswhole)
215.465 - assert |>PARAMETER:days<| == long(|>PARAMETER:days<|)
215.466 - d = long(|>PARAMETER:days<|)
215.467 - else:
215.468 - daysecondsfrac = 0.0
215.469 - d = |>PARAMETER:days<|
215.470 - assert isinstance(daysecondsfrac, float)
215.471 - assert abs(daysecondsfrac) <= 1.0
215.472 - assert isinstance(d, (int, long))
215.473 - assert abs(s) <= 24 * 3600
215.474 - # days isn't referenced again before redefinition
215.475 -
215.476 - if isinstance(|>PARAMETER:seconds<|, float):
215.477 - secondsfrac, |>PARAMETER:seconds<| = _math.modf(|>PARAMETER:seconds<|)
215.478 - assert |>PARAMETER:seconds<| == long(|>PARAMETER:seconds<|)
215.479 - |>PARAMETER:seconds<| = long(|>PARAMETER:seconds<|)
215.480 - secondsfrac += daysecondsfrac
215.481 - assert abs(secondsfrac) <= 2.0
215.482 - else:
215.483 - secondsfrac = daysecondsfrac
215.484 - # daysecondsfrac isn't referenced again
215.485 - assert isinstance(secondsfrac, float)
215.486 - assert abs(secondsfrac) <= 2.0
215.487 -
215.488 - assert isinstance(|>PARAMETER:seconds<|, (int, long))
215.489 - |>PARAMETER:days<|, |>PARAMETER:seconds<| = divmod(|>PARAMETER:seconds<|, 24*3600)
215.490 - d += |>PARAMETER:days<|
215.491 - s += int(|>PARAMETER:seconds<|) # can't overflow
215.492 - assert isinstance(s, int)
215.493 - assert abs(s) <= 2 * 24 * 3600
215.494 - # seconds isn't referenced again before redefinition
215.495 -
215.496 - usdouble = secondsfrac * 1e6
215.497 - assert abs(usdouble) < 2.1e6 # exact value not critical
215.498 - # secondsfrac isn't referenced again
215.499 -
215.500 - if isinstance(|>PARAMETER:microseconds<|, float):
215.501 - |>PARAMETER:microseconds<| += usdouble
215.502 - |>PARAMETER:microseconds<| = round(|>PARAMETER:microseconds<|)
215.503 - |>PARAMETER:seconds<|, |>PARAMETER:microseconds<| = divmod(|>PARAMETER:microseconds<|, 1e6)
215.504 - assert |>PARAMETER:microseconds<| == int(|>PARAMETER:microseconds<|)
215.505 - assert |>PARAMETER:seconds<| == long(|>PARAMETER:seconds<|)
215.506 - |>PARAMETER:days<|, |>PARAMETER:seconds<| = divmod(|>PARAMETER:seconds<|, 24.*3600.)
215.507 - assert |>PARAMETER:days<| == long(|>PARAMETER:days<|)
215.508 - assert |>PARAMETER:seconds<| == int(|>PARAMETER:seconds<|)
215.509 - d += long(|>PARAMETER:days<|)
215.510 - s += int(|>PARAMETER:seconds<|) # can't overflow
215.511 - assert isinstance(s, int)
215.512 - assert abs(s) <= 3 * 24 * 3600
215.513 - else:
215.514 - |>PARAMETER:seconds<|, |>PARAMETER:microseconds<| = divmod(|>PARAMETER:microseconds<|, 1000000)
215.515 - |>PARAMETER:days<|, |>PARAMETER:seconds<| = divmod(|>PARAMETER:seconds<|, 24*3600)
215.516 - d += |>PARAMETER:days<|
215.517 - s += int(|>PARAMETER:seconds<|) # can't overflow
215.518 - assert isinstance(s, int)
215.519 - assert abs(s) <= 3 * 24 * 3600
215.520 - |>PARAMETER:microseconds<| = float(|>PARAMETER:microseconds<|)
215.521 - |>PARAMETER:microseconds<| += usdouble
215.522 - |>PARAMETER:microseconds<| = round(|>PARAMETER:microseconds<|)
215.523 - assert abs(s) <= 3 * 24 * 3600
215.524 - assert abs(|>PARAMETER:microseconds<|) < 3.1e6
215.525 -
215.526 - # Just a little bit of carrying possible for microseconds and seconds.
215.527 - assert isinstance(|>PARAMETER:microseconds<|, float)
215.528 - assert int(|>PARAMETER:microseconds<|) == |>PARAMETER:microseconds<|
215.529 - us = int(|>PARAMETER:microseconds<|)
215.530 - |>PARAMETER:seconds<|, us = divmod(us, 1000000)
215.531 - s += |>PARAMETER:seconds<| # cant't overflow
215.532 - assert isinstance(s, int)
215.533 - |>PARAMETER:days<|, s = divmod(s, 24*3600)
215.534 - d += |>PARAMETER:days<|
215.535 -
215.536 - assert isinstance(d, (int, long))
215.537 - assert isinstance(s, int) and 0 <= s < 24*3600
215.538 - assert isinstance(us, int) and 0 <= us < 1000000
215.539 -
215.540 - self = object.__new__(|>PARAMETER:cls<|)
215.541 -
215.542 - self.__days = d
215.543 - self.__seconds = s
215.544 - self.__microseconds = us
215.545 - if abs(d) > 999999999:
215.546 - raise OverflowError("timedelta # of days is too large: %d" % d)
215.547 -
215.548 - return self
215.549 -
215.550 - def |>METHOD:__repr__<|(|>PARAMETER:self<|):
215.551 - if |>PARAMETER:self<|.__microseconds:
215.552 - return "%s(%d, %d, %d)" % ('datetime.' + |>PARAMETER:self<|.__class__.__name__,
215.553 - |>PARAMETER:self<|.__days,
215.554 - |>PARAMETER:self<|.__seconds,
215.555 - |>PARAMETER:self<|.__microseconds)
215.556 - if |>PARAMETER:self<|.__seconds:
215.557 - return "%s(%d, %d)" % ('datetime.' + |>PARAMETER:self<|.__class__.__name__,
215.558 - |>PARAMETER:self<|.__days,
215.559 - |>PARAMETER:self<|.__seconds)
215.560 - return "%s(%d)" % ('datetime.' + |>PARAMETER:self<|.__class__.__name__, |>PARAMETER:self<|.__days)
215.561 -
215.562 - def |>METHOD:__str__<|(|>PARAMETER:self<|):
215.563 - mm, ss = divmod(|>PARAMETER:self<|.__seconds, 60)
215.564 - hh, mm = divmod(mm, 60)
215.565 - s = "%d:%02d:%02d" % (hh, mm, ss)
215.566 - if |>PARAMETER:self<|.__days:
215.567 - def |>METHOD:plural<|(|>PARAMETER:n<|):
215.568 - return |>PARAMETER:n<|, abs(|>PARAMETER:n<|) != 1 and "s" or ""
215.569 - s = ("%d day%s, " % plural(|>PARAMETER:self<|.__days)) + s
215.570 - if |>PARAMETER:self<|.__microseconds:
215.571 - s = s + ".%06d" % |>PARAMETER:self<|.__microseconds
215.572 - return s
215.573 -
215.574 - days = property(lambda self: self.__days, doc="days")
215.575 - seconds = property(lambda self: self.__seconds, doc="seconds")
215.576 - microseconds = property(lambda self: self.__microseconds,
215.577 - doc="microseconds")
215.578 -
215.579 - def |>METHOD:__add__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.580 - if isinstance(|>PARAMETER:other<|, timedelta):
215.581 - return timedelta(|>PARAMETER:self<|.__days + |>PARAMETER:other<|.__days,
215.582 - |>PARAMETER:self<|.__seconds + |>PARAMETER:other<|.__seconds,
215.583 - |>PARAMETER:self<|.__microseconds + |>PARAMETER:other<|.__microseconds)
215.584 - return NotImplemented
215.585 -
215.586 - __radd__ = __add__
215.587 -
215.588 - def |>METHOD:__sub__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.589 - if isinstance(|>PARAMETER:other<|, timedelta):
215.590 - return |>PARAMETER:self<| + -|>PARAMETER:other<|
215.591 - return NotImplemented
215.592 -
215.593 - def |>METHOD:__rsub__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.594 - if isinstance(|>PARAMETER:other<|, timedelta):
215.595 - return -|>PARAMETER:self<| + |>PARAMETER:other<|
215.596 - return NotImplemented
215.597 -
215.598 - def |>METHOD:__neg__<|(|>PARAMETER:self<|):
215.599 - return |>PARAMETER:self<|.__class__(-|>PARAMETER:self<|.__days,
215.600 - -|>PARAMETER:self<|.__seconds,
215.601 - -|>PARAMETER:self<|.__microseconds)
215.602 -
215.603 - def |>METHOD:__pos__<|(|>PARAMETER:self<|):
215.604 - return |>PARAMETER:self<|
215.605 -
215.606 - def |>METHOD:__abs__<|(|>PARAMETER:self<|):
215.607 - if |>PARAMETER:self<|.__days < 0:
215.608 - return -|>PARAMETER:self<|
215.609 - else:
215.610 - return |>PARAMETER:self<|
215.611 -
215.612 - def |>METHOD:__mul__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.613 - if isinstance(|>PARAMETER:other<|, (int, long)):
215.614 - return |>PARAMETER:self<|.__class__(|>PARAMETER:self<|.__days * |>PARAMETER:other<|,
215.615 - |>PARAMETER:self<|.__seconds * |>PARAMETER:other<|,
215.616 - |>PARAMETER:self<|.__microseconds * |>PARAMETER:other<|)
215.617 - return NotImplemented
215.618 -
215.619 - __rmul__ = __mul__
215.620 -
215.621 - def |>METHOD:__div__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.622 - if isinstance(|>PARAMETER:other<|, (int, long)):
215.623 - usec = ((|>PARAMETER:self<|.__days * (24*3600L) + |>PARAMETER:self<|.__seconds) * 1000000 +
215.624 - |>PARAMETER:self<|.__microseconds)
215.625 - return |>PARAMETER:self<|.__class__(0, 0, usec // |>PARAMETER:other<|)
215.626 - return NotImplemented
215.627 -
215.628 - __floordiv__ = __div__
215.629 -
215.630 - # Comparisons.
215.631 -
215.632 - def |>METHOD:__eq__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.633 - if isinstance(|>PARAMETER:other<|, timedelta):
215.634 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) == 0
215.635 - else:
215.636 - return False
215.637 -
215.638 - def |>METHOD:__ne__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.639 - if isinstance(|>PARAMETER:other<|, timedelta):
215.640 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) != 0
215.641 - else:
215.642 - return True
215.643 -
215.644 - def |>METHOD:__le__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.645 - if isinstance(|>PARAMETER:other<|, timedelta):
215.646 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) <= 0
215.647 - else:
215.648 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
215.649 -
215.650 - def |>METHOD:__lt__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.651 - if isinstance(|>PARAMETER:other<|, timedelta):
215.652 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) < 0
215.653 - else:
215.654 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
215.655 -
215.656 - def |>METHOD:__ge__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.657 - if isinstance(|>PARAMETER:other<|, timedelta):
215.658 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) >= 0
215.659 - else:
215.660 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
215.661 -
215.662 - def |>METHOD:__gt__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.663 - if isinstance(|>PARAMETER:other<|, timedelta):
215.664 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) > 0
215.665 - else:
215.666 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
215.667 -
215.668 - def |>METHOD:__cmp<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.669 - assert isinstance(|>PARAMETER:other<|, timedelta)
215.670 - return cmp(|>PARAMETER:self<|.__getstate(), |>PARAMETER:other<|.__getstate())
215.671 -
215.672 - def |>METHOD:__hash__<|(|>PARAMETER:self<|):
215.673 - return hash(|>PARAMETER:self<|.__getstate())
215.674 -
215.675 - def |>METHOD:__nonzero__<|(|>PARAMETER:self<|):
215.676 - return (|>PARAMETER:self<|.__days != 0 or
215.677 - |>PARAMETER:self<|.__seconds != 0 or
215.678 - |>PARAMETER:self<|.__microseconds != 0)
215.679 -
215.680 - # Pickle support.
215.681 -
215.682 - __safe_for_unpickling__ = True # For Python 2.2
215.683 -
215.684 - def |>METHOD:__getstate<|(|>PARAMETER:self<|):
215.685 - return (|>PARAMETER:self<|.__days, |>PARAMETER:self<|.__seconds, |>PARAMETER:self<|.__microseconds)
215.686 -
215.687 - def |>METHOD:__reduce__<|(|>PARAMETER:self<|):
215.688 - return (|>PARAMETER:self<|.__class__, |>PARAMETER:self<|.__getstate())
215.689 -
215.690 -timedelta.min = timedelta(-999999999)
215.691 -timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
215.692 - microseconds=999999)
215.693 -timedelta.resolution = timedelta(microseconds=1)
215.694 -
215.695 -class date(object):
215.696 - """Concrete date type.
215.697 -
215.698 - Constructors:
215.699 -
215.700 - __new__()
215.701 - fromtimestamp()
215.702 - today()
215.703 - fromordinal()
215.704 -
215.705 - Operators:
215.706 -
215.707 - __repr__, __str__
215.708 - __cmp__, __hash__
215.709 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
215.710 -
215.711 - Methods:
215.712 -
215.713 - timetuple()
215.714 - toordinal()
215.715 - weekday()
215.716 - isoweekday(), isocalendar(), isoformat()
215.717 - ctime()
215.718 - strftime()
215.719 -
215.720 - Properties (readonly):
215.721 - year, month, day
215.722 - """
215.723 -
215.724 - def |>METHOD:__new__<|(|>PARAMETER:cls<|, |>PARAMETER:year<|, |>PARAMETER:month<|=None, |>PARAMETER:day<|=None):
215.725 - """Constructor.
215.726 -
215.727 - Arguments:
215.728 -
215.729 - year, month, day (required, base 1)
215.730 - """
215.731 - if isinstance(|>PARAMETER:year<|, str):
215.732 - # Pickle support
215.733 - self = object.__new__(|>PARAMETER:cls<|)
215.734 - self.__setstate((|>PARAMETER:year<|,))
215.735 - return self
215.736 - _check_date_fields(|>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|)
215.737 - self = object.__new__(|>PARAMETER:cls<|)
215.738 - self.__year = |>PARAMETER:year<|
215.739 - self.__month = |>PARAMETER:month<|
215.740 - self.__day = |>PARAMETER:day<|
215.741 - return self
215.742 -
215.743 - # Additional constructors
215.744 -
215.745 - def |>METHOD:fromtimestamp<|(|>PARAMETER:cls<|, |>PARAMETER:t<|):
215.746 - "Construct a date from a POSIX timestamp (like time.time())."
215.747 - y, m, d, |>UNUSED:hh<|, |>UNUSED:mm<|, |>UNUSED:ss<|, |>UNUSED:weekday<|, |>UNUSED:jday<|, |>UNUSED:dst<| = _time.localtime(|>PARAMETER:t<|)
215.748 - return |>PARAMETER:cls<|(y, m, d)
215.749 - fromtimestamp = classmethod(fromtimestamp)
215.750 -
215.751 - def |>METHOD:today<|(|>PARAMETER:cls<|):
215.752 - "Construct a date from time.time()."
215.753 - t = _time.time()
215.754 - return |>PARAMETER:cls<|.fromtimestamp(t)
215.755 - today = classmethod(today)
215.756 -
215.757 - def |>METHOD:fromordinal<|(|>PARAMETER:cls<|, |>PARAMETER:n<|):
215.758 - """Contruct a date from a proleptic Gregorian ordinal.
215.759 -
215.760 - January 1 of year 1 is day 1. Only the year, month and day are
215.761 - non-zero in the result.
215.762 - """
215.763 - y, m, d = _ord2ymd(|>PARAMETER:n<|)
215.764 - return |>PARAMETER:cls<|(y, m, d)
215.765 - fromordinal = classmethod(fromordinal)
215.766 -
215.767 - # Conversions to string
215.768 -
215.769 - def |>METHOD:__repr__<|(|>PARAMETER:self<|):
215.770 - "Convert to formal string, for repr()."
215.771 - return "%s(%d, %d, %d)" % ('datetime.' + |>PARAMETER:self<|.__class__.__name__,
215.772 - |>PARAMETER:self<|.__year,
215.773 - |>PARAMETER:self<|.__month,
215.774 - |>PARAMETER:self<|.__day)
215.775 - # XXX These shouldn't depend on time.localtime(), because that
215.776 - # clips the usable dates to [1970 .. 2038). At least ctime() is
215.777 - # easily done without using strftime() -- that's better too because
215.778 - # strftime("%c", ...) is locale specific.
215.779 -
215.780 - def |>METHOD:ctime<|(|>PARAMETER:self<|):
215.781 - "Format a la ctime()."
215.782 - return tmxxx(|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day).ctime()
215.783 -
215.784 - def |>METHOD:strftime<|(|>PARAMETER:self<|, |>PARAMETER:fmt<|):
215.785 - "Format using strftime()."
215.786 - return _wrap_strftime(|>PARAMETER:self<|, |>PARAMETER:fmt<|, |>PARAMETER:self<|.timetuple())
215.787 -
215.788 - def |>METHOD:isoformat<|(|>PARAMETER:self<|):
215.789 - """Return the date formatted according to ISO.
215.790 -
215.791 - This is 'YYYY-MM-DD'.
215.792 -
215.793 - References:
215.794 - - http://www.w3.org/TR/NOTE-datetime
215.795 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
215.796 - """
215.797 - return "%04d-%02d-%02d" % (|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day)
215.798 -
215.799 - __str__ = isoformat
215.800 -
215.801 - # Read-only field accessors
215.802 - year = property(lambda self: self.__year,
215.803 - doc="year (%d-%d)" % (MINYEAR, MAXYEAR))
215.804 - month = property(lambda self: self.__month, doc="month (1-12)")
215.805 - day = property(lambda self: self.__day, doc="day (1-31)")
215.806 -
215.807 - # Standard conversions, __cmp__, __hash__ (and helpers)
215.808 -
215.809 - def |>METHOD:timetuple<|(|>PARAMETER:self<|):
215.810 - "Return local time tuple compatible with time.localtime()."
215.811 - return _build_struct_time(|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day,
215.812 - 0, 0, 0, -1)
215.813 -
215.814 - def |>METHOD:toordinal<|(|>PARAMETER:self<|):
215.815 - """Return proleptic Gregorian ordinal for the year, month and day.
215.816 -
215.817 - January 1 of year 1 is day 1. Only the year, month and day values
215.818 - contribute to the result.
215.819 - """
215.820 - return _ymd2ord(|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day)
215.821 -
215.822 - def |>METHOD:replace<|(|>PARAMETER:self<|, |>PARAMETER:year<|=None, |>PARAMETER:month<|=None, |>PARAMETER:day<|=None):
215.823 - """Return a new date with new values for the specified fields."""
215.824 - if |>PARAMETER:year<| is None:
215.825 - |>PARAMETER:year<| = |>PARAMETER:self<|.__year
215.826 - if |>PARAMETER:month<| is None:
215.827 - |>PARAMETER:month<| = |>PARAMETER:self<|.__month
215.828 - if |>PARAMETER:day<| is None:
215.829 - |>PARAMETER:day<| = |>PARAMETER:self<|.__day
215.830 - _check_date_fields(|>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|)
215.831 - return date(|>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|)
215.832 -
215.833 - # Comparisons.
215.834 -
215.835 - def |>METHOD:__eq__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.836 - if isinstance(|>PARAMETER:other<|, date):
215.837 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) == 0
215.838 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
215.839 - return NotImplemented
215.840 - else:
215.841 - return False
215.842 -
215.843 - def |>METHOD:__ne__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.844 - if isinstance(|>PARAMETER:other<|, date):
215.845 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) != 0
215.846 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
215.847 - return NotImplemented
215.848 - else:
215.849 - return True
215.850 -
215.851 - def |>METHOD:__le__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.852 - if isinstance(|>PARAMETER:other<|, date):
215.853 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) <= 0
215.854 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
215.855 - return NotImplemented
215.856 - else:
215.857 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
215.858 -
215.859 - def |>METHOD:__lt__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.860 - if isinstance(|>PARAMETER:other<|, date):
215.861 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) < 0
215.862 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
215.863 - return NotImplemented
215.864 - else:
215.865 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
215.866 -
215.867 - def |>METHOD:__ge__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.868 - if isinstance(|>PARAMETER:other<|, date):
215.869 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) >= 0
215.870 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
215.871 - return NotImplemented
215.872 - else:
215.873 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
215.874 -
215.875 - def |>METHOD:__gt__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.876 - if isinstance(|>PARAMETER:other<|, date):
215.877 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) > 0
215.878 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
215.879 - return NotImplemented
215.880 - else:
215.881 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
215.882 -
215.883 - def |>METHOD:__cmp<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.884 - assert isinstance(|>PARAMETER:other<|, date)
215.885 - y, m, d = |>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day
215.886 - y2, m2, d2 = |>PARAMETER:other<|.__year, |>PARAMETER:other<|.__month, |>PARAMETER:other<|.__day
215.887 - return cmp((y, m, d), (y2, m2, d2))
215.888 -
215.889 - def |>METHOD:__hash__<|(|>PARAMETER:self<|):
215.890 - "Hash."
215.891 - return hash(|>PARAMETER:self<|.__getstate())
215.892 -
215.893 - # Computations
215.894 -
215.895 - def |>METHOD:_checkOverflow<|(|>PARAMETER,UNUSED:self<|, |>PARAMETER:year<|):
215.896 - if not MINYEAR <= |>PARAMETER:year<| <= MAXYEAR:
215.897 - raise OverflowError("date +/-: result year %d not in %d..%d" %
215.898 - (|>PARAMETER:year<|, MINYEAR, MAXYEAR))
215.899 -
215.900 - def |>METHOD:__add__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.901 - "Add a date to a timedelta."
215.902 - if isinstance(|>PARAMETER:other<|, timedelta):
215.903 - t = tmxxx(|>PARAMETER:self<|.__year,
215.904 - |>PARAMETER:self<|.__month,
215.905 - |>PARAMETER:self<|.__day + |>PARAMETER:other<|.days)
215.906 - |>PARAMETER:self<|._checkOverflow(t.year)
215.907 - result = |>PARAMETER:self<|.__class__(t.year, t.month, t.day)
215.908 - return result
215.909 - return NotImplemented
215.910 -
215.911 - __radd__ = __add__
215.912 -
215.913 - def |>METHOD:__sub__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.914 - """Subtract two dates, or a date and a timedelta."""
215.915 - if isinstance(|>PARAMETER:other<|, timedelta):
215.916 - return |>PARAMETER:self<| + timedelta(-|>PARAMETER:other<|.days)
215.917 - if isinstance(|>PARAMETER:other<|, date):
215.918 - days1 = |>PARAMETER:self<|.toordinal()
215.919 - days2 = |>PARAMETER:other<|.toordinal()
215.920 - return timedelta(days1 - days2)
215.921 - return NotImplemented
215.922 -
215.923 - def |>METHOD:weekday<|(|>PARAMETER:self<|):
215.924 - "Return day of the week, where Monday == 0 ... Sunday == 6."
215.925 - return (|>PARAMETER:self<|.toordinal() + 6) % 7
215.926 -
215.927 - # Day-of-the-week and week-of-the-year, according to ISO
215.928 -
215.929 - def |>METHOD:isoweekday<|(|>PARAMETER:self<|):
215.930 - "Return day of the week, where Monday == 1 ... Sunday == 7."
215.931 - # 1-Jan-0001 is a Monday
215.932 - return |>PARAMETER:self<|.toordinal() % 7 or 7
215.933 -
215.934 - def |>METHOD:isocalendar<|(|>PARAMETER:self<|):
215.935 - """Return a 3-tuple containing ISO year, week number, and weekday.
215.936 -
215.937 - The first ISO week of the year is the (Mon-Sun) week
215.938 - containing the year's first Thursday; everything else derives
215.939 - from that.
215.940 -
215.941 - The first week is 1; Monday is 1 ... Sunday is 7.
215.942 -
215.943 - ISO calendar algorithm taken from
215.944 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
215.945 - """
215.946 - year = |>PARAMETER:self<|.__year
215.947 - week1monday = _isoweek1monday(year)
215.948 - today = _ymd2ord(|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day)
215.949 - # Internally, week and day have origin 0
215.950 - week, day = divmod(today - week1monday, 7)
215.951 - if week < 0:
215.952 - year -= 1
215.953 - week1monday = _isoweek1monday(year)
215.954 - week, day = divmod(today - week1monday, 7)
215.955 - elif week >= 52:
215.956 - if today >= _isoweek1monday(year+1):
215.957 - year += 1
215.958 - week = 0
215.959 - return year, week+1, day+1
215.960 -
215.961 - # Pickle support.
215.962 -
215.963 - __safe_for_unpickling__ = True # For Python 2.2
215.964 -
215.965 - def |>METHOD:__getstate<|(|>PARAMETER:self<|):
215.966 - yhi, ylo = divmod(|>PARAMETER:self<|.__year, 256)
215.967 - return ("%c%c%c%c" % (yhi, ylo, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day), )
215.968 -
215.969 - def |>METHOD:__setstate<|(|>PARAMETER:self<|, |>PARAMETER:t<|):
215.970 - assert isinstance(|>PARAMETER:t<|, tuple) and len(|>PARAMETER:t<|) == 1, `|>PARAMETER:t<|`
215.971 - string = |>PARAMETER:t<|[0]
215.972 - assert len(string) == 4
215.973 - yhi, ylo, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day = map(ord, string)
215.974 - |>PARAMETER:self<|.__year = yhi * 256 + ylo
215.975 -
215.976 - def |>METHOD:__reduce__<|(|>PARAMETER:self<|):
215.977 - return (|>PARAMETER:self<|.__class__, |>PARAMETER:self<|.__getstate())
215.978 -
215.979 -_date_class = date # so functions w/ args named "date" can get at the class
215.980 -
215.981 -date.min = date(1, 1, 1)
215.982 -date.max = date(9999, 12, 31)
215.983 -date.resolution = timedelta(days=1)
215.984 -
215.985 -class tzinfo(object):
215.986 - """Abstract base class for time zone info classes.
215.987 -
215.988 - Subclasses must override the name(), utcoffset() and dst() methods.
215.989 - """
215.990 -
215.991 - def |>METHOD:tzname<|(|>PARAMETER,UNUSED:self<|, |>PARAMETER,UNUSED:dt<|):
215.992 - "datetime -> string name of time zone."
215.993 - raise NotImplementedError("tzinfo subclass must override tzname()")
215.994 -
215.995 - def |>METHOD:utcoffset<|(|>PARAMETER,UNUSED:self<|, |>PARAMETER,UNUSED:dt<|):
215.996 - "datetime -> minutes east of UTC (negative for west of UTC)"
215.997 - raise NotImplementedError("tzinfo subclass must override utcoffset()")
215.998 -
215.999 - def |>METHOD:dst<|(|>PARAMETER,UNUSED:self<|, |>PARAMETER,UNUSED:dt<|):
215.1000 - """datetime -> DST offset in minutes east of UTC.
215.1001 -
215.1002 - Return 0 if DST not in effect. utcoffset() must include the DST
215.1003 - offset.
215.1004 - """
215.1005 - raise NotImplementedError("tzinfo subclass must override dst()")
215.1006 -
215.1007 - def |>METHOD:fromutc<|(|>PARAMETER:self<|, |>PARAMETER:dt<|):
215.1008 - "datetime in UTC -> datetime in local time."
215.1009 -
215.1010 - if not isinstance(|>PARAMETER:dt<|, datetime):
215.1011 - raise TypeError("fromutc() requires a datetime argument")
215.1012 - if |>PARAMETER:dt<|.tzinfo is not |>PARAMETER:self<|:
215.1013 - raise ValueError("dt.tzinfo is not self")
215.1014 -
215.1015 - dtoff = |>PARAMETER:dt<|.utcoffset()
215.1016 - if dtoff is None:
215.1017 - raise ValueError("fromutc() requires a non-None utcoffset() "
215.1018 - "result")
215.1019 -
215.1020 - # See the long comment block at the end of this file for an
215.1021 - # explanation of this algorithm.
215.1022 - dtdst = |>PARAMETER:dt<|.dst()
215.1023 - if dtdst is None:
215.1024 - raise ValueError("fromutc() requires a non-None dst() result")
215.1025 - delta = dtoff - dtdst
215.1026 - if delta:
215.1027 - |>PARAMETER:dt<| += delta
215.1028 - dtdst = |>PARAMETER:dt<|.dst()
215.1029 - if dtdst is None:
215.1030 - raise ValueError("fromutc(): dt.dst gave inconsistent "
215.1031 - "results; cannot convert")
215.1032 - if dtdst:
215.1033 - return |>PARAMETER:dt<| + dtdst
215.1034 - else:
215.1035 - return |>PARAMETER:dt<|
215.1036 -
215.1037 - # Pickle support.
215.1038 -
215.1039 - __safe_for_unpickling__ = True # For Python 2.2
215.1040 -
215.1041 - def |>METHOD:__reduce__<|(|>PARAMETER:self<|):
215.1042 - getinitargs = getattr(|>PARAMETER:self<|, "__getinitargs__", None)
215.1043 - if getinitargs:
215.1044 - args = getinitargs()
215.1045 - else:
215.1046 - args = ()
215.1047 - getstate = getattr(|>PARAMETER:self<|, "__getstate__", None)
215.1048 - if getstate:
215.1049 - state = getstate()
215.1050 - else:
215.1051 - state = getattr(|>PARAMETER:self<|, "__dict__", None) or None
215.1052 - if state is None:
215.1053 - return (|>PARAMETER:self<|.__class__, args)
215.1054 - else:
215.1055 - return (|>PARAMETER:self<|.__class__, args, state)
215.1056 -
215.1057 -_tzinfo_class = tzinfo # so functions w/ args named "tinfo" can get at it
215.1058 -
215.1059 -class time(object):
215.1060 - """Time with time zone.
215.1061 -
215.1062 - Constructors:
215.1063 -
215.1064 - __new__()
215.1065 -
215.1066 - Operators:
215.1067 -
215.1068 - __repr__, __str__
215.1069 - __cmp__, __hash__
215.1070 -
215.1071 - Methods:
215.1072 -
215.1073 - strftime()
215.1074 - isoformat()
215.1075 - utcoffset()
215.1076 - tzname()
215.1077 - dst()
215.1078 -
215.1079 - Properties (readonly):
215.1080 - hour, minute, second, microsecond, tzinfo
215.1081 - """
215.1082 -
215.1083 - def |>METHOD:__new__<|(|>PARAMETER:cls<|, |>PARAMETER:hour<|=0, |>PARAMETER:minute<|=0, |>PARAMETER:second<|=0, |>PARAMETER:microsecond<|=0, |>PARAMETER:tzinfo<|=None):
215.1084 - """Constructor.
215.1085 -
215.1086 - Arguments:
215.1087 -
215.1088 - hour, minute (required)
215.1089 - second, microsecond (default to zero)
215.1090 - tzinfo (default to None)
215.1091 - """
215.1092 - self = object.__new__(|>PARAMETER:cls<|)
215.1093 - if isinstance(|>PARAMETER:hour<|, str):
215.1094 - # Pickle support
215.1095 - self.__setstate((|>PARAMETER:hour<|, |>PARAMETER:minute<| or None))
215.1096 - return self
215.1097 - _check_tzinfo_arg(|>PARAMETER:tzinfo<|)
215.1098 - _check_time_fields(|>PARAMETER:hour<|, |>PARAMETER:minute<|, |>PARAMETER:second<|, |>PARAMETER:microsecond<|)
215.1099 - self.__hour = |>PARAMETER:hour<|
215.1100 - self.__minute = |>PARAMETER:minute<|
215.1101 - self.__second = |>PARAMETER:second<|
215.1102 - self.__microsecond = |>PARAMETER:microsecond<|
215.1103 - self._tzinfo = |>PARAMETER:tzinfo<|
215.1104 - return self
215.1105 -
215.1106 - # Read-only field accessors
215.1107 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
215.1108 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
215.1109 - second = property(lambda self: self.__second, doc="second (0-59)")
215.1110 - microsecond = property(lambda self: self.__microsecond,
215.1111 - doc="microsecond (0-999999)")
215.1112 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
215.1113 -
215.1114 - # Standard conversions, __hash__ (and helpers)
215.1115 -
215.1116 - # Comparisons.
215.1117 -
215.1118 - def |>METHOD:__eq__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.1119 - if isinstance(|>PARAMETER:other<|, time):
215.1120 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) == 0
215.1121 - else:
215.1122 - return False
215.1123 -
215.1124 - def |>METHOD:__ne__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.1125 - if isinstance(|>PARAMETER:other<|, time):
215.1126 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) != 0
215.1127 - else:
215.1128 - return True
215.1129 -
215.1130 - def |>METHOD:__le__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.1131 - if isinstance(|>PARAMETER:other<|, time):
215.1132 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) <= 0
215.1133 - else:
215.1134 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
215.1135 -
215.1136 - def |>METHOD:__lt__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.1137 - if isinstance(|>PARAMETER:other<|, time):
215.1138 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) < 0
215.1139 - else:
215.1140 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
215.1141 -
215.1142 - def |>METHOD:__ge__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.1143 - if isinstance(|>PARAMETER:other<|, time):
215.1144 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) >= 0
215.1145 - else:
215.1146 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
215.1147 -
215.1148 - def |>METHOD:__gt__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.1149 - if isinstance(|>PARAMETER:other<|, time):
215.1150 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) > 0
215.1151 - else:
215.1152 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
215.1153 -
215.1154 - def |>METHOD:__cmp<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.1155 - assert isinstance(|>PARAMETER:other<|, time)
215.1156 - mytz = |>PARAMETER:self<|._tzinfo
215.1157 - ottz = |>PARAMETER:other<|._tzinfo
215.1158 - myoff = otoff = None
215.1159 -
215.1160 - if mytz is ottz:
215.1161 - base_compare = True
215.1162 - else:
215.1163 - myoff = |>PARAMETER:self<|._utcoffset()
215.1164 - otoff = |>PARAMETER:other<|._utcoffset()
215.1165 - base_compare = myoff == otoff
215.1166 -
215.1167 - if base_compare:
215.1168 - return cmp((|>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second,
215.1169 - |>PARAMETER:self<|.__microsecond),
215.1170 - (|>PARAMETER:other<|.__hour, |>PARAMETER:other<|.__minute, |>PARAMETER:other<|.__second,
215.1171 - |>PARAMETER:other<|.__microsecond))
215.1172 - if myoff is None or otoff is None:
215.1173 - # XXX Buggy in 2.2.2.
215.1174 - raise TypeError("cannot compare naive and aware times")
215.1175 - myhhmm = |>PARAMETER:self<|.__hour * 60 + |>PARAMETER:self<|.__minute - myoff
215.1176 - othhmm = |>PARAMETER:other<|.__hour * 60 + |>PARAMETER:other<|.__minute - otoff
215.1177 - return cmp((myhhmm, |>PARAMETER:self<|.__second, |>PARAMETER:self<|.__microsecond),
215.1178 - (othhmm, |>PARAMETER:other<|.__second, |>PARAMETER:other<|.__microsecond))
215.1179 -
215.1180 - def |>METHOD:__hash__<|(|>PARAMETER:self<|):
215.1181 - """Hash."""
215.1182 - tzoff = |>PARAMETER:self<|._utcoffset()
215.1183 - if not tzoff: # zero or None
215.1184 - return hash(|>PARAMETER:self<|.__getstate()[0])
215.1185 - h, m = divmod(|>PARAMETER:self<|.hour * 60 + |>PARAMETER:self<|.minute - tzoff, 60)
215.1186 - if 0 <= h < 24:
215.1187 - return hash(time(h, m, |>PARAMETER:self<|.second, |>PARAMETER:self<|.microsecond))
215.1188 - return hash((h, m, |>PARAMETER:self<|.second, |>PARAMETER:self<|.microsecond))
215.1189 -
215.1190 - # Conversion to string
215.1191 -
215.1192 - def |>METHOD:_tzstr<|(|>PARAMETER:self<|, |>PARAMETER:sep<|=":"):
215.1193 - """Return formatted timezone offset (+xx:xx) or None."""
215.1194 - off = |>PARAMETER:self<|._utcoffset()
215.1195 - if off is not None:
215.1196 - if off < 0:
215.1197 - sign = "-"
215.1198 - off = -off
215.1199 - else:
215.1200 - sign = "+"
215.1201 - hh, mm = divmod(off, 60)
215.1202 - assert 0 <= hh < 24
215.1203 - off = "%s%02d%s%02d" % (sign, hh, |>PARAMETER:sep<|, mm)
215.1204 - return off
215.1205 -
215.1206 - def |>METHOD:__repr__<|(|>PARAMETER:self<|):
215.1207 - """Convert to formal string, for repr()."""
215.1208 - if |>PARAMETER:self<|.__microsecond != 0:
215.1209 - s = ", %d, %d" % (|>PARAMETER:self<|.__second, |>PARAMETER:self<|.__microsecond)
215.1210 - elif |>PARAMETER:self<|.__second != 0:
215.1211 - s = ", %d" % |>PARAMETER:self<|.__second
215.1212 - else:
215.1213 - s = ""
215.1214 - s= "%s(%d, %d%s)" % ('datetime.' + |>PARAMETER:self<|.__class__.__name__,
215.1215 - |>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, s)
215.1216 - if |>PARAMETER:self<|._tzinfo is not None:
215.1217 - assert s[-1:] == ")"
215.1218 - s = s[:-1] + ", tzinfo=%r" % |>PARAMETER:self<|._tzinfo + ")"
215.1219 - return s
215.1220 -
215.1221 - def |>METHOD:isoformat<|(|>PARAMETER:self<|):
215.1222 - """Return the time formatted according to ISO.
215.1223 -
215.1224 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
215.1225 - self.microsecond == 0.
215.1226 - """
215.1227 - s = _format_time(|>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second,
215.1228 - |>PARAMETER:self<|.__microsecond)
215.1229 - tz = |>PARAMETER:self<|._tzstr()
215.1230 - if tz:
215.1231 - s += tz
215.1232 - return s
215.1233 -
215.1234 - __str__ = isoformat
215.1235 -
215.1236 - def |>METHOD:strftime<|(|>PARAMETER:self<|, |>PARAMETER:fmt<|):
215.1237 - """Format using strftime(). The date part of the timestamp passed
215.1238 - to underlying strftime should not be used.
215.1239 - """
215.1240 - # The year must be >= 1900 else Python's strftime implementation
215.1241 - # can raise a bogus exception.
215.1242 - timetuple = (1900, 1, 1,
215.1243 - |>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second,
215.1244 - 0, 1, -1)
215.1245 - return _wrap_strftime(|>PARAMETER:self<|, |>PARAMETER:fmt<|, timetuple)
215.1246 -
215.1247 - # Timezone functions
215.1248 -
215.1249 - def |>METHOD:utcoffset<|(|>PARAMETER:self<|):
215.1250 - """Return the timezone offset in minutes east of UTC (negative west of
215.1251 - UTC)."""
215.1252 - offset = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "utcoffset", None)
215.1253 - offset = _check_utc_offset("utcoffset", offset)
215.1254 - if offset is not None:
215.1255 - offset = timedelta(minutes=offset)
215.1256 - return offset
215.1257 -
215.1258 - # Return an integer (or None) instead of a timedelta (or None).
215.1259 - def |>METHOD:_utcoffset<|(|>PARAMETER:self<|):
215.1260 - offset = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "utcoffset", None)
215.1261 - offset = _check_utc_offset("utcoffset", offset)
215.1262 - return offset
215.1263 -
215.1264 - def |>METHOD:tzname<|(|>PARAMETER:self<|):
215.1265 - """Return the timezone name.
215.1266 -
215.1267 - Note that the name is 100% informational -- there's no requirement that
215.1268 - it mean anything in particular. For example, "GMT", "UTC", "-500",
215.1269 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
215.1270 - """
215.1271 - name = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "tzname", None)
215.1272 - _check_tzname(name)
215.1273 - return name
215.1274 -
215.1275 - def |>METHOD:dst<|(|>PARAMETER:self<|):
215.1276 - """Return 0 if DST is not in effect, or the DST offset (in minutes
215.1277 - eastward) if DST is in effect.
215.1278 -
215.1279 - This is purely informational; the DST offset has already been added to
215.1280 - the UTC offset returned by utcoffset() if applicable, so there's no
215.1281 - need to consult dst() unless you're interested in displaying the DST
215.1282 - info.
215.1283 - """
215.1284 - offset = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "dst", None)
215.1285 - offset = _check_utc_offset("dst", offset)
215.1286 - if offset is not None:
215.1287 - offset = timedelta(minutes=offset)
215.1288 - return offset
215.1289 -
215.1290 - def |>METHOD:replace<|(|>PARAMETER:self<|, |>PARAMETER:hour<|=None, |>PARAMETER:minute<|=None, |>PARAMETER:second<|=None, |>PARAMETER:microsecond<|=None,
215.1291 - |>PARAMETER:tzinfo<|=True):
215.1292 - """Return a new time with new values for the specified fields."""
215.1293 - if |>PARAMETER:hour<| is None:
215.1294 - |>PARAMETER:hour<| = |>PARAMETER:self<|.hour
215.1295 - if |>PARAMETER:minute<| is None:
215.1296 - |>PARAMETER:minute<| = |>PARAMETER:self<|.minute
215.1297 - if |>PARAMETER:second<| is None:
215.1298 - |>PARAMETER:second<| = |>PARAMETER:self<|.second
215.1299 - if |>PARAMETER:microsecond<| is None:
215.1300 - |>PARAMETER:microsecond<| = |>PARAMETER:self<|.microsecond
215.1301 - if |>PARAMETER:tzinfo<| is True:
215.1302 - |>PARAMETER:tzinfo<| = |>PARAMETER:self<|.tzinfo
215.1303 - _check_time_fields(|>PARAMETER:hour<|, |>PARAMETER:minute<|, |>PARAMETER:second<|, |>PARAMETER:microsecond<|)
215.1304 - _check_tzinfo_arg(|>PARAMETER:tzinfo<|)
215.1305 - return time(|>PARAMETER:hour<|, |>PARAMETER:minute<|, |>PARAMETER:second<|, |>PARAMETER:microsecond<|, |>PARAMETER:tzinfo<|)
215.1306 -
215.1307 - # Return an integer (or None) instead of a timedelta (or None).
215.1308 - def |>METHOD:_dst<|(|>PARAMETER:self<|):
215.1309 - offset = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "dst", None)
215.1310 - offset = _check_utc_offset("dst", offset)
215.1311 - return offset
215.1312 -
215.1313 - def |>METHOD:__nonzero__<|(|>PARAMETER:self<|):
215.1314 - if |>PARAMETER:self<|.second or |>PARAMETER:self<|.microsecond:
215.1315 - return 1
215.1316 - offset = |>PARAMETER:self<|._utcoffset() or 0
215.1317 - return |>PARAMETER:self<|.hour * 60 + |>PARAMETER:self<|.minute - offset != 0
215.1318 -
215.1319 - # Pickle support.
215.1320 -
215.1321 - __safe_for_unpickling__ = True # For Python 2.2
215.1322 -
215.1323 - def |>METHOD:__getstate<|(|>PARAMETER:self<|):
215.1324 - us2, us3 = divmod(|>PARAMETER:self<|.__microsecond, 256)
215.1325 - us1, us2 = divmod(us2, 256)
215.1326 - basestate = ("%c" * 6) % (|>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second,
215.1327 - us1, us2, us3)
215.1328 - if |>PARAMETER:self<|._tzinfo is None:
215.1329 - return (basestate,)
215.1330 - else:
215.1331 - return (basestate, |>PARAMETER:self<|._tzinfo)
215.1332 -
215.1333 - def |>METHOD:__setstate<|(|>PARAMETER:self<|, |>PARAMETER:state<|):
215.1334 - assert isinstance(|>PARAMETER:state<|, tuple)
215.1335 - assert 1 <= len(|>PARAMETER:state<|) <= 2
215.1336 - string = |>PARAMETER:state<|[0]
215.1337 - assert len(string) == 6
215.1338 - |>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second, us1, us2, us3 = \
215.1339 - map(ord, string)
215.1340 - |>PARAMETER:self<|.__microsecond = (((us1 << 8) | us2) << 8) | us3
215.1341 - if len(|>PARAMETER:state<|) == 1:
215.1342 - |>PARAMETER:self<|._tzinfo = None
215.1343 - else:
215.1344 - |>PARAMETER:self<|._tzinfo = |>PARAMETER:state<|[1]
215.1345 -
215.1346 - def |>METHOD:__reduce__<|(|>PARAMETER:self<|):
215.1347 - return (|>PARAMETER:self<|.__class__, |>PARAMETER:self<|.__getstate())
215.1348 -
215.1349 -_time_class = time # so functions w/ args named "time" can get at the class
215.1350 -
215.1351 -time.min = time(0, 0, 0)
215.1352 -time.max = time(23, 59, 59, 999999)
215.1353 -time.resolution = timedelta(microseconds=1)
215.1354 -
215.1355 -class datetime(date):
215.1356 -
215.1357 - # XXX needs docstrings
215.1358 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
215.1359 -
215.1360 - def |>METHOD:__new__<|(|>PARAMETER:cls<|, |>PARAMETER:year<|, |>PARAMETER:month<|=None, |>PARAMETER:day<|=None, |>PARAMETER:hour<|=0, |>PARAMETER:minute<|=0, |>PARAMETER:second<|=0,
215.1361 - |>PARAMETER:microsecond<|=0, |>PARAMETER:tzinfo<|=None):
215.1362 - if isinstance(|>PARAMETER:year<|, str):
215.1363 - # Pickle support
215.1364 - self = date.__new__(|>PARAMETER:cls<|, |>PARAMETER:year<|[:4])
215.1365 - self.__setstate((|>PARAMETER:year<|, |>PARAMETER:month<|))
215.1366 - return self
215.1367 - _check_tzinfo_arg(|>PARAMETER:tzinfo<|)
215.1368 - _check_time_fields(|>PARAMETER:hour<|, |>PARAMETER:minute<|, |>PARAMETER:second<|, |>PARAMETER:microsecond<|)
215.1369 - self = date.__new__(|>PARAMETER:cls<|, |>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|)
215.1370 - # XXX This duplicates __year, __month, __day for convenience :-(
215.1371 - self.__year = |>PARAMETER:year<|
215.1372 - self.__month = |>PARAMETER:month<|
215.1373 - self.__day = |>PARAMETER:day<|
215.1374 - self.__hour = |>PARAMETER:hour<|
215.1375 - self.__minute = |>PARAMETER:minute<|
215.1376 - self.__second = |>PARAMETER:second<|
215.1377 - self.__microsecond = |>PARAMETER:microsecond<|
215.1378 - self._tzinfo = |>PARAMETER:tzinfo<|
215.1379 - return self
215.1380 -
215.1381 - # Read-only field accessors
215.1382 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
215.1383 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
215.1384 - second = property(lambda self: self.__second, doc="second (0-59)")
215.1385 - microsecond = property(lambda self: self.__microsecond,
215.1386 - doc="microsecond (0-999999)")
215.1387 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
215.1388 -
215.1389 - def |>METHOD:fromtimestamp<|(|>PARAMETER:cls<|, |>PARAMETER:t<|, |>PARAMETER:tz<|=None):
215.1390 - """Construct a datetime from a POSIX timestamp (like time.time()).
215.1391 -
215.1392 - A timezone info object may be passed in as well.
215.1393 - """
215.1394 -
215.1395 - _check_tzinfo_arg(|>PARAMETER:tz<|)
215.1396 - if |>PARAMETER:tz<| is None:
215.1397 - converter = _time.localtime
215.1398 - else:
215.1399 - converter = _time.gmtime
215.1400 - y, m, d, hh, mm, ss, |>UNUSED:weekday<|, |>UNUSED:jday<|, |>UNUSED:dst<| = converter(|>PARAMETER:t<|)
215.1401 - us = int((|>PARAMETER:t<| % 1.0) * 1000000)
215.1402 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
215.1403 - result = |>PARAMETER:cls<|(y, m, d, hh, mm, ss, us, |>PARAMETER:tz<|)
215.1404 - if |>PARAMETER:tz<| is not None:
215.1405 - result = |>PARAMETER:tz<|.fromutc(result)
215.1406 - return result
215.1407 - fromtimestamp = classmethod(fromtimestamp)
215.1408 -
215.1409 - def |>METHOD:utcfromtimestamp<|(|>PARAMETER:cls<|, |>PARAMETER:t<|):
215.1410 - "Construct a UTC datetime from a POSIX timestamp (like time.time())."
215.1411 - y, m, d, hh, mm, ss, |>UNUSED:weekday<|, |>UNUSED:jday<|, |>UNUSED:dst<| = _time.gmtime(|>PARAMETER:t<|)
215.1412 - us = int((|>PARAMETER:t<| % 1.0) * 1000000)
215.1413 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
215.1414 - return |>PARAMETER:cls<|(y, m, d, hh, mm, ss, us)
215.1415 - utcfromtimestamp = classmethod(utcfromtimestamp)
215.1416 -
215.1417 - # XXX This is supposed to do better than we *can* do by using time.time(),
215.1418 - # XXX if the platform supports a more accurate way. The C implementation
215.1419 - # XXX uses gettimeofday on platforms that have it, but that isn't
215.1420 - # XXX available from Python. So now() may return different results
215.1421 - # XXX across the implementations.
215.1422 - def |>METHOD:now<|(|>PARAMETER:cls<|, |>PARAMETER:tz<|=None):
215.1423 - "Construct a datetime from time.time() and optional time zone info."
215.1424 - t = _time.time()
215.1425 - return |>PARAMETER:cls<|.fromtimestamp(t, |>PARAMETER:tz<|)
215.1426 - now = classmethod(now)
215.1427 -
215.1428 - def |>METHOD:utcnow<|(|>PARAMETER:cls<|):
215.1429 - "Construct a UTC datetime from time.time()."
215.1430 - t = _time.time()
215.1431 - return |>PARAMETER:cls<|.utcfromtimestamp(t)
215.1432 - utcnow = classmethod(utcnow)
215.1433 -
215.1434 - def |>METHOD:combine<|(|>PARAMETER:cls<|, |>PARAMETER:date<|, |>PARAMETER:time<|):
215.1435 - "Construct a datetime from a given date and a given time."
215.1436 - if not isinstance(|>PARAMETER:date<|, _date_class):
215.1437 - raise TypeError("date argument must be a date instance")
215.1438 - if not isinstance(|>PARAMETER:time<|, _time_class):
215.1439 - raise TypeError("time argument must be a time instance")
215.1440 - return |>PARAMETER:cls<|(|>PARAMETER:date<|.year, |>PARAMETER:date<|.month, |>PARAMETER:date<|.day,
215.1441 - |>PARAMETER:time<|.hour, |>PARAMETER:time<|.minute, |>PARAMETER:time<|.second, |>PARAMETER:time<|.microsecond,
215.1442 - |>PARAMETER:time<|.tzinfo)
215.1443 - combine = classmethod(combine)
215.1444 -
215.1445 - def |>METHOD:timetuple<|(|>PARAMETER:self<|):
215.1446 - "Return local time tuple compatible with time.localtime()."
215.1447 - dst = |>PARAMETER:self<|._dst()
215.1448 - if dst is None:
215.1449 - dst = -1
215.1450 - elif dst:
215.1451 - dst = 1
215.1452 - return _build_struct_time(|>PARAMETER:self<|.year, |>PARAMETER:self<|.month, |>PARAMETER:self<|.day,
215.1453 - |>PARAMETER:self<|.hour, |>PARAMETER:self<|.minute, |>PARAMETER:self<|.second,
215.1454 - dst)
215.1455 -
215.1456 - def |>METHOD:utctimetuple<|(|>PARAMETER:self<|):
215.1457 - "Return UTC time tuple compatible with time.gmtime()."
215.1458 - y, m, d = |>PARAMETER:self<|.year, |>PARAMETER:self<|.month, |>PARAMETER:self<|.day
215.1459 - hh, mm, ss = |>PARAMETER:self<|.hour, |>PARAMETER:self<|.minute, |>PARAMETER:self<|.second
215.1460 - offset = |>PARAMETER:self<|._utcoffset()
215.1461 - if offset: # neither None nor 0
215.1462 - tm = tmxxx(y, m, d, hh, mm - offset)
215.1463 - y, m, d = tm.year, tm.month, tm.day
215.1464 - hh, mm = tm.hour, tm.minute
215.1465 - return _build_struct_time(y, m, d, hh, mm, ss, 0)
215.1466 -
215.1467 - def |>METHOD:date<|(|>PARAMETER:self<|):
215.1468 - "Return the date part."
215.1469 - return date(|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day)
215.1470 -
215.1471 - def |>METHOD:time<|(|>PARAMETER:self<|):
215.1472 - "Return the time part, with tzinfo None."
215.1473 - return time(|>PARAMETER:self<|.hour, |>PARAMETER:self<|.minute, |>PARAMETER:self<|.second, |>PARAMETER:self<|.microsecond)
215.1474 -
215.1475 - def |>METHOD:timetz<|(|>PARAMETER:self<|):
215.1476 - "Return the time part, with same tzinfo."
215.1477 - return time(|>PARAMETER:self<|.hour, |>PARAMETER:self<|.minute, |>PARAMETER:self<|.second, |>PARAMETER:self<|.microsecond,
215.1478 - |>PARAMETER:self<|._tzinfo)
215.1479 -
215.1480 - def |>METHOD:replace<|(|>PARAMETER:self<|, |>PARAMETER:year<|=None, |>PARAMETER:month<|=None, |>PARAMETER:day<|=None, |>PARAMETER:hour<|=None,
215.1481 - |>PARAMETER:minute<|=None, |>PARAMETER:second<|=None, |>PARAMETER:microsecond<|=None, |>PARAMETER:tzinfo<|=True):
215.1482 - """Return a new datetime with new values for the specified fields."""
215.1483 - if |>PARAMETER:year<| is None:
215.1484 - |>PARAMETER:year<| = |>PARAMETER:self<|.year
215.1485 - if |>PARAMETER:month<| is None:
215.1486 - |>PARAMETER:month<| = |>PARAMETER:self<|.month
215.1487 - if |>PARAMETER:day<| is None:
215.1488 - |>PARAMETER:day<| = |>PARAMETER:self<|.day
215.1489 - if |>PARAMETER:hour<| is None:
215.1490 - |>PARAMETER:hour<| = |>PARAMETER:self<|.hour
215.1491 - if |>PARAMETER:minute<| is None:
215.1492 - |>PARAMETER:minute<| = |>PARAMETER:self<|.minute
215.1493 - if |>PARAMETER:second<| is None:
215.1494 - |>PARAMETER:second<| = |>PARAMETER:self<|.second
215.1495 - if |>PARAMETER:microsecond<| is None:
215.1496 - |>PARAMETER:microsecond<| = |>PARAMETER:self<|.microsecond
215.1497 - if |>PARAMETER:tzinfo<| is True:
215.1498 - |>PARAMETER:tzinfo<| = |>PARAMETER:self<|.tzinfo
215.1499 - _check_date_fields(|>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|)
215.1500 - _check_time_fields(|>PARAMETER:hour<|, |>PARAMETER:minute<|, |>PARAMETER:second<|, |>PARAMETER:microsecond<|)
215.1501 - _check_tzinfo_arg(|>PARAMETER:tzinfo<|)
215.1502 - return datetime(|>PARAMETER:year<|, |>PARAMETER:month<|, |>PARAMETER:day<|, |>PARAMETER:hour<|, |>PARAMETER:minute<|, |>PARAMETER:second<|,
215.1503 - |>PARAMETER:microsecond<|, |>PARAMETER:tzinfo<|)
215.1504 -
215.1505 - def |>METHOD:astimezone<|(|>PARAMETER:self<|, |>PARAMETER:tz<|):
215.1506 - if not isinstance(|>PARAMETER:tz<|, tzinfo):
215.1507 - raise TypeError("tz argument must be an instance of tzinfo")
215.1508 -
215.1509 - mytz = |>PARAMETER:self<|.tzinfo
215.1510 - if mytz is None:
215.1511 - raise ValueError("astimezone() requires an aware datetime")
215.1512 -
215.1513 - if |>PARAMETER:tz<| is mytz:
215.1514 - return |>PARAMETER:self<|
215.1515 -
215.1516 - # Convert self to UTC, and attach the new time zone object.
215.1517 - myoffset = |>PARAMETER:self<|.utcoffset()
215.1518 - if myoffset is None:
215.1519 - raise ValuError("astimezone() requires an aware datetime")
215.1520 - utc = (|>PARAMETER:self<| - myoffset).replace(tzinfo=|>PARAMETER:tz<|)
215.1521 -
215.1522 - # Convert from UTC to tz's local time.
215.1523 - return |>PARAMETER:tz<|.fromutc(utc)
215.1524 -
215.1525 - # Ways to produce a string.
215.1526 -
215.1527 - def |>METHOD:ctime<|(|>PARAMETER:self<|):
215.1528 - "Format a la ctime()."
215.1529 - t = tmxxx(|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day, |>PARAMETER:self<|.__hour,
215.1530 - |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second)
215.1531 - return t.ctime()
215.1532 -
215.1533 - def |>METHOD:isoformat<|(|>PARAMETER:self<|, |>PARAMETER:sep<|='T'):
215.1534 - """Return the time formatted according to ISO.
215.1535 -
215.1536 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
215.1537 - self.microsecond == 0.
215.1538 -
215.1539 - If self.tzinfo is not None, the UTC offset is also attached, giving
215.1540 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
215.1541 -
215.1542 - Optional argument sep specifies the separator between date and
215.1543 - time, default 'T'.
215.1544 - """
215.1545 - s = ("%04d-%02d-%02d%c" % (|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day,
215.1546 - |>PARAMETER:sep<|) +
215.1547 - _format_time(|>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second,
215.1548 - |>PARAMETER:self<|.__microsecond))
215.1549 - off = |>PARAMETER:self<|._utcoffset()
215.1550 - if off is not None:
215.1551 - if off < 0:
215.1552 - sign = "-"
215.1553 - off = -off
215.1554 - else:
215.1555 - sign = "+"
215.1556 - hh, mm = divmod(off, 60)
215.1557 - s += "%s%02d:%02d" % (sign, hh, mm)
215.1558 - return s
215.1559 -
215.1560 - def |>METHOD:__repr__<|(|>PARAMETER:self<|):
215.1561 - "Convert to formal string, for repr()."
215.1562 - L = [|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day, # These are never zero
215.1563 - |>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second, |>PARAMETER:self<|.__microsecond]
215.1564 - if L[-1] == 0:
215.1565 - del L[-1]
215.1566 - if L[-1] == 0:
215.1567 - del L[-1]
215.1568 - s = ", ".join(map(str, L))
215.1569 - s = "%s(%s)" % ('datetime.' + |>PARAMETER:self<|.__class__.__name__, s)
215.1570 - if |>PARAMETER:self<|._tzinfo is not None:
215.1571 - assert s[-1:] == ")"
215.1572 - s = s[:-1] + ", tzinfo=%r" % |>PARAMETER:self<|._tzinfo + ")"
215.1573 - return s
215.1574 -
215.1575 - def |>METHOD:__str__<|(|>PARAMETER:self<|):
215.1576 - "Convert to string, for str()."
215.1577 - return |>PARAMETER:self<|.isoformat(sep=' ')
215.1578 -
215.1579 - def |>METHOD:utcoffset<|(|>PARAMETER:self<|):
215.1580 - """Return the timezone offset in minutes east of UTC (negative west of
215.1581 - UTC)."""
215.1582 - offset = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "utcoffset", |>PARAMETER:self<|)
215.1583 - offset = _check_utc_offset("utcoffset", offset)
215.1584 - if offset is not None:
215.1585 - offset = timedelta(minutes=offset)
215.1586 - return offset
215.1587 -
215.1588 - # Return an integer (or None) instead of a timedelta (or None).
215.1589 - def |>METHOD:_utcoffset<|(|>PARAMETER:self<|):
215.1590 - offset = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "utcoffset", |>PARAMETER:self<|)
215.1591 - offset = _check_utc_offset("utcoffset", offset)
215.1592 - return offset
215.1593 -
215.1594 - def |>METHOD:tzname<|(|>PARAMETER:self<|):
215.1595 - """Return the timezone name.
215.1596 -
215.1597 - Note that the name is 100% informational -- there's no requirement that
215.1598 - it mean anything in particular. For example, "GMT", "UTC", "-500",
215.1599 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
215.1600 - """
215.1601 - name = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "tzname", |>PARAMETER:self<|)
215.1602 - _check_tzname(name)
215.1603 - return name
215.1604 -
215.1605 - def |>METHOD:dst<|(|>PARAMETER:self<|):
215.1606 - """Return 0 if DST is not in effect, or the DST offset (in minutes
215.1607 - eastward) if DST is in effect.
215.1608 -
215.1609 - This is purely informational; the DST offset has already been added to
215.1610 - the UTC offset returned by utcoffset() if applicable, so there's no
215.1611 - need to consult dst() unless you're interested in displaying the DST
215.1612 - info.
215.1613 - """
215.1614 - offset = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "dst", |>PARAMETER:self<|)
215.1615 - offset = _check_utc_offset("dst", offset)
215.1616 - if offset is not None:
215.1617 - offset = timedelta(minutes=offset)
215.1618 - return offset
215.1619 -
215.1620 - # Return an integer (or None) instead of a timedelta (or None).1573
215.1621 - def |>METHOD:_dst<|(|>PARAMETER:self<|):
215.1622 - offset = _call_tzinfo_method(|>PARAMETER:self<|._tzinfo, "dst", |>PARAMETER:self<|)
215.1623 - offset = _check_utc_offset("dst", offset)
215.1624 - return offset
215.1625 -
215.1626 - # Comparisons.
215.1627 -
215.1628 - def |>METHOD:__eq__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.1629 - if isinstance(|>PARAMETER:other<|, datetime):
215.1630 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) == 0
215.1631 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
215.1632 - return NotImplemented
215.1633 - else:
215.1634 - return False
215.1635 -
215.1636 - def |>METHOD:__ne__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.1637 - if isinstance(|>PARAMETER:other<|, datetime):
215.1638 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) != 0
215.1639 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
215.1640 - return NotImplemented
215.1641 - else:
215.1642 - return True
215.1643 -
215.1644 - def |>METHOD:__le__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.1645 - if isinstance(|>PARAMETER:other<|, datetime):
215.1646 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) <= 0
215.1647 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
215.1648 - return NotImplemented
215.1649 - else:
215.1650 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
215.1651 -
215.1652 - def |>METHOD:__lt__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.1653 - if isinstance(|>PARAMETER:other<|, datetime):
215.1654 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) < 0
215.1655 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
215.1656 - return NotImplemented
215.1657 - else:
215.1658 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
215.1659 -
215.1660 - def |>METHOD:__ge__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.1661 - if isinstance(|>PARAMETER:other<|, datetime):
215.1662 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) >= 0
215.1663 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
215.1664 - return NotImplemented
215.1665 - else:
215.1666 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
215.1667 -
215.1668 - def |>METHOD:__gt__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.1669 - if isinstance(|>PARAMETER:other<|, datetime):
215.1670 - return |>PARAMETER:self<|.__cmp(|>PARAMETER:other<|) > 0
215.1671 - elif hasattr(|>PARAMETER:other<|, "timetuple"):
215.1672 - return NotImplemented
215.1673 - else:
215.1674 - _cmperror(|>PARAMETER:self<|, |>PARAMETER:other<|)
215.1675 -
215.1676 - def |>METHOD:__cmp<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.1677 - assert isinstance(|>PARAMETER:other<|, datetime)
215.1678 - mytz = |>PARAMETER:self<|._tzinfo
215.1679 - ottz = |>PARAMETER:other<|._tzinfo
215.1680 - myoff = otoff = None
215.1681 -
215.1682 - if mytz is ottz:
215.1683 - base_compare = True
215.1684 - else:
215.1685 - if mytz is not None:
215.1686 - myoff = |>PARAMETER:self<|._utcoffset()
215.1687 - if ottz is not None:
215.1688 - otoff = |>PARAMETER:other<|._utcoffset()
215.1689 - base_compare = myoff == otoff
215.1690 -
215.1691 - if base_compare:
215.1692 - return cmp((|>PARAMETER:self<|.__year, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day,
215.1693 - |>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second,
215.1694 - |>PARAMETER:self<|.__microsecond),
215.1695 - (|>PARAMETER:other<|.__year, |>PARAMETER:other<|.__month, |>PARAMETER:other<|.__day,
215.1696 - |>PARAMETER:other<|.__hour, |>PARAMETER:other<|.__minute, |>PARAMETER:other<|.__second,
215.1697 - |>PARAMETER:other<|.__microsecond))
215.1698 - if myoff is None or otoff is None:
215.1699 - # XXX Buggy in 2.2.2.
215.1700 - raise TypeError("cannot compare naive and aware datetimes")
215.1701 - # XXX What follows could be done more efficiently...
215.1702 - diff = |>PARAMETER:self<| - |>PARAMETER:other<| # this will take offsets into account
215.1703 - if diff.days < 0:
215.1704 - return -1
215.1705 - return diff and 1 or 0
215.1706 -
215.1707 - def |>METHOD:__add__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.1708 - "Add a datetime and a timedelta."
215.1709 - if not isinstance(|>PARAMETER:other<|, timedelta):
215.1710 - return NotImplemented
215.1711 - t = tmxxx(|>PARAMETER:self<|.__year,
215.1712 - |>PARAMETER:self<|.__month,
215.1713 - |>PARAMETER:self<|.__day + |>PARAMETER:other<|.days,
215.1714 - |>PARAMETER:self<|.__hour,
215.1715 - |>PARAMETER:self<|.__minute,
215.1716 - |>PARAMETER:self<|.__second + |>PARAMETER:other<|.seconds,
215.1717 - |>PARAMETER:self<|.__microsecond + |>PARAMETER:other<|.microseconds)
215.1718 - |>PARAMETER:self<|._checkOverflow(t.year)
215.1719 - result = |>PARAMETER:self<|.__class__(t.year, t.month, t.day,
215.1720 - t.hour, t.minute, t.second,
215.1721 - t.microsecond, tzinfo=|>PARAMETER:self<|._tzinfo)
215.1722 - return result
215.1723 -
215.1724 - __radd__ = __add__
215.1725 -
215.1726 - def |>METHOD:__sub__<|(|>PARAMETER:self<|, |>PARAMETER:other<|):
215.1727 - "Subtract two datetimes, or a datetime and a timedelta."
215.1728 - if not isinstance(|>PARAMETER:other<|, datetime):
215.1729 - if isinstance(|>PARAMETER:other<|, timedelta):
215.1730 - return |>PARAMETER:self<| + -|>PARAMETER:other<|
215.1731 - return NotImplemented
215.1732 -
215.1733 - days1 = |>PARAMETER:self<|.toordinal()
215.1734 - days2 = |>PARAMETER:other<|.toordinal()
215.1735 - secs1 = |>PARAMETER:self<|.__second + |>PARAMETER:self<|.__minute * 60 + |>PARAMETER:self<|.__hour * 3600
215.1736 - secs2 = |>PARAMETER:other<|.__second + |>PARAMETER:other<|.__minute * 60 + |>PARAMETER:other<|.__hour * 3600
215.1737 - base = timedelta(days1 - days2,
215.1738 - secs1 - secs2,
215.1739 - |>PARAMETER:self<|.__microsecond - |>PARAMETER:other<|.__microsecond)
215.1740 - if |>PARAMETER:self<|._tzinfo is |>PARAMETER:other<|._tzinfo:
215.1741 - return base
215.1742 - myoff = |>PARAMETER:self<|._utcoffset()
215.1743 - otoff = |>PARAMETER:other<|._utcoffset()
215.1744 - if myoff == otoff:
215.1745 - return base
215.1746 - if myoff is None or otoff is None:
215.1747 - raise TypeError, "cannot mix naive and timezone-aware time"
215.1748 - return base + timedelta(minutes = otoff-myoff)
215.1749 -
215.1750 - def |>METHOD:__hash__<|(|>PARAMETER:self<|):
215.1751 - tzoff = |>PARAMETER:self<|._utcoffset()
215.1752 - if tzoff is None:
215.1753 - return hash(|>PARAMETER:self<|.__getstate()[0])
215.1754 - days = _ymd2ord(|>PARAMETER:self<|.year, |>PARAMETER:self<|.month, |>PARAMETER:self<|.day)
215.1755 - seconds = |>PARAMETER:self<|.hour * 3600 + (|>PARAMETER:self<|.minute - tzoff) * 60 + |>PARAMETER:self<|.second
215.1756 - return hash(timedelta(days, seconds, |>PARAMETER:self<|.microsecond))
215.1757 -
215.1758 - # Pickle support.
215.1759 -
215.1760 - __safe_for_unpickling__ = True # For Python 2.2
215.1761 -
215.1762 - def |>METHOD:__getstate<|(|>PARAMETER:self<|):
215.1763 - yhi, ylo = divmod(|>PARAMETER:self<|.__year, 256)
215.1764 - us2, us3 = divmod(|>PARAMETER:self<|.__microsecond, 256)
215.1765 - us1, us2 = divmod(us2, 256)
215.1766 - basestate = ("%c" * 10) % (yhi, ylo, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day,
215.1767 - |>PARAMETER:self<|.__hour, |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second,
215.1768 - us1, us2, us3)
215.1769 - if |>PARAMETER:self<|._tzinfo is None:
215.1770 - return (basestate,)
215.1771 - else:
215.1772 - return (basestate, |>PARAMETER:self<|._tzinfo)
215.1773 -
215.1774 - def |>METHOD:__setstate<|(|>PARAMETER:self<|, |>PARAMETER:state<|):
215.1775 - assert isinstance(|>PARAMETER:state<|, tuple)
215.1776 - assert 1 <= len(|>PARAMETER:state<|) <= 2
215.1777 - string = |>PARAMETER:state<|[0]
215.1778 - assert len(string) == 10
215.1779 - (yhi, ylo, |>PARAMETER:self<|.__month, |>PARAMETER:self<|.__day, |>PARAMETER:self<|.__hour,
215.1780 - |>PARAMETER:self<|.__minute, |>PARAMETER:self<|.__second, us1, us2, us3) = map(ord, string)
215.1781 - |>PARAMETER:self<|.__year = yhi * 256 + ylo
215.1782 - |>PARAMETER:self<|.__microsecond = (((us1 << 8) | us2) << 8) | us3
215.1783 - if len(|>PARAMETER:state<|) == 1:
215.1784 - |>PARAMETER:self<|._tzinfo = None
215.1785 - else:
215.1786 - |>PARAMETER:self<|._tzinfo = |>PARAMETER:state<|[1]
215.1787 -
215.1788 - def |>METHOD:__reduce__<|(|>PARAMETER:self<|):
215.1789 - return (|>PARAMETER:self<|.__class__, |>PARAMETER:self<|.__getstate())
215.1790 -
215.1791 -
215.1792 -datetime.min = datetime(1, 1, 1)
215.1793 -datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
215.1794 -datetime.resolution = timedelta(microseconds=1)
215.1795 -
215.1796 -
215.1797 -def |>METHOD:_isoweek1monday<|(|>PARAMETER:year<|):
215.1798 - # Helper to calculate the day number of the Monday starting week 1
215.1799 - # XXX This could be done more efficiently
215.1800 - THURSDAY = 3
215.1801 - firstday = _ymd2ord(|>PARAMETER:year<|, 1, 1)
215.1802 - firstweekday = (firstday + 6) % 7 # See weekday() above
215.1803 - week1monday = firstday - firstweekday
215.1804 - if firstweekday > THURSDAY:
215.1805 - week1monday += 7
215.1806 - return week1monday
215.1807 -
215.1808 -"""
215.1809 -Some time zone algebra. For a datetime x, let
215.1810 - x.n = x stripped of its timezone -- its naive time.
215.1811 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
215.1812 - return None
215.1813 - x.d = x.dst(), and assuming that doesn't raise an exception or
215.1814 - return None
215.1815 - x.s = x's standard offset, x.o - x.d
215.1816 -
215.1817 -Now some derived rules, where k is a duration (timedelta).
215.1818 -
215.1819 -1. x.o = x.s + x.d
215.1820 - This follows from the definition of x.s.
215.1821 -
215.1822 -2. If x and y have the same tzinfo member, x.s = y.s.
215.1823 - This is actually a requirement, an assumption we need to make about
215.1824 - sane tzinfo classes.
215.1825 -
215.1826 -3. The naive UTC time corresponding to x is x.n - x.o.
215.1827 - This is again a requirement for a sane tzinfo class.
215.1828 -
215.1829 -4. (x+k).s = x.s
215.1830 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
215.1831 -
215.1832 -5. (x+k).n = x.n + k
215.1833 - Again follows from how arithmetic is defined.
215.1834 -
215.1835 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
215.1836 -(meaning that the various tzinfo methods exist, and don't blow up or return
215.1837 -None when called).
215.1838 -
215.1839 -The function wants to return a datetime y with timezone tz, equivalent to x.
215.1840 -x is already in UTC.
215.1841 -
215.1842 -By #3, we want
215.1843 -
215.1844 - y.n - y.o = x.n [1]
215.1845 -
215.1846 -The algorithm starts by attaching tz to x.n, and calling that y. So
215.1847 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
215.1848 -becomes true; in effect, we want to solve [2] for k:
215.1849 -
215.1850 - (y+k).n - (y+k).o = x.n [2]
215.1851 -
215.1852 -By #1, this is the same as
215.1853 -
215.1854 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
215.1855 -
215.1856 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
215.1857 -Substituting that into [3],
215.1858 -
215.1859 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
215.1860 - k - (y+k).s - (y+k).d = 0; rearranging,
215.1861 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
215.1862 - k = y.s - (y+k).d
215.1863 -
215.1864 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
215.1865 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
215.1866 -very large, since all offset-returning methods return a duration of magnitude
215.1867 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
215.1868 -be 0, so ignoring it has no consequence then.
215.1869 -
215.1870 -In any case, the new value is
215.1871 -
215.1872 - z = y + y.s [4]
215.1873 -
215.1874 -It's helpful to step back at look at [4] from a higher level: it's simply
215.1875 -mapping from UTC to tz's standard time.
215.1876 -
215.1877 -At this point, if
215.1878 -
215.1879 - z.n - z.o = x.n [5]
215.1880 -
215.1881 -we have an equivalent time, and are almost done. The insecurity here is
215.1882 -at the start of daylight time. Picture US Eastern for concreteness. The wall
215.1883 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
215.1884 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
215.1885 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
215.1886 -on the day DST starts. We want to return the 1:MM EST spelling because that's
215.1887 -the only spelling that makes sense on the local wall clock.
215.1888 -
215.1889 -In fact, if [5] holds at this point, we do have the standard-time spelling,
215.1890 -but that takes a bit of proof. We first prove a stronger result. What's the
215.1891 -difference between the LHS and RHS of [5]? Let
215.1892 -
215.1893 - diff = x.n - (z.n - z.o) [6]
215.1894 -
215.1895 -Now
215.1896 - z.n = by [4]
215.1897 - (y + y.s).n = by #5
215.1898 - y.n + y.s = since y.n = x.n
215.1899 - x.n + y.s = since z and y are have the same tzinfo member,
215.1900 - y.s = z.s by #2
215.1901 - x.n + z.s
215.1902 -
215.1903 -Plugging that back into [6] gives
215.1904 -
215.1905 - diff =
215.1906 - x.n - ((x.n + z.s) - z.o) = expanding
215.1907 - x.n - x.n - z.s + z.o = cancelling
215.1908 - - z.s + z.o = by #2
215.1909 - z.d
215.1910 -
215.1911 -So diff = z.d.
215.1912 -
215.1913 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
215.1914 -spelling we wanted in the endcase described above. We're done. Contrarily,
215.1915 -if z.d = 0, then we have a UTC equivalent, and are also done.
215.1916 -
215.1917 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
215.1918 -add to z (in effect, z is in tz's standard time, and we need to shift the
215.1919 -local clock into tz's daylight time).
215.1920 -
215.1921 -Let
215.1922 -
215.1923 - z' = z + z.d = z + diff [7]
215.1924 -
215.1925 -and we can again ask whether
215.1926 -
215.1927 - z'.n - z'.o = x.n [8]
215.1928 -
215.1929 -If so, we're done. If not, the tzinfo class is insane, according to the
215.1930 -assumptions we've made. This also requires a bit of proof. As before, let's
215.1931 -compute the difference between the LHS and RHS of [8] (and skipping some of
215.1932 -the justifications for the kinds of substitutions we've done several times
215.1933 -already):
215.1934 -
215.1935 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
215.1936 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
215.1937 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
215.1938 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
215.1939 - - z.n + z.n - z.o + z'.o = cancel z.n
215.1940 - - z.o + z'.o = #1 twice
215.1941 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
215.1942 - z'.d - z.d
215.1943 -
215.1944 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
215.1945 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
215.1946 -return z', not bothering to compute z'.d.
215.1947 -
215.1948 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
215.1949 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
215.1950 -would have to change the result dst() returns: we start in DST, and moving
215.1951 -a little further into it takes us out of DST.
215.1952 -
215.1953 -There isn't a sane case where this can happen. The closest it gets is at
215.1954 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
215.1955 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
215.1956 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
215.1957 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
215.1958 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
215.1959 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
215.1960 -standard time. Since that's what the local clock *does*, we want to map both
215.1961 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
215.1962 -in local time, but so it goes -- it's the way the local clock works.
215.1963 -
215.1964 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
215.1965 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
215.1966 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
215.1967 -(correctly) concludes that z' is not UTC-equivalent to x.
215.1968 -
215.1969 -Because we know z.d said z was in daylight time (else [5] would have held and
215.1970 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
215.1971 -and we we have stopped then), and there are only 2 possible values dst() can
215.1972 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
215.1973 -but the reasoning doesn't depend on the example -- it depends on there being
215.1974 -two possible dst() outcomes, one zero and the other non-zero). Therefore
215.1975 -z' must be in standard time, and is the spelling we want in this case.
215.1976 -
215.1977 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
215.1978 -concerned (because it takes z' as being in standard time rather than the
215.1979 -daylight time we intend here), but returning it gives the real-life "local
215.1980 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
215.1981 -tz.
215.1982 -
215.1983 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
215.1984 -the 1:MM standard time spelling we want.
215.1985 -
215.1986 -So how can this break? One of the assumptions must be violated. Two
215.1987 -possibilities:
215.1988 -
215.1989 -1) [2] effectively says that y.s is invariant across all y belong to a given
215.1990 - time zone. This isn't true if, for political reasons or continental drift,
215.1991 - a region decides to change its base offset from UTC.
215.1992 -
215.1993 -2) There may be versions of "double daylight" time where the tail end of
215.1994 - the analysis gives up a step too early. I haven't thought about that
215.1995 - enough to say.
215.1996 -
215.1997 -In any case, it's clear that the default fromutc() is strong enough to handle
215.1998 -"almost all" time zones: so long as the standard offset is invariant, it
215.1999 -doesn't matter if daylight time transition points change from year to year, or
215.2000 -if daylight time is skipped in some years; it doesn't matter how large or
215.2001 -small dst() may get within its bounds; and it doesn't even matter if some
215.2002 -perverse time zone returns a negative dst()). So a breaking case must be
215.2003 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
215.2004 -"""
215.2005 -
215.2006 -def |>METHOD:_test<|():
215.2007 - import test_datetime
215.2008 - test_datetime.test_main()
215.2009 -
215.2010 -if __name__ == "__main__":
215.2011 - _test()
216.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.structure Sun Jan 04 13:11:53 2015 -0600
216.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
216.3 @@ -1,170 +0,0 @@
216.4 -_is_leap:METHOD:[PRIVATE]:ESCAPED{_is_leap}(PARAMETERS{ESCAPED{year}}):
216.5 -_days_in_year:METHOD:[PRIVATE]:ESCAPED{_days_in_year}(PARAMETERS{ESCAPED{year}}):
216.6 -_days_before_year:METHOD:[PRIVATE]:ESCAPED{_days_before_year}(PARAMETERS{ESCAPED{year}}):
216.7 -_days_in_month:METHOD:[PRIVATE]:ESCAPED{_days_in_month}(PARAMETERS{ESCAPED{year}ESCAPED{,}ESCAPED{month}}):
216.8 -_days_before_month:METHOD:[PRIVATE]:ESCAPED{_days_before_month}(PARAMETERS{ESCAPED{year}ESCAPED{,}ESCAPED{month}}):
216.9 -_ymd2ord:METHOD:[PRIVATE]:ESCAPED{_ymd2ord}(PARAMETERS{ESCAPED{year}ESCAPED{,}ESCAPED{month}ESCAPED{,}ESCAPED{day}}):
216.10 -_ord2ymd:METHOD:[PRIVATE]:ESCAPED{_ord2ymd}(PARAMETERS{ESCAPED{n}}):
216.11 -_build_struct_time:METHOD:[PRIVATE]:ESCAPED{_build_struct_time}(PARAMETERS{ESCAPED{y}ESCAPED{,}ESCAPED{m}ESCAPED{,}ESCAPED{d}ESCAPED{,}ESCAPED{hh}ESCAPED{,}ESCAPED{mm}ESCAPED{,}ESCAPED{ss}ESCAPED{,}ESCAPED{dstflag}}):
216.12 -_format_time:METHOD:[PRIVATE]:ESCAPED{_format_time}(PARAMETERS{ESCAPED{hh}ESCAPED{,}ESCAPED{mm}ESCAPED{,}ESCAPED{ss}ESCAPED{,}ESCAPED{us}}):
216.13 -_wrap_strftime:METHOD:[PRIVATE]:ESCAPED{_wrap_strftime}(PARAMETERS{ESCAPED{object}ESCAPED{,}ESCAPED{format}ESCAPED{,}ESCAPED{timetuple}}):
216.14 -_call_tzinfo_method:METHOD:[PRIVATE]:ESCAPED{_call_tzinfo_method}(PARAMETERS{ESCAPED{tzinfo}ESCAPED{,}ESCAPED{methname}ESCAPED{,}ESCAPED{tzinfoarg}}):
216.15 -_check_tzname:METHOD:[PRIVATE]:ESCAPED{_check_tzname}(PARAMETERS{ESCAPED{name}}):
216.16 -_check_utc_offset:METHOD:[PRIVATE]:ESCAPED{_check_utc_offset}(PARAMETERS{ESCAPED{name}ESCAPED{,}ESCAPED{offset}}):
216.17 -_check_date_fields:METHOD:[PRIVATE]:ESCAPED{_check_date_fields}(PARAMETERS{ESCAPED{year}ESCAPED{,}ESCAPED{month}ESCAPED{,}ESCAPED{day}}):
216.18 -_check_time_fields:METHOD:[PRIVATE]:ESCAPED{_check_time_fields}(PARAMETERS{ESCAPED{hour}ESCAPED{,}ESCAPED{minute}ESCAPED{,}ESCAPED{second}ESCAPED{,}ESCAPED{microsecond}}):
216.19 -_check_tzinfo_arg:METHOD:[PRIVATE]:ESCAPED{_check_tzinfo_arg}(PARAMETERS{ESCAPED{tz}}):
216.20 -_cmperror:METHOD:[PRIVATE]:ESCAPED{_cmperror}(PARAMETERS{ESCAPED{x}ESCAPED{,}ESCAPED{y}}):
216.21 -tmxxx:CLASS:[]:ESCAPED{tmxxx}:
216.22 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{year}ESCAPED{,}ESCAPED{month}ESCAPED{,}ESCAPED{day}ESCAPED{,}ESCAPED{hour}ESCAPED{,}ESCAPED{minute}ESCAPED{,}ESCAPED{second}ESCAPED{,}ESCAPED{microsecond}}):
216.23 - ctime:METHOD:[]:ESCAPED{ctime}(PARAMETERS{ESCAPED{self}}):
216.24 - day:ATTRIBUTE:[]:ESCAPED{day}:
216.25 - hour:ATTRIBUTE:[]:ESCAPED{hour}:
216.26 - microsecond:ATTRIBUTE:[]:ESCAPED{microsecond}:
216.27 - minute:ATTRIBUTE:[]:ESCAPED{minute}:
216.28 - month:ATTRIBUTE:[]:ESCAPED{month}:
216.29 - ordinal:ATTRIBUTE:[]:ESCAPED{ordinal}:
216.30 - second:ATTRIBUTE:[]:ESCAPED{second}:
216.31 - time:METHOD:[]:ESCAPED{time}(PARAMETERS{ESCAPED{self}}):
216.32 - toordinal:METHOD:[]:ESCAPED{toordinal}(PARAMETERS{ESCAPED{self}}):
216.33 - year:ATTRIBUTE:[]:ESCAPED{year}:
216.34 -timedelta:CLASS:[]:ESCAPED{timedelta}:
216.35 - __abs__:METHOD:[]:ESCAPED{__abs__}(PARAMETERS{ESCAPED{self}}):
216.36 - __add__:METHOD:[]:ESCAPED{__add__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.37 - __cmp:METHOD:[PRIVATE]:ESCAPED{__cmp}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.38 - __days:ATTRIBUTE:[]:ESCAPED{__days}:
216.39 - __div__:METHOD:[]:ESCAPED{__div__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.40 - __eq__:METHOD:[]:ESCAPED{__eq__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.41 - __ge__:METHOD:[]:ESCAPED{__ge__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.42 - __getstate:METHOD:[PRIVATE]:ESCAPED{__getstate}(PARAMETERS{ESCAPED{self}}):
216.43 - __gt__:METHOD:[]:ESCAPED{__gt__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.44 - __hash__:METHOD:[]:ESCAPED{__hash__}(PARAMETERS{ESCAPED{self}}):
216.45 - __le__:METHOD:[]:ESCAPED{__le__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.46 - __lt__:METHOD:[]:ESCAPED{__lt__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.47 - __microseconds:ATTRIBUTE:[]:ESCAPED{__microseconds}:
216.48 - __mul__:METHOD:[]:ESCAPED{__mul__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.49 - __ne__:METHOD:[]:ESCAPED{__ne__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.50 - __neg__:METHOD:[]:ESCAPED{__neg__}(PARAMETERS{ESCAPED{self}}):
216.51 - __new__:METHOD:[]:ESCAPED{__new__}(PARAMETERS{ESCAPED{cls}ESCAPED{,}ESCAPED{days}ESCAPED{,}ESCAPED{seconds}ESCAPED{,}ESCAPED{microseconds}ESCAPED{,}ESCAPED{milliseconds}ESCAPED{,}ESCAPED{minutes}ESCAPED{,}ESCAPED{hours}ESCAPED{,}ESCAPED{weeks}}):
216.52 - __nonzero__:METHOD:[]:ESCAPED{__nonzero__}(PARAMETERS{ESCAPED{self}}):
216.53 - __pos__:METHOD:[]:ESCAPED{__pos__}(PARAMETERS{ESCAPED{self}}):
216.54 - __reduce__:METHOD:[]:ESCAPED{__reduce__}(PARAMETERS{ESCAPED{self}}):
216.55 - __repr__:METHOD:[]:ESCAPED{__repr__}(PARAMETERS{ESCAPED{self}}):
216.56 - __rsub__:METHOD:[]:ESCAPED{__rsub__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.57 - __seconds:ATTRIBUTE:[]:ESCAPED{__seconds}:
216.58 - __str__:METHOD:[]:ESCAPED{__str__}(PARAMETERS{ESCAPED{self}}):
216.59 - plural:METHOD:[]:ESCAPED{plural}(PARAMETERS{ESCAPED{n}}):
216.60 - __sub__:METHOD:[]:ESCAPED{__sub__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.61 -date:CLASS:[]:ESCAPED{date}:
216.62 - __add__:METHOD:[]:ESCAPED{__add__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.63 - __cmp:METHOD:[PRIVATE]:ESCAPED{__cmp}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.64 - __day:ATTRIBUTE:[]:ESCAPED{__day}:
216.65 - __eq__:METHOD:[]:ESCAPED{__eq__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.66 - __ge__:METHOD:[]:ESCAPED{__ge__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.67 - __getstate:METHOD:[PRIVATE]:ESCAPED{__getstate}(PARAMETERS{ESCAPED{self}}):
216.68 - __gt__:METHOD:[]:ESCAPED{__gt__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.69 - __hash__:METHOD:[]:ESCAPED{__hash__}(PARAMETERS{ESCAPED{self}}):
216.70 - __le__:METHOD:[]:ESCAPED{__le__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.71 - __lt__:METHOD:[]:ESCAPED{__lt__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.72 - __month:ATTRIBUTE:[]:ESCAPED{__month}:
216.73 - __ne__:METHOD:[]:ESCAPED{__ne__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.74 - __new__:METHOD:[]:ESCAPED{__new__}(PARAMETERS{ESCAPED{cls}ESCAPED{,}ESCAPED{year}ESCAPED{,}ESCAPED{month}ESCAPED{,}ESCAPED{day}}):
216.75 - __reduce__:METHOD:[]:ESCAPED{__reduce__}(PARAMETERS{ESCAPED{self}}):
216.76 - __repr__:METHOD:[]:ESCAPED{__repr__}(PARAMETERS{ESCAPED{self}}):
216.77 - __setstate:METHOD:[PRIVATE]:ESCAPED{__setstate}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{t}}):
216.78 - __sub__:METHOD:[]:ESCAPED{__sub__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.79 - __year:ATTRIBUTE:[]:ESCAPED{__year}:
216.80 - _checkOverflow:METHOD:[PRIVATE]:ESCAPED{_checkOverflow}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{year}}):
216.81 - ctime:METHOD:[]:ESCAPED{ctime}(PARAMETERS{ESCAPED{self}}):
216.82 - fromordinal:METHOD:[]:ESCAPED{fromordinal}(PARAMETERS{ESCAPED{cls}ESCAPED{,}ESCAPED{n}}):
216.83 - fromtimestamp:METHOD:[]:ESCAPED{fromtimestamp}(PARAMETERS{ESCAPED{cls}ESCAPED{,}ESCAPED{t}}):
216.84 - isocalendar:METHOD:[]:ESCAPED{isocalendar}(PARAMETERS{ESCAPED{self}}):
216.85 - isoformat:METHOD:[]:ESCAPED{isoformat}(PARAMETERS{ESCAPED{self}}):
216.86 - isoweekday:METHOD:[]:ESCAPED{isoweekday}(PARAMETERS{ESCAPED{self}}):
216.87 - replace:METHOD:[]:ESCAPED{replace}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{year}ESCAPED{,}ESCAPED{month}ESCAPED{,}ESCAPED{day}}):
216.88 - strftime:METHOD:[]:ESCAPED{strftime}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{fmt}}):
216.89 - timetuple:METHOD:[]:ESCAPED{timetuple}(PARAMETERS{ESCAPED{self}}):
216.90 - today:METHOD:[]:ESCAPED{today}(PARAMETERS{ESCAPED{cls}}):
216.91 - toordinal:METHOD:[]:ESCAPED{toordinal}(PARAMETERS{ESCAPED{self}}):
216.92 - weekday:METHOD:[]:ESCAPED{weekday}(PARAMETERS{ESCAPED{self}}):
216.93 -tzinfo:CLASS:[]:ESCAPED{tzinfo}:
216.94 - __reduce__:METHOD:[]:ESCAPED{__reduce__}(PARAMETERS{ESCAPED{self}}):
216.95 - dst:METHOD:[]:ESCAPED{dst}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{dt}}):
216.96 - fromutc:METHOD:[]:ESCAPED{fromutc}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{dt}}):
216.97 - tzname:METHOD:[]:ESCAPED{tzname}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{dt}}):
216.98 - utcoffset:METHOD:[]:ESCAPED{utcoffset}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{dt}}):
216.99 -time:CLASS:[]:ESCAPED{time}:
216.100 - __cmp:METHOD:[PRIVATE]:ESCAPED{__cmp}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.101 - __eq__:METHOD:[]:ESCAPED{__eq__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.102 - __ge__:METHOD:[]:ESCAPED{__ge__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.103 - __getstate:METHOD:[PRIVATE]:ESCAPED{__getstate}(PARAMETERS{ESCAPED{self}}):
216.104 - __gt__:METHOD:[]:ESCAPED{__gt__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.105 - __hash__:METHOD:[]:ESCAPED{__hash__}(PARAMETERS{ESCAPED{self}}):
216.106 - __hour:ATTRIBUTE:[]:ESCAPED{__hour}:
216.107 - __le__:METHOD:[]:ESCAPED{__le__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.108 - __lt__:METHOD:[]:ESCAPED{__lt__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.109 - __microsecond:ATTRIBUTE:[]:ESCAPED{__microsecond}:
216.110 - __minute:ATTRIBUTE:[]:ESCAPED{__minute}:
216.111 - __ne__:METHOD:[]:ESCAPED{__ne__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.112 - __new__:METHOD:[]:ESCAPED{__new__}(PARAMETERS{ESCAPED{cls}ESCAPED{,}ESCAPED{hour}ESCAPED{,}ESCAPED{minute}ESCAPED{,}ESCAPED{second}ESCAPED{,}ESCAPED{microsecond}ESCAPED{,}ESCAPED{tzinfo}}):
216.113 - __nonzero__:METHOD:[]:ESCAPED{__nonzero__}(PARAMETERS{ESCAPED{self}}):
216.114 - __reduce__:METHOD:[]:ESCAPED{__reduce__}(PARAMETERS{ESCAPED{self}}):
216.115 - __repr__:METHOD:[]:ESCAPED{__repr__}(PARAMETERS{ESCAPED{self}}):
216.116 - __second:ATTRIBUTE:[]:ESCAPED{__second}:
216.117 - __setstate:METHOD:[PRIVATE]:ESCAPED{__setstate}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{state}}):
216.118 - _dst:METHOD:[PRIVATE]:ESCAPED{_dst}(PARAMETERS{ESCAPED{self}}):
216.119 - _tzinfo:ATTRIBUTE:[]:ESCAPED{_tzinfo}:
216.120 - _tzstr:METHOD:[PRIVATE]:ESCAPED{_tzstr}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{sep}}):
216.121 - _utcoffset:METHOD:[PRIVATE]:ESCAPED{_utcoffset}(PARAMETERS{ESCAPED{self}}):
216.122 - dst:METHOD:[]:ESCAPED{dst}(PARAMETERS{ESCAPED{self}}):
216.123 - isoformat:METHOD:[]:ESCAPED{isoformat}(PARAMETERS{ESCAPED{self}}):
216.124 - replace:METHOD:[]:ESCAPED{replace}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{hour}ESCAPED{,}ESCAPED{minute}ESCAPED{,}ESCAPED{second}ESCAPED{,}ESCAPED{microsecond}ESCAPED{,}ESCAPED{tzinfo}}):
216.125 - strftime:METHOD:[]:ESCAPED{strftime}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{fmt}}):
216.126 - tzname:METHOD:[]:ESCAPED{tzname}(PARAMETERS{ESCAPED{self}}):
216.127 - utcoffset:METHOD:[]:ESCAPED{utcoffset}(PARAMETERS{ESCAPED{self}}):
216.128 -datetime:CLASS:[]:ESCAPED{datetime}:
216.129 - __add__:METHOD:[]:ESCAPED{__add__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.130 - __cmp:METHOD:[PRIVATE]:ESCAPED{__cmp}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.131 - __day:ATTRIBUTE:[]:ESCAPED{__day}:
216.132 - __eq__:METHOD:[]:ESCAPED{__eq__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.133 - __ge__:METHOD:[]:ESCAPED{__ge__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.134 - __getstate:METHOD:[PRIVATE]:ESCAPED{__getstate}(PARAMETERS{ESCAPED{self}}):
216.135 - __gt__:METHOD:[]:ESCAPED{__gt__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.136 - __hash__:METHOD:[]:ESCAPED{__hash__}(PARAMETERS{ESCAPED{self}}):
216.137 - __hour:ATTRIBUTE:[]:ESCAPED{__hour}:
216.138 - __le__:METHOD:[]:ESCAPED{__le__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.139 - __lt__:METHOD:[]:ESCAPED{__lt__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.140 - __microsecond:ATTRIBUTE:[]:ESCAPED{__microsecond}:
216.141 - __minute:ATTRIBUTE:[]:ESCAPED{__minute}:
216.142 - __month:ATTRIBUTE:[]:ESCAPED{__month}:
216.143 - __ne__:METHOD:[]:ESCAPED{__ne__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.144 - __new__:METHOD:[]:ESCAPED{__new__}(PARAMETERS{ESCAPED{cls}ESCAPED{,}ESCAPED{year}ESCAPED{,}ESCAPED{month}ESCAPED{,}ESCAPED{day}ESCAPED{,}ESCAPED{hour}ESCAPED{,}ESCAPED{minute}ESCAPED{,}ESCAPED{second}ESCAPED{,}ESCAPED{microsecond}ESCAPED{,}ESCAPED{tzinfo}}):
216.145 - __reduce__:METHOD:[]:ESCAPED{__reduce__}(PARAMETERS{ESCAPED{self}}):
216.146 - __repr__:METHOD:[]:ESCAPED{__repr__}(PARAMETERS{ESCAPED{self}}):
216.147 - __second:ATTRIBUTE:[]:ESCAPED{__second}:
216.148 - __setstate:METHOD:[PRIVATE]:ESCAPED{__setstate}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{state}}):
216.149 - __str__:METHOD:[]:ESCAPED{__str__}(PARAMETERS{ESCAPED{self}}):
216.150 - __sub__:METHOD:[]:ESCAPED{__sub__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{other}}):
216.151 - __year:ATTRIBUTE:[]:ESCAPED{__year}:
216.152 - _dst:METHOD:[PRIVATE]:ESCAPED{_dst}(PARAMETERS{ESCAPED{self}}):
216.153 - _tzinfo:ATTRIBUTE:[]:ESCAPED{_tzinfo}:
216.154 - _utcoffset:METHOD:[PRIVATE]:ESCAPED{_utcoffset}(PARAMETERS{ESCAPED{self}}):
216.155 - astimezone:METHOD:[]:ESCAPED{astimezone}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{tz}}):
216.156 - combine:METHOD:[]:ESCAPED{combine}(PARAMETERS{ESCAPED{cls}ESCAPED{,}ESCAPED{date}ESCAPED{,}ESCAPED{time}}):
216.157 - ctime:METHOD:[]:ESCAPED{ctime}(PARAMETERS{ESCAPED{self}}):
216.158 - date:METHOD:[]:ESCAPED{date}(PARAMETERS{ESCAPED{self}}):
216.159 - dst:METHOD:[]:ESCAPED{dst}(PARAMETERS{ESCAPED{self}}):
216.160 - fromtimestamp:METHOD:[]:ESCAPED{fromtimestamp}(PARAMETERS{ESCAPED{cls}ESCAPED{,}ESCAPED{t}ESCAPED{,}ESCAPED{tz}}):
216.161 - isoformat:METHOD:[]:ESCAPED{isoformat}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{sep}}):
216.162 - now:METHOD:[]:ESCAPED{now}(PARAMETERS{ESCAPED{cls}ESCAPED{,}ESCAPED{tz}}):
216.163 - replace:METHOD:[]:ESCAPED{replace}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{year}ESCAPED{,}ESCAPED{month}ESCAPED{,}ESCAPED{day}ESCAPED{,}ESCAPED{hour}ESCAPED{,}ESCAPED{minute}ESCAPED{,}ESCAPED{second}ESCAPED{,}ESCAPED{microsecond}ESCAPED{,}ESCAPED{tzinfo}}):
216.164 - time:METHOD:[]:ESCAPED{time}(PARAMETERS{ESCAPED{self}}):
216.165 - timetuple:METHOD:[]:ESCAPED{timetuple}(PARAMETERS{ESCAPED{self}}):
216.166 - timetz:METHOD:[]:ESCAPED{timetz}(PARAMETERS{ESCAPED{self}}):
216.167 - tzname:METHOD:[]:ESCAPED{tzname}(PARAMETERS{ESCAPED{self}}):
216.168 - utcfromtimestamp:METHOD:[]:ESCAPED{utcfromtimestamp}(PARAMETERS{ESCAPED{cls}ESCAPED{,}ESCAPED{t}}):
216.169 - utcnow:METHOD:[]:ESCAPED{utcnow}(PARAMETERS{ESCAPED{cls}}):
216.170 - utcoffset:METHOD:[]:ESCAPED{utcoffset}(PARAMETERS{ESCAPED{self}}):
216.171 - utctimetuple:METHOD:[]:ESCAPED{utctimetuple}(PARAMETERS{ESCAPED{self}}):
216.172 -_isoweek1monday:METHOD:[PRIVATE]:ESCAPED{_isoweek1monday}(PARAMETERS{ESCAPED{year}}):
216.173 -_test:METHOD:[PRIVATE]:ESCAPED{_test}:
217.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testFix1.fixed Sun Jan 04 13:11:53 2015 -0600
217.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
217.3 @@ -1,2011 +0,0 @@
217.4 -"""Concrete date/time and related types -- prototype implemented in Python.
217.5 -
217.6 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
217.7 -
217.8 -See also http://dir.yahoo.com/Reference/calendars/
217.9 -
217.10 -For a primer on DST, including many current DST rules, see
217.11 -http://webexhibits.org/daylightsaving/
217.12 -
217.13 -For more about DST than you ever wanted to know, see
217.14 -ftp://elsie.nci.nih.gov/pub/
217.15 -
217.16 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
217.17 -
217.18 -"""
217.19 -
217.20 -import time as _time
217.21 -import math as _math
217.22 -
217.23 -MINYEAR = 1
217.24 -MAXYEAR = 9999
217.25 -
217.26 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
217.27 -# also assumes the current Gregorian calendar indefinitely extended in
217.28 -# both directions. Difference: Dates.py calls January 1 of year 0 day
217.29 -# number 1. The code here calls January 1 of year 1 day number 1. This is
217.30 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
217.31 -# and Reingold's "Calendrical Calculations", where it's the base calendar
217.32 -# for all computations. See the book for algorithms for converting between
217.33 -# proleptic Gregorian ordinals and many other calendar systems.
217.34 -
217.35 -_DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
217.36 -
217.37 -_DAYS_BEFORE_MONTH = [None]
217.38 -dbm = 0
217.39 -for dim in _DAYS_IN_MONTH[1:]:
217.40 - _DAYS_BEFORE_MONTH.append(dbm)
217.41 - dbm += dim
217.42 -del dbm, dim
217.43 -
217.44 -def _is_leap(year):
217.45 - "year -> 1 if leap year, else 0."
217.46 - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
217.47 -
217.48 -def _days_in_year(year):
217.49 - "year -> number of days in year (366 if a leap year, else 365)."
217.50 - return 365 + _is_leap(year)
217.51 -
217.52 -def _days_before_year(year):
217.53 - "year -> number of days before January 1st of year."
217.54 - y = year - 1
217.55 - return y*365 + y//4 - y//100 + y//400
217.56 -
217.57 -def _days_in_month(year, month):
217.58 - "year, month -> number of days in that month in that year."
217.59 - try:
217.60 - assert 1 <= month <= 12, month
217.61 - if month == 2 and _is_leap(year):
217.62 - return 29
217.63 - except Exception, e:
217.64 - print "Exception: ", e
217.65 - return _DAYS_IN_MONTH[month]
217.66 -
217.67 -def _days_before_month(year, month):
217.68 - "year, month -> number of days in year preceeding first day of month."
217.69 - if not 1 <= month <= 12:
217.70 - raise ValueError('month must be in 1..12', month)
217.71 - return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
217.72 -
217.73 -def _ymd2ord(year, month, day):
217.74 - "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
217.75 - if not 1 <= month <= 12:
217.76 - raise ValueError('month must be in 1..12', month)
217.77 - dim = _days_in_month(year, month)
217.78 - if not 1 <= day <= dim:
217.79 - raise ValueError('day must be in 1..%d' % dim, day)
217.80 - return (_days_before_year(year) +
217.81 - _days_before_month(year, month) +
217.82 - day)
217.83 -
217.84 -_DI400Y = _days_before_year(401) # number of days in 400 years
217.85 -_DI100Y = _days_before_year(101) # " " " " 100 "
217.86 -_DI4Y = _days_before_year(5) # " " " " 4 "
217.87 -
217.88 -# A 4-year cycle has an extra leap day over what we'd get from pasting
217.89 -# together 4 single years.
217.90 -assert _DI4Y == 4 * 365 + 1
217.91 -
217.92 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
217.93 -# pasting together 4 100-year cycles.
217.94 -assert _DI400Y == 4 * _DI100Y + 1
217.95 -
217.96 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
217.97 -# pasting together 25 4-year cycles.
217.98 -assert _DI100Y == 25 * _DI4Y - 1
217.99 -
217.100 -def _ord2ymd(n):
217.101 - "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
217.102 -
217.103 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
217.104 - # repeats exactly every 400 years. The basic strategy is to find the
217.105 - # closest 400-year boundary at or before n, then work with the offset
217.106 - # from that boundary to n. Life is much clearer if we subtract 1 from
217.107 - # n first -- then the values of n at 400-year boundaries are exactly
217.108 - # those divisible by _DI400Y:
217.109 - #
217.110 - # D M Y n n-1
217.111 - # -- --- ---- ---------- ----------------
217.112 - # 31 Dec -400 -_DI400Y -_DI400Y -1
217.113 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
217.114 - # ...
217.115 - # 30 Dec 000 -1 -2
217.116 - # 31 Dec 000 0 -1
217.117 - # 1 Jan 001 1 0 400-year boundary
217.118 - # 2 Jan 001 2 1
217.119 - # 3 Jan 001 3 2
217.120 - # ...
217.121 - # 31 Dec 400 _DI400Y _DI400Y -1
217.122 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
217.123 - n -= 1
217.124 - n400, n = divmod(n, _DI400Y)
217.125 - year = n400 * 400 + 1 # ..., -399, 1, 401, ...
217.126 -
217.127 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
217.128 - # the desired date. Now compute how many 100-year cycles precede n.
217.129 - # Note that it's possible for n100 to equal 4! In that case 4 full
217.130 - # 100-year cycles precede the desired day, which implies the desired
217.131 - # day is December 31 at the end of a 400-year cycle.
217.132 - n100, n = divmod(n, _DI100Y)
217.133 -
217.134 - # Now compute how many 4-year cycles precede it.
217.135 - n4, n = divmod(n, _DI4Y)
217.136 -
217.137 - # And now how many single years. Again n1 can be 4, and again meaning
217.138 - # that the desired day is December 31 at the end of the 4-year cycle.
217.139 - n1, n = divmod(n, 365)
217.140 -
217.141 - year += n100 * 100 + n4 * 4 + n1
217.142 - if n1 == 4 or n100 == 4:
217.143 - assert n == 0
217.144 - return year-1, 12, 31
217.145 -
217.146 - # Now the year is correct, and n is the offset from January 1. We find
217.147 - # the month via an estimate that's either exact or one too large.
217.148 - leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
217.149 - assert leapyear == _is_leap(year)
217.150 - month = (n + 50) >> 5
217.151 - preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
217.152 - if preceding > n: # estimate is too large
217.153 - month -= 1
217.154 - preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
217.155 - n -= preceding
217.156 - assert 0 <= n < _days_in_month(year, month)
217.157 -
217.158 - # Now the year and month are correct, and n is the offset from the
217.159 - # start of that month: we're done!
217.160 - return year, month, n+1
217.161 -
217.162 -# Month and day names. For localized versions, see the calendar module.
217.163 -_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
217.164 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
217.165 -_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
217.166 -
217.167 -
217.168 -def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
217.169 - wday = (_ymd2ord(y, m, d) + 6) % 7
217.170 - dnum = _days_before_month(y, m) + d
217.171 - return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
217.172 -
217.173 -def _format_time(hh, mm, ss, us):
217.174 - # Skip trailing microseconds when us==0.
217.175 - result = "%02d:%02d:%02d" % (hh, mm, ss)
217.176 - if us:
217.177 - result += ".%06d" % us
217.178 - return result
217.179 -
217.180 -# Correctly substitute for %z and %Z escapes in strftime formats.
217.181 -def _wrap_strftime(object, format, timetuple):
217.182 - year = timetuple[0]
217.183 - if year < 1900:
217.184 - raise ValueError("year=%d is before 1900; the datetime strftime() "
217.185 - "methods require year >= 1900" % year)
217.186 - # Don't call _utcoffset() or tzname() unless actually needed.
217.187 - zreplace = None # the string to use for %z
217.188 - Zreplace = None # the string to use for %Z
217.189 -
217.190 - # Scan format for %z and %Z escapes, replacing as needed.
217.191 - newformat = []
217.192 - push = newformat.append
217.193 - i, n = 0, len(format)
217.194 - while i < n:
217.195 - ch = format[i]
217.196 - i += 1
217.197 - if ch == '%':
217.198 - if i < n:
217.199 - ch = format[i]
217.200 - i += 1
217.201 - if ch == 'z':
217.202 - if zreplace is None:
217.203 - zreplace = ""
217.204 - if hasattr(object, "_utcoffset"):
217.205 - offset = object._utcoffset()
217.206 - if offset is not None:
217.207 - sign = '+'
217.208 - if offset < 0:
217.209 - offset = -offset
217.210 - sign = '-'
217.211 - h, m = divmod(offset, 60)
217.212 - zreplace = '%c%02d%02d' % (sign, h, m)
217.213 - assert '%' not in zreplace
217.214 - newformat.append(zreplace)
217.215 - elif ch == 'Z':
217.216 - if Zreplace is None:
217.217 - Zreplace = ""
217.218 - if hasattr(object, "tzname"):
217.219 - s = object.tzname()
217.220 - if s is not None:
217.221 - # strftime is going to have at this: escape %
217.222 - Zreplace = s.replace('%', '%%')
217.223 - newformat.append(Zreplace)
217.224 - else:
217.225 - push('%')
217.226 - push(ch)
217.227 - else:
217.228 - push('%')
217.229 - else:
217.230 - push(ch)
217.231 - newformat = "".join(newformat)
217.232 - return _time.strftime(newformat, timetuple)
217.233 -
217.234 -def _call_tzinfo_method(tzinfo, methname, tzinfoarg):
217.235 - if tzinfo is None:
217.236 - return None
217.237 - return getattr(tzinfo, methname)(tzinfoarg)
217.238 -
217.239 -# Just raise TypeError if the arg isn't None or a string.
217.240 -def _check_tzname(name):
217.241 - if name is not None and not isinstance(name, str):
217.242 - raise TypeError("tzinfo.tzname() must return None or string, "
217.243 - "not '%s'" % type(name))
217.244 -
217.245 -# name is the offset-producing method, "utcoffset" or "dst".
217.246 -# offset is what it returned.
217.247 -# If offset isn't None or timedelta, raises TypeError.
217.248 -# If offset is None, returns None.
217.249 -# Else offset is checked for being in range, and a whole # of minutes.
217.250 -# If it is, its integer value is returned. Else ValueError is raised.
217.251 -def _check_utc_offset(name, offset):
217.252 - assert name in ("utcoffset", "dst")
217.253 - if offset is None:
217.254 - return None
217.255 - if not isinstance(offset, timedelta):
217.256 - raise TypeError("tzinfo.%s() must return None "
217.257 - "or timedelta, not '%s'" % (name, type(offset)))
217.258 - days = offset.days
217.259 - if days < -1 or days > 0:
217.260 - offset = 1440 # trigger out-of-range
217.261 - else:
217.262 - seconds = days * 86400 + offset.seconds
217.263 - minutes, seconds = divmod(seconds, 60)
217.264 - if seconds or offset.microseconds:
217.265 - raise ValueError("tzinfo.%s() must return a whole number "
217.266 - "of minutes" % name)
217.267 - offset = minutes
217.268 - if -1440 < offset < 1440:
217.269 - return offset
217.270 - raise ValueError("%s()=%d, must be in -1439..1439" % (name, offset))
217.271 -
217.272 -def _check_date_fields(year, month, day):
217.273 - if not MINYEAR <= year <= MAXYEAR:
217.274 - raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
217.275 - if not 1 <= month <= 12:
217.276 - raise ValueError('month must be in 1..12', month)
217.277 - dim = _days_in_month(year, month)
217.278 - if not 1 <= day <= dim:
217.279 - raise ValueError('day must be in 1..%d' % dim, day)
217.280 -
217.281 -def _check_time_fields(hour, minute, second, microsecond):
217.282 - if not 0 <= hour <= 23:
217.283 - raise ValueError('hour must be in 0..23', hour)
217.284 - if not 0 <= minute <= 59:
217.285 - raise ValueError('minute must be in 0..59', minute)
217.286 - if not 0 <= second <= 59:
217.287 - raise ValueError('second must be in 0..59', second)
217.288 - if not 0 <= microsecond <= 999999:
217.289 - raise ValueError('microsecond must be in 0..999999', microsecond)
217.290 -
217.291 -def _check_tzinfo_arg(tz):
217.292 - if tz is not None and not isinstance(tz, tzinfo):
217.293 - raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
217.294 -
217.295 -
217.296 -# Notes on comparison: In general, datetime module comparison operators raise
217.297 -# TypeError when they don't know how to do a comparison themself. If they
217.298 -# returned NotImplemented instead, comparison could (silently) fall back to
217.299 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
217.300 -# and that's not helpful. There are two exceptions:
217.301 -#
217.302 -# 1. For date and datetime, if the other object has a "timetuple" attr,
217.303 -# NotImplemented is returned. This is a hook to allow other kinds of
217.304 -# datetime-like objects a chance to intercept the comparison.
217.305 -#
217.306 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
217.307 -# so opertaions like
217.308 -#
217.309 -# x == y
217.310 -# x != y
217.311 -# x in sequence
217.312 -# x not in sequence
217.313 -# dict[x] = y
217.314 -#
217.315 -# don't raise annoying TypeErrors just because a datetime object
217.316 -# is part of a heterogeneous collection. If there's no known way to
217.317 -# compare X to a datetime, saying they're not equal is reasonable.
217.318 -
217.319 -def _cmperror(x, y):
217.320 - raise TypeError("can't compare '%s' to '%s'" % (
217.321 - type(x).__name__, type(y).__name__))
217.322 -
217.323 -# This is a start at a struct tm workalike. Goals:
217.324 -#
217.325 -# + Works the same way across platforms.
217.326 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
217.327 -#
217.328 -# Note: I suspect it's best if this flavor of tm does *not* try to
217.329 -# second-guess timezones or DST. Instead fold whatever adjustments you want
217.330 -# into the minutes argument (and the constructor will normalize).
217.331 -
217.332 -_ORD1970 = _ymd2ord(1970, 1, 1) # base ordinal for UNIX epoch
217.333 -
217.334 -class tmxxx:
217.335 -
217.336 - ordinal = None
217.337 -
217.338 - def __init__(self, year, month, day, hour=0, minute=0, second=0,
217.339 - microsecond=0):
217.340 - # Normalize all the inputs, and store the normalized values.
217.341 - if not 0 <= microsecond <= 999999:
217.342 - carry, microsecond = divmod(microsecond, 1000000)
217.343 - second += carry
217.344 - if not 0 <= second <= 59:
217.345 - carry, second = divmod(second, 60)
217.346 - minute += carry
217.347 - if not 0 <= minute <= 59:
217.348 - carry, minute = divmod(minute, 60)
217.349 - hour += carry
217.350 - if not 0 <= hour <= 23:
217.351 - carry, hour = divmod(hour, 24)
217.352 - day += carry
217.353 -
217.354 - # That was easy. Now it gets muddy: the proper range for day
217.355 - # can't be determined without knowing the correct month and year,
217.356 - # but if day is, e.g., plus or minus a million, the current month
217.357 - # and year values make no sense (and may also be out of bounds
217.358 - # themselves).
217.359 - # Saying 12 months == 1 year should be non-controversial.
217.360 - if not 1 <= month <= 12:
217.361 - carry, month = divmod(month-1, 12)
217.362 - year += carry
217.363 - month += 1
217.364 - assert 1 <= month <= 12
217.365 -
217.366 - # Now only day can be out of bounds (year may also be out of bounds
217.367 - # for a datetime object, but we don't care about that here).
217.368 - # If day is out of bounds, what to do is arguable, but at least the
217.369 - # method here is principled and explainable.
217.370 - dim = _days_in_month(year, month)
217.371 - if not 1 <= day <= dim:
217.372 - # Move day-1 days from the first of the month. First try to
217.373 - # get off cheap if we're only one day out of range (adjustments
217.374 - # for timezone alone can't be worse than that).
217.375 - if day == 0: # move back a day
217.376 - month -= 1
217.377 - if month > 0:
217.378 - day = _days_in_month(year, month)
217.379 - else:
217.380 - year, month, day = year-1, 12, 31
217.381 - elif day == dim + 1: # move forward a day
217.382 - month += 1
217.383 - day = 1
217.384 - if month > 12:
217.385 - month = 1
217.386 - year += 1
217.387 - else:
217.388 - self.ordinal = _ymd2ord(year, month, 1) + (day - 1)
217.389 - year, month, day = _ord2ymd(self.ordinal)
217.390 -
217.391 - self.year, self.month, self.day = year, month, day
217.392 - self.hour, self.minute, self.second = hour, minute, second
217.393 - self.microsecond = microsecond
217.394 -
217.395 - def toordinal(self):
217.396 - """Return proleptic Gregorian ordinal for the year, month and day.
217.397 -
217.398 - January 1 of year 1 is day 1. Only the year, month and day values
217.399 - contribute to the result.
217.400 - """
217.401 - if self.ordinal is None:
217.402 - self.ordinal = _ymd2ord(self.year, self.month, self.day)
217.403 - return self.ordinal
217.404 -
217.405 - def time(self):
217.406 - "Return Unixish timestamp, as a float (assuming UTC)."
217.407 - days = self.toordinal() - _ORD1970 # convert to UNIX epoch
217.408 - seconds = ((days * 24. + self.hour)*60. + self.minute)*60.
217.409 - return seconds + self.second + self.microsecond / 1e6
217.410 -
217.411 - def ctime(self):
217.412 - "Return ctime() style string."
217.413 - weekday = self.toordinal() % 7 or 7
217.414 - return "%s %s %2d %02d:%02d:%02d %04d" % (
217.415 - _DAYNAMES[weekday],
217.416 - _MONTHNAMES[self.month],
217.417 - self.day,
217.418 - self.hour, self.minute, self.second,
217.419 - self.year)
217.420 -
217.421 -class timedelta(object):
217.422 - """Represent the difference between two datetime objects.
217.423 -
217.424 - Supported operators:
217.425 -
217.426 - - add, subtract timedelta
217.427 - - unary plus, minus, abs
217.428 - - compare to timedelta
217.429 - - multiply, divide by int/long
217.430 -
217.431 - In addition, datetime supports subtraction of two datetime objects
217.432 - returning a timedelta, and addition or subtraction of a datetime
217.433 - and a timedelta giving a datetime.
217.434 -
217.435 - Representation: (days, seconds, microseconds). Why? Because I
217.436 - felt like it.
217.437 - """
217.438 -
217.439 - def __new__(cls, days=0, seconds=0, microseconds=0,
217.440 - # XXX The following should only be used as keyword args:
217.441 - milliseconds=0, minutes=0, hours=0, weeks=0):
217.442 - # Doing this efficiently and accurately in C is going to be difficult
217.443 - # and error-prone, due to ubiquitous overflow possibilities, and that
217.444 - # C double doesn't have enough bits of precision to represent
217.445 - # microseconds over 10K years faithfully. The code here tries to make
217.446 - # explicit where go-fast assumptions can be relied on, in order to
217.447 - # guide the C implementation; it's way more convoluted than speed-
217.448 - # ignoring auto-overflow-to-long idiomatic Python could be.
217.449 -
217.450 - # XXX Check that all inputs are ints, longs or floats.
217.451 -
217.452 - # Final values, all integer.
217.453 - # s and us fit in 32-bit signed ints; d isn't bounded.
217.454 - d = s = us = 0
217.455 -
217.456 - # Normalize everything to days, seconds, microseconds.
217.457 - days += weeks*7
217.458 - seconds += minutes*60 + hours*3600
217.459 - microseconds += milliseconds*1000
217.460 -
217.461 - # Get rid of all fractions, and normalize s and us.
217.462 - # Take a deep breath <wink>.
217.463 - if isinstance(days, float):
217.464 - dayfrac, days = _math.modf(days)
217.465 - daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
217.466 - assert daysecondswhole == int(daysecondswhole) # can't overflow
217.467 - s = int(daysecondswhole)
217.468 - assert days == long(days)
217.469 - d = long(days)
217.470 - else:
217.471 - daysecondsfrac = 0.0
217.472 - d = days
217.473 - assert isinstance(daysecondsfrac, float)
217.474 - assert abs(daysecondsfrac) <= 1.0
217.475 - assert isinstance(d, (int, long))
217.476 - assert abs(s) <= 24 * 3600
217.477 - # days isn't referenced again before redefinition
217.478 -
217.479 - if isinstance(seconds, float):
217.480 - secondsfrac, seconds = _math.modf(seconds)
217.481 - assert seconds == long(seconds)
217.482 - seconds = long(seconds)
217.483 - secondsfrac += daysecondsfrac
217.484 - assert abs(secondsfrac) <= 2.0
217.485 - else:
217.486 - secondsfrac = daysecondsfrac
217.487 - # daysecondsfrac isn't referenced again
217.488 - assert isinstance(secondsfrac, float)
217.489 - assert abs(secondsfrac) <= 2.0
217.490 -
217.491 - assert isinstance(seconds, (int, long))
217.492 - days, seconds = divmod(seconds, 24*3600)
217.493 - d += days
217.494 - s += int(seconds) # can't overflow
217.495 - assert isinstance(s, int)
217.496 - assert abs(s) <= 2 * 24 * 3600
217.497 - # seconds isn't referenced again before redefinition
217.498 -
217.499 - usdouble = secondsfrac * 1e6
217.500 - assert abs(usdouble) < 2.1e6 # exact value not critical
217.501 - # secondsfrac isn't referenced again
217.502 -
217.503 - if isinstance(microseconds, float):
217.504 - microseconds += usdouble
217.505 - microseconds = round(microseconds)
217.506 - seconds, microseconds = divmod(microseconds, 1e6)
217.507 - assert microseconds == int(microseconds)
217.508 - assert seconds == long(seconds)
217.509 - days, seconds = divmod(seconds, 24.*3600.)
217.510 - assert days == long(days)
217.511 - assert seconds == int(seconds)
217.512 - d += long(days)
217.513 - s += int(seconds) # can't overflow
217.514 - assert isinstance(s, int)
217.515 - assert abs(s) <= 3 * 24 * 3600
217.516 - else:
217.517 - seconds, microseconds = divmod(microseconds, 1000000)
217.518 - days, seconds = divmod(seconds, 24*3600)
217.519 - d += days
217.520 - s += int(seconds) # can't overflow
217.521 - assert isinstance(s, int)
217.522 - assert abs(s) <= 3 * 24 * 3600
217.523 - microseconds = float(microseconds)
217.524 - microseconds += usdouble
217.525 - microseconds = round(microseconds)
217.526 - assert abs(s) <= 3 * 24 * 3600
217.527 - assert abs(microseconds) < 3.1e6
217.528 -
217.529 - # Just a little bit of carrying possible for microseconds and seconds.
217.530 - assert isinstance(microseconds, float)
217.531 - assert int(microseconds) == microseconds
217.532 - us = int(microseconds)
217.533 - seconds, us = divmod(us, 1000000)
217.534 - s += seconds # cant't overflow
217.535 - assert isinstance(s, int)
217.536 - days, s = divmod(s, 24*3600)
217.537 - d += days
217.538 -
217.539 - assert isinstance(d, (int, long))
217.540 - assert isinstance(s, int) and 0 <= s < 24*3600
217.541 - assert isinstance(us, int) and 0 <= us < 1000000
217.542 -
217.543 - self = object.__new__(cls)
217.544 -
217.545 - self.__days = d
217.546 - self.__seconds = s
217.547 - self.__microseconds = us
217.548 - if abs(d) > 999999999:
217.549 - raise OverflowError("timedelta # of days is too large: %d" % d)
217.550 -
217.551 - return self
217.552 -
217.553 - def __repr__(self):
217.554 - if self.__microseconds:
217.555 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
217.556 - self.__days,
217.557 - self.__seconds,
217.558 - self.__microseconds)
217.559 - if self.__seconds:
217.560 - return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__,
217.561 - self.__days,
217.562 - self.__seconds)
217.563 - return "%s(%d)" % ('datetime.' + self.__class__.__name__, self.__days)
217.564 -
217.565 - def __str__(self):
217.566 - mm, ss = divmod(self.__seconds, 60)
217.567 - hh, mm = divmod(mm, 60)
217.568 - s = "%d:%02d:%02d" % (hh, mm, ss)
217.569 - if self.__days:
217.570 - def plural(n):
217.571 - return n, abs(n) != 1 and "s" or ""
217.572 - s = ("%d day%s, " % plural(self.__days)) + s
217.573 - if self.__microseconds:
217.574 - s = s + ".%06d" % self.__microseconds
217.575 - return s
217.576 -
217.577 - days = property(lambda self: self.__days, doc="days")
217.578 - seconds = property(lambda self: self.__seconds, doc="seconds")
217.579 - microseconds = property(lambda self: self.__microseconds,
217.580 - doc="microseconds")
217.581 -
217.582 - def __add__(self, other):
217.583 - if isinstance(other, timedelta):
217.584 - return timedelta(self.__days + other.__days,
217.585 - self.__seconds + other.__seconds,
217.586 - self.__microseconds + other.__microseconds)
217.587 - return NotImplemented
217.588 -
217.589 - __radd__ = __add__
217.590 -
217.591 - def __sub__(self, other):
217.592 - if isinstance(other, timedelta):
217.593 - return self + -other
217.594 - return NotImplemented
217.595 -
217.596 - def __rsub__(self, other):
217.597 - if isinstance(other, timedelta):
217.598 - return -self + other
217.599 - return NotImplemented
217.600 -
217.601 - def __neg__(self):
217.602 - return self.__class__(-self.__days,
217.603 - -self.__seconds,
217.604 - -self.__microseconds)
217.605 -
217.606 - def __pos__(self):
217.607 - return self
217.608 -
217.609 - def __abs__(self):
217.610 - if self.__days < 0:
217.611 - return -self
217.612 - else:
217.613 - return self
217.614 -
217.615 - def __mul__(self, other):
217.616 - if isinstance(other, (int, long)):
217.617 - return self.__class__(self.__days * other,
217.618 - self.__seconds * other,
217.619 - self.__microseconds * other)
217.620 - return NotImplemented
217.621 -
217.622 - __rmul__ = __mul__
217.623 -
217.624 - def __div__(self, other):
217.625 - if isinstance(other, (int, long)):
217.626 - usec = ((self.__days * (24*3600L) + self.__seconds) * 1000000 +
217.627 - self.__microseconds)
217.628 - return self.__class__(0, 0, usec // other)
217.629 - return NotImplemented
217.630 -
217.631 - __floordiv__ = __div__
217.632 -
217.633 - # Comparisons.
217.634 -
217.635 - def __eq__(self, other):
217.636 - if isinstance(other, timedelta):
217.637 - return self.__cmp(other) == 0
217.638 - else:
217.639 - return False
217.640 -
217.641 - def __ne__(self, other):
217.642 - if isinstance(other, timedelta):
217.643 - return self.__cmp(other) != 0
217.644 - else:
217.645 - return True
217.646 -
217.647 - def __le__(self, other):
217.648 - if isinstance(other, timedelta):
217.649 - return self.__cmp(other) <= 0
217.650 - else:
217.651 - _cmperror(self, other)
217.652 -
217.653 - def __lt__(self, other):
217.654 - if isinstance(other, timedelta):
217.655 - return self.__cmp(other) < 0
217.656 - else:
217.657 - _cmperror(self, other)
217.658 -
217.659 - def __ge__(self, other):
217.660 - if isinstance(other, timedelta):
217.661 - return self.__cmp(other) >= 0
217.662 - else:
217.663 - _cmperror(self, other)
217.664 -
217.665 - def __gt__(self, other):
217.666 - if isinstance(other, timedelta):
217.667 - return self.__cmp(other) > 0
217.668 - else:
217.669 - _cmperror(self, other)
217.670 -
217.671 - def __cmp(self, other):
217.672 - assert isinstance(other, timedelta)
217.673 - return cmp(self.__getstate(), other.__getstate())
217.674 -
217.675 - def __hash__(self):
217.676 - return hash(self.__getstate())
217.677 -
217.678 - def __nonzero__(self):
217.679 - return (self.__days != 0 or
217.680 - self.__seconds != 0 or
217.681 - self.__microseconds != 0)
217.682 -
217.683 - # Pickle support.
217.684 -
217.685 - __safe_for_unpickling__ = True # For Python 2.2
217.686 -
217.687 - def __getstate(self):
217.688 - return (self.__days, self.__seconds, self.__microseconds)
217.689 -
217.690 - def __reduce__(self):
217.691 - return (self.__class__, self.__getstate())
217.692 -
217.693 -timedelta.min = timedelta(-999999999)
217.694 -timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
217.695 - microseconds=999999)
217.696 -timedelta.resolution = timedelta(microseconds=1)
217.697 -
217.698 -class date(object):
217.699 - """Concrete date type.
217.700 -
217.701 - Constructors:
217.702 -
217.703 - __new__()
217.704 - fromtimestamp()
217.705 - today()
217.706 - fromordinal()
217.707 -
217.708 - Operators:
217.709 -
217.710 - __repr__, __str__
217.711 - __cmp__, __hash__
217.712 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
217.713 -
217.714 - Methods:
217.715 -
217.716 - timetuple()
217.717 - toordinal()
217.718 - weekday()
217.719 - isoweekday(), isocalendar(), isoformat()
217.720 - ctime()
217.721 - strftime()
217.722 -
217.723 - Properties (readonly):
217.724 - year, month, day
217.725 - """
217.726 -
217.727 - def __new__(cls, year, month=None, day=None):
217.728 - """Constructor.
217.729 -
217.730 - Arguments:
217.731 -
217.732 - year, month, day (required, base 1)
217.733 - """
217.734 - if isinstance(year, str):
217.735 - # Pickle support
217.736 - self = object.__new__(cls)
217.737 - self.__setstate((year,))
217.738 - return self
217.739 - _check_date_fields(year, month, day)
217.740 - self = object.__new__(cls)
217.741 - self.__year = year
217.742 - self.__month = month
217.743 - self.__day = day
217.744 - return self
217.745 -
217.746 - # Additional constructors
217.747 -
217.748 - def fromtimestamp(cls, t):
217.749 - "Construct a date from a POSIX timestamp (like time.time())."
217.750 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
217.751 - return cls(y, m, d)
217.752 - fromtimestamp = classmethod(fromtimestamp)
217.753 -
217.754 - def today(cls):
217.755 - "Construct a date from time.time()."
217.756 - t = _time.time()
217.757 - return cls.fromtimestamp(t)
217.758 - today = classmethod(today)
217.759 -
217.760 - def fromordinal(cls, n):
217.761 - """Contruct a date from a proleptic Gregorian ordinal.
217.762 -
217.763 - January 1 of year 1 is day 1. Only the year, month and day are
217.764 - non-zero in the result.
217.765 - """
217.766 - y, m, d = _ord2ymd(n)
217.767 - return cls(y, m, d)
217.768 - fromordinal = classmethod(fromordinal)
217.769 -
217.770 - # Conversions to string
217.771 -
217.772 - def __repr__(self):
217.773 - "Convert to formal string, for repr()."
217.774 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
217.775 - self.__year,
217.776 - self.__month,
217.777 - self.__day)
217.778 - # XXX These shouldn't depend on time.localtime(), because that
217.779 - # clips the usable dates to [1970 .. 2038). At least ctime() is
217.780 - # easily done without using strftime() -- that's better too because
217.781 - # strftime("%c", ...) is locale specific.
217.782 -
217.783 - def ctime(self):
217.784 - "Format a la ctime()."
217.785 - return tmxxx(self.__year, self.__month, self.__day).ctime()
217.786 -
217.787 - def strftime(self, fmt):
217.788 - "Format using strftime()."
217.789 - return _wrap_strftime(self, fmt, self.timetuple())
217.790 -
217.791 - def isoformat(self):
217.792 - """Return the date formatted according to ISO.
217.793 -
217.794 - This is 'YYYY-MM-DD'.
217.795 -
217.796 - References:
217.797 - - http://www.w3.org/TR/NOTE-datetime
217.798 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
217.799 - """
217.800 - return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day)
217.801 -
217.802 - __str__ = isoformat
217.803 -
217.804 - # Read-only field accessors
217.805 - year = property(lambda self: self.__year,
217.806 - doc="year (%d-%d)" % (MINYEAR, MAXYEAR))
217.807 - month = property(lambda self: self.__month, doc="month (1-12)")
217.808 - day = property(lambda self: self.__day, doc="day (1-31)")
217.809 -
217.810 - # Standard conversions, __cmp__, __hash__ (and helpers)
217.811 -
217.812 - def timetuple(self):
217.813 - "Return local time tuple compatible with time.localtime()."
217.814 - return _build_struct_time(self.__year, self.__month, self.__day,
217.815 - 0, 0, 0, -1)
217.816 -
217.817 - def toordinal(self):
217.818 - """Return proleptic Gregorian ordinal for the year, month and day.
217.819 -
217.820 - January 1 of year 1 is day 1. Only the year, month and day values
217.821 - contribute to the result.
217.822 - """
217.823 - return _ymd2ord(self.__year, self.__month, self.__day)
217.824 -
217.825 - def replace(self, year=None, month=None, day=None):
217.826 - """Return a new date with new values for the specified fields."""
217.827 - if year is None:
217.828 - year = self.__year
217.829 - if month is None:
217.830 - month = self.__month
217.831 - if day is None:
217.832 - day = self.__day
217.833 - _check_date_fields(year, month, day)
217.834 - return date(year, month, day)
217.835 -
217.836 - # Comparisons.
217.837 -
217.838 - def __eq__(self, other):
217.839 - if isinstance(other, date):
217.840 - return self.__cmp(other) == 0
217.841 - elif hasattr(other, "timetuple"):
217.842 - return NotImplemented
217.843 - else:
217.844 - return False
217.845 -
217.846 - def __ne__(self, other):
217.847 - if isinstance(other, date):
217.848 - return self.__cmp(other) != 0
217.849 - elif hasattr(other, "timetuple"):
217.850 - return NotImplemented
217.851 - else:
217.852 - return True
217.853 -
217.854 - def __le__(self, other):
217.855 - if isinstance(other, date):
217.856 - return self.__cmp(other) <= 0
217.857 - elif hasattr(other, "timetuple"):
217.858 - return NotImplemented
217.859 - else:
217.860 - _cmperror(self, other)
217.861 -
217.862 - def __lt__(self, other):
217.863 - if isinstance(other, date):
217.864 - return self.__cmp(other) < 0
217.865 - elif hasattr(other, "timetuple"):
217.866 - return NotImplemented
217.867 - else:
217.868 - _cmperror(self, other)
217.869 -
217.870 - def __ge__(self, other):
217.871 - if isinstance(other, date):
217.872 - return self.__cmp(other) >= 0
217.873 - elif hasattr(other, "timetuple"):
217.874 - return NotImplemented
217.875 - else:
217.876 - _cmperror(self, other)
217.877 -
217.878 - def __gt__(self, other):
217.879 - if isinstance(other, date):
217.880 - return self.__cmp(other) > 0
217.881 - elif hasattr(other, "timetuple"):
217.882 - return NotImplemented
217.883 - else:
217.884 - _cmperror(self, other)
217.885 -
217.886 - def __cmp(self, other):
217.887 - assert isinstance(other, date)
217.888 - y, m, d = self.__year, self.__month, self.__day
217.889 - y2, m2, d2 = other.__year, other.__month, other.__day
217.890 - return cmp((y, m, d), (y2, m2, d2))
217.891 -
217.892 - def __hash__(self):
217.893 - "Hash."
217.894 - return hash(self.__getstate())
217.895 -
217.896 - # Computations
217.897 -
217.898 - def _checkOverflow(self, year):
217.899 - if not MINYEAR <= year <= MAXYEAR:
217.900 - raise OverflowError("date +/-: result year %d not in %d..%d" %
217.901 - (year, MINYEAR, MAXYEAR))
217.902 -
217.903 - def __add__(self, other):
217.904 - "Add a date to a timedelta."
217.905 - if isinstance(other, timedelta):
217.906 - t = tmxxx(self.__year,
217.907 - self.__month,
217.908 - self.__day + other.days)
217.909 - self._checkOverflow(t.year)
217.910 - result = self.__class__(t.year, t.month, t.day)
217.911 - return result
217.912 - return NotImplemented
217.913 -
217.914 - __radd__ = __add__
217.915 -
217.916 - def __sub__(self, other):
217.917 - """Subtract two dates, or a date and a timedelta."""
217.918 - if isinstance(other, timedelta):
217.919 - return self + timedelta(-other.days)
217.920 - if isinstance(other, date):
217.921 - days1 = self.toordinal()
217.922 - days2 = other.toordinal()
217.923 - return timedelta(days1 - days2)
217.924 - return NotImplemented
217.925 -
217.926 - def weekday(self):
217.927 - "Return day of the week, where Monday == 0 ... Sunday == 6."
217.928 - return (self.toordinal() + 6) % 7
217.929 -
217.930 - # Day-of-the-week and week-of-the-year, according to ISO
217.931 -
217.932 - def isoweekday(self):
217.933 - "Return day of the week, where Monday == 1 ... Sunday == 7."
217.934 - # 1-Jan-0001 is a Monday
217.935 - return self.toordinal() % 7 or 7
217.936 -
217.937 - def isocalendar(self):
217.938 - """Return a 3-tuple containing ISO year, week number, and weekday.
217.939 -
217.940 - The first ISO week of the year is the (Mon-Sun) week
217.941 - containing the year's first Thursday; everything else derives
217.942 - from that.
217.943 -
217.944 - The first week is 1; Monday is 1 ... Sunday is 7.
217.945 -
217.946 - ISO calendar algorithm taken from
217.947 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
217.948 - """
217.949 - year = self.__year
217.950 - week1monday = _isoweek1monday(year)
217.951 - today = _ymd2ord(self.__year, self.__month, self.__day)
217.952 - # Internally, week and day have origin 0
217.953 - week, day = divmod(today - week1monday, 7)
217.954 - if week < 0:
217.955 - year -= 1
217.956 - week1monday = _isoweek1monday(year)
217.957 - week, day = divmod(today - week1monday, 7)
217.958 - elif week >= 52:
217.959 - if today >= _isoweek1monday(year+1):
217.960 - year += 1
217.961 - week = 0
217.962 - return year, week+1, day+1
217.963 -
217.964 - # Pickle support.
217.965 -
217.966 - __safe_for_unpickling__ = True # For Python 2.2
217.967 -
217.968 - def __getstate(self):
217.969 - yhi, ylo = divmod(self.__year, 256)
217.970 - return ("%c%c%c%c" % (yhi, ylo, self.__month, self.__day), )
217.971 -
217.972 - def __setstate(self, t):
217.973 - assert isinstance(t, tuple) and len(t) == 1, `t`
217.974 - string = t[0]
217.975 - assert len(string) == 4
217.976 - yhi, ylo, self.__month, self.__day = map(ord, string)
217.977 - self.__year = yhi * 256 + ylo
217.978 -
217.979 - def __reduce__(self):
217.980 - return (self.__class__, self.__getstate())
217.981 -
217.982 -_date_class = date # so functions w/ args named "date" can get at the class
217.983 -
217.984 -date.min = date(1, 1, 1)
217.985 -date.max = date(9999, 12, 31)
217.986 -date.resolution = timedelta(days=1)
217.987 -
217.988 -class tzinfo(object):
217.989 - """Abstract base class for time zone info classes.
217.990 -
217.991 - Subclasses must override the name(), utcoffset() and dst() methods.
217.992 - """
217.993 -
217.994 - def tzname(self, dt):
217.995 - "datetime -> string name of time zone."
217.996 - raise NotImplementedError("tzinfo subclass must override tzname()")
217.997 -
217.998 - def utcoffset(self, dt):
217.999 - "datetime -> minutes east of UTC (negative for west of UTC)"
217.1000 - raise NotImplementedError("tzinfo subclass must override utcoffset()")
217.1001 -
217.1002 - def dst(self, dt):
217.1003 - """datetime -> DST offset in minutes east of UTC.
217.1004 -
217.1005 - Return 0 if DST not in effect. utcoffset() must include the DST
217.1006 - offset.
217.1007 - """
217.1008 - raise NotImplementedError("tzinfo subclass must override dst()")
217.1009 -
217.1010 - def fromutc(self, dt):
217.1011 - "datetime in UTC -> datetime in local time."
217.1012 -
217.1013 - if not isinstance(dt, datetime):
217.1014 - raise TypeError("fromutc() requires a datetime argument")
217.1015 - if dt.tzinfo is not self:
217.1016 - raise ValueError("dt.tzinfo is not self")
217.1017 -
217.1018 - dtoff = dt.utcoffset()
217.1019 - if dtoff is None:
217.1020 - raise ValueError("fromutc() requires a non-None utcoffset() "
217.1021 - "result")
217.1022 -
217.1023 - # See the long comment block at the end of this file for an
217.1024 - # explanation of this algorithm.
217.1025 - dtdst = dt.dst()
217.1026 - if dtdst is None:
217.1027 - raise ValueError("fromutc() requires a non-None dst() result")
217.1028 - delta = dtoff - dtdst
217.1029 - if delta:
217.1030 - dt += delta
217.1031 - dtdst = dt.dst()
217.1032 - if dtdst is None:
217.1033 - raise ValueError("fromutc(): dt.dst gave inconsistent "
217.1034 - "results; cannot convert")
217.1035 - if dtdst:
217.1036 - return dt + dtdst
217.1037 - else:
217.1038 - return dt
217.1039 -
217.1040 - # Pickle support.
217.1041 -
217.1042 - __safe_for_unpickling__ = True # For Python 2.2
217.1043 -
217.1044 - def __reduce__(self):
217.1045 - getinitargs = getattr(self, "__getinitargs__", None)
217.1046 - if getinitargs:
217.1047 - args = getinitargs()
217.1048 - else:
217.1049 - args = ()
217.1050 - getstate = getattr(self, "__getstate__", None)
217.1051 - if getstate:
217.1052 - state = getstate()
217.1053 - else:
217.1054 - state = getattr(self, "__dict__", None) or None
217.1055 - if state is None:
217.1056 - return (self.__class__, args)
217.1057 - else:
217.1058 - return (self.__class__, args, state)
217.1059 -
217.1060 -_tzinfo_class = tzinfo # so functions w/ args named "tinfo" can get at it
217.1061 -
217.1062 -class time(object):
217.1063 - """Time with time zone.
217.1064 -
217.1065 - Constructors:
217.1066 -
217.1067 - __new__()
217.1068 -
217.1069 - Operators:
217.1070 -
217.1071 - __repr__, __str__
217.1072 - __cmp__, __hash__
217.1073 -
217.1074 - Methods:
217.1075 -
217.1076 - strftime()
217.1077 - isoformat()
217.1078 - utcoffset()
217.1079 - tzname()
217.1080 - dst()
217.1081 -
217.1082 - Properties (readonly):
217.1083 - hour, minute, second, microsecond, tzinfo
217.1084 - """
217.1085 -
217.1086 - def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
217.1087 - """Constructor.
217.1088 -
217.1089 - Arguments:
217.1090 -
217.1091 - hour, minute (required)
217.1092 - second, microsecond (default to zero)
217.1093 - tzinfo (default to None)
217.1094 - """
217.1095 - self = object.__new__(cls)
217.1096 - if isinstance(hour, str):
217.1097 - # Pickle support
217.1098 - self.__setstate((hour, minute or None))
217.1099 - return self
217.1100 - _check_tzinfo_arg(tzinfo)
217.1101 - _check_time_fields(hour, minute, second, microsecond)
217.1102 - self.__hour = hour
217.1103 - self.__minute = minute
217.1104 - self.__second = second
217.1105 - self.__microsecond = microsecond
217.1106 - self._tzinfo = tzinfo
217.1107 - return self
217.1108 -
217.1109 - # Read-only field accessors
217.1110 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
217.1111 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
217.1112 - second = property(lambda self: self.__second, doc="second (0-59)")
217.1113 - microsecond = property(lambda self: self.__microsecond,
217.1114 - doc="microsecond (0-999999)")
217.1115 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
217.1116 -
217.1117 - # Standard conversions, __hash__ (and helpers)
217.1118 -
217.1119 - # Comparisons.
217.1120 -
217.1121 - def __eq__(self, other):
217.1122 - if isinstance(other, time):
217.1123 - return self.__cmp(other) == 0
217.1124 - else:
217.1125 - return False
217.1126 -
217.1127 - def __ne__(self, other):
217.1128 - if isinstance(other, time):
217.1129 - return self.__cmp(other) != 0
217.1130 - else:
217.1131 - return True
217.1132 -
217.1133 - def __le__(self, other):
217.1134 - if isinstance(other, time):
217.1135 - return self.__cmp(other) <= 0
217.1136 - else:
217.1137 - _cmperror(self, other)
217.1138 -
217.1139 - def __lt__(self, other):
217.1140 - if isinstance(other, time):
217.1141 - return self.__cmp(other) < 0
217.1142 - else:
217.1143 - _cmperror(self, other)
217.1144 -
217.1145 - def __ge__(self, other):
217.1146 - if isinstance(other, time):
217.1147 - return self.__cmp(other) >= 0
217.1148 - else:
217.1149 - _cmperror(self, other)
217.1150 -
217.1151 - def __gt__(self, other):
217.1152 - if isinstance(other, time):
217.1153 - return self.__cmp(other) > 0
217.1154 - else:
217.1155 - _cmperror(self, other)
217.1156 -
217.1157 - def __cmp(self, other):
217.1158 - assert isinstance(other, time)
217.1159 - mytz = self._tzinfo
217.1160 - ottz = other._tzinfo
217.1161 - myoff = otoff = None
217.1162 -
217.1163 - if mytz is ottz:
217.1164 - base_compare = True
217.1165 - else:
217.1166 - myoff = self._utcoffset()
217.1167 - otoff = other._utcoffset()
217.1168 - base_compare = myoff == otoff
217.1169 -
217.1170 - if base_compare:
217.1171 - return cmp((self.__hour, self.__minute, self.__second,
217.1172 - self.__microsecond),
217.1173 - (other.__hour, other.__minute, other.__second,
217.1174 - other.__microsecond))
217.1175 - if myoff is None or otoff is None:
217.1176 - # XXX Buggy in 2.2.2.
217.1177 - raise TypeError("cannot compare naive and aware times")
217.1178 - myhhmm = self.__hour * 60 + self.__minute - myoff
217.1179 - othhmm = other.__hour * 60 + other.__minute - otoff
217.1180 - return cmp((myhhmm, self.__second, self.__microsecond),
217.1181 - (othhmm, other.__second, other.__microsecond))
217.1182 -
217.1183 - def __hash__(self):
217.1184 - """Hash."""
217.1185 - tzoff = self._utcoffset()
217.1186 - if not tzoff: # zero or None
217.1187 - return hash(self.__getstate()[0])
217.1188 - h, m = divmod(self.hour * 60 + self.minute - tzoff, 60)
217.1189 - if 0 <= h < 24:
217.1190 - return hash(time(h, m, self.second, self.microsecond))
217.1191 - return hash((h, m, self.second, self.microsecond))
217.1192 -
217.1193 - # Conversion to string
217.1194 -
217.1195 - def _tzstr(self, sep=":"):
217.1196 - """Return formatted timezone offset (+xx:xx) or None."""
217.1197 - off = self._utcoffset()
217.1198 - if off is not None:
217.1199 - if off < 0:
217.1200 - sign = "-"
217.1201 - off = -off
217.1202 - else:
217.1203 - sign = "+"
217.1204 - hh, mm = divmod(off, 60)
217.1205 - assert 0 <= hh < 24
217.1206 - off = "%s%02d%s%02d" % (sign, hh, sep, mm)
217.1207 - return off
217.1208 -
217.1209 - def __repr__(self):
217.1210 - """Convert to formal string, for repr()."""
217.1211 - if self.__microsecond != 0:
217.1212 - s = ", %d, %d" % (self.__second, self.__microsecond)
217.1213 - elif self.__second != 0:
217.1214 - s = ", %d" % self.__second
217.1215 - else:
217.1216 - s = ""
217.1217 - s= "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__,
217.1218 - self.__hour, self.__minute, s)
217.1219 - if self._tzinfo is not None:
217.1220 - assert s[-1:] == ")"
217.1221 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
217.1222 - return s
217.1223 -
217.1224 - def isoformat(self):
217.1225 - """Return the time formatted according to ISO.
217.1226 -
217.1227 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
217.1228 - self.microsecond == 0.
217.1229 - """
217.1230 - s = _format_time(self.__hour, self.__minute, self.__second,
217.1231 - self.__microsecond)
217.1232 - tz = self._tzstr()
217.1233 - if tz:
217.1234 - s += tz
217.1235 - return s
217.1236 -
217.1237 - __str__ = isoformat
217.1238 -
217.1239 - def strftime(self, fmt):
217.1240 - """Format using strftime(). The date part of the timestamp passed
217.1241 - to underlying strftime should not be used.
217.1242 - """
217.1243 - # The year must be >= 1900 else Python's strftime implementation
217.1244 - # can raise a bogus exception.
217.1245 - timetuple = (1900, 1, 1,
217.1246 - self.__hour, self.__minute, self.__second,
217.1247 - 0, 1, -1)
217.1248 - return _wrap_strftime(self, fmt, timetuple)
217.1249 -
217.1250 - # Timezone functions
217.1251 -
217.1252 - def utcoffset(self):
217.1253 - """Return the timezone offset in minutes east of UTC (negative west of
217.1254 - UTC)."""
217.1255 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
217.1256 - offset = _check_utc_offset("utcoffset", offset)
217.1257 - if offset is not None:
217.1258 - offset = timedelta(minutes=offset)
217.1259 - return offset
217.1260 -
217.1261 - # Return an integer (or None) instead of a timedelta (or None).
217.1262 - def _utcoffset(self):
217.1263 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
217.1264 - offset = _check_utc_offset("utcoffset", offset)
217.1265 - return offset
217.1266 -
217.1267 - def tzname(self):
217.1268 - """Return the timezone name.
217.1269 -
217.1270 - Note that the name is 100% informational -- there's no requirement that
217.1271 - it mean anything in particular. For example, "GMT", "UTC", "-500",
217.1272 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
217.1273 - """
217.1274 - name = _call_tzinfo_method(self._tzinfo, "tzname", None)
217.1275 - _check_tzname(name)
217.1276 - return name
217.1277 -
217.1278 - def dst(self):
217.1279 - """Return 0 if DST is not in effect, or the DST offset (in minutes
217.1280 - eastward) if DST is in effect.
217.1281 -
217.1282 - This is purely informational; the DST offset has already been added to
217.1283 - the UTC offset returned by utcoffset() if applicable, so there's no
217.1284 - need to consult dst() unless you're interested in displaying the DST
217.1285 - info.
217.1286 - """
217.1287 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
217.1288 - offset = _check_utc_offset("dst", offset)
217.1289 - if offset is not None:
217.1290 - offset = timedelta(minutes=offset)
217.1291 - return offset
217.1292 -
217.1293 - def replace(self, hour=None, minute=None, second=None, microsecond=None,
217.1294 - tzinfo=True):
217.1295 - """Return a new time with new values for the specified fields."""
217.1296 - if hour is None:
217.1297 - hour = self.hour
217.1298 - if minute is None:
217.1299 - minute = self.minute
217.1300 - if second is None:
217.1301 - second = self.second
217.1302 - if microsecond is None:
217.1303 - microsecond = self.microsecond
217.1304 - if tzinfo is True:
217.1305 - tzinfo = self.tzinfo
217.1306 - _check_time_fields(hour, minute, second, microsecond)
217.1307 - _check_tzinfo_arg(tzinfo)
217.1308 - return time(hour, minute, second, microsecond, tzinfo)
217.1309 -
217.1310 - # Return an integer (or None) instead of a timedelta (or None).
217.1311 - def _dst(self):
217.1312 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
217.1313 - offset = _check_utc_offset("dst", offset)
217.1314 - return offset
217.1315 -
217.1316 - def __nonzero__(self):
217.1317 - if self.second or self.microsecond:
217.1318 - return 1
217.1319 - offset = self._utcoffset() or 0
217.1320 - return self.hour * 60 + self.minute - offset != 0
217.1321 -
217.1322 - # Pickle support.
217.1323 -
217.1324 - __safe_for_unpickling__ = True # For Python 2.2
217.1325 -
217.1326 - def __getstate(self):
217.1327 - us2, us3 = divmod(self.__microsecond, 256)
217.1328 - us1, us2 = divmod(us2, 256)
217.1329 - basestate = ("%c" * 6) % (self.__hour, self.__minute, self.__second,
217.1330 - us1, us2, us3)
217.1331 - if self._tzinfo is None:
217.1332 - return (basestate,)
217.1333 - else:
217.1334 - return (basestate, self._tzinfo)
217.1335 -
217.1336 - def __setstate(self, state):
217.1337 - assert isinstance(state, tuple)
217.1338 - assert 1 <= len(state) <= 2
217.1339 - string = state[0]
217.1340 - assert len(string) == 6
217.1341 - self.__hour, self.__minute, self.__second, us1, us2, us3 = \
217.1342 - map(ord, string)
217.1343 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
217.1344 - if len(state) == 1:
217.1345 - self._tzinfo = None
217.1346 - else:
217.1347 - self._tzinfo = state[1]
217.1348 -
217.1349 - def __reduce__(self):
217.1350 - return (self.__class__, self.__getstate())
217.1351 -
217.1352 -_time_class = time # so functions w/ args named "time" can get at the class
217.1353 -
217.1354 -time.min = time(0, 0, 0)
217.1355 -time.max = time(23, 59, 59, 999999)
217.1356 -time.resolution = timedelta(microseconds=1)
217.1357 -
217.1358 -class datetime(date):
217.1359 -
217.1360 - # XXX needs docstrings
217.1361 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
217.1362 -
217.1363 - def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
217.1364 - microsecond=0, tzinfo=None):
217.1365 - if isinstance(year, str):
217.1366 - # Pickle support
217.1367 - self = date.__new__(cls, year[:4])
217.1368 - self.__setstate((year, month))
217.1369 - return self
217.1370 - _check_tzinfo_arg(tzinfo)
217.1371 - _check_time_fields(hour, minute, second, microsecond)
217.1372 - self = date.__new__(cls, year, month, day)
217.1373 - # XXX This duplicates __year, __month, __day for convenience :-(
217.1374 - self.__year = year
217.1375 - self.__month = month
217.1376 - self.__day = day
217.1377 - self.__hour = hour
217.1378 - self.__minute = minute
217.1379 - self.__second = second
217.1380 - self.__microsecond = microsecond
217.1381 - self._tzinfo = tzinfo
217.1382 - return self
217.1383 -
217.1384 - # Read-only field accessors
217.1385 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
217.1386 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
217.1387 - second = property(lambda self: self.__second, doc="second (0-59)")
217.1388 - microsecond = property(lambda self: self.__microsecond,
217.1389 - doc="microsecond (0-999999)")
217.1390 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
217.1391 -
217.1392 - def fromtimestamp(cls, t, tz=None):
217.1393 - """Construct a datetime from a POSIX timestamp (like time.time()).
217.1394 -
217.1395 - A timezone info object may be passed in as well.
217.1396 - """
217.1397 -
217.1398 - _check_tzinfo_arg(tz)
217.1399 - if tz is None:
217.1400 - converter = _time.localtime
217.1401 - else:
217.1402 - converter = _time.gmtime
217.1403 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
217.1404 - us = int((t % 1.0) * 1000000)
217.1405 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
217.1406 - result = cls(y, m, d, hh, mm, ss, us, tz)
217.1407 - if tz is not None:
217.1408 - result = tz.fromutc(result)
217.1409 - return result
217.1410 - fromtimestamp = classmethod(fromtimestamp)
217.1411 -
217.1412 - def utcfromtimestamp(cls, t):
217.1413 - "Construct a UTC datetime from a POSIX timestamp (like time.time())."
217.1414 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
217.1415 - us = int((t % 1.0) * 1000000)
217.1416 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
217.1417 - return cls(y, m, d, hh, mm, ss, us)
217.1418 - utcfromtimestamp = classmethod(utcfromtimestamp)
217.1419 -
217.1420 - # XXX This is supposed to do better than we *can* do by using time.time(),
217.1421 - # XXX if the platform supports a more accurate way. The C implementation
217.1422 - # XXX uses gettimeofday on platforms that have it, but that isn't
217.1423 - # XXX available from Python. So now() may return different results
217.1424 - # XXX across the implementations.
217.1425 - def now(cls, tz=None):
217.1426 - "Construct a datetime from time.time() and optional time zone info."
217.1427 - t = _time.time()
217.1428 - return cls.fromtimestamp(t, tz)
217.1429 - now = classmethod(now)
217.1430 -
217.1431 - def utcnow(cls):
217.1432 - "Construct a UTC datetime from time.time()."
217.1433 - t = _time.time()
217.1434 - return cls.utcfromtimestamp(t)
217.1435 - utcnow = classmethod(utcnow)
217.1436 -
217.1437 - def combine(cls, date, time):
217.1438 - "Construct a datetime from a given date and a given time."
217.1439 - if not isinstance(date, _date_class):
217.1440 - raise TypeError("date argument must be a date instance")
217.1441 - if not isinstance(time, _time_class):
217.1442 - raise TypeError("time argument must be a time instance")
217.1443 - return cls(date.year, date.month, date.day,
217.1444 - time.hour, time.minute, time.second, time.microsecond,
217.1445 - time.tzinfo)
217.1446 - combine = classmethod(combine)
217.1447 -
217.1448 - def timetuple(self):
217.1449 - "Return local time tuple compatible with time.localtime()."
217.1450 - dst = self._dst()
217.1451 - if dst is None:
217.1452 - dst = -1
217.1453 - elif dst:
217.1454 - dst = 1
217.1455 - return _build_struct_time(self.year, self.month, self.day,
217.1456 - self.hour, self.minute, self.second,
217.1457 - dst)
217.1458 -
217.1459 - def utctimetuple(self):
217.1460 - "Return UTC time tuple compatible with time.gmtime()."
217.1461 - y, m, d = self.year, self.month, self.day
217.1462 - hh, mm, ss = self.hour, self.minute, self.second
217.1463 - offset = self._utcoffset()
217.1464 - if offset: # neither None nor 0
217.1465 - tm = tmxxx(y, m, d, hh, mm - offset)
217.1466 - y, m, d = tm.year, tm.month, tm.day
217.1467 - hh, mm = tm.hour, tm.minute
217.1468 - return _build_struct_time(y, m, d, hh, mm, ss, 0)
217.1469 -
217.1470 - def date(self):
217.1471 - "Return the date part."
217.1472 - return date(self.__year, self.__month, self.__day)
217.1473 -
217.1474 - def time(self):
217.1475 - "Return the time part, with tzinfo None."
217.1476 - return time(self.hour, self.minute, self.second, self.microsecond)
217.1477 -
217.1478 - def timetz(self):
217.1479 - "Return the time part, with same tzinfo."
217.1480 - return time(self.hour, self.minute, self.second, self.microsecond,
217.1481 - self._tzinfo)
217.1482 -
217.1483 - def replace(self, year=None, month=None, day=None, hour=None,
217.1484 - minute=None, second=None, microsecond=None, tzinfo=True):
217.1485 - """Return a new datetime with new values for the specified fields."""
217.1486 - if year is None:
217.1487 - year = self.year
217.1488 - if month is None:
217.1489 - month = self.month
217.1490 - if day is None:
217.1491 - day = self.day
217.1492 - if hour is None:
217.1493 - hour = self.hour
217.1494 - if minute is None:
217.1495 - minute = self.minute
217.1496 - if second is None:
217.1497 - second = self.second
217.1498 - if microsecond is None:
217.1499 - microsecond = self.microsecond
217.1500 - if tzinfo is True:
217.1501 - tzinfo = self.tzinfo
217.1502 - _check_date_fields(year, month, day)
217.1503 - _check_time_fields(hour, minute, second, microsecond)
217.1504 - _check_tzinfo_arg(tzinfo)
217.1505 - return datetime(year, month, day, hour, minute, second,
217.1506 - microsecond, tzinfo)
217.1507 -
217.1508 - def astimezone(self, tz):
217.1509 - if not isinstance(tz, tzinfo):
217.1510 - raise TypeError("tz argument must be an instance of tzinfo")
217.1511 -
217.1512 - mytz = self.tzinfo
217.1513 - if mytz is None:
217.1514 - raise ValueError("astimezone() requires an aware datetime")
217.1515 -
217.1516 - if tz is mytz:
217.1517 - return self
217.1518 -
217.1519 - # Convert self to UTC, and attach the new time zone object.
217.1520 - myoffset = self.utcoffset()
217.1521 - if myoffset is None:
217.1522 - raise ValuError("astimezone() requires an aware datetime")
217.1523 - utc = (self - myoffset).replace(tzinfo=tz)
217.1524 -
217.1525 - # Convert from UTC to tz's local time.
217.1526 - return tz.fromutc(utc)
217.1527 -
217.1528 - # Ways to produce a string.
217.1529 -
217.1530 - def ctime(self):
217.1531 - "Format a la ctime()."
217.1532 - t = tmxxx(self.__year, self.__month, self.__day, self.__hour,
217.1533 - self.__minute, self.__second)
217.1534 - return t.ctime()
217.1535 -
217.1536 - def isoformat(self, sep='T'):
217.1537 - """Return the time formatted according to ISO.
217.1538 -
217.1539 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
217.1540 - self.microsecond == 0.
217.1541 -
217.1542 - If self.tzinfo is not None, the UTC offset is also attached, giving
217.1543 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
217.1544 -
217.1545 - Optional argument sep specifies the separator between date and
217.1546 - time, default 'T'.
217.1547 - """
217.1548 - s = ("%04d-%02d-%02d%c" % (self.__year, self.__month, self.__day,
217.1549 - sep) +
217.1550 - _format_time(self.__hour, self.__minute, self.__second,
217.1551 - self.__microsecond))
217.1552 - off = self._utcoffset()
217.1553 - if off is not None:
217.1554 - if off < 0:
217.1555 - sign = "-"
217.1556 - off = -off
217.1557 - else:
217.1558 - sign = "+"
217.1559 - hh, mm = divmod(off, 60)
217.1560 - s += "%s%02d:%02d" % (sign, hh, mm)
217.1561 - return s
217.1562 -
217.1563 - def __repr__(self):
217.1564 - "Convert to formal string, for repr()."
217.1565 - L = [self.__year, self.__month, self.__day, # These are never zero
217.1566 - self.__hour, self.__minute, self.__second, self.__microsecond]
217.1567 - if L[-1] == 0:
217.1568 - del L[-1]
217.1569 - if L[-1] == 0:
217.1570 - del L[-1]
217.1571 - s = ", ".join(map(str, L))
217.1572 - s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s)
217.1573 - if self._tzinfo is not None:
217.1574 - assert s[-1:] == ")"
217.1575 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
217.1576 - return s
217.1577 -
217.1578 - def __str__(self):
217.1579 - "Convert to string, for str()."
217.1580 - return self.isoformat(sep=' ')
217.1581 -
217.1582 - def utcoffset(self):
217.1583 - """Return the timezone offset in minutes east of UTC (negative west of
217.1584 - UTC)."""
217.1585 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
217.1586 - offset = _check_utc_offset("utcoffset", offset)
217.1587 - if offset is not None:
217.1588 - offset = timedelta(minutes=offset)
217.1589 - return offset
217.1590 -
217.1591 - # Return an integer (or None) instead of a timedelta (or None).
217.1592 - def _utcoffset(self):
217.1593 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
217.1594 - offset = _check_utc_offset("utcoffset", offset)
217.1595 - return offset
217.1596 -
217.1597 - def tzname(self):
217.1598 - """Return the timezone name.
217.1599 -
217.1600 - Note that the name is 100% informational -- there's no requirement that
217.1601 - it mean anything in particular. For example, "GMT", "UTC", "-500",
217.1602 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
217.1603 - """
217.1604 - name = _call_tzinfo_method(self._tzinfo, "tzname", self)
217.1605 - _check_tzname(name)
217.1606 - return name
217.1607 -
217.1608 - def dst(self):
217.1609 - """Return 0 if DST is not in effect, or the DST offset (in minutes
217.1610 - eastward) if DST is in effect.
217.1611 -
217.1612 - This is purely informational; the DST offset has already been added to
217.1613 - the UTC offset returned by utcoffset() if applicable, so there's no
217.1614 - need to consult dst() unless you're interested in displaying the DST
217.1615 - info.
217.1616 - """
217.1617 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
217.1618 - offset = _check_utc_offset("dst", offset)
217.1619 - if offset is not None:
217.1620 - offset = timedelta(minutes=offset)
217.1621 - return offset
217.1622 -
217.1623 - # Return an integer (or None) instead of a timedelta (or None).1573
217.1624 - def _dst(self):
217.1625 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
217.1626 - offset = _check_utc_offset("dst", offset)
217.1627 - return offset
217.1628 -
217.1629 - # Comparisons.
217.1630 -
217.1631 - def __eq__(self, other):
217.1632 - if isinstance(other, datetime):
217.1633 - return self.__cmp(other) == 0
217.1634 - elif hasattr(other, "timetuple"):
217.1635 - return NotImplemented
217.1636 - else:
217.1637 - return False
217.1638 -
217.1639 - def __ne__(self, other):
217.1640 - if isinstance(other, datetime):
217.1641 - return self.__cmp(other) != 0
217.1642 - elif hasattr(other, "timetuple"):
217.1643 - return NotImplemented
217.1644 - else:
217.1645 - return True
217.1646 -
217.1647 - def __le__(self, other):
217.1648 - if isinstance(other, datetime):
217.1649 - return self.__cmp(other) <= 0
217.1650 - elif hasattr(other, "timetuple"):
217.1651 - return NotImplemented
217.1652 - else:
217.1653 - _cmperror(self, other)
217.1654 -
217.1655 - def __lt__(self, other):
217.1656 - if isinstance(other, datetime):
217.1657 - return self.__cmp(other) < 0
217.1658 - elif hasattr(other, "timetuple"):
217.1659 - return NotImplemented
217.1660 - else:
217.1661 - _cmperror(self, other)
217.1662 -
217.1663 - def __ge__(self, other):
217.1664 - if isinstance(other, datetime):
217.1665 - return self.__cmp(other) >= 0
217.1666 - elif hasattr(other, "timetuple"):
217.1667 - return NotImplemented
217.1668 - else:
217.1669 - _cmperror(self, other)
217.1670 -
217.1671 - def __gt__(self, other):
217.1672 - if isinstance(other, datetime):
217.1673 - return self.__cmp(other) > 0
217.1674 - elif hasattr(other, "timetuple"):
217.1675 - return NotImplemented
217.1676 - else:
217.1677 - _cmperror(self, other)
217.1678 -
217.1679 - def __cmp(self, other):
217.1680 - assert isinstance(other, datetime)
217.1681 - mytz = self._tzinfo
217.1682 - ottz = other._tzinfo
217.1683 - myoff = otoff = None
217.1684 -
217.1685 - if mytz is ottz:
217.1686 - base_compare = True
217.1687 - else:
217.1688 - if mytz is not None:
217.1689 - myoff = self._utcoffset()
217.1690 - if ottz is not None:
217.1691 - otoff = other._utcoffset()
217.1692 - base_compare = myoff == otoff
217.1693 -
217.1694 - if base_compare:
217.1695 - return cmp((self.__year, self.__month, self.__day,
217.1696 - self.__hour, self.__minute, self.__second,
217.1697 - self.__microsecond),
217.1698 - (other.__year, other.__month, other.__day,
217.1699 - other.__hour, other.__minute, other.__second,
217.1700 - other.__microsecond))
217.1701 - if myoff is None or otoff is None:
217.1702 - # XXX Buggy in 2.2.2.
217.1703 - raise TypeError("cannot compare naive and aware datetimes")
217.1704 - # XXX What follows could be done more efficiently...
217.1705 - diff = self - other # this will take offsets into account
217.1706 - if diff.days < 0:
217.1707 - return -1
217.1708 - return diff and 1 or 0
217.1709 -
217.1710 - def __add__(self, other):
217.1711 - "Add a datetime and a timedelta."
217.1712 - if not isinstance(other, timedelta):
217.1713 - return NotImplemented
217.1714 - t = tmxxx(self.__year,
217.1715 - self.__month,
217.1716 - self.__day + other.days,
217.1717 - self.__hour,
217.1718 - self.__minute,
217.1719 - self.__second + other.seconds,
217.1720 - self.__microsecond + other.microseconds)
217.1721 - self._checkOverflow(t.year)
217.1722 - result = self.__class__(t.year, t.month, t.day,
217.1723 - t.hour, t.minute, t.second,
217.1724 - t.microsecond, tzinfo=self._tzinfo)
217.1725 - return result
217.1726 -
217.1727 - __radd__ = __add__
217.1728 -
217.1729 - def __sub__(self, other):
217.1730 - "Subtract two datetimes, or a datetime and a timedelta."
217.1731 - if not isinstance(other, datetime):
217.1732 - if isinstance(other, timedelta):
217.1733 - return self + -other
217.1734 - return NotImplemented
217.1735 -
217.1736 - days1 = self.toordinal()
217.1737 - days2 = other.toordinal()
217.1738 - secs1 = self.__second + self.__minute * 60 + self.__hour * 3600
217.1739 - secs2 = other.__second + other.__minute * 60 + other.__hour * 3600
217.1740 - base = timedelta(days1 - days2,
217.1741 - secs1 - secs2,
217.1742 - self.__microsecond - other.__microsecond)
217.1743 - if self._tzinfo is other._tzinfo:
217.1744 - return base
217.1745 - myoff = self._utcoffset()
217.1746 - otoff = other._utcoffset()
217.1747 - if myoff == otoff:
217.1748 - return base
217.1749 - if myoff is None or otoff is None:
217.1750 - raise TypeError, "cannot mix naive and timezone-aware time"
217.1751 - return base + timedelta(minutes = otoff-myoff)
217.1752 -
217.1753 - def __hash__(self):
217.1754 - tzoff = self._utcoffset()
217.1755 - if tzoff is None:
217.1756 - return hash(self.__getstate()[0])
217.1757 - days = _ymd2ord(self.year, self.month, self.day)
217.1758 - seconds = self.hour * 3600 + (self.minute - tzoff) * 60 + self.second
217.1759 - return hash(timedelta(days, seconds, self.microsecond))
217.1760 -
217.1761 - # Pickle support.
217.1762 -
217.1763 - __safe_for_unpickling__ = True # For Python 2.2
217.1764 -
217.1765 - def __getstate(self):
217.1766 - yhi, ylo = divmod(self.__year, 256)
217.1767 - us2, us3 = divmod(self.__microsecond, 256)
217.1768 - us1, us2 = divmod(us2, 256)
217.1769 - basestate = ("%c" * 10) % (yhi, ylo, self.__month, self.__day,
217.1770 - self.__hour, self.__minute, self.__second,
217.1771 - us1, us2, us3)
217.1772 - if self._tzinfo is None:
217.1773 - return (basestate,)
217.1774 - else:
217.1775 - return (basestate, self._tzinfo)
217.1776 -
217.1777 - def __setstate(self, state):
217.1778 - assert isinstance(state, tuple)
217.1779 - assert 1 <= len(state) <= 2
217.1780 - string = state[0]
217.1781 - assert len(string) == 10
217.1782 - (yhi, ylo, self.__month, self.__day, self.__hour,
217.1783 - self.__minute, self.__second, us1, us2, us3) = map(ord, string)
217.1784 - self.__year = yhi * 256 + ylo
217.1785 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
217.1786 - if len(state) == 1:
217.1787 - self._tzinfo = None
217.1788 - else:
217.1789 - self._tzinfo = state[1]
217.1790 -
217.1791 - def __reduce__(self):
217.1792 - return (self.__class__, self.__getstate())
217.1793 -
217.1794 -
217.1795 -datetime.min = datetime(1, 1, 1)
217.1796 -datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
217.1797 -datetime.resolution = timedelta(microseconds=1)
217.1798 -
217.1799 -
217.1800 -def _isoweek1monday(year):
217.1801 - # Helper to calculate the day number of the Monday starting week 1
217.1802 - # XXX This could be done more efficiently
217.1803 - THURSDAY = 3
217.1804 - firstday = _ymd2ord(year, 1, 1)
217.1805 - firstweekday = (firstday + 6) % 7 # See weekday() above
217.1806 - week1monday = firstday - firstweekday
217.1807 - if firstweekday > THURSDAY:
217.1808 - week1monday += 7
217.1809 - return week1monday
217.1810 -
217.1811 -"""
217.1812 -Some time zone algebra. For a datetime x, let
217.1813 - x.n = x stripped of its timezone -- its naive time.
217.1814 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
217.1815 - return None
217.1816 - x.d = x.dst(), and assuming that doesn't raise an exception or
217.1817 - return None
217.1818 - x.s = x's standard offset, x.o - x.d
217.1819 -
217.1820 -Now some derived rules, where k is a duration (timedelta).
217.1821 -
217.1822 -1. x.o = x.s + x.d
217.1823 - This follows from the definition of x.s.
217.1824 -
217.1825 -2. If x and y have the same tzinfo member, x.s = y.s.
217.1826 - This is actually a requirement, an assumption we need to make about
217.1827 - sane tzinfo classes.
217.1828 -
217.1829 -3. The naive UTC time corresponding to x is x.n - x.o.
217.1830 - This is again a requirement for a sane tzinfo class.
217.1831 -
217.1832 -4. (x+k).s = x.s
217.1833 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
217.1834 -
217.1835 -5. (x+k).n = x.n + k
217.1836 - Again follows from how arithmetic is defined.
217.1837 -
217.1838 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
217.1839 -(meaning that the various tzinfo methods exist, and don't blow up or return
217.1840 -None when called).
217.1841 -
217.1842 -The function wants to return a datetime y with timezone tz, equivalent to x.
217.1843 -x is already in UTC.
217.1844 -
217.1845 -By #3, we want
217.1846 -
217.1847 - y.n - y.o = x.n [1]
217.1848 -
217.1849 -The algorithm starts by attaching tz to x.n, and calling that y. So
217.1850 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
217.1851 -becomes true; in effect, we want to solve [2] for k:
217.1852 -
217.1853 - (y+k).n - (y+k).o = x.n [2]
217.1854 -
217.1855 -By #1, this is the same as
217.1856 -
217.1857 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
217.1858 -
217.1859 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
217.1860 -Substituting that into [3],
217.1861 -
217.1862 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
217.1863 - k - (y+k).s - (y+k).d = 0; rearranging,
217.1864 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
217.1865 - k = y.s - (y+k).d
217.1866 -
217.1867 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
217.1868 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
217.1869 -very large, since all offset-returning methods return a duration of magnitude
217.1870 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
217.1871 -be 0, so ignoring it has no consequence then.
217.1872 -
217.1873 -In any case, the new value is
217.1874 -
217.1875 - z = y + y.s [4]
217.1876 -
217.1877 -It's helpful to step back at look at [4] from a higher level: it's simply
217.1878 -mapping from UTC to tz's standard time.
217.1879 -
217.1880 -At this point, if
217.1881 -
217.1882 - z.n - z.o = x.n [5]
217.1883 -
217.1884 -we have an equivalent time, and are almost done. The insecurity here is
217.1885 -at the start of daylight time. Picture US Eastern for concreteness. The wall
217.1886 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
217.1887 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
217.1888 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
217.1889 -on the day DST starts. We want to return the 1:MM EST spelling because that's
217.1890 -the only spelling that makes sense on the local wall clock.
217.1891 -
217.1892 -In fact, if [5] holds at this point, we do have the standard-time spelling,
217.1893 -but that takes a bit of proof. We first prove a stronger result. What's the
217.1894 -difference between the LHS and RHS of [5]? Let
217.1895 -
217.1896 - diff = x.n - (z.n - z.o) [6]
217.1897 -
217.1898 -Now
217.1899 - z.n = by [4]
217.1900 - (y + y.s).n = by #5
217.1901 - y.n + y.s = since y.n = x.n
217.1902 - x.n + y.s = since z and y are have the same tzinfo member,
217.1903 - y.s = z.s by #2
217.1904 - x.n + z.s
217.1905 -
217.1906 -Plugging that back into [6] gives
217.1907 -
217.1908 - diff =
217.1909 - x.n - ((x.n + z.s) - z.o) = expanding
217.1910 - x.n - x.n - z.s + z.o = cancelling
217.1911 - - z.s + z.o = by #2
217.1912 - z.d
217.1913 -
217.1914 -So diff = z.d.
217.1915 -
217.1916 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
217.1917 -spelling we wanted in the endcase described above. We're done. Contrarily,
217.1918 -if z.d = 0, then we have a UTC equivalent, and are also done.
217.1919 -
217.1920 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
217.1921 -add to z (in effect, z is in tz's standard time, and we need to shift the
217.1922 -local clock into tz's daylight time).
217.1923 -
217.1924 -Let
217.1925 -
217.1926 - z' = z + z.d = z + diff [7]
217.1927 -
217.1928 -and we can again ask whether
217.1929 -
217.1930 - z'.n - z'.o = x.n [8]
217.1931 -
217.1932 -If so, we're done. If not, the tzinfo class is insane, according to the
217.1933 -assumptions we've made. This also requires a bit of proof. As before, let's
217.1934 -compute the difference between the LHS and RHS of [8] (and skipping some of
217.1935 -the justifications for the kinds of substitutions we've done several times
217.1936 -already):
217.1937 -
217.1938 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
217.1939 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
217.1940 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
217.1941 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
217.1942 - - z.n + z.n - z.o + z'.o = cancel z.n
217.1943 - - z.o + z'.o = #1 twice
217.1944 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
217.1945 - z'.d - z.d
217.1946 -
217.1947 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
217.1948 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
217.1949 -return z', not bothering to compute z'.d.
217.1950 -
217.1951 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
217.1952 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
217.1953 -would have to change the result dst() returns: we start in DST, and moving
217.1954 -a little further into it takes us out of DST.
217.1955 -
217.1956 -There isn't a sane case where this can happen. The closest it gets is at
217.1957 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
217.1958 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
217.1959 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
217.1960 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
217.1961 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
217.1962 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
217.1963 -standard time. Since that's what the local clock *does*, we want to map both
217.1964 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
217.1965 -in local time, but so it goes -- it's the way the local clock works.
217.1966 -
217.1967 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
217.1968 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
217.1969 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
217.1970 -(correctly) concludes that z' is not UTC-equivalent to x.
217.1971 -
217.1972 -Because we know z.d said z was in daylight time (else [5] would have held and
217.1973 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
217.1974 -and we we have stopped then), and there are only 2 possible values dst() can
217.1975 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
217.1976 -but the reasoning doesn't depend on the example -- it depends on there being
217.1977 -two possible dst() outcomes, one zero and the other non-zero). Therefore
217.1978 -z' must be in standard time, and is the spelling we want in this case.
217.1979 -
217.1980 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
217.1981 -concerned (because it takes z' as being in standard time rather than the
217.1982 -daylight time we intend here), but returning it gives the real-life "local
217.1983 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
217.1984 -tz.
217.1985 -
217.1986 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
217.1987 -the 1:MM standard time spelling we want.
217.1988 -
217.1989 -So how can this break? One of the assumptions must be violated. Two
217.1990 -possibilities:
217.1991 -
217.1992 -1) [2] effectively says that y.s is invariant across all y belong to a given
217.1993 - time zone. This isn't true if, for political reasons or continental drift,
217.1994 - a region decides to change its base offset from UTC.
217.1995 -
217.1996 -2) There may be versions of "double daylight" time where the tail end of
217.1997 - the analysis gives up a step too early. I haven't thought about that
217.1998 - enough to say.
217.1999 -
217.2000 -In any case, it's clear that the default fromutc() is strong enough to handle
217.2001 -"almost all" time zones: so long as the standard offset is invariant, it
217.2002 -doesn't matter if daylight time transition points change from year to year, or
217.2003 -if daylight time is skipped in some years; it doesn't matter how large or
217.2004 -small dst() may get within its bounds; and it doesn't even matter if some
217.2005 -perverse time zone returns a negative dst()). So a breaking case must be
217.2006 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
217.2007 -"""
217.2008 -
217.2009 -def _test():
217.2010 - import test_datetime
217.2011 - test_datetime.test_main()
217.2012 -
217.2013 -if __name__ == "__main__":
217.2014 - _test()
218.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testFix2.fixed Sun Jan 04 13:11:53 2015 -0600
218.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
218.3 @@ -1,2013 +0,0 @@
218.4 -"""Concrete date/time and related types -- prototype implemented in Python.
218.5 -
218.6 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
218.7 -
218.8 -See also http://dir.yahoo.com/Reference/calendars/
218.9 -
218.10 -For a primer on DST, including many current DST rules, see
218.11 -http://webexhibits.org/daylightsaving/
218.12 -
218.13 -For more about DST than you ever wanted to know, see
218.14 -ftp://elsie.nci.nih.gov/pub/
218.15 -
218.16 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
218.17 -
218.18 -"""
218.19 -
218.20 -import time as _time
218.21 -import math as _math
218.22 -
218.23 -MINYEAR = 1
218.24 -MAXYEAR = 9999
218.25 -
218.26 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
218.27 -# also assumes the current Gregorian calendar indefinitely extended in
218.28 -# both directions. Difference: Dates.py calls January 1 of year 0 day
218.29 -# number 1. The code here calls January 1 of year 1 day number 1. This is
218.30 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
218.31 -# and Reingold's "Calendrical Calculations", where it's the base calendar
218.32 -# for all computations. See the book for algorithms for converting between
218.33 -# proleptic Gregorian ordinals and many other calendar systems.
218.34 -
218.35 -_DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
218.36 -
218.37 -_DAYS_BEFORE_MONTH = [None]
218.38 -dbm = 0
218.39 -for dim in _DAYS_IN_MONTH[1:]:
218.40 - _DAYS_BEFORE_MONTH.append(dbm)
218.41 - dbm += dim
218.42 -del dbm, dim
218.43 -
218.44 -def _is_leap(year):
218.45 - "year -> 1 if leap year, else 0."
218.46 - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
218.47 -
218.48 -def _days_in_year(year):
218.49 - "year -> number of days in year (366 if a leap year, else 365)."
218.50 - return 365 + _is_leap(year)
218.51 -
218.52 -def _days_before_year(year):
218.53 - "year -> number of days before January 1st of year."
218.54 - y = year - 1
218.55 - return y*365 + y//4 - y//100 + y//400
218.56 -
218.57 -def _days_in_month(year, month):
218.58 - "year, month -> number of days in that month in that year."
218.59 - try:
218.60 - assert 1 <= month <= 12, month
218.61 - if month == 2 and _is_leap(year):
218.62 - return 29
218.63 - except Exception, e:
218.64 - print "Exception: ", e
218.65 - finally:
218.66 -
218.67 - return _DAYS_IN_MONTH[month]
218.68 -
218.69 -def _days_before_month(year, month):
218.70 - "year, month -> number of days in year preceeding first day of month."
218.71 - if not 1 <= month <= 12:
218.72 - raise ValueError('month must be in 1..12', month)
218.73 - return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
218.74 -
218.75 -def _ymd2ord(year, month, day):
218.76 - "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
218.77 - if not 1 <= month <= 12:
218.78 - raise ValueError('month must be in 1..12', month)
218.79 - dim = _days_in_month(year, month)
218.80 - if not 1 <= day <= dim:
218.81 - raise ValueError('day must be in 1..%d' % dim, day)
218.82 - return (_days_before_year(year) +
218.83 - _days_before_month(year, month) +
218.84 - day)
218.85 -
218.86 -_DI400Y = _days_before_year(401) # number of days in 400 years
218.87 -_DI100Y = _days_before_year(101) # " " " " 100 "
218.88 -_DI4Y = _days_before_year(5) # " " " " 4 "
218.89 -
218.90 -# A 4-year cycle has an extra leap day over what we'd get from pasting
218.91 -# together 4 single years.
218.92 -assert _DI4Y == 4 * 365 + 1
218.93 -
218.94 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
218.95 -# pasting together 4 100-year cycles.
218.96 -assert _DI400Y == 4 * _DI100Y + 1
218.97 -
218.98 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
218.99 -# pasting together 25 4-year cycles.
218.100 -assert _DI100Y == 25 * _DI4Y - 1
218.101 -
218.102 -def _ord2ymd(n):
218.103 - "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
218.104 -
218.105 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
218.106 - # repeats exactly every 400 years. The basic strategy is to find the
218.107 - # closest 400-year boundary at or before n, then work with the offset
218.108 - # from that boundary to n. Life is much clearer if we subtract 1 from
218.109 - # n first -- then the values of n at 400-year boundaries are exactly
218.110 - # those divisible by _DI400Y:
218.111 - #
218.112 - # D M Y n n-1
218.113 - # -- --- ---- ---------- ----------------
218.114 - # 31 Dec -400 -_DI400Y -_DI400Y -1
218.115 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
218.116 - # ...
218.117 - # 30 Dec 000 -1 -2
218.118 - # 31 Dec 000 0 -1
218.119 - # 1 Jan 001 1 0 400-year boundary
218.120 - # 2 Jan 001 2 1
218.121 - # 3 Jan 001 3 2
218.122 - # ...
218.123 - # 31 Dec 400 _DI400Y _DI400Y -1
218.124 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
218.125 - n -= 1
218.126 - n400, n = divmod(n, _DI400Y)
218.127 - year = n400 * 400 + 1 # ..., -399, 1, 401, ...
218.128 -
218.129 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
218.130 - # the desired date. Now compute how many 100-year cycles precede n.
218.131 - # Note that it's possible for n100 to equal 4! In that case 4 full
218.132 - # 100-year cycles precede the desired day, which implies the desired
218.133 - # day is December 31 at the end of a 400-year cycle.
218.134 - n100, n = divmod(n, _DI100Y)
218.135 -
218.136 - # Now compute how many 4-year cycles precede it.
218.137 - n4, n = divmod(n, _DI4Y)
218.138 -
218.139 - # And now how many single years. Again n1 can be 4, and again meaning
218.140 - # that the desired day is December 31 at the end of the 4-year cycle.
218.141 - n1, n = divmod(n, 365)
218.142 -
218.143 - year += n100 * 100 + n4 * 4 + n1
218.144 - if n1 == 4 or n100 == 4:
218.145 - assert n == 0
218.146 - return year-1, 12, 31
218.147 -
218.148 - # Now the year is correct, and n is the offset from January 1. We find
218.149 - # the month via an estimate that's either exact or one too large.
218.150 - leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
218.151 - assert leapyear == _is_leap(year)
218.152 - month = (n + 50) >> 5
218.153 - preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
218.154 - if preceding > n: # estimate is too large
218.155 - month -= 1
218.156 - preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
218.157 - n -= preceding
218.158 - assert 0 <= n < _days_in_month(year, month)
218.159 -
218.160 - # Now the year and month are correct, and n is the offset from the
218.161 - # start of that month: we're done!
218.162 - return year, month, n+1
218.163 -
218.164 -# Month and day names. For localized versions, see the calendar module.
218.165 -_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
218.166 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
218.167 -_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
218.168 -
218.169 -
218.170 -def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
218.171 - wday = (_ymd2ord(y, m, d) + 6) % 7
218.172 - dnum = _days_before_month(y, m) + d
218.173 - return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
218.174 -
218.175 -def _format_time(hh, mm, ss, us):
218.176 - # Skip trailing microseconds when us==0.
218.177 - result = "%02d:%02d:%02d" % (hh, mm, ss)
218.178 - if us:
218.179 - result += ".%06d" % us
218.180 - return result
218.181 -
218.182 -# Correctly substitute for %z and %Z escapes in strftime formats.
218.183 -def _wrap_strftime(object, format, timetuple):
218.184 - year = timetuple[0]
218.185 - if year < 1900:
218.186 - raise ValueError("year=%d is before 1900; the datetime strftime() "
218.187 - "methods require year >= 1900" % year)
218.188 - # Don't call _utcoffset() or tzname() unless actually needed.
218.189 - zreplace = None # the string to use for %z
218.190 - Zreplace = None # the string to use for %Z
218.191 -
218.192 - # Scan format for %z and %Z escapes, replacing as needed.
218.193 - newformat = []
218.194 - push = newformat.append
218.195 - i, n = 0, len(format)
218.196 - while i < n:
218.197 - ch = format[i]
218.198 - i += 1
218.199 - if ch == '%':
218.200 - if i < n:
218.201 - ch = format[i]
218.202 - i += 1
218.203 - if ch == 'z':
218.204 - if zreplace is None:
218.205 - zreplace = ""
218.206 - if hasattr(object, "_utcoffset"):
218.207 - offset = object._utcoffset()
218.208 - if offset is not None:
218.209 - sign = '+'
218.210 - if offset < 0:
218.211 - offset = -offset
218.212 - sign = '-'
218.213 - h, m = divmod(offset, 60)
218.214 - zreplace = '%c%02d%02d' % (sign, h, m)
218.215 - assert '%' not in zreplace
218.216 - newformat.append(zreplace)
218.217 - elif ch == 'Z':
218.218 - if Zreplace is None:
218.219 - Zreplace = ""
218.220 - if hasattr(object, "tzname"):
218.221 - s = object.tzname()
218.222 - if s is not None:
218.223 - # strftime is going to have at this: escape %
218.224 - Zreplace = s.replace('%', '%%')
218.225 - newformat.append(Zreplace)
218.226 - else:
218.227 - push('%')
218.228 - push(ch)
218.229 - else:
218.230 - push('%')
218.231 - else:
218.232 - push(ch)
218.233 - newformat = "".join(newformat)
218.234 - return _time.strftime(newformat, timetuple)
218.235 -
218.236 -def _call_tzinfo_method(tzinfo, methname, tzinfoarg):
218.237 - if tzinfo is None:
218.238 - return None
218.239 - return getattr(tzinfo, methname)(tzinfoarg)
218.240 -
218.241 -# Just raise TypeError if the arg isn't None or a string.
218.242 -def _check_tzname(name):
218.243 - if name is not None and not isinstance(name, str):
218.244 - raise TypeError("tzinfo.tzname() must return None or string, "
218.245 - "not '%s'" % type(name))
218.246 -
218.247 -# name is the offset-producing method, "utcoffset" or "dst".
218.248 -# offset is what it returned.
218.249 -# If offset isn't None or timedelta, raises TypeError.
218.250 -# If offset is None, returns None.
218.251 -# Else offset is checked for being in range, and a whole # of minutes.
218.252 -# If it is, its integer value is returned. Else ValueError is raised.
218.253 -def _check_utc_offset(name, offset):
218.254 - assert name in ("utcoffset", "dst")
218.255 - if offset is None:
218.256 - return None
218.257 - if not isinstance(offset, timedelta):
218.258 - raise TypeError("tzinfo.%s() must return None "
218.259 - "or timedelta, not '%s'" % (name, type(offset)))
218.260 - days = offset.days
218.261 - if days < -1 or days > 0:
218.262 - offset = 1440 # trigger out-of-range
218.263 - else:
218.264 - seconds = days * 86400 + offset.seconds
218.265 - minutes, seconds = divmod(seconds, 60)
218.266 - if seconds or offset.microseconds:
218.267 - raise ValueError("tzinfo.%s() must return a whole number "
218.268 - "of minutes" % name)
218.269 - offset = minutes
218.270 - if -1440 < offset < 1440:
218.271 - return offset
218.272 - raise ValueError("%s()=%d, must be in -1439..1439" % (name, offset))
218.273 -
218.274 -def _check_date_fields(year, month, day):
218.275 - if not MINYEAR <= year <= MAXYEAR:
218.276 - raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
218.277 - if not 1 <= month <= 12:
218.278 - raise ValueError('month must be in 1..12', month)
218.279 - dim = _days_in_month(year, month)
218.280 - if not 1 <= day <= dim:
218.281 - raise ValueError('day must be in 1..%d' % dim, day)
218.282 -
218.283 -def _check_time_fields(hour, minute, second, microsecond):
218.284 - if not 0 <= hour <= 23:
218.285 - raise ValueError('hour must be in 0..23', hour)
218.286 - if not 0 <= minute <= 59:
218.287 - raise ValueError('minute must be in 0..59', minute)
218.288 - if not 0 <= second <= 59:
218.289 - raise ValueError('second must be in 0..59', second)
218.290 - if not 0 <= microsecond <= 999999:
218.291 - raise ValueError('microsecond must be in 0..999999', microsecond)
218.292 -
218.293 -def _check_tzinfo_arg(tz):
218.294 - if tz is not None and not isinstance(tz, tzinfo):
218.295 - raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
218.296 -
218.297 -
218.298 -# Notes on comparison: In general, datetime module comparison operators raise
218.299 -# TypeError when they don't know how to do a comparison themself. If they
218.300 -# returned NotImplemented instead, comparison could (silently) fall back to
218.301 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
218.302 -# and that's not helpful. There are two exceptions:
218.303 -#
218.304 -# 1. For date and datetime, if the other object has a "timetuple" attr,
218.305 -# NotImplemented is returned. This is a hook to allow other kinds of
218.306 -# datetime-like objects a chance to intercept the comparison.
218.307 -#
218.308 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
218.309 -# so opertaions like
218.310 -#
218.311 -# x == y
218.312 -# x != y
218.313 -# x in sequence
218.314 -# x not in sequence
218.315 -# dict[x] = y
218.316 -#
218.317 -# don't raise annoying TypeErrors just because a datetime object
218.318 -# is part of a heterogeneous collection. If there's no known way to
218.319 -# compare X to a datetime, saying they're not equal is reasonable.
218.320 -
218.321 -def _cmperror(x, y):
218.322 - raise TypeError("can't compare '%s' to '%s'" % (
218.323 - type(x).__name__, type(y).__name__))
218.324 -
218.325 -# This is a start at a struct tm workalike. Goals:
218.326 -#
218.327 -# + Works the same way across platforms.
218.328 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
218.329 -#
218.330 -# Note: I suspect it's best if this flavor of tm does *not* try to
218.331 -# second-guess timezones or DST. Instead fold whatever adjustments you want
218.332 -# into the minutes argument (and the constructor will normalize).
218.333 -
218.334 -_ORD1970 = _ymd2ord(1970, 1, 1) # base ordinal for UNIX epoch
218.335 -
218.336 -class tmxxx:
218.337 -
218.338 - ordinal = None
218.339 -
218.340 - def __init__(self, year, month, day, hour=0, minute=0, second=0,
218.341 - microsecond=0):
218.342 - # Normalize all the inputs, and store the normalized values.
218.343 - if not 0 <= microsecond <= 999999:
218.344 - carry, microsecond = divmod(microsecond, 1000000)
218.345 - second += carry
218.346 - if not 0 <= second <= 59:
218.347 - carry, second = divmod(second, 60)
218.348 - minute += carry
218.349 - if not 0 <= minute <= 59:
218.350 - carry, minute = divmod(minute, 60)
218.351 - hour += carry
218.352 - if not 0 <= hour <= 23:
218.353 - carry, hour = divmod(hour, 24)
218.354 - day += carry
218.355 -
218.356 - # That was easy. Now it gets muddy: the proper range for day
218.357 - # can't be determined without knowing the correct month and year,
218.358 - # but if day is, e.g., plus or minus a million, the current month
218.359 - # and year values make no sense (and may also be out of bounds
218.360 - # themselves).
218.361 - # Saying 12 months == 1 year should be non-controversial.
218.362 - if not 1 <= month <= 12:
218.363 - carry, month = divmod(month-1, 12)
218.364 - year += carry
218.365 - month += 1
218.366 - assert 1 <= month <= 12
218.367 -
218.368 - # Now only day can be out of bounds (year may also be out of bounds
218.369 - # for a datetime object, but we don't care about that here).
218.370 - # If day is out of bounds, what to do is arguable, but at least the
218.371 - # method here is principled and explainable.
218.372 - dim = _days_in_month(year, month)
218.373 - if not 1 <= day <= dim:
218.374 - # Move day-1 days from the first of the month. First try to
218.375 - # get off cheap if we're only one day out of range (adjustments
218.376 - # for timezone alone can't be worse than that).
218.377 - if day == 0: # move back a day
218.378 - month -= 1
218.379 - if month > 0:
218.380 - day = _days_in_month(year, month)
218.381 - else:
218.382 - year, month, day = year-1, 12, 31
218.383 - elif day == dim + 1: # move forward a day
218.384 - month += 1
218.385 - day = 1
218.386 - if month > 12:
218.387 - month = 1
218.388 - year += 1
218.389 - else:
218.390 - self.ordinal = _ymd2ord(year, month, 1) + (day - 1)
218.391 - year, month, day = _ord2ymd(self.ordinal)
218.392 -
218.393 - self.year, self.month, self.day = year, month, day
218.394 - self.hour, self.minute, self.second = hour, minute, second
218.395 - self.microsecond = microsecond
218.396 -
218.397 - def toordinal(self):
218.398 - """Return proleptic Gregorian ordinal for the year, month and day.
218.399 -
218.400 - January 1 of year 1 is day 1. Only the year, month and day values
218.401 - contribute to the result.
218.402 - """
218.403 - if self.ordinal is None:
218.404 - self.ordinal = _ymd2ord(self.year, self.month, self.day)
218.405 - return self.ordinal
218.406 -
218.407 - def time(self):
218.408 - "Return Unixish timestamp, as a float (assuming UTC)."
218.409 - days = self.toordinal() - _ORD1970 # convert to UNIX epoch
218.410 - seconds = ((days * 24. + self.hour)*60. + self.minute)*60.
218.411 - return seconds + self.second + self.microsecond / 1e6
218.412 -
218.413 - def ctime(self):
218.414 - "Return ctime() style string."
218.415 - weekday = self.toordinal() % 7 or 7
218.416 - return "%s %s %2d %02d:%02d:%02d %04d" % (
218.417 - _DAYNAMES[weekday],
218.418 - _MONTHNAMES[self.month],
218.419 - self.day,
218.420 - self.hour, self.minute, self.second,
218.421 - self.year)
218.422 -
218.423 -class timedelta(object):
218.424 - """Represent the difference between two datetime objects.
218.425 -
218.426 - Supported operators:
218.427 -
218.428 - - add, subtract timedelta
218.429 - - unary plus, minus, abs
218.430 - - compare to timedelta
218.431 - - multiply, divide by int/long
218.432 -
218.433 - In addition, datetime supports subtraction of two datetime objects
218.434 - returning a timedelta, and addition or subtraction of a datetime
218.435 - and a timedelta giving a datetime.
218.436 -
218.437 - Representation: (days, seconds, microseconds). Why? Because I
218.438 - felt like it.
218.439 - """
218.440 -
218.441 - def __new__(cls, days=0, seconds=0, microseconds=0,
218.442 - # XXX The following should only be used as keyword args:
218.443 - milliseconds=0, minutes=0, hours=0, weeks=0):
218.444 - # Doing this efficiently and accurately in C is going to be difficult
218.445 - # and error-prone, due to ubiquitous overflow possibilities, and that
218.446 - # C double doesn't have enough bits of precision to represent
218.447 - # microseconds over 10K years faithfully. The code here tries to make
218.448 - # explicit where go-fast assumptions can be relied on, in order to
218.449 - # guide the C implementation; it's way more convoluted than speed-
218.450 - # ignoring auto-overflow-to-long idiomatic Python could be.
218.451 -
218.452 - # XXX Check that all inputs are ints, longs or floats.
218.453 -
218.454 - # Final values, all integer.
218.455 - # s and us fit in 32-bit signed ints; d isn't bounded.
218.456 - d = s = us = 0
218.457 -
218.458 - # Normalize everything to days, seconds, microseconds.
218.459 - days += weeks*7
218.460 - seconds += minutes*60 + hours*3600
218.461 - microseconds += milliseconds*1000
218.462 -
218.463 - # Get rid of all fractions, and normalize s and us.
218.464 - # Take a deep breath <wink>.
218.465 - if isinstance(days, float):
218.466 - dayfrac, days = _math.modf(days)
218.467 - daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
218.468 - assert daysecondswhole == int(daysecondswhole) # can't overflow
218.469 - s = int(daysecondswhole)
218.470 - assert days == long(days)
218.471 - d = long(days)
218.472 - else:
218.473 - daysecondsfrac = 0.0
218.474 - d = days
218.475 - assert isinstance(daysecondsfrac, float)
218.476 - assert abs(daysecondsfrac) <= 1.0
218.477 - assert isinstance(d, (int, long))
218.478 - assert abs(s) <= 24 * 3600
218.479 - # days isn't referenced again before redefinition
218.480 -
218.481 - if isinstance(seconds, float):
218.482 - secondsfrac, seconds = _math.modf(seconds)
218.483 - assert seconds == long(seconds)
218.484 - seconds = long(seconds)
218.485 - secondsfrac += daysecondsfrac
218.486 - assert abs(secondsfrac) <= 2.0
218.487 - else:
218.488 - secondsfrac = daysecondsfrac
218.489 - # daysecondsfrac isn't referenced again
218.490 - assert isinstance(secondsfrac, float)
218.491 - assert abs(secondsfrac) <= 2.0
218.492 -
218.493 - assert isinstance(seconds, (int, long))
218.494 - days, seconds = divmod(seconds, 24*3600)
218.495 - d += days
218.496 - s += int(seconds) # can't overflow
218.497 - assert isinstance(s, int)
218.498 - assert abs(s) <= 2 * 24 * 3600
218.499 - # seconds isn't referenced again before redefinition
218.500 -
218.501 - usdouble = secondsfrac * 1e6
218.502 - assert abs(usdouble) < 2.1e6 # exact value not critical
218.503 - # secondsfrac isn't referenced again
218.504 -
218.505 - if isinstance(microseconds, float):
218.506 - microseconds += usdouble
218.507 - microseconds = round(microseconds)
218.508 - seconds, microseconds = divmod(microseconds, 1e6)
218.509 - assert microseconds == int(microseconds)
218.510 - assert seconds == long(seconds)
218.511 - days, seconds = divmod(seconds, 24.*3600.)
218.512 - assert days == long(days)
218.513 - assert seconds == int(seconds)
218.514 - d += long(days)
218.515 - s += int(seconds) # can't overflow
218.516 - assert isinstance(s, int)
218.517 - assert abs(s) <= 3 * 24 * 3600
218.518 - else:
218.519 - seconds, microseconds = divmod(microseconds, 1000000)
218.520 - days, seconds = divmod(seconds, 24*3600)
218.521 - d += days
218.522 - s += int(seconds) # can't overflow
218.523 - assert isinstance(s, int)
218.524 - assert abs(s) <= 3 * 24 * 3600
218.525 - microseconds = float(microseconds)
218.526 - microseconds += usdouble
218.527 - microseconds = round(microseconds)
218.528 - assert abs(s) <= 3 * 24 * 3600
218.529 - assert abs(microseconds) < 3.1e6
218.530 -
218.531 - # Just a little bit of carrying possible for microseconds and seconds.
218.532 - assert isinstance(microseconds, float)
218.533 - assert int(microseconds) == microseconds
218.534 - us = int(microseconds)
218.535 - seconds, us = divmod(us, 1000000)
218.536 - s += seconds # cant't overflow
218.537 - assert isinstance(s, int)
218.538 - days, s = divmod(s, 24*3600)
218.539 - d += days
218.540 -
218.541 - assert isinstance(d, (int, long))
218.542 - assert isinstance(s, int) and 0 <= s < 24*3600
218.543 - assert isinstance(us, int) and 0 <= us < 1000000
218.544 -
218.545 - self = object.__new__(cls)
218.546 -
218.547 - self.__days = d
218.548 - self.__seconds = s
218.549 - self.__microseconds = us
218.550 - if abs(d) > 999999999:
218.551 - raise OverflowError("timedelta # of days is too large: %d" % d)
218.552 -
218.553 - return self
218.554 -
218.555 - def __repr__(self):
218.556 - if self.__microseconds:
218.557 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
218.558 - self.__days,
218.559 - self.__seconds,
218.560 - self.__microseconds)
218.561 - if self.__seconds:
218.562 - return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__,
218.563 - self.__days,
218.564 - self.__seconds)
218.565 - return "%s(%d)" % ('datetime.' + self.__class__.__name__, self.__days)
218.566 -
218.567 - def __str__(self):
218.568 - mm, ss = divmod(self.__seconds, 60)
218.569 - hh, mm = divmod(mm, 60)
218.570 - s = "%d:%02d:%02d" % (hh, mm, ss)
218.571 - if self.__days:
218.572 - def plural(n):
218.573 - return n, abs(n) != 1 and "s" or ""
218.574 - s = ("%d day%s, " % plural(self.__days)) + s
218.575 - if self.__microseconds:
218.576 - s = s + ".%06d" % self.__microseconds
218.577 - return s
218.578 -
218.579 - days = property(lambda self: self.__days, doc="days")
218.580 - seconds = property(lambda self: self.__seconds, doc="seconds")
218.581 - microseconds = property(lambda self: self.__microseconds,
218.582 - doc="microseconds")
218.583 -
218.584 - def __add__(self, other):
218.585 - if isinstance(other, timedelta):
218.586 - return timedelta(self.__days + other.__days,
218.587 - self.__seconds + other.__seconds,
218.588 - self.__microseconds + other.__microseconds)
218.589 - return NotImplemented
218.590 -
218.591 - __radd__ = __add__
218.592 -
218.593 - def __sub__(self, other):
218.594 - if isinstance(other, timedelta):
218.595 - return self + -other
218.596 - return NotImplemented
218.597 -
218.598 - def __rsub__(self, other):
218.599 - if isinstance(other, timedelta):
218.600 - return -self + other
218.601 - return NotImplemented
218.602 -
218.603 - def __neg__(self):
218.604 - return self.__class__(-self.__days,
218.605 - -self.__seconds,
218.606 - -self.__microseconds)
218.607 -
218.608 - def __pos__(self):
218.609 - return self
218.610 -
218.611 - def __abs__(self):
218.612 - if self.__days < 0:
218.613 - return -self
218.614 - else:
218.615 - return self
218.616 -
218.617 - def __mul__(self, other):
218.618 - if isinstance(other, (int, long)):
218.619 - return self.__class__(self.__days * other,
218.620 - self.__seconds * other,
218.621 - self.__microseconds * other)
218.622 - return NotImplemented
218.623 -
218.624 - __rmul__ = __mul__
218.625 -
218.626 - def __div__(self, other):
218.627 - if isinstance(other, (int, long)):
218.628 - usec = ((self.__days * (24*3600L) + self.__seconds) * 1000000 +
218.629 - self.__microseconds)
218.630 - return self.__class__(0, 0, usec // other)
218.631 - return NotImplemented
218.632 -
218.633 - __floordiv__ = __div__
218.634 -
218.635 - # Comparisons.
218.636 -
218.637 - def __eq__(self, other):
218.638 - if isinstance(other, timedelta):
218.639 - return self.__cmp(other) == 0
218.640 - else:
218.641 - return False
218.642 -
218.643 - def __ne__(self, other):
218.644 - if isinstance(other, timedelta):
218.645 - return self.__cmp(other) != 0
218.646 - else:
218.647 - return True
218.648 -
218.649 - def __le__(self, other):
218.650 - if isinstance(other, timedelta):
218.651 - return self.__cmp(other) <= 0
218.652 - else:
218.653 - _cmperror(self, other)
218.654 -
218.655 - def __lt__(self, other):
218.656 - if isinstance(other, timedelta):
218.657 - return self.__cmp(other) < 0
218.658 - else:
218.659 - _cmperror(self, other)
218.660 -
218.661 - def __ge__(self, other):
218.662 - if isinstance(other, timedelta):
218.663 - return self.__cmp(other) >= 0
218.664 - else:
218.665 - _cmperror(self, other)
218.666 -
218.667 - def __gt__(self, other):
218.668 - if isinstance(other, timedelta):
218.669 - return self.__cmp(other) > 0
218.670 - else:
218.671 - _cmperror(self, other)
218.672 -
218.673 - def __cmp(self, other):
218.674 - assert isinstance(other, timedelta)
218.675 - return cmp(self.__getstate(), other.__getstate())
218.676 -
218.677 - def __hash__(self):
218.678 - return hash(self.__getstate())
218.679 -
218.680 - def __nonzero__(self):
218.681 - return (self.__days != 0 or
218.682 - self.__seconds != 0 or
218.683 - self.__microseconds != 0)
218.684 -
218.685 - # Pickle support.
218.686 -
218.687 - __safe_for_unpickling__ = True # For Python 2.2
218.688 -
218.689 - def __getstate(self):
218.690 - return (self.__days, self.__seconds, self.__microseconds)
218.691 -
218.692 - def __reduce__(self):
218.693 - return (self.__class__, self.__getstate())
218.694 -
218.695 -timedelta.min = timedelta(-999999999)
218.696 -timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
218.697 - microseconds=999999)
218.698 -timedelta.resolution = timedelta(microseconds=1)
218.699 -
218.700 -class date(object):
218.701 - """Concrete date type.
218.702 -
218.703 - Constructors:
218.704 -
218.705 - __new__()
218.706 - fromtimestamp()
218.707 - today()
218.708 - fromordinal()
218.709 -
218.710 - Operators:
218.711 -
218.712 - __repr__, __str__
218.713 - __cmp__, __hash__
218.714 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
218.715 -
218.716 - Methods:
218.717 -
218.718 - timetuple()
218.719 - toordinal()
218.720 - weekday()
218.721 - isoweekday(), isocalendar(), isoformat()
218.722 - ctime()
218.723 - strftime()
218.724 -
218.725 - Properties (readonly):
218.726 - year, month, day
218.727 - """
218.728 -
218.729 - def __new__(cls, year, month=None, day=None):
218.730 - """Constructor.
218.731 -
218.732 - Arguments:
218.733 -
218.734 - year, month, day (required, base 1)
218.735 - """
218.736 - if isinstance(year, str):
218.737 - # Pickle support
218.738 - self = object.__new__(cls)
218.739 - self.__setstate((year,))
218.740 - return self
218.741 - _check_date_fields(year, month, day)
218.742 - self = object.__new__(cls)
218.743 - self.__year = year
218.744 - self.__month = month
218.745 - self.__day = day
218.746 - return self
218.747 -
218.748 - # Additional constructors
218.749 -
218.750 - def fromtimestamp(cls, t):
218.751 - "Construct a date from a POSIX timestamp (like time.time())."
218.752 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
218.753 - return cls(y, m, d)
218.754 - fromtimestamp = classmethod(fromtimestamp)
218.755 -
218.756 - def today(cls):
218.757 - "Construct a date from time.time()."
218.758 - t = _time.time()
218.759 - return cls.fromtimestamp(t)
218.760 - today = classmethod(today)
218.761 -
218.762 - def fromordinal(cls, n):
218.763 - """Contruct a date from a proleptic Gregorian ordinal.
218.764 -
218.765 - January 1 of year 1 is day 1. Only the year, month and day are
218.766 - non-zero in the result.
218.767 - """
218.768 - y, m, d = _ord2ymd(n)
218.769 - return cls(y, m, d)
218.770 - fromordinal = classmethod(fromordinal)
218.771 -
218.772 - # Conversions to string
218.773 -
218.774 - def __repr__(self):
218.775 - "Convert to formal string, for repr()."
218.776 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
218.777 - self.__year,
218.778 - self.__month,
218.779 - self.__day)
218.780 - # XXX These shouldn't depend on time.localtime(), because that
218.781 - # clips the usable dates to [1970 .. 2038). At least ctime() is
218.782 - # easily done without using strftime() -- that's better too because
218.783 - # strftime("%c", ...) is locale specific.
218.784 -
218.785 - def ctime(self):
218.786 - "Format a la ctime()."
218.787 - return tmxxx(self.__year, self.__month, self.__day).ctime()
218.788 -
218.789 - def strftime(self, fmt):
218.790 - "Format using strftime()."
218.791 - return _wrap_strftime(self, fmt, self.timetuple())
218.792 -
218.793 - def isoformat(self):
218.794 - """Return the date formatted according to ISO.
218.795 -
218.796 - This is 'YYYY-MM-DD'.
218.797 -
218.798 - References:
218.799 - - http://www.w3.org/TR/NOTE-datetime
218.800 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
218.801 - """
218.802 - return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day)
218.803 -
218.804 - __str__ = isoformat
218.805 -
218.806 - # Read-only field accessors
218.807 - year = property(lambda self: self.__year,
218.808 - doc="year (%d-%d)" % (MINYEAR, MAXYEAR))
218.809 - month = property(lambda self: self.__month, doc="month (1-12)")
218.810 - day = property(lambda self: self.__day, doc="day (1-31)")
218.811 -
218.812 - # Standard conversions, __cmp__, __hash__ (and helpers)
218.813 -
218.814 - def timetuple(self):
218.815 - "Return local time tuple compatible with time.localtime()."
218.816 - return _build_struct_time(self.__year, self.__month, self.__day,
218.817 - 0, 0, 0, -1)
218.818 -
218.819 - def toordinal(self):
218.820 - """Return proleptic Gregorian ordinal for the year, month and day.
218.821 -
218.822 - January 1 of year 1 is day 1. Only the year, month and day values
218.823 - contribute to the result.
218.824 - """
218.825 - return _ymd2ord(self.__year, self.__month, self.__day)
218.826 -
218.827 - def replace(self, year=None, month=None, day=None):
218.828 - """Return a new date with new values for the specified fields."""
218.829 - if year is None:
218.830 - year = self.__year
218.831 - if month is None:
218.832 - month = self.__month
218.833 - if day is None:
218.834 - day = self.__day
218.835 - _check_date_fields(year, month, day)
218.836 - return date(year, month, day)
218.837 -
218.838 - # Comparisons.
218.839 -
218.840 - def __eq__(self, other):
218.841 - if isinstance(other, date):
218.842 - return self.__cmp(other) == 0
218.843 - elif hasattr(other, "timetuple"):
218.844 - return NotImplemented
218.845 - else:
218.846 - return False
218.847 -
218.848 - def __ne__(self, other):
218.849 - if isinstance(other, date):
218.850 - return self.__cmp(other) != 0
218.851 - elif hasattr(other, "timetuple"):
218.852 - return NotImplemented
218.853 - else:
218.854 - return True
218.855 -
218.856 - def __le__(self, other):
218.857 - if isinstance(other, date):
218.858 - return self.__cmp(other) <= 0
218.859 - elif hasattr(other, "timetuple"):
218.860 - return NotImplemented
218.861 - else:
218.862 - _cmperror(self, other)
218.863 -
218.864 - def __lt__(self, other):
218.865 - if isinstance(other, date):
218.866 - return self.__cmp(other) < 0
218.867 - elif hasattr(other, "timetuple"):
218.868 - return NotImplemented
218.869 - else:
218.870 - _cmperror(self, other)
218.871 -
218.872 - def __ge__(self, other):
218.873 - if isinstance(other, date):
218.874 - return self.__cmp(other) >= 0
218.875 - elif hasattr(other, "timetuple"):
218.876 - return NotImplemented
218.877 - else:
218.878 - _cmperror(self, other)
218.879 -
218.880 - def __gt__(self, other):
218.881 - if isinstance(other, date):
218.882 - return self.__cmp(other) > 0
218.883 - elif hasattr(other, "timetuple"):
218.884 - return NotImplemented
218.885 - else:
218.886 - _cmperror(self, other)
218.887 -
218.888 - def __cmp(self, other):
218.889 - assert isinstance(other, date)
218.890 - y, m, d = self.__year, self.__month, self.__day
218.891 - y2, m2, d2 = other.__year, other.__month, other.__day
218.892 - return cmp((y, m, d), (y2, m2, d2))
218.893 -
218.894 - def __hash__(self):
218.895 - "Hash."
218.896 - return hash(self.__getstate())
218.897 -
218.898 - # Computations
218.899 -
218.900 - def _checkOverflow(self, year):
218.901 - if not MINYEAR <= year <= MAXYEAR:
218.902 - raise OverflowError("date +/-: result year %d not in %d..%d" %
218.903 - (year, MINYEAR, MAXYEAR))
218.904 -
218.905 - def __add__(self, other):
218.906 - "Add a date to a timedelta."
218.907 - if isinstance(other, timedelta):
218.908 - t = tmxxx(self.__year,
218.909 - self.__month,
218.910 - self.__day + other.days)
218.911 - self._checkOverflow(t.year)
218.912 - result = self.__class__(t.year, t.month, t.day)
218.913 - return result
218.914 - return NotImplemented
218.915 -
218.916 - __radd__ = __add__
218.917 -
218.918 - def __sub__(self, other):
218.919 - """Subtract two dates, or a date and a timedelta."""
218.920 - if isinstance(other, timedelta):
218.921 - return self + timedelta(-other.days)
218.922 - if isinstance(other, date):
218.923 - days1 = self.toordinal()
218.924 - days2 = other.toordinal()
218.925 - return timedelta(days1 - days2)
218.926 - return NotImplemented
218.927 -
218.928 - def weekday(self):
218.929 - "Return day of the week, where Monday == 0 ... Sunday == 6."
218.930 - return (self.toordinal() + 6) % 7
218.931 -
218.932 - # Day-of-the-week and week-of-the-year, according to ISO
218.933 -
218.934 - def isoweekday(self):
218.935 - "Return day of the week, where Monday == 1 ... Sunday == 7."
218.936 - # 1-Jan-0001 is a Monday
218.937 - return self.toordinal() % 7 or 7
218.938 -
218.939 - def isocalendar(self):
218.940 - """Return a 3-tuple containing ISO year, week number, and weekday.
218.941 -
218.942 - The first ISO week of the year is the (Mon-Sun) week
218.943 - containing the year's first Thursday; everything else derives
218.944 - from that.
218.945 -
218.946 - The first week is 1; Monday is 1 ... Sunday is 7.
218.947 -
218.948 - ISO calendar algorithm taken from
218.949 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
218.950 - """
218.951 - year = self.__year
218.952 - week1monday = _isoweek1monday(year)
218.953 - today = _ymd2ord(self.__year, self.__month, self.__day)
218.954 - # Internally, week and day have origin 0
218.955 - week, day = divmod(today - week1monday, 7)
218.956 - if week < 0:
218.957 - year -= 1
218.958 - week1monday = _isoweek1monday(year)
218.959 - week, day = divmod(today - week1monday, 7)
218.960 - elif week >= 52:
218.961 - if today >= _isoweek1monday(year+1):
218.962 - year += 1
218.963 - week = 0
218.964 - return year, week+1, day+1
218.965 -
218.966 - # Pickle support.
218.967 -
218.968 - __safe_for_unpickling__ = True # For Python 2.2
218.969 -
218.970 - def __getstate(self):
218.971 - yhi, ylo = divmod(self.__year, 256)
218.972 - return ("%c%c%c%c" % (yhi, ylo, self.__month, self.__day), )
218.973 -
218.974 - def __setstate(self, t):
218.975 - assert isinstance(t, tuple) and len(t) == 1, `t`
218.976 - string = t[0]
218.977 - assert len(string) == 4
218.978 - yhi, ylo, self.__month, self.__day = map(ord, string)
218.979 - self.__year = yhi * 256 + ylo
218.980 -
218.981 - def __reduce__(self):
218.982 - return (self.__class__, self.__getstate())
218.983 -
218.984 -_date_class = date # so functions w/ args named "date" can get at the class
218.985 -
218.986 -date.min = date(1, 1, 1)
218.987 -date.max = date(9999, 12, 31)
218.988 -date.resolution = timedelta(days=1)
218.989 -
218.990 -class tzinfo(object):
218.991 - """Abstract base class for time zone info classes.
218.992 -
218.993 - Subclasses must override the name(), utcoffset() and dst() methods.
218.994 - """
218.995 -
218.996 - def tzname(self, dt):
218.997 - "datetime -> string name of time zone."
218.998 - raise NotImplementedError("tzinfo subclass must override tzname()")
218.999 -
218.1000 - def utcoffset(self, dt):
218.1001 - "datetime -> minutes east of UTC (negative for west of UTC)"
218.1002 - raise NotImplementedError("tzinfo subclass must override utcoffset()")
218.1003 -
218.1004 - def dst(self, dt):
218.1005 - """datetime -> DST offset in minutes east of UTC.
218.1006 -
218.1007 - Return 0 if DST not in effect. utcoffset() must include the DST
218.1008 - offset.
218.1009 - """
218.1010 - raise NotImplementedError("tzinfo subclass must override dst()")
218.1011 -
218.1012 - def fromutc(self, dt):
218.1013 - "datetime in UTC -> datetime in local time."
218.1014 -
218.1015 - if not isinstance(dt, datetime):
218.1016 - raise TypeError("fromutc() requires a datetime argument")
218.1017 - if dt.tzinfo is not self:
218.1018 - raise ValueError("dt.tzinfo is not self")
218.1019 -
218.1020 - dtoff = dt.utcoffset()
218.1021 - if dtoff is None:
218.1022 - raise ValueError("fromutc() requires a non-None utcoffset() "
218.1023 - "result")
218.1024 -
218.1025 - # See the long comment block at the end of this file for an
218.1026 - # explanation of this algorithm.
218.1027 - dtdst = dt.dst()
218.1028 - if dtdst is None:
218.1029 - raise ValueError("fromutc() requires a non-None dst() result")
218.1030 - delta = dtoff - dtdst
218.1031 - if delta:
218.1032 - dt += delta
218.1033 - dtdst = dt.dst()
218.1034 - if dtdst is None:
218.1035 - raise ValueError("fromutc(): dt.dst gave inconsistent "
218.1036 - "results; cannot convert")
218.1037 - if dtdst:
218.1038 - return dt + dtdst
218.1039 - else:
218.1040 - return dt
218.1041 -
218.1042 - # Pickle support.
218.1043 -
218.1044 - __safe_for_unpickling__ = True # For Python 2.2
218.1045 -
218.1046 - def __reduce__(self):
218.1047 - getinitargs = getattr(self, "__getinitargs__", None)
218.1048 - if getinitargs:
218.1049 - args = getinitargs()
218.1050 - else:
218.1051 - args = ()
218.1052 - getstate = getattr(self, "__getstate__", None)
218.1053 - if getstate:
218.1054 - state = getstate()
218.1055 - else:
218.1056 - state = getattr(self, "__dict__", None) or None
218.1057 - if state is None:
218.1058 - return (self.__class__, args)
218.1059 - else:
218.1060 - return (self.__class__, args, state)
218.1061 -
218.1062 -_tzinfo_class = tzinfo # so functions w/ args named "tinfo" can get at it
218.1063 -
218.1064 -class time(object):
218.1065 - """Time with time zone.
218.1066 -
218.1067 - Constructors:
218.1068 -
218.1069 - __new__()
218.1070 -
218.1071 - Operators:
218.1072 -
218.1073 - __repr__, __str__
218.1074 - __cmp__, __hash__
218.1075 -
218.1076 - Methods:
218.1077 -
218.1078 - strftime()
218.1079 - isoformat()
218.1080 - utcoffset()
218.1081 - tzname()
218.1082 - dst()
218.1083 -
218.1084 - Properties (readonly):
218.1085 - hour, minute, second, microsecond, tzinfo
218.1086 - """
218.1087 -
218.1088 - def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
218.1089 - """Constructor.
218.1090 -
218.1091 - Arguments:
218.1092 -
218.1093 - hour, minute (required)
218.1094 - second, microsecond (default to zero)
218.1095 - tzinfo (default to None)
218.1096 - """
218.1097 - self = object.__new__(cls)
218.1098 - if isinstance(hour, str):
218.1099 - # Pickle support
218.1100 - self.__setstate((hour, minute or None))
218.1101 - return self
218.1102 - _check_tzinfo_arg(tzinfo)
218.1103 - _check_time_fields(hour, minute, second, microsecond)
218.1104 - self.__hour = hour
218.1105 - self.__minute = minute
218.1106 - self.__second = second
218.1107 - self.__microsecond = microsecond
218.1108 - self._tzinfo = tzinfo
218.1109 - return self
218.1110 -
218.1111 - # Read-only field accessors
218.1112 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
218.1113 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
218.1114 - second = property(lambda self: self.__second, doc="second (0-59)")
218.1115 - microsecond = property(lambda self: self.__microsecond,
218.1116 - doc="microsecond (0-999999)")
218.1117 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
218.1118 -
218.1119 - # Standard conversions, __hash__ (and helpers)
218.1120 -
218.1121 - # Comparisons.
218.1122 -
218.1123 - def __eq__(self, other):
218.1124 - if isinstance(other, time):
218.1125 - return self.__cmp(other) == 0
218.1126 - else:
218.1127 - return False
218.1128 -
218.1129 - def __ne__(self, other):
218.1130 - if isinstance(other, time):
218.1131 - return self.__cmp(other) != 0
218.1132 - else:
218.1133 - return True
218.1134 -
218.1135 - def __le__(self, other):
218.1136 - if isinstance(other, time):
218.1137 - return self.__cmp(other) <= 0
218.1138 - else:
218.1139 - _cmperror(self, other)
218.1140 -
218.1141 - def __lt__(self, other):
218.1142 - if isinstance(other, time):
218.1143 - return self.__cmp(other) < 0
218.1144 - else:
218.1145 - _cmperror(self, other)
218.1146 -
218.1147 - def __ge__(self, other):
218.1148 - if isinstance(other, time):
218.1149 - return self.__cmp(other) >= 0
218.1150 - else:
218.1151 - _cmperror(self, other)
218.1152 -
218.1153 - def __gt__(self, other):
218.1154 - if isinstance(other, time):
218.1155 - return self.__cmp(other) > 0
218.1156 - else:
218.1157 - _cmperror(self, other)
218.1158 -
218.1159 - def __cmp(self, other):
218.1160 - assert isinstance(other, time)
218.1161 - mytz = self._tzinfo
218.1162 - ottz = other._tzinfo
218.1163 - myoff = otoff = None
218.1164 -
218.1165 - if mytz is ottz:
218.1166 - base_compare = True
218.1167 - else:
218.1168 - myoff = self._utcoffset()
218.1169 - otoff = other._utcoffset()
218.1170 - base_compare = myoff == otoff
218.1171 -
218.1172 - if base_compare:
218.1173 - return cmp((self.__hour, self.__minute, self.__second,
218.1174 - self.__microsecond),
218.1175 - (other.__hour, other.__minute, other.__second,
218.1176 - other.__microsecond))
218.1177 - if myoff is None or otoff is None:
218.1178 - # XXX Buggy in 2.2.2.
218.1179 - raise TypeError("cannot compare naive and aware times")
218.1180 - myhhmm = self.__hour * 60 + self.__minute - myoff
218.1181 - othhmm = other.__hour * 60 + other.__minute - otoff
218.1182 - return cmp((myhhmm, self.__second, self.__microsecond),
218.1183 - (othhmm, other.__second, other.__microsecond))
218.1184 -
218.1185 - def __hash__(self):
218.1186 - """Hash."""
218.1187 - tzoff = self._utcoffset()
218.1188 - if not tzoff: # zero or None
218.1189 - return hash(self.__getstate()[0])
218.1190 - h, m = divmod(self.hour * 60 + self.minute - tzoff, 60)
218.1191 - if 0 <= h < 24:
218.1192 - return hash(time(h, m, self.second, self.microsecond))
218.1193 - return hash((h, m, self.second, self.microsecond))
218.1194 -
218.1195 - # Conversion to string
218.1196 -
218.1197 - def _tzstr(self, sep=":"):
218.1198 - """Return formatted timezone offset (+xx:xx) or None."""
218.1199 - off = self._utcoffset()
218.1200 - if off is not None:
218.1201 - if off < 0:
218.1202 - sign = "-"
218.1203 - off = -off
218.1204 - else:
218.1205 - sign = "+"
218.1206 - hh, mm = divmod(off, 60)
218.1207 - assert 0 <= hh < 24
218.1208 - off = "%s%02d%s%02d" % (sign, hh, sep, mm)
218.1209 - return off
218.1210 -
218.1211 - def __repr__(self):
218.1212 - """Convert to formal string, for repr()."""
218.1213 - if self.__microsecond != 0:
218.1214 - s = ", %d, %d" % (self.__second, self.__microsecond)
218.1215 - elif self.__second != 0:
218.1216 - s = ", %d" % self.__second
218.1217 - else:
218.1218 - s = ""
218.1219 - s= "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__,
218.1220 - self.__hour, self.__minute, s)
218.1221 - if self._tzinfo is not None:
218.1222 - assert s[-1:] == ")"
218.1223 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
218.1224 - return s
218.1225 -
218.1226 - def isoformat(self):
218.1227 - """Return the time formatted according to ISO.
218.1228 -
218.1229 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
218.1230 - self.microsecond == 0.
218.1231 - """
218.1232 - s = _format_time(self.__hour, self.__minute, self.__second,
218.1233 - self.__microsecond)
218.1234 - tz = self._tzstr()
218.1235 - if tz:
218.1236 - s += tz
218.1237 - return s
218.1238 -
218.1239 - __str__ = isoformat
218.1240 -
218.1241 - def strftime(self, fmt):
218.1242 - """Format using strftime(). The date part of the timestamp passed
218.1243 - to underlying strftime should not be used.
218.1244 - """
218.1245 - # The year must be >= 1900 else Python's strftime implementation
218.1246 - # can raise a bogus exception.
218.1247 - timetuple = (1900, 1, 1,
218.1248 - self.__hour, self.__minute, self.__second,
218.1249 - 0, 1, -1)
218.1250 - return _wrap_strftime(self, fmt, timetuple)
218.1251 -
218.1252 - # Timezone functions
218.1253 -
218.1254 - def utcoffset(self):
218.1255 - """Return the timezone offset in minutes east of UTC (negative west of
218.1256 - UTC)."""
218.1257 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
218.1258 - offset = _check_utc_offset("utcoffset", offset)
218.1259 - if offset is not None:
218.1260 - offset = timedelta(minutes=offset)
218.1261 - return offset
218.1262 -
218.1263 - # Return an integer (or None) instead of a timedelta (or None).
218.1264 - def _utcoffset(self):
218.1265 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
218.1266 - offset = _check_utc_offset("utcoffset", offset)
218.1267 - return offset
218.1268 -
218.1269 - def tzname(self):
218.1270 - """Return the timezone name.
218.1271 -
218.1272 - Note that the name is 100% informational -- there's no requirement that
218.1273 - it mean anything in particular. For example, "GMT", "UTC", "-500",
218.1274 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
218.1275 - """
218.1276 - name = _call_tzinfo_method(self._tzinfo, "tzname", None)
218.1277 - _check_tzname(name)
218.1278 - return name
218.1279 -
218.1280 - def dst(self):
218.1281 - """Return 0 if DST is not in effect, or the DST offset (in minutes
218.1282 - eastward) if DST is in effect.
218.1283 -
218.1284 - This is purely informational; the DST offset has already been added to
218.1285 - the UTC offset returned by utcoffset() if applicable, so there's no
218.1286 - need to consult dst() unless you're interested in displaying the DST
218.1287 - info.
218.1288 - """
218.1289 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
218.1290 - offset = _check_utc_offset("dst", offset)
218.1291 - if offset is not None:
218.1292 - offset = timedelta(minutes=offset)
218.1293 - return offset
218.1294 -
218.1295 - def replace(self, hour=None, minute=None, second=None, microsecond=None,
218.1296 - tzinfo=True):
218.1297 - """Return a new time with new values for the specified fields."""
218.1298 - if hour is None:
218.1299 - hour = self.hour
218.1300 - if minute is None:
218.1301 - minute = self.minute
218.1302 - if second is None:
218.1303 - second = self.second
218.1304 - if microsecond is None:
218.1305 - microsecond = self.microsecond
218.1306 - if tzinfo is True:
218.1307 - tzinfo = self.tzinfo
218.1308 - _check_time_fields(hour, minute, second, microsecond)
218.1309 - _check_tzinfo_arg(tzinfo)
218.1310 - return time(hour, minute, second, microsecond, tzinfo)
218.1311 -
218.1312 - # Return an integer (or None) instead of a timedelta (or None).
218.1313 - def _dst(self):
218.1314 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
218.1315 - offset = _check_utc_offset("dst", offset)
218.1316 - return offset
218.1317 -
218.1318 - def __nonzero__(self):
218.1319 - if self.second or self.microsecond:
218.1320 - return 1
218.1321 - offset = self._utcoffset() or 0
218.1322 - return self.hour * 60 + self.minute - offset != 0
218.1323 -
218.1324 - # Pickle support.
218.1325 -
218.1326 - __safe_for_unpickling__ = True # For Python 2.2
218.1327 -
218.1328 - def __getstate(self):
218.1329 - us2, us3 = divmod(self.__microsecond, 256)
218.1330 - us1, us2 = divmod(us2, 256)
218.1331 - basestate = ("%c" * 6) % (self.__hour, self.__minute, self.__second,
218.1332 - us1, us2, us3)
218.1333 - if self._tzinfo is None:
218.1334 - return (basestate,)
218.1335 - else:
218.1336 - return (basestate, self._tzinfo)
218.1337 -
218.1338 - def __setstate(self, state):
218.1339 - assert isinstance(state, tuple)
218.1340 - assert 1 <= len(state) <= 2
218.1341 - string = state[0]
218.1342 - assert len(string) == 6
218.1343 - self.__hour, self.__minute, self.__second, us1, us2, us3 = \
218.1344 - map(ord, string)
218.1345 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
218.1346 - if len(state) == 1:
218.1347 - self._tzinfo = None
218.1348 - else:
218.1349 - self._tzinfo = state[1]
218.1350 -
218.1351 - def __reduce__(self):
218.1352 - return (self.__class__, self.__getstate())
218.1353 -
218.1354 -_time_class = time # so functions w/ args named "time" can get at the class
218.1355 -
218.1356 -time.min = time(0, 0, 0)
218.1357 -time.max = time(23, 59, 59, 999999)
218.1358 -time.resolution = timedelta(microseconds=1)
218.1359 -
218.1360 -class datetime(date):
218.1361 -
218.1362 - # XXX needs docstrings
218.1363 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
218.1364 -
218.1365 - def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
218.1366 - microsecond=0, tzinfo=None):
218.1367 - if isinstance(year, str):
218.1368 - # Pickle support
218.1369 - self = date.__new__(cls, year[:4])
218.1370 - self.__setstate((year, month))
218.1371 - return self
218.1372 - _check_tzinfo_arg(tzinfo)
218.1373 - _check_time_fields(hour, minute, second, microsecond)
218.1374 - self = date.__new__(cls, year, month, day)
218.1375 - # XXX This duplicates __year, __month, __day for convenience :-(
218.1376 - self.__year = year
218.1377 - self.__month = month
218.1378 - self.__day = day
218.1379 - self.__hour = hour
218.1380 - self.__minute = minute
218.1381 - self.__second = second
218.1382 - self.__microsecond = microsecond
218.1383 - self._tzinfo = tzinfo
218.1384 - return self
218.1385 -
218.1386 - # Read-only field accessors
218.1387 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
218.1388 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
218.1389 - second = property(lambda self: self.__second, doc="second (0-59)")
218.1390 - microsecond = property(lambda self: self.__microsecond,
218.1391 - doc="microsecond (0-999999)")
218.1392 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
218.1393 -
218.1394 - def fromtimestamp(cls, t, tz=None):
218.1395 - """Construct a datetime from a POSIX timestamp (like time.time()).
218.1396 -
218.1397 - A timezone info object may be passed in as well.
218.1398 - """
218.1399 -
218.1400 - _check_tzinfo_arg(tz)
218.1401 - if tz is None:
218.1402 - converter = _time.localtime
218.1403 - else:
218.1404 - converter = _time.gmtime
218.1405 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
218.1406 - us = int((t % 1.0) * 1000000)
218.1407 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
218.1408 - result = cls(y, m, d, hh, mm, ss, us, tz)
218.1409 - if tz is not None:
218.1410 - result = tz.fromutc(result)
218.1411 - return result
218.1412 - fromtimestamp = classmethod(fromtimestamp)
218.1413 -
218.1414 - def utcfromtimestamp(cls, t):
218.1415 - "Construct a UTC datetime from a POSIX timestamp (like time.time())."
218.1416 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
218.1417 - us = int((t % 1.0) * 1000000)
218.1418 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
218.1419 - return cls(y, m, d, hh, mm, ss, us)
218.1420 - utcfromtimestamp = classmethod(utcfromtimestamp)
218.1421 -
218.1422 - # XXX This is supposed to do better than we *can* do by using time.time(),
218.1423 - # XXX if the platform supports a more accurate way. The C implementation
218.1424 - # XXX uses gettimeofday on platforms that have it, but that isn't
218.1425 - # XXX available from Python. So now() may return different results
218.1426 - # XXX across the implementations.
218.1427 - def now(cls, tz=None):
218.1428 - "Construct a datetime from time.time() and optional time zone info."
218.1429 - t = _time.time()
218.1430 - return cls.fromtimestamp(t, tz)
218.1431 - now = classmethod(now)
218.1432 -
218.1433 - def utcnow(cls):
218.1434 - "Construct a UTC datetime from time.time()."
218.1435 - t = _time.time()
218.1436 - return cls.utcfromtimestamp(t)
218.1437 - utcnow = classmethod(utcnow)
218.1438 -
218.1439 - def combine(cls, date, time):
218.1440 - "Construct a datetime from a given date and a given time."
218.1441 - if not isinstance(date, _date_class):
218.1442 - raise TypeError("date argument must be a date instance")
218.1443 - if not isinstance(time, _time_class):
218.1444 - raise TypeError("time argument must be a time instance")
218.1445 - return cls(date.year, date.month, date.day,
218.1446 - time.hour, time.minute, time.second, time.microsecond,
218.1447 - time.tzinfo)
218.1448 - combine = classmethod(combine)
218.1449 -
218.1450 - def timetuple(self):
218.1451 - "Return local time tuple compatible with time.localtime()."
218.1452 - dst = self._dst()
218.1453 - if dst is None:
218.1454 - dst = -1
218.1455 - elif dst:
218.1456 - dst = 1
218.1457 - return _build_struct_time(self.year, self.month, self.day,
218.1458 - self.hour, self.minute, self.second,
218.1459 - dst)
218.1460 -
218.1461 - def utctimetuple(self):
218.1462 - "Return UTC time tuple compatible with time.gmtime()."
218.1463 - y, m, d = self.year, self.month, self.day
218.1464 - hh, mm, ss = self.hour, self.minute, self.second
218.1465 - offset = self._utcoffset()
218.1466 - if offset: # neither None nor 0
218.1467 - tm = tmxxx(y, m, d, hh, mm - offset)
218.1468 - y, m, d = tm.year, tm.month, tm.day
218.1469 - hh, mm = tm.hour, tm.minute
218.1470 - return _build_struct_time(y, m, d, hh, mm, ss, 0)
218.1471 -
218.1472 - def date(self):
218.1473 - "Return the date part."
218.1474 - return date(self.__year, self.__month, self.__day)
218.1475 -
218.1476 - def time(self):
218.1477 - "Return the time part, with tzinfo None."
218.1478 - return time(self.hour, self.minute, self.second, self.microsecond)
218.1479 -
218.1480 - def timetz(self):
218.1481 - "Return the time part, with same tzinfo."
218.1482 - return time(self.hour, self.minute, self.second, self.microsecond,
218.1483 - self._tzinfo)
218.1484 -
218.1485 - def replace(self, year=None, month=None, day=None, hour=None,
218.1486 - minute=None, second=None, microsecond=None, tzinfo=True):
218.1487 - """Return a new datetime with new values for the specified fields."""
218.1488 - if year is None:
218.1489 - year = self.year
218.1490 - if month is None:
218.1491 - month = self.month
218.1492 - if day is None:
218.1493 - day = self.day
218.1494 - if hour is None:
218.1495 - hour = self.hour
218.1496 - if minute is None:
218.1497 - minute = self.minute
218.1498 - if second is None:
218.1499 - second = self.second
218.1500 - if microsecond is None:
218.1501 - microsecond = self.microsecond
218.1502 - if tzinfo is True:
218.1503 - tzinfo = self.tzinfo
218.1504 - _check_date_fields(year, month, day)
218.1505 - _check_time_fields(hour, minute, second, microsecond)
218.1506 - _check_tzinfo_arg(tzinfo)
218.1507 - return datetime(year, month, day, hour, minute, second,
218.1508 - microsecond, tzinfo)
218.1509 -
218.1510 - def astimezone(self, tz):
218.1511 - if not isinstance(tz, tzinfo):
218.1512 - raise TypeError("tz argument must be an instance of tzinfo")
218.1513 -
218.1514 - mytz = self.tzinfo
218.1515 - if mytz is None:
218.1516 - raise ValueError("astimezone() requires an aware datetime")
218.1517 -
218.1518 - if tz is mytz:
218.1519 - return self
218.1520 -
218.1521 - # Convert self to UTC, and attach the new time zone object.
218.1522 - myoffset = self.utcoffset()
218.1523 - if myoffset is None:
218.1524 - raise ValuError("astimezone() requires an aware datetime")
218.1525 - utc = (self - myoffset).replace(tzinfo=tz)
218.1526 -
218.1527 - # Convert from UTC to tz's local time.
218.1528 - return tz.fromutc(utc)
218.1529 -
218.1530 - # Ways to produce a string.
218.1531 -
218.1532 - def ctime(self):
218.1533 - "Format a la ctime()."
218.1534 - t = tmxxx(self.__year, self.__month, self.__day, self.__hour,
218.1535 - self.__minute, self.__second)
218.1536 - return t.ctime()
218.1537 -
218.1538 - def isoformat(self, sep='T'):
218.1539 - """Return the time formatted according to ISO.
218.1540 -
218.1541 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
218.1542 - self.microsecond == 0.
218.1543 -
218.1544 - If self.tzinfo is not None, the UTC offset is also attached, giving
218.1545 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
218.1546 -
218.1547 - Optional argument sep specifies the separator between date and
218.1548 - time, default 'T'.
218.1549 - """
218.1550 - s = ("%04d-%02d-%02d%c" % (self.__year, self.__month, self.__day,
218.1551 - sep) +
218.1552 - _format_time(self.__hour, self.__minute, self.__second,
218.1553 - self.__microsecond))
218.1554 - off = self._utcoffset()
218.1555 - if off is not None:
218.1556 - if off < 0:
218.1557 - sign = "-"
218.1558 - off = -off
218.1559 - else:
218.1560 - sign = "+"
218.1561 - hh, mm = divmod(off, 60)
218.1562 - s += "%s%02d:%02d" % (sign, hh, mm)
218.1563 - return s
218.1564 -
218.1565 - def __repr__(self):
218.1566 - "Convert to formal string, for repr()."
218.1567 - L = [self.__year, self.__month, self.__day, # These are never zero
218.1568 - self.__hour, self.__minute, self.__second, self.__microsecond]
218.1569 - if L[-1] == 0:
218.1570 - del L[-1]
218.1571 - if L[-1] == 0:
218.1572 - del L[-1]
218.1573 - s = ", ".join(map(str, L))
218.1574 - s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s)
218.1575 - if self._tzinfo is not None:
218.1576 - assert s[-1:] == ")"
218.1577 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
218.1578 - return s
218.1579 -
218.1580 - def __str__(self):
218.1581 - "Convert to string, for str()."
218.1582 - return self.isoformat(sep=' ')
218.1583 -
218.1584 - def utcoffset(self):
218.1585 - """Return the timezone offset in minutes east of UTC (negative west of
218.1586 - UTC)."""
218.1587 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
218.1588 - offset = _check_utc_offset("utcoffset", offset)
218.1589 - if offset is not None:
218.1590 - offset = timedelta(minutes=offset)
218.1591 - return offset
218.1592 -
218.1593 - # Return an integer (or None) instead of a timedelta (or None).
218.1594 - def _utcoffset(self):
218.1595 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
218.1596 - offset = _check_utc_offset("utcoffset", offset)
218.1597 - return offset
218.1598 -
218.1599 - def tzname(self):
218.1600 - """Return the timezone name.
218.1601 -
218.1602 - Note that the name is 100% informational -- there's no requirement that
218.1603 - it mean anything in particular. For example, "GMT", "UTC", "-500",
218.1604 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
218.1605 - """
218.1606 - name = _call_tzinfo_method(self._tzinfo, "tzname", self)
218.1607 - _check_tzname(name)
218.1608 - return name
218.1609 -
218.1610 - def dst(self):
218.1611 - """Return 0 if DST is not in effect, or the DST offset (in minutes
218.1612 - eastward) if DST is in effect.
218.1613 -
218.1614 - This is purely informational; the DST offset has already been added to
218.1615 - the UTC offset returned by utcoffset() if applicable, so there's no
218.1616 - need to consult dst() unless you're interested in displaying the DST
218.1617 - info.
218.1618 - """
218.1619 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
218.1620 - offset = _check_utc_offset("dst", offset)
218.1621 - if offset is not None:
218.1622 - offset = timedelta(minutes=offset)
218.1623 - return offset
218.1624 -
218.1625 - # Return an integer (or None) instead of a timedelta (or None).1573
218.1626 - def _dst(self):
218.1627 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
218.1628 - offset = _check_utc_offset("dst", offset)
218.1629 - return offset
218.1630 -
218.1631 - # Comparisons.
218.1632 -
218.1633 - def __eq__(self, other):
218.1634 - if isinstance(other, datetime):
218.1635 - return self.__cmp(other) == 0
218.1636 - elif hasattr(other, "timetuple"):
218.1637 - return NotImplemented
218.1638 - else:
218.1639 - return False
218.1640 -
218.1641 - def __ne__(self, other):
218.1642 - if isinstance(other, datetime):
218.1643 - return self.__cmp(other) != 0
218.1644 - elif hasattr(other, "timetuple"):
218.1645 - return NotImplemented
218.1646 - else:
218.1647 - return True
218.1648 -
218.1649 - def __le__(self, other):
218.1650 - if isinstance(other, datetime):
218.1651 - return self.__cmp(other) <= 0
218.1652 - elif hasattr(other, "timetuple"):
218.1653 - return NotImplemented
218.1654 - else:
218.1655 - _cmperror(self, other)
218.1656 -
218.1657 - def __lt__(self, other):
218.1658 - if isinstance(other, datetime):
218.1659 - return self.__cmp(other) < 0
218.1660 - elif hasattr(other, "timetuple"):
218.1661 - return NotImplemented
218.1662 - else:
218.1663 - _cmperror(self, other)
218.1664 -
218.1665 - def __ge__(self, other):
218.1666 - if isinstance(other, datetime):
218.1667 - return self.__cmp(other) >= 0
218.1668 - elif hasattr(other, "timetuple"):
218.1669 - return NotImplemented
218.1670 - else:
218.1671 - _cmperror(self, other)
218.1672 -
218.1673 - def __gt__(self, other):
218.1674 - if isinstance(other, datetime):
218.1675 - return self.__cmp(other) > 0
218.1676 - elif hasattr(other, "timetuple"):
218.1677 - return NotImplemented
218.1678 - else:
218.1679 - _cmperror(self, other)
218.1680 -
218.1681 - def __cmp(self, other):
218.1682 - assert isinstance(other, datetime)
218.1683 - mytz = self._tzinfo
218.1684 - ottz = other._tzinfo
218.1685 - myoff = otoff = None
218.1686 -
218.1687 - if mytz is ottz:
218.1688 - base_compare = True
218.1689 - else:
218.1690 - if mytz is not None:
218.1691 - myoff = self._utcoffset()
218.1692 - if ottz is not None:
218.1693 - otoff = other._utcoffset()
218.1694 - base_compare = myoff == otoff
218.1695 -
218.1696 - if base_compare:
218.1697 - return cmp((self.__year, self.__month, self.__day,
218.1698 - self.__hour, self.__minute, self.__second,
218.1699 - self.__microsecond),
218.1700 - (other.__year, other.__month, other.__day,
218.1701 - other.__hour, other.__minute, other.__second,
218.1702 - other.__microsecond))
218.1703 - if myoff is None or otoff is None:
218.1704 - # XXX Buggy in 2.2.2.
218.1705 - raise TypeError("cannot compare naive and aware datetimes")
218.1706 - # XXX What follows could be done more efficiently...
218.1707 - diff = self - other # this will take offsets into account
218.1708 - if diff.days < 0:
218.1709 - return -1
218.1710 - return diff and 1 or 0
218.1711 -
218.1712 - def __add__(self, other):
218.1713 - "Add a datetime and a timedelta."
218.1714 - if not isinstance(other, timedelta):
218.1715 - return NotImplemented
218.1716 - t = tmxxx(self.__year,
218.1717 - self.__month,
218.1718 - self.__day + other.days,
218.1719 - self.__hour,
218.1720 - self.__minute,
218.1721 - self.__second + other.seconds,
218.1722 - self.__microsecond + other.microseconds)
218.1723 - self._checkOverflow(t.year)
218.1724 - result = self.__class__(t.year, t.month, t.day,
218.1725 - t.hour, t.minute, t.second,
218.1726 - t.microsecond, tzinfo=self._tzinfo)
218.1727 - return result
218.1728 -
218.1729 - __radd__ = __add__
218.1730 -
218.1731 - def __sub__(self, other):
218.1732 - "Subtract two datetimes, or a datetime and a timedelta."
218.1733 - if not isinstance(other, datetime):
218.1734 - if isinstance(other, timedelta):
218.1735 - return self + -other
218.1736 - return NotImplemented
218.1737 -
218.1738 - days1 = self.toordinal()
218.1739 - days2 = other.toordinal()
218.1740 - secs1 = self.__second + self.__minute * 60 + self.__hour * 3600
218.1741 - secs2 = other.__second + other.__minute * 60 + other.__hour * 3600
218.1742 - base = timedelta(days1 - days2,
218.1743 - secs1 - secs2,
218.1744 - self.__microsecond - other.__microsecond)
218.1745 - if self._tzinfo is other._tzinfo:
218.1746 - return base
218.1747 - myoff = self._utcoffset()
218.1748 - otoff = other._utcoffset()
218.1749 - if myoff == otoff:
218.1750 - return base
218.1751 - if myoff is None or otoff is None:
218.1752 - raise TypeError, "cannot mix naive and timezone-aware time"
218.1753 - return base + timedelta(minutes = otoff-myoff)
218.1754 -
218.1755 - def __hash__(self):
218.1756 - tzoff = self._utcoffset()
218.1757 - if tzoff is None:
218.1758 - return hash(self.__getstate()[0])
218.1759 - days = _ymd2ord(self.year, self.month, self.day)
218.1760 - seconds = self.hour * 3600 + (self.minute - tzoff) * 60 + self.second
218.1761 - return hash(timedelta(days, seconds, self.microsecond))
218.1762 -
218.1763 - # Pickle support.
218.1764 -
218.1765 - __safe_for_unpickling__ = True # For Python 2.2
218.1766 -
218.1767 - def __getstate(self):
218.1768 - yhi, ylo = divmod(self.__year, 256)
218.1769 - us2, us3 = divmod(self.__microsecond, 256)
218.1770 - us1, us2 = divmod(us2, 256)
218.1771 - basestate = ("%c" * 10) % (yhi, ylo, self.__month, self.__day,
218.1772 - self.__hour, self.__minute, self.__second,
218.1773 - us1, us2, us3)
218.1774 - if self._tzinfo is None:
218.1775 - return (basestate,)
218.1776 - else:
218.1777 - return (basestate, self._tzinfo)
218.1778 -
218.1779 - def __setstate(self, state):
218.1780 - assert isinstance(state, tuple)
218.1781 - assert 1 <= len(state) <= 2
218.1782 - string = state[0]
218.1783 - assert len(string) == 10
218.1784 - (yhi, ylo, self.__month, self.__day, self.__hour,
218.1785 - self.__minute, self.__second, us1, us2, us3) = map(ord, string)
218.1786 - self.__year = yhi * 256 + ylo
218.1787 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
218.1788 - if len(state) == 1:
218.1789 - self._tzinfo = None
218.1790 - else:
218.1791 - self._tzinfo = state[1]
218.1792 -
218.1793 - def __reduce__(self):
218.1794 - return (self.__class__, self.__getstate())
218.1795 -
218.1796 -
218.1797 -datetime.min = datetime(1, 1, 1)
218.1798 -datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
218.1799 -datetime.resolution = timedelta(microseconds=1)
218.1800 -
218.1801 -
218.1802 -def _isoweek1monday(year):
218.1803 - # Helper to calculate the day number of the Monday starting week 1
218.1804 - # XXX This could be done more efficiently
218.1805 - THURSDAY = 3
218.1806 - firstday = _ymd2ord(year, 1, 1)
218.1807 - firstweekday = (firstday + 6) % 7 # See weekday() above
218.1808 - week1monday = firstday - firstweekday
218.1809 - if firstweekday > THURSDAY:
218.1810 - week1monday += 7
218.1811 - return week1monday
218.1812 -
218.1813 -"""
218.1814 -Some time zone algebra. For a datetime x, let
218.1815 - x.n = x stripped of its timezone -- its naive time.
218.1816 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
218.1817 - return None
218.1818 - x.d = x.dst(), and assuming that doesn't raise an exception or
218.1819 - return None
218.1820 - x.s = x's standard offset, x.o - x.d
218.1821 -
218.1822 -Now some derived rules, where k is a duration (timedelta).
218.1823 -
218.1824 -1. x.o = x.s + x.d
218.1825 - This follows from the definition of x.s.
218.1826 -
218.1827 -2. If x and y have the same tzinfo member, x.s = y.s.
218.1828 - This is actually a requirement, an assumption we need to make about
218.1829 - sane tzinfo classes.
218.1830 -
218.1831 -3. The naive UTC time corresponding to x is x.n - x.o.
218.1832 - This is again a requirement for a sane tzinfo class.
218.1833 -
218.1834 -4. (x+k).s = x.s
218.1835 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
218.1836 -
218.1837 -5. (x+k).n = x.n + k
218.1838 - Again follows from how arithmetic is defined.
218.1839 -
218.1840 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
218.1841 -(meaning that the various tzinfo methods exist, and don't blow up or return
218.1842 -None when called).
218.1843 -
218.1844 -The function wants to return a datetime y with timezone tz, equivalent to x.
218.1845 -x is already in UTC.
218.1846 -
218.1847 -By #3, we want
218.1848 -
218.1849 - y.n - y.o = x.n [1]
218.1850 -
218.1851 -The algorithm starts by attaching tz to x.n, and calling that y. So
218.1852 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
218.1853 -becomes true; in effect, we want to solve [2] for k:
218.1854 -
218.1855 - (y+k).n - (y+k).o = x.n [2]
218.1856 -
218.1857 -By #1, this is the same as
218.1858 -
218.1859 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
218.1860 -
218.1861 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
218.1862 -Substituting that into [3],
218.1863 -
218.1864 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
218.1865 - k - (y+k).s - (y+k).d = 0; rearranging,
218.1866 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
218.1867 - k = y.s - (y+k).d
218.1868 -
218.1869 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
218.1870 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
218.1871 -very large, since all offset-returning methods return a duration of magnitude
218.1872 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
218.1873 -be 0, so ignoring it has no consequence then.
218.1874 -
218.1875 -In any case, the new value is
218.1876 -
218.1877 - z = y + y.s [4]
218.1878 -
218.1879 -It's helpful to step back at look at [4] from a higher level: it's simply
218.1880 -mapping from UTC to tz's standard time.
218.1881 -
218.1882 -At this point, if
218.1883 -
218.1884 - z.n - z.o = x.n [5]
218.1885 -
218.1886 -we have an equivalent time, and are almost done. The insecurity here is
218.1887 -at the start of daylight time. Picture US Eastern for concreteness. The wall
218.1888 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
218.1889 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
218.1890 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
218.1891 -on the day DST starts. We want to return the 1:MM EST spelling because that's
218.1892 -the only spelling that makes sense on the local wall clock.
218.1893 -
218.1894 -In fact, if [5] holds at this point, we do have the standard-time spelling,
218.1895 -but that takes a bit of proof. We first prove a stronger result. What's the
218.1896 -difference between the LHS and RHS of [5]? Let
218.1897 -
218.1898 - diff = x.n - (z.n - z.o) [6]
218.1899 -
218.1900 -Now
218.1901 - z.n = by [4]
218.1902 - (y + y.s).n = by #5
218.1903 - y.n + y.s = since y.n = x.n
218.1904 - x.n + y.s = since z and y are have the same tzinfo member,
218.1905 - y.s = z.s by #2
218.1906 - x.n + z.s
218.1907 -
218.1908 -Plugging that back into [6] gives
218.1909 -
218.1910 - diff =
218.1911 - x.n - ((x.n + z.s) - z.o) = expanding
218.1912 - x.n - x.n - z.s + z.o = cancelling
218.1913 - - z.s + z.o = by #2
218.1914 - z.d
218.1915 -
218.1916 -So diff = z.d.
218.1917 -
218.1918 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
218.1919 -spelling we wanted in the endcase described above. We're done. Contrarily,
218.1920 -if z.d = 0, then we have a UTC equivalent, and are also done.
218.1921 -
218.1922 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
218.1923 -add to z (in effect, z is in tz's standard time, and we need to shift the
218.1924 -local clock into tz's daylight time).
218.1925 -
218.1926 -Let
218.1927 -
218.1928 - z' = z + z.d = z + diff [7]
218.1929 -
218.1930 -and we can again ask whether
218.1931 -
218.1932 - z'.n - z'.o = x.n [8]
218.1933 -
218.1934 -If so, we're done. If not, the tzinfo class is insane, according to the
218.1935 -assumptions we've made. This also requires a bit of proof. As before, let's
218.1936 -compute the difference between the LHS and RHS of [8] (and skipping some of
218.1937 -the justifications for the kinds of substitutions we've done several times
218.1938 -already):
218.1939 -
218.1940 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
218.1941 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
218.1942 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
218.1943 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
218.1944 - - z.n + z.n - z.o + z'.o = cancel z.n
218.1945 - - z.o + z'.o = #1 twice
218.1946 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
218.1947 - z'.d - z.d
218.1948 -
218.1949 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
218.1950 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
218.1951 -return z', not bothering to compute z'.d.
218.1952 -
218.1953 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
218.1954 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
218.1955 -would have to change the result dst() returns: we start in DST, and moving
218.1956 -a little further into it takes us out of DST.
218.1957 -
218.1958 -There isn't a sane case where this can happen. The closest it gets is at
218.1959 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
218.1960 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
218.1961 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
218.1962 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
218.1963 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
218.1964 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
218.1965 -standard time. Since that's what the local clock *does*, we want to map both
218.1966 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
218.1967 -in local time, but so it goes -- it's the way the local clock works.
218.1968 -
218.1969 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
218.1970 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
218.1971 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
218.1972 -(correctly) concludes that z' is not UTC-equivalent to x.
218.1973 -
218.1974 -Because we know z.d said z was in daylight time (else [5] would have held and
218.1975 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
218.1976 -and we we have stopped then), and there are only 2 possible values dst() can
218.1977 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
218.1978 -but the reasoning doesn't depend on the example -- it depends on there being
218.1979 -two possible dst() outcomes, one zero and the other non-zero). Therefore
218.1980 -z' must be in standard time, and is the spelling we want in this case.
218.1981 -
218.1982 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
218.1983 -concerned (because it takes z' as being in standard time rather than the
218.1984 -daylight time we intend here), but returning it gives the real-life "local
218.1985 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
218.1986 -tz.
218.1987 -
218.1988 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
218.1989 -the 1:MM standard time spelling we want.
218.1990 -
218.1991 -So how can this break? One of the assumptions must be violated. Two
218.1992 -possibilities:
218.1993 -
218.1994 -1) [2] effectively says that y.s is invariant across all y belong to a given
218.1995 - time zone. This isn't true if, for political reasons or continental drift,
218.1996 - a region decides to change its base offset from UTC.
218.1997 -
218.1998 -2) There may be versions of "double daylight" time where the tail end of
218.1999 - the analysis gives up a step too early. I haven't thought about that
218.2000 - enough to say.
218.2001 -
218.2002 -In any case, it's clear that the default fromutc() is strong enough to handle
218.2003 -"almost all" time zones: so long as the standard offset is invariant, it
218.2004 -doesn't matter if daylight time transition points change from year to year, or
218.2005 -if daylight time is skipped in some years; it doesn't matter how large or
218.2006 -small dst() may get within its bounds; and it doesn't even matter if some
218.2007 -perverse time zone returns a negative dst()). So a breaking case must be
218.2008 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
218.2009 -"""
218.2010 -
218.2011 -def _test():
218.2012 - import test_datetime
218.2013 - test_datetime.test_main()
218.2014 -
218.2015 -if __name__ == "__main__":
218.2016 - _test()
219.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testFix3.fixed Sun Jan 04 13:11:53 2015 -0600
219.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
219.3 @@ -1,2011 +0,0 @@
219.4 -"""Concrete date/time and related types -- prototype implemented in Python.
219.5 -
219.6 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
219.7 -
219.8 -See also http://dir.yahoo.com/Reference/calendars/
219.9 -
219.10 -For a primer on DST, including many current DST rules, see
219.11 -http://webexhibits.org/daylightsaving/
219.12 -
219.13 -For more about DST than you ever wanted to know, see
219.14 -ftp://elsie.nci.nih.gov/pub/
219.15 -
219.16 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
219.17 -
219.18 -"""
219.19 -
219.20 -import time as _time
219.21 -import math as _math
219.22 -
219.23 -MINYEAR = 1
219.24 -MAXYEAR = 9999
219.25 -
219.26 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
219.27 -# also assumes the current Gregorian calendar indefinitely extended in
219.28 -# both directions. Difference: Dates.py calls January 1 of year 0 day
219.29 -# number 1. The code here calls January 1 of year 1 day number 1. This is
219.30 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
219.31 -# and Reingold's "Calendrical Calculations", where it's the base calendar
219.32 -# for all computations. See the book for algorithms for converting between
219.33 -# proleptic Gregorian ordinals and many other calendar systems.
219.34 -
219.35 -_DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
219.36 -
219.37 -_DAYS_BEFORE_MONTH = [None]
219.38 -dbm = 0
219.39 -for dim in _DAYS_IN_MONTH[1:]:
219.40 - _DAYS_BEFORE_MONTH.append(dbm)
219.41 - dbm += dim
219.42 -del dbm, dim
219.43 -
219.44 -def _is_leap(year):
219.45 - "year -> 1 if leap year, else 0."
219.46 - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
219.47 -
219.48 -def _days_in_year(year):
219.49 - "year -> number of days in year (366 if a leap year, else 365)."
219.50 - return 365 + _is_leap(year)
219.51 -
219.52 -def _days_before_year(year):
219.53 - "year -> number of days before January 1st of year."
219.54 - y = year - 1
219.55 - return y*365 + y//4 - y//100 + y//400
219.56 -
219.57 -def _days_in_month(year, month):
219.58 - "year, month -> number of days in that month in that year."
219.59 - try:
219.60 - assert 1 <= month <= 12, month
219.61 - if month == 2 and _is_leap(year):
219.62 - return 29
219.63 - finally:
219.64 -
219.65 - return _DAYS_IN_MONTH[month]
219.66 -
219.67 -def _days_before_month(year, month):
219.68 - "year, month -> number of days in year preceeding first day of month."
219.69 - if not 1 <= month <= 12:
219.70 - raise ValueError('month must be in 1..12', month)
219.71 - return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
219.72 -
219.73 -def _ymd2ord(year, month, day):
219.74 - "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
219.75 - if not 1 <= month <= 12:
219.76 - raise ValueError('month must be in 1..12', month)
219.77 - dim = _days_in_month(year, month)
219.78 - if not 1 <= day <= dim:
219.79 - raise ValueError('day must be in 1..%d' % dim, day)
219.80 - return (_days_before_year(year) +
219.81 - _days_before_month(year, month) +
219.82 - day)
219.83 -
219.84 -_DI400Y = _days_before_year(401) # number of days in 400 years
219.85 -_DI100Y = _days_before_year(101) # " " " " 100 "
219.86 -_DI4Y = _days_before_year(5) # " " " " 4 "
219.87 -
219.88 -# A 4-year cycle has an extra leap day over what we'd get from pasting
219.89 -# together 4 single years.
219.90 -assert _DI4Y == 4 * 365 + 1
219.91 -
219.92 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
219.93 -# pasting together 4 100-year cycles.
219.94 -assert _DI400Y == 4 * _DI100Y + 1
219.95 -
219.96 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
219.97 -# pasting together 25 4-year cycles.
219.98 -assert _DI100Y == 25 * _DI4Y - 1
219.99 -
219.100 -def _ord2ymd(n):
219.101 - "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
219.102 -
219.103 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
219.104 - # repeats exactly every 400 years. The basic strategy is to find the
219.105 - # closest 400-year boundary at or before n, then work with the offset
219.106 - # from that boundary to n. Life is much clearer if we subtract 1 from
219.107 - # n first -- then the values of n at 400-year boundaries are exactly
219.108 - # those divisible by _DI400Y:
219.109 - #
219.110 - # D M Y n n-1
219.111 - # -- --- ---- ---------- ----------------
219.112 - # 31 Dec -400 -_DI400Y -_DI400Y -1
219.113 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
219.114 - # ...
219.115 - # 30 Dec 000 -1 -2
219.116 - # 31 Dec 000 0 -1
219.117 - # 1 Jan 001 1 0 400-year boundary
219.118 - # 2 Jan 001 2 1
219.119 - # 3 Jan 001 3 2
219.120 - # ...
219.121 - # 31 Dec 400 _DI400Y _DI400Y -1
219.122 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
219.123 - n -= 1
219.124 - n400, n = divmod(n, _DI400Y)
219.125 - year = n400 * 400 + 1 # ..., -399, 1, 401, ...
219.126 -
219.127 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
219.128 - # the desired date. Now compute how many 100-year cycles precede n.
219.129 - # Note that it's possible for n100 to equal 4! In that case 4 full
219.130 - # 100-year cycles precede the desired day, which implies the desired
219.131 - # day is December 31 at the end of a 400-year cycle.
219.132 - n100, n = divmod(n, _DI100Y)
219.133 -
219.134 - # Now compute how many 4-year cycles precede it.
219.135 - n4, n = divmod(n, _DI4Y)
219.136 -
219.137 - # And now how many single years. Again n1 can be 4, and again meaning
219.138 - # that the desired day is December 31 at the end of the 4-year cycle.
219.139 - n1, n = divmod(n, 365)
219.140 -
219.141 - year += n100 * 100 + n4 * 4 + n1
219.142 - if n1 == 4 or n100 == 4:
219.143 - assert n == 0
219.144 - return year-1, 12, 31
219.145 -
219.146 - # Now the year is correct, and n is the offset from January 1. We find
219.147 - # the month via an estimate that's either exact or one too large.
219.148 - leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
219.149 - assert leapyear == _is_leap(year)
219.150 - month = (n + 50) >> 5
219.151 - preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
219.152 - if preceding > n: # estimate is too large
219.153 - month -= 1
219.154 - preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
219.155 - n -= preceding
219.156 - assert 0 <= n < _days_in_month(year, month)
219.157 -
219.158 - # Now the year and month are correct, and n is the offset from the
219.159 - # start of that month: we're done!
219.160 - return year, month, n+1
219.161 -
219.162 -# Month and day names. For localized versions, see the calendar module.
219.163 -_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
219.164 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
219.165 -_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
219.166 -
219.167 -
219.168 -def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
219.169 - wday = (_ymd2ord(y, m, d) + 6) % 7
219.170 - dnum = _days_before_month(y, m) + d
219.171 - return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
219.172 -
219.173 -def _format_time(hh, mm, ss, us):
219.174 - # Skip trailing microseconds when us==0.
219.175 - result = "%02d:%02d:%02d" % (hh, mm, ss)
219.176 - if us:
219.177 - result += ".%06d" % us
219.178 - return result
219.179 -
219.180 -# Correctly substitute for %z and %Z escapes in strftime formats.
219.181 -def _wrap_strftime(object, format, timetuple):
219.182 - year = timetuple[0]
219.183 - if year < 1900:
219.184 - raise ValueError("year=%d is before 1900; the datetime strftime() "
219.185 - "methods require year >= 1900" % year)
219.186 - # Don't call _utcoffset() or tzname() unless actually needed.
219.187 - zreplace = None # the string to use for %z
219.188 - Zreplace = None # the string to use for %Z
219.189 -
219.190 - # Scan format for %z and %Z escapes, replacing as needed.
219.191 - newformat = []
219.192 - push = newformat.append
219.193 - i, n = 0, len(format)
219.194 - while i < n:
219.195 - ch = format[i]
219.196 - i += 1
219.197 - if ch == '%':
219.198 - if i < n:
219.199 - ch = format[i]
219.200 - i += 1
219.201 - if ch == 'z':
219.202 - if zreplace is None:
219.203 - zreplace = ""
219.204 - if hasattr(object, "_utcoffset"):
219.205 - offset = object._utcoffset()
219.206 - if offset is not None:
219.207 - sign = '+'
219.208 - if offset < 0:
219.209 - offset = -offset
219.210 - sign = '-'
219.211 - h, m = divmod(offset, 60)
219.212 - zreplace = '%c%02d%02d' % (sign, h, m)
219.213 - assert '%' not in zreplace
219.214 - newformat.append(zreplace)
219.215 - elif ch == 'Z':
219.216 - if Zreplace is None:
219.217 - Zreplace = ""
219.218 - if hasattr(object, "tzname"):
219.219 - s = object.tzname()
219.220 - if s is not None:
219.221 - # strftime is going to have at this: escape %
219.222 - Zreplace = s.replace('%', '%%')
219.223 - newformat.append(Zreplace)
219.224 - else:
219.225 - push('%')
219.226 - push(ch)
219.227 - else:
219.228 - push('%')
219.229 - else:
219.230 - push(ch)
219.231 - newformat = "".join(newformat)
219.232 - return _time.strftime(newformat, timetuple)
219.233 -
219.234 -def _call_tzinfo_method(tzinfo, methname, tzinfoarg):
219.235 - if tzinfo is None:
219.236 - return None
219.237 - return getattr(tzinfo, methname)(tzinfoarg)
219.238 -
219.239 -# Just raise TypeError if the arg isn't None or a string.
219.240 -def _check_tzname(name):
219.241 - if name is not None and not isinstance(name, str):
219.242 - raise TypeError("tzinfo.tzname() must return None or string, "
219.243 - "not '%s'" % type(name))
219.244 -
219.245 -# name is the offset-producing method, "utcoffset" or "dst".
219.246 -# offset is what it returned.
219.247 -# If offset isn't None or timedelta, raises TypeError.
219.248 -# If offset is None, returns None.
219.249 -# Else offset is checked for being in range, and a whole # of minutes.
219.250 -# If it is, its integer value is returned. Else ValueError is raised.
219.251 -def _check_utc_offset(name, offset):
219.252 - assert name in ("utcoffset", "dst")
219.253 - if offset is None:
219.254 - return None
219.255 - if not isinstance(offset, timedelta):
219.256 - raise TypeError("tzinfo.%s() must return None "
219.257 - "or timedelta, not '%s'" % (name, type(offset)))
219.258 - days = offset.days
219.259 - if days < -1 or days > 0:
219.260 - offset = 1440 # trigger out-of-range
219.261 - else:
219.262 - seconds = days * 86400 + offset.seconds
219.263 - minutes, seconds = divmod(seconds, 60)
219.264 - if seconds or offset.microseconds:
219.265 - raise ValueError("tzinfo.%s() must return a whole number "
219.266 - "of minutes" % name)
219.267 - offset = minutes
219.268 - if -1440 < offset < 1440:
219.269 - return offset
219.270 - raise ValueError("%s()=%d, must be in -1439..1439" % (name, offset))
219.271 -
219.272 -def _check_date_fields(year, month, day):
219.273 - if not MINYEAR <= year <= MAXYEAR:
219.274 - raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
219.275 - if not 1 <= month <= 12:
219.276 - raise ValueError('month must be in 1..12', month)
219.277 - dim = _days_in_month(year, month)
219.278 - if not 1 <= day <= dim:
219.279 - raise ValueError('day must be in 1..%d' % dim, day)
219.280 -
219.281 -def _check_time_fields(hour, minute, second, microsecond):
219.282 - if not 0 <= hour <= 23:
219.283 - raise ValueError('hour must be in 0..23', hour)
219.284 - if not 0 <= minute <= 59:
219.285 - raise ValueError('minute must be in 0..59', minute)
219.286 - if not 0 <= second <= 59:
219.287 - raise ValueError('second must be in 0..59', second)
219.288 - if not 0 <= microsecond <= 999999:
219.289 - raise ValueError('microsecond must be in 0..999999', microsecond)
219.290 -
219.291 -def _check_tzinfo_arg(tz):
219.292 - if tz is not None and not isinstance(tz, tzinfo):
219.293 - raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
219.294 -
219.295 -
219.296 -# Notes on comparison: In general, datetime module comparison operators raise
219.297 -# TypeError when they don't know how to do a comparison themself. If they
219.298 -# returned NotImplemented instead, comparison could (silently) fall back to
219.299 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
219.300 -# and that's not helpful. There are two exceptions:
219.301 -#
219.302 -# 1. For date and datetime, if the other object has a "timetuple" attr,
219.303 -# NotImplemented is returned. This is a hook to allow other kinds of
219.304 -# datetime-like objects a chance to intercept the comparison.
219.305 -#
219.306 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
219.307 -# so opertaions like
219.308 -#
219.309 -# x == y
219.310 -# x != y
219.311 -# x in sequence
219.312 -# x not in sequence
219.313 -# dict[x] = y
219.314 -#
219.315 -# don't raise annoying TypeErrors just because a datetime object
219.316 -# is part of a heterogeneous collection. If there's no known way to
219.317 -# compare X to a datetime, saying they're not equal is reasonable.
219.318 -
219.319 -def _cmperror(x, y):
219.320 - raise TypeError("can't compare '%s' to '%s'" % (
219.321 - type(x).__name__, type(y).__name__))
219.322 -
219.323 -# This is a start at a struct tm workalike. Goals:
219.324 -#
219.325 -# + Works the same way across platforms.
219.326 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
219.327 -#
219.328 -# Note: I suspect it's best if this flavor of tm does *not* try to
219.329 -# second-guess timezones or DST. Instead fold whatever adjustments you want
219.330 -# into the minutes argument (and the constructor will normalize).
219.331 -
219.332 -_ORD1970 = _ymd2ord(1970, 1, 1) # base ordinal for UNIX epoch
219.333 -
219.334 -class tmxxx:
219.335 -
219.336 - ordinal = None
219.337 -
219.338 - def __init__(self, year, month, day, hour=0, minute=0, second=0,
219.339 - microsecond=0):
219.340 - # Normalize all the inputs, and store the normalized values.
219.341 - if not 0 <= microsecond <= 999999:
219.342 - carry, microsecond = divmod(microsecond, 1000000)
219.343 - second += carry
219.344 - if not 0 <= second <= 59:
219.345 - carry, second = divmod(second, 60)
219.346 - minute += carry
219.347 - if not 0 <= minute <= 59:
219.348 - carry, minute = divmod(minute, 60)
219.349 - hour += carry
219.350 - if not 0 <= hour <= 23:
219.351 - carry, hour = divmod(hour, 24)
219.352 - day += carry
219.353 -
219.354 - # That was easy. Now it gets muddy: the proper range for day
219.355 - # can't be determined without knowing the correct month and year,
219.356 - # but if day is, e.g., plus or minus a million, the current month
219.357 - # and year values make no sense (and may also be out of bounds
219.358 - # themselves).
219.359 - # Saying 12 months == 1 year should be non-controversial.
219.360 - if not 1 <= month <= 12:
219.361 - carry, month = divmod(month-1, 12)
219.362 - year += carry
219.363 - month += 1
219.364 - assert 1 <= month <= 12
219.365 -
219.366 - # Now only day can be out of bounds (year may also be out of bounds
219.367 - # for a datetime object, but we don't care about that here).
219.368 - # If day is out of bounds, what to do is arguable, but at least the
219.369 - # method here is principled and explainable.
219.370 - dim = _days_in_month(year, month)
219.371 - if not 1 <= day <= dim:
219.372 - # Move day-1 days from the first of the month. First try to
219.373 - # get off cheap if we're only one day out of range (adjustments
219.374 - # for timezone alone can't be worse than that).
219.375 - if day == 0: # move back a day
219.376 - month -= 1
219.377 - if month > 0:
219.378 - day = _days_in_month(year, month)
219.379 - else:
219.380 - year, month, day = year-1, 12, 31
219.381 - elif day == dim + 1: # move forward a day
219.382 - month += 1
219.383 - day = 1
219.384 - if month > 12:
219.385 - month = 1
219.386 - year += 1
219.387 - else:
219.388 - self.ordinal = _ymd2ord(year, month, 1) + (day - 1)
219.389 - year, month, day = _ord2ymd(self.ordinal)
219.390 -
219.391 - self.year, self.month, self.day = year, month, day
219.392 - self.hour, self.minute, self.second = hour, minute, second
219.393 - self.microsecond = microsecond
219.394 -
219.395 - def toordinal(self):
219.396 - """Return proleptic Gregorian ordinal for the year, month and day.
219.397 -
219.398 - January 1 of year 1 is day 1. Only the year, month and day values
219.399 - contribute to the result.
219.400 - """
219.401 - if self.ordinal is None:
219.402 - self.ordinal = _ymd2ord(self.year, self.month, self.day)
219.403 - return self.ordinal
219.404 -
219.405 - def time(self):
219.406 - "Return Unixish timestamp, as a float (assuming UTC)."
219.407 - days = self.toordinal() - _ORD1970 # convert to UNIX epoch
219.408 - seconds = ((days * 24. + self.hour)*60. + self.minute)*60.
219.409 - return seconds + self.second + self.microsecond / 1e6
219.410 -
219.411 - def ctime(self):
219.412 - "Return ctime() style string."
219.413 - weekday = self.toordinal() % 7 or 7
219.414 - return "%s %s %2d %02d:%02d:%02d %04d" % (
219.415 - _DAYNAMES[weekday],
219.416 - _MONTHNAMES[self.month],
219.417 - self.day,
219.418 - self.hour, self.minute, self.second,
219.419 - self.year)
219.420 -
219.421 -class timedelta(object):
219.422 - """Represent the difference between two datetime objects.
219.423 -
219.424 - Supported operators:
219.425 -
219.426 - - add, subtract timedelta
219.427 - - unary plus, minus, abs
219.428 - - compare to timedelta
219.429 - - multiply, divide by int/long
219.430 -
219.431 - In addition, datetime supports subtraction of two datetime objects
219.432 - returning a timedelta, and addition or subtraction of a datetime
219.433 - and a timedelta giving a datetime.
219.434 -
219.435 - Representation: (days, seconds, microseconds). Why? Because I
219.436 - felt like it.
219.437 - """
219.438 -
219.439 - def __new__(cls, days=0, seconds=0, microseconds=0,
219.440 - # XXX The following should only be used as keyword args:
219.441 - milliseconds=0, minutes=0, hours=0, weeks=0):
219.442 - # Doing this efficiently and accurately in C is going to be difficult
219.443 - # and error-prone, due to ubiquitous overflow possibilities, and that
219.444 - # C double doesn't have enough bits of precision to represent
219.445 - # microseconds over 10K years faithfully. The code here tries to make
219.446 - # explicit where go-fast assumptions can be relied on, in order to
219.447 - # guide the C implementation; it's way more convoluted than speed-
219.448 - # ignoring auto-overflow-to-long idiomatic Python could be.
219.449 -
219.450 - # XXX Check that all inputs are ints, longs or floats.
219.451 -
219.452 - # Final values, all integer.
219.453 - # s and us fit in 32-bit signed ints; d isn't bounded.
219.454 - d = s = us = 0
219.455 -
219.456 - # Normalize everything to days, seconds, microseconds.
219.457 - days += weeks*7
219.458 - seconds += minutes*60 + hours*3600
219.459 - microseconds += milliseconds*1000
219.460 -
219.461 - # Get rid of all fractions, and normalize s and us.
219.462 - # Take a deep breath <wink>.
219.463 - if isinstance(days, float):
219.464 - dayfrac, days = _math.modf(days)
219.465 - daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
219.466 - assert daysecondswhole == int(daysecondswhole) # can't overflow
219.467 - s = int(daysecondswhole)
219.468 - assert days == long(days)
219.469 - d = long(days)
219.470 - else:
219.471 - daysecondsfrac = 0.0
219.472 - d = days
219.473 - assert isinstance(daysecondsfrac, float)
219.474 - assert abs(daysecondsfrac) <= 1.0
219.475 - assert isinstance(d, (int, long))
219.476 - assert abs(s) <= 24 * 3600
219.477 - # days isn't referenced again before redefinition
219.478 -
219.479 - if isinstance(seconds, float):
219.480 - secondsfrac, seconds = _math.modf(seconds)
219.481 - assert seconds == long(seconds)
219.482 - seconds = long(seconds)
219.483 - secondsfrac += daysecondsfrac
219.484 - assert abs(secondsfrac) <= 2.0
219.485 - else:
219.486 - secondsfrac = daysecondsfrac
219.487 - # daysecondsfrac isn't referenced again
219.488 - assert isinstance(secondsfrac, float)
219.489 - assert abs(secondsfrac) <= 2.0
219.490 -
219.491 - assert isinstance(seconds, (int, long))
219.492 - days, seconds = divmod(seconds, 24*3600)
219.493 - d += days
219.494 - s += int(seconds) # can't overflow
219.495 - assert isinstance(s, int)
219.496 - assert abs(s) <= 2 * 24 * 3600
219.497 - # seconds isn't referenced again before redefinition
219.498 -
219.499 - usdouble = secondsfrac * 1e6
219.500 - assert abs(usdouble) < 2.1e6 # exact value not critical
219.501 - # secondsfrac isn't referenced again
219.502 -
219.503 - if isinstance(microseconds, float):
219.504 - microseconds += usdouble
219.505 - microseconds = round(microseconds)
219.506 - seconds, microseconds = divmod(microseconds, 1e6)
219.507 - assert microseconds == int(microseconds)
219.508 - assert seconds == long(seconds)
219.509 - days, seconds = divmod(seconds, 24.*3600.)
219.510 - assert days == long(days)
219.511 - assert seconds == int(seconds)
219.512 - d += long(days)
219.513 - s += int(seconds) # can't overflow
219.514 - assert isinstance(s, int)
219.515 - assert abs(s) <= 3 * 24 * 3600
219.516 - else:
219.517 - seconds, microseconds = divmod(microseconds, 1000000)
219.518 - days, seconds = divmod(seconds, 24*3600)
219.519 - d += days
219.520 - s += int(seconds) # can't overflow
219.521 - assert isinstance(s, int)
219.522 - assert abs(s) <= 3 * 24 * 3600
219.523 - microseconds = float(microseconds)
219.524 - microseconds += usdouble
219.525 - microseconds = round(microseconds)
219.526 - assert abs(s) <= 3 * 24 * 3600
219.527 - assert abs(microseconds) < 3.1e6
219.528 -
219.529 - # Just a little bit of carrying possible for microseconds and seconds.
219.530 - assert isinstance(microseconds, float)
219.531 - assert int(microseconds) == microseconds
219.532 - us = int(microseconds)
219.533 - seconds, us = divmod(us, 1000000)
219.534 - s += seconds # cant't overflow
219.535 - assert isinstance(s, int)
219.536 - days, s = divmod(s, 24*3600)
219.537 - d += days
219.538 -
219.539 - assert isinstance(d, (int, long))
219.540 - assert isinstance(s, int) and 0 <= s < 24*3600
219.541 - assert isinstance(us, int) and 0 <= us < 1000000
219.542 -
219.543 - self = object.__new__(cls)
219.544 -
219.545 - self.__days = d
219.546 - self.__seconds = s
219.547 - self.__microseconds = us
219.548 - if abs(d) > 999999999:
219.549 - raise OverflowError("timedelta # of days is too large: %d" % d)
219.550 -
219.551 - return self
219.552 -
219.553 - def __repr__(self):
219.554 - if self.__microseconds:
219.555 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
219.556 - self.__days,
219.557 - self.__seconds,
219.558 - self.__microseconds)
219.559 - if self.__seconds:
219.560 - return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__,
219.561 - self.__days,
219.562 - self.__seconds)
219.563 - return "%s(%d)" % ('datetime.' + self.__class__.__name__, self.__days)
219.564 -
219.565 - def __str__(self):
219.566 - mm, ss = divmod(self.__seconds, 60)
219.567 - hh, mm = divmod(mm, 60)
219.568 - s = "%d:%02d:%02d" % (hh, mm, ss)
219.569 - if self.__days:
219.570 - def plural(n):
219.571 - return n, abs(n) != 1 and "s" or ""
219.572 - s = ("%d day%s, " % plural(self.__days)) + s
219.573 - if self.__microseconds:
219.574 - s = s + ".%06d" % self.__microseconds
219.575 - return s
219.576 -
219.577 - days = property(lambda self: self.__days, doc="days")
219.578 - seconds = property(lambda self: self.__seconds, doc="seconds")
219.579 - microseconds = property(lambda self: self.__microseconds,
219.580 - doc="microseconds")
219.581 -
219.582 - def __add__(self, other):
219.583 - if isinstance(other, timedelta):
219.584 - return timedelta(self.__days + other.__days,
219.585 - self.__seconds + other.__seconds,
219.586 - self.__microseconds + other.__microseconds)
219.587 - return NotImplemented
219.588 -
219.589 - __radd__ = __add__
219.590 -
219.591 - def __sub__(self, other):
219.592 - if isinstance(other, timedelta):
219.593 - return self + -other
219.594 - return NotImplemented
219.595 -
219.596 - def __rsub__(self, other):
219.597 - if isinstance(other, timedelta):
219.598 - return -self + other
219.599 - return NotImplemented
219.600 -
219.601 - def __neg__(self):
219.602 - return self.__class__(-self.__days,
219.603 - -self.__seconds,
219.604 - -self.__microseconds)
219.605 -
219.606 - def __pos__(self):
219.607 - return self
219.608 -
219.609 - def __abs__(self):
219.610 - if self.__days < 0:
219.611 - return -self
219.612 - else:
219.613 - return self
219.614 -
219.615 - def __mul__(self, other):
219.616 - if isinstance(other, (int, long)):
219.617 - return self.__class__(self.__days * other,
219.618 - self.__seconds * other,
219.619 - self.__microseconds * other)
219.620 - return NotImplemented
219.621 -
219.622 - __rmul__ = __mul__
219.623 -
219.624 - def __div__(self, other):
219.625 - if isinstance(other, (int, long)):
219.626 - usec = ((self.__days * (24*3600L) + self.__seconds) * 1000000 +
219.627 - self.__microseconds)
219.628 - return self.__class__(0, 0, usec // other)
219.629 - return NotImplemented
219.630 -
219.631 - __floordiv__ = __div__
219.632 -
219.633 - # Comparisons.
219.634 -
219.635 - def __eq__(self, other):
219.636 - if isinstance(other, timedelta):
219.637 - return self.__cmp(other) == 0
219.638 - else:
219.639 - return False
219.640 -
219.641 - def __ne__(self, other):
219.642 - if isinstance(other, timedelta):
219.643 - return self.__cmp(other) != 0
219.644 - else:
219.645 - return True
219.646 -
219.647 - def __le__(self, other):
219.648 - if isinstance(other, timedelta):
219.649 - return self.__cmp(other) <= 0
219.650 - else:
219.651 - _cmperror(self, other)
219.652 -
219.653 - def __lt__(self, other):
219.654 - if isinstance(other, timedelta):
219.655 - return self.__cmp(other) < 0
219.656 - else:
219.657 - _cmperror(self, other)
219.658 -
219.659 - def __ge__(self, other):
219.660 - if isinstance(other, timedelta):
219.661 - return self.__cmp(other) >= 0
219.662 - else:
219.663 - _cmperror(self, other)
219.664 -
219.665 - def __gt__(self, other):
219.666 - if isinstance(other, timedelta):
219.667 - return self.__cmp(other) > 0
219.668 - else:
219.669 - _cmperror(self, other)
219.670 -
219.671 - def __cmp(self, other):
219.672 - assert isinstance(other, timedelta)
219.673 - return cmp(self.__getstate(), other.__getstate())
219.674 -
219.675 - def __hash__(self):
219.676 - return hash(self.__getstate())
219.677 -
219.678 - def __nonzero__(self):
219.679 - return (self.__days != 0 or
219.680 - self.__seconds != 0 or
219.681 - self.__microseconds != 0)
219.682 -
219.683 - # Pickle support.
219.684 -
219.685 - __safe_for_unpickling__ = True # For Python 2.2
219.686 -
219.687 - def __getstate(self):
219.688 - return (self.__days, self.__seconds, self.__microseconds)
219.689 -
219.690 - def __reduce__(self):
219.691 - return (self.__class__, self.__getstate())
219.692 -
219.693 -timedelta.min = timedelta(-999999999)
219.694 -timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
219.695 - microseconds=999999)
219.696 -timedelta.resolution = timedelta(microseconds=1)
219.697 -
219.698 -class date(object):
219.699 - """Concrete date type.
219.700 -
219.701 - Constructors:
219.702 -
219.703 - __new__()
219.704 - fromtimestamp()
219.705 - today()
219.706 - fromordinal()
219.707 -
219.708 - Operators:
219.709 -
219.710 - __repr__, __str__
219.711 - __cmp__, __hash__
219.712 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
219.713 -
219.714 - Methods:
219.715 -
219.716 - timetuple()
219.717 - toordinal()
219.718 - weekday()
219.719 - isoweekday(), isocalendar(), isoformat()
219.720 - ctime()
219.721 - strftime()
219.722 -
219.723 - Properties (readonly):
219.724 - year, month, day
219.725 - """
219.726 -
219.727 - def __new__(cls, year, month=None, day=None):
219.728 - """Constructor.
219.729 -
219.730 - Arguments:
219.731 -
219.732 - year, month, day (required, base 1)
219.733 - """
219.734 - if isinstance(year, str):
219.735 - # Pickle support
219.736 - self = object.__new__(cls)
219.737 - self.__setstate((year,))
219.738 - return self
219.739 - _check_date_fields(year, month, day)
219.740 - self = object.__new__(cls)
219.741 - self.__year = year
219.742 - self.__month = month
219.743 - self.__day = day
219.744 - return self
219.745 -
219.746 - # Additional constructors
219.747 -
219.748 - def fromtimestamp(cls, t):
219.749 - "Construct a date from a POSIX timestamp (like time.time())."
219.750 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
219.751 - return cls(y, m, d)
219.752 - fromtimestamp = classmethod(fromtimestamp)
219.753 -
219.754 - def today(cls):
219.755 - "Construct a date from time.time()."
219.756 - t = _time.time()
219.757 - return cls.fromtimestamp(t)
219.758 - today = classmethod(today)
219.759 -
219.760 - def fromordinal(cls, n):
219.761 - """Contruct a date from a proleptic Gregorian ordinal.
219.762 -
219.763 - January 1 of year 1 is day 1. Only the year, month and day are
219.764 - non-zero in the result.
219.765 - """
219.766 - y, m, d = _ord2ymd(n)
219.767 - return cls(y, m, d)
219.768 - fromordinal = classmethod(fromordinal)
219.769 -
219.770 - # Conversions to string
219.771 -
219.772 - def __repr__(self):
219.773 - "Convert to formal string, for repr()."
219.774 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
219.775 - self.__year,
219.776 - self.__month,
219.777 - self.__day)
219.778 - # XXX These shouldn't depend on time.localtime(), because that
219.779 - # clips the usable dates to [1970 .. 2038). At least ctime() is
219.780 - # easily done without using strftime() -- that's better too because
219.781 - # strftime("%c", ...) is locale specific.
219.782 -
219.783 - def ctime(self):
219.784 - "Format a la ctime()."
219.785 - return tmxxx(self.__year, self.__month, self.__day).ctime()
219.786 -
219.787 - def strftime(self, fmt):
219.788 - "Format using strftime()."
219.789 - return _wrap_strftime(self, fmt, self.timetuple())
219.790 -
219.791 - def isoformat(self):
219.792 - """Return the date formatted according to ISO.
219.793 -
219.794 - This is 'YYYY-MM-DD'.
219.795 -
219.796 - References:
219.797 - - http://www.w3.org/TR/NOTE-datetime
219.798 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
219.799 - """
219.800 - return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day)
219.801 -
219.802 - __str__ = isoformat
219.803 -
219.804 - # Read-only field accessors
219.805 - year = property(lambda self: self.__year,
219.806 - doc="year (%d-%d)" % (MINYEAR, MAXYEAR))
219.807 - month = property(lambda self: self.__month, doc="month (1-12)")
219.808 - day = property(lambda self: self.__day, doc="day (1-31)")
219.809 -
219.810 - # Standard conversions, __cmp__, __hash__ (and helpers)
219.811 -
219.812 - def timetuple(self):
219.813 - "Return local time tuple compatible with time.localtime()."
219.814 - return _build_struct_time(self.__year, self.__month, self.__day,
219.815 - 0, 0, 0, -1)
219.816 -
219.817 - def toordinal(self):
219.818 - """Return proleptic Gregorian ordinal for the year, month and day.
219.819 -
219.820 - January 1 of year 1 is day 1. Only the year, month and day values
219.821 - contribute to the result.
219.822 - """
219.823 - return _ymd2ord(self.__year, self.__month, self.__day)
219.824 -
219.825 - def replace(self, year=None, month=None, day=None):
219.826 - """Return a new date with new values for the specified fields."""
219.827 - if year is None:
219.828 - year = self.__year
219.829 - if month is None:
219.830 - month = self.__month
219.831 - if day is None:
219.832 - day = self.__day
219.833 - _check_date_fields(year, month, day)
219.834 - return date(year, month, day)
219.835 -
219.836 - # Comparisons.
219.837 -
219.838 - def __eq__(self, other):
219.839 - if isinstance(other, date):
219.840 - return self.__cmp(other) == 0
219.841 - elif hasattr(other, "timetuple"):
219.842 - return NotImplemented
219.843 - else:
219.844 - return False
219.845 -
219.846 - def __ne__(self, other):
219.847 - if isinstance(other, date):
219.848 - return self.__cmp(other) != 0
219.849 - elif hasattr(other, "timetuple"):
219.850 - return NotImplemented
219.851 - else:
219.852 - return True
219.853 -
219.854 - def __le__(self, other):
219.855 - if isinstance(other, date):
219.856 - return self.__cmp(other) <= 0
219.857 - elif hasattr(other, "timetuple"):
219.858 - return NotImplemented
219.859 - else:
219.860 - _cmperror(self, other)
219.861 -
219.862 - def __lt__(self, other):
219.863 - if isinstance(other, date):
219.864 - return self.__cmp(other) < 0
219.865 - elif hasattr(other, "timetuple"):
219.866 - return NotImplemented
219.867 - else:
219.868 - _cmperror(self, other)
219.869 -
219.870 - def __ge__(self, other):
219.871 - if isinstance(other, date):
219.872 - return self.__cmp(other) >= 0
219.873 - elif hasattr(other, "timetuple"):
219.874 - return NotImplemented
219.875 - else:
219.876 - _cmperror(self, other)
219.877 -
219.878 - def __gt__(self, other):
219.879 - if isinstance(other, date):
219.880 - return self.__cmp(other) > 0
219.881 - elif hasattr(other, "timetuple"):
219.882 - return NotImplemented
219.883 - else:
219.884 - _cmperror(self, other)
219.885 -
219.886 - def __cmp(self, other):
219.887 - assert isinstance(other, date)
219.888 - y, m, d = self.__year, self.__month, self.__day
219.889 - y2, m2, d2 = other.__year, other.__month, other.__day
219.890 - return cmp((y, m, d), (y2, m2, d2))
219.891 -
219.892 - def __hash__(self):
219.893 - "Hash."
219.894 - return hash(self.__getstate())
219.895 -
219.896 - # Computations
219.897 -
219.898 - def _checkOverflow(self, year):
219.899 - if not MINYEAR <= year <= MAXYEAR:
219.900 - raise OverflowError("date +/-: result year %d not in %d..%d" %
219.901 - (year, MINYEAR, MAXYEAR))
219.902 -
219.903 - def __add__(self, other):
219.904 - "Add a date to a timedelta."
219.905 - if isinstance(other, timedelta):
219.906 - t = tmxxx(self.__year,
219.907 - self.__month,
219.908 - self.__day + other.days)
219.909 - self._checkOverflow(t.year)
219.910 - result = self.__class__(t.year, t.month, t.day)
219.911 - return result
219.912 - return NotImplemented
219.913 -
219.914 - __radd__ = __add__
219.915 -
219.916 - def __sub__(self, other):
219.917 - """Subtract two dates, or a date and a timedelta."""
219.918 - if isinstance(other, timedelta):
219.919 - return self + timedelta(-other.days)
219.920 - if isinstance(other, date):
219.921 - days1 = self.toordinal()
219.922 - days2 = other.toordinal()
219.923 - return timedelta(days1 - days2)
219.924 - return NotImplemented
219.925 -
219.926 - def weekday(self):
219.927 - "Return day of the week, where Monday == 0 ... Sunday == 6."
219.928 - return (self.toordinal() + 6) % 7
219.929 -
219.930 - # Day-of-the-week and week-of-the-year, according to ISO
219.931 -
219.932 - def isoweekday(self):
219.933 - "Return day of the week, where Monday == 1 ... Sunday == 7."
219.934 - # 1-Jan-0001 is a Monday
219.935 - return self.toordinal() % 7 or 7
219.936 -
219.937 - def isocalendar(self):
219.938 - """Return a 3-tuple containing ISO year, week number, and weekday.
219.939 -
219.940 - The first ISO week of the year is the (Mon-Sun) week
219.941 - containing the year's first Thursday; everything else derives
219.942 - from that.
219.943 -
219.944 - The first week is 1; Monday is 1 ... Sunday is 7.
219.945 -
219.946 - ISO calendar algorithm taken from
219.947 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
219.948 - """
219.949 - year = self.__year
219.950 - week1monday = _isoweek1monday(year)
219.951 - today = _ymd2ord(self.__year, self.__month, self.__day)
219.952 - # Internally, week and day have origin 0
219.953 - week, day = divmod(today - week1monday, 7)
219.954 - if week < 0:
219.955 - year -= 1
219.956 - week1monday = _isoweek1monday(year)
219.957 - week, day = divmod(today - week1monday, 7)
219.958 - elif week >= 52:
219.959 - if today >= _isoweek1monday(year+1):
219.960 - year += 1
219.961 - week = 0
219.962 - return year, week+1, day+1
219.963 -
219.964 - # Pickle support.
219.965 -
219.966 - __safe_for_unpickling__ = True # For Python 2.2
219.967 -
219.968 - def __getstate(self):
219.969 - yhi, ylo = divmod(self.__year, 256)
219.970 - return ("%c%c%c%c" % (yhi, ylo, self.__month, self.__day), )
219.971 -
219.972 - def __setstate(self, t):
219.973 - assert isinstance(t, tuple) and len(t) == 1, `t`
219.974 - string = t[0]
219.975 - assert len(string) == 4
219.976 - yhi, ylo, self.__month, self.__day = map(ord, string)
219.977 - self.__year = yhi * 256 + ylo
219.978 -
219.979 - def __reduce__(self):
219.980 - return (self.__class__, self.__getstate())
219.981 -
219.982 -_date_class = date # so functions w/ args named "date" can get at the class
219.983 -
219.984 -date.min = date(1, 1, 1)
219.985 -date.max = date(9999, 12, 31)
219.986 -date.resolution = timedelta(days=1)
219.987 -
219.988 -class tzinfo(object):
219.989 - """Abstract base class for time zone info classes.
219.990 -
219.991 - Subclasses must override the name(), utcoffset() and dst() methods.
219.992 - """
219.993 -
219.994 - def tzname(self, dt):
219.995 - "datetime -> string name of time zone."
219.996 - raise NotImplementedError("tzinfo subclass must override tzname()")
219.997 -
219.998 - def utcoffset(self, dt):
219.999 - "datetime -> minutes east of UTC (negative for west of UTC)"
219.1000 - raise NotImplementedError("tzinfo subclass must override utcoffset()")
219.1001 -
219.1002 - def dst(self, dt):
219.1003 - """datetime -> DST offset in minutes east of UTC.
219.1004 -
219.1005 - Return 0 if DST not in effect. utcoffset() must include the DST
219.1006 - offset.
219.1007 - """
219.1008 - raise NotImplementedError("tzinfo subclass must override dst()")
219.1009 -
219.1010 - def fromutc(self, dt):
219.1011 - "datetime in UTC -> datetime in local time."
219.1012 -
219.1013 - if not isinstance(dt, datetime):
219.1014 - raise TypeError("fromutc() requires a datetime argument")
219.1015 - if dt.tzinfo is not self:
219.1016 - raise ValueError("dt.tzinfo is not self")
219.1017 -
219.1018 - dtoff = dt.utcoffset()
219.1019 - if dtoff is None:
219.1020 - raise ValueError("fromutc() requires a non-None utcoffset() "
219.1021 - "result")
219.1022 -
219.1023 - # See the long comment block at the end of this file for an
219.1024 - # explanation of this algorithm.
219.1025 - dtdst = dt.dst()
219.1026 - if dtdst is None:
219.1027 - raise ValueError("fromutc() requires a non-None dst() result")
219.1028 - delta = dtoff - dtdst
219.1029 - if delta:
219.1030 - dt += delta
219.1031 - dtdst = dt.dst()
219.1032 - if dtdst is None:
219.1033 - raise ValueError("fromutc(): dt.dst gave inconsistent "
219.1034 - "results; cannot convert")
219.1035 - if dtdst:
219.1036 - return dt + dtdst
219.1037 - else:
219.1038 - return dt
219.1039 -
219.1040 - # Pickle support.
219.1041 -
219.1042 - __safe_for_unpickling__ = True # For Python 2.2
219.1043 -
219.1044 - def __reduce__(self):
219.1045 - getinitargs = getattr(self, "__getinitargs__", None)
219.1046 - if getinitargs:
219.1047 - args = getinitargs()
219.1048 - else:
219.1049 - args = ()
219.1050 - getstate = getattr(self, "__getstate__", None)
219.1051 - if getstate:
219.1052 - state = getstate()
219.1053 - else:
219.1054 - state = getattr(self, "__dict__", None) or None
219.1055 - if state is None:
219.1056 - return (self.__class__, args)
219.1057 - else:
219.1058 - return (self.__class__, args, state)
219.1059 -
219.1060 -_tzinfo_class = tzinfo # so functions w/ args named "tinfo" can get at it
219.1061 -
219.1062 -class time(object):
219.1063 - """Time with time zone.
219.1064 -
219.1065 - Constructors:
219.1066 -
219.1067 - __new__()
219.1068 -
219.1069 - Operators:
219.1070 -
219.1071 - __repr__, __str__
219.1072 - __cmp__, __hash__
219.1073 -
219.1074 - Methods:
219.1075 -
219.1076 - strftime()
219.1077 - isoformat()
219.1078 - utcoffset()
219.1079 - tzname()
219.1080 - dst()
219.1081 -
219.1082 - Properties (readonly):
219.1083 - hour, minute, second, microsecond, tzinfo
219.1084 - """
219.1085 -
219.1086 - def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
219.1087 - """Constructor.
219.1088 -
219.1089 - Arguments:
219.1090 -
219.1091 - hour, minute (required)
219.1092 - second, microsecond (default to zero)
219.1093 - tzinfo (default to None)
219.1094 - """
219.1095 - self = object.__new__(cls)
219.1096 - if isinstance(hour, str):
219.1097 - # Pickle support
219.1098 - self.__setstate((hour, minute or None))
219.1099 - return self
219.1100 - _check_tzinfo_arg(tzinfo)
219.1101 - _check_time_fields(hour, minute, second, microsecond)
219.1102 - self.__hour = hour
219.1103 - self.__minute = minute
219.1104 - self.__second = second
219.1105 - self.__microsecond = microsecond
219.1106 - self._tzinfo = tzinfo
219.1107 - return self
219.1108 -
219.1109 - # Read-only field accessors
219.1110 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
219.1111 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
219.1112 - second = property(lambda self: self.__second, doc="second (0-59)")
219.1113 - microsecond = property(lambda self: self.__microsecond,
219.1114 - doc="microsecond (0-999999)")
219.1115 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
219.1116 -
219.1117 - # Standard conversions, __hash__ (and helpers)
219.1118 -
219.1119 - # Comparisons.
219.1120 -
219.1121 - def __eq__(self, other):
219.1122 - if isinstance(other, time):
219.1123 - return self.__cmp(other) == 0
219.1124 - else:
219.1125 - return False
219.1126 -
219.1127 - def __ne__(self, other):
219.1128 - if isinstance(other, time):
219.1129 - return self.__cmp(other) != 0
219.1130 - else:
219.1131 - return True
219.1132 -
219.1133 - def __le__(self, other):
219.1134 - if isinstance(other, time):
219.1135 - return self.__cmp(other) <= 0
219.1136 - else:
219.1137 - _cmperror(self, other)
219.1138 -
219.1139 - def __lt__(self, other):
219.1140 - if isinstance(other, time):
219.1141 - return self.__cmp(other) < 0
219.1142 - else:
219.1143 - _cmperror(self, other)
219.1144 -
219.1145 - def __ge__(self, other):
219.1146 - if isinstance(other, time):
219.1147 - return self.__cmp(other) >= 0
219.1148 - else:
219.1149 - _cmperror(self, other)
219.1150 -
219.1151 - def __gt__(self, other):
219.1152 - if isinstance(other, time):
219.1153 - return self.__cmp(other) > 0
219.1154 - else:
219.1155 - _cmperror(self, other)
219.1156 -
219.1157 - def __cmp(self, other):
219.1158 - assert isinstance(other, time)
219.1159 - mytz = self._tzinfo
219.1160 - ottz = other._tzinfo
219.1161 - myoff = otoff = None
219.1162 -
219.1163 - if mytz is ottz:
219.1164 - base_compare = True
219.1165 - else:
219.1166 - myoff = self._utcoffset()
219.1167 - otoff = other._utcoffset()
219.1168 - base_compare = myoff == otoff
219.1169 -
219.1170 - if base_compare:
219.1171 - return cmp((self.__hour, self.__minute, self.__second,
219.1172 - self.__microsecond),
219.1173 - (other.__hour, other.__minute, other.__second,
219.1174 - other.__microsecond))
219.1175 - if myoff is None or otoff is None:
219.1176 - # XXX Buggy in 2.2.2.
219.1177 - raise TypeError("cannot compare naive and aware times")
219.1178 - myhhmm = self.__hour * 60 + self.__minute - myoff
219.1179 - othhmm = other.__hour * 60 + other.__minute - otoff
219.1180 - return cmp((myhhmm, self.__second, self.__microsecond),
219.1181 - (othhmm, other.__second, other.__microsecond))
219.1182 -
219.1183 - def __hash__(self):
219.1184 - """Hash."""
219.1185 - tzoff = self._utcoffset()
219.1186 - if not tzoff: # zero or None
219.1187 - return hash(self.__getstate()[0])
219.1188 - h, m = divmod(self.hour * 60 + self.minute - tzoff, 60)
219.1189 - if 0 <= h < 24:
219.1190 - return hash(time(h, m, self.second, self.microsecond))
219.1191 - return hash((h, m, self.second, self.microsecond))
219.1192 -
219.1193 - # Conversion to string
219.1194 -
219.1195 - def _tzstr(self, sep=":"):
219.1196 - """Return formatted timezone offset (+xx:xx) or None."""
219.1197 - off = self._utcoffset()
219.1198 - if off is not None:
219.1199 - if off < 0:
219.1200 - sign = "-"
219.1201 - off = -off
219.1202 - else:
219.1203 - sign = "+"
219.1204 - hh, mm = divmod(off, 60)
219.1205 - assert 0 <= hh < 24
219.1206 - off = "%s%02d%s%02d" % (sign, hh, sep, mm)
219.1207 - return off
219.1208 -
219.1209 - def __repr__(self):
219.1210 - """Convert to formal string, for repr()."""
219.1211 - if self.__microsecond != 0:
219.1212 - s = ", %d, %d" % (self.__second, self.__microsecond)
219.1213 - elif self.__second != 0:
219.1214 - s = ", %d" % self.__second
219.1215 - else:
219.1216 - s = ""
219.1217 - s= "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__,
219.1218 - self.__hour, self.__minute, s)
219.1219 - if self._tzinfo is not None:
219.1220 - assert s[-1:] == ")"
219.1221 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
219.1222 - return s
219.1223 -
219.1224 - def isoformat(self):
219.1225 - """Return the time formatted according to ISO.
219.1226 -
219.1227 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
219.1228 - self.microsecond == 0.
219.1229 - """
219.1230 - s = _format_time(self.__hour, self.__minute, self.__second,
219.1231 - self.__microsecond)
219.1232 - tz = self._tzstr()
219.1233 - if tz:
219.1234 - s += tz
219.1235 - return s
219.1236 -
219.1237 - __str__ = isoformat
219.1238 -
219.1239 - def strftime(self, fmt):
219.1240 - """Format using strftime(). The date part of the timestamp passed
219.1241 - to underlying strftime should not be used.
219.1242 - """
219.1243 - # The year must be >= 1900 else Python's strftime implementation
219.1244 - # can raise a bogus exception.
219.1245 - timetuple = (1900, 1, 1,
219.1246 - self.__hour, self.__minute, self.__second,
219.1247 - 0, 1, -1)
219.1248 - return _wrap_strftime(self, fmt, timetuple)
219.1249 -
219.1250 - # Timezone functions
219.1251 -
219.1252 - def utcoffset(self):
219.1253 - """Return the timezone offset in minutes east of UTC (negative west of
219.1254 - UTC)."""
219.1255 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
219.1256 - offset = _check_utc_offset("utcoffset", offset)
219.1257 - if offset is not None:
219.1258 - offset = timedelta(minutes=offset)
219.1259 - return offset
219.1260 -
219.1261 - # Return an integer (or None) instead of a timedelta (or None).
219.1262 - def _utcoffset(self):
219.1263 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
219.1264 - offset = _check_utc_offset("utcoffset", offset)
219.1265 - return offset
219.1266 -
219.1267 - def tzname(self):
219.1268 - """Return the timezone name.
219.1269 -
219.1270 - Note that the name is 100% informational -- there's no requirement that
219.1271 - it mean anything in particular. For example, "GMT", "UTC", "-500",
219.1272 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
219.1273 - """
219.1274 - name = _call_tzinfo_method(self._tzinfo, "tzname", None)
219.1275 - _check_tzname(name)
219.1276 - return name
219.1277 -
219.1278 - def dst(self):
219.1279 - """Return 0 if DST is not in effect, or the DST offset (in minutes
219.1280 - eastward) if DST is in effect.
219.1281 -
219.1282 - This is purely informational; the DST offset has already been added to
219.1283 - the UTC offset returned by utcoffset() if applicable, so there's no
219.1284 - need to consult dst() unless you're interested in displaying the DST
219.1285 - info.
219.1286 - """
219.1287 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
219.1288 - offset = _check_utc_offset("dst", offset)
219.1289 - if offset is not None:
219.1290 - offset = timedelta(minutes=offset)
219.1291 - return offset
219.1292 -
219.1293 - def replace(self, hour=None, minute=None, second=None, microsecond=None,
219.1294 - tzinfo=True):
219.1295 - """Return a new time with new values for the specified fields."""
219.1296 - if hour is None:
219.1297 - hour = self.hour
219.1298 - if minute is None:
219.1299 - minute = self.minute
219.1300 - if second is None:
219.1301 - second = self.second
219.1302 - if microsecond is None:
219.1303 - microsecond = self.microsecond
219.1304 - if tzinfo is True:
219.1305 - tzinfo = self.tzinfo
219.1306 - _check_time_fields(hour, minute, second, microsecond)
219.1307 - _check_tzinfo_arg(tzinfo)
219.1308 - return time(hour, minute, second, microsecond, tzinfo)
219.1309 -
219.1310 - # Return an integer (or None) instead of a timedelta (or None).
219.1311 - def _dst(self):
219.1312 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
219.1313 - offset = _check_utc_offset("dst", offset)
219.1314 - return offset
219.1315 -
219.1316 - def __nonzero__(self):
219.1317 - if self.second or self.microsecond:
219.1318 - return 1
219.1319 - offset = self._utcoffset() or 0
219.1320 - return self.hour * 60 + self.minute - offset != 0
219.1321 -
219.1322 - # Pickle support.
219.1323 -
219.1324 - __safe_for_unpickling__ = True # For Python 2.2
219.1325 -
219.1326 - def __getstate(self):
219.1327 - us2, us3 = divmod(self.__microsecond, 256)
219.1328 - us1, us2 = divmod(us2, 256)
219.1329 - basestate = ("%c" * 6) % (self.__hour, self.__minute, self.__second,
219.1330 - us1, us2, us3)
219.1331 - if self._tzinfo is None:
219.1332 - return (basestate,)
219.1333 - else:
219.1334 - return (basestate, self._tzinfo)
219.1335 -
219.1336 - def __setstate(self, state):
219.1337 - assert isinstance(state, tuple)
219.1338 - assert 1 <= len(state) <= 2
219.1339 - string = state[0]
219.1340 - assert len(string) == 6
219.1341 - self.__hour, self.__minute, self.__second, us1, us2, us3 = \
219.1342 - map(ord, string)
219.1343 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
219.1344 - if len(state) == 1:
219.1345 - self._tzinfo = None
219.1346 - else:
219.1347 - self._tzinfo = state[1]
219.1348 -
219.1349 - def __reduce__(self):
219.1350 - return (self.__class__, self.__getstate())
219.1351 -
219.1352 -_time_class = time # so functions w/ args named "time" can get at the class
219.1353 -
219.1354 -time.min = time(0, 0, 0)
219.1355 -time.max = time(23, 59, 59, 999999)
219.1356 -time.resolution = timedelta(microseconds=1)
219.1357 -
219.1358 -class datetime(date):
219.1359 -
219.1360 - # XXX needs docstrings
219.1361 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
219.1362 -
219.1363 - def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
219.1364 - microsecond=0, tzinfo=None):
219.1365 - if isinstance(year, str):
219.1366 - # Pickle support
219.1367 - self = date.__new__(cls, year[:4])
219.1368 - self.__setstate((year, month))
219.1369 - return self
219.1370 - _check_tzinfo_arg(tzinfo)
219.1371 - _check_time_fields(hour, minute, second, microsecond)
219.1372 - self = date.__new__(cls, year, month, day)
219.1373 - # XXX This duplicates __year, __month, __day for convenience :-(
219.1374 - self.__year = year
219.1375 - self.__month = month
219.1376 - self.__day = day
219.1377 - self.__hour = hour
219.1378 - self.__minute = minute
219.1379 - self.__second = second
219.1380 - self.__microsecond = microsecond
219.1381 - self._tzinfo = tzinfo
219.1382 - return self
219.1383 -
219.1384 - # Read-only field accessors
219.1385 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
219.1386 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
219.1387 - second = property(lambda self: self.__second, doc="second (0-59)")
219.1388 - microsecond = property(lambda self: self.__microsecond,
219.1389 - doc="microsecond (0-999999)")
219.1390 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
219.1391 -
219.1392 - def fromtimestamp(cls, t, tz=None):
219.1393 - """Construct a datetime from a POSIX timestamp (like time.time()).
219.1394 -
219.1395 - A timezone info object may be passed in as well.
219.1396 - """
219.1397 -
219.1398 - _check_tzinfo_arg(tz)
219.1399 - if tz is None:
219.1400 - converter = _time.localtime
219.1401 - else:
219.1402 - converter = _time.gmtime
219.1403 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
219.1404 - us = int((t % 1.0) * 1000000)
219.1405 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
219.1406 - result = cls(y, m, d, hh, mm, ss, us, tz)
219.1407 - if tz is not None:
219.1408 - result = tz.fromutc(result)
219.1409 - return result
219.1410 - fromtimestamp = classmethod(fromtimestamp)
219.1411 -
219.1412 - def utcfromtimestamp(cls, t):
219.1413 - "Construct a UTC datetime from a POSIX timestamp (like time.time())."
219.1414 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
219.1415 - us = int((t % 1.0) * 1000000)
219.1416 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
219.1417 - return cls(y, m, d, hh, mm, ss, us)
219.1418 - utcfromtimestamp = classmethod(utcfromtimestamp)
219.1419 -
219.1420 - # XXX This is supposed to do better than we *can* do by using time.time(),
219.1421 - # XXX if the platform supports a more accurate way. The C implementation
219.1422 - # XXX uses gettimeofday on platforms that have it, but that isn't
219.1423 - # XXX available from Python. So now() may return different results
219.1424 - # XXX across the implementations.
219.1425 - def now(cls, tz=None):
219.1426 - "Construct a datetime from time.time() and optional time zone info."
219.1427 - t = _time.time()
219.1428 - return cls.fromtimestamp(t, tz)
219.1429 - now = classmethod(now)
219.1430 -
219.1431 - def utcnow(cls):
219.1432 - "Construct a UTC datetime from time.time()."
219.1433 - t = _time.time()
219.1434 - return cls.utcfromtimestamp(t)
219.1435 - utcnow = classmethod(utcnow)
219.1436 -
219.1437 - def combine(cls, date, time):
219.1438 - "Construct a datetime from a given date and a given time."
219.1439 - if not isinstance(date, _date_class):
219.1440 - raise TypeError("date argument must be a date instance")
219.1441 - if not isinstance(time, _time_class):
219.1442 - raise TypeError("time argument must be a time instance")
219.1443 - return cls(date.year, date.month, date.day,
219.1444 - time.hour, time.minute, time.second, time.microsecond,
219.1445 - time.tzinfo)
219.1446 - combine = classmethod(combine)
219.1447 -
219.1448 - def timetuple(self):
219.1449 - "Return local time tuple compatible with time.localtime()."
219.1450 - dst = self._dst()
219.1451 - if dst is None:
219.1452 - dst = -1
219.1453 - elif dst:
219.1454 - dst = 1
219.1455 - return _build_struct_time(self.year, self.month, self.day,
219.1456 - self.hour, self.minute, self.second,
219.1457 - dst)
219.1458 -
219.1459 - def utctimetuple(self):
219.1460 - "Return UTC time tuple compatible with time.gmtime()."
219.1461 - y, m, d = self.year, self.month, self.day
219.1462 - hh, mm, ss = self.hour, self.minute, self.second
219.1463 - offset = self._utcoffset()
219.1464 - if offset: # neither None nor 0
219.1465 - tm = tmxxx(y, m, d, hh, mm - offset)
219.1466 - y, m, d = tm.year, tm.month, tm.day
219.1467 - hh, mm = tm.hour, tm.minute
219.1468 - return _build_struct_time(y, m, d, hh, mm, ss, 0)
219.1469 -
219.1470 - def date(self):
219.1471 - "Return the date part."
219.1472 - return date(self.__year, self.__month, self.__day)
219.1473 -
219.1474 - def time(self):
219.1475 - "Return the time part, with tzinfo None."
219.1476 - return time(self.hour, self.minute, self.second, self.microsecond)
219.1477 -
219.1478 - def timetz(self):
219.1479 - "Return the time part, with same tzinfo."
219.1480 - return time(self.hour, self.minute, self.second, self.microsecond,
219.1481 - self._tzinfo)
219.1482 -
219.1483 - def replace(self, year=None, month=None, day=None, hour=None,
219.1484 - minute=None, second=None, microsecond=None, tzinfo=True):
219.1485 - """Return a new datetime with new values for the specified fields."""
219.1486 - if year is None:
219.1487 - year = self.year
219.1488 - if month is None:
219.1489 - month = self.month
219.1490 - if day is None:
219.1491 - day = self.day
219.1492 - if hour is None:
219.1493 - hour = self.hour
219.1494 - if minute is None:
219.1495 - minute = self.minute
219.1496 - if second is None:
219.1497 - second = self.second
219.1498 - if microsecond is None:
219.1499 - microsecond = self.microsecond
219.1500 - if tzinfo is True:
219.1501 - tzinfo = self.tzinfo
219.1502 - _check_date_fields(year, month, day)
219.1503 - _check_time_fields(hour, minute, second, microsecond)
219.1504 - _check_tzinfo_arg(tzinfo)
219.1505 - return datetime(year, month, day, hour, minute, second,
219.1506 - microsecond, tzinfo)
219.1507 -
219.1508 - def astimezone(self, tz):
219.1509 - if not isinstance(tz, tzinfo):
219.1510 - raise TypeError("tz argument must be an instance of tzinfo")
219.1511 -
219.1512 - mytz = self.tzinfo
219.1513 - if mytz is None:
219.1514 - raise ValueError("astimezone() requires an aware datetime")
219.1515 -
219.1516 - if tz is mytz:
219.1517 - return self
219.1518 -
219.1519 - # Convert self to UTC, and attach the new time zone object.
219.1520 - myoffset = self.utcoffset()
219.1521 - if myoffset is None:
219.1522 - raise ValuError("astimezone() requires an aware datetime")
219.1523 - utc = (self - myoffset).replace(tzinfo=tz)
219.1524 -
219.1525 - # Convert from UTC to tz's local time.
219.1526 - return tz.fromutc(utc)
219.1527 -
219.1528 - # Ways to produce a string.
219.1529 -
219.1530 - def ctime(self):
219.1531 - "Format a la ctime()."
219.1532 - t = tmxxx(self.__year, self.__month, self.__day, self.__hour,
219.1533 - self.__minute, self.__second)
219.1534 - return t.ctime()
219.1535 -
219.1536 - def isoformat(self, sep='T'):
219.1537 - """Return the time formatted according to ISO.
219.1538 -
219.1539 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
219.1540 - self.microsecond == 0.
219.1541 -
219.1542 - If self.tzinfo is not None, the UTC offset is also attached, giving
219.1543 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
219.1544 -
219.1545 - Optional argument sep specifies the separator between date and
219.1546 - time, default 'T'.
219.1547 - """
219.1548 - s = ("%04d-%02d-%02d%c" % (self.__year, self.__month, self.__day,
219.1549 - sep) +
219.1550 - _format_time(self.__hour, self.__minute, self.__second,
219.1551 - self.__microsecond))
219.1552 - off = self._utcoffset()
219.1553 - if off is not None:
219.1554 - if off < 0:
219.1555 - sign = "-"
219.1556 - off = -off
219.1557 - else:
219.1558 - sign = "+"
219.1559 - hh, mm = divmod(off, 60)
219.1560 - s += "%s%02d:%02d" % (sign, hh, mm)
219.1561 - return s
219.1562 -
219.1563 - def __repr__(self):
219.1564 - "Convert to formal string, for repr()."
219.1565 - L = [self.__year, self.__month, self.__day, # These are never zero
219.1566 - self.__hour, self.__minute, self.__second, self.__microsecond]
219.1567 - if L[-1] == 0:
219.1568 - del L[-1]
219.1569 - if L[-1] == 0:
219.1570 - del L[-1]
219.1571 - s = ", ".join(map(str, L))
219.1572 - s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s)
219.1573 - if self._tzinfo is not None:
219.1574 - assert s[-1:] == ")"
219.1575 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
219.1576 - return s
219.1577 -
219.1578 - def __str__(self):
219.1579 - "Convert to string, for str()."
219.1580 - return self.isoformat(sep=' ')
219.1581 -
219.1582 - def utcoffset(self):
219.1583 - """Return the timezone offset in minutes east of UTC (negative west of
219.1584 - UTC)."""
219.1585 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
219.1586 - offset = _check_utc_offset("utcoffset", offset)
219.1587 - if offset is not None:
219.1588 - offset = timedelta(minutes=offset)
219.1589 - return offset
219.1590 -
219.1591 - # Return an integer (or None) instead of a timedelta (or None).
219.1592 - def _utcoffset(self):
219.1593 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
219.1594 - offset = _check_utc_offset("utcoffset", offset)
219.1595 - return offset
219.1596 -
219.1597 - def tzname(self):
219.1598 - """Return the timezone name.
219.1599 -
219.1600 - Note that the name is 100% informational -- there's no requirement that
219.1601 - it mean anything in particular. For example, "GMT", "UTC", "-500",
219.1602 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
219.1603 - """
219.1604 - name = _call_tzinfo_method(self._tzinfo, "tzname", self)
219.1605 - _check_tzname(name)
219.1606 - return name
219.1607 -
219.1608 - def dst(self):
219.1609 - """Return 0 if DST is not in effect, or the DST offset (in minutes
219.1610 - eastward) if DST is in effect.
219.1611 -
219.1612 - This is purely informational; the DST offset has already been added to
219.1613 - the UTC offset returned by utcoffset() if applicable, so there's no
219.1614 - need to consult dst() unless you're interested in displaying the DST
219.1615 - info.
219.1616 - """
219.1617 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
219.1618 - offset = _check_utc_offset("dst", offset)
219.1619 - if offset is not None:
219.1620 - offset = timedelta(minutes=offset)
219.1621 - return offset
219.1622 -
219.1623 - # Return an integer (or None) instead of a timedelta (or None).1573
219.1624 - def _dst(self):
219.1625 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
219.1626 - offset = _check_utc_offset("dst", offset)
219.1627 - return offset
219.1628 -
219.1629 - # Comparisons.
219.1630 -
219.1631 - def __eq__(self, other):
219.1632 - if isinstance(other, datetime):
219.1633 - return self.__cmp(other) == 0
219.1634 - elif hasattr(other, "timetuple"):
219.1635 - return NotImplemented
219.1636 - else:
219.1637 - return False
219.1638 -
219.1639 - def __ne__(self, other):
219.1640 - if isinstance(other, datetime):
219.1641 - return self.__cmp(other) != 0
219.1642 - elif hasattr(other, "timetuple"):
219.1643 - return NotImplemented
219.1644 - else:
219.1645 - return True
219.1646 -
219.1647 - def __le__(self, other):
219.1648 - if isinstance(other, datetime):
219.1649 - return self.__cmp(other) <= 0
219.1650 - elif hasattr(other, "timetuple"):
219.1651 - return NotImplemented
219.1652 - else:
219.1653 - _cmperror(self, other)
219.1654 -
219.1655 - def __lt__(self, other):
219.1656 - if isinstance(other, datetime):
219.1657 - return self.__cmp(other) < 0
219.1658 - elif hasattr(other, "timetuple"):
219.1659 - return NotImplemented
219.1660 - else:
219.1661 - _cmperror(self, other)
219.1662 -
219.1663 - def __ge__(self, other):
219.1664 - if isinstance(other, datetime):
219.1665 - return self.__cmp(other) >= 0
219.1666 - elif hasattr(other, "timetuple"):
219.1667 - return NotImplemented
219.1668 - else:
219.1669 - _cmperror(self, other)
219.1670 -
219.1671 - def __gt__(self, other):
219.1672 - if isinstance(other, datetime):
219.1673 - return self.__cmp(other) > 0
219.1674 - elif hasattr(other, "timetuple"):
219.1675 - return NotImplemented
219.1676 - else:
219.1677 - _cmperror(self, other)
219.1678 -
219.1679 - def __cmp(self, other):
219.1680 - assert isinstance(other, datetime)
219.1681 - mytz = self._tzinfo
219.1682 - ottz = other._tzinfo
219.1683 - myoff = otoff = None
219.1684 -
219.1685 - if mytz is ottz:
219.1686 - base_compare = True
219.1687 - else:
219.1688 - if mytz is not None:
219.1689 - myoff = self._utcoffset()
219.1690 - if ottz is not None:
219.1691 - otoff = other._utcoffset()
219.1692 - base_compare = myoff == otoff
219.1693 -
219.1694 - if base_compare:
219.1695 - return cmp((self.__year, self.__month, self.__day,
219.1696 - self.__hour, self.__minute, self.__second,
219.1697 - self.__microsecond),
219.1698 - (other.__year, other.__month, other.__day,
219.1699 - other.__hour, other.__minute, other.__second,
219.1700 - other.__microsecond))
219.1701 - if myoff is None or otoff is None:
219.1702 - # XXX Buggy in 2.2.2.
219.1703 - raise TypeError("cannot compare naive and aware datetimes")
219.1704 - # XXX What follows could be done more efficiently...
219.1705 - diff = self - other # this will take offsets into account
219.1706 - if diff.days < 0:
219.1707 - return -1
219.1708 - return diff and 1 or 0
219.1709 -
219.1710 - def __add__(self, other):
219.1711 - "Add a datetime and a timedelta."
219.1712 - if not isinstance(other, timedelta):
219.1713 - return NotImplemented
219.1714 - t = tmxxx(self.__year,
219.1715 - self.__month,
219.1716 - self.__day + other.days,
219.1717 - self.__hour,
219.1718 - self.__minute,
219.1719 - self.__second + other.seconds,
219.1720 - self.__microsecond + other.microseconds)
219.1721 - self._checkOverflow(t.year)
219.1722 - result = self.__class__(t.year, t.month, t.day,
219.1723 - t.hour, t.minute, t.second,
219.1724 - t.microsecond, tzinfo=self._tzinfo)
219.1725 - return result
219.1726 -
219.1727 - __radd__ = __add__
219.1728 -
219.1729 - def __sub__(self, other):
219.1730 - "Subtract two datetimes, or a datetime and a timedelta."
219.1731 - if not isinstance(other, datetime):
219.1732 - if isinstance(other, timedelta):
219.1733 - return self + -other
219.1734 - return NotImplemented
219.1735 -
219.1736 - days1 = self.toordinal()
219.1737 - days2 = other.toordinal()
219.1738 - secs1 = self.__second + self.__minute * 60 + self.__hour * 3600
219.1739 - secs2 = other.__second + other.__minute * 60 + other.__hour * 3600
219.1740 - base = timedelta(days1 - days2,
219.1741 - secs1 - secs2,
219.1742 - self.__microsecond - other.__microsecond)
219.1743 - if self._tzinfo is other._tzinfo:
219.1744 - return base
219.1745 - myoff = self._utcoffset()
219.1746 - otoff = other._utcoffset()
219.1747 - if myoff == otoff:
219.1748 - return base
219.1749 - if myoff is None or otoff is None:
219.1750 - raise TypeError, "cannot mix naive and timezone-aware time"
219.1751 - return base + timedelta(minutes = otoff-myoff)
219.1752 -
219.1753 - def __hash__(self):
219.1754 - tzoff = self._utcoffset()
219.1755 - if tzoff is None:
219.1756 - return hash(self.__getstate()[0])
219.1757 - days = _ymd2ord(self.year, self.month, self.day)
219.1758 - seconds = self.hour * 3600 + (self.minute - tzoff) * 60 + self.second
219.1759 - return hash(timedelta(days, seconds, self.microsecond))
219.1760 -
219.1761 - # Pickle support.
219.1762 -
219.1763 - __safe_for_unpickling__ = True # For Python 2.2
219.1764 -
219.1765 - def __getstate(self):
219.1766 - yhi, ylo = divmod(self.__year, 256)
219.1767 - us2, us3 = divmod(self.__microsecond, 256)
219.1768 - us1, us2 = divmod(us2, 256)
219.1769 - basestate = ("%c" * 10) % (yhi, ylo, self.__month, self.__day,
219.1770 - self.__hour, self.__minute, self.__second,
219.1771 - us1, us2, us3)
219.1772 - if self._tzinfo is None:
219.1773 - return (basestate,)
219.1774 - else:
219.1775 - return (basestate, self._tzinfo)
219.1776 -
219.1777 - def __setstate(self, state):
219.1778 - assert isinstance(state, tuple)
219.1779 - assert 1 <= len(state) <= 2
219.1780 - string = state[0]
219.1781 - assert len(string) == 10
219.1782 - (yhi, ylo, self.__month, self.__day, self.__hour,
219.1783 - self.__minute, self.__second, us1, us2, us3) = map(ord, string)
219.1784 - self.__year = yhi * 256 + ylo
219.1785 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
219.1786 - if len(state) == 1:
219.1787 - self._tzinfo = None
219.1788 - else:
219.1789 - self._tzinfo = state[1]
219.1790 -
219.1791 - def __reduce__(self):
219.1792 - return (self.__class__, self.__getstate())
219.1793 -
219.1794 -
219.1795 -datetime.min = datetime(1, 1, 1)
219.1796 -datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
219.1797 -datetime.resolution = timedelta(microseconds=1)
219.1798 -
219.1799 -
219.1800 -def _isoweek1monday(year):
219.1801 - # Helper to calculate the day number of the Monday starting week 1
219.1802 - # XXX This could be done more efficiently
219.1803 - THURSDAY = 3
219.1804 - firstday = _ymd2ord(year, 1, 1)
219.1805 - firstweekday = (firstday + 6) % 7 # See weekday() above
219.1806 - week1monday = firstday - firstweekday
219.1807 - if firstweekday > THURSDAY:
219.1808 - week1monday += 7
219.1809 - return week1monday
219.1810 -
219.1811 -"""
219.1812 -Some time zone algebra. For a datetime x, let
219.1813 - x.n = x stripped of its timezone -- its naive time.
219.1814 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
219.1815 - return None
219.1816 - x.d = x.dst(), and assuming that doesn't raise an exception or
219.1817 - return None
219.1818 - x.s = x's standard offset, x.o - x.d
219.1819 -
219.1820 -Now some derived rules, where k is a duration (timedelta).
219.1821 -
219.1822 -1. x.o = x.s + x.d
219.1823 - This follows from the definition of x.s.
219.1824 -
219.1825 -2. If x and y have the same tzinfo member, x.s = y.s.
219.1826 - This is actually a requirement, an assumption we need to make about
219.1827 - sane tzinfo classes.
219.1828 -
219.1829 -3. The naive UTC time corresponding to x is x.n - x.o.
219.1830 - This is again a requirement for a sane tzinfo class.
219.1831 -
219.1832 -4. (x+k).s = x.s
219.1833 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
219.1834 -
219.1835 -5. (x+k).n = x.n + k
219.1836 - Again follows from how arithmetic is defined.
219.1837 -
219.1838 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
219.1839 -(meaning that the various tzinfo methods exist, and don't blow up or return
219.1840 -None when called).
219.1841 -
219.1842 -The function wants to return a datetime y with timezone tz, equivalent to x.
219.1843 -x is already in UTC.
219.1844 -
219.1845 -By #3, we want
219.1846 -
219.1847 - y.n - y.o = x.n [1]
219.1848 -
219.1849 -The algorithm starts by attaching tz to x.n, and calling that y. So
219.1850 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
219.1851 -becomes true; in effect, we want to solve [2] for k:
219.1852 -
219.1853 - (y+k).n - (y+k).o = x.n [2]
219.1854 -
219.1855 -By #1, this is the same as
219.1856 -
219.1857 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
219.1858 -
219.1859 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
219.1860 -Substituting that into [3],
219.1861 -
219.1862 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
219.1863 - k - (y+k).s - (y+k).d = 0; rearranging,
219.1864 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
219.1865 - k = y.s - (y+k).d
219.1866 -
219.1867 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
219.1868 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
219.1869 -very large, since all offset-returning methods return a duration of magnitude
219.1870 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
219.1871 -be 0, so ignoring it has no consequence then.
219.1872 -
219.1873 -In any case, the new value is
219.1874 -
219.1875 - z = y + y.s [4]
219.1876 -
219.1877 -It's helpful to step back at look at [4] from a higher level: it's simply
219.1878 -mapping from UTC to tz's standard time.
219.1879 -
219.1880 -At this point, if
219.1881 -
219.1882 - z.n - z.o = x.n [5]
219.1883 -
219.1884 -we have an equivalent time, and are almost done. The insecurity here is
219.1885 -at the start of daylight time. Picture US Eastern for concreteness. The wall
219.1886 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
219.1887 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
219.1888 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
219.1889 -on the day DST starts. We want to return the 1:MM EST spelling because that's
219.1890 -the only spelling that makes sense on the local wall clock.
219.1891 -
219.1892 -In fact, if [5] holds at this point, we do have the standard-time spelling,
219.1893 -but that takes a bit of proof. We first prove a stronger result. What's the
219.1894 -difference between the LHS and RHS of [5]? Let
219.1895 -
219.1896 - diff = x.n - (z.n - z.o) [6]
219.1897 -
219.1898 -Now
219.1899 - z.n = by [4]
219.1900 - (y + y.s).n = by #5
219.1901 - y.n + y.s = since y.n = x.n
219.1902 - x.n + y.s = since z and y are have the same tzinfo member,
219.1903 - y.s = z.s by #2
219.1904 - x.n + z.s
219.1905 -
219.1906 -Plugging that back into [6] gives
219.1907 -
219.1908 - diff =
219.1909 - x.n - ((x.n + z.s) - z.o) = expanding
219.1910 - x.n - x.n - z.s + z.o = cancelling
219.1911 - - z.s + z.o = by #2
219.1912 - z.d
219.1913 -
219.1914 -So diff = z.d.
219.1915 -
219.1916 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
219.1917 -spelling we wanted in the endcase described above. We're done. Contrarily,
219.1918 -if z.d = 0, then we have a UTC equivalent, and are also done.
219.1919 -
219.1920 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
219.1921 -add to z (in effect, z is in tz's standard time, and we need to shift the
219.1922 -local clock into tz's daylight time).
219.1923 -
219.1924 -Let
219.1925 -
219.1926 - z' = z + z.d = z + diff [7]
219.1927 -
219.1928 -and we can again ask whether
219.1929 -
219.1930 - z'.n - z'.o = x.n [8]
219.1931 -
219.1932 -If so, we're done. If not, the tzinfo class is insane, according to the
219.1933 -assumptions we've made. This also requires a bit of proof. As before, let's
219.1934 -compute the difference between the LHS and RHS of [8] (and skipping some of
219.1935 -the justifications for the kinds of substitutions we've done several times
219.1936 -already):
219.1937 -
219.1938 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
219.1939 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
219.1940 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
219.1941 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
219.1942 - - z.n + z.n - z.o + z'.o = cancel z.n
219.1943 - - z.o + z'.o = #1 twice
219.1944 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
219.1945 - z'.d - z.d
219.1946 -
219.1947 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
219.1948 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
219.1949 -return z', not bothering to compute z'.d.
219.1950 -
219.1951 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
219.1952 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
219.1953 -would have to change the result dst() returns: we start in DST, and moving
219.1954 -a little further into it takes us out of DST.
219.1955 -
219.1956 -There isn't a sane case where this can happen. The closest it gets is at
219.1957 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
219.1958 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
219.1959 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
219.1960 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
219.1961 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
219.1962 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
219.1963 -standard time. Since that's what the local clock *does*, we want to map both
219.1964 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
219.1965 -in local time, but so it goes -- it's the way the local clock works.
219.1966 -
219.1967 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
219.1968 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
219.1969 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
219.1970 -(correctly) concludes that z' is not UTC-equivalent to x.
219.1971 -
219.1972 -Because we know z.d said z was in daylight time (else [5] would have held and
219.1973 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
219.1974 -and we we have stopped then), and there are only 2 possible values dst() can
219.1975 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
219.1976 -but the reasoning doesn't depend on the example -- it depends on there being
219.1977 -two possible dst() outcomes, one zero and the other non-zero). Therefore
219.1978 -z' must be in standard time, and is the spelling we want in this case.
219.1979 -
219.1980 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
219.1981 -concerned (because it takes z' as being in standard time rather than the
219.1982 -daylight time we intend here), but returning it gives the real-life "local
219.1983 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
219.1984 -tz.
219.1985 -
219.1986 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
219.1987 -the 1:MM standard time spelling we want.
219.1988 -
219.1989 -So how can this break? One of the assumptions must be violated. Two
219.1990 -possibilities:
219.1991 -
219.1992 -1) [2] effectively says that y.s is invariant across all y belong to a given
219.1993 - time zone. This isn't true if, for political reasons or continental drift,
219.1994 - a region decides to change its base offset from UTC.
219.1995 -
219.1996 -2) There may be versions of "double daylight" time where the tail end of
219.1997 - the analysis gives up a step too early. I haven't thought about that
219.1998 - enough to say.
219.1999 -
219.2000 -In any case, it's clear that the default fromutc() is strong enough to handle
219.2001 -"almost all" time zones: so long as the standard offset is invariant, it
219.2002 -doesn't matter if daylight time transition points change from year to year, or
219.2003 -if daylight time is skipped in some years; it doesn't matter how large or
219.2004 -small dst() may get within its bounds; and it doesn't even matter if some
219.2005 -perverse time zone returns a negative dst()). So a breaking case must be
219.2006 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
219.2007 -"""
219.2008 -
219.2009 -def _test():
219.2010 - import test_datetime
219.2011 - test_datetime.test_main()
219.2012 -
219.2013 -if __name__ == "__main__":
219.2014 - _test()
220.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testFix4.fixed Sun Jan 04 13:11:53 2015 -0600
220.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
220.3 @@ -1,2012 +0,0 @@
220.4 -"""Concrete date/time and related types -- prototype implemented in Python.
220.5 -
220.6 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
220.7 -
220.8 -See also http://dir.yahoo.com/Reference/calendars/
220.9 -
220.10 -For a primer on DST, including many current DST rules, see
220.11 -http://webexhibits.org/daylightsaving/
220.12 -
220.13 -For more about DST than you ever wanted to know, see
220.14 -ftp://elsie.nci.nih.gov/pub/
220.15 -
220.16 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
220.17 -
220.18 -"""
220.19 -
220.20 -import time as _time
220.21 -import math as _math
220.22 -
220.23 -MINYEAR = 1
220.24 -MAXYEAR = 9999
220.25 -
220.26 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
220.27 -# also assumes the current Gregorian calendar indefinitely extended in
220.28 -# both directions. Difference: Dates.py calls January 1 of year 0 day
220.29 -# number 1. The code here calls January 1 of year 1 day number 1. This is
220.30 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
220.31 -# and Reingold's "Calendrical Calculations", where it's the base calendar
220.32 -# for all computations. See the book for algorithms for converting between
220.33 -# proleptic Gregorian ordinals and many other calendar systems.
220.34 -
220.35 -_DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
220.36 -
220.37 -_DAYS_BEFORE_MONTH = [None]
220.38 -dbm = 0
220.39 -for dim in _DAYS_IN_MONTH[1:]:
220.40 - _DAYS_BEFORE_MONTH.append(dbm)
220.41 - dbm += dim
220.42 -del dbm, dim
220.43 -
220.44 -def _is_leap(year):
220.45 - "year -> 1 if leap year, else 0."
220.46 - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
220.47 -
220.48 -def _days_in_year(year):
220.49 - "year -> number of days in year (366 if a leap year, else 365)."
220.50 - return 365 + _is_leap(year)
220.51 -
220.52 -def _days_before_year(year):
220.53 - "year -> number of days before January 1st of year."
220.54 - y = year - 1
220.55 - return y*365 + y//4 - y//100 + y//400
220.56 -
220.57 -def _days_in_month(year, month):
220.58 - "year, month -> number of days in that month in that year."
220.59 - |>new_name<|(month)
220.60 - if month == 2 and _is_leap(year):
220.61 - return 29
220.62 - return _DAYS_IN_MONTH[month]
220.63 -
220.64 -
220.65 -def |>^new_name<|(month):
220.66 - assert 1 <= month <= 12, month
220.67 -
220.68 -def _days_before_month(year, month):
220.69 - "year, month -> number of days in year preceeding first day of month."
220.70 - if not 1 <= month <= 12:
220.71 - raise ValueError('month must be in 1..12', month)
220.72 - return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
220.73 -
220.74 -def _ymd2ord(year, month, day):
220.75 - "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
220.76 - if not 1 <= month <= 12:
220.77 - raise ValueError('month must be in 1..12', month)
220.78 - dim = _days_in_month(year, month)
220.79 - if not 1 <= day <= dim:
220.80 - raise ValueError('day must be in 1..%d' % dim, day)
220.81 - return (_days_before_year(year) +
220.82 - _days_before_month(year, month) +
220.83 - day)
220.84 -
220.85 -_DI400Y = _days_before_year(401) # number of days in 400 years
220.86 -_DI100Y = _days_before_year(101) # " " " " 100 "
220.87 -_DI4Y = _days_before_year(5) # " " " " 4 "
220.88 -
220.89 -# A 4-year cycle has an extra leap day over what we'd get from pasting
220.90 -# together 4 single years.
220.91 -assert _DI4Y == 4 * 365 + 1
220.92 -
220.93 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
220.94 -# pasting together 4 100-year cycles.
220.95 -assert _DI400Y == 4 * _DI100Y + 1
220.96 -
220.97 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
220.98 -# pasting together 25 4-year cycles.
220.99 -assert _DI100Y == 25 * _DI4Y - 1
220.100 -
220.101 -def _ord2ymd(n):
220.102 - "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
220.103 -
220.104 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
220.105 - # repeats exactly every 400 years. The basic strategy is to find the
220.106 - # closest 400-year boundary at or before n, then work with the offset
220.107 - # from that boundary to n. Life is much clearer if we subtract 1 from
220.108 - # n first -- then the values of n at 400-year boundaries are exactly
220.109 - # those divisible by _DI400Y:
220.110 - #
220.111 - # D M Y n n-1
220.112 - # -- --- ---- ---------- ----------------
220.113 - # 31 Dec -400 -_DI400Y -_DI400Y -1
220.114 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
220.115 - # ...
220.116 - # 30 Dec 000 -1 -2
220.117 - # 31 Dec 000 0 -1
220.118 - # 1 Jan 001 1 0 400-year boundary
220.119 - # 2 Jan 001 2 1
220.120 - # 3 Jan 001 3 2
220.121 - # ...
220.122 - # 31 Dec 400 _DI400Y _DI400Y -1
220.123 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
220.124 - n -= 1
220.125 - n400, n = divmod(n, _DI400Y)
220.126 - year = n400 * 400 + 1 # ..., -399, 1, 401, ...
220.127 -
220.128 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
220.129 - # the desired date. Now compute how many 100-year cycles precede n.
220.130 - # Note that it's possible for n100 to equal 4! In that case 4 full
220.131 - # 100-year cycles precede the desired day, which implies the desired
220.132 - # day is December 31 at the end of a 400-year cycle.
220.133 - n100, n = divmod(n, _DI100Y)
220.134 -
220.135 - # Now compute how many 4-year cycles precede it.
220.136 - n4, n = divmod(n, _DI4Y)
220.137 -
220.138 - # And now how many single years. Again n1 can be 4, and again meaning
220.139 - # that the desired day is December 31 at the end of the 4-year cycle.
220.140 - n1, n = divmod(n, 365)
220.141 -
220.142 - year += n100 * 100 + n4 * 4 + n1
220.143 - if n1 == 4 or n100 == 4:
220.144 - assert n == 0
220.145 - return year-1, 12, 31
220.146 -
220.147 - # Now the year is correct, and n is the offset from January 1. We find
220.148 - # the month via an estimate that's either exact or one too large.
220.149 - leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
220.150 - assert leapyear == _is_leap(year)
220.151 - month = (n + 50) >> 5
220.152 - preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
220.153 - if preceding > n: # estimate is too large
220.154 - month -= 1
220.155 - preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
220.156 - n -= preceding
220.157 - assert 0 <= n < _days_in_month(year, month)
220.158 -
220.159 - # Now the year and month are correct, and n is the offset from the
220.160 - # start of that month: we're done!
220.161 - return year, month, n+1
220.162 -
220.163 -# Month and day names. For localized versions, see the calendar module.
220.164 -_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
220.165 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
220.166 -_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
220.167 -
220.168 -
220.169 -def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
220.170 - wday = (_ymd2ord(y, m, d) + 6) % 7
220.171 - dnum = _days_before_month(y, m) + d
220.172 - return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
220.173 -
220.174 -def _format_time(hh, mm, ss, us):
220.175 - # Skip trailing microseconds when us==0.
220.176 - result = "%02d:%02d:%02d" % (hh, mm, ss)
220.177 - if us:
220.178 - result += ".%06d" % us
220.179 - return result
220.180 -
220.181 -# Correctly substitute for %z and %Z escapes in strftime formats.
220.182 -def _wrap_strftime(object, format, timetuple):
220.183 - year = timetuple[0]
220.184 - if year < 1900:
220.185 - raise ValueError("year=%d is before 1900; the datetime strftime() "
220.186 - "methods require year >= 1900" % year)
220.187 - # Don't call _utcoffset() or tzname() unless actually needed.
220.188 - zreplace = None # the string to use for %z
220.189 - Zreplace = None # the string to use for %Z
220.190 -
220.191 - # Scan format for %z and %Z escapes, replacing as needed.
220.192 - newformat = []
220.193 - push = newformat.append
220.194 - i, n = 0, len(format)
220.195 - while i < n:
220.196 - ch = format[i]
220.197 - i += 1
220.198 - if ch == '%':
220.199 - if i < n:
220.200 - ch = format[i]
220.201 - i += 1
220.202 - if ch == 'z':
220.203 - if zreplace is None:
220.204 - zreplace = ""
220.205 - if hasattr(object, "_utcoffset"):
220.206 - offset = object._utcoffset()
220.207 - if offset is not None:
220.208 - sign = '+'
220.209 - if offset < 0:
220.210 - offset = -offset
220.211 - sign = '-'
220.212 - h, m = divmod(offset, 60)
220.213 - zreplace = '%c%02d%02d' % (sign, h, m)
220.214 - assert '%' not in zreplace
220.215 - newformat.append(zreplace)
220.216 - elif ch == 'Z':
220.217 - if Zreplace is None:
220.218 - Zreplace = ""
220.219 - if hasattr(object, "tzname"):
220.220 - s = object.tzname()
220.221 - if s is not None:
220.222 - # strftime is going to have at this: escape %
220.223 - Zreplace = s.replace('%', '%%')
220.224 - newformat.append(Zreplace)
220.225 - else:
220.226 - push('%')
220.227 - push(ch)
220.228 - else:
220.229 - push('%')
220.230 - else:
220.231 - push(ch)
220.232 - newformat = "".join(newformat)
220.233 - return _time.strftime(newformat, timetuple)
220.234 -
220.235 -def _call_tzinfo_method(tzinfo, methname, tzinfoarg):
220.236 - if tzinfo is None:
220.237 - return None
220.238 - return getattr(tzinfo, methname)(tzinfoarg)
220.239 -
220.240 -# Just raise TypeError if the arg isn't None or a string.
220.241 -def _check_tzname(name):
220.242 - if name is not None and not isinstance(name, str):
220.243 - raise TypeError("tzinfo.tzname() must return None or string, "
220.244 - "not '%s'" % type(name))
220.245 -
220.246 -# name is the offset-producing method, "utcoffset" or "dst".
220.247 -# offset is what it returned.
220.248 -# If offset isn't None or timedelta, raises TypeError.
220.249 -# If offset is None, returns None.
220.250 -# Else offset is checked for being in range, and a whole # of minutes.
220.251 -# If it is, its integer value is returned. Else ValueError is raised.
220.252 -def _check_utc_offset(name, offset):
220.253 - assert name in ("utcoffset", "dst")
220.254 - if offset is None:
220.255 - return None
220.256 - if not isinstance(offset, timedelta):
220.257 - raise TypeError("tzinfo.%s() must return None "
220.258 - "or timedelta, not '%s'" % (name, type(offset)))
220.259 - days = offset.days
220.260 - if days < -1 or days > 0:
220.261 - offset = 1440 # trigger out-of-range
220.262 - else:
220.263 - seconds = days * 86400 + offset.seconds
220.264 - minutes, seconds = divmod(seconds, 60)
220.265 - if seconds or offset.microseconds:
220.266 - raise ValueError("tzinfo.%s() must return a whole number "
220.267 - "of minutes" % name)
220.268 - offset = minutes
220.269 - if -1440 < offset < 1440:
220.270 - return offset
220.271 - raise ValueError("%s()=%d, must be in -1439..1439" % (name, offset))
220.272 -
220.273 -def _check_date_fields(year, month, day):
220.274 - if not MINYEAR <= year <= MAXYEAR:
220.275 - raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
220.276 - if not 1 <= month <= 12:
220.277 - raise ValueError('month must be in 1..12', month)
220.278 - dim = _days_in_month(year, month)
220.279 - if not 1 <= day <= dim:
220.280 - raise ValueError('day must be in 1..%d' % dim, day)
220.281 -
220.282 -def _check_time_fields(hour, minute, second, microsecond):
220.283 - if not 0 <= hour <= 23:
220.284 - raise ValueError('hour must be in 0..23', hour)
220.285 - if not 0 <= minute <= 59:
220.286 - raise ValueError('minute must be in 0..59', minute)
220.287 - if not 0 <= second <= 59:
220.288 - raise ValueError('second must be in 0..59', second)
220.289 - if not 0 <= microsecond <= 999999:
220.290 - raise ValueError('microsecond must be in 0..999999', microsecond)
220.291 -
220.292 -def _check_tzinfo_arg(tz):
220.293 - if tz is not None and not isinstance(tz, tzinfo):
220.294 - raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
220.295 -
220.296 -
220.297 -# Notes on comparison: In general, datetime module comparison operators raise
220.298 -# TypeError when they don't know how to do a comparison themself. If they
220.299 -# returned NotImplemented instead, comparison could (silently) fall back to
220.300 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
220.301 -# and that's not helpful. There are two exceptions:
220.302 -#
220.303 -# 1. For date and datetime, if the other object has a "timetuple" attr,
220.304 -# NotImplemented is returned. This is a hook to allow other kinds of
220.305 -# datetime-like objects a chance to intercept the comparison.
220.306 -#
220.307 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
220.308 -# so opertaions like
220.309 -#
220.310 -# x == y
220.311 -# x != y
220.312 -# x in sequence
220.313 -# x not in sequence
220.314 -# dict[x] = y
220.315 -#
220.316 -# don't raise annoying TypeErrors just because a datetime object
220.317 -# is part of a heterogeneous collection. If there's no known way to
220.318 -# compare X to a datetime, saying they're not equal is reasonable.
220.319 -
220.320 -def _cmperror(x, y):
220.321 - raise TypeError("can't compare '%s' to '%s'" % (
220.322 - type(x).__name__, type(y).__name__))
220.323 -
220.324 -# This is a start at a struct tm workalike. Goals:
220.325 -#
220.326 -# + Works the same way across platforms.
220.327 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
220.328 -#
220.329 -# Note: I suspect it's best if this flavor of tm does *not* try to
220.330 -# second-guess timezones or DST. Instead fold whatever adjustments you want
220.331 -# into the minutes argument (and the constructor will normalize).
220.332 -
220.333 -_ORD1970 = _ymd2ord(1970, 1, 1) # base ordinal for UNIX epoch
220.334 -
220.335 -class tmxxx:
220.336 -
220.337 - ordinal = None
220.338 -
220.339 - def __init__(self, year, month, day, hour=0, minute=0, second=0,
220.340 - microsecond=0):
220.341 - # Normalize all the inputs, and store the normalized values.
220.342 - if not 0 <= microsecond <= 999999:
220.343 - carry, microsecond = divmod(microsecond, 1000000)
220.344 - second += carry
220.345 - if not 0 <= second <= 59:
220.346 - carry, second = divmod(second, 60)
220.347 - minute += carry
220.348 - if not 0 <= minute <= 59:
220.349 - carry, minute = divmod(minute, 60)
220.350 - hour += carry
220.351 - if not 0 <= hour <= 23:
220.352 - carry, hour = divmod(hour, 24)
220.353 - day += carry
220.354 -
220.355 - # That was easy. Now it gets muddy: the proper range for day
220.356 - # can't be determined without knowing the correct month and year,
220.357 - # but if day is, e.g., plus or minus a million, the current month
220.358 - # and year values make no sense (and may also be out of bounds
220.359 - # themselves).
220.360 - # Saying 12 months == 1 year should be non-controversial.
220.361 - if not 1 <= month <= 12:
220.362 - carry, month = divmod(month-1, 12)
220.363 - year += carry
220.364 - month += 1
220.365 - assert 1 <= month <= 12
220.366 -
220.367 - # Now only day can be out of bounds (year may also be out of bounds
220.368 - # for a datetime object, but we don't care about that here).
220.369 - # If day is out of bounds, what to do is arguable, but at least the
220.370 - # method here is principled and explainable.
220.371 - dim = _days_in_month(year, month)
220.372 - if not 1 <= day <= dim:
220.373 - # Move day-1 days from the first of the month. First try to
220.374 - # get off cheap if we're only one day out of range (adjustments
220.375 - # for timezone alone can't be worse than that).
220.376 - if day == 0: # move back a day
220.377 - month -= 1
220.378 - if month > 0:
220.379 - day = _days_in_month(year, month)
220.380 - else:
220.381 - year, month, day = year-1, 12, 31
220.382 - elif day == dim + 1: # move forward a day
220.383 - month += 1
220.384 - day = 1
220.385 - if month > 12:
220.386 - month = 1
220.387 - year += 1
220.388 - else:
220.389 - self.ordinal = _ymd2ord(year, month, 1) + (day - 1)
220.390 - year, month, day = _ord2ymd(self.ordinal)
220.391 -
220.392 - self.year, self.month, self.day = year, month, day
220.393 - self.hour, self.minute, self.second = hour, minute, second
220.394 - self.microsecond = microsecond
220.395 -
220.396 - def toordinal(self):
220.397 - """Return proleptic Gregorian ordinal for the year, month and day.
220.398 -
220.399 - January 1 of year 1 is day 1. Only the year, month and day values
220.400 - contribute to the result.
220.401 - """
220.402 - if self.ordinal is None:
220.403 - self.ordinal = _ymd2ord(self.year, self.month, self.day)
220.404 - return self.ordinal
220.405 -
220.406 - def time(self):
220.407 - "Return Unixish timestamp, as a float (assuming UTC)."
220.408 - days = self.toordinal() - _ORD1970 # convert to UNIX epoch
220.409 - seconds = ((days * 24. + self.hour)*60. + self.minute)*60.
220.410 - return seconds + self.second + self.microsecond / 1e6
220.411 -
220.412 - def ctime(self):
220.413 - "Return ctime() style string."
220.414 - weekday = self.toordinal() % 7 or 7
220.415 - return "%s %s %2d %02d:%02d:%02d %04d" % (
220.416 - _DAYNAMES[weekday],
220.417 - _MONTHNAMES[self.month],
220.418 - self.day,
220.419 - self.hour, self.minute, self.second,
220.420 - self.year)
220.421 -
220.422 -class timedelta(object):
220.423 - """Represent the difference between two datetime objects.
220.424 -
220.425 - Supported operators:
220.426 -
220.427 - - add, subtract timedelta
220.428 - - unary plus, minus, abs
220.429 - - compare to timedelta
220.430 - - multiply, divide by int/long
220.431 -
220.432 - In addition, datetime supports subtraction of two datetime objects
220.433 - returning a timedelta, and addition or subtraction of a datetime
220.434 - and a timedelta giving a datetime.
220.435 -
220.436 - Representation: (days, seconds, microseconds). Why? Because I
220.437 - felt like it.
220.438 - """
220.439 -
220.440 - def __new__(cls, days=0, seconds=0, microseconds=0,
220.441 - # XXX The following should only be used as keyword args:
220.442 - milliseconds=0, minutes=0, hours=0, weeks=0):
220.443 - # Doing this efficiently and accurately in C is going to be difficult
220.444 - # and error-prone, due to ubiquitous overflow possibilities, and that
220.445 - # C double doesn't have enough bits of precision to represent
220.446 - # microseconds over 10K years faithfully. The code here tries to make
220.447 - # explicit where go-fast assumptions can be relied on, in order to
220.448 - # guide the C implementation; it's way more convoluted than speed-
220.449 - # ignoring auto-overflow-to-long idiomatic Python could be.
220.450 -
220.451 - # XXX Check that all inputs are ints, longs or floats.
220.452 -
220.453 - # Final values, all integer.
220.454 - # s and us fit in 32-bit signed ints; d isn't bounded.
220.455 - d = s = us = 0
220.456 -
220.457 - # Normalize everything to days, seconds, microseconds.
220.458 - days += weeks*7
220.459 - seconds += minutes*60 + hours*3600
220.460 - microseconds += milliseconds*1000
220.461 -
220.462 - # Get rid of all fractions, and normalize s and us.
220.463 - # Take a deep breath <wink>.
220.464 - if isinstance(days, float):
220.465 - dayfrac, days = _math.modf(days)
220.466 - daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
220.467 - assert daysecondswhole == int(daysecondswhole) # can't overflow
220.468 - s = int(daysecondswhole)
220.469 - assert days == long(days)
220.470 - d = long(days)
220.471 - else:
220.472 - daysecondsfrac = 0.0
220.473 - d = days
220.474 - assert isinstance(daysecondsfrac, float)
220.475 - assert abs(daysecondsfrac) <= 1.0
220.476 - assert isinstance(d, (int, long))
220.477 - assert abs(s) <= 24 * 3600
220.478 - # days isn't referenced again before redefinition
220.479 -
220.480 - if isinstance(seconds, float):
220.481 - secondsfrac, seconds = _math.modf(seconds)
220.482 - assert seconds == long(seconds)
220.483 - seconds = long(seconds)
220.484 - secondsfrac += daysecondsfrac
220.485 - assert abs(secondsfrac) <= 2.0
220.486 - else:
220.487 - secondsfrac = daysecondsfrac
220.488 - # daysecondsfrac isn't referenced again
220.489 - assert isinstance(secondsfrac, float)
220.490 - assert abs(secondsfrac) <= 2.0
220.491 -
220.492 - assert isinstance(seconds, (int, long))
220.493 - days, seconds = divmod(seconds, 24*3600)
220.494 - d += days
220.495 - s += int(seconds) # can't overflow
220.496 - assert isinstance(s, int)
220.497 - assert abs(s) <= 2 * 24 * 3600
220.498 - # seconds isn't referenced again before redefinition
220.499 -
220.500 - usdouble = secondsfrac * 1e6
220.501 - assert abs(usdouble) < 2.1e6 # exact value not critical
220.502 - # secondsfrac isn't referenced again
220.503 -
220.504 - if isinstance(microseconds, float):
220.505 - microseconds += usdouble
220.506 - microseconds = round(microseconds)
220.507 - seconds, microseconds = divmod(microseconds, 1e6)
220.508 - assert microseconds == int(microseconds)
220.509 - assert seconds == long(seconds)
220.510 - days, seconds = divmod(seconds, 24.*3600.)
220.511 - assert days == long(days)
220.512 - assert seconds == int(seconds)
220.513 - d += long(days)
220.514 - s += int(seconds) # can't overflow
220.515 - assert isinstance(s, int)
220.516 - assert abs(s) <= 3 * 24 * 3600
220.517 - else:
220.518 - seconds, microseconds = divmod(microseconds, 1000000)
220.519 - days, seconds = divmod(seconds, 24*3600)
220.520 - d += days
220.521 - s += int(seconds) # can't overflow
220.522 - assert isinstance(s, int)
220.523 - assert abs(s) <= 3 * 24 * 3600
220.524 - microseconds = float(microseconds)
220.525 - microseconds += usdouble
220.526 - microseconds = round(microseconds)
220.527 - assert abs(s) <= 3 * 24 * 3600
220.528 - assert abs(microseconds) < 3.1e6
220.529 -
220.530 - # Just a little bit of carrying possible for microseconds and seconds.
220.531 - assert isinstance(microseconds, float)
220.532 - assert int(microseconds) == microseconds
220.533 - us = int(microseconds)
220.534 - seconds, us = divmod(us, 1000000)
220.535 - s += seconds # cant't overflow
220.536 - assert isinstance(s, int)
220.537 - days, s = divmod(s, 24*3600)
220.538 - d += days
220.539 -
220.540 - assert isinstance(d, (int, long))
220.541 - assert isinstance(s, int) and 0 <= s < 24*3600
220.542 - assert isinstance(us, int) and 0 <= us < 1000000
220.543 -
220.544 - self = object.__new__(cls)
220.545 -
220.546 - self.__days = d
220.547 - self.__seconds = s
220.548 - self.__microseconds = us
220.549 - if abs(d) > 999999999:
220.550 - raise OverflowError("timedelta # of days is too large: %d" % d)
220.551 -
220.552 - return self
220.553 -
220.554 - def __repr__(self):
220.555 - if self.__microseconds:
220.556 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
220.557 - self.__days,
220.558 - self.__seconds,
220.559 - self.__microseconds)
220.560 - if self.__seconds:
220.561 - return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__,
220.562 - self.__days,
220.563 - self.__seconds)
220.564 - return "%s(%d)" % ('datetime.' + self.__class__.__name__, self.__days)
220.565 -
220.566 - def __str__(self):
220.567 - mm, ss = divmod(self.__seconds, 60)
220.568 - hh, mm = divmod(mm, 60)
220.569 - s = "%d:%02d:%02d" % (hh, mm, ss)
220.570 - if self.__days:
220.571 - def plural(n):
220.572 - return n, abs(n) != 1 and "s" or ""
220.573 - s = ("%d day%s, " % plural(self.__days)) + s
220.574 - if self.__microseconds:
220.575 - s = s + ".%06d" % self.__microseconds
220.576 - return s
220.577 -
220.578 - days = property(lambda self: self.__days, doc="days")
220.579 - seconds = property(lambda self: self.__seconds, doc="seconds")
220.580 - microseconds = property(lambda self: self.__microseconds,
220.581 - doc="microseconds")
220.582 -
220.583 - def __add__(self, other):
220.584 - if isinstance(other, timedelta):
220.585 - return timedelta(self.__days + other.__days,
220.586 - self.__seconds + other.__seconds,
220.587 - self.__microseconds + other.__microseconds)
220.588 - return NotImplemented
220.589 -
220.590 - __radd__ = __add__
220.591 -
220.592 - def __sub__(self, other):
220.593 - if isinstance(other, timedelta):
220.594 - return self + -other
220.595 - return NotImplemented
220.596 -
220.597 - def __rsub__(self, other):
220.598 - if isinstance(other, timedelta):
220.599 - return -self + other
220.600 - return NotImplemented
220.601 -
220.602 - def __neg__(self):
220.603 - return self.__class__(-self.__days,
220.604 - -self.__seconds,
220.605 - -self.__microseconds)
220.606 -
220.607 - def __pos__(self):
220.608 - return self
220.609 -
220.610 - def __abs__(self):
220.611 - if self.__days < 0:
220.612 - return -self
220.613 - else:
220.614 - return self
220.615 -
220.616 - def __mul__(self, other):
220.617 - if isinstance(other, (int, long)):
220.618 - return self.__class__(self.__days * other,
220.619 - self.__seconds * other,
220.620 - self.__microseconds * other)
220.621 - return NotImplemented
220.622 -
220.623 - __rmul__ = __mul__
220.624 -
220.625 - def __div__(self, other):
220.626 - if isinstance(other, (int, long)):
220.627 - usec = ((self.__days * (24*3600L) + self.__seconds) * 1000000 +
220.628 - self.__microseconds)
220.629 - return self.__class__(0, 0, usec // other)
220.630 - return NotImplemented
220.631 -
220.632 - __floordiv__ = __div__
220.633 -
220.634 - # Comparisons.
220.635 -
220.636 - def __eq__(self, other):
220.637 - if isinstance(other, timedelta):
220.638 - return self.__cmp(other) == 0
220.639 - else:
220.640 - return False
220.641 -
220.642 - def __ne__(self, other):
220.643 - if isinstance(other, timedelta):
220.644 - return self.__cmp(other) != 0
220.645 - else:
220.646 - return True
220.647 -
220.648 - def __le__(self, other):
220.649 - if isinstance(other, timedelta):
220.650 - return self.__cmp(other) <= 0
220.651 - else:
220.652 - _cmperror(self, other)
220.653 -
220.654 - def __lt__(self, other):
220.655 - if isinstance(other, timedelta):
220.656 - return self.__cmp(other) < 0
220.657 - else:
220.658 - _cmperror(self, other)
220.659 -
220.660 - def __ge__(self, other):
220.661 - if isinstance(other, timedelta):
220.662 - return self.__cmp(other) >= 0
220.663 - else:
220.664 - _cmperror(self, other)
220.665 -
220.666 - def __gt__(self, other):
220.667 - if isinstance(other, timedelta):
220.668 - return self.__cmp(other) > 0
220.669 - else:
220.670 - _cmperror(self, other)
220.671 -
220.672 - def __cmp(self, other):
220.673 - assert isinstance(other, timedelta)
220.674 - return cmp(self.__getstate(), other.__getstate())
220.675 -
220.676 - def __hash__(self):
220.677 - return hash(self.__getstate())
220.678 -
220.679 - def __nonzero__(self):
220.680 - return (self.__days != 0 or
220.681 - self.__seconds != 0 or
220.682 - self.__microseconds != 0)
220.683 -
220.684 - # Pickle support.
220.685 -
220.686 - __safe_for_unpickling__ = True # For Python 2.2
220.687 -
220.688 - def __getstate(self):
220.689 - return (self.__days, self.__seconds, self.__microseconds)
220.690 -
220.691 - def __reduce__(self):
220.692 - return (self.__class__, self.__getstate())
220.693 -
220.694 -timedelta.min = timedelta(-999999999)
220.695 -timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
220.696 - microseconds=999999)
220.697 -timedelta.resolution = timedelta(microseconds=1)
220.698 -
220.699 -class date(object):
220.700 - """Concrete date type.
220.701 -
220.702 - Constructors:
220.703 -
220.704 - __new__()
220.705 - fromtimestamp()
220.706 - today()
220.707 - fromordinal()
220.708 -
220.709 - Operators:
220.710 -
220.711 - __repr__, __str__
220.712 - __cmp__, __hash__
220.713 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
220.714 -
220.715 - Methods:
220.716 -
220.717 - timetuple()
220.718 - toordinal()
220.719 - weekday()
220.720 - isoweekday(), isocalendar(), isoformat()
220.721 - ctime()
220.722 - strftime()
220.723 -
220.724 - Properties (readonly):
220.725 - year, month, day
220.726 - """
220.727 -
220.728 - def __new__(cls, year, month=None, day=None):
220.729 - """Constructor.
220.730 -
220.731 - Arguments:
220.732 -
220.733 - year, month, day (required, base 1)
220.734 - """
220.735 - if isinstance(year, str):
220.736 - # Pickle support
220.737 - self = object.__new__(cls)
220.738 - self.__setstate((year,))
220.739 - return self
220.740 - _check_date_fields(year, month, day)
220.741 - self = object.__new__(cls)
220.742 - self.__year = year
220.743 - self.__month = month
220.744 - self.__day = day
220.745 - return self
220.746 -
220.747 - # Additional constructors
220.748 -
220.749 - def fromtimestamp(cls, t):
220.750 - "Construct a date from a POSIX timestamp (like time.time())."
220.751 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
220.752 - return cls(y, m, d)
220.753 - fromtimestamp = classmethod(fromtimestamp)
220.754 -
220.755 - def today(cls):
220.756 - "Construct a date from time.time()."
220.757 - t = _time.time()
220.758 - return cls.fromtimestamp(t)
220.759 - today = classmethod(today)
220.760 -
220.761 - def fromordinal(cls, n):
220.762 - """Contruct a date from a proleptic Gregorian ordinal.
220.763 -
220.764 - January 1 of year 1 is day 1. Only the year, month and day are
220.765 - non-zero in the result.
220.766 - """
220.767 - y, m, d = _ord2ymd(n)
220.768 - return cls(y, m, d)
220.769 - fromordinal = classmethod(fromordinal)
220.770 -
220.771 - # Conversions to string
220.772 -
220.773 - def __repr__(self):
220.774 - "Convert to formal string, for repr()."
220.775 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
220.776 - self.__year,
220.777 - self.__month,
220.778 - self.__day)
220.779 - # XXX These shouldn't depend on time.localtime(), because that
220.780 - # clips the usable dates to [1970 .. 2038). At least ctime() is
220.781 - # easily done without using strftime() -- that's better too because
220.782 - # strftime("%c", ...) is locale specific.
220.783 -
220.784 - def ctime(self):
220.785 - "Format a la ctime()."
220.786 - return tmxxx(self.__year, self.__month, self.__day).ctime()
220.787 -
220.788 - def strftime(self, fmt):
220.789 - "Format using strftime()."
220.790 - return _wrap_strftime(self, fmt, self.timetuple())
220.791 -
220.792 - def isoformat(self):
220.793 - """Return the date formatted according to ISO.
220.794 -
220.795 - This is 'YYYY-MM-DD'.
220.796 -
220.797 - References:
220.798 - - http://www.w3.org/TR/NOTE-datetime
220.799 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
220.800 - """
220.801 - return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day)
220.802 -
220.803 - __str__ = isoformat
220.804 -
220.805 - # Read-only field accessors
220.806 - year = property(lambda self: self.__year,
220.807 - doc="year (%d-%d)" % (MINYEAR, MAXYEAR))
220.808 - month = property(lambda self: self.__month, doc="month (1-12)")
220.809 - day = property(lambda self: self.__day, doc="day (1-31)")
220.810 -
220.811 - # Standard conversions, __cmp__, __hash__ (and helpers)
220.812 -
220.813 - def timetuple(self):
220.814 - "Return local time tuple compatible with time.localtime()."
220.815 - return _build_struct_time(self.__year, self.__month, self.__day,
220.816 - 0, 0, 0, -1)
220.817 -
220.818 - def toordinal(self):
220.819 - """Return proleptic Gregorian ordinal for the year, month and day.
220.820 -
220.821 - January 1 of year 1 is day 1. Only the year, month and day values
220.822 - contribute to the result.
220.823 - """
220.824 - return _ymd2ord(self.__year, self.__month, self.__day)
220.825 -
220.826 - def replace(self, year=None, month=None, day=None):
220.827 - """Return a new date with new values for the specified fields."""
220.828 - if year is None:
220.829 - year = self.__year
220.830 - if month is None:
220.831 - month = self.__month
220.832 - if day is None:
220.833 - day = self.__day
220.834 - _check_date_fields(year, month, day)
220.835 - return date(year, month, day)
220.836 -
220.837 - # Comparisons.
220.838 -
220.839 - def __eq__(self, other):
220.840 - if isinstance(other, date):
220.841 - return self.__cmp(other) == 0
220.842 - elif hasattr(other, "timetuple"):
220.843 - return NotImplemented
220.844 - else:
220.845 - return False
220.846 -
220.847 - def __ne__(self, other):
220.848 - if isinstance(other, date):
220.849 - return self.__cmp(other) != 0
220.850 - elif hasattr(other, "timetuple"):
220.851 - return NotImplemented
220.852 - else:
220.853 - return True
220.854 -
220.855 - def __le__(self, other):
220.856 - if isinstance(other, date):
220.857 - return self.__cmp(other) <= 0
220.858 - elif hasattr(other, "timetuple"):
220.859 - return NotImplemented
220.860 - else:
220.861 - _cmperror(self, other)
220.862 -
220.863 - def __lt__(self, other):
220.864 - if isinstance(other, date):
220.865 - return self.__cmp(other) < 0
220.866 - elif hasattr(other, "timetuple"):
220.867 - return NotImplemented
220.868 - else:
220.869 - _cmperror(self, other)
220.870 -
220.871 - def __ge__(self, other):
220.872 - if isinstance(other, date):
220.873 - return self.__cmp(other) >= 0
220.874 - elif hasattr(other, "timetuple"):
220.875 - return NotImplemented
220.876 - else:
220.877 - _cmperror(self, other)
220.878 -
220.879 - def __gt__(self, other):
220.880 - if isinstance(other, date):
220.881 - return self.__cmp(other) > 0
220.882 - elif hasattr(other, "timetuple"):
220.883 - return NotImplemented
220.884 - else:
220.885 - _cmperror(self, other)
220.886 -
220.887 - def __cmp(self, other):
220.888 - assert isinstance(other, date)
220.889 - y, m, d = self.__year, self.__month, self.__day
220.890 - y2, m2, d2 = other.__year, other.__month, other.__day
220.891 - return cmp((y, m, d), (y2, m2, d2))
220.892 -
220.893 - def __hash__(self):
220.894 - "Hash."
220.895 - return hash(self.__getstate())
220.896 -
220.897 - # Computations
220.898 -
220.899 - def _checkOverflow(self, year):
220.900 - if not MINYEAR <= year <= MAXYEAR:
220.901 - raise OverflowError("date +/-: result year %d not in %d..%d" %
220.902 - (year, MINYEAR, MAXYEAR))
220.903 -
220.904 - def __add__(self, other):
220.905 - "Add a date to a timedelta."
220.906 - if isinstance(other, timedelta):
220.907 - t = tmxxx(self.__year,
220.908 - self.__month,
220.909 - self.__day + other.days)
220.910 - self._checkOverflow(t.year)
220.911 - result = self.__class__(t.year, t.month, t.day)
220.912 - return result
220.913 - return NotImplemented
220.914 -
220.915 - __radd__ = __add__
220.916 -
220.917 - def __sub__(self, other):
220.918 - """Subtract two dates, or a date and a timedelta."""
220.919 - if isinstance(other, timedelta):
220.920 - return self + timedelta(-other.days)
220.921 - if isinstance(other, date):
220.922 - days1 = self.toordinal()
220.923 - days2 = other.toordinal()
220.924 - return timedelta(days1 - days2)
220.925 - return NotImplemented
220.926 -
220.927 - def weekday(self):
220.928 - "Return day of the week, where Monday == 0 ... Sunday == 6."
220.929 - return (self.toordinal() + 6) % 7
220.930 -
220.931 - # Day-of-the-week and week-of-the-year, according to ISO
220.932 -
220.933 - def isoweekday(self):
220.934 - "Return day of the week, where Monday == 1 ... Sunday == 7."
220.935 - # 1-Jan-0001 is a Monday
220.936 - return self.toordinal() % 7 or 7
220.937 -
220.938 - def isocalendar(self):
220.939 - """Return a 3-tuple containing ISO year, week number, and weekday.
220.940 -
220.941 - The first ISO week of the year is the (Mon-Sun) week
220.942 - containing the year's first Thursday; everything else derives
220.943 - from that.
220.944 -
220.945 - The first week is 1; Monday is 1 ... Sunday is 7.
220.946 -
220.947 - ISO calendar algorithm taken from
220.948 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
220.949 - """
220.950 - year = self.__year
220.951 - week1monday = _isoweek1monday(year)
220.952 - today = _ymd2ord(self.__year, self.__month, self.__day)
220.953 - # Internally, week and day have origin 0
220.954 - week, day = divmod(today - week1monday, 7)
220.955 - if week < 0:
220.956 - year -= 1
220.957 - week1monday = _isoweek1monday(year)
220.958 - week, day = divmod(today - week1monday, 7)
220.959 - elif week >= 52:
220.960 - if today >= _isoweek1monday(year+1):
220.961 - year += 1
220.962 - week = 0
220.963 - return year, week+1, day+1
220.964 -
220.965 - # Pickle support.
220.966 -
220.967 - __safe_for_unpickling__ = True # For Python 2.2
220.968 -
220.969 - def __getstate(self):
220.970 - yhi, ylo = divmod(self.__year, 256)
220.971 - return ("%c%c%c%c" % (yhi, ylo, self.__month, self.__day), )
220.972 -
220.973 - def __setstate(self, t):
220.974 - assert isinstance(t, tuple) and len(t) == 1, `t`
220.975 - string = t[0]
220.976 - assert len(string) == 4
220.977 - yhi, ylo, self.__month, self.__day = map(ord, string)
220.978 - self.__year = yhi * 256 + ylo
220.979 -
220.980 - def __reduce__(self):
220.981 - return (self.__class__, self.__getstate())
220.982 -
220.983 -_date_class = date # so functions w/ args named "date" can get at the class
220.984 -
220.985 -date.min = date(1, 1, 1)
220.986 -date.max = date(9999, 12, 31)
220.987 -date.resolution = timedelta(days=1)
220.988 -
220.989 -class tzinfo(object):
220.990 - """Abstract base class for time zone info classes.
220.991 -
220.992 - Subclasses must override the name(), utcoffset() and dst() methods.
220.993 - """
220.994 -
220.995 - def tzname(self, dt):
220.996 - "datetime -> string name of time zone."
220.997 - raise NotImplementedError("tzinfo subclass must override tzname()")
220.998 -
220.999 - def utcoffset(self, dt):
220.1000 - "datetime -> minutes east of UTC (negative for west of UTC)"
220.1001 - raise NotImplementedError("tzinfo subclass must override utcoffset()")
220.1002 -
220.1003 - def dst(self, dt):
220.1004 - """datetime -> DST offset in minutes east of UTC.
220.1005 -
220.1006 - Return 0 if DST not in effect. utcoffset() must include the DST
220.1007 - offset.
220.1008 - """
220.1009 - raise NotImplementedError("tzinfo subclass must override dst()")
220.1010 -
220.1011 - def fromutc(self, dt):
220.1012 - "datetime in UTC -> datetime in local time."
220.1013 -
220.1014 - if not isinstance(dt, datetime):
220.1015 - raise TypeError("fromutc() requires a datetime argument")
220.1016 - if dt.tzinfo is not self:
220.1017 - raise ValueError("dt.tzinfo is not self")
220.1018 -
220.1019 - dtoff = dt.utcoffset()
220.1020 - if dtoff is None:
220.1021 - raise ValueError("fromutc() requires a non-None utcoffset() "
220.1022 - "result")
220.1023 -
220.1024 - # See the long comment block at the end of this file for an
220.1025 - # explanation of this algorithm.
220.1026 - dtdst = dt.dst()
220.1027 - if dtdst is None:
220.1028 - raise ValueError("fromutc() requires a non-None dst() result")
220.1029 - delta = dtoff - dtdst
220.1030 - if delta:
220.1031 - dt += delta
220.1032 - dtdst = dt.dst()
220.1033 - if dtdst is None:
220.1034 - raise ValueError("fromutc(): dt.dst gave inconsistent "
220.1035 - "results; cannot convert")
220.1036 - if dtdst:
220.1037 - return dt + dtdst
220.1038 - else:
220.1039 - return dt
220.1040 -
220.1041 - # Pickle support.
220.1042 -
220.1043 - __safe_for_unpickling__ = True # For Python 2.2
220.1044 -
220.1045 - def __reduce__(self):
220.1046 - getinitargs = getattr(self, "__getinitargs__", None)
220.1047 - if getinitargs:
220.1048 - args = getinitargs()
220.1049 - else:
220.1050 - args = ()
220.1051 - getstate = getattr(self, "__getstate__", None)
220.1052 - if getstate:
220.1053 - state = getstate()
220.1054 - else:
220.1055 - state = getattr(self, "__dict__", None) or None
220.1056 - if state is None:
220.1057 - return (self.__class__, args)
220.1058 - else:
220.1059 - return (self.__class__, args, state)
220.1060 -
220.1061 -_tzinfo_class = tzinfo # so functions w/ args named "tinfo" can get at it
220.1062 -
220.1063 -class time(object):
220.1064 - """Time with time zone.
220.1065 -
220.1066 - Constructors:
220.1067 -
220.1068 - __new__()
220.1069 -
220.1070 - Operators:
220.1071 -
220.1072 - __repr__, __str__
220.1073 - __cmp__, __hash__
220.1074 -
220.1075 - Methods:
220.1076 -
220.1077 - strftime()
220.1078 - isoformat()
220.1079 - utcoffset()
220.1080 - tzname()
220.1081 - dst()
220.1082 -
220.1083 - Properties (readonly):
220.1084 - hour, minute, second, microsecond, tzinfo
220.1085 - """
220.1086 -
220.1087 - def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
220.1088 - """Constructor.
220.1089 -
220.1090 - Arguments:
220.1091 -
220.1092 - hour, minute (required)
220.1093 - second, microsecond (default to zero)
220.1094 - tzinfo (default to None)
220.1095 - """
220.1096 - self = object.__new__(cls)
220.1097 - if isinstance(hour, str):
220.1098 - # Pickle support
220.1099 - self.__setstate((hour, minute or None))
220.1100 - return self
220.1101 - _check_tzinfo_arg(tzinfo)
220.1102 - _check_time_fields(hour, minute, second, microsecond)
220.1103 - self.__hour = hour
220.1104 - self.__minute = minute
220.1105 - self.__second = second
220.1106 - self.__microsecond = microsecond
220.1107 - self._tzinfo = tzinfo
220.1108 - return self
220.1109 -
220.1110 - # Read-only field accessors
220.1111 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
220.1112 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
220.1113 - second = property(lambda self: self.__second, doc="second (0-59)")
220.1114 - microsecond = property(lambda self: self.__microsecond,
220.1115 - doc="microsecond (0-999999)")
220.1116 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
220.1117 -
220.1118 - # Standard conversions, __hash__ (and helpers)
220.1119 -
220.1120 - # Comparisons.
220.1121 -
220.1122 - def __eq__(self, other):
220.1123 - if isinstance(other, time):
220.1124 - return self.__cmp(other) == 0
220.1125 - else:
220.1126 - return False
220.1127 -
220.1128 - def __ne__(self, other):
220.1129 - if isinstance(other, time):
220.1130 - return self.__cmp(other) != 0
220.1131 - else:
220.1132 - return True
220.1133 -
220.1134 - def __le__(self, other):
220.1135 - if isinstance(other, time):
220.1136 - return self.__cmp(other) <= 0
220.1137 - else:
220.1138 - _cmperror(self, other)
220.1139 -
220.1140 - def __lt__(self, other):
220.1141 - if isinstance(other, time):
220.1142 - return self.__cmp(other) < 0
220.1143 - else:
220.1144 - _cmperror(self, other)
220.1145 -
220.1146 - def __ge__(self, other):
220.1147 - if isinstance(other, time):
220.1148 - return self.__cmp(other) >= 0
220.1149 - else:
220.1150 - _cmperror(self, other)
220.1151 -
220.1152 - def __gt__(self, other):
220.1153 - if isinstance(other, time):
220.1154 - return self.__cmp(other) > 0
220.1155 - else:
220.1156 - _cmperror(self, other)
220.1157 -
220.1158 - def __cmp(self, other):
220.1159 - assert isinstance(other, time)
220.1160 - mytz = self._tzinfo
220.1161 - ottz = other._tzinfo
220.1162 - myoff = otoff = None
220.1163 -
220.1164 - if mytz is ottz:
220.1165 - base_compare = True
220.1166 - else:
220.1167 - myoff = self._utcoffset()
220.1168 - otoff = other._utcoffset()
220.1169 - base_compare = myoff == otoff
220.1170 -
220.1171 - if base_compare:
220.1172 - return cmp((self.__hour, self.__minute, self.__second,
220.1173 - self.__microsecond),
220.1174 - (other.__hour, other.__minute, other.__second,
220.1175 - other.__microsecond))
220.1176 - if myoff is None or otoff is None:
220.1177 - # XXX Buggy in 2.2.2.
220.1178 - raise TypeError("cannot compare naive and aware times")
220.1179 - myhhmm = self.__hour * 60 + self.__minute - myoff
220.1180 - othhmm = other.__hour * 60 + other.__minute - otoff
220.1181 - return cmp((myhhmm, self.__second, self.__microsecond),
220.1182 - (othhmm, other.__second, other.__microsecond))
220.1183 -
220.1184 - def __hash__(self):
220.1185 - """Hash."""
220.1186 - tzoff = self._utcoffset()
220.1187 - if not tzoff: # zero or None
220.1188 - return hash(self.__getstate()[0])
220.1189 - h, m = divmod(self.hour * 60 + self.minute - tzoff, 60)
220.1190 - if 0 <= h < 24:
220.1191 - return hash(time(h, m, self.second, self.microsecond))
220.1192 - return hash((h, m, self.second, self.microsecond))
220.1193 -
220.1194 - # Conversion to string
220.1195 -
220.1196 - def _tzstr(self, sep=":"):
220.1197 - """Return formatted timezone offset (+xx:xx) or None."""
220.1198 - off = self._utcoffset()
220.1199 - if off is not None:
220.1200 - if off < 0:
220.1201 - sign = "-"
220.1202 - off = -off
220.1203 - else:
220.1204 - sign = "+"
220.1205 - hh, mm = divmod(off, 60)
220.1206 - assert 0 <= hh < 24
220.1207 - off = "%s%02d%s%02d" % (sign, hh, sep, mm)
220.1208 - return off
220.1209 -
220.1210 - def __repr__(self):
220.1211 - """Convert to formal string, for repr()."""
220.1212 - if self.__microsecond != 0:
220.1213 - s = ", %d, %d" % (self.__second, self.__microsecond)
220.1214 - elif self.__second != 0:
220.1215 - s = ", %d" % self.__second
220.1216 - else:
220.1217 - s = ""
220.1218 - s= "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__,
220.1219 - self.__hour, self.__minute, s)
220.1220 - if self._tzinfo is not None:
220.1221 - assert s[-1:] == ")"
220.1222 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
220.1223 - return s
220.1224 -
220.1225 - def isoformat(self):
220.1226 - """Return the time formatted according to ISO.
220.1227 -
220.1228 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
220.1229 - self.microsecond == 0.
220.1230 - """
220.1231 - s = _format_time(self.__hour, self.__minute, self.__second,
220.1232 - self.__microsecond)
220.1233 - tz = self._tzstr()
220.1234 - if tz:
220.1235 - s += tz
220.1236 - return s
220.1237 -
220.1238 - __str__ = isoformat
220.1239 -
220.1240 - def strftime(self, fmt):
220.1241 - """Format using strftime(). The date part of the timestamp passed
220.1242 - to underlying strftime should not be used.
220.1243 - """
220.1244 - # The year must be >= 1900 else Python's strftime implementation
220.1245 - # can raise a bogus exception.
220.1246 - timetuple = (1900, 1, 1,
220.1247 - self.__hour, self.__minute, self.__second,
220.1248 - 0, 1, -1)
220.1249 - return _wrap_strftime(self, fmt, timetuple)
220.1250 -
220.1251 - # Timezone functions
220.1252 -
220.1253 - def utcoffset(self):
220.1254 - """Return the timezone offset in minutes east of UTC (negative west of
220.1255 - UTC)."""
220.1256 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
220.1257 - offset = _check_utc_offset("utcoffset", offset)
220.1258 - if offset is not None:
220.1259 - offset = timedelta(minutes=offset)
220.1260 - return offset
220.1261 -
220.1262 - # Return an integer (or None) instead of a timedelta (or None).
220.1263 - def _utcoffset(self):
220.1264 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
220.1265 - offset = _check_utc_offset("utcoffset", offset)
220.1266 - return offset
220.1267 -
220.1268 - def tzname(self):
220.1269 - """Return the timezone name.
220.1270 -
220.1271 - Note that the name is 100% informational -- there's no requirement that
220.1272 - it mean anything in particular. For example, "GMT", "UTC", "-500",
220.1273 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
220.1274 - """
220.1275 - name = _call_tzinfo_method(self._tzinfo, "tzname", None)
220.1276 - _check_tzname(name)
220.1277 - return name
220.1278 -
220.1279 - def dst(self):
220.1280 - """Return 0 if DST is not in effect, or the DST offset (in minutes
220.1281 - eastward) if DST is in effect.
220.1282 -
220.1283 - This is purely informational; the DST offset has already been added to
220.1284 - the UTC offset returned by utcoffset() if applicable, so there's no
220.1285 - need to consult dst() unless you're interested in displaying the DST
220.1286 - info.
220.1287 - """
220.1288 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
220.1289 - offset = _check_utc_offset("dst", offset)
220.1290 - if offset is not None:
220.1291 - offset = timedelta(minutes=offset)
220.1292 - return offset
220.1293 -
220.1294 - def replace(self, hour=None, minute=None, second=None, microsecond=None,
220.1295 - tzinfo=True):
220.1296 - """Return a new time with new values for the specified fields."""
220.1297 - if hour is None:
220.1298 - hour = self.hour
220.1299 - if minute is None:
220.1300 - minute = self.minute
220.1301 - if second is None:
220.1302 - second = self.second
220.1303 - if microsecond is None:
220.1304 - microsecond = self.microsecond
220.1305 - if tzinfo is True:
220.1306 - tzinfo = self.tzinfo
220.1307 - _check_time_fields(hour, minute, second, microsecond)
220.1308 - _check_tzinfo_arg(tzinfo)
220.1309 - return time(hour, minute, second, microsecond, tzinfo)
220.1310 -
220.1311 - # Return an integer (or None) instead of a timedelta (or None).
220.1312 - def _dst(self):
220.1313 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
220.1314 - offset = _check_utc_offset("dst", offset)
220.1315 - return offset
220.1316 -
220.1317 - def __nonzero__(self):
220.1318 - if self.second or self.microsecond:
220.1319 - return 1
220.1320 - offset = self._utcoffset() or 0
220.1321 - return self.hour * 60 + self.minute - offset != 0
220.1322 -
220.1323 - # Pickle support.
220.1324 -
220.1325 - __safe_for_unpickling__ = True # For Python 2.2
220.1326 -
220.1327 - def __getstate(self):
220.1328 - us2, us3 = divmod(self.__microsecond, 256)
220.1329 - us1, us2 = divmod(us2, 256)
220.1330 - basestate = ("%c" * 6) % (self.__hour, self.__minute, self.__second,
220.1331 - us1, us2, us3)
220.1332 - if self._tzinfo is None:
220.1333 - return (basestate,)
220.1334 - else:
220.1335 - return (basestate, self._tzinfo)
220.1336 -
220.1337 - def __setstate(self, state):
220.1338 - assert isinstance(state, tuple)
220.1339 - assert 1 <= len(state) <= 2
220.1340 - string = state[0]
220.1341 - assert len(string) == 6
220.1342 - self.__hour, self.__minute, self.__second, us1, us2, us3 = \
220.1343 - map(ord, string)
220.1344 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
220.1345 - if len(state) == 1:
220.1346 - self._tzinfo = None
220.1347 - else:
220.1348 - self._tzinfo = state[1]
220.1349 -
220.1350 - def __reduce__(self):
220.1351 - return (self.__class__, self.__getstate())
220.1352 -
220.1353 -_time_class = time # so functions w/ args named "time" can get at the class
220.1354 -
220.1355 -time.min = time(0, 0, 0)
220.1356 -time.max = time(23, 59, 59, 999999)
220.1357 -time.resolution = timedelta(microseconds=1)
220.1358 -
220.1359 -class datetime(date):
220.1360 -
220.1361 - # XXX needs docstrings
220.1362 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
220.1363 -
220.1364 - def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
220.1365 - microsecond=0, tzinfo=None):
220.1366 - if isinstance(year, str):
220.1367 - # Pickle support
220.1368 - self = date.__new__(cls, year[:4])
220.1369 - self.__setstate((year, month))
220.1370 - return self
220.1371 - _check_tzinfo_arg(tzinfo)
220.1372 - _check_time_fields(hour, minute, second, microsecond)
220.1373 - self = date.__new__(cls, year, month, day)
220.1374 - # XXX This duplicates __year, __month, __day for convenience :-(
220.1375 - self.__year = year
220.1376 - self.__month = month
220.1377 - self.__day = day
220.1378 - self.__hour = hour
220.1379 - self.__minute = minute
220.1380 - self.__second = second
220.1381 - self.__microsecond = microsecond
220.1382 - self._tzinfo = tzinfo
220.1383 - return self
220.1384 -
220.1385 - # Read-only field accessors
220.1386 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
220.1387 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
220.1388 - second = property(lambda self: self.__second, doc="second (0-59)")
220.1389 - microsecond = property(lambda self: self.__microsecond,
220.1390 - doc="microsecond (0-999999)")
220.1391 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
220.1392 -
220.1393 - def fromtimestamp(cls, t, tz=None):
220.1394 - """Construct a datetime from a POSIX timestamp (like time.time()).
220.1395 -
220.1396 - A timezone info object may be passed in as well.
220.1397 - """
220.1398 -
220.1399 - _check_tzinfo_arg(tz)
220.1400 - if tz is None:
220.1401 - converter = _time.localtime
220.1402 - else:
220.1403 - converter = _time.gmtime
220.1404 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
220.1405 - us = int((t % 1.0) * 1000000)
220.1406 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
220.1407 - result = cls(y, m, d, hh, mm, ss, us, tz)
220.1408 - if tz is not None:
220.1409 - result = tz.fromutc(result)
220.1410 - return result
220.1411 - fromtimestamp = classmethod(fromtimestamp)
220.1412 -
220.1413 - def utcfromtimestamp(cls, t):
220.1414 - "Construct a UTC datetime from a POSIX timestamp (like time.time())."
220.1415 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
220.1416 - us = int((t % 1.0) * 1000000)
220.1417 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
220.1418 - return cls(y, m, d, hh, mm, ss, us)
220.1419 - utcfromtimestamp = classmethod(utcfromtimestamp)
220.1420 -
220.1421 - # XXX This is supposed to do better than we *can* do by using time.time(),
220.1422 - # XXX if the platform supports a more accurate way. The C implementation
220.1423 - # XXX uses gettimeofday on platforms that have it, but that isn't
220.1424 - # XXX available from Python. So now() may return different results
220.1425 - # XXX across the implementations.
220.1426 - def now(cls, tz=None):
220.1427 - "Construct a datetime from time.time() and optional time zone info."
220.1428 - t = _time.time()
220.1429 - return cls.fromtimestamp(t, tz)
220.1430 - now = classmethod(now)
220.1431 -
220.1432 - def utcnow(cls):
220.1433 - "Construct a UTC datetime from time.time()."
220.1434 - t = _time.time()
220.1435 - return cls.utcfromtimestamp(t)
220.1436 - utcnow = classmethod(utcnow)
220.1437 -
220.1438 - def combine(cls, date, time):
220.1439 - "Construct a datetime from a given date and a given time."
220.1440 - if not isinstance(date, _date_class):
220.1441 - raise TypeError("date argument must be a date instance")
220.1442 - if not isinstance(time, _time_class):
220.1443 - raise TypeError("time argument must be a time instance")
220.1444 - return cls(date.year, date.month, date.day,
220.1445 - time.hour, time.minute, time.second, time.microsecond,
220.1446 - time.tzinfo)
220.1447 - combine = classmethod(combine)
220.1448 -
220.1449 - def timetuple(self):
220.1450 - "Return local time tuple compatible with time.localtime()."
220.1451 - dst = self._dst()
220.1452 - if dst is None:
220.1453 - dst = -1
220.1454 - elif dst:
220.1455 - dst = 1
220.1456 - return _build_struct_time(self.year, self.month, self.day,
220.1457 - self.hour, self.minute, self.second,
220.1458 - dst)
220.1459 -
220.1460 - def utctimetuple(self):
220.1461 - "Return UTC time tuple compatible with time.gmtime()."
220.1462 - y, m, d = self.year, self.month, self.day
220.1463 - hh, mm, ss = self.hour, self.minute, self.second
220.1464 - offset = self._utcoffset()
220.1465 - if offset: # neither None nor 0
220.1466 - tm = tmxxx(y, m, d, hh, mm - offset)
220.1467 - y, m, d = tm.year, tm.month, tm.day
220.1468 - hh, mm = tm.hour, tm.minute
220.1469 - return _build_struct_time(y, m, d, hh, mm, ss, 0)
220.1470 -
220.1471 - def date(self):
220.1472 - "Return the date part."
220.1473 - return date(self.__year, self.__month, self.__day)
220.1474 -
220.1475 - def time(self):
220.1476 - "Return the time part, with tzinfo None."
220.1477 - return time(self.hour, self.minute, self.second, self.microsecond)
220.1478 -
220.1479 - def timetz(self):
220.1480 - "Return the time part, with same tzinfo."
220.1481 - return time(self.hour, self.minute, self.second, self.microsecond,
220.1482 - self._tzinfo)
220.1483 -
220.1484 - def replace(self, year=None, month=None, day=None, hour=None,
220.1485 - minute=None, second=None, microsecond=None, tzinfo=True):
220.1486 - """Return a new datetime with new values for the specified fields."""
220.1487 - if year is None:
220.1488 - year = self.year
220.1489 - if month is None:
220.1490 - month = self.month
220.1491 - if day is None:
220.1492 - day = self.day
220.1493 - if hour is None:
220.1494 - hour = self.hour
220.1495 - if minute is None:
220.1496 - minute = self.minute
220.1497 - if second is None:
220.1498 - second = self.second
220.1499 - if microsecond is None:
220.1500 - microsecond = self.microsecond
220.1501 - if tzinfo is True:
220.1502 - tzinfo = self.tzinfo
220.1503 - _check_date_fields(year, month, day)
220.1504 - _check_time_fields(hour, minute, second, microsecond)
220.1505 - _check_tzinfo_arg(tzinfo)
220.1506 - return datetime(year, month, day, hour, minute, second,
220.1507 - microsecond, tzinfo)
220.1508 -
220.1509 - def astimezone(self, tz):
220.1510 - if not isinstance(tz, tzinfo):
220.1511 - raise TypeError("tz argument must be an instance of tzinfo")
220.1512 -
220.1513 - mytz = self.tzinfo
220.1514 - if mytz is None:
220.1515 - raise ValueError("astimezone() requires an aware datetime")
220.1516 -
220.1517 - if tz is mytz:
220.1518 - return self
220.1519 -
220.1520 - # Convert self to UTC, and attach the new time zone object.
220.1521 - myoffset = self.utcoffset()
220.1522 - if myoffset is None:
220.1523 - raise ValuError("astimezone() requires an aware datetime")
220.1524 - utc = (self - myoffset).replace(tzinfo=tz)
220.1525 -
220.1526 - # Convert from UTC to tz's local time.
220.1527 - return tz.fromutc(utc)
220.1528 -
220.1529 - # Ways to produce a string.
220.1530 -
220.1531 - def ctime(self):
220.1532 - "Format a la ctime()."
220.1533 - t = tmxxx(self.__year, self.__month, self.__day, self.__hour,
220.1534 - self.__minute, self.__second)
220.1535 - return t.ctime()
220.1536 -
220.1537 - def isoformat(self, sep='T'):
220.1538 - """Return the time formatted according to ISO.
220.1539 -
220.1540 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
220.1541 - self.microsecond == 0.
220.1542 -
220.1543 - If self.tzinfo is not None, the UTC offset is also attached, giving
220.1544 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
220.1545 -
220.1546 - Optional argument sep specifies the separator between date and
220.1547 - time, default 'T'.
220.1548 - """
220.1549 - s = ("%04d-%02d-%02d%c" % (self.__year, self.__month, self.__day,
220.1550 - sep) +
220.1551 - _format_time(self.__hour, self.__minute, self.__second,
220.1552 - self.__microsecond))
220.1553 - off = self._utcoffset()
220.1554 - if off is not None:
220.1555 - if off < 0:
220.1556 - sign = "-"
220.1557 - off = -off
220.1558 - else:
220.1559 - sign = "+"
220.1560 - hh, mm = divmod(off, 60)
220.1561 - s += "%s%02d:%02d" % (sign, hh, mm)
220.1562 - return s
220.1563 -
220.1564 - def __repr__(self):
220.1565 - "Convert to formal string, for repr()."
220.1566 - L = [self.__year, self.__month, self.__day, # These are never zero
220.1567 - self.__hour, self.__minute, self.__second, self.__microsecond]
220.1568 - if L[-1] == 0:
220.1569 - del L[-1]
220.1570 - if L[-1] == 0:
220.1571 - del L[-1]
220.1572 - s = ", ".join(map(str, L))
220.1573 - s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s)
220.1574 - if self._tzinfo is not None:
220.1575 - assert s[-1:] == ")"
220.1576 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
220.1577 - return s
220.1578 -
220.1579 - def __str__(self):
220.1580 - "Convert to string, for str()."
220.1581 - return self.isoformat(sep=' ')
220.1582 -
220.1583 - def utcoffset(self):
220.1584 - """Return the timezone offset in minutes east of UTC (negative west of
220.1585 - UTC)."""
220.1586 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
220.1587 - offset = _check_utc_offset("utcoffset", offset)
220.1588 - if offset is not None:
220.1589 - offset = timedelta(minutes=offset)
220.1590 - return offset
220.1591 -
220.1592 - # Return an integer (or None) instead of a timedelta (or None).
220.1593 - def _utcoffset(self):
220.1594 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
220.1595 - offset = _check_utc_offset("utcoffset", offset)
220.1596 - return offset
220.1597 -
220.1598 - def tzname(self):
220.1599 - """Return the timezone name.
220.1600 -
220.1601 - Note that the name is 100% informational -- there's no requirement that
220.1602 - it mean anything in particular. For example, "GMT", "UTC", "-500",
220.1603 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
220.1604 - """
220.1605 - name = _call_tzinfo_method(self._tzinfo, "tzname", self)
220.1606 - _check_tzname(name)
220.1607 - return name
220.1608 -
220.1609 - def dst(self):
220.1610 - """Return 0 if DST is not in effect, or the DST offset (in minutes
220.1611 - eastward) if DST is in effect.
220.1612 -
220.1613 - This is purely informational; the DST offset has already been added to
220.1614 - the UTC offset returned by utcoffset() if applicable, so there's no
220.1615 - need to consult dst() unless you're interested in displaying the DST
220.1616 - info.
220.1617 - """
220.1618 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
220.1619 - offset = _check_utc_offset("dst", offset)
220.1620 - if offset is not None:
220.1621 - offset = timedelta(minutes=offset)
220.1622 - return offset
220.1623 -
220.1624 - # Return an integer (or None) instead of a timedelta (or None).1573
220.1625 - def _dst(self):
220.1626 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
220.1627 - offset = _check_utc_offset("dst", offset)
220.1628 - return offset
220.1629 -
220.1630 - # Comparisons.
220.1631 -
220.1632 - def __eq__(self, other):
220.1633 - if isinstance(other, datetime):
220.1634 - return self.__cmp(other) == 0
220.1635 - elif hasattr(other, "timetuple"):
220.1636 - return NotImplemented
220.1637 - else:
220.1638 - return False
220.1639 -
220.1640 - def __ne__(self, other):
220.1641 - if isinstance(other, datetime):
220.1642 - return self.__cmp(other) != 0
220.1643 - elif hasattr(other, "timetuple"):
220.1644 - return NotImplemented
220.1645 - else:
220.1646 - return True
220.1647 -
220.1648 - def __le__(self, other):
220.1649 - if isinstance(other, datetime):
220.1650 - return self.__cmp(other) <= 0
220.1651 - elif hasattr(other, "timetuple"):
220.1652 - return NotImplemented
220.1653 - else:
220.1654 - _cmperror(self, other)
220.1655 -
220.1656 - def __lt__(self, other):
220.1657 - if isinstance(other, datetime):
220.1658 - return self.__cmp(other) < 0
220.1659 - elif hasattr(other, "timetuple"):
220.1660 - return NotImplemented
220.1661 - else:
220.1662 - _cmperror(self, other)
220.1663 -
220.1664 - def __ge__(self, other):
220.1665 - if isinstance(other, datetime):
220.1666 - return self.__cmp(other) >= 0
220.1667 - elif hasattr(other, "timetuple"):
220.1668 - return NotImplemented
220.1669 - else:
220.1670 - _cmperror(self, other)
220.1671 -
220.1672 - def __gt__(self, other):
220.1673 - if isinstance(other, datetime):
220.1674 - return self.__cmp(other) > 0
220.1675 - elif hasattr(other, "timetuple"):
220.1676 - return NotImplemented
220.1677 - else:
220.1678 - _cmperror(self, other)
220.1679 -
220.1680 - def __cmp(self, other):
220.1681 - assert isinstance(other, datetime)
220.1682 - mytz = self._tzinfo
220.1683 - ottz = other._tzinfo
220.1684 - myoff = otoff = None
220.1685 -
220.1686 - if mytz is ottz:
220.1687 - base_compare = True
220.1688 - else:
220.1689 - if mytz is not None:
220.1690 - myoff = self._utcoffset()
220.1691 - if ottz is not None:
220.1692 - otoff = other._utcoffset()
220.1693 - base_compare = myoff == otoff
220.1694 -
220.1695 - if base_compare:
220.1696 - return cmp((self.__year, self.__month, self.__day,
220.1697 - self.__hour, self.__minute, self.__second,
220.1698 - self.__microsecond),
220.1699 - (other.__year, other.__month, other.__day,
220.1700 - other.__hour, other.__minute, other.__second,
220.1701 - other.__microsecond))
220.1702 - if myoff is None or otoff is None:
220.1703 - # XXX Buggy in 2.2.2.
220.1704 - raise TypeError("cannot compare naive and aware datetimes")
220.1705 - # XXX What follows could be done more efficiently...
220.1706 - diff = self - other # this will take offsets into account
220.1707 - if diff.days < 0:
220.1708 - return -1
220.1709 - return diff and 1 or 0
220.1710 -
220.1711 - def __add__(self, other):
220.1712 - "Add a datetime and a timedelta."
220.1713 - if not isinstance(other, timedelta):
220.1714 - return NotImplemented
220.1715 - t = tmxxx(self.__year,
220.1716 - self.__month,
220.1717 - self.__day + other.days,
220.1718 - self.__hour,
220.1719 - self.__minute,
220.1720 - self.__second + other.seconds,
220.1721 - self.__microsecond + other.microseconds)
220.1722 - self._checkOverflow(t.year)
220.1723 - result = self.__class__(t.year, t.month, t.day,
220.1724 - t.hour, t.minute, t.second,
220.1725 - t.microsecond, tzinfo=self._tzinfo)
220.1726 - return result
220.1727 -
220.1728 - __radd__ = __add__
220.1729 -
220.1730 - def __sub__(self, other):
220.1731 - "Subtract two datetimes, or a datetime and a timedelta."
220.1732 - if not isinstance(other, datetime):
220.1733 - if isinstance(other, timedelta):
220.1734 - return self + -other
220.1735 - return NotImplemented
220.1736 -
220.1737 - days1 = self.toordinal()
220.1738 - days2 = other.toordinal()
220.1739 - secs1 = self.__second + self.__minute * 60 + self.__hour * 3600
220.1740 - secs2 = other.__second + other.__minute * 60 + other.__hour * 3600
220.1741 - base = timedelta(days1 - days2,
220.1742 - secs1 - secs2,
220.1743 - self.__microsecond - other.__microsecond)
220.1744 - if self._tzinfo is other._tzinfo:
220.1745 - return base
220.1746 - myoff = self._utcoffset()
220.1747 - otoff = other._utcoffset()
220.1748 - if myoff == otoff:
220.1749 - return base
220.1750 - if myoff is None or otoff is None:
220.1751 - raise TypeError, "cannot mix naive and timezone-aware time"
220.1752 - return base + timedelta(minutes = otoff-myoff)
220.1753 -
220.1754 - def __hash__(self):
220.1755 - tzoff = self._utcoffset()
220.1756 - if tzoff is None:
220.1757 - return hash(self.__getstate()[0])
220.1758 - days = _ymd2ord(self.year, self.month, self.day)
220.1759 - seconds = self.hour * 3600 + (self.minute - tzoff) * 60 + self.second
220.1760 - return hash(timedelta(days, seconds, self.microsecond))
220.1761 -
220.1762 - # Pickle support.
220.1763 -
220.1764 - __safe_for_unpickling__ = True # For Python 2.2
220.1765 -
220.1766 - def __getstate(self):
220.1767 - yhi, ylo = divmod(self.__year, 256)
220.1768 - us2, us3 = divmod(self.__microsecond, 256)
220.1769 - us1, us2 = divmod(us2, 256)
220.1770 - basestate = ("%c" * 10) % (yhi, ylo, self.__month, self.__day,
220.1771 - self.__hour, self.__minute, self.__second,
220.1772 - us1, us2, us3)
220.1773 - if self._tzinfo is None:
220.1774 - return (basestate,)
220.1775 - else:
220.1776 - return (basestate, self._tzinfo)
220.1777 -
220.1778 - def __setstate(self, state):
220.1779 - assert isinstance(state, tuple)
220.1780 - assert 1 <= len(state) <= 2
220.1781 - string = state[0]
220.1782 - assert len(string) == 10
220.1783 - (yhi, ylo, self.__month, self.__day, self.__hour,
220.1784 - self.__minute, self.__second, us1, us2, us3) = map(ord, string)
220.1785 - self.__year = yhi * 256 + ylo
220.1786 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
220.1787 - if len(state) == 1:
220.1788 - self._tzinfo = None
220.1789 - else:
220.1790 - self._tzinfo = state[1]
220.1791 -
220.1792 - def __reduce__(self):
220.1793 - return (self.__class__, self.__getstate())
220.1794 -
220.1795 -
220.1796 -datetime.min = datetime(1, 1, 1)
220.1797 -datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
220.1798 -datetime.resolution = timedelta(microseconds=1)
220.1799 -
220.1800 -
220.1801 -def _isoweek1monday(year):
220.1802 - # Helper to calculate the day number of the Monday starting week 1
220.1803 - # XXX This could be done more efficiently
220.1804 - THURSDAY = 3
220.1805 - firstday = _ymd2ord(year, 1, 1)
220.1806 - firstweekday = (firstday + 6) % 7 # See weekday() above
220.1807 - week1monday = firstday - firstweekday
220.1808 - if firstweekday > THURSDAY:
220.1809 - week1monday += 7
220.1810 - return week1monday
220.1811 -
220.1812 -"""
220.1813 -Some time zone algebra. For a datetime x, let
220.1814 - x.n = x stripped of its timezone -- its naive time.
220.1815 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
220.1816 - return None
220.1817 - x.d = x.dst(), and assuming that doesn't raise an exception or
220.1818 - return None
220.1819 - x.s = x's standard offset, x.o - x.d
220.1820 -
220.1821 -Now some derived rules, where k is a duration (timedelta).
220.1822 -
220.1823 -1. x.o = x.s + x.d
220.1824 - This follows from the definition of x.s.
220.1825 -
220.1826 -2. If x and y have the same tzinfo member, x.s = y.s.
220.1827 - This is actually a requirement, an assumption we need to make about
220.1828 - sane tzinfo classes.
220.1829 -
220.1830 -3. The naive UTC time corresponding to x is x.n - x.o.
220.1831 - This is again a requirement for a sane tzinfo class.
220.1832 -
220.1833 -4. (x+k).s = x.s
220.1834 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
220.1835 -
220.1836 -5. (x+k).n = x.n + k
220.1837 - Again follows from how arithmetic is defined.
220.1838 -
220.1839 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
220.1840 -(meaning that the various tzinfo methods exist, and don't blow up or return
220.1841 -None when called).
220.1842 -
220.1843 -The function wants to return a datetime y with timezone tz, equivalent to x.
220.1844 -x is already in UTC.
220.1845 -
220.1846 -By #3, we want
220.1847 -
220.1848 - y.n - y.o = x.n [1]
220.1849 -
220.1850 -The algorithm starts by attaching tz to x.n, and calling that y. So
220.1851 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
220.1852 -becomes true; in effect, we want to solve [2] for k:
220.1853 -
220.1854 - (y+k).n - (y+k).o = x.n [2]
220.1855 -
220.1856 -By #1, this is the same as
220.1857 -
220.1858 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
220.1859 -
220.1860 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
220.1861 -Substituting that into [3],
220.1862 -
220.1863 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
220.1864 - k - (y+k).s - (y+k).d = 0; rearranging,
220.1865 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
220.1866 - k = y.s - (y+k).d
220.1867 -
220.1868 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
220.1869 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
220.1870 -very large, since all offset-returning methods return a duration of magnitude
220.1871 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
220.1872 -be 0, so ignoring it has no consequence then.
220.1873 -
220.1874 -In any case, the new value is
220.1875 -
220.1876 - z = y + y.s [4]
220.1877 -
220.1878 -It's helpful to step back at look at [4] from a higher level: it's simply
220.1879 -mapping from UTC to tz's standard time.
220.1880 -
220.1881 -At this point, if
220.1882 -
220.1883 - z.n - z.o = x.n [5]
220.1884 -
220.1885 -we have an equivalent time, and are almost done. The insecurity here is
220.1886 -at the start of daylight time. Picture US Eastern for concreteness. The wall
220.1887 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
220.1888 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
220.1889 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
220.1890 -on the day DST starts. We want to return the 1:MM EST spelling because that's
220.1891 -the only spelling that makes sense on the local wall clock.
220.1892 -
220.1893 -In fact, if [5] holds at this point, we do have the standard-time spelling,
220.1894 -but that takes a bit of proof. We first prove a stronger result. What's the
220.1895 -difference between the LHS and RHS of [5]? Let
220.1896 -
220.1897 - diff = x.n - (z.n - z.o) [6]
220.1898 -
220.1899 -Now
220.1900 - z.n = by [4]
220.1901 - (y + y.s).n = by #5
220.1902 - y.n + y.s = since y.n = x.n
220.1903 - x.n + y.s = since z and y are have the same tzinfo member,
220.1904 - y.s = z.s by #2
220.1905 - x.n + z.s
220.1906 -
220.1907 -Plugging that back into [6] gives
220.1908 -
220.1909 - diff =
220.1910 - x.n - ((x.n + z.s) - z.o) = expanding
220.1911 - x.n - x.n - z.s + z.o = cancelling
220.1912 - - z.s + z.o = by #2
220.1913 - z.d
220.1914 -
220.1915 -So diff = z.d.
220.1916 -
220.1917 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
220.1918 -spelling we wanted in the endcase described above. We're done. Contrarily,
220.1919 -if z.d = 0, then we have a UTC equivalent, and are also done.
220.1920 -
220.1921 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
220.1922 -add to z (in effect, z is in tz's standard time, and we need to shift the
220.1923 -local clock into tz's daylight time).
220.1924 -
220.1925 -Let
220.1926 -
220.1927 - z' = z + z.d = z + diff [7]
220.1928 -
220.1929 -and we can again ask whether
220.1930 -
220.1931 - z'.n - z'.o = x.n [8]
220.1932 -
220.1933 -If so, we're done. If not, the tzinfo class is insane, according to the
220.1934 -assumptions we've made. This also requires a bit of proof. As before, let's
220.1935 -compute the difference between the LHS and RHS of [8] (and skipping some of
220.1936 -the justifications for the kinds of substitutions we've done several times
220.1937 -already):
220.1938 -
220.1939 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
220.1940 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
220.1941 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
220.1942 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
220.1943 - - z.n + z.n - z.o + z'.o = cancel z.n
220.1944 - - z.o + z'.o = #1 twice
220.1945 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
220.1946 - z'.d - z.d
220.1947 -
220.1948 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
220.1949 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
220.1950 -return z', not bothering to compute z'.d.
220.1951 -
220.1952 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
220.1953 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
220.1954 -would have to change the result dst() returns: we start in DST, and moving
220.1955 -a little further into it takes us out of DST.
220.1956 -
220.1957 -There isn't a sane case where this can happen. The closest it gets is at
220.1958 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
220.1959 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
220.1960 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
220.1961 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
220.1962 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
220.1963 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
220.1964 -standard time. Since that's what the local clock *does*, we want to map both
220.1965 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
220.1966 -in local time, but so it goes -- it's the way the local clock works.
220.1967 -
220.1968 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
220.1969 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
220.1970 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
220.1971 -(correctly) concludes that z' is not UTC-equivalent to x.
220.1972 -
220.1973 -Because we know z.d said z was in daylight time (else [5] would have held and
220.1974 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
220.1975 -and we we have stopped then), and there are only 2 possible values dst() can
220.1976 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
220.1977 -but the reasoning doesn't depend on the example -- it depends on there being
220.1978 -two possible dst() outcomes, one zero and the other non-zero). Therefore
220.1979 -z' must be in standard time, and is the spelling we want in this case.
220.1980 -
220.1981 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
220.1982 -concerned (because it takes z' as being in standard time rather than the
220.1983 -daylight time we intend here), but returning it gives the real-life "local
220.1984 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
220.1985 -tz.
220.1986 -
220.1987 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
220.1988 -the 1:MM standard time spelling we want.
220.1989 -
220.1990 -So how can this break? One of the assumptions must be violated. Two
220.1991 -possibilities:
220.1992 -
220.1993 -1) [2] effectively says that y.s is invariant across all y belong to a given
220.1994 - time zone. This isn't true if, for political reasons or continental drift,
220.1995 - a region decides to change its base offset from UTC.
220.1996 -
220.1997 -2) There may be versions of "double daylight" time where the tail end of
220.1998 - the analysis gives up a step too early. I haven't thought about that
220.1999 - enough to say.
220.2000 -
220.2001 -In any case, it's clear that the default fromutc() is strong enough to handle
220.2002 -"almost all" time zones: so long as the standard offset is invariant, it
220.2003 -doesn't matter if daylight time transition points change from year to year, or
220.2004 -if daylight time is skipped in some years; it doesn't matter how large or
220.2005 -small dst() may get within its bounds; and it doesn't even matter if some
220.2006 -perverse time zone returns a negative dst()). So a breaking case must be
220.2007 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
220.2008 -"""
220.2009 -
220.2010 -def _test():
220.2011 - import test_datetime
220.2012 - test_datetime.test_main()
220.2013 -
220.2014 -if __name__ == "__main__":
220.2015 - _test()
221.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testFix5.fixed Sun Jan 04 13:11:53 2015 -0600
221.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
221.3 @@ -1,2011 +0,0 @@
221.4 -"""Concrete date/time and related types -- prototype implemented in Python.
221.5 -
221.6 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
221.7 -
221.8 -See also http://dir.yahoo.com/Reference/calendars/
221.9 -
221.10 -For a primer on DST, including many current DST rules, see
221.11 -http://webexhibits.org/daylightsaving/
221.12 -
221.13 -For more about DST than you ever wanted to know, see
221.14 -ftp://elsie.nci.nih.gov/pub/
221.15 -
221.16 -Sources for time zone and DST data: http://www.twinsun.com/tz/tz-link.htm
221.17 -
221.18 -"""
221.19 -
221.20 -import time as _time
221.21 -import math as _math
221.22 -
221.23 -MINYEAR = 1
221.24 -MAXYEAR = 9999
221.25 -
221.26 -# Utility functions, adapted from Python's Demo/classes/Dates.py, which
221.27 -# also assumes the current Gregorian calendar indefinitely extended in
221.28 -# both directions. Difference: Dates.py calls January 1 of year 0 day
221.29 -# number 1. The code here calls January 1 of year 1 day number 1. This is
221.30 -# to match the definition of the "proleptic Gregorian" calendar in Dershowitz
221.31 -# and Reingold's "Calendrical Calculations", where it's the base calendar
221.32 -# for all computations. See the book for algorithms for converting between
221.33 -# proleptic Gregorian ordinals and many other calendar systems.
221.34 -
221.35 -_DAYS_IN_MONTH = [None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
221.36 -
221.37 -_DAYS_BEFORE_MONTH = [None]
221.38 -dbm = 0
221.39 -for dim in _DAYS_IN_MONTH[1:]:
221.40 - _DAYS_BEFORE_MONTH.append(dbm)
221.41 - dbm += dim
221.42 -del dbm, dim
221.43 -
221.44 -def _is_leap(year):
221.45 - "year -> 1 if leap year, else 0."
221.46 - return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
221.47 -
221.48 -def _days_in_year(year):
221.49 - "year -> number of days in year (366 if a leap year, else 365)."
221.50 - return 365 + _is_leap(year)
221.51 -
221.52 -def _days_before_year(year):
221.53 - "year -> number of days before January 1st of year."
221.54 - y = year - 1
221.55 - return y*365 + y//4 - y//100 + y//400
221.56 -
221.57 -def _days_in_month(year, month):
221.58 - "year, month -> number of days in that month in that year."
221.59 - assert 1 <= month <= 12, month
221.60 - if month == 2 and _is_leap(year):
221.61 - return 29
221.62 - return _DAYS_IN_MONTH[month]
221.63 -
221.64 -def _days_before_month(year, month):
221.65 - "year, month -> number of days in year preceeding first day of month."
221.66 - if not 1 <= month <= 12:
221.67 - raise ValueError('month must be in 1..12', month)
221.68 - return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
221.69 -
221.70 -def _ymd2ord(year, month, day):
221.71 - "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
221.72 - if not 1 <= month <= 12:
221.73 - raise ValueError('month must be in 1..12', month)
221.74 - dim = _days_in_month(year, month)
221.75 - if not 1 <= day <= dim:
221.76 - raise ValueError('day must be in 1..%d' % dim, day)
221.77 - return (_days_before_year(year) +
221.78 - _days_before_month(year, month) +
221.79 - day)
221.80 -
221.81 -try:
221.82 - _DI400Y = _days_before_year(401) # number of days in 400 years
221.83 - _DI100Y = _days_before_year(101) # " " " " 100 "
221.84 -finally:
221.85 -
221.86 -_DI4Y = _days_before_year(5) # " " " " 4 "
221.87 -
221.88 -# A 4-year cycle has an extra leap day over what we'd get from pasting
221.89 -# together 4 single years.
221.90 -assert _DI4Y == 4 * 365 + 1
221.91 -
221.92 -# Similarly, a 400-year cycle has an extra leap day over what we'd get from
221.93 -# pasting together 4 100-year cycles.
221.94 -assert _DI400Y == 4 * _DI100Y + 1
221.95 -
221.96 -# OTOH, a 100-year cycle has one fewer leap day than we'd get from
221.97 -# pasting together 25 4-year cycles.
221.98 -assert _DI100Y == 25 * _DI4Y - 1
221.99 -
221.100 -def _ord2ymd(n):
221.101 - "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
221.102 -
221.103 - # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
221.104 - # repeats exactly every 400 years. The basic strategy is to find the
221.105 - # closest 400-year boundary at or before n, then work with the offset
221.106 - # from that boundary to n. Life is much clearer if we subtract 1 from
221.107 - # n first -- then the values of n at 400-year boundaries are exactly
221.108 - # those divisible by _DI400Y:
221.109 - #
221.110 - # D M Y n n-1
221.111 - # -- --- ---- ---------- ----------------
221.112 - # 31 Dec -400 -_DI400Y -_DI400Y -1
221.113 - # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
221.114 - # ...
221.115 - # 30 Dec 000 -1 -2
221.116 - # 31 Dec 000 0 -1
221.117 - # 1 Jan 001 1 0 400-year boundary
221.118 - # 2 Jan 001 2 1
221.119 - # 3 Jan 001 3 2
221.120 - # ...
221.121 - # 31 Dec 400 _DI400Y _DI400Y -1
221.122 - # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
221.123 - n -= 1
221.124 - n400, n = divmod(n, _DI400Y)
221.125 - year = n400 * 400 + 1 # ..., -399, 1, 401, ...
221.126 -
221.127 - # Now n is the (non-negative) offset, in days, from January 1 of year, to
221.128 - # the desired date. Now compute how many 100-year cycles precede n.
221.129 - # Note that it's possible for n100 to equal 4! In that case 4 full
221.130 - # 100-year cycles precede the desired day, which implies the desired
221.131 - # day is December 31 at the end of a 400-year cycle.
221.132 - n100, n = divmod(n, _DI100Y)
221.133 -
221.134 - # Now compute how many 4-year cycles precede it.
221.135 - n4, n = divmod(n, _DI4Y)
221.136 -
221.137 - # And now how many single years. Again n1 can be 4, and again meaning
221.138 - # that the desired day is December 31 at the end of the 4-year cycle.
221.139 - n1, n = divmod(n, 365)
221.140 -
221.141 - year += n100 * 100 + n4 * 4 + n1
221.142 - if n1 == 4 or n100 == 4:
221.143 - assert n == 0
221.144 - return year-1, 12, 31
221.145 -
221.146 - # Now the year is correct, and n is the offset from January 1. We find
221.147 - # the month via an estimate that's either exact or one too large.
221.148 - leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
221.149 - assert leapyear == _is_leap(year)
221.150 - month = (n + 50) >> 5
221.151 - preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
221.152 - if preceding > n: # estimate is too large
221.153 - month -= 1
221.154 - preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
221.155 - n -= preceding
221.156 - assert 0 <= n < _days_in_month(year, month)
221.157 -
221.158 - # Now the year and month are correct, and n is the offset from the
221.159 - # start of that month: we're done!
221.160 - return year, month, n+1
221.161 -
221.162 -# Month and day names. For localized versions, see the calendar module.
221.163 -_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
221.164 - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
221.165 -_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
221.166 -
221.167 -
221.168 -def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
221.169 - wday = (_ymd2ord(y, m, d) + 6) % 7
221.170 - dnum = _days_before_month(y, m) + d
221.171 - return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
221.172 -
221.173 -def _format_time(hh, mm, ss, us):
221.174 - # Skip trailing microseconds when us==0.
221.175 - result = "%02d:%02d:%02d" % (hh, mm, ss)
221.176 - if us:
221.177 - result += ".%06d" % us
221.178 - return result
221.179 -
221.180 -# Correctly substitute for %z and %Z escapes in strftime formats.
221.181 -def _wrap_strftime(object, format, timetuple):
221.182 - year = timetuple[0]
221.183 - if year < 1900:
221.184 - raise ValueError("year=%d is before 1900; the datetime strftime() "
221.185 - "methods require year >= 1900" % year)
221.186 - # Don't call _utcoffset() or tzname() unless actually needed.
221.187 - zreplace = None # the string to use for %z
221.188 - Zreplace = None # the string to use for %Z
221.189 -
221.190 - # Scan format for %z and %Z escapes, replacing as needed.
221.191 - newformat = []
221.192 - push = newformat.append
221.193 - i, n = 0, len(format)
221.194 - while i < n:
221.195 - ch = format[i]
221.196 - i += 1
221.197 - if ch == '%':
221.198 - if i < n:
221.199 - ch = format[i]
221.200 - i += 1
221.201 - if ch == 'z':
221.202 - if zreplace is None:
221.203 - zreplace = ""
221.204 - if hasattr(object, "_utcoffset"):
221.205 - offset = object._utcoffset()
221.206 - if offset is not None:
221.207 - sign = '+'
221.208 - if offset < 0:
221.209 - offset = -offset
221.210 - sign = '-'
221.211 - h, m = divmod(offset, 60)
221.212 - zreplace = '%c%02d%02d' % (sign, h, m)
221.213 - assert '%' not in zreplace
221.214 - newformat.append(zreplace)
221.215 - elif ch == 'Z':
221.216 - if Zreplace is None:
221.217 - Zreplace = ""
221.218 - if hasattr(object, "tzname"):
221.219 - s = object.tzname()
221.220 - if s is not None:
221.221 - # strftime is going to have at this: escape %
221.222 - Zreplace = s.replace('%', '%%')
221.223 - newformat.append(Zreplace)
221.224 - else:
221.225 - push('%')
221.226 - push(ch)
221.227 - else:
221.228 - push('%')
221.229 - else:
221.230 - push(ch)
221.231 - newformat = "".join(newformat)
221.232 - return _time.strftime(newformat, timetuple)
221.233 -
221.234 -def _call_tzinfo_method(tzinfo, methname, tzinfoarg):
221.235 - if tzinfo is None:
221.236 - return None
221.237 - return getattr(tzinfo, methname)(tzinfoarg)
221.238 -
221.239 -# Just raise TypeError if the arg isn't None or a string.
221.240 -def _check_tzname(name):
221.241 - if name is not None and not isinstance(name, str):
221.242 - raise TypeError("tzinfo.tzname() must return None or string, "
221.243 - "not '%s'" % type(name))
221.244 -
221.245 -# name is the offset-producing method, "utcoffset" or "dst".
221.246 -# offset is what it returned.
221.247 -# If offset isn't None or timedelta, raises TypeError.
221.248 -# If offset is None, returns None.
221.249 -# Else offset is checked for being in range, and a whole # of minutes.
221.250 -# If it is, its integer value is returned. Else ValueError is raised.
221.251 -def _check_utc_offset(name, offset):
221.252 - assert name in ("utcoffset", "dst")
221.253 - if offset is None:
221.254 - return None
221.255 - if not isinstance(offset, timedelta):
221.256 - raise TypeError("tzinfo.%s() must return None "
221.257 - "or timedelta, not '%s'" % (name, type(offset)))
221.258 - days = offset.days
221.259 - if days < -1 or days > 0:
221.260 - offset = 1440 # trigger out-of-range
221.261 - else:
221.262 - seconds = days * 86400 + offset.seconds
221.263 - minutes, seconds = divmod(seconds, 60)
221.264 - if seconds or offset.microseconds:
221.265 - raise ValueError("tzinfo.%s() must return a whole number "
221.266 - "of minutes" % name)
221.267 - offset = minutes
221.268 - if -1440 < offset < 1440:
221.269 - return offset
221.270 - raise ValueError("%s()=%d, must be in -1439..1439" % (name, offset))
221.271 -
221.272 -def _check_date_fields(year, month, day):
221.273 - if not MINYEAR <= year <= MAXYEAR:
221.274 - raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
221.275 - if not 1 <= month <= 12:
221.276 - raise ValueError('month must be in 1..12', month)
221.277 - dim = _days_in_month(year, month)
221.278 - if not 1 <= day <= dim:
221.279 - raise ValueError('day must be in 1..%d' % dim, day)
221.280 -
221.281 -def _check_time_fields(hour, minute, second, microsecond):
221.282 - if not 0 <= hour <= 23:
221.283 - raise ValueError('hour must be in 0..23', hour)
221.284 - if not 0 <= minute <= 59:
221.285 - raise ValueError('minute must be in 0..59', minute)
221.286 - if not 0 <= second <= 59:
221.287 - raise ValueError('second must be in 0..59', second)
221.288 - if not 0 <= microsecond <= 999999:
221.289 - raise ValueError('microsecond must be in 0..999999', microsecond)
221.290 -
221.291 -def _check_tzinfo_arg(tz):
221.292 - if tz is not None and not isinstance(tz, tzinfo):
221.293 - raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
221.294 -
221.295 -
221.296 -# Notes on comparison: In general, datetime module comparison operators raise
221.297 -# TypeError when they don't know how to do a comparison themself. If they
221.298 -# returned NotImplemented instead, comparison could (silently) fall back to
221.299 -# the default compare-objects-by-comparing-their-memory-addresses strategy,
221.300 -# and that's not helpful. There are two exceptions:
221.301 -#
221.302 -# 1. For date and datetime, if the other object has a "timetuple" attr,
221.303 -# NotImplemented is returned. This is a hook to allow other kinds of
221.304 -# datetime-like objects a chance to intercept the comparison.
221.305 -#
221.306 -# 2. Else __eq__ and __ne__ return False and True, respectively. This is
221.307 -# so opertaions like
221.308 -#
221.309 -# x == y
221.310 -# x != y
221.311 -# x in sequence
221.312 -# x not in sequence
221.313 -# dict[x] = y
221.314 -#
221.315 -# don't raise annoying TypeErrors just because a datetime object
221.316 -# is part of a heterogeneous collection. If there's no known way to
221.317 -# compare X to a datetime, saying they're not equal is reasonable.
221.318 -
221.319 -def _cmperror(x, y):
221.320 - raise TypeError("can't compare '%s' to '%s'" % (
221.321 - type(x).__name__, type(y).__name__))
221.322 -
221.323 -# This is a start at a struct tm workalike. Goals:
221.324 -#
221.325 -# + Works the same way across platforms.
221.326 -# + Handles all the fields datetime needs handled, without 1970-2038 glitches.
221.327 -#
221.328 -# Note: I suspect it's best if this flavor of tm does *not* try to
221.329 -# second-guess timezones or DST. Instead fold whatever adjustments you want
221.330 -# into the minutes argument (and the constructor will normalize).
221.331 -
221.332 -_ORD1970 = _ymd2ord(1970, 1, 1) # base ordinal for UNIX epoch
221.333 -
221.334 -class tmxxx:
221.335 -
221.336 - ordinal = None
221.337 -
221.338 - def __init__(self, year, month, day, hour=0, minute=0, second=0,
221.339 - microsecond=0):
221.340 - # Normalize all the inputs, and store the normalized values.
221.341 - if not 0 <= microsecond <= 999999:
221.342 - carry, microsecond = divmod(microsecond, 1000000)
221.343 - second += carry
221.344 - if not 0 <= second <= 59:
221.345 - carry, second = divmod(second, 60)
221.346 - minute += carry
221.347 - if not 0 <= minute <= 59:
221.348 - carry, minute = divmod(minute, 60)
221.349 - hour += carry
221.350 - if not 0 <= hour <= 23:
221.351 - carry, hour = divmod(hour, 24)
221.352 - day += carry
221.353 -
221.354 - # That was easy. Now it gets muddy: the proper range for day
221.355 - # can't be determined without knowing the correct month and year,
221.356 - # but if day is, e.g., plus or minus a million, the current month
221.357 - # and year values make no sense (and may also be out of bounds
221.358 - # themselves).
221.359 - # Saying 12 months == 1 year should be non-controversial.
221.360 - if not 1 <= month <= 12:
221.361 - carry, month = divmod(month-1, 12)
221.362 - year += carry
221.363 - month += 1
221.364 - assert 1 <= month <= 12
221.365 -
221.366 - # Now only day can be out of bounds (year may also be out of bounds
221.367 - # for a datetime object, but we don't care about that here).
221.368 - # If day is out of bounds, what to do is arguable, but at least the
221.369 - # method here is principled and explainable.
221.370 - dim = _days_in_month(year, month)
221.371 - if not 1 <= day <= dim:
221.372 - # Move day-1 days from the first of the month. First try to
221.373 - # get off cheap if we're only one day out of range (adjustments
221.374 - # for timezone alone can't be worse than that).
221.375 - if day == 0: # move back a day
221.376 - month -= 1
221.377 - if month > 0:
221.378 - day = _days_in_month(year, month)
221.379 - else:
221.380 - year, month, day = year-1, 12, 31
221.381 - elif day == dim + 1: # move forward a day
221.382 - month += 1
221.383 - day = 1
221.384 - if month > 12:
221.385 - month = 1
221.386 - year += 1
221.387 - else:
221.388 - self.ordinal = _ymd2ord(year, month, 1) + (day - 1)
221.389 - year, month, day = _ord2ymd(self.ordinal)
221.390 -
221.391 - self.year, self.month, self.day = year, month, day
221.392 - self.hour, self.minute, self.second = hour, minute, second
221.393 - self.microsecond = microsecond
221.394 -
221.395 - def toordinal(self):
221.396 - """Return proleptic Gregorian ordinal for the year, month and day.
221.397 -
221.398 - January 1 of year 1 is day 1. Only the year, month and day values
221.399 - contribute to the result.
221.400 - """
221.401 - if self.ordinal is None:
221.402 - self.ordinal = _ymd2ord(self.year, self.month, self.day)
221.403 - return self.ordinal
221.404 -
221.405 - def time(self):
221.406 - "Return Unixish timestamp, as a float (assuming UTC)."
221.407 - days = self.toordinal() - _ORD1970 # convert to UNIX epoch
221.408 - seconds = ((days * 24. + self.hour)*60. + self.minute)*60.
221.409 - return seconds + self.second + self.microsecond / 1e6
221.410 -
221.411 - def ctime(self):
221.412 - "Return ctime() style string."
221.413 - weekday = self.toordinal() % 7 or 7
221.414 - return "%s %s %2d %02d:%02d:%02d %04d" % (
221.415 - _DAYNAMES[weekday],
221.416 - _MONTHNAMES[self.month],
221.417 - self.day,
221.418 - self.hour, self.minute, self.second,
221.419 - self.year)
221.420 -
221.421 -class timedelta(object):
221.422 - """Represent the difference between two datetime objects.
221.423 -
221.424 - Supported operators:
221.425 -
221.426 - - add, subtract timedelta
221.427 - - unary plus, minus, abs
221.428 - - compare to timedelta
221.429 - - multiply, divide by int/long
221.430 -
221.431 - In addition, datetime supports subtraction of two datetime objects
221.432 - returning a timedelta, and addition or subtraction of a datetime
221.433 - and a timedelta giving a datetime.
221.434 -
221.435 - Representation: (days, seconds, microseconds). Why? Because I
221.436 - felt like it.
221.437 - """
221.438 -
221.439 - def __new__(cls, days=0, seconds=0, microseconds=0,
221.440 - # XXX The following should only be used as keyword args:
221.441 - milliseconds=0, minutes=0, hours=0, weeks=0):
221.442 - # Doing this efficiently and accurately in C is going to be difficult
221.443 - # and error-prone, due to ubiquitous overflow possibilities, and that
221.444 - # C double doesn't have enough bits of precision to represent
221.445 - # microseconds over 10K years faithfully. The code here tries to make
221.446 - # explicit where go-fast assumptions can be relied on, in order to
221.447 - # guide the C implementation; it's way more convoluted than speed-
221.448 - # ignoring auto-overflow-to-long idiomatic Python could be.
221.449 -
221.450 - # XXX Check that all inputs are ints, longs or floats.
221.451 -
221.452 - # Final values, all integer.
221.453 - # s and us fit in 32-bit signed ints; d isn't bounded.
221.454 - d = s = us = 0
221.455 -
221.456 - # Normalize everything to days, seconds, microseconds.
221.457 - days += weeks*7
221.458 - seconds += minutes*60 + hours*3600
221.459 - microseconds += milliseconds*1000
221.460 -
221.461 - # Get rid of all fractions, and normalize s and us.
221.462 - # Take a deep breath <wink>.
221.463 - if isinstance(days, float):
221.464 - dayfrac, days = _math.modf(days)
221.465 - daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
221.466 - assert daysecondswhole == int(daysecondswhole) # can't overflow
221.467 - s = int(daysecondswhole)
221.468 - assert days == long(days)
221.469 - d = long(days)
221.470 - else:
221.471 - daysecondsfrac = 0.0
221.472 - d = days
221.473 - assert isinstance(daysecondsfrac, float)
221.474 - assert abs(daysecondsfrac) <= 1.0
221.475 - assert isinstance(d, (int, long))
221.476 - assert abs(s) <= 24 * 3600
221.477 - # days isn't referenced again before redefinition
221.478 -
221.479 - if isinstance(seconds, float):
221.480 - secondsfrac, seconds = _math.modf(seconds)
221.481 - assert seconds == long(seconds)
221.482 - seconds = long(seconds)
221.483 - secondsfrac += daysecondsfrac
221.484 - assert abs(secondsfrac) <= 2.0
221.485 - else:
221.486 - secondsfrac = daysecondsfrac
221.487 - # daysecondsfrac isn't referenced again
221.488 - assert isinstance(secondsfrac, float)
221.489 - assert abs(secondsfrac) <= 2.0
221.490 -
221.491 - assert isinstance(seconds, (int, long))
221.492 - days, seconds = divmod(seconds, 24*3600)
221.493 - d += days
221.494 - s += int(seconds) # can't overflow
221.495 - assert isinstance(s, int)
221.496 - assert abs(s) <= 2 * 24 * 3600
221.497 - # seconds isn't referenced again before redefinition
221.498 -
221.499 - usdouble = secondsfrac * 1e6
221.500 - assert abs(usdouble) < 2.1e6 # exact value not critical
221.501 - # secondsfrac isn't referenced again
221.502 -
221.503 - if isinstance(microseconds, float):
221.504 - microseconds += usdouble
221.505 - microseconds = round(microseconds)
221.506 - seconds, microseconds = divmod(microseconds, 1e6)
221.507 - assert microseconds == int(microseconds)
221.508 - assert seconds == long(seconds)
221.509 - days, seconds = divmod(seconds, 24.*3600.)
221.510 - assert days == long(days)
221.511 - assert seconds == int(seconds)
221.512 - d += long(days)
221.513 - s += int(seconds) # can't overflow
221.514 - assert isinstance(s, int)
221.515 - assert abs(s) <= 3 * 24 * 3600
221.516 - else:
221.517 - seconds, microseconds = divmod(microseconds, 1000000)
221.518 - days, seconds = divmod(seconds, 24*3600)
221.519 - d += days
221.520 - s += int(seconds) # can't overflow
221.521 - assert isinstance(s, int)
221.522 - assert abs(s) <= 3 * 24 * 3600
221.523 - microseconds = float(microseconds)
221.524 - microseconds += usdouble
221.525 - microseconds = round(microseconds)
221.526 - assert abs(s) <= 3 * 24 * 3600
221.527 - assert abs(microseconds) < 3.1e6
221.528 -
221.529 - # Just a little bit of carrying possible for microseconds and seconds.
221.530 - assert isinstance(microseconds, float)
221.531 - assert int(microseconds) == microseconds
221.532 - us = int(microseconds)
221.533 - seconds, us = divmod(us, 1000000)
221.534 - s += seconds # cant't overflow
221.535 - assert isinstance(s, int)
221.536 - days, s = divmod(s, 24*3600)
221.537 - d += days
221.538 -
221.539 - assert isinstance(d, (int, long))
221.540 - assert isinstance(s, int) and 0 <= s < 24*3600
221.541 - assert isinstance(us, int) and 0 <= us < 1000000
221.542 -
221.543 - self = object.__new__(cls)
221.544 -
221.545 - self.__days = d
221.546 - self.__seconds = s
221.547 - self.__microseconds = us
221.548 - if abs(d) > 999999999:
221.549 - raise OverflowError("timedelta # of days is too large: %d" % d)
221.550 -
221.551 - return self
221.552 -
221.553 - def __repr__(self):
221.554 - if self.__microseconds:
221.555 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
221.556 - self.__days,
221.557 - self.__seconds,
221.558 - self.__microseconds)
221.559 - if self.__seconds:
221.560 - return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__,
221.561 - self.__days,
221.562 - self.__seconds)
221.563 - return "%s(%d)" % ('datetime.' + self.__class__.__name__, self.__days)
221.564 -
221.565 - def __str__(self):
221.566 - mm, ss = divmod(self.__seconds, 60)
221.567 - hh, mm = divmod(mm, 60)
221.568 - s = "%d:%02d:%02d" % (hh, mm, ss)
221.569 - if self.__days:
221.570 - def plural(n):
221.571 - return n, abs(n) != 1 and "s" or ""
221.572 - s = ("%d day%s, " % plural(self.__days)) + s
221.573 - if self.__microseconds:
221.574 - s = s + ".%06d" % self.__microseconds
221.575 - return s
221.576 -
221.577 - days = property(lambda self: self.__days, doc="days")
221.578 - seconds = property(lambda self: self.__seconds, doc="seconds")
221.579 - microseconds = property(lambda self: self.__microseconds,
221.580 - doc="microseconds")
221.581 -
221.582 - def __add__(self, other):
221.583 - if isinstance(other, timedelta):
221.584 - return timedelta(self.__days + other.__days,
221.585 - self.__seconds + other.__seconds,
221.586 - self.__microseconds + other.__microseconds)
221.587 - return NotImplemented
221.588 -
221.589 - __radd__ = __add__
221.590 -
221.591 - def __sub__(self, other):
221.592 - if isinstance(other, timedelta):
221.593 - return self + -other
221.594 - return NotImplemented
221.595 -
221.596 - def __rsub__(self, other):
221.597 - if isinstance(other, timedelta):
221.598 - return -self + other
221.599 - return NotImplemented
221.600 -
221.601 - def __neg__(self):
221.602 - return self.__class__(-self.__days,
221.603 - -self.__seconds,
221.604 - -self.__microseconds)
221.605 -
221.606 - def __pos__(self):
221.607 - return self
221.608 -
221.609 - def __abs__(self):
221.610 - if self.__days < 0:
221.611 - return -self
221.612 - else:
221.613 - return self
221.614 -
221.615 - def __mul__(self, other):
221.616 - if isinstance(other, (int, long)):
221.617 - return self.__class__(self.__days * other,
221.618 - self.__seconds * other,
221.619 - self.__microseconds * other)
221.620 - return NotImplemented
221.621 -
221.622 - __rmul__ = __mul__
221.623 -
221.624 - def __div__(self, other):
221.625 - if isinstance(other, (int, long)):
221.626 - usec = ((self.__days * (24*3600L) + self.__seconds) * 1000000 +
221.627 - self.__microseconds)
221.628 - return self.__class__(0, 0, usec // other)
221.629 - return NotImplemented
221.630 -
221.631 - __floordiv__ = __div__
221.632 -
221.633 - # Comparisons.
221.634 -
221.635 - def __eq__(self, other):
221.636 - if isinstance(other, timedelta):
221.637 - return self.__cmp(other) == 0
221.638 - else:
221.639 - return False
221.640 -
221.641 - def __ne__(self, other):
221.642 - if isinstance(other, timedelta):
221.643 - return self.__cmp(other) != 0
221.644 - else:
221.645 - return True
221.646 -
221.647 - def __le__(self, other):
221.648 - if isinstance(other, timedelta):
221.649 - return self.__cmp(other) <= 0
221.650 - else:
221.651 - _cmperror(self, other)
221.652 -
221.653 - def __lt__(self, other):
221.654 - if isinstance(other, timedelta):
221.655 - return self.__cmp(other) < 0
221.656 - else:
221.657 - _cmperror(self, other)
221.658 -
221.659 - def __ge__(self, other):
221.660 - if isinstance(other, timedelta):
221.661 - return self.__cmp(other) >= 0
221.662 - else:
221.663 - _cmperror(self, other)
221.664 -
221.665 - def __gt__(self, other):
221.666 - if isinstance(other, timedelta):
221.667 - return self.__cmp(other) > 0
221.668 - else:
221.669 - _cmperror(self, other)
221.670 -
221.671 - def __cmp(self, other):
221.672 - assert isinstance(other, timedelta)
221.673 - return cmp(self.__getstate(), other.__getstate())
221.674 -
221.675 - def __hash__(self):
221.676 - return hash(self.__getstate())
221.677 -
221.678 - def __nonzero__(self):
221.679 - return (self.__days != 0 or
221.680 - self.__seconds != 0 or
221.681 - self.__microseconds != 0)
221.682 -
221.683 - # Pickle support.
221.684 -
221.685 - __safe_for_unpickling__ = True # For Python 2.2
221.686 -
221.687 - def __getstate(self):
221.688 - return (self.__days, self.__seconds, self.__microseconds)
221.689 -
221.690 - def __reduce__(self):
221.691 - return (self.__class__, self.__getstate())
221.692 -
221.693 -timedelta.min = timedelta(-999999999)
221.694 -timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
221.695 - microseconds=999999)
221.696 -timedelta.resolution = timedelta(microseconds=1)
221.697 -
221.698 -class date(object):
221.699 - """Concrete date type.
221.700 -
221.701 - Constructors:
221.702 -
221.703 - __new__()
221.704 - fromtimestamp()
221.705 - today()
221.706 - fromordinal()
221.707 -
221.708 - Operators:
221.709 -
221.710 - __repr__, __str__
221.711 - __cmp__, __hash__
221.712 - __add__, __radd__, __sub__ (add/radd only with timedelta arg)
221.713 -
221.714 - Methods:
221.715 -
221.716 - timetuple()
221.717 - toordinal()
221.718 - weekday()
221.719 - isoweekday(), isocalendar(), isoformat()
221.720 - ctime()
221.721 - strftime()
221.722 -
221.723 - Properties (readonly):
221.724 - year, month, day
221.725 - """
221.726 -
221.727 - def __new__(cls, year, month=None, day=None):
221.728 - """Constructor.
221.729 -
221.730 - Arguments:
221.731 -
221.732 - year, month, day (required, base 1)
221.733 - """
221.734 - if isinstance(year, str):
221.735 - # Pickle support
221.736 - self = object.__new__(cls)
221.737 - self.__setstate((year,))
221.738 - return self
221.739 - _check_date_fields(year, month, day)
221.740 - self = object.__new__(cls)
221.741 - self.__year = year
221.742 - self.__month = month
221.743 - self.__day = day
221.744 - return self
221.745 -
221.746 - # Additional constructors
221.747 -
221.748 - def fromtimestamp(cls, t):
221.749 - "Construct a date from a POSIX timestamp (like time.time())."
221.750 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
221.751 - return cls(y, m, d)
221.752 - fromtimestamp = classmethod(fromtimestamp)
221.753 -
221.754 - def today(cls):
221.755 - "Construct a date from time.time()."
221.756 - t = _time.time()
221.757 - return cls.fromtimestamp(t)
221.758 - today = classmethod(today)
221.759 -
221.760 - def fromordinal(cls, n):
221.761 - """Contruct a date from a proleptic Gregorian ordinal.
221.762 -
221.763 - January 1 of year 1 is day 1. Only the year, month and day are
221.764 - non-zero in the result.
221.765 - """
221.766 - y, m, d = _ord2ymd(n)
221.767 - return cls(y, m, d)
221.768 - fromordinal = classmethod(fromordinal)
221.769 -
221.770 - # Conversions to string
221.771 -
221.772 - def __repr__(self):
221.773 - "Convert to formal string, for repr()."
221.774 - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
221.775 - self.__year,
221.776 - self.__month,
221.777 - self.__day)
221.778 - # XXX These shouldn't depend on time.localtime(), because that
221.779 - # clips the usable dates to [1970 .. 2038). At least ctime() is
221.780 - # easily done without using strftime() -- that's better too because
221.781 - # strftime("%c", ...) is locale specific.
221.782 -
221.783 - def ctime(self):
221.784 - "Format a la ctime()."
221.785 - return tmxxx(self.__year, self.__month, self.__day).ctime()
221.786 -
221.787 - def strftime(self, fmt):
221.788 - "Format using strftime()."
221.789 - return _wrap_strftime(self, fmt, self.timetuple())
221.790 -
221.791 - def isoformat(self):
221.792 - """Return the date formatted according to ISO.
221.793 -
221.794 - This is 'YYYY-MM-DD'.
221.795 -
221.796 - References:
221.797 - - http://www.w3.org/TR/NOTE-datetime
221.798 - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
221.799 - """
221.800 - return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day)
221.801 -
221.802 - __str__ = isoformat
221.803 -
221.804 - # Read-only field accessors
221.805 - year = property(lambda self: self.__year,
221.806 - doc="year (%d-%d)" % (MINYEAR, MAXYEAR))
221.807 - month = property(lambda self: self.__month, doc="month (1-12)")
221.808 - day = property(lambda self: self.__day, doc="day (1-31)")
221.809 -
221.810 - # Standard conversions, __cmp__, __hash__ (and helpers)
221.811 -
221.812 - def timetuple(self):
221.813 - "Return local time tuple compatible with time.localtime()."
221.814 - return _build_struct_time(self.__year, self.__month, self.__day,
221.815 - 0, 0, 0, -1)
221.816 -
221.817 - def toordinal(self):
221.818 - """Return proleptic Gregorian ordinal for the year, month and day.
221.819 -
221.820 - January 1 of year 1 is day 1. Only the year, month and day values
221.821 - contribute to the result.
221.822 - """
221.823 - return _ymd2ord(self.__year, self.__month, self.__day)
221.824 -
221.825 - def replace(self, year=None, month=None, day=None):
221.826 - """Return a new date with new values for the specified fields."""
221.827 - if year is None:
221.828 - year = self.__year
221.829 - if month is None:
221.830 - month = self.__month
221.831 - if day is None:
221.832 - day = self.__day
221.833 - _check_date_fields(year, month, day)
221.834 - return date(year, month, day)
221.835 -
221.836 - # Comparisons.
221.837 -
221.838 - def __eq__(self, other):
221.839 - if isinstance(other, date):
221.840 - return self.__cmp(other) == 0
221.841 - elif hasattr(other, "timetuple"):
221.842 - return NotImplemented
221.843 - else:
221.844 - return False
221.845 -
221.846 - def __ne__(self, other):
221.847 - if isinstance(other, date):
221.848 - return self.__cmp(other) != 0
221.849 - elif hasattr(other, "timetuple"):
221.850 - return NotImplemented
221.851 - else:
221.852 - return True
221.853 -
221.854 - def __le__(self, other):
221.855 - if isinstance(other, date):
221.856 - return self.__cmp(other) <= 0
221.857 - elif hasattr(other, "timetuple"):
221.858 - return NotImplemented
221.859 - else:
221.860 - _cmperror(self, other)
221.861 -
221.862 - def __lt__(self, other):
221.863 - if isinstance(other, date):
221.864 - return self.__cmp(other) < 0
221.865 - elif hasattr(other, "timetuple"):
221.866 - return NotImplemented
221.867 - else:
221.868 - _cmperror(self, other)
221.869 -
221.870 - def __ge__(self, other):
221.871 - if isinstance(other, date):
221.872 - return self.__cmp(other) >= 0
221.873 - elif hasattr(other, "timetuple"):
221.874 - return NotImplemented
221.875 - else:
221.876 - _cmperror(self, other)
221.877 -
221.878 - def __gt__(self, other):
221.879 - if isinstance(other, date):
221.880 - return self.__cmp(other) > 0
221.881 - elif hasattr(other, "timetuple"):
221.882 - return NotImplemented
221.883 - else:
221.884 - _cmperror(self, other)
221.885 -
221.886 - def __cmp(self, other):
221.887 - assert isinstance(other, date)
221.888 - y, m, d = self.__year, self.__month, self.__day
221.889 - y2, m2, d2 = other.__year, other.__month, other.__day
221.890 - return cmp((y, m, d), (y2, m2, d2))
221.891 -
221.892 - def __hash__(self):
221.893 - "Hash."
221.894 - return hash(self.__getstate())
221.895 -
221.896 - # Computations
221.897 -
221.898 - def _checkOverflow(self, year):
221.899 - if not MINYEAR <= year <= MAXYEAR:
221.900 - raise OverflowError("date +/-: result year %d not in %d..%d" %
221.901 - (year, MINYEAR, MAXYEAR))
221.902 -
221.903 - def __add__(self, other):
221.904 - "Add a date to a timedelta."
221.905 - if isinstance(other, timedelta):
221.906 - t = tmxxx(self.__year,
221.907 - self.__month,
221.908 - self.__day + other.days)
221.909 - self._checkOverflow(t.year)
221.910 - result = self.__class__(t.year, t.month, t.day)
221.911 - return result
221.912 - return NotImplemented
221.913 -
221.914 - __radd__ = __add__
221.915 -
221.916 - def __sub__(self, other):
221.917 - """Subtract two dates, or a date and a timedelta."""
221.918 - if isinstance(other, timedelta):
221.919 - return self + timedelta(-other.days)
221.920 - if isinstance(other, date):
221.921 - days1 = self.toordinal()
221.922 - days2 = other.toordinal()
221.923 - return timedelta(days1 - days2)
221.924 - return NotImplemented
221.925 -
221.926 - def weekday(self):
221.927 - "Return day of the week, where Monday == 0 ... Sunday == 6."
221.928 - return (self.toordinal() + 6) % 7
221.929 -
221.930 - # Day-of-the-week and week-of-the-year, according to ISO
221.931 -
221.932 - def isoweekday(self):
221.933 - "Return day of the week, where Monday == 1 ... Sunday == 7."
221.934 - # 1-Jan-0001 is a Monday
221.935 - return self.toordinal() % 7 or 7
221.936 -
221.937 - def isocalendar(self):
221.938 - """Return a 3-tuple containing ISO year, week number, and weekday.
221.939 -
221.940 - The first ISO week of the year is the (Mon-Sun) week
221.941 - containing the year's first Thursday; everything else derives
221.942 - from that.
221.943 -
221.944 - The first week is 1; Monday is 1 ... Sunday is 7.
221.945 -
221.946 - ISO calendar algorithm taken from
221.947 - http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
221.948 - """
221.949 - year = self.__year
221.950 - week1monday = _isoweek1monday(year)
221.951 - today = _ymd2ord(self.__year, self.__month, self.__day)
221.952 - # Internally, week and day have origin 0
221.953 - week, day = divmod(today - week1monday, 7)
221.954 - if week < 0:
221.955 - year -= 1
221.956 - week1monday = _isoweek1monday(year)
221.957 - week, day = divmod(today - week1monday, 7)
221.958 - elif week >= 52:
221.959 - if today >= _isoweek1monday(year+1):
221.960 - year += 1
221.961 - week = 0
221.962 - return year, week+1, day+1
221.963 -
221.964 - # Pickle support.
221.965 -
221.966 - __safe_for_unpickling__ = True # For Python 2.2
221.967 -
221.968 - def __getstate(self):
221.969 - yhi, ylo = divmod(self.__year, 256)
221.970 - return ("%c%c%c%c" % (yhi, ylo, self.__month, self.__day), )
221.971 -
221.972 - def __setstate(self, t):
221.973 - assert isinstance(t, tuple) and len(t) == 1, `t`
221.974 - string = t[0]
221.975 - assert len(string) == 4
221.976 - yhi, ylo, self.__month, self.__day = map(ord, string)
221.977 - self.__year = yhi * 256 + ylo
221.978 -
221.979 - def __reduce__(self):
221.980 - return (self.__class__, self.__getstate())
221.981 -
221.982 -_date_class = date # so functions w/ args named "date" can get at the class
221.983 -
221.984 -date.min = date(1, 1, 1)
221.985 -date.max = date(9999, 12, 31)
221.986 -date.resolution = timedelta(days=1)
221.987 -
221.988 -class tzinfo(object):
221.989 - """Abstract base class for time zone info classes.
221.990 -
221.991 - Subclasses must override the name(), utcoffset() and dst() methods.
221.992 - """
221.993 -
221.994 - def tzname(self, dt):
221.995 - "datetime -> string name of time zone."
221.996 - raise NotImplementedError("tzinfo subclass must override tzname()")
221.997 -
221.998 - def utcoffset(self, dt):
221.999 - "datetime -> minutes east of UTC (negative for west of UTC)"
221.1000 - raise NotImplementedError("tzinfo subclass must override utcoffset()")
221.1001 -
221.1002 - def dst(self, dt):
221.1003 - """datetime -> DST offset in minutes east of UTC.
221.1004 -
221.1005 - Return 0 if DST not in effect. utcoffset() must include the DST
221.1006 - offset.
221.1007 - """
221.1008 - raise NotImplementedError("tzinfo subclass must override dst()")
221.1009 -
221.1010 - def fromutc(self, dt):
221.1011 - "datetime in UTC -> datetime in local time."
221.1012 -
221.1013 - if not isinstance(dt, datetime):
221.1014 - raise TypeError("fromutc() requires a datetime argument")
221.1015 - if dt.tzinfo is not self:
221.1016 - raise ValueError("dt.tzinfo is not self")
221.1017 -
221.1018 - dtoff = dt.utcoffset()
221.1019 - if dtoff is None:
221.1020 - raise ValueError("fromutc() requires a non-None utcoffset() "
221.1021 - "result")
221.1022 -
221.1023 - # See the long comment block at the end of this file for an
221.1024 - # explanation of this algorithm.
221.1025 - dtdst = dt.dst()
221.1026 - if dtdst is None:
221.1027 - raise ValueError("fromutc() requires a non-None dst() result")
221.1028 - delta = dtoff - dtdst
221.1029 - if delta:
221.1030 - dt += delta
221.1031 - dtdst = dt.dst()
221.1032 - if dtdst is None:
221.1033 - raise ValueError("fromutc(): dt.dst gave inconsistent "
221.1034 - "results; cannot convert")
221.1035 - if dtdst:
221.1036 - return dt + dtdst
221.1037 - else:
221.1038 - return dt
221.1039 -
221.1040 - # Pickle support.
221.1041 -
221.1042 - __safe_for_unpickling__ = True # For Python 2.2
221.1043 -
221.1044 - def __reduce__(self):
221.1045 - getinitargs = getattr(self, "__getinitargs__", None)
221.1046 - if getinitargs:
221.1047 - args = getinitargs()
221.1048 - else:
221.1049 - args = ()
221.1050 - getstate = getattr(self, "__getstate__", None)
221.1051 - if getstate:
221.1052 - state = getstate()
221.1053 - else:
221.1054 - state = getattr(self, "__dict__", None) or None
221.1055 - if state is None:
221.1056 - return (self.__class__, args)
221.1057 - else:
221.1058 - return (self.__class__, args, state)
221.1059 -
221.1060 -_tzinfo_class = tzinfo # so functions w/ args named "tinfo" can get at it
221.1061 -
221.1062 -class time(object):
221.1063 - """Time with time zone.
221.1064 -
221.1065 - Constructors:
221.1066 -
221.1067 - __new__()
221.1068 -
221.1069 - Operators:
221.1070 -
221.1071 - __repr__, __str__
221.1072 - __cmp__, __hash__
221.1073 -
221.1074 - Methods:
221.1075 -
221.1076 - strftime()
221.1077 - isoformat()
221.1078 - utcoffset()
221.1079 - tzname()
221.1080 - dst()
221.1081 -
221.1082 - Properties (readonly):
221.1083 - hour, minute, second, microsecond, tzinfo
221.1084 - """
221.1085 -
221.1086 - def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
221.1087 - """Constructor.
221.1088 -
221.1089 - Arguments:
221.1090 -
221.1091 - hour, minute (required)
221.1092 - second, microsecond (default to zero)
221.1093 - tzinfo (default to None)
221.1094 - """
221.1095 - self = object.__new__(cls)
221.1096 - if isinstance(hour, str):
221.1097 - # Pickle support
221.1098 - self.__setstate((hour, minute or None))
221.1099 - return self
221.1100 - _check_tzinfo_arg(tzinfo)
221.1101 - _check_time_fields(hour, minute, second, microsecond)
221.1102 - self.__hour = hour
221.1103 - self.__minute = minute
221.1104 - self.__second = second
221.1105 - self.__microsecond = microsecond
221.1106 - self._tzinfo = tzinfo
221.1107 - return self
221.1108 -
221.1109 - # Read-only field accessors
221.1110 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
221.1111 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
221.1112 - second = property(lambda self: self.__second, doc="second (0-59)")
221.1113 - microsecond = property(lambda self: self.__microsecond,
221.1114 - doc="microsecond (0-999999)")
221.1115 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
221.1116 -
221.1117 - # Standard conversions, __hash__ (and helpers)
221.1118 -
221.1119 - # Comparisons.
221.1120 -
221.1121 - def __eq__(self, other):
221.1122 - if isinstance(other, time):
221.1123 - return self.__cmp(other) == 0
221.1124 - else:
221.1125 - return False
221.1126 -
221.1127 - def __ne__(self, other):
221.1128 - if isinstance(other, time):
221.1129 - return self.__cmp(other) != 0
221.1130 - else:
221.1131 - return True
221.1132 -
221.1133 - def __le__(self, other):
221.1134 - if isinstance(other, time):
221.1135 - return self.__cmp(other) <= 0
221.1136 - else:
221.1137 - _cmperror(self, other)
221.1138 -
221.1139 - def __lt__(self, other):
221.1140 - if isinstance(other, time):
221.1141 - return self.__cmp(other) < 0
221.1142 - else:
221.1143 - _cmperror(self, other)
221.1144 -
221.1145 - def __ge__(self, other):
221.1146 - if isinstance(other, time):
221.1147 - return self.__cmp(other) >= 0
221.1148 - else:
221.1149 - _cmperror(self, other)
221.1150 -
221.1151 - def __gt__(self, other):
221.1152 - if isinstance(other, time):
221.1153 - return self.__cmp(other) > 0
221.1154 - else:
221.1155 - _cmperror(self, other)
221.1156 -
221.1157 - def __cmp(self, other):
221.1158 - assert isinstance(other, time)
221.1159 - mytz = self._tzinfo
221.1160 - ottz = other._tzinfo
221.1161 - myoff = otoff = None
221.1162 -
221.1163 - if mytz is ottz:
221.1164 - base_compare = True
221.1165 - else:
221.1166 - myoff = self._utcoffset()
221.1167 - otoff = other._utcoffset()
221.1168 - base_compare = myoff == otoff
221.1169 -
221.1170 - if base_compare:
221.1171 - return cmp((self.__hour, self.__minute, self.__second,
221.1172 - self.__microsecond),
221.1173 - (other.__hour, other.__minute, other.__second,
221.1174 - other.__microsecond))
221.1175 - if myoff is None or otoff is None:
221.1176 - # XXX Buggy in 2.2.2.
221.1177 - raise TypeError("cannot compare naive and aware times")
221.1178 - myhhmm = self.__hour * 60 + self.__minute - myoff
221.1179 - othhmm = other.__hour * 60 + other.__minute - otoff
221.1180 - return cmp((myhhmm, self.__second, self.__microsecond),
221.1181 - (othhmm, other.__second, other.__microsecond))
221.1182 -
221.1183 - def __hash__(self):
221.1184 - """Hash."""
221.1185 - tzoff = self._utcoffset()
221.1186 - if not tzoff: # zero or None
221.1187 - return hash(self.__getstate()[0])
221.1188 - h, m = divmod(self.hour * 60 + self.minute - tzoff, 60)
221.1189 - if 0 <= h < 24:
221.1190 - return hash(time(h, m, self.second, self.microsecond))
221.1191 - return hash((h, m, self.second, self.microsecond))
221.1192 -
221.1193 - # Conversion to string
221.1194 -
221.1195 - def _tzstr(self, sep=":"):
221.1196 - """Return formatted timezone offset (+xx:xx) or None."""
221.1197 - off = self._utcoffset()
221.1198 - if off is not None:
221.1199 - if off < 0:
221.1200 - sign = "-"
221.1201 - off = -off
221.1202 - else:
221.1203 - sign = "+"
221.1204 - hh, mm = divmod(off, 60)
221.1205 - assert 0 <= hh < 24
221.1206 - off = "%s%02d%s%02d" % (sign, hh, sep, mm)
221.1207 - return off
221.1208 -
221.1209 - def __repr__(self):
221.1210 - """Convert to formal string, for repr()."""
221.1211 - if self.__microsecond != 0:
221.1212 - s = ", %d, %d" % (self.__second, self.__microsecond)
221.1213 - elif self.__second != 0:
221.1214 - s = ", %d" % self.__second
221.1215 - else:
221.1216 - s = ""
221.1217 - s= "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__,
221.1218 - self.__hour, self.__minute, s)
221.1219 - if self._tzinfo is not None:
221.1220 - assert s[-1:] == ")"
221.1221 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
221.1222 - return s
221.1223 -
221.1224 - def isoformat(self):
221.1225 - """Return the time formatted according to ISO.
221.1226 -
221.1227 - This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
221.1228 - self.microsecond == 0.
221.1229 - """
221.1230 - s = _format_time(self.__hour, self.__minute, self.__second,
221.1231 - self.__microsecond)
221.1232 - tz = self._tzstr()
221.1233 - if tz:
221.1234 - s += tz
221.1235 - return s
221.1236 -
221.1237 - __str__ = isoformat
221.1238 -
221.1239 - def strftime(self, fmt):
221.1240 - """Format using strftime(). The date part of the timestamp passed
221.1241 - to underlying strftime should not be used.
221.1242 - """
221.1243 - # The year must be >= 1900 else Python's strftime implementation
221.1244 - # can raise a bogus exception.
221.1245 - timetuple = (1900, 1, 1,
221.1246 - self.__hour, self.__minute, self.__second,
221.1247 - 0, 1, -1)
221.1248 - return _wrap_strftime(self, fmt, timetuple)
221.1249 -
221.1250 - # Timezone functions
221.1251 -
221.1252 - def utcoffset(self):
221.1253 - """Return the timezone offset in minutes east of UTC (negative west of
221.1254 - UTC)."""
221.1255 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
221.1256 - offset = _check_utc_offset("utcoffset", offset)
221.1257 - if offset is not None:
221.1258 - offset = timedelta(minutes=offset)
221.1259 - return offset
221.1260 -
221.1261 - # Return an integer (or None) instead of a timedelta (or None).
221.1262 - def _utcoffset(self):
221.1263 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", None)
221.1264 - offset = _check_utc_offset("utcoffset", offset)
221.1265 - return offset
221.1266 -
221.1267 - def tzname(self):
221.1268 - """Return the timezone name.
221.1269 -
221.1270 - Note that the name is 100% informational -- there's no requirement that
221.1271 - it mean anything in particular. For example, "GMT", "UTC", "-500",
221.1272 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
221.1273 - """
221.1274 - name = _call_tzinfo_method(self._tzinfo, "tzname", None)
221.1275 - _check_tzname(name)
221.1276 - return name
221.1277 -
221.1278 - def dst(self):
221.1279 - """Return 0 if DST is not in effect, or the DST offset (in minutes
221.1280 - eastward) if DST is in effect.
221.1281 -
221.1282 - This is purely informational; the DST offset has already been added to
221.1283 - the UTC offset returned by utcoffset() if applicable, so there's no
221.1284 - need to consult dst() unless you're interested in displaying the DST
221.1285 - info.
221.1286 - """
221.1287 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
221.1288 - offset = _check_utc_offset("dst", offset)
221.1289 - if offset is not None:
221.1290 - offset = timedelta(minutes=offset)
221.1291 - return offset
221.1292 -
221.1293 - def replace(self, hour=None, minute=None, second=None, microsecond=None,
221.1294 - tzinfo=True):
221.1295 - """Return a new time with new values for the specified fields."""
221.1296 - if hour is None:
221.1297 - hour = self.hour
221.1298 - if minute is None:
221.1299 - minute = self.minute
221.1300 - if second is None:
221.1301 - second = self.second
221.1302 - if microsecond is None:
221.1303 - microsecond = self.microsecond
221.1304 - if tzinfo is True:
221.1305 - tzinfo = self.tzinfo
221.1306 - _check_time_fields(hour, minute, second, microsecond)
221.1307 - _check_tzinfo_arg(tzinfo)
221.1308 - return time(hour, minute, second, microsecond, tzinfo)
221.1309 -
221.1310 - # Return an integer (or None) instead of a timedelta (or None).
221.1311 - def _dst(self):
221.1312 - offset = _call_tzinfo_method(self._tzinfo, "dst", None)
221.1313 - offset = _check_utc_offset("dst", offset)
221.1314 - return offset
221.1315 -
221.1316 - def __nonzero__(self):
221.1317 - if self.second or self.microsecond:
221.1318 - return 1
221.1319 - offset = self._utcoffset() or 0
221.1320 - return self.hour * 60 + self.minute - offset != 0
221.1321 -
221.1322 - # Pickle support.
221.1323 -
221.1324 - __safe_for_unpickling__ = True # For Python 2.2
221.1325 -
221.1326 - def __getstate(self):
221.1327 - us2, us3 = divmod(self.__microsecond, 256)
221.1328 - us1, us2 = divmod(us2, 256)
221.1329 - basestate = ("%c" * 6) % (self.__hour, self.__minute, self.__second,
221.1330 - us1, us2, us3)
221.1331 - if self._tzinfo is None:
221.1332 - return (basestate,)
221.1333 - else:
221.1334 - return (basestate, self._tzinfo)
221.1335 -
221.1336 - def __setstate(self, state):
221.1337 - assert isinstance(state, tuple)
221.1338 - assert 1 <= len(state) <= 2
221.1339 - string = state[0]
221.1340 - assert len(string) == 6
221.1341 - self.__hour, self.__minute, self.__second, us1, us2, us3 = \
221.1342 - map(ord, string)
221.1343 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
221.1344 - if len(state) == 1:
221.1345 - self._tzinfo = None
221.1346 - else:
221.1347 - self._tzinfo = state[1]
221.1348 -
221.1349 - def __reduce__(self):
221.1350 - return (self.__class__, self.__getstate())
221.1351 -
221.1352 -_time_class = time # so functions w/ args named "time" can get at the class
221.1353 -
221.1354 -time.min = time(0, 0, 0)
221.1355 -time.max = time(23, 59, 59, 999999)
221.1356 -time.resolution = timedelta(microseconds=1)
221.1357 -
221.1358 -class datetime(date):
221.1359 -
221.1360 - # XXX needs docstrings
221.1361 - # See http://www.zope.org/Members/fdrake/DateTimeWiki/TimeZoneInfo
221.1362 -
221.1363 - def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
221.1364 - microsecond=0, tzinfo=None):
221.1365 - if isinstance(year, str):
221.1366 - # Pickle support
221.1367 - self = date.__new__(cls, year[:4])
221.1368 - self.__setstate((year, month))
221.1369 - return self
221.1370 - _check_tzinfo_arg(tzinfo)
221.1371 - _check_time_fields(hour, minute, second, microsecond)
221.1372 - self = date.__new__(cls, year, month, day)
221.1373 - # XXX This duplicates __year, __month, __day for convenience :-(
221.1374 - self.__year = year
221.1375 - self.__month = month
221.1376 - self.__day = day
221.1377 - self.__hour = hour
221.1378 - self.__minute = minute
221.1379 - self.__second = second
221.1380 - self.__microsecond = microsecond
221.1381 - self._tzinfo = tzinfo
221.1382 - return self
221.1383 -
221.1384 - # Read-only field accessors
221.1385 - hour = property(lambda self: self.__hour, doc="hour (0-23)")
221.1386 - minute = property(lambda self: self.__minute, doc="minute (0-59)")
221.1387 - second = property(lambda self: self.__second, doc="second (0-59)")
221.1388 - microsecond = property(lambda self: self.__microsecond,
221.1389 - doc="microsecond (0-999999)")
221.1390 - tzinfo = property(lambda self: self._tzinfo, doc="timezone info object")
221.1391 -
221.1392 - def fromtimestamp(cls, t, tz=None):
221.1393 - """Construct a datetime from a POSIX timestamp (like time.time()).
221.1394 -
221.1395 - A timezone info object may be passed in as well.
221.1396 - """
221.1397 -
221.1398 - _check_tzinfo_arg(tz)
221.1399 - if tz is None:
221.1400 - converter = _time.localtime
221.1401 - else:
221.1402 - converter = _time.gmtime
221.1403 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
221.1404 - us = int((t % 1.0) * 1000000)
221.1405 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
221.1406 - result = cls(y, m, d, hh, mm, ss, us, tz)
221.1407 - if tz is not None:
221.1408 - result = tz.fromutc(result)
221.1409 - return result
221.1410 - fromtimestamp = classmethod(fromtimestamp)
221.1411 -
221.1412 - def utcfromtimestamp(cls, t):
221.1413 - "Construct a UTC datetime from a POSIX timestamp (like time.time())."
221.1414 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
221.1415 - us = int((t % 1.0) * 1000000)
221.1416 - ss = min(ss, 59) # clamp out leap seconds if the platform has them
221.1417 - return cls(y, m, d, hh, mm, ss, us)
221.1418 - utcfromtimestamp = classmethod(utcfromtimestamp)
221.1419 -
221.1420 - # XXX This is supposed to do better than we *can* do by using time.time(),
221.1421 - # XXX if the platform supports a more accurate way. The C implementation
221.1422 - # XXX uses gettimeofday on platforms that have it, but that isn't
221.1423 - # XXX available from Python. So now() may return different results
221.1424 - # XXX across the implementations.
221.1425 - def now(cls, tz=None):
221.1426 - "Construct a datetime from time.time() and optional time zone info."
221.1427 - t = _time.time()
221.1428 - return cls.fromtimestamp(t, tz)
221.1429 - now = classmethod(now)
221.1430 -
221.1431 - def utcnow(cls):
221.1432 - "Construct a UTC datetime from time.time()."
221.1433 - t = _time.time()
221.1434 - return cls.utcfromtimestamp(t)
221.1435 - utcnow = classmethod(utcnow)
221.1436 -
221.1437 - def combine(cls, date, time):
221.1438 - "Construct a datetime from a given date and a given time."
221.1439 - if not isinstance(date, _date_class):
221.1440 - raise TypeError("date argument must be a date instance")
221.1441 - if not isinstance(time, _time_class):
221.1442 - raise TypeError("time argument must be a time instance")
221.1443 - return cls(date.year, date.month, date.day,
221.1444 - time.hour, time.minute, time.second, time.microsecond,
221.1445 - time.tzinfo)
221.1446 - combine = classmethod(combine)
221.1447 -
221.1448 - def timetuple(self):
221.1449 - "Return local time tuple compatible with time.localtime()."
221.1450 - dst = self._dst()
221.1451 - if dst is None:
221.1452 - dst = -1
221.1453 - elif dst:
221.1454 - dst = 1
221.1455 - return _build_struct_time(self.year, self.month, self.day,
221.1456 - self.hour, self.minute, self.second,
221.1457 - dst)
221.1458 -
221.1459 - def utctimetuple(self):
221.1460 - "Return UTC time tuple compatible with time.gmtime()."
221.1461 - y, m, d = self.year, self.month, self.day
221.1462 - hh, mm, ss = self.hour, self.minute, self.second
221.1463 - offset = self._utcoffset()
221.1464 - if offset: # neither None nor 0
221.1465 - tm = tmxxx(y, m, d, hh, mm - offset)
221.1466 - y, m, d = tm.year, tm.month, tm.day
221.1467 - hh, mm = tm.hour, tm.minute
221.1468 - return _build_struct_time(y, m, d, hh, mm, ss, 0)
221.1469 -
221.1470 - def date(self):
221.1471 - "Return the date part."
221.1472 - return date(self.__year, self.__month, self.__day)
221.1473 -
221.1474 - def time(self):
221.1475 - "Return the time part, with tzinfo None."
221.1476 - return time(self.hour, self.minute, self.second, self.microsecond)
221.1477 -
221.1478 - def timetz(self):
221.1479 - "Return the time part, with same tzinfo."
221.1480 - return time(self.hour, self.minute, self.second, self.microsecond,
221.1481 - self._tzinfo)
221.1482 -
221.1483 - def replace(self, year=None, month=None, day=None, hour=None,
221.1484 - minute=None, second=None, microsecond=None, tzinfo=True):
221.1485 - """Return a new datetime with new values for the specified fields."""
221.1486 - if year is None:
221.1487 - year = self.year
221.1488 - if month is None:
221.1489 - month = self.month
221.1490 - if day is None:
221.1491 - day = self.day
221.1492 - if hour is None:
221.1493 - hour = self.hour
221.1494 - if minute is None:
221.1495 - minute = self.minute
221.1496 - if second is None:
221.1497 - second = self.second
221.1498 - if microsecond is None:
221.1499 - microsecond = self.microsecond
221.1500 - if tzinfo is True:
221.1501 - tzinfo = self.tzinfo
221.1502 - _check_date_fields(year, month, day)
221.1503 - _check_time_fields(hour, minute, second, microsecond)
221.1504 - _check_tzinfo_arg(tzinfo)
221.1505 - return datetime(year, month, day, hour, minute, second,
221.1506 - microsecond, tzinfo)
221.1507 -
221.1508 - def astimezone(self, tz):
221.1509 - if not isinstance(tz, tzinfo):
221.1510 - raise TypeError("tz argument must be an instance of tzinfo")
221.1511 -
221.1512 - mytz = self.tzinfo
221.1513 - if mytz is None:
221.1514 - raise ValueError("astimezone() requires an aware datetime")
221.1515 -
221.1516 - if tz is mytz:
221.1517 - return self
221.1518 -
221.1519 - # Convert self to UTC, and attach the new time zone object.
221.1520 - myoffset = self.utcoffset()
221.1521 - if myoffset is None:
221.1522 - raise ValuError("astimezone() requires an aware datetime")
221.1523 - utc = (self - myoffset).replace(tzinfo=tz)
221.1524 -
221.1525 - # Convert from UTC to tz's local time.
221.1526 - return tz.fromutc(utc)
221.1527 -
221.1528 - # Ways to produce a string.
221.1529 -
221.1530 - def ctime(self):
221.1531 - "Format a la ctime()."
221.1532 - t = tmxxx(self.__year, self.__month, self.__day, self.__hour,
221.1533 - self.__minute, self.__second)
221.1534 - return t.ctime()
221.1535 -
221.1536 - def isoformat(self, sep='T'):
221.1537 - """Return the time formatted according to ISO.
221.1538 -
221.1539 - This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
221.1540 - self.microsecond == 0.
221.1541 -
221.1542 - If self.tzinfo is not None, the UTC offset is also attached, giving
221.1543 - 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
221.1544 -
221.1545 - Optional argument sep specifies the separator between date and
221.1546 - time, default 'T'.
221.1547 - """
221.1548 - s = ("%04d-%02d-%02d%c" % (self.__year, self.__month, self.__day,
221.1549 - sep) +
221.1550 - _format_time(self.__hour, self.__minute, self.__second,
221.1551 - self.__microsecond))
221.1552 - off = self._utcoffset()
221.1553 - if off is not None:
221.1554 - if off < 0:
221.1555 - sign = "-"
221.1556 - off = -off
221.1557 - else:
221.1558 - sign = "+"
221.1559 - hh, mm = divmod(off, 60)
221.1560 - s += "%s%02d:%02d" % (sign, hh, mm)
221.1561 - return s
221.1562 -
221.1563 - def __repr__(self):
221.1564 - "Convert to formal string, for repr()."
221.1565 - L = [self.__year, self.__month, self.__day, # These are never zero
221.1566 - self.__hour, self.__minute, self.__second, self.__microsecond]
221.1567 - if L[-1] == 0:
221.1568 - del L[-1]
221.1569 - if L[-1] == 0:
221.1570 - del L[-1]
221.1571 - s = ", ".join(map(str, L))
221.1572 - s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s)
221.1573 - if self._tzinfo is not None:
221.1574 - assert s[-1:] == ")"
221.1575 - s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
221.1576 - return s
221.1577 -
221.1578 - def __str__(self):
221.1579 - "Convert to string, for str()."
221.1580 - return self.isoformat(sep=' ')
221.1581 -
221.1582 - def utcoffset(self):
221.1583 - """Return the timezone offset in minutes east of UTC (negative west of
221.1584 - UTC)."""
221.1585 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
221.1586 - offset = _check_utc_offset("utcoffset", offset)
221.1587 - if offset is not None:
221.1588 - offset = timedelta(minutes=offset)
221.1589 - return offset
221.1590 -
221.1591 - # Return an integer (or None) instead of a timedelta (or None).
221.1592 - def _utcoffset(self):
221.1593 - offset = _call_tzinfo_method(self._tzinfo, "utcoffset", self)
221.1594 - offset = _check_utc_offset("utcoffset", offset)
221.1595 - return offset
221.1596 -
221.1597 - def tzname(self):
221.1598 - """Return the timezone name.
221.1599 -
221.1600 - Note that the name is 100% informational -- there's no requirement that
221.1601 - it mean anything in particular. For example, "GMT", "UTC", "-500",
221.1602 - "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
221.1603 - """
221.1604 - name = _call_tzinfo_method(self._tzinfo, "tzname", self)
221.1605 - _check_tzname(name)
221.1606 - return name
221.1607 -
221.1608 - def dst(self):
221.1609 - """Return 0 if DST is not in effect, or the DST offset (in minutes
221.1610 - eastward) if DST is in effect.
221.1611 -
221.1612 - This is purely informational; the DST offset has already been added to
221.1613 - the UTC offset returned by utcoffset() if applicable, so there's no
221.1614 - need to consult dst() unless you're interested in displaying the DST
221.1615 - info.
221.1616 - """
221.1617 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
221.1618 - offset = _check_utc_offset("dst", offset)
221.1619 - if offset is not None:
221.1620 - offset = timedelta(minutes=offset)
221.1621 - return offset
221.1622 -
221.1623 - # Return an integer (or None) instead of a timedelta (or None).1573
221.1624 - def _dst(self):
221.1625 - offset = _call_tzinfo_method(self._tzinfo, "dst", self)
221.1626 - offset = _check_utc_offset("dst", offset)
221.1627 - return offset
221.1628 -
221.1629 - # Comparisons.
221.1630 -
221.1631 - def __eq__(self, other):
221.1632 - if isinstance(other, datetime):
221.1633 - return self.__cmp(other) == 0
221.1634 - elif hasattr(other, "timetuple"):
221.1635 - return NotImplemented
221.1636 - else:
221.1637 - return False
221.1638 -
221.1639 - def __ne__(self, other):
221.1640 - if isinstance(other, datetime):
221.1641 - return self.__cmp(other) != 0
221.1642 - elif hasattr(other, "timetuple"):
221.1643 - return NotImplemented
221.1644 - else:
221.1645 - return True
221.1646 -
221.1647 - def __le__(self, other):
221.1648 - if isinstance(other, datetime):
221.1649 - return self.__cmp(other) <= 0
221.1650 - elif hasattr(other, "timetuple"):
221.1651 - return NotImplemented
221.1652 - else:
221.1653 - _cmperror(self, other)
221.1654 -
221.1655 - def __lt__(self, other):
221.1656 - if isinstance(other, datetime):
221.1657 - return self.__cmp(other) < 0
221.1658 - elif hasattr(other, "timetuple"):
221.1659 - return NotImplemented
221.1660 - else:
221.1661 - _cmperror(self, other)
221.1662 -
221.1663 - def __ge__(self, other):
221.1664 - if isinstance(other, datetime):
221.1665 - return self.__cmp(other) >= 0
221.1666 - elif hasattr(other, "timetuple"):
221.1667 - return NotImplemented
221.1668 - else:
221.1669 - _cmperror(self, other)
221.1670 -
221.1671 - def __gt__(self, other):
221.1672 - if isinstance(other, datetime):
221.1673 - return self.__cmp(other) > 0
221.1674 - elif hasattr(other, "timetuple"):
221.1675 - return NotImplemented
221.1676 - else:
221.1677 - _cmperror(self, other)
221.1678 -
221.1679 - def __cmp(self, other):
221.1680 - assert isinstance(other, datetime)
221.1681 - mytz = self._tzinfo
221.1682 - ottz = other._tzinfo
221.1683 - myoff = otoff = None
221.1684 -
221.1685 - if mytz is ottz:
221.1686 - base_compare = True
221.1687 - else:
221.1688 - if mytz is not None:
221.1689 - myoff = self._utcoffset()
221.1690 - if ottz is not None:
221.1691 - otoff = other._utcoffset()
221.1692 - base_compare = myoff == otoff
221.1693 -
221.1694 - if base_compare:
221.1695 - return cmp((self.__year, self.__month, self.__day,
221.1696 - self.__hour, self.__minute, self.__second,
221.1697 - self.__microsecond),
221.1698 - (other.__year, other.__month, other.__day,
221.1699 - other.__hour, other.__minute, other.__second,
221.1700 - other.__microsecond))
221.1701 - if myoff is None or otoff is None:
221.1702 - # XXX Buggy in 2.2.2.
221.1703 - raise TypeError("cannot compare naive and aware datetimes")
221.1704 - # XXX What follows could be done more efficiently...
221.1705 - diff = self - other # this will take offsets into account
221.1706 - if diff.days < 0:
221.1707 - return -1
221.1708 - return diff and 1 or 0
221.1709 -
221.1710 - def __add__(self, other):
221.1711 - "Add a datetime and a timedelta."
221.1712 - if not isinstance(other, timedelta):
221.1713 - return NotImplemented
221.1714 - t = tmxxx(self.__year,
221.1715 - self.__month,
221.1716 - self.__day + other.days,
221.1717 - self.__hour,
221.1718 - self.__minute,
221.1719 - self.__second + other.seconds,
221.1720 - self.__microsecond + other.microseconds)
221.1721 - self._checkOverflow(t.year)
221.1722 - result = self.__class__(t.year, t.month, t.day,
221.1723 - t.hour, t.minute, t.second,
221.1724 - t.microsecond, tzinfo=self._tzinfo)
221.1725 - return result
221.1726 -
221.1727 - __radd__ = __add__
221.1728 -
221.1729 - def __sub__(self, other):
221.1730 - "Subtract two datetimes, or a datetime and a timedelta."
221.1731 - if not isinstance(other, datetime):
221.1732 - if isinstance(other, timedelta):
221.1733 - return self + -other
221.1734 - return NotImplemented
221.1735 -
221.1736 - days1 = self.toordinal()
221.1737 - days2 = other.toordinal()
221.1738 - secs1 = self.__second + self.__minute * 60 + self.__hour * 3600
221.1739 - secs2 = other.__second + other.__minute * 60 + other.__hour * 3600
221.1740 - base = timedelta(days1 - days2,
221.1741 - secs1 - secs2,
221.1742 - self.__microsecond - other.__microsecond)
221.1743 - if self._tzinfo is other._tzinfo:
221.1744 - return base
221.1745 - myoff = self._utcoffset()
221.1746 - otoff = other._utcoffset()
221.1747 - if myoff == otoff:
221.1748 - return base
221.1749 - if myoff is None or otoff is None:
221.1750 - raise TypeError, "cannot mix naive and timezone-aware time"
221.1751 - return base + timedelta(minutes = otoff-myoff)
221.1752 -
221.1753 - def __hash__(self):
221.1754 - tzoff = self._utcoffset()
221.1755 - if tzoff is None:
221.1756 - return hash(self.__getstate()[0])
221.1757 - days = _ymd2ord(self.year, self.month, self.day)
221.1758 - seconds = self.hour * 3600 + (self.minute - tzoff) * 60 + self.second
221.1759 - return hash(timedelta(days, seconds, self.microsecond))
221.1760 -
221.1761 - # Pickle support.
221.1762 -
221.1763 - __safe_for_unpickling__ = True # For Python 2.2
221.1764 -
221.1765 - def __getstate(self):
221.1766 - yhi, ylo = divmod(self.__year, 256)
221.1767 - us2, us3 = divmod(self.__microsecond, 256)
221.1768 - us1, us2 = divmod(us2, 256)
221.1769 - basestate = ("%c" * 10) % (yhi, ylo, self.__month, self.__day,
221.1770 - self.__hour, self.__minute, self.__second,
221.1771 - us1, us2, us3)
221.1772 - if self._tzinfo is None:
221.1773 - return (basestate,)
221.1774 - else:
221.1775 - return (basestate, self._tzinfo)
221.1776 -
221.1777 - def __setstate(self, state):
221.1778 - assert isinstance(state, tuple)
221.1779 - assert 1 <= len(state) <= 2
221.1780 - string = state[0]
221.1781 - assert len(string) == 10
221.1782 - (yhi, ylo, self.__month, self.__day, self.__hour,
221.1783 - self.__minute, self.__second, us1, us2, us3) = map(ord, string)
221.1784 - self.__year = yhi * 256 + ylo
221.1785 - self.__microsecond = (((us1 << 8) | us2) << 8) | us3
221.1786 - if len(state) == 1:
221.1787 - self._tzinfo = None
221.1788 - else:
221.1789 - self._tzinfo = state[1]
221.1790 -
221.1791 - def __reduce__(self):
221.1792 - return (self.__class__, self.__getstate())
221.1793 -
221.1794 -
221.1795 -datetime.min = datetime(1, 1, 1)
221.1796 -datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
221.1797 -datetime.resolution = timedelta(microseconds=1)
221.1798 -
221.1799 -
221.1800 -def _isoweek1monday(year):
221.1801 - # Helper to calculate the day number of the Monday starting week 1
221.1802 - # XXX This could be done more efficiently
221.1803 - THURSDAY = 3
221.1804 - firstday = _ymd2ord(year, 1, 1)
221.1805 - firstweekday = (firstday + 6) % 7 # See weekday() above
221.1806 - week1monday = firstday - firstweekday
221.1807 - if firstweekday > THURSDAY:
221.1808 - week1monday += 7
221.1809 - return week1monday
221.1810 -
221.1811 -"""
221.1812 -Some time zone algebra. For a datetime x, let
221.1813 - x.n = x stripped of its timezone -- its naive time.
221.1814 - x.o = x.utcoffset(), and assuming that doesn't raise an exception or
221.1815 - return None
221.1816 - x.d = x.dst(), and assuming that doesn't raise an exception or
221.1817 - return None
221.1818 - x.s = x's standard offset, x.o - x.d
221.1819 -
221.1820 -Now some derived rules, where k is a duration (timedelta).
221.1821 -
221.1822 -1. x.o = x.s + x.d
221.1823 - This follows from the definition of x.s.
221.1824 -
221.1825 -2. If x and y have the same tzinfo member, x.s = y.s.
221.1826 - This is actually a requirement, an assumption we need to make about
221.1827 - sane tzinfo classes.
221.1828 -
221.1829 -3. The naive UTC time corresponding to x is x.n - x.o.
221.1830 - This is again a requirement for a sane tzinfo class.
221.1831 -
221.1832 -4. (x+k).s = x.s
221.1833 - This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
221.1834 -
221.1835 -5. (x+k).n = x.n + k
221.1836 - Again follows from how arithmetic is defined.
221.1837 -
221.1838 -Now we can explain tz.fromutc(x). Let's assume it's an interesting case
221.1839 -(meaning that the various tzinfo methods exist, and don't blow up or return
221.1840 -None when called).
221.1841 -
221.1842 -The function wants to return a datetime y with timezone tz, equivalent to x.
221.1843 -x is already in UTC.
221.1844 -
221.1845 -By #3, we want
221.1846 -
221.1847 - y.n - y.o = x.n [1]
221.1848 -
221.1849 -The algorithm starts by attaching tz to x.n, and calling that y. So
221.1850 -x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
221.1851 -becomes true; in effect, we want to solve [2] for k:
221.1852 -
221.1853 - (y+k).n - (y+k).o = x.n [2]
221.1854 -
221.1855 -By #1, this is the same as
221.1856 -
221.1857 - (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
221.1858 -
221.1859 -By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
221.1860 -Substituting that into [3],
221.1861 -
221.1862 - x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
221.1863 - k - (y+k).s - (y+k).d = 0; rearranging,
221.1864 - k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
221.1865 - k = y.s - (y+k).d
221.1866 -
221.1867 -On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
221.1868 -approximate k by ignoring the (y+k).d term at first. Note that k can't be
221.1869 -very large, since all offset-returning methods return a duration of magnitude
221.1870 -less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
221.1871 -be 0, so ignoring it has no consequence then.
221.1872 -
221.1873 -In any case, the new value is
221.1874 -
221.1875 - z = y + y.s [4]
221.1876 -
221.1877 -It's helpful to step back at look at [4] from a higher level: it's simply
221.1878 -mapping from UTC to tz's standard time.
221.1879 -
221.1880 -At this point, if
221.1881 -
221.1882 - z.n - z.o = x.n [5]
221.1883 -
221.1884 -we have an equivalent time, and are almost done. The insecurity here is
221.1885 -at the start of daylight time. Picture US Eastern for concreteness. The wall
221.1886 -time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
221.1887 -sense then. The docs ask that an Eastern tzinfo class consider such a time to
221.1888 -be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
221.1889 -on the day DST starts. We want to return the 1:MM EST spelling because that's
221.1890 -the only spelling that makes sense on the local wall clock.
221.1891 -
221.1892 -In fact, if [5] holds at this point, we do have the standard-time spelling,
221.1893 -but that takes a bit of proof. We first prove a stronger result. What's the
221.1894 -difference between the LHS and RHS of [5]? Let
221.1895 -
221.1896 - diff = x.n - (z.n - z.o) [6]
221.1897 -
221.1898 -Now
221.1899 - z.n = by [4]
221.1900 - (y + y.s).n = by #5
221.1901 - y.n + y.s = since y.n = x.n
221.1902 - x.n + y.s = since z and y are have the same tzinfo member,
221.1903 - y.s = z.s by #2
221.1904 - x.n + z.s
221.1905 -
221.1906 -Plugging that back into [6] gives
221.1907 -
221.1908 - diff =
221.1909 - x.n - ((x.n + z.s) - z.o) = expanding
221.1910 - x.n - x.n - z.s + z.o = cancelling
221.1911 - - z.s + z.o = by #2
221.1912 - z.d
221.1913 -
221.1914 -So diff = z.d.
221.1915 -
221.1916 -If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
221.1917 -spelling we wanted in the endcase described above. We're done. Contrarily,
221.1918 -if z.d = 0, then we have a UTC equivalent, and are also done.
221.1919 -
221.1920 -If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
221.1921 -add to z (in effect, z is in tz's standard time, and we need to shift the
221.1922 -local clock into tz's daylight time).
221.1923 -
221.1924 -Let
221.1925 -
221.1926 - z' = z + z.d = z + diff [7]
221.1927 -
221.1928 -and we can again ask whether
221.1929 -
221.1930 - z'.n - z'.o = x.n [8]
221.1931 -
221.1932 -If so, we're done. If not, the tzinfo class is insane, according to the
221.1933 -assumptions we've made. This also requires a bit of proof. As before, let's
221.1934 -compute the difference between the LHS and RHS of [8] (and skipping some of
221.1935 -the justifications for the kinds of substitutions we've done several times
221.1936 -already):
221.1937 -
221.1938 - diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
221.1939 - x.n - (z.n + diff - z'.o) = replacing diff via [6]
221.1940 - x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
221.1941 - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
221.1942 - - z.n + z.n - z.o + z'.o = cancel z.n
221.1943 - - z.o + z'.o = #1 twice
221.1944 - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
221.1945 - z'.d - z.d
221.1946 -
221.1947 -So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
221.1948 -we've found the UTC-equivalent so are done. In fact, we stop with [7] and
221.1949 -return z', not bothering to compute z'.d.
221.1950 -
221.1951 -How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
221.1952 -a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
221.1953 -would have to change the result dst() returns: we start in DST, and moving
221.1954 -a little further into it takes us out of DST.
221.1955 -
221.1956 -There isn't a sane case where this can happen. The closest it gets is at
221.1957 -the end of DST, where there's an hour in UTC with no spelling in a hybrid
221.1958 -tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
221.1959 -that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
221.1960 -UTC) because the docs insist on that, but 0:MM is taken as being in daylight
221.1961 -time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
221.1962 -clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
221.1963 -standard time. Since that's what the local clock *does*, we want to map both
221.1964 -UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
221.1965 -in local time, but so it goes -- it's the way the local clock works.
221.1966 -
221.1967 -When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
221.1968 -so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
221.1969 -z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
221.1970 -(correctly) concludes that z' is not UTC-equivalent to x.
221.1971 -
221.1972 -Because we know z.d said z was in daylight time (else [5] would have held and
221.1973 -we would have stopped then), and we know z.d != z'.d (else [8] would have held
221.1974 -and we we have stopped then), and there are only 2 possible values dst() can
221.1975 -return in Eastern, it follows that z'.d must be 0 (which it is in the example,
221.1976 -but the reasoning doesn't depend on the example -- it depends on there being
221.1977 -two possible dst() outcomes, one zero and the other non-zero). Therefore
221.1978 -z' must be in standard time, and is the spelling we want in this case.
221.1979 -
221.1980 -Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
221.1981 -concerned (because it takes z' as being in standard time rather than the
221.1982 -daylight time we intend here), but returning it gives the real-life "local
221.1983 -clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
221.1984 -tz.
221.1985 -
221.1986 -When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
221.1987 -the 1:MM standard time spelling we want.
221.1988 -
221.1989 -So how can this break? One of the assumptions must be violated. Two
221.1990 -possibilities:
221.1991 -
221.1992 -1) [2] effectively says that y.s is invariant across all y belong to a given
221.1993 - time zone. This isn't true if, for political reasons or continental drift,
221.1994 - a region decides to change its base offset from UTC.
221.1995 -
221.1996 -2) There may be versions of "double daylight" time where the tail end of
221.1997 - the analysis gives up a step too early. I haven't thought about that
221.1998 - enough to say.
221.1999 -
221.2000 -In any case, it's clear that the default fromutc() is strong enough to handle
221.2001 -"almost all" time zones: so long as the standard offset is invariant, it
221.2002 -doesn't matter if daylight time transition points change from year to year, or
221.2003 -if daylight time is skipped in some years; it doesn't matter how large or
221.2004 -small dst() may get within its bounds; and it doesn't even matter if some
221.2005 -perverse time zone returns a negative dst()). So a breaking case must be
221.2006 -pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
221.2007 -"""
221.2008 -
221.2009 -def _test():
221.2010 - import test_datetime
221.2011 - test_datetime.test_main()
221.2012 -
221.2013 -if __name__ == "__main__":
221.2014 - _test()
222.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testHint1.hints Sun Jan 04 13:11:53 2015 -0600
222.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
222.3 @@ -1,7 +0,0 @@
222.4 -for dim in _DAYS_IN_MONTH[1:]:
222.5 -
222.6 -HINT:Surround With...
222.7 -FIX:Surround With Try/Except
222.8 -FIX:Surround With Try/Except/Finally
222.9 -FIX:Surround With Try/Finally
222.10 -del dbm, dim^
223.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testHint2.hints Sun Jan 04 13:11:53 2015 -0600
223.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
223.3 @@ -1,6 +0,0 @@
223.4 - "year -> number of days in year (366 if a leap year, else 365)."^
223.5 - ----------------------------------------------------------------
223.6 -HINT:Surround With...
223.7 -FIX:Surround With Try/Except
223.8 -FIX:Surround With Try/Except/Finally
223.9 -FIX:Surround With Try/Finally
224.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testHint3.hints Sun Jan 04 13:11:53 2015 -0600
224.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
224.3 @@ -1,7 +0,0 @@
224.4 - # Now compute how many 4-year cycles precede it.
224.5 -
224.6 -HINT:Surround With...
224.7 -FIX:Surround With Try/Except
224.8 -FIX:Surround With Try/Except/Finally
224.9 -FIX:Surround With Try/Finally
224.10 -^ # And now how many single years. Again n1 can be 4, and again meaning
225.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testHint5.hints Sun Jan 04 13:11:53 2015 -0600
225.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
225.3 @@ -1,54 +0,0 @@
225.4 -class tmxxx:
225.5 - -----
225.6 -HINT:Name "tmxxx" is not a valid class name according to your code style (CapitalizedWords)
225.7 -FIX:Ignore name violations for "tmxxx"
225.8 -FIX:Change preferred class name style to lowercase
225.9 -FIX:Change preferred class name style to lowercase_with_underscores
225.10 -FIX:Change preferred class name style to mixedCase
225.11 -FIX:Turn off class name style checks
225.12 -class timedelta(object):
225.13 - ---------
225.14 -HINT:Name "timedelta" is not a valid class name according to your code style (CapitalizedWords)
225.15 -FIX:Ignore name violations for "timedelta"
225.16 -FIX:Change preferred class name style to lowercase
225.17 -FIX:Change preferred class name style to lowercase_with_underscores
225.18 -FIX:Change preferred class name style to mixedCase
225.19 -FIX:Turn off class name style checks
225.20 -class date(object):
225.21 - ----
225.22 -HINT:Name "date" is not a valid class name according to your code style (CapitalizedWords)
225.23 -FIX:Ignore name violations for "date"
225.24 -FIX:Change preferred class name style to lowercase
225.25 -FIX:Change preferred class name style to lowercase_with_underscores
225.26 -FIX:Change preferred class name style to mixedCase
225.27 -FIX:Turn off class name style checks
225.28 - def _checkOverflow(self, year):
225.29 - --------------
225.30 -HINT:Name "_checkOverflow" is not a valid function name according to your code style (lowercase_with_underscores)
225.31 -FIX:Ignore name violations for "_checkOverflow"
225.32 -FIX:Change preferred function name style to mixedCase
225.33 -FIX:Turn off function name style checks
225.34 -class tzinfo(object):
225.35 - ------
225.36 -HINT:Name "tzinfo" is not a valid class name according to your code style (CapitalizedWords)
225.37 -FIX:Ignore name violations for "tzinfo"
225.38 -FIX:Change preferred class name style to lowercase
225.39 -FIX:Change preferred class name style to lowercase_with_underscores
225.40 -FIX:Change preferred class name style to mixedCase
225.41 -FIX:Turn off class name style checks
225.42 -class time(object):
225.43 - ----
225.44 -HINT:Name "time" is not a valid class name according to your code style (CapitalizedWords)
225.45 -FIX:Ignore name violations for "time"
225.46 -FIX:Change preferred class name style to lowercase
225.47 -FIX:Change preferred class name style to lowercase_with_underscores
225.48 -FIX:Change preferred class name style to mixedCase
225.49 -FIX:Turn off class name style checks
225.50 -class datetime(date):
225.51 - --------
225.52 -HINT:Name "datetime" is not a valid class name according to your code style (CapitalizedWords)
225.53 -FIX:Ignore name violations for "datetime"
225.54 -FIX:Change preferred class name style to lowercase
225.55 -FIX:Change preferred class name style to lowercase_with_underscores
225.56 -FIX:Change preferred class name style to mixedCase
225.57 -FIX:Turn off class name style checks
226.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testLocals2.completion Sun Jan 04 13:11:53 2015 -0600
226.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
226.3 @@ -1,1276 +0,0 @@
226.4 -Code completion result for source line:
226.5 -|dnum = _days_before_month(y, m) + d
226.6 -(QueryType=COMPLETION, NameKind=PREFIX)
226.7 -MODULE _math [PRIVATE]
226.8 -MODULE _time [PRIVATE]
226.9 -CLASS date
226.10 -CLASS datetime
226.11 -CLASS time
226.12 -CLASS timedelta
226.13 -CLASS tmxxx
226.14 -CLASS tzinfo
226.15 -METHOD _build_struct_time(y, m, d, hh [PRIVATE]
226.16 -METHOD _call_tzinfo_method(tzinfo, me [PRIVATE]
226.17 -METHOD _check_date_fields(year, month [PRIVATE]
226.18 -METHOD _check_time_fields(hour, minut [PRIVATE]
226.19 -METHOD _check_tzinfo_arg(tz) [PRIVATE]
226.20 -METHOD _check_tzname(name) [PRIVATE]
226.21 -METHOD _check_utc_offset(name, offset [PRIVATE]
226.22 -METHOD _cmperror(x, y) [PRIVATE]
226.23 -METHOD _days_before_month(year, month [PRIVATE]
226.24 -METHOD _days_before_year(year) [PRIVATE]
226.25 -METHOD _days_in_month(year, month) [PRIVATE]
226.26 -METHOD _days_in_year(year) [PRIVATE]
226.27 -METHOD _format_time(hh, mm, ss, us) [PRIVATE]
226.28 -METHOD _is_leap(year) [PRIVATE]
226.29 -METHOD _isoweek1monday(year) [PRIVATE]
226.30 -METHOD _ord2ymd(n) [PRIVATE]
226.31 -METHOD _test() [PRIVATE]
226.32 -METHOD _wrap_strftime(object, format, [PRIVATE]
226.33 -METHOD _ymd2ord(year, month, day) [PRIVATE]
226.34 -VARIABLE MAXYEAR
226.35 -VARIABLE MINYEAR
226.36 -VARIABLE _DAYNAMES [PRIVATE]
226.37 -VARIABLE _DAYS_BEFORE_MONTH [PRIVATE]
226.38 -VARIABLE _DAYS_IN_MONTH [PRIVATE]
226.39 -VARIABLE _DI100Y [PRIVATE]
226.40 -VARIABLE _DI400Y [PRIVATE]
226.41 -VARIABLE _DI4Y [PRIVATE]
226.42 -VARIABLE _MONTHNAMES [PRIVATE]
226.43 -VARIABLE _ORD1970 [PRIVATE]
226.44 -VARIABLE _date_class [PRIVATE]
226.45 -VARIABLE _time_class [PRIVATE]
226.46 -VARIABLE _tzinfo_class [PRIVATE]
226.47 -VARIABLE d
226.48 -VARIABLE dbm
226.49 -VARIABLE dim
226.50 -VARIABLE dnum
226.51 -VARIABLE dstflag
226.52 -VARIABLE hh
226.53 -VARIABLE m
226.54 -VARIABLE mm
226.55 -VARIABLE ss
226.56 -VARIABLE wday
226.57 -VARIABLE y
226.58 -------------------------------------
226.59 -CLASS A
226.60 -CLASS ABCMeta
226.61 -CLASS AEServer
226.62 -CLASS AEText
226.63 -CLASS ASTVisitor
226.64 -CLASS AbstractBasicAuthHandler
226.65 -CLASS AbstractClassCode
226.66 -CLASS AbstractCompileMode
226.67 -CLASS AbstractDigestAuthHandler
226.68 -CLASS AbstractFormatter
226.69 -CLASS AbstractFunctionCode
226.70 -CLASS AbstractHTTPHandler
226.71 -CLASS AbstractWriter
226.72 -CLASS Add
226.73 -CLASS And
226.74 -CLASS Application
226.75 -CLASS ArgumentError
226.76 -CLASS ArithmeticError
226.77 -CLASS ArithmeticError
226.78 -CLASS Array
226.79 -CLASS ArrayInstance
226.80 -CLASS AssAttr
226.81 -CLASS AssList
226.82 -CLASS AssName
226.83 -CLASS AssTuple
226.84 -CLASS Assert
226.85 -CLASS AssertionError
226.86 -CLASS AssertionError
226.87 -CLASS Assign
226.88 -CLASS AsyncResult
226.89 -CLASS Attr
226.90 -CLASS AttributeError
226.91 -CLASS AttributeError
226.92 -CLASS AttributeList
226.93 -CLASS AttributeMap
226.94 -CLASS Attributes
226.95 -CLASS AttributesImpl
226.96 -CLASS AttributesNS
226.97 -CLASS AttributesNSImpl
226.98 -CLASS AugAssign
226.99 -CLASS AugGetattr
226.100 -CLASS AugName
226.101 -CLASS AugSlice
226.102 -CLASS AugSubscript
226.103 -CLASS AuthenticationError
226.104 -CLASS AutoGILError
226.105 -CLASS B
226.106 -CLASS BCPPCompiler
226.107 -CLASS BCPTestCase
226.108 -CLASS BZ2Compressor
226.109 -CLASS BZ2Decompressor
226.110 -CLASS BZ2File
226.111 -CLASS Babyl
226.112 -CLASS BabylMailbox
226.113 -CLASS BabylMessage
226.114 -CLASS Backquote
226.115 -CLASS BadBoundaryPointsErr
226.116 -CLASS BadFutureParser
226.117 -CLASS BadOptionError
226.118 -CLASS BadStatusLine
226.119 -CLASS BadZipfile
226.120 -CLASS Balloon
226.121 -CLASS Bar
226.122 -CLASS BaseCGIHandler
226.123 -CLASS BaseCookie
226.124 -CLASS BaseException
226.125 -CLASS BaseException
226.126 -CLASS BaseHTTPRequestHandler
226.127 -CLASS BaseHandler
226.128 -CLASS BaseIncrementalParser
226.129 -CLASS BaseManager
226.130 -CLASS BaseProxy
226.131 -CLASS BaseRequestHandler
226.132 -CLASS BaseRotatingHandler
226.133 -CLASS BaseSet
226.134 -CLASS BasicModuleImporter
226.135 -CLASS BasicModuleLoader
226.136 -CLASS BastionClass
226.137 -CLASS Baz
226.138 -CLASS Bdb
226.139 -CLASS BdbQuit
226.140 -CLASS BigEndianStructure
226.141 -CLASS Binary
226.142 -CLASS Bitand
226.143 -CLASS Bitor
226.144 -CLASS Bitxor
226.145 -CLASS Block
226.146 -CLASS BlockFinder
226.147 -CLASS BlockingIOError
226.148 -CLASS Boolean
226.149 -CLASS BoundaryError
226.150 -CLASS BoundedSemaphore
226.151 -CLASS Break
226.152 -CLASS Breakpoint
226.153 -CLASS BsdDbShelf
226.154 -CLASS BufferTooShort
226.155 -CLASS BufferedIOBase
226.156 -CLASS BufferedRWPair
226.157 -CLASS BufferedRandom
226.158 -CLASS BufferedReader
226.159 -CLASS BufferedWriter
226.160 -CLASS BufferingFormatter
226.161 -CLASS BufferingHandler
226.162 -CLASS BuildPyTestCase
226.163 -CLASS BuildScriptsTestCase
226.164 -CLASS BuiltinImporter
226.165 -CLASS Bulkcopy
226.166 -CLASS ButtonBox
226.167 -CLASS BytesIO
226.168 -CLASS C
226.169 -CLASS CAB
226.170 -CLASS CCompiler
226.171 -CLASS CCompilerError
226.172 -CLASS CDATASection
226.173 -CLASS CDLL
226.174 -CLASS CGIHTTPRequestHandler
226.175 -CLASS CGIHandler
226.176 -CLASS CGIXMLRPCRequestHandler
226.177 -CLASS CacheFTPHandler
226.178 -CLASS CallFunc
226.179 -CLASS CalledProcessError
226.180 -CLASS CannotSendHeader
226.181 -CLASS CannotSendRequest
226.182 -CLASS Canonizer
226.183 -CLASS CharacterData
226.184 -CLASS Charset
226.185 -CLASS CharsetError
226.186 -CLASS CheckList
226.187 -CLASS Childless
226.188 -CLASS Chunk
226.189 -CLASS Clamped
226.190 -CLASS Class
226.191 -CLASS ClassCodeGenerator
226.192 -CLASS ClassScope
226.193 -CLASS Cmd
226.194 -CLASS CodeGenerator
226.195 -CLASS Codec
226.196 -CLASS CodecRegistryError
226.197 -CLASS ComboBox
226.198 -CLASS Command
226.199 -CLASS CommandCompiler
226.200 -CLASS Comment
226.201 -CLASS Compare
226.202 -CLASS Comparison
226.203 -CLASS Compile
226.204 -CLASS CompileError
226.205 -CLASS Completer
226.206 -CLASS Complex
226.207 -CLASS ComponentItem
226.208 -CLASS Condition
226.209 -CLASS ConfigParser
226.210 -CLASS Connection
226.211 -CLASS Const
226.212 -CLASS ContentGenerator
226.213 -CLASS ContentHandler
226.214 -CLASS Context
226.215 -CLASS Continue
226.216 -CLASS Control
226.217 -CLASS ControlsWindow
226.218 -CLASS ConversionError
226.219 -CLASS Cookie
226.220 -CLASS CookieError
226.221 -CLASS CookieJar
226.222 -CLASS CookiePolicy
226.223 -CLASS CoverageResults
226.224 -CLASS Cursor
226.225 -CLASS CygwinCCompiler
226.226 -CLASS D
226.227 -CLASS DOMBuilder
226.228 -CLASS DOMEntityResolver
226.229 -CLASS DOMError
226.230 -CLASS DOMEventStream
226.231 -CLASS DOMException
226.232 -CLASS DOMImplementation
226.233 -CLASS DOMInputSource
226.234 -CLASS DOMStringSizeErr
226.235 -CLASS DTDHandler
226.236 -CLASS Data
226.237 -CLASS Database
226.238 -CLASS DatagramHandler
226.239 -CLASS DatagramRequestHandler
226.240 -CLASS DateTime
226.241 -CLASS DbfilenameShelf
226.242 -CLASS DebugRunner
226.243 -CLASS DebuggingServer
226.244 -CLASS Decimal
226.245 -CLASS DecimalException
226.246 -CLASS DeclHandler
226.247 -CLASS DecodedGenerator
226.248 -CLASS Decorators
226.249 -CLASS DefaultCookiePolicy
226.250 -CLASS DefaultHandler
226.251 -CLASS Delegator
226.252 -CLASS DeprecationWarning
226.253 -CLASS DeprecationWarning
226.254 -CLASS Dialect
226.255 -CLASS Dialog
226.256 -CLASS DialogWindow
226.257 -CLASS Dict
226.258 -CLASS DictMixin
226.259 -CLASS DictReader
226.260 -CLASS DictWriter
226.261 -CLASS Differ
226.262 -CLASS DirList
226.263 -CLASS DirSelectBox
226.264 -CLASS DirSelectDialog
226.265 -CLASS DirTree
226.266 -CLASS Directory
226.267 -CLASS Discard
226.268 -CLASS Distribution
226.269 -CLASS DistributionMetadata
226.270 -CLASS DistributionTestCase
226.271 -CLASS DistutilsArgError
226.272 -CLASS DistutilsClassError
226.273 -CLASS DistutilsError
226.274 -CLASS DistutilsExecError
226.275 -CLASS DistutilsFileError
226.276 -CLASS DistutilsGetoptError
226.277 -CLASS DistutilsInternalError
226.278 -CLASS DistutilsModuleError
226.279 -CLASS DistutilsOptionError
226.280 -CLASS DistutilsPlatformError
226.281 -CLASS DistutilsSetupError
226.282 -CLASS DistutilsTemplateError
226.283 -CLASS Div
226.284 -CLASS DivisionByZero
226.285 -CLASS Doc
226.286 -CLASS DocCGIXMLRPCRequestHandler
226.287 -CLASS DocTest
226.288 -CLASS DocTestFailure
226.289 -CLASS DocTestFinder
226.290 -CLASS DocTestParser
226.291 -CLASS DocTestRunner
226.292 -CLASS DocXMLRPCRequestHandler
226.293 -CLASS DocXMLRPCServer
226.294 -CLASS Document
226.295 -CLASS DocumentFragment
226.296 -CLASS DocumentHandler
226.297 -CLASS DocumentType
226.298 -CLASS DomstringSizeErr
226.299 -CLASS DumbWriter
226.300 -CLASS DummyCommand
226.301 -CLASS DuplicateSectionError
226.302 -CLASS DynLoadSuffixImporter
226.303 -CLASS EMXCCompiler
226.304 -CLASS EOFError
226.305 -CLASS EOFError
226.306 -CLASS ESISDocHandler
226.307 -CLASS Element
226.308 -CLASS ElementInfo
226.309 -CLASS ElementTree
226.310 -CLASS Ellipsis
226.311 -CLASS Empty
226.312 -CLASS EmptyNode
226.313 -CLASS EndOfBlock
226.314 -CLASS Entity
226.315 -CLASS EntityResolver
226.316 -CLASS Enum
226.317 -CLASS EnvironmentError
226.318 -CLASS EnvironmentError
226.319 -CLASS Error
226.320 -CLASS ErrorDuringImport
226.321 -CLASS ErrorHandler
226.322 -CLASS ErrorPrinter
226.323 -CLASS ErrorRaiser
226.324 -CLASS Event
226.325 -CLASS EventBroadcaster
226.326 -CLASS EventException
226.327 -CLASS ExFileSelectBox
226.328 -CLASS Example
226.329 -CLASS ExampleASTVisitor
226.330 -CLASS Exception
226.331 -CLASS Exception
226.332 -CLASS Exec
226.333 -CLASS ExitNow
226.334 -CLASS ExpatError
226.335 -CLASS ExpatParser
226.336 -CLASS Expression
226.337 -CLASS ExpressionCodeGenerator
226.338 -CLASS Extension
226.339 -CLASS F
226.340 -CLASS FTP
226.341 -CLASS FTPHandler
226.342 -CLASS Factory
226.343 -CLASS FancyGetopt
226.344 -CLASS FancyModuleLoader
226.345 -CLASS FancyURLopener
226.346 -CLASS Fault
226.347 -CLASS Feature
226.348 -CLASS FeedParser
226.349 -CLASS FieldStorage
226.350 -CLASS FileCookieJar
226.351 -CLASS FileEntry
226.352 -CLASS FileHandler
226.353 -CLASS FileIO
226.354 -CLASS FileInput
226.355 -CLASS FileList
226.356 -CLASS FileSelectBox
226.357 -CLASS FileWrapper
226.358 -CLASS Filter
226.359 -CLASS Filterer
226.360 -CLASS FingerHandler
226.361 -CLASS FirstHeaderLineIsContinuationD
226.362 -CLASS FloatingPointError
226.363 -CLASS FloatingPointError
226.364 -CLASS FloorDiv
226.365 -CLASS FlowGraph
226.366 -CLASS Folder
226.367 -CLASS Foo
226.368 -CLASS For
226.369 -CLASS ForkingMixIn
226.370 -CLASS ForkingTCPServer
226.371 -CLASS ForkingUDPServer
226.372 -CLASS Form
226.373 -CLASS FormContent
226.374 -CLASS FormContentDict
226.375 -CLASS Formatter
226.376 -CLASS Fraction
226.377 -CLASS From
226.378 -CLASS FtException
226.379 -CLASS Full
226.380 -CLASS FuncPtr
226.381 -CLASS Function
226.382 -CLASS FunctionCodeGenerator
226.383 -CLASS FunctionScope
226.384 -CLASS FunctionTestCase
226.385 -CLASS FutureParser
226.386 -CLASS FutureWarning
226.387 -CLASS FutureWarning
226.388 -CLASS GNUTranslations
226.389 -CLASS GenExpr
226.390 -CLASS GenExprFor
226.391 -CLASS GenExprIf
226.392 -CLASS GenExprInner
226.393 -CLASS GenExprScope
226.394 -CLASS Generator
226.395 -CLASS GeneratorExit
226.396 -CLASS GeneratorExit
226.397 -CLASS Getattr
226.398 -CLASS GetattrMagic
226.399 -CLASS GetoptError
226.400 -CLASS Global
226.401 -CLASS GopherError
226.402 -CLASS GopherHandler
226.403 -CLASS GridBag
226.404 -CLASS GzipFile
226.405 -CLASS HList
226.406 -CLASS HMAC
226.407 -CLASS HRESULT
226.408 -CLASS HTMLDoc
226.409 -CLASS HTMLParseError
226.410 -CLASS HTMLParser
226.411 -CLASS HTMLRepr
226.412 -CLASS HTTP
226.413 -CLASS HTTPBasicAuthHandler
226.414 -CLASS HTTPConnection
226.415 -CLASS HTTPCookieProcessor
226.416 -CLASS HTTPDefaultErrorHandler
226.417 -CLASS HTTPDigestAuthHandler
226.418 -CLASS HTTPError
226.419 -CLASS HTTPErrorProcessor
226.420 -CLASS HTTPException
226.421 -CLASS HTTPHandler
226.422 -CLASS HTTPPasswordMgr
226.423 -CLASS HTTPPasswordMgrWithDefaultReal
226.424 -CLASS HTTPRedirectHandler
226.425 -CLASS HTTPResponse
226.426 -CLASS HTTPSConnection
226.427 -CLASS HTTPSHandler
226.428 -CLASS HTTPServer
226.429 -CLASS Handler
226.430 -CLASS HandlerBase
226.431 -CLASS Header
226.432 -CLASS HeaderParseError
226.433 -CLASS HeaderParser
226.434 -CLASS Headers
226.435 -CLASS HelpFormatter
226.436 -CLASS Helper
226.437 -CLASS HierarchyRequestErr
226.438 -CLASS Hook
226.439 -CLASS Hooks
226.440 -CLASS HtmlDiff
226.441 -CLASS IC
226.442 -CLASS IMAP4
226.443 -CLASS IMAP4_SSL
226.444 -CLASS IMAP4_stream
226.445 -CLASS IOBase
226.446 -CLASS IOError
226.447 -CLASS IOError
226.448 -CLASS Identified
226.449 -CLASS If
226.450 -CLASS IfExp
226.451 -CLASS Ignore
226.452 -CLASS IllegalMonthError
226.453 -CLASS IllegalWeekdayError
226.454 -CLASS ImmutableSet
226.455 -CLASS ImpImporter
226.456 -CLASS ImpLoader
226.457 -CLASS Import
226.458 -CLASS ImportError
226.459 -CLASS ImportError
226.460 -CLASS ImportManager
226.461 -CLASS ImportWarning
226.462 -CLASS ImportWarning
226.463 -CLASS Importer
226.464 -CLASS ImproperConnectionState
226.465 -CLASS Incomplete
226.466 -CLASS IncompleteRead
226.467 -CLASS IncrementalDecoder
226.468 -CLASS IncrementalEncoder
226.469 -CLASS IncrementalNewlineDecoder
226.470 -CLASS IncrementalParser
226.471 -CLASS IndentedHelpFormatter
226.472 -CLASS IndexError
226.473 -CLASS IndexError
226.474 -CLASS IndexSizeErr
226.475 -CLASS Inexact
226.476 -CLASS IniParser
226.477 -CLASS InputOnly
226.478 -CLASS InputSource
226.479 -CLASS InsertionLoc
226.480 -CLASS InstallScriptsTestCase
226.481 -CLASS InstallTestCase
226.482 -CLASS Integral
226.483 -CLASS Interactive
226.484 -CLASS InteractiveCodeGenerator
226.485 -CLASS InteractiveConsole
226.486 -CLASS InteractiveInterpreter
226.487 -CLASS InterpFormContentDict
226.488 -CLASS InterpolationDepthError
226.489 -CLASS InterpolationError
226.490 -CLASS InterpolationSyntaxError
226.491 -CLASS IntlText
226.492 -CLASS IntlWritingCode
226.493 -CLASS InuseAttributeErr
226.494 -CLASS InvalidAccessErr
226.495 -CLASS InvalidCharacterErr
226.496 -CLASS InvalidModificationErr
226.497 -CLASS InvalidNodeTypeErr
226.498 -CLASS InvalidOperation
226.499 -CLASS InvalidStateErr
226.500 -CLASS InvalidURL
226.501 -CLASS Invert
226.502 -CLASS IsqlCmd
226.503 -CLASS IsqlExit
226.504 -CLASS IterableUserDict
226.505 -CLASS JSONDecoder
226.506 -CLASS JSONEncoder
226.507 -CLASS JavaSAXParser
226.508 -CLASS JoinableQueue
226.509 -CLASS JyDTDHandlerWrapper
226.510 -CLASS JyEntityResolverWrapper
226.511 -CLASS JyErrorHandlerWrapper
226.512 -CLASS JyInputSourceWrapper
226.513 -CLASS JythonCompiler
226.514 -CLASS JythonSignalHandler
226.515 -CLASS KeyError
226.516 -CLASS KeyError
226.517 -CLASS KeyboardInterrupt
226.518 -CLASS KeyboardInterrupt
226.519 -CLASS Keyword
226.520 -CLASS LOBTestCase
226.521 -CLASS LWPCookieJar
226.522 -CLASS LabelEntry
226.523 -CLASS LabelFrame
226.524 -CLASS Lambda
226.525 -CLASS LambdaScope
226.526 -CLASS LargeZipFile
226.527 -CLASS LeftShift
226.528 -CLASS LexicalHandler
226.529 -CLASS LexicalXMLGenerator
226.530 -CLASS LibError
226.531 -CLASS LibraryLoader
226.532 -CLASS LineAddrTable
226.533 -CLASS LinkError
226.534 -CLASS List
226.535 -CLASS ListComp
226.536 -CLASS ListCompFor
226.537 -CLASS ListCompIf
226.538 -CLASS ListNoteBook
226.539 -CLASS Listener
226.540 -CLASS LittleEndianStructure
226.541 -CLASS LoadError
226.542 -CLASS LocalNameFinder
226.543 -CLASS Location
226.544 -CLASS Locator
226.545 -CLASS Lock
226.546 -CLASS Log
226.547 -CLASS LogRecord
226.548 -CLASS Logger
226.549 -CLASS LoggingSilencer
226.550 -CLASS Logical
226.551 -CLASS LookupError
226.552 -CLASS LookupError
226.553 -CLASS LooseVersion
226.554 -CLASS MH
226.555 -CLASS MHMailbox
226.556 -CLASS MHMessage
226.557 -CLASS MIMEApplication
226.558 -CLASS MIMEAudio
226.559 -CLASS MIMEBase
226.560 -CLASS MIMEImage
226.561 -CLASS MIMEMessage
226.562 -CLASS MIMEMultipart
226.563 -CLASS MIMENonMultipart
226.564 -CLASS MIMEText
226.565 -CLASS MMDF
226.566 -CLASS MMDFMessage
226.567 -CLASS MSVCCompiler
226.568 -CLASS MWerksCompiler
226.569 -CLASS MacroExpander
226.570 -CLASS Mailbox
226.571 -CLASS Maildir
226.572 -CLASS MaildirMessage
226.573 -CLASS MailmanProxy
226.574 -CLASS MalformedHeaderDefect
226.575 -CLASS Manager
226.576 -CLASS Marshaller
226.577 -CLASS MemoryError
226.578 -CLASS MemoryError
226.579 -CLASS MemoryHandler
226.580 -CLASS Message
226.581 -CLASS MessageDefect
226.582 -CLASS MessageError
226.583 -CLASS MessageParseError
226.584 -CLASS MetadataTestCase
226.585 -CLASS Meter
226.586 -CLASS MimeWriter
226.587 -CLASS Mingw32CCompiler
226.588 -CLASS MiniApplication
226.589 -CLASS MiniFieldStorage
226.590 -CLASS MisplacedEnvelopeHeaderDefect
226.591 -CLASS MissingSectionHeaderError
226.592 -CLASS MmdfMailbox
226.593 -CLASS Mod
226.594 -CLASS Model
226.595 -CLASS Module
226.596 -CLASS ModuleCodeGenerator
226.597 -CLASS ModuleFinder
226.598 -CLASS ModuleImporter
226.599 -CLASS ModuleLoader
226.600 -CLASS ModuleScanner
226.601 -CLASS ModuleScope
226.602 -CLASS MozillaCookieJar
226.603 -CLASS Mul
226.604 -CLASS MultiCall
226.605 -CLASS MultiCallIterator
226.606 -CLASS MultiFile
226.607 -CLASS MultipartConversionError
226.608 -CLASS MultipartInvariantViolationDef
226.609 -CLASS MutableString
226.610 -CLASS MyClass
226.611 -CLASS MyTest
226.612 -CLASS NNTP
226.613 -CLASS NNTPDataError
226.614 -CLASS NNTPPermanentError
226.615 -CLASS NNTPProtocolError
226.616 -CLASS NNTPReplyError
226.617 -CLASS NNTPTemporaryError
226.618 -CLASS NProperty
226.619 -CLASS NTEventLogHandler
226.620 -CLASS NULL
226.621 -CLASS Name
226.622 -CLASS NameError
226.623 -CLASS NameError
226.624 -CLASS NamedNodeMap
226.625 -CLASS NamespaceErr
226.626 -CLASS NannyNag
226.627 -CLASS NestedScopeMixin
226.628 -CLASS Netrc
226.629 -CLASS NetrcParseError
226.630 -CLASS NewStyle
226.631 -CLASS NoBoundaryInMultipartDefect
226.632 -CLASS NoDataAllowedErr
226.633 -CLASS NoModificationAllowedErr
226.634 -CLASS NoOpMetaClass
226.635 -CLASS NoOptionError
226.636 -CLASS NoSectionError
226.637 -CLASS Node
226.638 -CLASS NodeFilter
226.639 -CLASS NodeTransformer
226.640 -CLASS NodeVisitor
226.641 -CLASS Not
226.642 -CLASS NotANumber
226.643 -CLASS NotConnected
226.644 -CLASS NotFoundErr
226.645 -CLASS NotImplementedError
226.646 -CLASS NotImplementedError
226.647 -CLASS NotSupportedErr
226.648 -CLASS Notation
226.649 -CLASS NoteBook
226.650 -CLASS NullFormatter
226.651 -CLASS NullImporter
226.652 -CLASS NullTranslations
226.653 -CLASS NullWriter
226.654 -CLASS Number
226.655 -CLASS OSError
226.656 -CLASS OSError
226.657 -CLASS OSSAudioError
226.658 -CLASS ObjectSpecifier
226.659 -CLASS OleDLL
226.660 -CLASS OpFinder
226.661 -CLASS OpenerDirector
226.662 -CLASS OptParseError
226.663 -CLASS Option
226.664 -CLASS OptionConflictError
226.665 -CLASS OptionContainer
226.666 -CLASS OptionDummy
226.667 -CLASS OptionError
226.668 -CLASS OptionGroup
226.669 -CLASS OptionMenu
226.670 -CLASS OptionParser
226.671 -CLASS OptionValueError
226.672 -CLASS Or
226.673 -CLASS OracleSPTest
226.674 -CLASS Ordinal
226.675 -CLASS OutputChecker
226.676 -CLASS Overflow
226.677 -CLASS OverflowError
226.678 -CLASS OverflowError
226.679 -CLASS POP3
226.680 -CLASS POP3_SSL
226.681 -CLASS Packer
226.682 -CLASS PanedWindow
226.683 -CLASS Panel
226.684 -CLASS Parser
226.685 -CLASS ParserBase
226.686 -CLASS ParserError
226.687 -CLASS ParsingError
226.688 -CLASS Pass
226.689 -CLASS Pattern
226.690 -CLASS Pdb
226.691 -CLASS PendingDeprecationWarning
226.692 -CLASS PendingDeprecationWarning
226.693 -CLASS PickleError
226.694 -CLASS Pickler
226.695 -CLASS PicklingError
226.696 -CLASS PlaceHolder
226.697 -CLASS Popen
226.698 -CLASS Popen3
226.699 -CLASS Popen4
226.700 -CLASS PopupMenu
226.701 -CLASS PortableUnixMailbox
226.702 -CLASS Power
226.703 -CLASS PreprocessError
226.704 -CLASS PrettyPrinter
226.705 -CLASS Print
226.706 -CLASS Printnl
226.707 -CLASS Process
226.708 -CLASS ProcessingInstruction
226.709 -CLASS Profile
226.710 -CLASS ProgressBar
226.711 -CLASS Prompt
226.712 -CLASS ProtocolError
226.713 -CLASS ProxyBasicAuthHandler
226.714 -CLASS ProxyDigestAuthHandler
226.715 -CLASS ProxyHandler
226.716 -CLASS PullDOM
226.717 -CLASS PureProxy
226.718 -CLASS PyCompileError
226.719 -CLASS PyDLL
226.720 -CLASS PyDialog
226.721 -CLASS PyFlowGraph
226.722 -CLASS PyHKEY
226.723 -CLASS PyZipFile
226.724 -CLASS QDPoint
226.725 -CLASS QDRectangle
226.726 -CLASS QName
226.727 -CLASS Queue
226.728 -CLASS RExec
226.729 -CLASS RGBColor
226.730 -CLASS RLock
226.731 -CLASS RadioButtonGroup
226.732 -CLASS Raise
226.733 -CLASS Random
226.734 -CLASS Range
226.735 -CLASS RangeException
226.736 -CLASS Rational
226.737 -CLASS RawIOBase
226.738 -CLASS RawTurtle
226.739 -CLASS ReadOnlySequentialNamedNodeMap
226.740 -CLASS Real
226.741 -CLASS Record
226.742 -CLASS ReferenceError
226.743 -CLASS ReferenceError
226.744 -CLASS Repr
226.745 -CLASS Request
226.746 -CLASS ResponseError
226.747 -CLASS ResponseNotReady
226.748 -CLASS ResultSet
226.749 -CLASS ResultSetRow
226.750 -CLASS Return
226.751 -CLASS RightShift
226.752 -CLASS RobotFileParser
226.753 -CLASS RootLogger
226.754 -CLASS RotatingFileHandler
226.755 -CLASS Rounded
226.756 -CLASS Row
226.757 -CLASS RuntimeError
226.758 -CLASS RuntimeError
226.759 -CLASS RuntimeWarning
226.760 -CLASS RuntimeWarning
226.761 -CLASS SAX2DOM
226.762 -CLASS SAXException
226.763 -CLASS SAXNotRecognizedException
226.764 -CLASS SAXNotSupportedException
226.765 -CLASS SAXParseException
226.766 -CLASS SAXReaderNotAvailable
226.767 -CLASS SGMLParseError
226.768 -CLASS SGMLParser
226.769 -CLASS SMTP
226.770 -CLASS SMTPAuthenticationError
226.771 -CLASS SMTPConnectError
226.772 -CLASS SMTPDataError
226.773 -CLASS SMTPException
226.774 -CLASS SMTPHandler
226.775 -CLASS SMTPHeloError
226.776 -CLASS SMTPRecipientsRefused
226.777 -CLASS SMTPResponseException
226.778 -CLASS SMTPSenderRefused
226.779 -CLASS SMTPServer
226.780 -CLASS SMTPServerDisconnected
226.781 -CLASS SQLServerSPTest
226.782 -CLASS SQLTestCase
226.783 -CLASS SSLError
226.784 -CLASS SSLSocket
226.785 -CLASS ST
226.786 -CLASS SafeConfigParser
226.787 -CLASS SafeTransport
226.788 -CLASS Scanner
226.789 -CLASS Schema
226.790 -CLASS Scope
226.791 -CLASS Screen
226.792 -CLASS ScrolledCavas
226.793 -CLASS ScrolledText
226.794 -CLASS ScrolledWindow
226.795 -CLASS Select
226.796 -CLASS Semaphore
226.797 -CLASS SequenceMatcher
226.798 -CLASS SerialCookie
226.799 -CLASS Server
226.800 -CLASS ServerHTMLDoc
226.801 -CLASS ServerProxy
226.802 -CLASS Set
226.803 -CLASS SgmlopParser
226.804 -CLASS Shape
226.805 -CLASS Shelf
226.806 -CLASS SimpleCookie
226.807 -CLASS SimpleHTTPRequestHandler
226.808 -CLASS SimpleHandler
226.809 -CLASS SimpleLocator
226.810 -CLASS SimpleXMLRPCDispatcher
226.811 -CLASS SimpleXMLRPCRequestHandler
226.812 -CLASS SimpleXMLRPCServer
226.813 -CLASS Slice
226.814 -CLASS Sliceobj
226.815 -CLASS SlowParser
226.816 -CLASS SmartCookie
226.817 -CLASS Sniffer
226.818 -CLASS SocketHandler
226.819 -CLASS SocketType
226.820 -CLASS Stack
226.821 -CLASS StackDepthTracker
226.822 -CLASS StandardError
226.823 -CLASS StandardError
226.824 -CLASS StartBoundaryNotFoundDefect
226.825 -CLASS Stats
226.826 -CLASS StdButtonBox
226.827 -CLASS Stmt
226.828 -CLASS StopIteration
226.829 -CLASS StopIteration
226.830 -CLASS StopTokenizing
226.831 -CLASS Strange
226.832 -CLASS StreamConverter
226.833 -CLASS StreamHandler
226.834 -CLASS StreamReader
226.835 -CLASS StreamRequestHandler
226.836 -CLASS StreamWriter
226.837 -CLASS StrictVersion
226.838 -CLASS StringIO
226.839 -CLASS Struct
226.840 -CLASS Structure
226.841 -CLASS StyledText
226.842 -CLASS Sub
226.843 -CLASS SubPattern
226.844 -CLASS Subnormal
226.845 -CLASS Subscript
226.846 -CLASS SummaryInformation
226.847 -CLASS Super
226.848 -CLASS SuperSuper
226.849 -CLASS SvFormContentDict
226.850 -CLASS Symbol
226.851 -CLASS SymbolTable
226.852 -CLASS SymbolVisitor
226.853 -CLASS SyncManager
226.854 -CLASS SyntaxErr
226.855 -CLASS SyntaxError
226.856 -CLASS SyntaxError
226.857 -CLASS SyntaxErrorChecker
226.858 -CLASS SyntaxWarning
226.859 -CLASS SyntaxWarning
226.860 -CLASS SysLogHandler
226.861 -CLASS SystemError
226.862 -CLASS SystemError
226.863 -CLASS SystemExit
226.864 -CLASS SystemExit
226.865 -CLASS SystemRandom
226.866 -CLASS TCPServer
226.867 -CLASS TList
226.868 -CLASS TalkTo
226.869 -CLASS TarError
226.870 -CLASS TarFile
226.871 -CLASS TarInfo
226.872 -CLASS Telnet
226.873 -CLASS TempdirManager
226.874 -CLASS Template
226.875 -CLASS Test
226.876 -CLASS TestCase
226.877 -CLASS TestClass
226.878 -CLASS TestCrispinTorture
226.879 -CLASS TestDistribution
226.880 -CLASS TestLoader
226.881 -CLASS TestResult
226.882 -CLASS TestSuite
226.883 -CLASS TestThread
226.884 -CLASS TestXMLParser
226.885 -CLASS Testcase
226.886 -CLASS Tester
226.887 -CLASS Text
226.888 -CLASS TextDoc
226.889 -CLASS TextFile
226.890 -CLASS TextIOBase
226.891 -CLASS TextIOWrapper
226.892 -CLASS TextRepr
226.893 -CLASS TextTestRunner
226.894 -CLASS TextWrapper
226.895 -CLASS Textbox
226.896 -CLASS Thread
226.897 -CLASS ThreadingMixIn
226.898 -CLASS ThreadingTCPServer
226.899 -CLASS ThreadingUDPServer
226.900 -CLASS ThreadingUnixDatagramServer
226.901 -CLASS ThreadingUnixStreamServer
226.902 -CLASS TimedRotatingFileHandler
226.903 -CLASS Timer
226.904 -CLASS TitledHelpFormatter
226.905 -CLASS Tix
226.906 -CLASS Tk
226.907 -CLASS TokenError
226.908 -CLASS Tokenizer
226.909 -CLASS TortureBase
226.910 -CLASS Trace
226.911 -CLASS Transformer
226.912 -CLASS Transport
226.913 -CLASS Tree
226.914 -CLASS TreeBuilder
226.915 -CLASS TryExcept
226.916 -CLASS TryFinally
226.917 -CLASS Tuple
226.918 -CLASS TupleArg
226.919 -CLASS Turtle
226.920 -CLASS TurtleScreen
226.921 -CLASS Type
226.922 -CLASS TypeError
226.923 -CLASS TypeError
226.924 -CLASS TypeInfo
226.925 -CLASS UDPServer
226.926 -CLASS URLError
226.927 -CLASS URLopener
226.928 -CLASS UUID
226.929 -CLASS UnaryAdd
226.930 -CLASS UnarySub
226.931 -CLASS UnboundLocalError
226.932 -CLASS UnboundLocalError
226.933 -CLASS Underflow
226.934 -CLASS UnexpectedException
226.935 -CLASS UnicodeDecodeError
226.936 -CLASS UnicodeDecodeError
226.937 -CLASS UnicodeEncodeError
226.938 -CLASS UnicodeEncodeError
226.939 -CLASS UnicodeError
226.940 -CLASS UnicodeError
226.941 -CLASS UnicodeTranslateError
226.942 -CLASS UnicodeTranslateError
226.943 -CLASS UnicodeWarning
226.944 -CLASS UnicodeWarning
226.945 -CLASS UnimplementedFileMode
226.946 -CLASS Union
226.947 -CLASS UnixCCompiler
226.948 -CLASS UnixDatagramServer
226.949 -CLASS UnixMailbox
226.950 -CLASS UnixStreamServer
226.951 -CLASS Unknown
226.952 -CLASS UnknownFileError
226.953 -CLASS UnknownHandler
226.954 -CLASS UnknownProtocol
226.955 -CLASS UnknownTransferEncoding
226.956 -CLASS Unload
226.957 -CLASS Unmarshaller
226.958 -CLASS Unpacker
226.959 -CLASS Unpickler
226.960 -CLASS UnpicklingError
226.961 -CLASS UnspecifiedEventTypeErr
226.962 -CLASS UnsupportedOperation
226.963 -CLASS UserDataHandler
226.964 -CLASS UserDict
226.965 -CLASS UserList
226.966 -CLASS UserString
226.967 -CLASS UserWarning
226.968 -CLASS UserWarning
226.969 -CLASS ValidationErr
226.970 -CLASS ValueError
226.971 -CLASS ValueError
226.972 -CLASS Values
226.973 -CLASS Vec2D
226.974 -CLASS Vendor
226.975 -CLASS Version
226.976 -CLASS VersionPredicate
226.977 -CLASS View
226.978 -CLASS WSGIRequestHandler
226.979 -CLASS WSGIServer
226.980 -CLASS Warning
226.981 -CLASS Warning
226.982 -CLASS Wave_read
226.983 -CLASS Wave_write
226.984 -CLASS WeakKeyDictionary
226.985 -CLASS WeakValueDictionary
226.986 -CLASS While
226.987 -CLASS WichmannHill
226.988 -CLASS WinDLL
226.989 -CLASS Window
226.990 -CLASS WindowsError
226.991 -CLASS WindowsError
226.992 -CLASS With
226.993 -CLASS WrongDocumentErr
226.994 -CLASS X
226.995 -CLASS XMLFilter
226.996 -CLASS XMLFilterBase
226.997 -CLASS XMLFilterImpl
226.998 -CLASS XMLGenerator
226.999 -CLASS XMLParser
226.1000 -CLASS XMLRPCDocGenerator
226.1001 -CLASS XMLReader
226.1002 -CLASS XMLTreeBuilder
226.1003 -CLASS XmlParseErr
226.1004 -CLASS Yield
226.1005 -CLASS Yuck
226.1006 -CLASS ZeroDivisionError
226.1007 -CLASS ZeroDivisionError
226.1008 -CLASS ZipFile
226.1009 -CLASS ZipImportError
226.1010 -CLASS ZipInfo
226.1011 -CLASS _CData [PROTECTE
226.1012 -CLASS _FuncPtr [PROTECTE
226.1013 -CLASS _SimpleCData [PROTECTE
226.1014 -CLASS _date_class [PRIVATE]
226.1015 -CLASS _posixfile_
226.1016 -CLASS _time_class [PRIVATE]
226.1017 -CLASS array
226.1018 -CLASS async_chat
226.1019 -CLASS bdist
226.1020 -CLASS bdist_dumb
226.1021 -CLASS bdist_msi
226.1022 -CLASS bdist_rpm
226.1023 -CLASS bdist_wininst
226.1024 -CLASS bool
226.1025 -CLASS bsddbobject
226.1026 -CLASS build
226.1027 -CLASS build_clib
226.1028 -CLASS build_ext
226.1029 -CLASS build_py
226.1030 -CLASS build_scripts
226.1031 -CLASS c_bool
226.1032 -CLASS c_byte
226.1033 -CLASS c_char
226.1034 -CLASS c_char_p
226.1035 -CLASS c_double
226.1036 -CLASS c_float
226.1037 -CLASS c_int
226.1038 -CLASS c_int16
226.1039 -CLASS c_int32
226.1040 -CLASS c_int64
226.1041 -CLASS c_int8
226.1042 -CLASS c_long
226.1043 -CLASS c_longdouble
226.1044 -CLASS c_longlong
226.1045 -CLASS c_short
226.1046 -CLASS c_size_t
226.1047 -CLASS c_ubyte
226.1048 -CLASS c_uint
226.1049 -CLASS c_uint16
226.1050 -CLASS c_uint32
226.1051 -CLASS c_uint64
226.1052 -CLASS c_uint8
226.1053 -CLASS c_ulong
226.1054 -CLASS c_ulonglong
226.1055 -CLASS c_ushort
226.1056 -CLASS c_void_p
226.1057 -CLASS c_wchar
226.1058 -CLASS c_wchar_p
226.1059 -CLASS class
226.1060 -CLASS class
226.1061 -CLASS clean
226.1062 -CLASS closing
226.1063 -CLASS complex
226.1064 -CLASS compressobj
226.1065 -CLASS config
226.1066 -CLASS container
226.1067 -CLASS container
226.1068 -CLASS contextmanager
226.1069 -CLASS contextmanager
226.1070 -CLASS controller
226.1071 -CLASS date
226.1072 -CLASS datetime
226.1073 -CLASS dbexts
226.1074 -CLASS dbextsTestCase
226.1075 -CLASS dbhash
226.1076 -CLASS decompressobj
226.1077 -CLASS deque
226.1078 -CLASS dict
226.1079 -CLASS dict
226.1080 -CLASS dircmp
226.1081 -CLASS dispatcher
226.1082 -CLASS dispatcher_with_send
226.1083 -CLASS dl
226.1084 -CLASS error
226.1085 -CLASS error_data
226.1086 -CLASS error_perm
226.1087 -CLASS error_proto
226.1088 -CLASS error_reply
226.1089 -CLASS excel
226.1090 -CLASS excel_tab
226.1091 -CLASS executor
226.1092 -CLASS fifo
226.1093 -CLASS file
226.1094 -CLASS file
226.1095 -CLASS file_dispatcher
226.1096 -CLASS file_wrapper
226.1097 -CLASS float
226.1098 -CLASS float
226.1099 -CLASS foo
226.1100 -CLASS gaierror
226.1101 -CLASS herror
226.1102 -CLASS install
226.1103 -CLASS install_data
226.1104 -CLASS install_egg_info
226.1105 -CLASS install_headers
226.1106 -CLASS install_lib
226.1107 -CLASS install_misc
226.1108 -CLASS install_scripts
226.1109 -CLASS instance
226.1110 -CLASS instance
226.1111 -CLASS int
226.1112 -CLASS iterator
226.1113 -CLASS iterator
226.1114 -CLASS list
226.1115 -CLASS local
226.1116 -CLASS lock
226.1117 -CLASS long
226.1118 -CLASS main
226.1119 -CLASS mbox
226.1120 -CLASS mboxMessage
226.1121 -CLASS mllib
226.1122 -CLASS mmap
226.1123 -CLASS multiprocessing.Pool
226.1124 -CLASS mutex
226.1125 -CLASS mxODBCProxy
226.1126 -CLASS netrc
226.1127 -CLASS object
226.1128 -CLASS object
226.1129 -CLASS oss_audio_device
226.1130 -CLASS oss_mixer_device
226.1131 -CLASS poll
226.1132 -CLASS py_object
226.1133 -CLASS register
226.1134 -CLASS scheduler
226.1135 -CLASS sdist
226.1136 -CLASS set
226.1137 -CLASS set
226.1138 -CLASS shlex
226.1139 -CLASS simple_producer
226.1140 -CLASS socket
226.1141 -CLASS stat_result
226.1142 -CLASS str
226.1143 -CLASS str
226.1144 -CLASS test_dist
226.1145 -CLASS test_zxjdbc
226.1146 -CLASS time
226.1147 -CLASS timedelta
226.1148 -CLASS timeout
226.1149 -CLASS tixCommand
226.1150 -CLASS tmxxx
226.1151 -CLASS tuple
226.1152 -CLASS tzinfo
226.1153 -CLASS unicode
226.1154 -CLASS unicode
226.1155 -CLASS upload
226.1156 -CLASS window
226.1157 -CLASS xmlparser
226.1158 -CLASS zipimporter
226.1159 -CLASS zxAPITestCase
226.1160 -CLASS zxCoreTestCase
226.1161 -CLASS zxJDBCTestCase
226.1162 -METHOD __import__(name, globals, loca
226.1163 -METHOD abs(x)
226.1164 -METHOD all(iterable)
226.1165 -METHOD any(iterable)
226.1166 -METHOD ---apply(function, args, ke---
226.1167 -METHOD basestring()
226.1168 -METHOD bin(x)
226.1169 -METHOD bool(x)
226.1170 -METHOD buffer(object, offset, size)
226.1171 -METHOD callable(object)
226.1172 -METHOD chr(i)
226.1173 -METHOD classmethod(function)
226.1174 -METHOD cmp(x, y)
226.1175 -METHOD coerce(x, y)
226.1176 -METHOD compile(source, filename, mode
226.1177 -METHOD complex(real, imag)
226.1178 -METHOD delattr(object, name)
226.1179 -METHOD dict(arg)
226.1180 -METHOD dir(object)
226.1181 -METHOD divmod(a, b)
226.1182 -METHOD enumerate(sequence, start)
226.1183 -METHOD eval(expression, globals, loca
226.1184 -METHOD execfile(filename, globals, lo
226.1185 -METHOD exit(code)
226.1186 -METHOD file(filename, mode, bufsize)
226.1187 -METHOD filter(function, iterable)
226.1188 -METHOD float(x)
226.1189 -METHOD frozenset(iterable)
226.1190 -METHOD getattr(object, name, default)
226.1191 -METHOD globals()
226.1192 -METHOD hasattr(object, name)
226.1193 -METHOD hash(object)
226.1194 -METHOD help(object)
226.1195 -METHOD hex(x)
226.1196 -METHOD id(object)
226.1197 -METHOD input(prompt)
226.1198 -METHOD int(x, radix)
226.1199 -METHOD intern(string)
226.1200 -METHOD isinstance(object, classinfo)
226.1201 -METHOD issubclass(class, classinfo)
226.1202 -METHOD iter(o, sentinel)
226.1203 -METHOD len(s)
226.1204 -METHOD list(iterable)
226.1205 -METHOD locals()
226.1206 -METHOD long(x, radix)
226.1207 -METHOD map(function, iterable)
226.1208 -METHOD max(iterable, argskey)
226.1209 -METHOD min(iterable, argskey)
226.1210 -METHOD next(iterator, default)
226.1211 -METHOD object()
226.1212 -METHOD oct(x)
226.1213 -METHOD open(filename, mode, bufsize)
226.1214 -METHOD ord(c)
226.1215 -METHOD pow(x, y, z)
226.1216 -METHOD print(object, sep, end, file)
226.1217 -METHOD property(fget, fset, fdel, doc
226.1218 -METHOD quit(code)
226.1219 -METHOD range(start, stop, step)
226.1220 -METHOD raw_input(prompt)
226.1221 -METHOD reduce(function, iterable, ini
226.1222 -METHOD reload(module)
226.1223 -METHOD repr(object)
226.1224 -METHOD reversed(seq)
226.1225 -METHOD round(x, n)
226.1226 -METHOD set(iterable)
226.1227 -METHOD setattr(object, name, value)
226.1228 -METHOD slice(start, stop, step)
226.1229 -METHOD sorted(iterable, cmp, key, rev
226.1230 -METHOD staticmethod(function)
226.1231 -METHOD str(object)
226.1232 -METHOD sum(iterable, start)
226.1233 -METHOD super(type, object-or-type)
226.1234 -METHOD tuple(iterable)
226.1235 -METHOD type(name, bases, dict)
226.1236 -METHOD type(object)
226.1237 -METHOD unichr(i)
226.1238 -METHOD unicode(object, encoding, erro
226.1239 -METHOD vars(object)
226.1240 -METHOD xrange(start, stop, step)
226.1241 -METHOD zip(iterable)
226.1242 -VARIABLE Ellipsis
226.1243 -VARIABLE False
226.1244 -VARIABLE None
226.1245 -VARIABLE NotImplemented
226.1246 -VARIABLE True
226.1247 -VARIABLE __debug__
226.1248 -VARIABLE copyright
226.1249 -KEYWORD and
226.1250 -KEYWORD as
226.1251 -KEYWORD assert
226.1252 -KEYWORD break
226.1253 -KEYWORD class
226.1254 -KEYWORD continue
226.1255 -KEYWORD def
226.1256 -KEYWORD del
226.1257 -KEYWORD elif
226.1258 -KEYWORD else
226.1259 -KEYWORD except
226.1260 -KEYWORD exec
226.1261 -KEYWORD finally
226.1262 -KEYWORD for
226.1263 -KEYWORD from
226.1264 -KEYWORD global
226.1265 -KEYWORD if
226.1266 -KEYWORD import
226.1267 -KEYWORD in
226.1268 -KEYWORD is
226.1269 -KEYWORD lambda
226.1270 -KEYWORD not
226.1271 -KEYWORD or
226.1272 -KEYWORD pass
226.1273 -KEYWORD print
226.1274 -KEYWORD raise
226.1275 -KEYWORD return
226.1276 -KEYWORD try
226.1277 -KEYWORD while
226.1278 -KEYWORD with
226.1279 -KEYWORD yield
227.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testMarks10.occurrences Sun Jan 04 13:11:53 2015 -0600
227.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
227.3 @@ -1,6 +0,0 @@
227.4 - def __init__(|>MARK_OCCURRENCES:self<|, year, month, day, hour=0, minute=0, second=0,
227.5 - |>MARK_OCCURRENCES:self<|.ordinal = _ymd2ord(year, month, 1) + (day - 1)
227.6 - year, month, day = _ord2ymd(|>MARK_OCCURRENCES:self<|.ordinal)
227.7 - |>MARK_OCCURRENCES:sel^f<|.year, |>MARK_OCCURRENCES:self<|.month, |>MARK_OCCURRENCES:self<|.day = year, month, day
227.8 - |>MARK_OCCURRENCES:self<|.hour, |>MARK_OCCURRENCES:self<|.minute, |>MARK_OCCURRENCES:self<|.second = hour, minute, second
227.9 - |>MARK_OCCURRENCES:self<|.microsecond = microsecond
228.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testMarks3.occurrences Sun Jan 04 13:11:53 2015 -0600
228.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
228.3 @@ -1,6 +0,0 @@
228.4 - |>MARK_OCCURRENCES:newformat<| = []
228.5 - push = |>MARK_OCCURRENCES:newformat<|.append
228.6 - |>MARK_OCCURRENCES:new^format<|.append(zreplace)
228.7 - |>MARK_OCCURRENCES:newformat<|.append(Zreplace)
228.8 - |>MARK_OCCURRENCES:newformat<| = "".join(|>MARK_OCCURRENCES:newformat<|)
228.9 - return _time.strftime(|>MARK_OCCURRENCES:newformat<|, timetuple)
229.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testMarks9.occurrences Sun Jan 04 13:11:53 2015 -0600
229.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
229.3 @@ -1,4 +0,0 @@
229.4 -def |>MARK_OCCURRENCES:_bu^ild_struct_time<|(y, m, d, hh, mm, ss, dstflag):
229.5 - return |>MARK_OCCURRENCES:_build_struct_time<|(self.__year, self.__month, self.__day,
229.6 - return |>MARK_OCCURRENCES:_build_struct_time<|(self.year, self.month, self.day,
229.7 - return |>MARK_OCCURRENCES:_build_struct_time<|(y, m, d, hh, mm, ss, 0)
230.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testUnresolvedHints7.hints Sun Jan 04 13:11:53 2015 -0600
230.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
230.3 @@ -1,3 +0,0 @@
230.4 - raise ValuError("astimezone() requires an aware datetime")
230.5 - ---------
230.6 -HINT:Undefined name "ValuError"
231.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testUnusedHints.hints Sun Jan 04 13:11:53 2015 -0600
231.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
231.3 @@ -1,27 +0,0 @@
231.4 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
231.5 - ---
231.6 -HINT:Unused Variable dst
231.7 -HINT:Unused Variable hh
231.8 -HINT:Unused Variable jday
231.9 -HINT:Unused Variable mm
231.10 -HINT:Unused Variable ss
231.11 -HINT:Unused Variable weekday
231.12 - def tzname(self, dt):
231.13 - --
231.14 -HINT:Unused Variable dt
231.15 - def utcoffset(self, dt):
231.16 - --
231.17 -HINT:Unused Variable dt
231.18 - def dst(self, dt):
231.19 - --
231.20 -HINT:Unused Variable dt
231.21 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
231.22 - ---
231.23 -HINT:Unused Variable dst
231.24 -HINT:Unused Variable jday
231.25 -HINT:Unused Variable weekday
231.26 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
231.27 - ---
231.28 -HINT:Unused Variable dst
231.29 -HINT:Unused Variable jday
231.30 -HINT:Unused Variable weekday
232.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testUnusedHints3.hints Sun Jan 04 13:11:53 2015 -0600
232.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
232.3 @@ -1,18 +0,0 @@
232.4 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
232.5 - ---
232.6 -HINT:Unused Variable dst
232.7 -HINT:Unused Variable hh
232.8 -HINT:Unused Variable jday
232.9 -HINT:Unused Variable mm
232.10 -HINT:Unused Variable ss
232.11 -HINT:Unused Variable weekday
232.12 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
232.13 - ---
232.14 -HINT:Unused Variable dst
232.15 -HINT:Unused Variable jday
232.16 -HINT:Unused Variable weekday
232.17 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
232.18 - ---
232.19 -HINT:Unused Variable dst
232.20 -HINT:Unused Variable jday
232.21 -HINT:Unused Variable weekday
233.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testUnusedHints4.hints Sun Jan 04 13:11:53 2015 -0600
233.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
233.3 @@ -1,18 +0,0 @@
233.4 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
233.5 - ---
233.6 -HINT:Unused Variable dst
233.7 -HINT:Unused Variable hh
233.8 -HINT:Unused Variable jday
233.9 -HINT:Unused Variable mm
233.10 -HINT:Unused Variable ss
233.11 -HINT:Unused Variable weekday
233.12 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
233.13 - ---
233.14 -HINT:Unused Variable dst
233.15 -HINT:Unused Variable jday
233.16 -HINT:Unused Variable weekday
233.17 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
233.18 - ---
233.19 -HINT:Unused Variable dst
233.20 -HINT:Unused Variable jday
233.21 -HINT:Unused Variable weekday
234.1 --- a/python.editor/test/unit/data/testfiles/datetime.py.testUnusedHints5.hints Sun Jan 04 13:11:53 2015 -0600
234.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
234.3 @@ -1,23 +0,0 @@
234.4 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
234.5 - ---
234.6 -HINT:Unused Variable dst
234.7 -HINT:Unused Variable hh
234.8 -HINT:Unused Variable ss
234.9 -HINT:Unused Variable weekday
234.10 - def tzname(self, dt):
234.11 - --
234.12 -HINT:Unused Variable dt
234.13 - def utcoffset(self, dt):
234.14 - --
234.15 -HINT:Unused Variable dt
234.16 - def dst(self, dt):
234.17 - --
234.18 -HINT:Unused Variable dt
234.19 - y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
234.20 - ---
234.21 -HINT:Unused Variable dst
234.22 -HINT:Unused Variable weekday
234.23 - y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
234.24 - ---
234.25 -HINT:Unused Variable dst
234.26 -HINT:Unused Variable weekday
235.1 --- a/python.editor/test/unit/data/testfiles/declarations.py Sun Jan 04 13:11:53 2015 -0600
235.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
235.3 @@ -1,3 +0,0 @@
235.4 -# Go to random function
235.5 -fnmatchcase(x)
235.6 -
236.1 --- a/python.editor/test/unit/data/testfiles/decorators.py Sun Jan 04 13:11:53 2015 -0600
236.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
236.3 @@ -1,5 +0,0 @@
236.4 -@classmethod
236.5 -@synchronized(lock)
236.6 -def foo(cls):
236.7 - pass
236.8 -
237.1 --- a/python.editor/test/unit/data/testfiles/decorators.py.scopes Sun Jan 04 13:11:53 2015 -0600
237.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
237.3 @@ -1,11 +0,0 @@
237.4 -=============================================
237.5 -<file-top>: Module : OffsetRange[0,56>
237.6 -classmethod [read][UNRESOLVED][node=Name]
237.7 -foo [bound][function][def][node=FunctionDef]
237.8 -lock [read][UNRESOLVED][node=Name]
237.9 -synchronized [read][called][UNRESOLVED][node=Name]
237.10 -
237.11 - =============================================
237.12 - foo: FunctionDef : OffsetRange[0,56>
237.13 - cls [bound][param][data][unused][node=Name]
237.14 -
238.1 --- a/python.editor/test/unit/data/testfiles/decorators.py.semantic Sun Jan 04 13:11:53 2015 -0600
238.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
238.3 @@ -1,5 +0,0 @@
238.4 -@classmethod
238.5 -@synchronized(lock)
238.6 -def |>METHOD:foo<|(|>PARAMETER,UNUSED:cls<|):
238.7 - pass
238.8 -
239.1 --- a/python.editor/test/unit/data/testfiles/decorators.py.testDecorators2.completion Sun Jan 04 13:11:53 2015 -0600
239.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
239.3 @@ -1,5 +0,0 @@
239.4 -Code completion result for source line:
239.5 -@c|lassmethod
239.6 -(QueryType=COMPLETION, NameKind=PREFIX)
239.7 -METHOD classmethod
239.8 -METHOD contextmanager
240.1 --- a/python.editor/test/unit/data/testfiles/delete.py Sun Jan 04 13:11:53 2015 -0600
240.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
240.3 @@ -1,8 +0,0 @@
240.4 -# From http://www.netbeans.org/issues/show_bug.cgi?id=155586
240.5 -def test_lock():
240.6 - lck = self.lock_somehow()
240.7 - try:
240.8 - do_some_atomic_stuff()
240.9 - finally:
240.10 - del lck
240.11 -
241.1 --- a/python.editor/test/unit/data/testfiles/delete2.py Sun Jan 04 13:11:53 2015 -0600
241.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
241.3 @@ -1,6 +0,0 @@
241.4 -# From http://www.netbeans.org/issues/show_bug.cgi?id=155586
241.5 -lck = self.lock_somehow()
241.6 -try:
241.7 - do_some_atomic_stuff()
241.8 -finally:
241.9 - del lck
242.1 --- a/python.editor/test/unit/data/testfiles/delete2.py.scopes Sun Jan 04 13:11:53 2015 -0600
242.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
242.3 @@ -1,6 +0,0 @@
242.4 -=============================================
242.5 -<file-top>: Module : OffsetRange[61,137>
242.6 -do_some_atomic_stuff [read][called][UNRESOLVED][node=Name]
242.7 -lck [bound][data][read][node=Name]
242.8 -self [read][UNRESOLVED][node=Name]
242.9 -
243.1 --- a/python.editor/test/unit/data/testfiles/deprecated-imports.py Sun Jan 04 13:11:53 2015 -0600
243.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
243.3 @@ -1,56 +0,0 @@
243.4 -import cl
243.5 -import sv
243.6 -import timing
243.7 -import addpack
243.8 -import cmp
243.9 -import cmpcache
243.10 -import codehack
243.11 -import dircmp
243.12 -import dump
243.13 -import find
243.14 -import fmt
243.15 -import grep
243.16 -import lockfile
243.17 -import newdir
243.18 -import ni
243.19 -import packmail
243.20 -import Para
243.21 -import poly
243.22 -import rand
243.23 -import reconvert
243.24 -import regex
243.25 -import regsub
243.26 -import statcache
243.27 -import tb
243.28 -import tzparse
243.29 -import util
243.30 -import whatsound
243.31 -import whrandom
243.32 -import zmod
243.33 -import gopherlib
243.34 -import rgbimg
243.35 -import macfs
243.36 -
243.37 -
243.38 -import posixfile
243.39 -import gopherlib
243.40 -import rgbimgmodule
243.41 -import pre
243.42 -import whrandom
243.43 -import rfc822
243.44 -import mimetools
243.45 -import MimeWriter
243.46 -import mimify
243.47 -import rotor
243.48 -import TERMIOS.py
243.49 -import statcache
243.50 -import mpz
243.51 -import xreadlines
243.52 -import multifile
243.53 -import sets
243.54 -import buildtools
243.55 -import cfmfile
243.56 -import macfs
243.57 -import md5
243.58 -import sha
243.59 -
244.1 --- a/python.editor/test/unit/data/testfiles/deprecated-imports.py.testDeprecations.hints Sun Jan 04 13:11:53 2015 -0600
244.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
244.3 @@ -1,159 +0,0 @@
244.4 -import cl
244.5 ----------
244.6 -HINT:cl is deprecated. Listed as obsolete in the library documentation
244.7 -import sv
244.8 ----------
244.9 -HINT:sv is deprecated. Listed as obsolete in the library documentation
244.10 -import timing
244.11 --------------
244.12 -HINT:timing is deprecated. Listed as obsolete in the library documentation
244.13 -import addpack
244.14 ---------------
244.15 -HINT:addpack is deprecated. Obsolete module, removed in Python 2.5
244.16 -import cmp
244.17 -----------
244.18 -HINT:cmp is deprecated. Obsolete module, removed in Python 2.5
244.19 -import cmpcache
244.20 ----------------
244.21 -HINT:cmpcache is deprecated. Obsolete module, removed in Python 2.5
244.22 -import codehack
244.23 ----------------
244.24 -HINT:codehack is deprecated. Obsolete module, removed in Python 2.5
244.25 -import dircmp
244.26 --------------
244.27 -HINT:dircmp is deprecated. Obsolete module, removed in Python 2.5
244.28 -import dump
244.29 ------------
244.30 -HINT:dump is deprecated. Obsolete module, removed in Python 2.5
244.31 -import find
244.32 ------------
244.33 -HINT:find is deprecated. Obsolete module, removed in Python 2.5
244.34 -import fmt
244.35 -----------
244.36 -HINT:fmt is deprecated. Obsolete module, removed in Python 2.5
244.37 -import grep
244.38 ------------
244.39 -HINT:grep is deprecated. Obsolete module, removed in Python 2.5
244.40 -import lockfile
244.41 ----------------
244.42 -HINT:lockfile is deprecated. Obsolete module, removed in Python 2.5
244.43 -import newdir
244.44 --------------
244.45 -HINT:newdir is deprecated. Obsolete module, removed in Python 2.5
244.46 -import ni
244.47 ----------
244.48 -HINT:ni is deprecated. Obsolete module, removed in Python 2.5
244.49 -import packmail
244.50 ----------------
244.51 -HINT:packmail is deprecated. Obsolete module, removed in Python 2.5
244.52 -import Para
244.53 ------------
244.54 -HINT:Para is deprecated. Obsolete module, removed in Python 2.5
244.55 -import poly
244.56 ------------
244.57 -HINT:poly is deprecated. Obsolete module, removed in Python 2.5
244.58 -import rand
244.59 ------------
244.60 -HINT:rand is deprecated. Obsolete module, removed in Python 2.5
244.61 -import reconvert
244.62 -----------------
244.63 -HINT:reconvert is deprecated. Obsolete module, removed in Python 2.5
244.64 -import regex
244.65 -------------
244.66 -HINT:regex is deprecated. Obsolete module, removed in Python 2.5
244.67 -import regsub
244.68 --------------
244.69 -HINT:regsub is deprecated. Obsolete module, removed in Python 2.5
244.70 -import statcache
244.71 -----------------
244.72 -HINT:statcache is deprecated. Using the cache can be fragile and error-prone; applications should just use os.stat() directly.
244.73 -import tb
244.74 ----------
244.75 -HINT:tb is deprecated. Obsolete module, removed in Python 2.5
244.76 -import tzparse
244.77 ---------------
244.78 -HINT:tzparse is deprecated. Obsolete module, removed in Python 2.5
244.79 -import util
244.80 ------------
244.81 -HINT:util is deprecated. Obsolete module, removed in Python 2.5
244.82 -import whatsound
244.83 -----------------
244.84 -HINT:whatsound is deprecated. Obsolete module, removed in Python 2.5
244.85 -import whrandom
244.86 ----------------
244.87 -HINT:whrandom is deprecated. The module's default seed computation was inherently insecure; the random module should be used instead.
244.88 -import zmod
244.89 ------------
244.90 -HINT:zmod is deprecated. Obsolete module, removed in Python 2.5
244.91 -import gopherlib
244.92 -----------------
244.93 -HINT:gopherlib is deprecated. The gopher protocol is not in active use anymore.
244.94 -import rgbimg
244.95 --------------
244.96 -HINT:rgbimg is deprecated. Obsolete module, removed in Python 2.6
244.97 -import macfs
244.98 -------------
244.99 -HINT:macfs is deprecated
244.100 -import posixfile
244.101 -----------------
244.102 -HINT:posixfile is deprecated. Locking is better done by fcntl.lockf().
244.103 -import gopherlib
244.104 -----------------
244.105 -HINT:gopherlib is deprecated. The gopher protocol is not in active use anymore.
244.106 -import rgbimgmodule
244.107 --------------------
244.108 -HINT:rgbimgmodule is deprecated
244.109 -import pre
244.110 -----------
244.111 -HINT:pre is deprecated. The underlying PCRE engine doesn't support Unicode, and has been unmaintained since Python 1.5.2.
244.112 -import whrandom
244.113 ----------------
244.114 -HINT:whrandom is deprecated. The module's default seed computation was inherently insecure; the random module should be used instead.
244.115 -import rfc822
244.116 --------------
244.117 -HINT:rfc822 is deprecated. Supplanted by Python 2.2's email package.
244.118 -import mimetools
244.119 -----------------
244.120 -HINT:mimetools is deprecated. Supplanted by Python 2.2's email package.
244.121 -import MimeWriter
244.122 ------------------
244.123 -HINT:MimeWriter is deprecated. Supplanted by Python 2.2's email package.
244.124 -import mimify
244.125 --------------
244.126 -HINT:mimify is deprecated. Supplanted by Python 2.2's email package.
244.127 -import rotor
244.128 -------------
244.129 -HINT:rotor is deprecated. Uses insecure algorithm.
244.130 -import TERMIOS.py
244.131 ------------------
244.132 -HINT:TERMIOS.py is deprecated. The constants in this file are now in the 'termios' module.
244.133 -import statcache
244.134 -----------------
244.135 -HINT:statcache is deprecated. Using the cache can be fragile and error-prone; applications should just use os.stat() directly.
244.136 -import mpz
244.137 -----------
244.138 -HINT:mpz is deprecated. Third-party packages provide similiar features and wrap more of GMP's API.
244.139 -import xreadlines
244.140 ------------------
244.141 -HINT:xreadlines is deprecated. Using 'for line in file', introduced in 2.3, is preferable.
244.142 -import multifile
244.143 -----------------
244.144 -HINT:multifile is deprecated. Supplanted by the email package.
244.145 -import sets
244.146 ------------
244.147 -HINT:sets is deprecated. The built-in set/frozenset types, introduced in Python 2.4, supplant the module.
244.148 -import buildtools
244.149 ------------------
244.150 -HINT:buildtools is deprecated
244.151 -import cfmfile
244.152 ---------------
244.153 -HINT:cfmfile is deprecated
244.154 -import macfs
244.155 -------------
244.156 -HINT:macfs is deprecated
244.157 -import md5
244.158 -----------
244.159 -HINT:md5 is deprecated. Replaced by the 'hashlib' module.
244.160 -import sha
244.161 -----------
244.162 -HINT:sha is deprecated. Replaced by the 'hashlib' module.
245.1 --- a/python.editor/test/unit/data/testfiles/doc.py Sun Jan 04 13:11:53 2015 -0600
245.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
245.3 @@ -1,123 +0,0 @@
245.4 -"""Configuration file parser.
245.5 -
245.6 -A setup file consists of sections, lead by a "[section]" header,
245.7 -and followed by "name: value" entries, with continuations and such in
245.8 -the style of RFC 822.
245.9 -
245.10 - the same section, or values in a special [DEFAULT] section.
245.11 -
245.12 -For example:
245.13 -
245.14 - something: %(dir)s/whatever
245.15 -
245.16 -would resolve the "%(dir)s" to the value of dir. All reference
245.17 -expansions are done late, on demand.
245.18 -
245.19 -Intrinsic defaults can be specified by passing them into the
245.20 -ConfigParser constructor as a dictionary.
245.21 -
245.22 -class:
245.23 -
245.24 -ConfigParser -- responsible for parsing a list of
245.25 - configuration files, and managing the parsed database.
245.26 -
245.27 - methods:
245.28 -
245.29 - __init__(defaults=None)
245.30 - create the parser and specify a dictionary of intrinsic defaults. The
245.31 - keys must be strings, the values must be appropriate for %()s string
245.32 - interpolation. Note that `__name__' is always an intrinsic default;
245.33 - it's value is the section's name.
245.34 -
245.35 - sections()
245.36 - return all the configuration section names, sans DEFAULT
245.37 -
245.38 - has_section(section)
245.39 - return whether the given section exists
245.40 -
245.41 - has_option(section, option)
245.42 - return whether the given option exists in the given section
245.43 -
245.44 - options(section)
245.45 - return list of configuration options for the named section
245.46 -
245.47 - read(filenames)
245.48 - read and parse the list of named configuration files, given by
245.49 - name. A single filename is also allowed. Non-existing files
245.50 - are ignored.
245.51 -
245.52 - readfp(fp, filename=None)
245.53 - read and parse one configuration file, given as a file object.
245.54 - The filename defaults to fp.name; it is only used in error
245.55 - messages (if fp has no `name' attribute, the string `<???>' is used).
245.56 -
245.57 - get(section, option, raw=False, vars=None)
245.58 - return a string value for the named option. All % interpolations are
245.59 - expanded in the return values, based on the defaults passed into the
245.60 - constructor and the DEFAULT section. Additional substitutions may be
245.61 - provided using the `vars' argument, which must be a dictionary whose
245.62 - contents override any pre-existing defaults.
245.63 -
245.64 - getint(section, options)
245.65 - like get(), but convert value to an integer
245.66 -
245.67 - getfloat(section, options)
245.68 - like get(), but convert value to a float
245.69 -
245.70 - getboolean(section, options)
245.71 - like get(), but convert value to a boolean (currently case
245.72 - insensitively defined as 0, false, no, off for False, and 1, true,
245.73 - yes, on for True). Returns False or True.
245.74 -
245.75 - items(section, raw=False, vars=None)
245.76 - return a list of tuples with (name, value) for each option
245.77 - in the section.
245.78 -
245.79 - remove_section(section)
245.80 - remove the given file section and all its options
245.81 -
245.82 - remove_option(section, option)
245.83 - remove the given option from the given section
245.84 -
245.85 - set(section, option, value)
245.86 - set the given option
245.87 -
245.88 - write(fp)
245.89 - write the configuration state in .ini format
245.90 -"""
245.91 -
245.92 -# exception classes
245.93 -class Error(Exception):
245.94 - """Base class for ConfigParser exceptions."""
245.95 -
245.96 - def readfp(self, fp, filename=None):
245.97 - """Like read() but the argument must be a file-like object.
245.98 -
245.99 - The `fp' argument must have a `readline' method. Optional
245.100 - second argument is the `filename', which if not given, is
245.101 - taken from fp.name. If fp has no `name' attribute, `<???>' is
245.102 - used.
245.103 -
245.104 - """
245.105 - if filename is None:
245.106 - try:
245.107 - filename = fp.name
245.108 - except AttributeError:
245.109 - filename = '<???>'
245.110 - self._read(fp, filename)
245.111 -
245.112 - def get(self, section, option):
245.113 - opt = self.optionxform(option)
245.114 - if section not in self._sections:
245.115 - if section != DEFAULTSECT:
245.116 - raise NoSectionError(section)
245.117 - if opt in self._defaults:
245.118 - return self._defaults[opt]
245.119 - else:
245.120 - raise NoOptionError(option, section)
245.121 - elif opt in self._sections[section]:
245.122 - return self._sections[section][opt]
245.123 - elif opt in self._defaults:
245.124 - return self._defaults[opt]
245.125 - else:
245.126 - raise NoOptionError(option, section)
246.1 --- a/python.editor/test/unit/data/testfiles/doc.py.indexed Sun Jan 04 13:11:53 2015 -0600
246.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
246.3 @@ -1,20 +0,0 @@
246.4 -
246.5 -
246.6 -Document 0
246.7 -Searchable Keys:
246.8 - class : Error
246.9 - class-ig : error
246.10 - extends : Exception
246.11 - in : doc
246.12 - member : get;F;;self,section,option;
246.13 - member : readfp;F;;self,fp,filename;
246.14 -
246.15 -Not Searchable Keys:
246.16 -
246.17 -
246.18 -Document 1
246.19 -Searchable Keys:
246.20 - item : Error;C;;
246.21 - module : doc
246.22 -
246.23 -Not Searchable Keys:
247.1 --- a/python.editor/test/unit/data/testfiles/doctest.py Sun Jan 04 13:11:53 2015 -0600
247.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
247.3 @@ -1,2637 +0,0 @@
247.4 -# Module doctest.
247.5 -# Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org).
247.6 -# Major enhancements and refactoring by:
247.7 -# Jim Fulton
247.8 -# Edward Loper
247.9 -
247.10 -# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
247.11 -
247.12 -r"""Module doctest -- a framework for running examples in docstrings.
247.13 -
247.14 -In simplest use, end each module M to be tested with:
247.15 -
247.16 -def _test():
247.17 - import doctest
247.18 - doctest.testmod()
247.19 -
247.20 -if __name__ == "__main__":
247.21 - _test()
247.22 -
247.23 -Then running the module as a script will cause the examples in the
247.24 -docstrings to get executed and verified:
247.25 -
247.26 -python M.py
247.27 -
247.28 -This won't display anything unless an example fails, in which case the
247.29 -failing example(s) and the cause(s) of the failure(s) are printed to stdout
247.30 -(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
247.31 -line of output is "Test failed.".
247.32 -
247.33 -Run it with the -v switch instead:
247.34 -
247.35 -python M.py -v
247.36 -
247.37 -and a detailed report of all examples tried is printed to stdout, along
247.38 -with assorted summaries at the end.
247.39 -
247.40 -You can force verbose mode by passing "verbose=True" to testmod, or prohibit
247.41 -it by passing "verbose=False". In either of those cases, sys.argv is not
247.42 -examined by testmod.
247.43 -
247.44 -There are a variety of other ways to run doctests, including integration
247.45 -with the unittest framework, and support for running non-Python text
247.46 -files containing doctests. There are also many ways to override parts
247.47 -of doctest's default behaviors. See the Library Reference Manual for
247.48 -details.
247.49 -"""
247.50 -
247.51 -__docformat__ = 'reStructuredText en'
247.52 -
247.53 -__all__ = [
247.54 - # 0, Option Flags
247.55 - 'register_optionflag',
247.56 - 'DONT_ACCEPT_TRUE_FOR_1',
247.57 - 'DONT_ACCEPT_BLANKLINE',
247.58 - 'NORMALIZE_WHITESPACE',
247.59 - 'ELLIPSIS',
247.60 - 'SKIP',
247.61 - 'IGNORE_EXCEPTION_DETAIL',
247.62 - 'COMPARISON_FLAGS',
247.63 - 'REPORT_UDIFF',
247.64 - 'REPORT_CDIFF',
247.65 - 'REPORT_NDIFF',
247.66 - 'REPORT_ONLY_FIRST_FAILURE',
247.67 - 'REPORTING_FLAGS',
247.68 - # 1. Utility Functions
247.69 - # 2. Example & DocTest
247.70 - 'Example',
247.71 - 'DocTest',
247.72 - # 3. Doctest Parser
247.73 - 'DocTestParser',
247.74 - # 4. Doctest Finder
247.75 - 'DocTestFinder',
247.76 - # 5. Doctest Runner
247.77 - 'DocTestRunner',
247.78 - 'OutputChecker',
247.79 - 'DocTestFailure',
247.80 - 'UnexpectedException',
247.81 - 'DebugRunner',
247.82 - # 6. Test Functions
247.83 - 'testmod',
247.84 - 'testfile',
247.85 - 'run_docstring_examples',
247.86 - # 7. Tester
247.87 - 'Tester',
247.88 - # 8. Unittest Support
247.89 - 'DocTestSuite',
247.90 - 'DocFileSuite',
247.91 - 'set_unittest_reportflags',
247.92 - # 9. Debugging Support
247.93 - 'script_from_examples',
247.94 - 'testsource',
247.95 - 'debug_src',
247.96 - 'debug',
247.97 -]
247.98 -
247.99 -import __future__
247.100 -
247.101 -import sys, traceback, inspect, linecache, os, re
247.102 -import unittest, difflib, pdb, tempfile
247.103 -import warnings
247.104 -from StringIO import StringIO
247.105 -
247.106 -# There are 4 basic classes:
247.107 -# - Example: a <source, want> pair, plus an intra-docstring line number.
247.108 -# - DocTest: a collection of examples, parsed from a docstring, plus
247.109 -# info about where the docstring came from (name, filename, lineno).
247.110 -# - DocTestFinder: extracts DocTests from a given object's docstring and
247.111 -# its contained objects' docstrings.
247.112 -# - DocTestRunner: runs DocTest cases, and accumulates statistics.
247.113 -#
247.114 -# So the basic picture is:
247.115 -#
247.116 -# list of:
247.117 -# +------+ +---------+ +-------+
247.118 -# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
247.119 -# +------+ +---------+ +-------+
247.120 -# | Example |
247.121 -# | ... |
247.122 -# | Example |
247.123 -# +---------+
247.124 -
247.125 -# Option constants.
247.126 -
247.127 -OPTIONFLAGS_BY_NAME = {}
247.128 -def register_optionflag(name):
247.129 - # Create a new flag unless `name` is already known.
247.130 - return OPTIONFLAGS_BY_NAME.setdefault(name, 1 << len(OPTIONFLAGS_BY_NAME))
247.131 -
247.132 -DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
247.133 -DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
247.134 -NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
247.135 -ELLIPSIS = register_optionflag('ELLIPSIS')
247.136 -SKIP = register_optionflag('SKIP')
247.137 -IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL')
247.138 -
247.139 -COMPARISON_FLAGS = (DONT_ACCEPT_TRUE_FOR_1 |
247.140 - DONT_ACCEPT_BLANKLINE |
247.141 - NORMALIZE_WHITESPACE |
247.142 - ELLIPSIS |
247.143 - SKIP |
247.144 - IGNORE_EXCEPTION_DETAIL)
247.145 -
247.146 -REPORT_UDIFF = register_optionflag('REPORT_UDIFF')
247.147 -REPORT_CDIFF = register_optionflag('REPORT_CDIFF')
247.148 -REPORT_NDIFF = register_optionflag('REPORT_NDIFF')
247.149 -REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE')
247.150 -
247.151 -REPORTING_FLAGS = (REPORT_UDIFF |
247.152 - REPORT_CDIFF |
247.153 - REPORT_NDIFF |
247.154 - REPORT_ONLY_FIRST_FAILURE)
247.155 -
247.156 -# Special string markers for use in `want` strings:
247.157 -BLANKLINE_MARKER = '<BLANKLINE>'
247.158 -ELLIPSIS_MARKER = '...'
247.159 -
247.160 -######################################################################
247.161 -## Table of Contents
247.162 -######################################################################
247.163 -# 1. Utility Functions
247.164 -# 2. Example & DocTest -- store test cases
247.165 -# 3. DocTest Parser -- extracts examples from strings
247.166 -# 4. DocTest Finder -- extracts test cases from objects
247.167 -# 5. DocTest Runner -- runs test cases
247.168 -# 6. Test Functions -- convenient wrappers for testing
247.169 -# 7. Tester Class -- for backwards compatibility
247.170 -# 8. Unittest Support
247.171 -# 9. Debugging Support
247.172 -# 10. Example Usage
247.173 -
247.174 -######################################################################
247.175 -## 1. Utility Functions
247.176 -######################################################################
247.177 -
247.178 -def _extract_future_flags(globs):
247.179 - """
247.180 - Return the compiler-flags associated with the future features that
247.181 - have been imported into the given namespace (globs).
247.182 - """
247.183 - flags = 0
247.184 - for fname in __future__.all_feature_names:
247.185 - feature = globs.get(fname, None)
247.186 - if feature is getattr(__future__, fname):
247.187 - flags |= feature.compiler_flag
247.188 - return flags
247.189 -
247.190 -def _normalize_module(module, depth=2):
247.191 - """
247.192 - Return the module specified by `module`. In particular:
247.193 - - If `module` is a module, then return module.
247.194 - - If `module` is a string, then import and return the
247.195 - module with that name.
247.196 - - If `module` is None, then return the calling module.
247.197 - The calling module is assumed to be the module of
247.198 - the stack frame at the given depth in the call stack.
247.199 - """
247.200 - if inspect.ismodule(module):
247.201 - return module
247.202 - elif isinstance(module, (str, unicode)):
247.203 - return __import__(module, globals(), locals(), ["*"])
247.204 - elif module is None:
247.205 - return sys.modules[sys._getframe(depth).f_globals['__name__']]
247.206 - else:
247.207 - raise TypeError("Expected a module, string, or None")
247.208 -
247.209 -def _load_testfile(filename, package, module_relative):
247.210 - if module_relative:
247.211 - package = _normalize_module(package, 3)
247.212 - filename = _module_relative_path(package, filename)
247.213 - if hasattr(package, '__loader__'):
247.214 - if hasattr(package.__loader__, 'get_data'):
247.215 - return package.__loader__.get_data(filename), filename
247.216 - return open(filename).read(), filename
247.217 -
247.218 -def _indent(s, indent=4):
247.219 - """
247.220 - Add the given number of space characters to the beginning every
247.221 - non-blank line in `s`, and return the result.
247.222 - """
247.223 - # This regexp matches the start of non-blank lines:
247.224 - return re.sub('(?m)^(?!$)', indent*' ', s)
247.225 -
247.226 -def _exception_traceback(exc_info):
247.227 - """
247.228 - Return a string containing a traceback message for the given
247.229 - exc_info tuple (as returned by sys.exc_info()).
247.230 - """
247.231 - # Get a traceback message.
247.232 - excout = StringIO()
247.233 - exc_type, exc_val, exc_tb = exc_info
247.234 - traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
247.235 - return excout.getvalue()
247.236 -
247.237 -# Override some StringIO methods.
247.238 -class _SpoofOut(StringIO):
247.239 - def getvalue(self):
247.240 - result = StringIO.getvalue(self)
247.241 - # If anything at all was written, make sure there's a trailing
247.242 - # newline. There's no way for the expected output to indicate
247.243 - # that a trailing newline is missing.
247.244 - if result and not result.endswith("\n"):
247.245 - result += "\n"
247.246 - # Prevent softspace from screwing up the next test case, in
247.247 - # case they used print with a trailing comma in an example.
247.248 - if hasattr(self, "softspace"):
247.249 - del self.softspace
247.250 - return result
247.251 -
247.252 - def truncate(self, size=None):
247.253 - StringIO.truncate(self, size)
247.254 - if hasattr(self, "softspace"):
247.255 - del self.softspace
247.256 -
247.257 -# Worst-case linear-time ellipsis matching.
247.258 -def _ellipsis_match(want, got):
247.259 - """
247.260 - Essentially the only subtle case:
247.261 - >>> _ellipsis_match('aa...aa', 'aaa')
247.262 - False
247.263 - """
247.264 - if ELLIPSIS_MARKER not in want:
247.265 - return want == got
247.266 -
247.267 - # Find "the real" strings.
247.268 - ws = want.split(ELLIPSIS_MARKER)
247.269 - assert len(ws) >= 2
247.270 -
247.271 - # Deal with exact matches possibly needed at one or both ends.
247.272 - startpos, endpos = 0, len(got)
247.273 - w = ws[0]
247.274 - if w: # starts with exact match
247.275 - if got.startswith(w):
247.276 - startpos = len(w)
247.277 - del ws[0]
247.278 - else:
247.279 - return False
247.280 - w = ws[-1]
247.281 - if w: # ends with exact match
247.282 - if got.endswith(w):
247.283 - endpos -= len(w)
247.284 - del ws[-1]
247.285 - else:
247.286 - return False
247.287 -
247.288 - if startpos > endpos:
247.289 - # Exact end matches required more characters than we have, as in
247.290 - # _ellipsis_match('aa...aa', 'aaa')
247.291 - return False
247.292 -
247.293 - # For the rest, we only need to find the leftmost non-overlapping
247.294 - # match for each piece. If there's no overall match that way alone,
247.295 - # there's no overall match period.
247.296 - for w in ws:
247.297 - # w may be '' at times, if there are consecutive ellipses, or
247.298 - # due to an ellipsis at the start or end of `want`. That's OK.
247.299 - # Search for an empty string succeeds, and doesn't change startpos.
247.300 - startpos = got.find(w, startpos, endpos)
247.301 - if startpos < 0:
247.302 - return False
247.303 - startpos += len(w)
247.304 -
247.305 - return True
247.306 -
247.307 -def _comment_line(line):
247.308 - "Return a commented form of the given line"
247.309 - line = line.rstrip()
247.310 - if line:
247.311 - return '# '+line
247.312 - else:
247.313 - return '#'
247.314 -
247.315 -class _OutputRedirectingPdb(pdb.Pdb):
247.316 - """
247.317 - A specialized version of the python debugger that redirects stdout
247.318 - to a given stream when interacting with the user. Stdout is *not*
247.319 - redirected when traced code is executed.
247.320 - """
247.321 - def __init__(self, out):
247.322 - self.__out = out
247.323 - pdb.Pdb.__init__(self, stdout=out)
247.324 -
247.325 - def trace_dispatch(self, *args):
247.326 - # Redirect stdout to the given stream.
247.327 - save_stdout = sys.stdout
247.328 - sys.stdout = self.__out
247.329 - # Call Pdb's trace dispatch method.
247.330 - try:
247.331 - return pdb.Pdb.trace_dispatch(self, *args)
247.332 - finally:
247.333 - sys.stdout = save_stdout
247.334 -
247.335 -# [XX] Normalize with respect to os.path.pardir?
247.336 -def _module_relative_path(module, path):
247.337 - if not inspect.ismodule(module):
247.338 - raise TypeError, 'Expected a module: %r' % module
247.339 - if path.startswith('/'):
247.340 - raise ValueError, 'Module-relative files may not have absolute paths'
247.341 -
247.342 - # Find the base directory for the path.
247.343 - if hasattr(module, '__file__'):
247.344 - # A normal module/package
247.345 - basedir = os.path.split(module.__file__)[0]
247.346 - elif module.__name__ == '__main__':
247.347 - # An interactive session.
247.348 - if len(sys.argv)>0 and sys.argv[0] != '':
247.349 - basedir = os.path.split(sys.argv[0])[0]
247.350 - else:
247.351 - basedir = os.curdir
247.352 - else:
247.353 - # A module w/o __file__ (this includes builtins)
247.354 - raise ValueError("Can't resolve paths relative to the module " +
247.355 - module + " (it has no __file__)")
247.356 -
247.357 - # Combine the base directory and the path.
247.358 - return os.path.join(basedir, *(path.split('/')))
247.359 -
247.360 -######################################################################
247.361 -## 2. Example & DocTest
247.362 -######################################################################
247.363 -## - An "example" is a <source, want> pair, where "source" is a
247.364 -## fragment of source code, and "want" is the expected output for
247.365 -## "source." The Example class also includes information about
247.366 -## where the example was extracted from.
247.367 -##
247.368 -## - A "doctest" is a collection of examples, typically extracted from
247.369 -## a string (such as an object's docstring). The DocTest class also
247.370 -## includes information about where the string was extracted from.
247.371 -
247.372 -class Example:
247.373 - """
247.374 - A single doctest example, consisting of source code and expected
247.375 - output. `Example` defines the following attributes:
247.376 -
247.377 - - source: A single Python statement, always ending with a newline.
247.378 - The constructor adds a newline if needed.
247.379 -
247.380 - - want: The expected output from running the source code (either
247.381 - from stdout, or a traceback in case of exception). `want` ends
247.382 - with a newline unless it's empty, in which case it's an empty
247.383 - string. The constructor adds a newline if needed.
247.384 -
247.385 - - exc_msg: The exception message generated by the example, if
247.386 - the example is expected to generate an exception; or `None` if
247.387 - it is not expected to generate an exception. This exception
247.388 - message is compared against the return value of
247.389 - `traceback.format_exception_only()`. `exc_msg` ends with a
247.390 - newline unless it's `None`. The constructor adds a newline
247.391 - if needed.
247.392 -
247.393 - - lineno: The line number within the DocTest string containing
247.394 - this Example where the Example begins. This line number is
247.395 - zero-based, with respect to the beginning of the DocTest.
247.396 -
247.397 - - indent: The example's indentation in the DocTest string.
247.398 - I.e., the number of space characters that preceed the
247.399 - example's first prompt.
247.400 -
247.401 - - options: A dictionary mapping from option flags to True or
247.402 - False, which is used to override default options for this
247.403 - example. Any option flags not contained in this dictionary
247.404 - are left at their default value (as specified by the
247.405 - DocTestRunner's optionflags). By default, no options are set.
247.406 - """
247.407 - def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
247.408 - options=None):
247.409 - # Normalize inputs.
247.410 - if not source.endswith('\n'):
247.411 - source += '\n'
247.412 - if want and not want.endswith('\n'):
247.413 - want += '\n'
247.414 - if exc_msg is not None and not exc_msg.endswith('\n'):
247.415 - exc_msg += '\n'
247.416 - # Store properties.
247.417 - self.source = source
247.418 - self.want = want
247.419 - self.lineno = lineno
247.420 - self.indent = indent
247.421 - if options is None: options = {}
247.422 - self.options = options
247.423 - self.exc_msg = exc_msg
247.424 -
247.425 -class DocTest:
247.426 - """
247.427 - A collection of doctest examples that should be run in a single
247.428 - namespace. Each `DocTest` defines the following attributes:
247.429 -
247.430 - - examples: the list of examples.
247.431 -
247.432 - - globs: The namespace (aka globals) that the examples should
247.433 - be run in.
247.434 -
247.435 - - name: A name identifying the DocTest (typically, the name of
247.436 - the object whose docstring this DocTest was extracted from).
247.437 -
247.438 - - filename: The name of the file that this DocTest was extracted
247.439 - from, or `None` if the filename is unknown.
247.440 -
247.441 - - lineno: The line number within filename where this DocTest
247.442 - begins, or `None` if the line number is unavailable. This
247.443 - line number is zero-based, with respect to the beginning of
247.444 - the file.
247.445 -
247.446 - - docstring: The string that the examples were extracted from,
247.447 - or `None` if the string is unavailable.
247.448 - """
247.449 - def __init__(self, examples, globs, name, filename, lineno, docstring):
247.450 - """
247.451 - Create a new DocTest containing the given examples. The
247.452 - DocTest's globals are initialized with a copy of `globs`.
247.453 - """
247.454 - assert not isinstance(examples, basestring), \
247.455 - "DocTest no longer accepts str; use DocTestParser instead"
247.456 - self.examples = examples
247.457 - self.docstring = docstring
247.458 - self.globs = globs.copy()
247.459 - self.name = name
247.460 - self.filename = filename
247.461 - self.lineno = lineno
247.462 -
247.463 - def __repr__(self):
247.464 - if len(self.examples) == 0:
247.465 - examples = 'no examples'
247.466 - elif len(self.examples) == 1:
247.467 - examples = '1 example'
247.468 - else:
247.469 - examples = '%d examples' % len(self.examples)
247.470 - return ('<DocTest %s from %s:%s (%s)>' %
247.471 - (self.name, self.filename, self.lineno, examples))
247.472 -
247.473 -
247.474 - # This lets us sort tests by name:
247.475 - def __cmp__(self, other):
247.476 - if not isinstance(other, DocTest):
247.477 - return -1
247.478 - return cmp((self.name, self.filename, self.lineno, id(self)),
247.479 - (other.name, other.filename, other.lineno, id(other)))
247.480 -
247.481 -######################################################################
247.482 -## 3. DocTestParser
247.483 -######################################################################
247.484 -
247.485 -class DocTestParser:
247.486 - """
247.487 - A class used to parse strings containing doctest examples.
247.488 - """
247.489 - # This regular expression is used to find doctest examples in a
247.490 - # string. It defines three groups: `source` is the source code
247.491 - # (including leading indentation and prompts); `indent` is the
247.492 - # indentation of the first (PS1) line of the source code; and
247.493 - # `want` is the expected output (including leading indentation).
247.494 - _EXAMPLE_RE = re.compile(r'''
247.495 - # Source consists of a PS1 line followed by zero or more PS2 lines.
247.496 - (?P<source>
247.497 - (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
247.498 - (?:\n [ ]* \.\.\. .*)*) # PS2 lines
247.499 - \n?
247.500 - # Want consists of any non-blank lines that do not start with PS1.
247.501 - (?P<want> (?:(?![ ]*$) # Not a blank line
247.502 - (?![ ]*>>>) # Not a line starting with PS1
247.503 - .*$\n? # But any other line
247.504 - )*)
247.505 - ''', re.MULTILINE | re.VERBOSE)
247.506 -
247.507 - # A regular expression for handling `want` strings that contain
247.508 - # expected exceptions. It divides `want` into three pieces:
247.509 - # - the traceback header line (`hdr`)
247.510 - # - the traceback stack (`stack`)
247.511 - # - the exception message (`msg`), as generated by
247.512 - # traceback.format_exception_only()
247.513 - # `msg` may have multiple lines. We assume/require that the
247.514 - # exception message is the first non-indented line starting with a word
247.515 - # character following the traceback header line.
247.516 - _EXCEPTION_RE = re.compile(r"""
247.517 - # Grab the traceback header. Different versions of Python have
247.518 - # said different things on the first traceback line.
247.519 - ^(?P<hdr> Traceback\ \(
247.520 - (?: most\ recent\ call\ last
247.521 - | innermost\ last
247.522 - ) \) :
247.523 - )
247.524 - \s* $ # toss trailing whitespace on the header.
247.525 - (?P<stack> .*?) # don't blink: absorb stuff until...
247.526 - ^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
247.527 - """, re.VERBOSE | re.MULTILINE | re.DOTALL)
247.528 -
247.529 - # A callable returning a true value iff its argument is a blank line
247.530 - # or contains a single comment.
247.531 - _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
247.532 -
247.533 - def parse(self, string, name='<string>'):
247.534 - """
247.535 - Divide the given string into examples and intervening text,
247.536 - and return them as a list of alternating Examples and strings.
247.537 - Line numbers for the Examples are 0-based. The optional
247.538 - argument `name` is a name identifying this string, and is only
247.539 - used for error messages.
247.540 - """
247.541 - string = string.expandtabs()
247.542 - # If all lines begin with the same indentation, then strip it.
247.543 - min_indent = self._min_indent(string)
247.544 - if min_indent > 0:
247.545 - string = '\n'.join([l[min_indent:] for l in string.split('\n')])
247.546 -
247.547 - output = []
247.548 - charno, lineno = 0, 0
247.549 - # Find all doctest examples in the string:
247.550 - for m in self._EXAMPLE_RE.finditer(string):
247.551 - # Add the pre-example text to `output`.
247.552 - output.append(string[charno:m.start()])
247.553 - # Update lineno (lines before this example)
247.554 - lineno += string.count('\n', charno, m.start())
247.555 - # Extract info from the regexp match.
247.556 - (source, options, want, exc_msg) = \
247.557 - self._parse_example(m, name, lineno)
247.558 - # Create an Example, and add it to the list.
247.559 - if not self._IS_BLANK_OR_COMMENT(source):
247.560 - output.append( Example(source, want, exc_msg,
247.561 - lineno=lineno,
247.562 - indent=min_indent+len(m.group('indent')),
247.563 - options=options) )
247.564 - # Update lineno (lines inside this example)
247.565 - lineno += string.count('\n', m.start(), m.end())
247.566 - # Update charno.
247.567 - charno = m.end()
247.568 - # Add any remaining post-example text to `output`.
247.569 - output.append(string[charno:])
247.570 - return output
247.571 -
247.572 - def get_doctest(self, string, globs, name, filename, lineno):
247.573 - """
247.574 - Extract all doctest examples from the given string, and
247.575 - collect them into a `DocTest` object.
247.576 -
247.577 - `globs`, `name`, `filename`, and `lineno` are attributes for
247.578 - the new `DocTest` object. See the documentation for `DocTest`
247.579 - for more information.
247.580 - """
247.581 - return DocTest(self.get_examples(string, name), globs,
247.582 - name, filename, lineno, string)
247.583 -
247.584 - def get_examples(self, string, name='<string>'):
247.585 - """
247.586 - Extract all doctest examples from the given string, and return
247.587 - them as a list of `Example` objects. Line numbers are
247.588 - 0-based, because it's most common in doctests that nothing
247.589 - interesting appears on the same line as opening triple-quote,
247.590 - and so the first interesting line is called \"line 1\" then.
247.591 -
247.592 - The optional argument `name` is a name identifying this
247.593 - string, and is only used for error messages.
247.594 - """
247.595 - return [x for x in self.parse(string, name)
247.596 - if isinstance(x, Example)]
247.597 -
247.598 - def _parse_example(self, m, name, lineno):
247.599 - """
247.600 - Given a regular expression match from `_EXAMPLE_RE` (`m`),
247.601 - return a pair `(source, want)`, where `source` is the matched
247.602 - example's source code (with prompts and indentation stripped);
247.603 - and `want` is the example's expected output (with indentation
247.604 - stripped).
247.605 -
247.606 - `name` is the string's name, and `lineno` is the line number
247.607 - where the example starts; both are used for error messages.
247.608 - """
247.609 - # Get the example's indentation level.
247.610 - indent = len(m.group('indent'))
247.611 -
247.612 - # Divide source into lines; check that they're properly
247.613 - # indented; and then strip their indentation & prompts.
247.614 - source_lines = m.group('source').split('\n')
247.615 - self._check_prompt_blank(source_lines, indent, name, lineno)
247.616 - self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
247.617 - source = '\n'.join([sl[indent+4:] for sl in source_lines])
247.618 -
247.619 - # Divide want into lines; check that it's properly indented; and
247.620 - # then strip the indentation. Spaces before the last newline should
247.621 - # be preserved, so plain rstrip() isn't good enough.
247.622 - want = m.group('want')
247.623 - want_lines = want.split('\n')
247.624 - if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
247.625 - del want_lines[-1] # forget final newline & spaces after it
247.626 - self._check_prefix(want_lines, ' '*indent, name,
247.627 - lineno + len(source_lines))
247.628 - want = '\n'.join([wl[indent:] for wl in want_lines])
247.629 -
247.630 - # If `want` contains a traceback message, then extract it.
247.631 - m = self._EXCEPTION_RE.match(want)
247.632 - if m:
247.633 - exc_msg = m.group('msg')
247.634 - else:
247.635 - exc_msg = None
247.636 -
247.637 - # Extract options from the source.
247.638 - options = self._find_options(source, name, lineno)
247.639 -
247.640 - return source, options, want, exc_msg
247.641 -
247.642 - # This regular expression looks for option directives in the
247.643 - # source code of an example. Option directives are comments
247.644 - # starting with "doctest:". Warning: this may give false
247.645 - # positives for string-literals that contain the string
247.646 - # "#doctest:". Eliminating these false positives would require
247.647 - # actually parsing the string; but we limit them by ignoring any
247.648 - # line containing "#doctest:" that is *followed* by a quote mark.
247.649 - _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
247.650 - re.MULTILINE)
247.651 -
247.652 - def _find_options(self, source, name, lineno):
247.653 - """
247.654 - Return a dictionary containing option overrides extracted from
247.655 - option directives in the given source string.
247.656 -
247.657 - `name` is the string's name, and `lineno` is the line number
247.658 - where the example starts; both are used for error messages.
247.659 - """
247.660 - options = {}
247.661 - # (note: with the current regexp, this will match at most once:)
247.662 - for m in self._OPTION_DIRECTIVE_RE.finditer(source):
247.663 - option_strings = m.group(1).replace(',', ' ').split()
247.664 - for option in option_strings:
247.665 - if (option[0] not in '+-' or
247.666 - option[1:] not in OPTIONFLAGS_BY_NAME):
247.667 - raise ValueError('line %r of the doctest for %s '
247.668 - 'has an invalid option: %r' %
247.669 - (lineno+1, name, option))
247.670 - flag = OPTIONFLAGS_BY_NAME[option[1:]]
247.671 - options[flag] = (option[0] == '+')
247.672 - if options and self._IS_BLANK_OR_COMMENT(source):
247.673 - raise ValueError('line %r of the doctest for %s has an option '
247.674 - 'directive on a line with no example: %r' %
247.675 - (lineno, name, source))
247.676 - return options
247.677 -
247.678 - # This regular expression finds the indentation of every non-blank
247.679 - # line in a string.
247.680 - _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
247.681 -
247.682 - def _min_indent(self, s):
247.683 - "Return the minimum indentation of any non-blank line in `s`"
247.684 - indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
247.685 - if len(indents) > 0:
247.686 - return min(indents)
247.687 - else:
247.688 - return 0
247.689 -
247.690 - def _check_prompt_blank(self, lines, indent, name, lineno):
247.691 - """
247.692 - Given the lines of a source string (including prompts and
247.693 - leading indentation), check to make sure that every prompt is
247.694 - followed by a space character. If any line is not followed by
247.695 - a space character, then raise ValueError.
247.696 - """
247.697 - for i, line in enumerate(lines):
247.698 - if len(line) >= indent+4 and line[indent+3] != ' ':
247.699 - raise ValueError('line %r of the docstring for %s '
247.700 - 'lacks blank after %s: %r' %
247.701 - (lineno+i+1, name,
247.702 - line[indent:indent+3], line))
247.703 -
247.704 - def _check_prefix(self, lines, prefix, name, lineno):
247.705 - """
247.706 - Check that every line in the given list starts with the given
247.707 - prefix; if any line does not, then raise a ValueError.
247.708 - """
247.709 - for i, line in enumerate(lines):
247.710 - if line and not line.startswith(prefix):
247.711 - raise ValueError('line %r of the docstring for %s has '
247.712 - 'inconsistent leading whitespace: %r' %
247.713 - (lineno+i+1, name, line))
247.714 -
247.715 -
247.716 -######################################################################
247.717 -## 4. DocTest Finder
247.718 -######################################################################
247.719 -
247.720 -class DocTestFinder:
247.721 - """
247.722 - A class used to extract the DocTests that are relevant to a given
247.723 - object, from its docstring and the docstrings of its contained
247.724 - objects. Doctests can currently be extracted from the following
247.725 - object types: modules, functions, classes, methods, staticmethods,
247.726 - classmethods, and properties.
247.727 - """
247.728 -
247.729 - def __init__(self, verbose=False, parser=DocTestParser(),
247.730 - recurse=True, exclude_empty=True):
247.731 - """
247.732 - Create a new doctest finder.
247.733 -
247.734 - The optional argument `parser` specifies a class or
247.735 - function that should be used to create new DocTest objects (or
247.736 - objects that implement the same interface as DocTest). The
247.737 - signature for this factory function should match the signature
247.738 - of the DocTest constructor.
247.739 -
247.740 - If the optional argument `recurse` is false, then `find` will
247.741 - only examine the given object, and not any contained objects.
247.742 -
247.743 - If the optional argument `exclude_empty` is false, then `find`
247.744 - will include tests for objects with empty docstrings.
247.745 - """
247.746 - self._parser = parser
247.747 - self._verbose = verbose
247.748 - self._recurse = recurse
247.749 - self._exclude_empty = exclude_empty
247.750 -
247.751 - def find(self, obj, name=None, module=None, globs=None, extraglobs=None):
247.752 - """
247.753 - Return a list of the DocTests that are defined by the given
247.754 - object's docstring, or by any of its contained objects'
247.755 - docstrings.
247.756 -
247.757 - The optional parameter `module` is the module that contains
247.758 - the given object. If the module is not specified or is None, then
247.759 - the test finder will attempt to automatically determine the
247.760 - correct module. The object's module is used:
247.761 -
247.762 - - As a default namespace, if `globs` is not specified.
247.763 - - To prevent the DocTestFinder from extracting DocTests
247.764 - from objects that are imported from other modules.
247.765 - - To find the name of the file containing the object.
247.766 - - To help find the line number of the object within its
247.767 - file.
247.768 -
247.769 - Contained objects whose module does not match `module` are ignored.
247.770 -
247.771 - If `module` is False, no attempt to find the module will be made.
247.772 - This is obscure, of use mostly in tests: if `module` is False, or
247.773 - is None but cannot be found automatically, then all objects are
247.774 - considered to belong to the (non-existent) module, so all contained
247.775 - objects will (recursively) be searched for doctests.
247.776 -
247.777 - The globals for each DocTest is formed by combining `globs`
247.778 - and `extraglobs` (bindings in `extraglobs` override bindings
247.779 - in `globs`). A new copy of the globals dictionary is created
247.780 - for each DocTest. If `globs` is not specified, then it
247.781 - defaults to the module's `__dict__`, if specified, or {}
247.782 - otherwise. If `extraglobs` is not specified, then it defaults
247.783 - to {}.
247.784 -
247.785 - """
247.786 - # If name was not specified, then extract it from the object.
247.787 - if name is None:
247.788 - name = getattr(obj, '__name__', None)
247.789 - if name is None:
247.790 - raise ValueError("DocTestFinder.find: name must be given "
247.791 - "when obj.__name__ doesn't exist: %r" %
247.792 - (type(obj),))
247.793 -
247.794 - # Find the module that contains the given object (if obj is
247.795 - # a module, then module=obj.). Note: this may fail, in which
247.796 - # case module will be None.
247.797 - if module is False:
247.798 - module = None
247.799 - elif module is None:
247.800 - module = inspect.getmodule(obj)
247.801 -
247.802 - # Read the module's source code. This is used by
247.803 - # DocTestFinder._find_lineno to find the line number for a
247.804 - # given object's docstring.
247.805 - try:
247.806 - file = inspect.getsourcefile(obj) or inspect.getfile(obj)
247.807 - source_lines = linecache.getlines(file)
247.808 - if not source_lines:
247.809 - source_lines = None
247.810 - except TypeError:
247.811 - source_lines = None
247.812 -
247.813 - # Initialize globals, and merge in extraglobs.
247.814 - if globs is None:
247.815 - if module is None:
247.816 - globs = {}
247.817 - else:
247.818 - globs = module.__dict__.copy()
247.819 - else:
247.820 - globs = globs.copy()
247.821 - if extraglobs is not None:
247.822 - globs.update(extraglobs)
247.823 -
247.824 - # Recursively expore `obj`, extracting DocTests.
247.825 - tests = []
247.826 - self._find(tests, obj, name, module, source_lines, globs, {})
247.827 - # Sort the tests by alpha order of names, for consistency in
247.828 - # verbose-mode output. This was a feature of doctest in Pythons
247.829 - # <= 2.3 that got lost by accident in 2.4. It was repaired in
247.830 - # 2.4.4 and 2.5.
247.831 - tests.sort()
247.832 - return tests
247.833 -
247.834 - def _from_module(self, module, object):
247.835 - """
247.836 - Return true if the given object is defined in the given
247.837 - module.
247.838 - """
247.839 - if module is None:
247.840 - return True
247.841 - elif inspect.isfunction(object):
247.842 - return module.__dict__ is object.func_globals
247.843 - elif inspect.isclass(object):
247.844 - return module.__name__ == object.__module__
247.845 - elif inspect.getmodule(object) is not None:
247.846 - return module is inspect.getmodule(object)
247.847 - elif hasattr(object, '__module__'):
247.848 - return module.__name__ == object.__module__
247.849 - elif isinstance(object, property):
247.850 - return True # [XX] no way not be sure.
247.851 - else:
247.852 - raise ValueError("object must be a class or function")
247.853 -
247.854 - def _find(self, tests, obj, name, module, source_lines, globs, seen):
247.855 - """
247.856 - Find tests for the given object and any contained objects, and
247.857 - add them to `tests`.
247.858 - """
247.859 - if self._verbose:
247.860 - print 'Finding tests in %s' % name
247.861 -
247.862 - # If we've already processed this object, then ignore it.
247.863 - if id(obj) in seen:
247.864 - return
247.865 - seen[id(obj)] = 1
247.866 -
247.867 - # Find a test for this object, and add it to the list of tests.
247.868 - test = self._get_test(obj, name, module, globs, source_lines)
247.869 - if test is not None:
247.870 - tests.append(test)
247.871 -
247.872 - # Look for tests in a module's contained objects.
247.873 - if inspect.ismodule(obj) and self._recurse:
247.874 - for valname, val in obj.__dict__.items():
247.875 - valname = '%s.%s' % (name, valname)
247.876 - # Recurse to functions & classes.
247.877 - if ((inspect.isfunction(val) or inspect.isclass(val)) and
247.878 - self._from_module(module, val)):
247.879 - self._find(tests, val, valname, module, source_lines,
247.880 - globs, seen)
247.881 -
247.882 - # Look for tests in a module's __test__ dictionary.
247.883 - if inspect.ismodule(obj) and self._recurse:
247.884 - for valname, val in getattr(obj, '__test__', {}).items():
247.885 - if not isinstance(valname, basestring):
247.886 - raise ValueError("DocTestFinder.find: __test__ keys "
247.887 - "must be strings: %r" %
247.888 - (type(valname),))
247.889 - if not (inspect.isfunction(val) or inspect.isclass(val) or
247.890 - inspect.ismethod(val) or inspect.ismodule(val) or
247.891 - isinstance(val, basestring)):
247.892 - raise ValueError("DocTestFinder.find: __test__ values "
247.893 - "must be strings, functions, methods, "
247.894 - "classes, or modules: %r" %
247.895 - (type(val),))
247.896 - valname = '%s.__test__.%s' % (name, valname)
247.897 - self._find(tests, val, valname, module, source_lines,
247.898 - globs, seen)
247.899 -
247.900 - # Look for tests in a class's contained objects.
247.901 - if inspect.isclass(obj) and self._recurse:
247.902 - for valname, val in obj.__dict__.items():
247.903 - # Special handling for staticmethod/classmethod.
247.904 - if isinstance(val, staticmethod):
247.905 - val = getattr(obj, valname)
247.906 - if isinstance(val, classmethod):
247.907 - val = getattr(obj, valname).im_func
247.908 -
247.909 - # Recurse to methods, properties, and nested classes.
247.910 - if ((inspect.isfunction(val) or inspect.isclass(val) or
247.911 - isinstance(val, property)) and
247.912 - self._from_module(module, val)):
247.913 - valname = '%s.%s' % (name, valname)
247.914 - self._find(tests, val, valname, module, source_lines,
247.915 - globs, seen)
247.916 -
247.917 - def _get_test(self, obj, name, module, globs, source_lines):
247.918 - """
247.919 - Return a DocTest for the given object, if it defines a docstring;
247.920 - otherwise, return None.
247.921 - """
247.922 - # Extract the object's docstring. If it doesn't have one,
247.923 - # then return None (no test for this object).
247.924 - if isinstance(obj, basestring):
247.925 - docstring = obj
247.926 - else:
247.927 - try:
247.928 - if obj.__doc__ is None:
247.929 - docstring = ''
247.930 - else:
247.931 - docstring = obj.__doc__
247.932 - if not isinstance(docstring, basestring):
247.933 - docstring = str(docstring)
247.934 - except (TypeError, AttributeError):
247.935 - docstring = ''
247.936 -
247.937 - # Find the docstring's location in the file.
247.938 - lineno = self._find_lineno(obj, source_lines)
247.939 -
247.940 - # Don't bother if the docstring is empty.
247.941 - if self._exclude_empty and not docstring:
247.942 - return None
247.943 -
247.944 - # Return a DocTest for this object.
247.945 - if module is None:
247.946 - filename = None
247.947 - else:
247.948 - filename = getattr(module, '__file__', module.__name__)
247.949 - if filename[-4:] in (".pyc", ".pyo"):
247.950 - filename = filename[:-1]
247.951 - return self._parser.get_doctest(docstring, globs, name,
247.952 - filename, lineno)
247.953 -
247.954 - def _find_lineno(self, obj, source_lines):
247.955 - """
247.956 - Return a line number of the given object's docstring. Note:
247.957 - this method assumes that the object has a docstring.
247.958 - """
247.959 - lineno = None
247.960 -
247.961 - # Find the line number for modules.
247.962 - if inspect.ismodule(obj):
247.963 - lineno = 0
247.964 -
247.965 - # Find the line number for classes.
247.966 - # Note: this could be fooled if a class is defined multiple
247.967 - # times in a single file.
247.968 - if inspect.isclass(obj):
247.969 - if source_lines is None:
247.970 - return None
247.971 - pat = re.compile(r'^\s*class\s*%s\b' %
247.972 - getattr(obj, '__name__', '-'))
247.973 - for i, line in enumerate(source_lines):
247.974 - if pat.match(line):
247.975 - lineno = i
247.976 - break
247.977 -
247.978 - # Find the line number for functions & methods.
247.979 - if inspect.ismethod(obj): obj = obj.im_func
247.980 - if inspect.isfunction(obj): obj = obj.func_code
247.981 - if inspect.istraceback(obj): obj = obj.tb_frame
247.982 - if inspect.isframe(obj): obj = obj.f_code
247.983 - if inspect.iscode(obj):
247.984 - lineno = getattr(obj, 'co_firstlineno', None)-1
247.985 -
247.986 - # Find the line number where the docstring starts. Assume
247.987 - # that it's the first line that begins with a quote mark.
247.988 - # Note: this could be fooled by a multiline function
247.989 - # signature, where a continuation line begins with a quote
247.990 - # mark.
247.991 - if lineno is not None:
247.992 - if source_lines is None:
247.993 - return lineno+1
247.994 - pat = re.compile('(^|.*:)\s*\w*("|\')')
247.995 - for lineno in range(lineno, len(source_lines)):
247.996 - if pat.match(source_lines[lineno]):
247.997 - return lineno
247.998 -
247.999 - # We couldn't find the line number.
247.1000 - return None
247.1001 -
247.1002 -######################################################################
247.1003 -## 5. DocTest Runner
247.1004 -######################################################################
247.1005 -
247.1006 -class DocTestRunner:
247.1007 - """
247.1008 - A class used to run DocTest test cases, and accumulate statistics.
247.1009 - The `run` method is used to process a single DocTest case. It
247.1010 - returns a tuple `(f, t)`, where `t` is the number of test cases
247.1011 - tried, and `f` is the number of test cases that failed.
247.1012 -
247.1013 - >>> tests = DocTestFinder().find(_TestClass)
247.1014 - >>> runner = DocTestRunner(verbose=False)
247.1015 - >>> tests.sort(key = lambda test: test.name)
247.1016 - >>> for test in tests:
247.1017 - ... print test.name, '->', runner.run(test)
247.1018 - _TestClass -> (0, 2)
247.1019 - _TestClass.__init__ -> (0, 2)
247.1020 - _TestClass.get -> (0, 2)
247.1021 - _TestClass.square -> (0, 1)
247.1022 -
247.1023 - The `summarize` method prints a summary of all the test cases that
247.1024 - have been run by the runner, and returns an aggregated `(f, t)`
247.1025 - tuple:
247.1026 -
247.1027 - >>> runner.summarize(verbose=1)
247.1028 - 4 items passed all tests:
247.1029 - 2 tests in _TestClass
247.1030 - 2 tests in _TestClass.__init__
247.1031 - 2 tests in _TestClass.get
247.1032 - 1 tests in _TestClass.square
247.1033 - 7 tests in 4 items.
247.1034 - 7 passed and 0 failed.
247.1035 - Test passed.
247.1036 - (0, 7)
247.1037 -
247.1038 - The aggregated number of tried examples and failed examples is
247.1039 - also available via the `tries` and `failures` attributes:
247.1040 -
247.1041 - >>> runner.tries
247.1042 - 7
247.1043 - >>> runner.failures
247.1044 - 0
247.1045 -
247.1046 - The comparison between expected outputs and actual outputs is done
247.1047 - by an `OutputChecker`. This comparison may be customized with a
247.1048 - number of option flags; see the documentation for `testmod` for
247.1049 - more information. If the option flags are insufficient, then the
247.1050 - comparison may also be customized by passing a subclass of
247.1051 - `OutputChecker` to the constructor.
247.1052 -
247.1053 - The test runner's display output can be controlled in two ways.
247.1054 - First, an output function (`out) can be passed to
247.1055 - `TestRunner.run`; this function will be called with strings that
247.1056 - should be displayed. It defaults to `sys.stdout.write`. If
247.1057 - capturing the output is not sufficient, then the display output
247.1058 - can be also customized by subclassing DocTestRunner, and
247.1059 - overriding the methods `report_start`, `report_success`,
247.1060 - `report_unexpected_exception`, and `report_failure`.
247.1061 - """
247.1062 - # This divider string is used to separate failure messages, and to
247.1063 - # separate sections of the summary.
247.1064 - DIVIDER = "*" * 70
247.1065 -
247.1066 - def __init__(self, checker=None, verbose=None, optionflags=0):
247.1067 - """
247.1068 - Create a new test runner.
247.1069 -
247.1070 - Optional keyword arg `checker` is the `OutputChecker` that
247.1071 - should be used to compare the expected outputs and actual
247.1072 - outputs of doctest examples.
247.1073 -
247.1074 - Optional keyword arg 'verbose' prints lots of stuff if true,
247.1075 - only failures if false; by default, it's true iff '-v' is in
247.1076 - sys.argv.
247.1077 -
247.1078 - Optional argument `optionflags` can be used to control how the
247.1079 - test runner compares expected output to actual output, and how
247.1080 - it displays failures. See the documentation for `testmod` for
247.1081 - more information.
247.1082 - """
247.1083 - self._checker = checker or OutputChecker()
247.1084 - if verbose is None:
247.1085 - verbose = '-v' in sys.argv
247.1086 - self._verbose = verbose
247.1087 - self.optionflags = optionflags
247.1088 - self.original_optionflags = optionflags
247.1089 -
247.1090 - # Keep track of the examples we've run.
247.1091 - self.tries = 0
247.1092 - self.failures = 0
247.1093 - self._name2ft = {}
247.1094 -
247.1095 - # Create a fake output target for capturing doctest output.
247.1096 - self._fakeout = _SpoofOut()
247.1097 -
247.1098 - #/////////////////////////////////////////////////////////////////
247.1099 - # Reporting methods
247.1100 - #/////////////////////////////////////////////////////////////////
247.1101 -
247.1102 - def report_start(self, out, test, example):
247.1103 - """
247.1104 - Report that the test runner is about to process the given
247.1105 - example. (Only displays a message if verbose=True)
247.1106 - """
247.1107 - if self._verbose:
247.1108 - if example.want:
247.1109 - out('Trying:\n' + _indent(example.source) +
247.1110 - 'Expecting:\n' + _indent(example.want))
247.1111 - else:
247.1112 - out('Trying:\n' + _indent(example.source) +
247.1113 - 'Expecting nothing\n')
247.1114 -
247.1115 - def report_success(self, out, test, example, got):
247.1116 - """
247.1117 - Report that the given example ran successfully. (Only
247.1118 - displays a message if verbose=True)
247.1119 - """
247.1120 - if self._verbose:
247.1121 - out("ok\n")
247.1122 -
247.1123 - def report_failure(self, out, test, example, got):
247.1124 - """
247.1125 - Report that the given example failed.
247.1126 - """
247.1127 - out(self._failure_header(test, example) +
247.1128 - self._checker.output_difference(example, got, self.optionflags))
247.1129 -
247.1130 - def report_unexpected_exception(self, out, test, example, exc_info):
247.1131 - """
247.1132 - Report that the given example raised an unexpected exception.
247.1133 - """
247.1134 - out(self._failure_header(test, example) +
247.1135 - 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
247.1136 -
247.1137 - def _failure_header(self, test, example):
247.1138 - out = [self.DIVIDER]
247.1139 - if test.filename:
247.1140 - if test.lineno is not None and example.lineno is not None:
247.1141 - lineno = test.lineno + example.lineno + 1
247.1142 - else:
247.1143 - lineno = '?'
247.1144 - out.append('File "%s", line %s, in %s' %
247.1145 - (test.filename, lineno, test.name))
247.1146 - else:
247.1147 - out.append('Line %s, in %s' % (example.lineno+1, test.name))
247.1148 - out.append('Failed example:')
247.1149 - source = example.source
247.1150 - out.append(_indent(source))
247.1151 - return '\n'.join(out)
247.1152 -
247.1153 - #/////////////////////////////////////////////////////////////////
247.1154 - # DocTest Running
247.1155 - #/////////////////////////////////////////////////////////////////
247.1156 -
247.1157 - def __run(self, test, compileflags, out):
247.1158 - """
247.1159 - Run the examples in `test`. Write the outcome of each example
247.1160 - with one of the `DocTestRunner.report_*` methods, using the
247.1161 - writer function `out`. `compileflags` is the set of compiler
247.1162 - flags that should be used to execute examples. Return a tuple
247.1163 - `(f, t)`, where `t` is the number of examples tried, and `f`
247.1164 - is the number of examples that failed. The examples are run
247.1165 - in the namespace `test.globs`.
247.1166 - """
247.1167 - # Keep track of the number of failures and tries.
247.1168 - failures = tries = 0
247.1169 -
247.1170 - # Save the option flags (since option directives can be used
247.1171 - # to modify them).
247.1172 - original_optionflags = self.optionflags
247.1173 -
247.1174 - SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
247.1175 -
247.1176 - check = self._checker.check_output
247.1177 -
247.1178 - # Process each example.
247.1179 - for examplenum, example in enumerate(test.examples):
247.1180 -
247.1181 - # If REPORT_ONLY_FIRST_FAILURE is set, then supress
247.1182 - # reporting after the first failure.
247.1183 - quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
247.1184 - failures > 0)
247.1185 -
247.1186 - # Merge in the example's options.
247.1187 - self.optionflags = original_optionflags
247.1188 - if example.options:
247.1189 - for (optionflag, val) in example.options.items():
247.1190 - if val:
247.1191 - self.optionflags |= optionflag
247.1192 - else:
247.1193 - self.optionflags &= ~optionflag
247.1194 -
247.1195 - # If 'SKIP' is set, then skip this example.
247.1196 - if self.optionflags & SKIP:
247.1197 - continue
247.1198 -
247.1199 - # Record that we started this example.
247.1200 - tries += 1
247.1201 - if not quiet:
247.1202 - self.report_start(out, test, example)
247.1203 -
247.1204 - # Use a special filename for compile(), so we can retrieve
247.1205 - # the source code during interactive debugging (see
247.1206 - # __patched_linecache_getlines).
247.1207 - filename = '<doctest %s[%d]>' % (test.name, examplenum)
247.1208 -
247.1209 - # Run the example in the given context (globs), and record
247.1210 - # any exception that gets raised. (But don't intercept
247.1211 - # keyboard interrupts.)
247.1212 - try:
247.1213 - # Don't blink! This is where the user's code gets run.
247.1214 - exec compile(example.source, filename, "single",
247.1215 - compileflags, 1) in test.globs
247.1216 - self.debugger.set_continue() # ==== Example Finished ====
247.1217 - exception = None
247.1218 - except KeyboardInterrupt:
247.1219 - raise
247.1220 - except:
247.1221 - exception = sys.exc_info()
247.1222 - self.debugger.set_continue() # ==== Example Finished ====
247.1223 -
247.1224 - got = self._fakeout.getvalue() # the actual output
247.1225 - self._fakeout.truncate(0)
247.1226 - outcome = FAILURE # guilty until proved innocent or insane
247.1227 -
247.1228 - # If the example executed without raising any exceptions,
247.1229 - # verify its output.
247.1230 - if exception is None:
247.1231 - if check(example.want, got, self.optionflags):
247.1232 - outcome = SUCCESS
247.1233 -
247.1234 - # The example raised an exception: check if it was expected.
247.1235 - else:
247.1236 - exc_info = sys.exc_info()
247.1237 - exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
247.1238 - if not quiet:
247.1239 - got += _exception_traceback(exc_info)
247.1240 -
247.1241 - # If `example.exc_msg` is None, then we weren't expecting
247.1242 - # an exception.
247.1243 - if example.exc_msg is None:
247.1244 - outcome = BOOM
247.1245 -
247.1246 - # We expected an exception: see whether it matches.
247.1247 - elif check(example.exc_msg, exc_msg, self.optionflags):
247.1248 - outcome = SUCCESS
247.1249 -
247.1250 - # Another chance if they didn't care about the detail.
247.1251 - elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
247.1252 - m1 = re.match(r'[^:]*:', example.exc_msg)
247.1253 - m2 = re.match(r'[^:]*:', exc_msg)
247.1254 - if m1 and m2 and check(m1.group(0), m2.group(0),
247.1255 - self.optionflags):
247.1256 - outcome = SUCCESS
247.1257 -
247.1258 - # Report the outcome.
247.1259 - if outcome is SUCCESS:
247.1260 - if not quiet:
247.1261 - self.report_success(out, test, example, got)
247.1262 - elif outcome is FAILURE:
247.1263 - if not quiet:
247.1264 - self.report_failure(out, test, example, got)
247.1265 - failures += 1
247.1266 - elif outcome is BOOM:
247.1267 - if not quiet:
247.1268 - self.report_unexpected_exception(out, test, example,
247.1269 - exc_info)
247.1270 - failures += 1
247.1271 - else:
247.1272 - assert False, ("unknown outcome", outcome)
247.1273 -
247.1274 - # Restore the option flags (in case they were modified)
247.1275 - self.optionflags = original_optionflags
247.1276 -
247.1277 - # Record and return the number of failures and tries.
247.1278 - self.__record_outcome(test, failures, tries)
247.1279 - return failures, tries
247.1280 -
247.1281 - def __record_outcome(self, test, f, t):
247.1282 - """
247.1283 - Record the fact that the given DocTest (`test`) generated `f`
247.1284 - failures out of `t` tried examples.
247.1285 - """
247.1286 - f2, t2 = self._name2ft.get(test.name, (0,0))
247.1287 - self._name2ft[test.name] = (f+f2, t+t2)
247.1288 - self.failures += f
247.1289 - self.tries += t
247.1290 -
247.1291 - __LINECACHE_FILENAME_RE = re.compile(r'<doctest '
247.1292 - r'(?P<name>[\w\.]+)'
247.1293 - r'\[(?P<examplenum>\d+)\]>$')
247.1294 - def __patched_linecache_getlines(self, filename, module_globals=None):
247.1295 - m = self.__LINECACHE_FILENAME_RE.match(filename)
247.1296 - if m and m.group('name') == self.test.name:
247.1297 - example = self.test.examples[int(m.group('examplenum'))]
247.1298 - return example.source.splitlines(True)
247.1299 - else:
247.1300 - return self.save_linecache_getlines(filename, module_globals)
247.1301 -
247.1302 - def run(self, test, compileflags=None, out=None, clear_globs=True):
247.1303 - """
247.1304 - Run the examples in `test`, and display the results using the
247.1305 - writer function `out`.
247.1306 -
247.1307 - The examples are run in the namespace `test.globs`. If
247.1308 - `clear_globs` is true (the default), then this namespace will
247.1309 - be cleared after the test runs, to help with garbage
247.1310 - collection. If you would like to examine the namespace after
247.1311 - the test completes, then use `clear_globs=False`.
247.1312 -
247.1313 - `compileflags` gives the set of flags that should be used by
247.1314 - the Python compiler when running the examples. If not
247.1315 - specified, then it will default to the set of future-import
247.1316 - flags that apply to `globs`.
247.1317 -
247.1318 - The output of each example is checked using
247.1319 - `DocTestRunner.check_output`, and the results are formatted by
247.1320 - the `DocTestRunner.report_*` methods.
247.1321 - """
247.1322 - self.test = test
247.1323 -
247.1324 - if compileflags is None:
247.1325 - compileflags = _extract_future_flags(test.globs)
247.1326 -
247.1327 - save_stdout = sys.stdout
247.1328 - if out is None:
247.1329 - out = save_stdout.write
247.1330 - sys.stdout = self._fakeout
247.1331 -
247.1332 - # Patch pdb.set_trace to restore sys.stdout during interactive
247.1333 - # debugging (so it's not still redirected to self._fakeout).
247.1334 - # Note that the interactive output will go to *our*
247.1335 - # save_stdout, even if that's not the real sys.stdout; this
247.1336 - # allows us to write test cases for the set_trace behavior.
247.1337 - save_set_trace = pdb.set_trace
247.1338 - self.debugger = _OutputRedirectingPdb(save_stdout)
247.1339 - self.debugger.reset()
247.1340 - pdb.set_trace = self.debugger.set_trace
247.1341 -
247.1342 - # Patch linecache.getlines, so we can see the example's source
247.1343 - # when we're inside the debugger.
247.1344 - self.save_linecache_getlines = linecache.getlines
247.1345 - linecache.getlines = self.__patched_linecache_getlines
247.1346 -
247.1347 - try:
247.1348 - return self.__run(test, compileflags, out)
247.1349 - finally:
247.1350 - sys.stdout = save_stdout
247.1351 - pdb.set_trace = save_set_trace
247.1352 - linecache.getlines = self.save_linecache_getlines
247.1353 - if clear_globs:
247.1354 - test.globs.clear()
247.1355 -
247.1356 - #/////////////////////////////////////////////////////////////////
247.1357 - # Summarization
247.1358 - #/////////////////////////////////////////////////////////////////
247.1359 - def summarize(self, verbose=None):
247.1360 - """
247.1361 - Print a summary of all the test cases that have been run by
247.1362 - this DocTestRunner, and return a tuple `(f, t)`, where `f` is
247.1363 - the total number of failed examples, and `t` is the total
247.1364 - number of tried examples.
247.1365 -
247.1366 - The optional `verbose` argument controls how detailed the
247.1367 - summary is. If the verbosity is not specified, then the
247.1368 - DocTestRunner's verbosity is used.
247.1369 - """
247.1370 - if verbose is None:
247.1371 - verbose = self._verbose
247.1372 - notests = []
247.1373 - passed = []
247.1374 - failed = []
247.1375 - totalt = totalf = 0
247.1376 - for x in self._name2ft.items():
247.1377 - name, (f, t) = x
247.1378 - assert f <= t
247.1379 - totalt += t
247.1380 - totalf += f
247.1381 - if t == 0:
247.1382 - notests.append(name)
247.1383 - elif f == 0:
247.1384 - passed.append( (name, t) )
247.1385 - else:
247.1386 - failed.append(x)
247.1387 - if verbose:
247.1388 - if notests:
247.1389 - print len(notests), "items had no tests:"
247.1390 - notests.sort()
247.1391 - for thing in notests:
247.1392 - print " ", thing
247.1393 - if passed:
247.1394 - print len(passed), "items passed all tests:"
247.1395 - passed.sort()
247.1396 - for thing, count in passed:
247.1397 - print " %3d tests in %s" % (count, thing)
247.1398 - if failed:
247.1399 - print self.DIVIDER
247.1400 - print len(failed), "items had failures:"
247.1401 - failed.sort()
247.1402 - for thing, (f, t) in failed:
247.1403 - print " %3d of %3d in %s" % (f, t, thing)
247.1404 - if verbose:
247.1405 - print totalt, "tests in", len(self._name2ft), "items."
247.1406 - print totalt - totalf, "passed and", totalf, "failed."
247.1407 - if totalf:
247.1408 - print "***Test Failed***", totalf, "failures."
247.1409 - elif verbose:
247.1410 - print "Test passed."
247.1411 - return totalf, totalt
247.1412 -
247.1413 - #/////////////////////////////////////////////////////////////////
247.1414 - # Backward compatibility cruft to maintain doctest.master.
247.1415 - #/////////////////////////////////////////////////////////////////
247.1416 - def merge(self, other):
247.1417 - d = self._name2ft
247.1418 - for name, (f, t) in other._name2ft.items():
247.1419 - if name in d:
247.1420 - print "*** DocTestRunner.merge: '" + name + "' in both" \
247.1421 - " testers; summing outcomes."
247.1422 - f2, t2 = d[name]
247.1423 - f = f + f2
247.1424 - t = t + t2
247.1425 - d[name] = f, t
247.1426 -
247.1427 -class OutputChecker:
247.1428 - """
247.1429 - A class used to check the whether the actual output from a doctest
247.1430 - example matches the expected output. `OutputChecker` defines two
247.1431 - methods: `check_output`, which compares a given pair of outputs,
247.1432 - and returns true if they match; and `output_difference`, which
247.1433 - returns a string describing the differences between two outputs.
247.1434 - """
247.1435 - def check_output(self, want, got, optionflags):
247.1436 - """
247.1437 - Return True iff the actual output from an example (`got`)
247.1438 - matches the expected output (`want`). These strings are
247.1439 - always considered to match if they are identical; but
247.1440 - depending on what option flags the test runner is using,
247.1441 - several non-exact match types are also possible. See the
247.1442 - documentation for `TestRunner` for more information about
247.1443 - option flags.
247.1444 - """
247.1445 - # Handle the common case first, for efficiency:
247.1446 - # if they're string-identical, always return true.
247.1447 - if got == want:
247.1448 - return True
247.1449 -
247.1450 - # The values True and False replaced 1 and 0 as the return
247.1451 - # value for boolean comparisons in Python 2.3.
247.1452 - if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
247.1453 - if (got,want) == ("True\n", "1\n"):
247.1454 - return True
247.1455 - if (got,want) == ("False\n", "0\n"):
247.1456 - return True
247.1457 -
247.1458 - # <BLANKLINE> can be used as a special sequence to signify a
247.1459 - # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
247.1460 - if not (optionflags & DONT_ACCEPT_BLANKLINE):
247.1461 - # Replace <BLANKLINE> in want with a blank line.
247.1462 - want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
247.1463 - '', want)
247.1464 - # If a line in got contains only spaces, then remove the
247.1465 - # spaces.
247.1466 - got = re.sub('(?m)^\s*?$', '', got)
247.1467 - if got == want:
247.1468 - return True
247.1469 -
247.1470 - # This flag causes doctest to ignore any differences in the
247.1471 - # contents of whitespace strings. Note that this can be used
247.1472 - # in conjunction with the ELLIPSIS flag.
247.1473 - if optionflags & NORMALIZE_WHITESPACE:
247.1474 - got = ' '.join(got.split())
247.1475 - want = ' '.join(want.split())
247.1476 - if got == want:
247.1477 - return True
247.1478 -
247.1479 - # The ELLIPSIS flag says to let the sequence "..." in `want`
247.1480 - # match any substring in `got`.
247.1481 - if optionflags & ELLIPSIS:
247.1482 - if _ellipsis_match(want, got):
247.1483 - return True
247.1484 -
247.1485 - # We didn't find any match; return false.
247.1486 - return False
247.1487 -
247.1488 - # Should we do a fancy diff?
247.1489 - def _do_a_fancy_diff(self, want, got, optionflags):
247.1490 - # Not unless they asked for a fancy diff.
247.1491 - if not optionflags & (REPORT_UDIFF |
247.1492 - REPORT_CDIFF |
247.1493 - REPORT_NDIFF):
247.1494 - return False
247.1495 -
247.1496 - # If expected output uses ellipsis, a meaningful fancy diff is
247.1497 - # too hard ... or maybe not. In two real-life failures Tim saw,
247.1498 - # a diff was a major help anyway, so this is commented out.
247.1499 - # [todo] _ellipsis_match() knows which pieces do and don't match,
247.1500 - # and could be the basis for a kick-ass diff in this case.
247.1501 - ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
247.1502 - ## return False
247.1503 -
247.1504 - # ndiff does intraline difference marking, so can be useful even
247.1505 - # for 1-line differences.
247.1506 - if optionflags & REPORT_NDIFF:
247.1507 - return True
247.1508 -
247.1509 - # The other diff types need at least a few lines to be helpful.
247.1510 - return want.count('\n') > 2 and got.count('\n') > 2
247.1511 -
247.1512 - def output_difference(self, example, got, optionflags):
247.1513 - """
247.1514 - Return a string describing the differences between the
247.1515 - expected output for a given example (`example`) and the actual
247.1516 - output (`got`). `optionflags` is the set of option flags used
247.1517 - to compare `want` and `got`.
247.1518 - """
247.1519 - want = example.want
247.1520 - # If <BLANKLINE>s are being used, then replace blank lines
247.1521 - # with <BLANKLINE> in the actual output string.
247.1522 - if not (optionflags & DONT_ACCEPT_BLANKLINE):
247.1523 - got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
247.1524 -
247.1525 - # Check if we should use diff.
247.1526 - if self._do_a_fancy_diff(want, got, optionflags):
247.1527 - # Split want & got into lines.
247.1528 - want_lines = want.splitlines(True) # True == keep line ends
247.1529 - got_lines = got.splitlines(True)
247.1530 - # Use difflib to find their differences.
247.1531 - if optionflags & REPORT_UDIFF:
247.1532 - diff = difflib.unified_diff(want_lines, got_lines, n=2)
247.1533 - diff = list(diff)[2:] # strip the diff header
247.1534 - kind = 'unified diff with -expected +actual'
247.1535 - elif optionflags & REPORT_CDIFF:
247.1536 - diff = difflib.context_diff(want_lines, got_lines, n=2)
247.1537 - diff = list(diff)[2:] # strip the diff header
247.1538 - kind = 'context diff with expected followed by actual'
247.1539 - elif optionflags & REPORT_NDIFF:
247.1540 - engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
247.1541 - diff = list(engine.compare(want_lines, got_lines))
247.1542 - kind = 'ndiff with -expected +actual'
247.1543 - else:
247.1544 - assert 0, 'Bad diff option'
247.1545 - # Remove trailing whitespace on diff output.
247.1546 - diff = [line.rstrip() + '\n' for line in diff]
247.1547 - return 'Differences (%s):\n' % kind + _indent(''.join(diff))
247.1548 -
247.1549 - # If we're not using diff, then simply list the expected
247.1550 - # output followed by the actual output.
247.1551 - if want and got:
247.1552 - return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
247.1553 - elif want:
247.1554 - return 'Expected:\n%sGot nothing\n' % _indent(want)
247.1555 - elif got:
247.1556 - return 'Expected nothing\nGot:\n%s' % _indent(got)
247.1557 - else:
247.1558 - return 'Expected nothing\nGot nothing\n'
247.1559 -
247.1560 -class DocTestFailure(Exception):
247.1561 - """A DocTest example has failed in debugging mode.
247.1562 -
247.1563 - The exception instance has variables:
247.1564 -
247.1565 - - test: the DocTest object being run
247.1566 -
247.1567 - - example: the Example object that failed
247.1568 -
247.1569 - - got: the actual output
247.1570 - """
247.1571 - def __init__(self, test, example, got):
247.1572 - self.test = test
247.1573 - self.example = example
247.1574 - self.got = got
247.1575 -
247.1576 - def __str__(self):
247.1577 - return str(self.test)
247.1578 -
247.1579 -class UnexpectedException(Exception):
247.1580 - """A DocTest example has encountered an unexpected exception
247.1581 -
247.1582 - The exception instance has variables:
247.1583 -
247.1584 - - test: the DocTest object being run
247.1585 -
247.1586 - - example: the Example object that failed
247.1587 -
247.1588 - - exc_info: the exception info
247.1589 - """
247.1590 - def __init__(self, test, example, exc_info):
247.1591 - self.test = test
247.1592 - self.example = example
247.1593 - self.exc_info = exc_info
247.1594 -
247.1595 - def __str__(self):
247.1596 - return str(self.test)
247.1597 -
247.1598 -class DebugRunner(DocTestRunner):
247.1599 - r"""Run doc tests but raise an exception as soon as there is a failure.
247.1600 -
247.1601 - If an unexpected exception occurs, an UnexpectedException is raised.
247.1602 - It contains the test, the example, and the original exception:
247.1603 -
247.1604 - >>> runner = DebugRunner(verbose=False)
247.1605 - >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
247.1606 - ... {}, 'foo', 'foo.py', 0)
247.1607 - >>> try:
247.1608 - ... runner.run(test)
247.1609 - ... except UnexpectedException, failure:
247.1610 - ... pass
247.1611 -
247.1612 - >>> failure.test is test
247.1613 - True
247.1614 -
247.1615 - >>> failure.example.want
247.1616 - '42\n'
247.1617 -
247.1618 - >>> exc_info = failure.exc_info
247.1619 - >>> raise exc_info[0], exc_info[1], exc_info[2]
247.1620 - Traceback (most recent call last):
247.1621 - ...
247.1622 - KeyError
247.1623 -
247.1624 - We wrap the original exception to give the calling application
247.1625 - access to the test and example information.
247.1626 -
247.1627 - If the output doesn't match, then a DocTestFailure is raised:
247.1628 -
247.1629 - >>> test = DocTestParser().get_doctest('''
247.1630 - ... >>> x = 1
247.1631 - ... >>> x
247.1632 - ... 2
247.1633 - ... ''', {}, 'foo', 'foo.py', 0)
247.1634 -
247.1635 - >>> try:
247.1636 - ... runner.run(test)
247.1637 - ... except DocTestFailure, failure:
247.1638 - ... pass
247.1639 -
247.1640 - DocTestFailure objects provide access to the test:
247.1641 -
247.1642 - >>> failure.test is test
247.1643 - True
247.1644 -
247.1645 - As well as to the example:
247.1646 -
247.1647 - >>> failure.example.want
247.1648 - '2\n'
247.1649 -
247.1650 - and the actual output:
247.1651 -
247.1652 - >>> failure.got
247.1653 - '1\n'
247.1654 -
247.1655 - If a failure or error occurs, the globals are left intact:
247.1656 -
247.1657 - >>> del test.globs['__builtins__']
247.1658 - >>> test.globs
247.1659 - {'x': 1}
247.1660 -
247.1661 - >>> test = DocTestParser().get_doctest('''
247.1662 - ... >>> x = 2
247.1663 - ... >>> raise KeyError
247.1664 - ... ''', {}, 'foo', 'foo.py', 0)
247.1665 -
247.1666 - >>> runner.run(test)
247.1667 - Traceback (most recent call last):
247.1668 - ...
247.1669 - UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
247.1670 -
247.1671 - >>> del test.globs['__builtins__']
247.1672 - >>> test.globs
247.1673 - {'x': 2}
247.1674 -
247.1675 - But the globals are cleared if there is no error:
247.1676 -
247.1677 - >>> test = DocTestParser().get_doctest('''
247.1678 - ... >>> x = 2
247.1679 - ... ''', {}, 'foo', 'foo.py', 0)
247.1680 -
247.1681 - >>> runner.run(test)
247.1682 - (0, 1)
247.1683 -
247.1684 - >>> test.globs
247.1685 - {}
247.1686 -
247.1687 - """
247.1688 -
247.1689 - def run(self, test, compileflags=None, out=None, clear_globs=True):
247.1690 - r = DocTestRunner.run(self, test, compileflags, out, False)
247.1691 - if clear_globs:
247.1692 - test.globs.clear()
247.1693 - return r
247.1694 -
247.1695 - def report_unexpected_exception(self, out, test, example, exc_info):
247.1696 - raise UnexpectedException(test, example, exc_info)
247.1697 -
247.1698 - def report_failure(self, out, test, example, got):
247.1699 - raise DocTestFailure(test, example, got)
247.1700 -
247.1701 -######################################################################
247.1702 -## 6. Test Functions
247.1703 -######################################################################
247.1704 -# These should be backwards compatible.
247.1705 -
247.1706 -# For backward compatibility, a global instance of a DocTestRunner
247.1707 -# class, updated by testmod.
247.1708 -master = None
247.1709 -
247.1710 -def testmod(m=None, name=None, globs=None, verbose=None,
247.1711 - report=True, optionflags=0, extraglobs=None,
247.1712 - raise_on_error=False, exclude_empty=False):
247.1713 - """m=None, name=None, globs=None, verbose=None, report=True,
247.1714 - optionflags=0, extraglobs=None, raise_on_error=False,
247.1715 - exclude_empty=False
247.1716 -
247.1717 - Test examples in docstrings in functions and classes reachable
247.1718 - from module m (or the current module if m is not supplied), starting
247.1719 - with m.__doc__.
247.1720 -
247.1721 - Also test examples reachable from dict m.__test__ if it exists and is
247.1722 - not None. m.__test__ maps names to functions, classes and strings;
247.1723 - function and class docstrings are tested even if the name is private;
247.1724 - strings are tested directly, as if they were docstrings.
247.1725 -
247.1726 - Return (#failures, #tests).
247.1727 -
247.1728 - See doctest.__doc__ for an overview.
247.1729 -
247.1730 - Optional keyword arg "name" gives the name of the module; by default
247.1731 - use m.__name__.
247.1732 -
247.1733 - Optional keyword arg "globs" gives a dict to be used as the globals
247.1734 - when executing examples; by default, use m.__dict__. A copy of this
247.1735 - dict is actually used for each docstring, so that each docstring's
247.1736 - examples start with a clean slate.
247.1737 -
247.1738 - Optional keyword arg "extraglobs" gives a dictionary that should be
247.1739 - merged into the globals that are used to execute examples. By
247.1740 - default, no extra globals are used. This is new in 2.4.
247.1741 -
247.1742 - Optional keyword arg "verbose" prints lots of stuff if true, prints
247.1743 - only failures if false; by default, it's true iff "-v" is in sys.argv.
247.1744 -
247.1745 - Optional keyword arg "report" prints a summary at the end when true,
247.1746 - else prints nothing at the end. In verbose mode, the summary is
247.1747 - detailed, else very brief (in fact, empty if all tests passed).
247.1748 -
247.1749 - Optional keyword arg "optionflags" or's together module constants,
247.1750 - and defaults to 0. This is new in 2.3. Possible values (see the
247.1751 - docs for details):
247.1752 -
247.1753 - DONT_ACCEPT_TRUE_FOR_1
247.1754 - DONT_ACCEPT_BLANKLINE
247.1755 - NORMALIZE_WHITESPACE
247.1756 - ELLIPSIS
247.1757 - SKIP
247.1758 - IGNORE_EXCEPTION_DETAIL
247.1759 - REPORT_UDIFF
247.1760 - REPORT_CDIFF
247.1761 - REPORT_NDIFF
247.1762 - REPORT_ONLY_FIRST_FAILURE
247.1763 -
247.1764 - Optional keyword arg "raise_on_error" raises an exception on the
247.1765 - first unexpected exception or failure. This allows failures to be
247.1766 - post-mortem debugged.
247.1767 -
247.1768 - Advanced tomfoolery: testmod runs methods of a local instance of
247.1769 - class doctest.Tester, then merges the results into (or creates)
247.1770 - global Tester instance doctest.master. Methods of doctest.master
247.1771 - can be called directly too, if you want to do something unusual.
247.1772 - Passing report=0 to testmod is especially useful then, to delay
247.1773 - displaying a summary. Invoke doctest.master.summarize(verbose)
247.1774 - when you're done fiddling.
247.1775 - """
247.1776 - global master
247.1777 -
247.1778 - # If no module was given, then use __main__.
247.1779 - if m is None:
247.1780 - # DWA - m will still be None if this wasn't invoked from the command
247.1781 - # line, in which case the following TypeError is about as good an error
247.1782 - # as we should expect
247.1783 - m = sys.modules.get('__main__')
247.1784 -
247.1785 - # Check that we were actually given a module.
247.1786 - if not inspect.ismodule(m):
247.1787 - raise TypeError("testmod: module required; %r" % (m,))
247.1788 -
247.1789 - # If no name was given, then use the module's name.
247.1790 - if name is None:
247.1791 - name = m.__name__
247.1792 -
247.1793 - # Find, parse, and run all tests in the given module.
247.1794 - finder = DocTestFinder(exclude_empty=exclude_empty)
247.1795 -
247.1796 - if raise_on_error:
247.1797 - runner = DebugRunner(verbose=verbose, optionflags=optionflags)
247.1798 - else:
247.1799 - runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
247.1800 -
247.1801 - for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
247.1802 - runner.run(test)
247.1803 -
247.1804 - if report:
247.1805 - runner.summarize()
247.1806 -
247.1807 - if master is None:
247.1808 - master = runner
247.1809 - else:
247.1810 - master.merge(runner)
247.1811 -
247.1812 - return runner.failures, runner.tries
247.1813 -
247.1814 -def testfile(filename, module_relative=True, name=None, package=None,
247.1815 - globs=None, verbose=None, report=True, optionflags=0,
247.1816 - extraglobs=None, raise_on_error=False, parser=DocTestParser(),
247.1817 - encoding=None):
247.1818 - """
247.1819 - Test examples in the given file. Return (#failures, #tests).
247.1820 -
247.1821 - Optional keyword arg "module_relative" specifies how filenames
247.1822 - should be interpreted:
247.1823 -
247.1824 - - If "module_relative" is True (the default), then "filename"
247.1825 - specifies a module-relative path. By default, this path is
247.1826 - relative to the calling module's directory; but if the
247.1827 - "package" argument is specified, then it is relative to that
247.1828 - package. To ensure os-independence, "filename" should use
247.1829 - "/" characters to separate path segments, and should not
247.1830 - be an absolute path (i.e., it may not begin with "/").
247.1831 -
247.1832 - - If "module_relative" is False, then "filename" specifies an
247.1833 - os-specific path. The path may be absolute or relative (to
247.1834 - the current working directory).
247.1835 -
247.1836 - Optional keyword arg "name" gives the name of the test; by default
247.1837 - use the file's basename.
247.1838 -
247.1839 - Optional keyword argument "package" is a Python package or the
247.1840 - name of a Python package whose directory should be used as the
247.1841 - base directory for a module relative filename. If no package is
247.1842 - specified, then the calling module's directory is used as the base
247.1843 - directory for module relative filenames. It is an error to
247.1844 - specify "package" if "module_relative" is False.
247.1845 -
247.1846 - Optional keyword arg "globs" gives a dict to be used as the globals
247.1847 - when executing examples; by default, use {}. A copy of this dict
247.1848 - is actually used for each docstring, so that each docstring's
247.1849 - examples start with a clean slate.
247.1850 -
247.1851 - Optional keyword arg "extraglobs" gives a dictionary that should be
247.1852 - merged into the globals that are used to execute examples. By
247.1853 - default, no extra globals are used.
247.1854 -
247.1855 - Optional keyword arg "verbose" prints lots of stuff if true, prints
247.1856 - only failures if false; by default, it's true iff "-v" is in sys.argv.
247.1857 -
247.1858 - Optional keyword arg "report" prints a summary at the end when true,
247.1859 - else prints nothing at the end. In verbose mode, the summary is
247.1860 - detailed, else very brief (in fact, empty if all tests passed).
247.1861 -
247.1862 - Optional keyword arg "optionflags" or's together module constants,
247.1863 - and defaults to 0. Possible values (see the docs for details):
247.1864 -
247.1865 - DONT_ACCEPT_TRUE_FOR_1
247.1866 - DONT_ACCEPT_BLANKLINE
247.1867 - NORMALIZE_WHITESPACE
247.1868 - ELLIPSIS
247.1869 - SKIP
247.1870 - IGNORE_EXCEPTION_DETAIL
247.1871 - REPORT_UDIFF
247.1872 - REPORT_CDIFF
247.1873 - REPORT_NDIFF
247.1874 - REPORT_ONLY_FIRST_FAILURE
247.1875 -
247.1876 - Optional keyword arg "raise_on_error" raises an exception on the
247.1877 - first unexpected exception or failure. This allows failures to be
247.1878 - post-mortem debugged.
247.1879 -
247.1880 - Optional keyword arg "parser" specifies a DocTestParser (or
247.1881 - subclass) that should be used to extract tests from the files.
247.1882 -
247.1883 - Optional keyword arg "encoding" specifies an encoding that should
247.1884 - be used to convert the file to unicode.
247.1885 -
247.1886 - Advanced tomfoolery: testmod runs methods of a local instance of
247.1887 - class doctest.Tester, then merges the results into (or creates)
247.1888 - global Tester instance doctest.master. Methods of doctest.master
247.1889 - can be called directly too, if you want to do something unusual.
247.1890 - Passing report=0 to testmod is especially useful then, to delay
247.1891 - displaying a summary. Invoke doctest.master.summarize(verbose)
247.1892 - when you're done fiddling.
247.1893 - """
247.1894 - global master
247.1895 -
247.1896 - if package and not module_relative:
247.1897 - raise ValueError("Package may only be specified for module-"
247.1898 - "relative paths.")
247.1899 -
247.1900 - # Relativize the path
247.1901 - text, filename = _load_testfile(filename, package, module_relative)
247.1902 -
247.1903 - # If no name was given, then use the file's name.
247.1904 - if name is None:
247.1905 - name = os.path.basename(filename)
247.1906 -
247.1907 - # Assemble the globals.
247.1908 - if globs is None:
247.1909 - globs = {}
247.1910 - else:
247.1911 - globs = globs.copy()
247.1912 - if extraglobs is not None:
247.1913 - globs.update(extraglobs)
247.1914 -
247.1915 - if raise_on_error:
247.1916 - runner = DebugRunner(verbose=verbose, optionflags=optionflags)
247.1917 - else:
247.1918 - runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
247.1919 -
247.1920 - if encoding is not None:
247.1921 - text = text.decode(encoding)
247.1922 -
247.1923 - # Read the file, convert it to a test, and run it.
247.1924 - test = parser.get_doctest(text, globs, name, filename, 0)
247.1925 - runner.run(test)
247.1926 -
247.1927 - if report:
247.1928 - runner.summarize()
247.1929 -
247.1930 - if master is None:
247.1931 - master = runner
247.1932 - else:
247.1933 - master.merge(runner)
247.1934 -
247.1935 - return runner.failures, runner.tries
247.1936 -
247.1937 -def run_docstring_examples(f, globs, verbose=False, name="NoName",
247.1938 - compileflags=None, optionflags=0):
247.1939 - """
247.1940 - Test examples in the given object's docstring (`f`), using `globs`
247.1941 - as globals. Optional argument `name` is used in failure messages.
247.1942 - If the optional argument `verbose` is true, then generate output
247.1943 - even if there are no failures.
247.1944 -
247.1945 - `compileflags` gives the set of flags that should be used by the
247.1946 - Python compiler when running the examples. If not specified, then
247.1947 - it will default to the set of future-import flags that apply to
247.1948 - `globs`.
247.1949 -
247.1950 - Optional keyword arg `optionflags` specifies options for the
247.1951 - testing and output. See the documentation for `testmod` for more
247.1952 - information.
247.1953 - """
247.1954 - # Find, parse, and run all tests in the given module.
247.1955 - finder = DocTestFinder(verbose=verbose, recurse=False)
247.1956 - runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
247.1957 - for test in finder.find(f, name, globs=globs):
247.1958 - runner.run(test, compileflags=compileflags)
247.1959 -
247.1960 -######################################################################
247.1961 -## 7. Tester
247.1962 -######################################################################
247.1963 -# This is provided only for backwards compatibility. It's not
247.1964 -# actually used in any way.
247.1965 -
247.1966 -class Tester:
247.1967 - def __init__(self, mod=None, globs=None, verbose=None, optionflags=0):
247.1968 -
247.1969 - warnings.warn("class Tester is deprecated; "
247.1970 - "use class doctest.DocTestRunner instead",
247.1971 - DeprecationWarning, stacklevel=2)
247.1972 - if mod is None and globs is None:
247.1973 - raise TypeError("Tester.__init__: must specify mod or globs")
247.1974 - if mod is not None and not inspect.ismodule(mod):
247.1975 - raise TypeError("Tester.__init__: mod must be a module; %r" %
247.1976 - (mod,))
247.1977 - if globs is None:
247.1978 - globs = mod.__dict__
247.1979 - self.globs = globs
247.1980 -
247.1981 - self.verbose = verbose
247.1982 - self.optionflags = optionflags
247.1983 - self.testfinder = DocTestFinder()
247.1984 - self.testrunner = DocTestRunner(verbose=verbose,
247.1985 - optionflags=optionflags)
247.1986 -
247.1987 - def runstring(self, s, name):
247.1988 - test = DocTestParser().get_doctest(s, self.globs, name, None, None)
247.1989 - if self.verbose:
247.1990 - print "Running string", name
247.1991 - (f,t) = self.testrunner.run(test)
247.1992 - if self.verbose:
247.1993 - print f, "of", t, "examples failed in string", name
247.1994 - return (f,t)
247.1995 -
247.1996 - def rundoc(self, object, name=None, module=None):
247.1997 - f = t = 0
247.1998 - tests = self.testfinder.find(object, name, module=module,
247.1999 - globs=self.globs)
247.2000 - for test in tests:
247.2001 - (f2, t2) = self.testrunner.run(test)
247.2002 - (f,t) = (f+f2, t+t2)
247.2003 - return (f,t)
247.2004 -
247.2005 - def rundict(self, d, name, module=None):
247.2006 - import new
247.2007 - m = new.module(name)
247.2008 - m.__dict__.update(d)
247.2009 - if module is None:
247.2010 - module = False
247.2011 - return self.rundoc(m, name, module)
247.2012 -
247.2013 - def run__test__(self, d, name):
247.2014 - import new
247.2015 - m = new.module(name)
247.2016 - m.__test__ = d
247.2017 - return self.rundoc(m, name)
247.2018 -
247.2019 - def summarize(self, verbose=None):
247.2020 - return self.testrunner.summarize(verbose)
247.2021 -
247.2022 - def merge(self, other):
247.2023 - self.testrunner.merge(other.testrunner)
247.2024 -
247.2025 -######################################################################
247.2026 -## 8. Unittest Support
247.2027 -######################################################################
247.2028 -
247.2029 -_unittest_reportflags = 0
247.2030 -
247.2031 -def set_unittest_reportflags(flags):
247.2032 - """Sets the unittest option flags.
247.2033 -
247.2034 - The old flag is returned so that a runner could restore the old
247.2035 - value if it wished to:
247.2036 -
247.2037 - >>> import doctest
247.2038 - >>> old = doctest._unittest_reportflags
247.2039 - >>> doctest.set_unittest_reportflags(REPORT_NDIFF |
247.2040 - ... REPORT_ONLY_FIRST_FAILURE) == old
247.2041 - True
247.2042 -
247.2043 - >>> doctest._unittest_reportflags == (REPORT_NDIFF |
247.2044 - ... REPORT_ONLY_FIRST_FAILURE)
247.2045 - True
247.2046 -
247.2047 - Only reporting flags can be set:
247.2048 -
247.2049 - >>> doctest.set_unittest_reportflags(ELLIPSIS)
247.2050 - Traceback (most recent call last):
247.2051 - ...
247.2052 - ValueError: ('Only reporting flags allowed', 8)
247.2053 -
247.2054 - >>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF |
247.2055 - ... REPORT_ONLY_FIRST_FAILURE)
247.2056 - True
247.2057 - """
247.2058 - global _unittest_reportflags
247.2059 -
247.2060 - if (flags & REPORTING_FLAGS) != flags:
247.2061 - raise ValueError("Only reporting flags allowed", flags)
247.2062 - old = _unittest_reportflags
247.2063 - _unittest_reportflags = flags
247.2064 - return old
247.2065 -
247.2066 -
247.2067 -class DocTestCase(unittest.TestCase):
247.2068 -
247.2069 - def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
247.2070 - checker=None):
247.2071 -
247.2072 - unittest.TestCase.__init__(self)
247.2073 - self._dt_optionflags = optionflags
247.2074 - self._dt_checker = checker
247.2075 - self._dt_test = test
247.2076 - self._dt_setUp = setUp
247.2077 - self._dt_tearDown = tearDown
247.2078 -
247.2079 - def setUp(self):
247.2080 - test = self._dt_test
247.2081 -
247.2082 - if self._dt_setUp is not None:
247.2083 - self._dt_setUp(test)
247.2084 -
247.2085 - def tearDown(self):
247.2086 - test = self._dt_test
247.2087 -
247.2088 - if self._dt_tearDown is not None:
247.2089 - self._dt_tearDown(test)
247.2090 -
247.2091 - test.globs.clear()
247.2092 -
247.2093 - def runTest(self):
247.2094 - test = self._dt_test
247.2095 - old = sys.stdout
247.2096 - new = StringIO()
247.2097 - optionflags = self._dt_optionflags
247.2098 -
247.2099 - if not (optionflags & REPORTING_FLAGS):
247.2100 - # The option flags don't include any reporting flags,
247.2101 - # so add the default reporting flags
247.2102 - optionflags |= _unittest_reportflags
247.2103 -
247.2104 - runner = DocTestRunner(optionflags=optionflags,
247.2105 - checker=self._dt_checker, verbose=False)
247.2106 -
247.2107 - try:
247.2108 - runner.DIVIDER = "-"*70
247.2109 - failures, tries = runner.run(
247.2110 - test, out=new.write, clear_globs=False)
247.2111 - finally:
247.2112 - sys.stdout = old
247.2113 -
247.2114 - if failures:
247.2115 - raise self.failureException(self.format_failure(new.getvalue()))
247.2116 -
247.2117 - def format_failure(self, err):
247.2118 - test = self._dt_test
247.2119 - if test.lineno is None:
247.2120 - lineno = 'unknown line number'
247.2121 - else:
247.2122 - lineno = '%s' % test.lineno
247.2123 - lname = '.'.join(test.name.split('.')[-1:])
247.2124 - return ('Failed doctest test for %s\n'
247.2125 - ' File "%s", line %s, in %s\n\n%s'
247.2126 - % (test.name, test.filename, lineno, lname, err)
247.2127 - )
247.2128 -
247.2129 - def debug(self):
247.2130 - r"""Run the test case without results and without catching exceptions
247.2131 -
247.2132 - The unit test framework includes a debug method on test cases
247.2133 - and test suites to support post-mortem debugging. The test code
247.2134 - is run in such a way that errors are not caught. This way a
247.2135 - caller can catch the errors and initiate post-mortem debugging.
247.2136 -
247.2137 - The DocTestCase provides a debug method that raises
247.2138 - UnexpectedException errors if there is an unexepcted
247.2139 - exception:
247.2140 -
247.2141 - >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
247.2142 - ... {}, 'foo', 'foo.py', 0)
247.2143 - >>> case = DocTestCase(test)
247.2144 - >>> try:
247.2145 - ... case.debug()
247.2146 - ... except UnexpectedException, failure:
247.2147 - ... pass
247.2148 -
247.2149 - The UnexpectedException contains the test, the example, and
247.2150 - the original exception:
247.2151 -
247.2152 - >>> failure.test is test
247.2153 - True
247.2154 -
247.2155 - >>> failure.example.want
247.2156 - '42\n'
247.2157 -
247.2158 - >>> exc_info = failure.exc_info
247.2159 - >>> raise exc_info[0], exc_info[1], exc_info[2]
247.2160 - Traceback (most recent call last):
247.2161 - ...
247.2162 - KeyError
247.2163 -
247.2164 - If the output doesn't match, then a DocTestFailure is raised:
247.2165 -
247.2166 - >>> test = DocTestParser().get_doctest('''
247.2167 - ... >>> x = 1
247.2168 - ... >>> x
247.2169 - ... 2
247.2170 - ... ''', {}, 'foo', 'foo.py', 0)
247.2171 - >>> case = DocTestCase(test)
247.2172 -
247.2173 - >>> try:
247.2174 - ... case.debug()
247.2175 - ... except DocTestFailure, failure:
247.2176 - ... pass
247.2177 -
247.2178 - DocTestFailure objects provide access to the test:
247.2179 -
247.2180 - >>> failure.test is test
247.2181 - True
247.2182 -
247.2183 - As well as to the example:
247.2184 -
247.2185 - >>> failure.example.want
247.2186 - '2\n'
247.2187 -
247.2188 - and the actual output:
247.2189 -
247.2190 - >>> failure.got
247.2191 - '1\n'
247.2192 -
247.2193 - """
247.2194 -
247.2195 - self.setUp()
247.2196 - runner = DebugRunner(optionflags=self._dt_optionflags,
247.2197 - checker=self._dt_checker, verbose=False)
247.2198 - runner.run(self._dt_test)
247.2199 - self.tearDown()
247.2200 -
247.2201 - def id(self):
247.2202 - return self._dt_test.name
247.2203 -
247.2204 - def __repr__(self):
247.2205 - name = self._dt_test.name.split('.')
247.2206 - return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
247.2207 -
247.2208 - __str__ = __repr__
247.2209 -
247.2210 - def shortDescription(self):
247.2211 - return "Doctest: " + self._dt_test.name
247.2212 -
247.2213 -def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
247.2214 - **options):
247.2215 - """
247.2216 - Convert doctest tests for a module to a unittest test suite.
247.2217 -
247.2218 - This converts each documentation string in a module that
247.2219 - contains doctest tests to a unittest test case. If any of the
247.2220 - tests in a doc string fail, then the test case fails. An exception
247.2221 - is raised showing the name of the file containing the test and a
247.2222 - (sometimes approximate) line number.
247.2223 -
247.2224 - The `module` argument provides the module to be tested. The argument
247.2225 - can be either a module or a module name.
247.2226 -
247.2227 - If no argument is given, the calling module is used.
247.2228 -
247.2229 - A number of options may be provided as keyword arguments:
247.2230 -
247.2231 - setUp
247.2232 - A set-up function. This is called before running the
247.2233 - tests in each file. The setUp function will be passed a DocTest
247.2234 - object. The setUp function can access the test globals as the
247.2235 - globs attribute of the test passed.
247.2236 -
247.2237 - tearDown
247.2238 - A tear-down function. This is called after running the
247.2239 - tests in each file. The tearDown function will be passed a DocTest
247.2240 - object. The tearDown function can access the test globals as the
247.2241 - globs attribute of the test passed.
247.2242 -
247.2243 - globs
247.2244 - A dictionary containing initial global variables for the tests.
247.2245 -
247.2246 - optionflags
247.2247 - A set of doctest option flags expressed as an integer.
247.2248 - """
247.2249 -
247.2250 - if test_finder is None:
247.2251 - test_finder = DocTestFinder()
247.2252 -
247.2253 - module = _normalize_module(module)
247.2254 - tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
247.2255 - if globs is None:
247.2256 - globs = module.__dict__
247.2257 - if not tests:
247.2258 - # Why do we want to do this? Because it reveals a bug that might
247.2259 - # otherwise be hidden.
247.2260 - raise ValueError(module, "has no tests")
247.2261 -
247.2262 - tests.sort()
247.2263 - suite = unittest.TestSuite()
247.2264 - for test in tests:
247.2265 - if len(test.examples) == 0:
247.2266 - continue
247.2267 - if not test.filename:
247.2268 - filename = module.__file__
247.2269 - if filename[-4:] in (".pyc", ".pyo"):
247.2270 - filename = filename[:-1]
247.2271 - test.filename = filename
247.2272 - suite.addTest(DocTestCase(test, **options))
247.2273 -
247.2274 - return suite
247.2275 -
247.2276 -class DocFileCase(DocTestCase):
247.2277 -
247.2278 - def id(self):
247.2279 - return '_'.join(self._dt_test.name.split('.'))
247.2280 -
247.2281 - def __repr__(self):
247.2282 - return self._dt_test.filename
247.2283 - __str__ = __repr__
247.2284 -
247.2285 - def format_failure(self, err):
247.2286 - return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
247.2287 - % (self._dt_test.name, self._dt_test.filename, err)
247.2288 - )
247.2289 -
247.2290 -def DocFileTest(path, module_relative=True, package=None,
247.2291 - globs=None, parser=DocTestParser(),
247.2292 - encoding=None, **options):
247.2293 - if globs is None:
247.2294 - globs = {}
247.2295 - else:
247.2296 - globs = globs.copy()
247.2297 -
247.2298 - if package and not module_relative:
247.2299 - raise ValueError("Package may only be specified for module-"
247.2300 - "relative paths.")
247.2301 -
247.2302 - # Relativize the path.
247.2303 - doc, path = _load_testfile(path, package, module_relative)
247.2304 -
247.2305 - if "__file__" not in globs:
247.2306 - globs["__file__"] = path
247.2307 -
247.2308 - # Find the file and read it.
247.2309 - name = os.path.basename(path)
247.2310 -
247.2311 - # If an encoding is specified, use it to convert the file to unicode
247.2312 - if encoding is not None:
247.2313 - doc = doc.decode(encoding)
247.2314 -
247.2315 - # Convert it to a test, and wrap it in a DocFileCase.
247.2316 - test = parser.get_doctest(doc, globs, name, path, 0)
247.2317 - return DocFileCase(test, **options)
247.2318 -
247.2319 -def DocFileSuite(*paths, **kw):
247.2320 - """A unittest suite for one or more doctest files.
247.2321 -
247.2322 - The path to each doctest file is given as a string; the
247.2323 - interpretation of that string depends on the keyword argument
247.2324 - "module_relative".
247.2325 -
247.2326 - A number of options may be provided as keyword arguments:
247.2327 -
247.2328 - module_relative
247.2329 - If "module_relative" is True, then the given file paths are
247.2330 - interpreted as os-independent module-relative paths. By
247.2331 - default, these paths are relative to the calling module's
247.2332 - directory; but if the "package" argument is specified, then
247.2333 - they are relative to that package. To ensure os-independence,
247.2334 - "filename" should use "/" characters to separate path
247.2335 - segments, and may not be an absolute path (i.e., it may not
247.2336 - begin with "/").
247.2337 -
247.2338 - If "module_relative" is False, then the given file paths are
247.2339 - interpreted as os-specific paths. These paths may be absolute
247.2340 - or relative (to the current working directory).
247.2341 -
247.2342 - package
247.2343 - A Python package or the name of a Python package whose directory
247.2344 - should be used as the base directory for module relative paths.
247.2345 - If "package" is not specified, then the calling module's
247.2346 - directory is used as the base directory for module relative
247.2347 - filenames. It is an error to specify "package" if
247.2348 - "module_relative" is False.
247.2349 -
247.2350 - setUp
247.2351 - A set-up function. This is called before running the
247.2352 - tests in each file. The setUp function will be passed a DocTest
247.2353 - object. The setUp function can access the test globals as the
247.2354 - globs attribute of the test passed.
247.2355 -
247.2356 - tearDown
247.2357 - A tear-down function. This is called after running the
247.2358 - tests in each file. The tearDown function will be passed a DocTest
247.2359 - object. The tearDown function can access the test globals as the
247.2360 - globs attribute of the test passed.
247.2361 -
247.2362 - globs
247.2363 - A dictionary containing initial global variables for the tests.
247.2364 -
247.2365 - optionflags
247.2366 - A set of doctest option flags expressed as an integer.
247.2367 -
247.2368 - parser
247.2369 - A DocTestParser (or subclass) that should be used to extract
247.2370 - tests from the files.
247.2371 -
247.2372 - encoding
247.2373 - An encoding that will be used to convert the files to unicode.
247.2374 - """
247.2375 - suite = unittest.TestSuite()
247.2376 -
247.2377 - # We do this here so that _normalize_module is called at the right
247.2378 - # level. If it were called in DocFileTest, then this function
247.2379 - # would be the caller and we might guess the package incorrectly.
247.2380 - if kw.get('module_relative', True):
247.2381 - kw['package'] = _normalize_module(kw.get('package'))
247.2382 -
247.2383 - for path in paths:
247.2384 - suite.addTest(DocFileTest(path, **kw))
247.2385 -
247.2386 - return suite
247.2387 -
247.2388 -######################################################################
247.2389 -## 9. Debugging Support
247.2390 -######################################################################
247.2391 -
247.2392 -def script_from_examples(s):
247.2393 - r"""Extract script from text with examples.
247.2394 -
247.2395 - Converts text with examples to a Python script. Example input is
247.2396 - converted to regular code. Example output and all other words
247.2397 - are converted to comments:
247.2398 -
247.2399 - >>> text = '''
247.2400 - ... Here are examples of simple math.
247.2401 - ...
247.2402 - ... Python has super accurate integer addition
247.2403 - ...
247.2404 - ... >>> 2 + 2
247.2405 - ... 5
247.2406 - ...
247.2407 - ... And very friendly error messages:
247.2408 - ...
247.2409 - ... >>> 1/0
247.2410 - ... To Infinity
247.2411 - ... And
247.2412 - ... Beyond
247.2413 - ...
247.2414 - ... You can use logic if you want:
247.2415 - ...
247.2416 - ... >>> if 0:
247.2417 - ... ... blah
247.2418 - ... ... blah
247.2419 - ... ...
247.2420 - ...
247.2421 - ... Ho hum
247.2422 - ... '''
247.2423 -
247.2424 - >>> print script_from_examples(text)
247.2425 - # Here are examples of simple math.
247.2426 - #
247.2427 - # Python has super accurate integer addition
247.2428 - #
247.2429 - 2 + 2
247.2430 - # Expected:
247.2431 - ## 5
247.2432 - #
247.2433 - # And very friendly error messages:
247.2434 - #
247.2435 - 1/0
247.2436 - # Expected:
247.2437 - ## To Infinity
247.2438 - ## And
247.2439 - ## Beyond
247.2440 - #
247.2441 - # You can use logic if you want:
247.2442 - #
247.2443 - if 0:
247.2444 - blah
247.2445 - blah
247.2446 - #
247.2447 - # Ho hum
247.2448 - <BLANKLINE>
247.2449 - """
247.2450 - output = []
247.2451 - for piece in DocTestParser().parse(s):
247.2452 - if isinstance(piece, Example):
247.2453 - # Add the example's source code (strip trailing NL)
247.2454 - output.append(piece.source[:-1])
247.2455 - # Add the expected output:
247.2456 - want = piece.want
247.2457 - if want:
247.2458 - output.append('# Expected:')
247.2459 - output += ['## '+l for l in want.split('\n')[:-1]]
247.2460 - else:
247.2461 - # Add non-example text.
247.2462 - output += [_comment_line(l)
247.2463 - for l in piece.split('\n')[:-1]]
247.2464 -
247.2465 - # Trim junk on both ends.
247.2466 - while output and output[-1] == '#':
247.2467 - output.pop()
247.2468 - while output and output[0] == '#':
247.2469 - output.pop(0)
247.2470 - # Combine the output, and return it.
247.2471 - # Add a courtesy newline to prevent exec from choking (see bug #1172785)
247.2472 - return '\n'.join(output) + '\n'
247.2473 -
247.2474 -def testsource(module, name):
247.2475 - """Extract the test sources from a doctest docstring as a script.
247.2476 -
247.2477 - Provide the module (or dotted name of the module) containing the
247.2478 - test to be debugged and the name (within the module) of the object
247.2479 - with the doc string with tests to be debugged.
247.2480 - """
247.2481 - module = _normalize_module(module)
247.2482 - tests = DocTestFinder().find(module)
247.2483 - test = [t for t in tests if t.name == name]
247.2484 - if not test:
247.2485 - raise ValueError(name, "not found in tests")
247.2486 - test = test[0]
247.2487 - testsrc = script_from_examples(test.docstring)
247.2488 - return testsrc
247.2489 -
247.2490 -def debug_src(src, pm=False, globs=None):
247.2491 - """Debug a single doctest docstring, in argument `src`'"""
247.2492 - testsrc = script_from_examples(src)
247.2493 - debug_script(testsrc, pm, globs)
247.2494 -
247.2495 -def debug_script(src, pm=False, globs=None):
247.2496 - "Debug a test script. `src` is the script, as a string."
247.2497 - import pdb
247.2498 -
247.2499 - # Note that tempfile.NameTemporaryFile() cannot be used. As the
247.2500 - # docs say, a file so created cannot be opened by name a second time
247.2501 - # on modern Windows boxes, and execfile() needs to open it.
247.2502 - srcfilename = tempfile.mktemp(".py", "doctestdebug")
247.2503 - f = open(srcfilename, 'w')
247.2504 - f.write(src)
247.2505 - f.close()
247.2506 -
247.2507 - try:
247.2508 - if globs:
247.2509 - globs = globs.copy()
247.2510 - else:
247.2511 - globs = {}
247.2512 -
247.2513 - if pm:
247.2514 - try:
247.2515 - execfile(srcfilename, globs, globs)
247.2516 - except:
247.2517 - print sys.exc_info()[1]
247.2518 - pdb.post_mortem(sys.exc_info()[2])
247.2519 - else:
247.2520 - # Note that %r is vital here. '%s' instead can, e.g., cause
247.2521 - # backslashes to get treated as metacharacters on Windows.
247.2522 - pdb.run("execfile(%r)" % srcfilename, globs, globs)
247.2523 -
247.2524 - finally:
247.2525 - os.remove(srcfilename)
247.2526 -
247.2527 -def debug(module, name, pm=False):
247.2528 - """Debug a single doctest docstring.
247.2529 -
247.2530 - Provide the module (or dotted name of the module) containing the
247.2531 - test to be debugged and the name (within the module) of the object
247.2532 - with the docstring with tests to be debugged.
247.2533 - """
247.2534 - module = _normalize_module(module)
247.2535 - testsrc = testsource(module, name)
247.2536 - debug_script(testsrc, pm, module.__dict__)
247.2537 -
247.2538 -######################################################################
247.2539 -## 10. Example Usage
247.2540 -######################################################################
247.2541 -class _TestClass:
247.2542 - """
247.2543 - A pointless class, for sanity-checking of docstring testing.
247.2544 -
247.2545 - Methods:
247.2546 - square()
247.2547 - get()
247.2548 -
247.2549 - >>> _TestClass(13).get() + _TestClass(-12).get()
247.2550 - 1
247.2551 - >>> hex(_TestClass(13).square().get())
247.2552 - '0xa9'
247.2553 - """
247.2554 -
247.2555 - def __init__(self, val):
247.2556 - """val -> _TestClass object with associated value val.
247.2557 -
247.2558 - >>> t = _TestClass(123)
247.2559 - >>> print t.get()
247.2560 - 123
247.2561 - """
247.2562 -
247.2563 - self.val = val
247.2564 -
247.2565 - def square(self):
247.2566 - """square() -> square TestClass's associated value
247.2567 -
247.2568 - >>> _TestClass(13).square().get()
247.2569 - 169
247.2570 - """
247.2571 -
247.2572 - self.val = self.val ** 2
247.2573 - return self
247.2574 -
247.2575 - def get(self):
247.2576 - """get() -> return TestClass's associated value.
247.2577 -
247.2578 - >>> x = _TestClass(-42)
247.2579 - >>> print x.get()
247.2580 - -42
247.2581 - """
247.2582 -
247.2583 - return self.val
247.2584 -
247.2585 -__test__ = {"_TestClass": _TestClass,
247.2586 - "string": r"""
247.2587 - Example of a string object, searched as-is.
247.2588 - >>> x = 1; y = 2
247.2589 - >>> x + y, x * y
247.2590 - (3, 2)
247.2591 - """,
247.2592 -
247.2593 - "bool-int equivalence": r"""
247.2594 - In 2.2, boolean expressions displayed
247.2595 - 0 or 1. By default, we still accept
247.2596 - them. This can be disabled by passing
247.2597 - DONT_ACCEPT_TRUE_FOR_1 to the new
247.2598 - optionflags argument.
247.2599 - >>> 4 == 4
247.2600 - 1
247.2601 - >>> 4 == 4
247.2602 - True
247.2603 - >>> 4 > 4
247.2604 - 0
247.2605 - >>> 4 > 4
247.2606 - False
247.2607 - """,
247.2608 -
247.2609 - "blank lines": r"""
247.2610 - Blank lines can be marked with <BLANKLINE>:
247.2611 - >>> print 'foo\n\nbar\n'
247.2612 - foo
247.2613 - <BLANKLINE>
247.2614 - bar
247.2615 - <BLANKLINE>
247.2616 - """,
247.2617 -
247.2618 - "ellipsis": r"""
247.2619 - If the ellipsis flag is used, then '...' can be used to
247.2620 - elide substrings in the desired output:
247.2621 - >>> print range(1000) #doctest: +ELLIPSIS
247.2622 - [0, 1, 2, ..., 999]
247.2623 - """,
247.2624 -
247.2625 - "whitespace normalization": r"""
247.2626 - If the whitespace normalization flag is used, then
247.2627 - differences in whitespace are ignored.
247.2628 - >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
247.2629 - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
247.2630 - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
247.2631 - 27, 28, 29]
247.2632 - """,
247.2633 - }
247.2634 -
247.2635 -def _test():
247.2636 - r = unittest.TextTestRunner()
247.2637 - r.run(DocTestSuite())
247.2638 -
247.2639 -if __name__ == "__main__":
247.2640 - _test()
248.1 --- a/python.editor/test/unit/data/testfiles/doctest.py.indexed Sun Jan 04 13:11:53 2015 -0600
248.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
248.3 @@ -1,344 +0,0 @@
248.4 -
248.5 -
248.6 -Document 0
248.7 -Searchable Keys:
248.8 - class : DebugRunner
248.9 - class-ig : debugrunner
248.10 - extends : DocTestRunner
248.11 - in : doctest
248.12 - member : report_failure;F;;self,out,test,example,got;
248.13 - member : report_unexpected_exception;F;;self,out,test,example,exc_info;
248.14 - member : run;F;;self,test,compileflags,out,clear_globs;
248.15 -
248.16 -Not Searchable Keys:
248.17 -
248.18 -
248.19 -Document 1
248.20 -Searchable Keys:
248.21 - class : DocFileCase
248.22 - class-ig : docfilecase
248.23 - extends : DocTestCase
248.24 - in : doctest
248.25 - member : __repr__;F;|PRIVATE|;self;
248.26 - member : __str__;F;|PRIVATE|;self;
248.27 - member : format_failure;F;|PRIVATE|;self,err;
248.28 - member : id;F;|PRIVATE|;self;
248.29 -
248.30 -Not Searchable Keys:
248.31 - clzattrs : ;|PRIVATE|;
248.32 -
248.33 -
248.34 -Document 2
248.35 -Searchable Keys:
248.36 - class : DocTest
248.37 - class-ig : doctest
248.38 - in : doctest
248.39 - member : __cmp__;F;;self,other;
248.40 - member : __init__;c;|CONSTRUCTOR|;self,examples,globs,name,filename,lineno,docstring;
248.41 - member : __repr__;F;;self;
248.42 - member : docstring;D;;
248.43 - member : examples;D;;
248.44 - member : filename;D;;
248.45 - member : globs;D;;
248.46 - member : lineno;D;;
248.47 - member : name;D;;
248.48 -
248.49 -Not Searchable Keys:
248.50 -
248.51 -
248.52 -Document 3
248.53 -Searchable Keys:
248.54 - class : DocTestCase
248.55 - class-ig : doctestcase
248.56 - extends : TestCase
248.57 - in : doctest
248.58 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,test,optionflags,setUp,tearDown,checker;
248.59 - member : __repr__;F;|PRIVATE|;self;
248.60 - member : __str__;F;|PRIVATE|;self;
248.61 - member : _dt_checker;D;|PRIVATE|;
248.62 - member : _dt_optionflags;D;|PRIVATE|;
248.63 - member : _dt_setUp;D;|PRIVATE|;
248.64 - member : _dt_tearDown;D;|PRIVATE|;
248.65 - member : _dt_test;D;|PRIVATE|;
248.66 - member : debug;F;|PRIVATE|;self;
248.67 - member : format_failure;F;|PRIVATE|;self,err;
248.68 - member : id;F;|PRIVATE|;self;
248.69 - member : runTest;F;|PRIVATE|;self;
248.70 - member : setUp;F;|PRIVATE|;self;
248.71 - member : shortDescription;F;|PRIVATE|;self;
248.72 - member : tearDown;F;|PRIVATE|;self;
248.73 -
248.74 -Not Searchable Keys:
248.75 - clzattrs : ;|PRIVATE|;
248.76 -
248.77 -
248.78 -Document 4
248.79 -Searchable Keys:
248.80 - class : DocTestFailure
248.81 - class-ig : doctestfailure
248.82 - extends : Exception
248.83 - in : doctest
248.84 - member : __init__;c;|CONSTRUCTOR|;self,test,example,got;
248.85 - member : __str__;F;;self;
248.86 - member : example;D;;
248.87 - member : got;D;;
248.88 - member : test;D;;
248.89 -
248.90 -Not Searchable Keys:
248.91 -
248.92 -
248.93 -Document 5
248.94 -Searchable Keys:
248.95 - class : DocTestFinder
248.96 - class-ig : doctestfinder
248.97 - in : doctest
248.98 - member : __init__;c;|CONSTRUCTOR|;self,verbose,parser,recurse,exclude_empty;
248.99 - member : _exclude_empty;D;|PRIVATE|;
248.100 - member : _find;F;|PRIVATE|;self,tests,obj,name,module,source_lines,globs,seen;
248.101 - member : _find_lineno;F;|PRIVATE|;self,obj,source_lines;
248.102 - member : _from_module;F;|PRIVATE|;self,module,object;
248.103 - member : _get_test;F;|PRIVATE|;self,obj,name,module,globs,source_lines;
248.104 - member : _parser;D;|PRIVATE|;
248.105 - member : _recurse;D;|PRIVATE|;
248.106 - member : _verbose;D;|PRIVATE|;
248.107 - member : find;F;;self,obj,name,module,globs,extraglobs;
248.108 -
248.109 -Not Searchable Keys:
248.110 -
248.111 -
248.112 -Document 6
248.113 -Searchable Keys:
248.114 - class : DocTestParser
248.115 - class-ig : doctestparser
248.116 - in : doctest
248.117 - member : _EXAMPLE_RE;D;|PRIVATE|;
248.118 - member : _EXCEPTION_RE;D;|PRIVATE|;
248.119 - member : _INDENT_RE;D;|PRIVATE|;
248.120 - member : _IS_BLANK_OR_COMMENT;D;|PRIVATE|;
248.121 - member : _OPTION_DIRECTIVE_RE;D;|PRIVATE|;
248.122 - member : _check_prefix;F;|PRIVATE|;self,lines,prefix,name,lineno;
248.123 - member : _check_prompt_blank;F;|PRIVATE|;self,lines,indent,name,lineno;
248.124 - member : _find_options;F;|PRIVATE|;self,source,name,lineno;
248.125 - member : _min_indent;F;|PRIVATE|;self,s;
248.126 - member : _parse_example;F;|PRIVATE|;self,m,name,lineno;
248.127 - member : get_doctest;F;;self,string,globs,name,filename,lineno;
248.128 - member : get_examples;F;;self,string,name;
248.129 - member : parse;F;;self,string,name;
248.130 -
248.131 -Not Searchable Keys:
248.132 -
248.133 -
248.134 -Document 7
248.135 -Searchable Keys:
248.136 - class : DocTestRunner
248.137 - class-ig : doctestrunner
248.138 - in : doctest
248.139 - member : DIVIDER;D;;
248.140 - member : __LINECACHE_FILENAME_RE;D;|PRIVATE|;
248.141 - member : __init__;c;|CONSTRUCTOR|;self,checker,verbose,optionflags;
248.142 - member : __patched_linecache_getlines;F;|PRIVATE|;self,filename,module_globals;
248.143 - member : __record_outcome;F;|PRIVATE|;self,test,f,t;
248.144 - member : __run;F;|PRIVATE|;self,test,compileflags,out;
248.145 - member : _checker;D;|PRIVATE|;
248.146 - member : _failure_header;F;|PRIVATE|;self,test,example;
248.147 - member : _fakeout;D;|PRIVATE|;
248.148 - member : _name2ft;D;|PRIVATE|;
248.149 - member : _verbose;D;|PRIVATE|;
248.150 - member : debugger;D;;
248.151 - member : failures;D;;
248.152 - member : merge;F;;self,other;
248.153 - member : optionflags;D;;
248.154 - member : original_optionflags;D;;
248.155 - member : report_failure;F;;self,out,test,example,got;
248.156 - member : report_start;F;;self,out,test,example;
248.157 - member : report_success;F;;self,out,test,example,got;
248.158 - member : report_unexpected_exception;F;;self,out,test,example,exc_info;
248.159 - member : run;F;;self,test,compileflags,out,clear_globs;
248.160 - member : save_linecache_getlines;D;;
248.161 - member : summarize;F;;self,verbose;
248.162 - member : test;D;;
248.163 - member : tries;D;;
248.164 -
248.165 -Not Searchable Keys:
248.166 -
248.167 -
248.168 -Document 8
248.169 -Searchable Keys:
248.170 - class : Example
248.171 - class-ig : example
248.172 - in : doctest
248.173 - member : __init__;c;|CONSTRUCTOR|;self,source,want,exc_msg,lineno,indent,options;
248.174 - member : exc_msg;D;;
248.175 - member : indent;D;;
248.176 - member : lineno;D;;
248.177 - member : options;D;;
248.178 - member : source;D;;
248.179 - member : want;D;;
248.180 -
248.181 -Not Searchable Keys:
248.182 -
248.183 -
248.184 -Document 9
248.185 -Searchable Keys:
248.186 - class : OutputChecker
248.187 - class-ig : outputchecker
248.188 - in : doctest
248.189 - member : _do_a_fancy_diff;F;|PRIVATE|;self,want,got,optionflags;
248.190 - member : check_output;F;;self,want,got,optionflags;
248.191 - member : output_difference;F;;self,example,got,optionflags;
248.192 -
248.193 -Not Searchable Keys:
248.194 -
248.195 -
248.196 -Document 10
248.197 -Searchable Keys:
248.198 - class : Tester
248.199 - class-ig : tester
248.200 - in : doctest
248.201 - member : __init__;c;|CONSTRUCTOR|;self,mod,globs,verbose,optionflags;
248.202 - member : globs;D;;
248.203 - member : merge;F;;self,other;
248.204 - member : optionflags;D;;
248.205 - member : run__test__;F;;self,d,name;
248.206 - member : rundict;F;;self,d,name,module;
248.207 - member : rundoc;F;;self,object,name,module;
248.208 - member : runstring;F;;self,s,name;
248.209 - member : summarize;F;;self,verbose;
248.210 - member : testfinder;D;;
248.211 - member : testrunner;D;;
248.212 - member : verbose;D;;
248.213 -
248.214 -Not Searchable Keys:
248.215 -
248.216 -
248.217 -Document 11
248.218 -Searchable Keys:
248.219 - class : UnexpectedException
248.220 - class-ig : unexpectedexception
248.221 - extends : Exception
248.222 - in : doctest
248.223 - member : __init__;c;|CONSTRUCTOR|;self,test,example,exc_info;
248.224 - member : __str__;F;;self;
248.225 - member : example;D;;
248.226 - member : exc_info;D;;
248.227 - member : test;D;;
248.228 -
248.229 -Not Searchable Keys:
248.230 -
248.231 -
248.232 -Document 12
248.233 -Searchable Keys:
248.234 - class : _OutputRedirectingPdb
248.235 - class-ig : _outputredirectingpdb
248.236 - extends : Pdb
248.237 - in : doctest
248.238 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,out;
248.239 - member : __out;D;|PRIVATE|;
248.240 - member : trace_dispatch;F;|PRIVATE|;self,args;
248.241 -
248.242 -Not Searchable Keys:
248.243 - clzattrs : ;|PRIVATE|;
248.244 -
248.245 -
248.246 -Document 13
248.247 -Searchable Keys:
248.248 - class : _SpoofOut
248.249 - class-ig : _spoofout
248.250 - extends : StringIO
248.251 - in : doctest
248.252 - member : getvalue;F;|PRIVATE|;self;
248.253 - member : truncate;F;|PRIVATE|;self,size;
248.254 -
248.255 -Not Searchable Keys:
248.256 - clzattrs : ;|PRIVATE|;
248.257 -
248.258 -
248.259 -Document 14
248.260 -Searchable Keys:
248.261 - class : _TestClass
248.262 - class-ig : _testclass
248.263 - in : doctest
248.264 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,val;
248.265 - member : get;F;|PRIVATE|;self;
248.266 - member : square;F;|PRIVATE|;self;
248.267 - member : val;D;;
248.268 -
248.269 -Not Searchable Keys:
248.270 - clzattrs : ;|PRIVATE|;
248.271 -
248.272 -
248.273 -Document 15
248.274 -Searchable Keys:
248.275 - item : BLANKLINE_MARKER;D;|PRIVATE|;
248.276 - item : COMPARISON_FLAGS;D;;
248.277 - item : DONT_ACCEPT_BLANKLINE;D;;
248.278 - item : DONT_ACCEPT_TRUE_FOR_1;D;;
248.279 - item : DebugRunner;C;;
248.280 - item : DocFileCase;C;|PRIVATE|;
248.281 - item : DocFileSuite;F;;paths,kw;
248.282 - item : DocFileTest;F;|PRIVATE|;path,module_relative,package,globs,parser,encoding,options;
248.283 - item : DocTest;C;;
248.284 - item : DocTestCase;C;|PRIVATE|;
248.285 - item : DocTestFailure;C;;
248.286 - item : DocTestFinder;C;;
248.287 - item : DocTestParser;C;;
248.288 - item : DocTestRunner;C;;
248.289 - item : DocTestSuite;F;;module,globs,extraglobs,test_finder,options;
248.290 - item : ELLIPSIS;D;;
248.291 - item : ELLIPSIS_MARKER;D;|PRIVATE|;
248.292 - item : Example;C;;
248.293 - item : IGNORE_EXCEPTION_DETAIL;D;;
248.294 - item : NORMALIZE_WHITESPACE;D;;
248.295 - item : OPTIONFLAGS_BY_NAME;D;|PRIVATE|;
248.296 - item : OutputChecker;C;;
248.297 - item : REPORTING_FLAGS;D;;
248.298 - item : REPORT_CDIFF;D;;
248.299 - item : REPORT_NDIFF;D;;
248.300 - item : REPORT_ONLY_FIRST_FAILURE;D;;
248.301 - item : REPORT_UDIFF;D;;
248.302 - item : SKIP;D;;
248.303 - item : StringIO;I;|PRIVATE|;
248.304 - item : Tester;C;;
248.305 - item : UnexpectedException;C;;
248.306 - item : _OutputRedirectingPdb;C;|PRIVATE|;
248.307 - item : _SpoofOut;C;|PRIVATE|;
248.308 - item : _TestClass;C;|PRIVATE|;
248.309 - item : __all__;D;;
248.310 - item : __docformat__;D;|PRIVATE|;
248.311 - item : __future__;I;|PRIVATE|;
248.312 - item : __test__;D;|PRIVATE|;
248.313 - item : _comment_line;F;|PRIVATE|;line;
248.314 - item : _ellipsis_match;F;|PRIVATE|;want,got;
248.315 - item : _exception_traceback;F;|PRIVATE|;exc_info;
248.316 - item : _extract_future_flags;F;|PRIVATE|;globs;
248.317 - item : _indent;F;|PRIVATE|;s,indent;
248.318 - item : _load_testfile;F;|PRIVATE|;filename,package,module_relative;
248.319 - item : _module_relative_path;F;|PRIVATE|;module,path;
248.320 - item : _normalize_module;F;|PRIVATE|;module,depth;
248.321 - item : _test;F;|PRIVATE|;;
248.322 - item : _unittest_reportflags;D;|PRIVATE|;
248.323 - item : debug;F;;module,name,pm;
248.324 - item : debug_script;F;|PRIVATE|;src,pm,globs;
248.325 - item : debug_src;F;;src,pm,globs;
248.326 - item : difflib;I;|PRIVATE|;
248.327 - item : inspect;I;|PRIVATE|;
248.328 - item : linecache;I;|PRIVATE|;
248.329 - item : master;D;|PRIVATE|;
248.330 - item : os;I;|PRIVATE|;
248.331 - item : pdb;I;|PRIVATE|;
248.332 - item : re;I;|PRIVATE|;
248.333 - item : register_optionflag;F;;name;
248.334 - item : run_docstring_examples;F;;f,globs,verbose,name,compileflags,optionflags;
248.335 - item : script_from_examples;F;;s;
248.336 - item : set_unittest_reportflags;F;;flags;
248.337 - item : sys;I;|PRIVATE|;
248.338 - item : tempfile;I;|PRIVATE|;
248.339 - item : testfile;F;;filename,module_relative,name,package,globs,verbose,report,optionflags,extraglobs,raise_on_error,parser,encoding;
248.340 - item : testmod;F;;m,name,globs,verbose,report,optionflags,extraglobs,raise_on_error,exclude_empty;
248.341 - item : testsource;F;;module,name;
248.342 - item : traceback;I;|PRIVATE|;
248.343 - item : unittest;I;|PRIVATE|;
248.344 - item : warnings;I;|PRIVATE|;
248.345 - module : doctest
248.346 -
248.347 -Not Searchable Keys:
249.1 --- a/python.editor/test/unit/data/testfiles/empty.py Sun Jan 04 13:11:53 2015 -0600
249.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
249.3 @@ -1,5 +0,0 @@
249.4 -#! /usr/bin/python
249.5 -
249.6 -print "Hello World!"
249.7 -
249.8 -
250.1 --- a/python.editor/test/unit/data/testfiles/empty.py.folds Sun Jan 04 13:11:53 2015 -0600
250.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
250.3 @@ -1,6 +0,0 @@
250.4 - #! /usr/bin/python
250.5 -
250.6 - print "Hello World!"
250.7 -
250.8 -
250.9 -
251.1 --- a/python.editor/test/unit/data/testfiles/empty.py.nameoffsets Sun Jan 04 13:11:53 2015 -0600
251.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
251.3 @@ -1,6 +0,0 @@
251.4 -
251.5 -#! /usr/bin/python
251.6 -
251.7 -print "Hello World!"
251.8 -
251.9 -
252.1 --- a/python.editor/test/unit/data/testfiles/empty.py.offsets Sun Jan 04 13:11:53 2015 -0600
252.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
252.3 @@ -1,6 +0,0 @@
252.4 -
252.5 -#! /usr/bin/python
252.6 -
252.7 -<Module><Print>print <Str>"Hello World!"</Str></Print></Module>
252.8 -
252.9 -
253.1 --- a/python.editor/test/unit/data/testfiles/empty.py.semantic Sun Jan 04 13:11:53 2015 -0600
253.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
253.3 @@ -1,5 +0,0 @@
253.4 -#! /usr/bin/python
253.5 -
253.6 -print "Hello World!"
253.7 -
253.8 -
254.1 --- a/python.editor/test/unit/data/testfiles/empty.py.testKeywords.completion Sun Jan 04 13:11:53 2015 -0600
254.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
254.3 @@ -1,1220 +0,0 @@
254.4 -Code completion result for source line:
254.5 -|print "Hello World!"
254.6 -(QueryType=COMPLETION, NameKind=PREFIX)
254.7 -------------------------------------
254.8 -CLASS A
254.9 -CLASS ABCMeta
254.10 -CLASS AEServer
254.11 -CLASS AEText
254.12 -CLASS ASTVisitor
254.13 -CLASS AbstractBasicAuthHandler
254.14 -CLASS AbstractClassCode
254.15 -CLASS AbstractCompileMode
254.16 -CLASS AbstractDigestAuthHandler
254.17 -CLASS AbstractFormatter
254.18 -CLASS AbstractFunctionCode
254.19 -CLASS AbstractHTTPHandler
254.20 -CLASS AbstractWriter
254.21 -CLASS Add
254.22 -CLASS And
254.23 -CLASS Application
254.24 -CLASS ArgumentError
254.25 -CLASS ArithmeticError
254.26 -CLASS ArithmeticError
254.27 -CLASS Array
254.28 -CLASS ArrayInstance
254.29 -CLASS AssAttr
254.30 -CLASS AssList
254.31 -CLASS AssName
254.32 -CLASS AssTuple
254.33 -CLASS Assert
254.34 -CLASS AssertionError
254.35 -CLASS AssertionError
254.36 -CLASS Assign
254.37 -CLASS AsyncResult
254.38 -CLASS Attr
254.39 -CLASS AttributeError
254.40 -CLASS AttributeError
254.41 -CLASS AttributeList
254.42 -CLASS AttributeMap
254.43 -CLASS Attributes
254.44 -CLASS AttributesImpl
254.45 -CLASS AttributesNS
254.46 -CLASS AttributesNSImpl
254.47 -CLASS AugAssign
254.48 -CLASS AugGetattr
254.49 -CLASS AugName
254.50 -CLASS AugSlice
254.51 -CLASS AugSubscript
254.52 -CLASS AuthenticationError
254.53 -CLASS AutoGILError
254.54 -CLASS B
254.55 -CLASS BCPPCompiler
254.56 -CLASS BCPTestCase
254.57 -CLASS BZ2Compressor
254.58 -CLASS BZ2Decompressor
254.59 -CLASS BZ2File
254.60 -CLASS Babyl
254.61 -CLASS BabylMailbox
254.62 -CLASS BabylMessage
254.63 -CLASS Backquote
254.64 -CLASS BadBoundaryPointsErr
254.65 -CLASS BadFutureParser
254.66 -CLASS BadOptionError
254.67 -CLASS BadStatusLine
254.68 -CLASS BadZipfile
254.69 -CLASS Balloon
254.70 -CLASS Bar
254.71 -CLASS BaseCGIHandler
254.72 -CLASS BaseCookie
254.73 -CLASS BaseException
254.74 -CLASS BaseException
254.75 -CLASS BaseHTTPRequestHandler
254.76 -CLASS BaseHandler
254.77 -CLASS BaseIncrementalParser
254.78 -CLASS BaseManager
254.79 -CLASS BaseProxy
254.80 -CLASS BaseRequestHandler
254.81 -CLASS BaseRotatingHandler
254.82 -CLASS BaseSet
254.83 -CLASS BasicModuleImporter
254.84 -CLASS BasicModuleLoader
254.85 -CLASS BastionClass
254.86 -CLASS Baz
254.87 -CLASS Bdb
254.88 -CLASS BdbQuit
254.89 -CLASS BigEndianStructure
254.90 -CLASS Binary
254.91 -CLASS Bitand
254.92 -CLASS Bitor
254.93 -CLASS Bitxor
254.94 -CLASS Block
254.95 -CLASS BlockFinder
254.96 -CLASS BlockingIOError
254.97 -CLASS Boolean
254.98 -CLASS BoundaryError
254.99 -CLASS BoundedSemaphore
254.100 -CLASS Break
254.101 -CLASS Breakpoint
254.102 -CLASS BsdDbShelf
254.103 -CLASS BufferTooShort
254.104 -CLASS BufferedIOBase
254.105 -CLASS BufferedRWPair
254.106 -CLASS BufferedRandom
254.107 -CLASS BufferedReader
254.108 -CLASS BufferedWriter
254.109 -CLASS BufferingFormatter
254.110 -CLASS BufferingHandler
254.111 -CLASS BuildPyTestCase
254.112 -CLASS BuildScriptsTestCase
254.113 -CLASS BuiltinImporter
254.114 -CLASS Bulkcopy
254.115 -CLASS ButtonBox
254.116 -CLASS BytesIO
254.117 -CLASS C
254.118 -CLASS CAB
254.119 -CLASS CCompiler
254.120 -CLASS CCompilerError
254.121 -CLASS CDATASection
254.122 -CLASS CDLL
254.123 -CLASS CGIHTTPRequestHandler
254.124 -CLASS CGIHandler
254.125 -CLASS CGIXMLRPCRequestHandler
254.126 -CLASS CacheFTPHandler
254.127 -CLASS CallFunc
254.128 -CLASS CalledProcessError
254.129 -CLASS CannotSendHeader
254.130 -CLASS CannotSendRequest
254.131 -CLASS Canonizer
254.132 -CLASS CharacterData
254.133 -CLASS Charset
254.134 -CLASS CharsetError
254.135 -CLASS CheckList
254.136 -CLASS Childless
254.137 -CLASS Chunk
254.138 -CLASS Clamped
254.139 -CLASS Class
254.140 -CLASS ClassCodeGenerator
254.141 -CLASS ClassScope
254.142 -CLASS Cmd
254.143 -CLASS CodeGenerator
254.144 -CLASS Codec
254.145 -CLASS CodecRegistryError
254.146 -CLASS ComboBox
254.147 -CLASS Command
254.148 -CLASS CommandCompiler
254.149 -CLASS Comment
254.150 -CLASS Compare
254.151 -CLASS Comparison
254.152 -CLASS Compile
254.153 -CLASS CompileError
254.154 -CLASS Completer
254.155 -CLASS Complex
254.156 -CLASS ComponentItem
254.157 -CLASS Condition
254.158 -CLASS ConfigParser
254.159 -CLASS Connection
254.160 -CLASS Const
254.161 -CLASS ContentGenerator
254.162 -CLASS ContentHandler
254.163 -CLASS Context
254.164 -CLASS Continue
254.165 -CLASS Control
254.166 -CLASS ControlsWindow
254.167 -CLASS ConversionError
254.168 -CLASS Cookie
254.169 -CLASS CookieError
254.170 -CLASS CookieJar
254.171 -CLASS CookiePolicy
254.172 -CLASS CoverageResults
254.173 -CLASS Cursor
254.174 -CLASS CygwinCCompiler
254.175 -CLASS D
254.176 -CLASS DOMBuilder
254.177 -CLASS DOMEntityResolver
254.178 -CLASS DOMError
254.179 -CLASS DOMEventStream
254.180 -CLASS DOMException
254.181 -CLASS DOMImplementation
254.182 -CLASS DOMInputSource
254.183 -CLASS DOMStringSizeErr
254.184 -CLASS DTDHandler
254.185 -CLASS Data
254.186 -CLASS Database
254.187 -CLASS DatagramHandler
254.188 -CLASS DatagramRequestHandler
254.189 -CLASS DateTime
254.190 -CLASS DbfilenameShelf
254.191 -CLASS DebugRunner
254.192 -CLASS DebuggingServer
254.193 -CLASS Decimal
254.194 -CLASS DecimalException
254.195 -CLASS DeclHandler
254.196 -CLASS DecodedGenerator
254.197 -CLASS Decorators
254.198 -CLASS DefaultCookiePolicy
254.199 -CLASS DefaultHandler
254.200 -CLASS Delegator
254.201 -CLASS DeprecationWarning
254.202 -CLASS DeprecationWarning
254.203 -CLASS Dialect
254.204 -CLASS Dialog
254.205 -CLASS DialogWindow
254.206 -CLASS Dict
254.207 -CLASS DictMixin
254.208 -CLASS DictReader
254.209 -CLASS DictWriter
254.210 -CLASS Differ
254.211 -CLASS DirList
254.212 -CLASS DirSelectBox
254.213 -CLASS DirSelectDialog
254.214 -CLASS DirTree
254.215 -CLASS Directory
254.216 -CLASS Discard
254.217 -CLASS Distribution
254.218 -CLASS DistributionMetadata
254.219 -CLASS DistributionTestCase
254.220 -CLASS DistutilsArgError
254.221 -CLASS DistutilsClassError
254.222 -CLASS DistutilsError
254.223 -CLASS DistutilsExecError
254.224 -CLASS DistutilsFileError
254.225 -CLASS DistutilsGetoptError
254.226 -CLASS DistutilsInternalError
254.227 -CLASS DistutilsModuleError
254.228 -CLASS DistutilsOptionError
254.229 -CLASS DistutilsPlatformError
254.230 -CLASS DistutilsSetupError
254.231 -CLASS DistutilsTemplateError
254.232 -CLASS Div
254.233 -CLASS DivisionByZero
254.234 -CLASS Doc
254.235 -CLASS DocCGIXMLRPCRequestHandler
254.236 -CLASS DocTest
254.237 -CLASS DocTestFailure
254.238 -CLASS DocTestFinder
254.239 -CLASS DocTestParser
254.240 -CLASS DocTestRunner
254.241 -CLASS DocXMLRPCRequestHandler
254.242 -CLASS DocXMLRPCServer
254.243 -CLASS Document
254.244 -CLASS DocumentFragment
254.245 -CLASS DocumentHandler
254.246 -CLASS DocumentType
254.247 -CLASS DomstringSizeErr
254.248 -CLASS DumbWriter
254.249 -CLASS DummyCommand
254.250 -CLASS DuplicateSectionError
254.251 -CLASS DynLoadSuffixImporter
254.252 -CLASS EMXCCompiler
254.253 -CLASS EOFError
254.254 -CLASS EOFError
254.255 -CLASS ESISDocHandler
254.256 -CLASS Element
254.257 -CLASS ElementInfo
254.258 -CLASS ElementTree
254.259 -CLASS Ellipsis
254.260 -CLASS Empty
254.261 -CLASS EmptyNode
254.262 -CLASS EndOfBlock
254.263 -CLASS Entity
254.264 -CLASS EntityResolver
254.265 -CLASS Enum
254.266 -CLASS EnvironmentError
254.267 -CLASS EnvironmentError
254.268 -CLASS Error
254.269 -CLASS ErrorDuringImport
254.270 -CLASS ErrorHandler
254.271 -CLASS ErrorPrinter
254.272 -CLASS ErrorRaiser
254.273 -CLASS Event
254.274 -CLASS EventBroadcaster
254.275 -CLASS EventException
254.276 -CLASS ExFileSelectBox
254.277 -CLASS Example
254.278 -CLASS ExampleASTVisitor
254.279 -CLASS Exception
254.280 -CLASS Exception
254.281 -CLASS Exec
254.282 -CLASS ExitNow
254.283 -CLASS ExpatError
254.284 -CLASS ExpatParser
254.285 -CLASS Expression
254.286 -CLASS ExpressionCodeGenerator
254.287 -CLASS Extension
254.288 -CLASS F
254.289 -CLASS FTP
254.290 -CLASS FTPHandler
254.291 -CLASS Factory
254.292 -CLASS FancyGetopt
254.293 -CLASS FancyModuleLoader
254.294 -CLASS FancyURLopener
254.295 -CLASS Fault
254.296 -CLASS Feature
254.297 -CLASS FeedParser
254.298 -CLASS FieldStorage
254.299 -CLASS FileCookieJar
254.300 -CLASS FileEntry
254.301 -CLASS FileHandler
254.302 -CLASS FileIO
254.303 -CLASS FileInput
254.304 -CLASS FileList
254.305 -CLASS FileSelectBox
254.306 -CLASS FileWrapper
254.307 -CLASS Filter
254.308 -CLASS Filterer
254.309 -CLASS FingerHandler
254.310 -CLASS FirstHeaderLineIsContinuationD
254.311 -CLASS FloatingPointError
254.312 -CLASS FloatingPointError
254.313 -CLASS FloorDiv
254.314 -CLASS FlowGraph
254.315 -CLASS Folder
254.316 -CLASS Foo
254.317 -CLASS For
254.318 -CLASS ForkingMixIn
254.319 -CLASS ForkingTCPServer
254.320 -CLASS ForkingUDPServer
254.321 -CLASS Form
254.322 -CLASS FormContent
254.323 -CLASS FormContentDict
254.324 -CLASS Formatter
254.325 -CLASS Fraction
254.326 -CLASS From
254.327 -CLASS FtException
254.328 -CLASS Full
254.329 -CLASS FuncPtr
254.330 -CLASS Function
254.331 -CLASS FunctionCodeGenerator
254.332 -CLASS FunctionScope
254.333 -CLASS FunctionTestCase
254.334 -CLASS FutureParser
254.335 -CLASS FutureWarning
254.336 -CLASS FutureWarning
254.337 -CLASS GNUTranslations
254.338 -CLASS GenExpr
254.339 -CLASS GenExprFor
254.340 -CLASS GenExprIf
254.341 -CLASS GenExprInner
254.342 -CLASS GenExprScope
254.343 -CLASS Generator
254.344 -CLASS GeneratorExit
254.345 -CLASS GeneratorExit
254.346 -CLASS Getattr
254.347 -CLASS GetattrMagic
254.348 -CLASS GetoptError
254.349 -CLASS Global
254.350 -CLASS GopherError
254.351 -CLASS GopherHandler
254.352 -CLASS GridBag
254.353 -CLASS GzipFile
254.354 -CLASS HList
254.355 -CLASS HMAC
254.356 -CLASS HRESULT
254.357 -CLASS HTMLDoc
254.358 -CLASS HTMLParseError
254.359 -CLASS HTMLParser
254.360 -CLASS HTMLRepr
254.361 -CLASS HTTP
254.362 -CLASS HTTPBasicAuthHandler
254.363 -CLASS HTTPConnection
254.364 -CLASS HTTPCookieProcessor
254.365 -CLASS HTTPDefaultErrorHandler
254.366 -CLASS HTTPDigestAuthHandler
254.367 -CLASS HTTPError
254.368 -CLASS HTTPErrorProcessor
254.369 -CLASS HTTPException
254.370 -CLASS HTTPHandler
254.371 -CLASS HTTPPasswordMgr
254.372 -CLASS HTTPPasswordMgrWithDefaultReal
254.373 -CLASS HTTPRedirectHandler
254.374 -CLASS HTTPResponse
254.375 -CLASS HTTPSConnection
254.376 -CLASS HTTPSHandler
254.377 -CLASS HTTPServer
254.378 -CLASS Handler
254.379 -CLASS HandlerBase
254.380 -CLASS Header
254.381 -CLASS HeaderParseError
254.382 -CLASS HeaderParser
254.383 -CLASS Headers
254.384 -CLASS HelpFormatter
254.385 -CLASS Helper
254.386 -CLASS HierarchyRequestErr
254.387 -CLASS Hook
254.388 -CLASS Hooks
254.389 -CLASS HtmlDiff
254.390 -CLASS IC
254.391 -CLASS IMAP4
254.392 -CLASS IMAP4_SSL
254.393 -CLASS IMAP4_stream
254.394 -CLASS IOBase
254.395 -CLASS IOError
254.396 -CLASS IOError
254.397 -CLASS Identified
254.398 -CLASS If
254.399 -CLASS IfExp
254.400 -CLASS Ignore
254.401 -CLASS IllegalMonthError
254.402 -CLASS IllegalWeekdayError
254.403 -CLASS ImmutableSet
254.404 -CLASS ImpImporter
254.405 -CLASS ImpLoader
254.406 -CLASS Import
254.407 -CLASS ImportError
254.408 -CLASS ImportError
254.409 -CLASS ImportManager
254.410 -CLASS ImportWarning
254.411 -CLASS ImportWarning
254.412 -CLASS Importer
254.413 -CLASS ImproperConnectionState
254.414 -CLASS Incomplete
254.415 -CLASS IncompleteRead
254.416 -CLASS IncrementalDecoder
254.417 -CLASS IncrementalEncoder
254.418 -CLASS IncrementalNewlineDecoder
254.419 -CLASS IncrementalParser
254.420 -CLASS IndentedHelpFormatter
254.421 -CLASS IndexError
254.422 -CLASS IndexError
254.423 -CLASS IndexSizeErr
254.424 -CLASS Inexact
254.425 -CLASS IniParser
254.426 -CLASS InputOnly
254.427 -CLASS InputSource
254.428 -CLASS InsertionLoc
254.429 -CLASS InstallScriptsTestCase
254.430 -CLASS InstallTestCase
254.431 -CLASS Integral
254.432 -CLASS Interactive
254.433 -CLASS InteractiveCodeGenerator
254.434 -CLASS InteractiveConsole
254.435 -CLASS InteractiveInterpreter
254.436 -CLASS InterpFormContentDict
254.437 -CLASS InterpolationDepthError
254.438 -CLASS InterpolationError
254.439 -CLASS InterpolationSyntaxError
254.440 -CLASS IntlText
254.441 -CLASS IntlWritingCode
254.442 -CLASS InuseAttributeErr
254.443 -CLASS InvalidAccessErr
254.444 -CLASS InvalidCharacterErr
254.445 -CLASS InvalidModificationErr
254.446 -CLASS InvalidNodeTypeErr
254.447 -CLASS InvalidOperation
254.448 -CLASS InvalidStateErr
254.449 -CLASS InvalidURL
254.450 -CLASS Invert
254.451 -CLASS IsqlCmd
254.452 -CLASS IsqlExit
254.453 -CLASS IterableUserDict
254.454 -CLASS JSONDecoder
254.455 -CLASS JSONEncoder
254.456 -CLASS JavaSAXParser
254.457 -CLASS JoinableQueue
254.458 -CLASS JyDTDHandlerWrapper
254.459 -CLASS JyEntityResolverWrapper
254.460 -CLASS JyErrorHandlerWrapper
254.461 -CLASS JyInputSourceWrapper
254.462 -CLASS JythonCompiler
254.463 -CLASS JythonSignalHandler
254.464 -CLASS KeyError
254.465 -CLASS KeyError
254.466 -CLASS KeyboardInterrupt
254.467 -CLASS KeyboardInterrupt
254.468 -CLASS Keyword
254.469 -CLASS LOBTestCase
254.470 -CLASS LWPCookieJar
254.471 -CLASS LabelEntry
254.472 -CLASS LabelFrame
254.473 -CLASS Lambda
254.474 -CLASS LambdaScope
254.475 -CLASS LargeZipFile
254.476 -CLASS LeftShift
254.477 -CLASS LexicalHandler
254.478 -CLASS LexicalXMLGenerator
254.479 -CLASS LibError
254.480 -CLASS LibraryLoader
254.481 -CLASS LineAddrTable
254.482 -CLASS LinkError
254.483 -CLASS List
254.484 -CLASS ListComp
254.485 -CLASS ListCompFor
254.486 -CLASS ListCompIf
254.487 -CLASS ListNoteBook
254.488 -CLASS Listener
254.489 -CLASS LittleEndianStructure
254.490 -CLASS LoadError
254.491 -CLASS LocalNameFinder
254.492 -CLASS Location
254.493 -CLASS Locator
254.494 -CLASS Lock
254.495 -CLASS Log
254.496 -CLASS LogRecord
254.497 -CLASS Logger
254.498 -CLASS LoggingSilencer
254.499 -CLASS Logical
254.500 -CLASS LookupError
254.501 -CLASS LookupError
254.502 -CLASS LooseVersion
254.503 -CLASS MH
254.504 -CLASS MHMailbox
254.505 -CLASS MHMessage
254.506 -CLASS MIMEApplication
254.507 -CLASS MIMEAudio
254.508 -CLASS MIMEBase
254.509 -CLASS MIMEImage
254.510 -CLASS MIMEMessage
254.511 -CLASS MIMEMultipart
254.512 -CLASS MIMENonMultipart
254.513 -CLASS MIMEText
254.514 -CLASS MMDF
254.515 -CLASS MMDFMessage
254.516 -CLASS MSVCCompiler
254.517 -CLASS MWerksCompiler
254.518 -CLASS MacroExpander
254.519 -CLASS Mailbox
254.520 -CLASS Maildir
254.521 -CLASS MaildirMessage
254.522 -CLASS MailmanProxy
254.523 -CLASS MalformedHeaderDefect
254.524 -CLASS Manager
254.525 -CLASS Marshaller
254.526 -CLASS MemoryError
254.527 -CLASS MemoryError
254.528 -CLASS MemoryHandler
254.529 -CLASS Message
254.530 -CLASS MessageDefect
254.531 -CLASS MessageError
254.532 -CLASS MessageParseError
254.533 -CLASS MetadataTestCase
254.534 -CLASS Meter
254.535 -CLASS MimeWriter
254.536 -CLASS Mingw32CCompiler
254.537 -CLASS MiniApplication
254.538 -CLASS MiniFieldStorage
254.539 -CLASS MisplacedEnvelopeHeaderDefect
254.540 -CLASS MissingSectionHeaderError
254.541 -CLASS MmdfMailbox
254.542 -CLASS Mod
254.543 -CLASS Model
254.544 -CLASS Module
254.545 -CLASS ModuleCodeGenerator
254.546 -CLASS ModuleFinder
254.547 -CLASS ModuleImporter
254.548 -CLASS ModuleLoader
254.549 -CLASS ModuleScanner
254.550 -CLASS ModuleScope
254.551 -CLASS MozillaCookieJar
254.552 -CLASS Mul
254.553 -CLASS MultiCall
254.554 -CLASS MultiCallIterator
254.555 -CLASS MultiFile
254.556 -CLASS MultipartConversionError
254.557 -CLASS MultipartInvariantViolationDef
254.558 -CLASS MutableString
254.559 -CLASS MyClass
254.560 -CLASS MyTest
254.561 -CLASS NNTP
254.562 -CLASS NNTPDataError
254.563 -CLASS NNTPPermanentError
254.564 -CLASS NNTPProtocolError
254.565 -CLASS NNTPReplyError
254.566 -CLASS NNTPTemporaryError
254.567 -CLASS NProperty
254.568 -CLASS NTEventLogHandler
254.569 -CLASS NULL
254.570 -CLASS Name
254.571 -CLASS NameError
254.572 -CLASS NameError
254.573 -CLASS NamedNodeMap
254.574 -CLASS NamespaceErr
254.575 -CLASS NannyNag
254.576 -CLASS NestedScopeMixin
254.577 -CLASS Netrc
254.578 -CLASS NetrcParseError
254.579 -CLASS NewStyle
254.580 -CLASS NoBoundaryInMultipartDefect
254.581 -CLASS NoDataAllowedErr
254.582 -CLASS NoModificationAllowedErr
254.583 -CLASS NoOpMetaClass
254.584 -CLASS NoOptionError
254.585 -CLASS NoSectionError
254.586 -CLASS Node
254.587 -CLASS NodeFilter
254.588 -CLASS NodeTransformer
254.589 -CLASS NodeVisitor
254.590 -CLASS Not
254.591 -CLASS NotANumber
254.592 -CLASS NotConnected
254.593 -CLASS NotFoundErr
254.594 -CLASS NotImplementedError
254.595 -CLASS NotImplementedError
254.596 -CLASS NotSupportedErr
254.597 -CLASS Notation
254.598 -CLASS NoteBook
254.599 -CLASS NullFormatter
254.600 -CLASS NullImporter
254.601 -CLASS NullTranslations
254.602 -CLASS NullWriter
254.603 -CLASS Number
254.604 -CLASS OSError
254.605 -CLASS OSError
254.606 -CLASS OSSAudioError
254.607 -CLASS ObjectSpecifier
254.608 -CLASS OleDLL
254.609 -CLASS OpFinder
254.610 -CLASS OpenerDirector
254.611 -CLASS OptParseError
254.612 -CLASS Option
254.613 -CLASS OptionConflictError
254.614 -CLASS OptionContainer
254.615 -CLASS OptionDummy
254.616 -CLASS OptionError
254.617 -CLASS OptionGroup
254.618 -CLASS OptionMenu
254.619 -CLASS OptionParser
254.620 -CLASS OptionValueError
254.621 -CLASS Or
254.622 -CLASS OracleSPTest
254.623 -CLASS Ordinal
254.624 -CLASS OutputChecker
254.625 -CLASS Overflow
254.626 -CLASS OverflowError
254.627 -CLASS OverflowError
254.628 -CLASS POP3
254.629 -CLASS POP3_SSL
254.630 -CLASS Packer
254.631 -CLASS PanedWindow
254.632 -CLASS Panel
254.633 -CLASS Parser
254.634 -CLASS ParserBase
254.635 -CLASS ParserError
254.636 -CLASS ParsingError
254.637 -CLASS Pass
254.638 -CLASS Pattern
254.639 -CLASS Pdb
254.640 -CLASS PendingDeprecationWarning
254.641 -CLASS PendingDeprecationWarning
254.642 -CLASS PickleError
254.643 -CLASS Pickler
254.644 -CLASS PicklingError
254.645 -CLASS PlaceHolder
254.646 -CLASS Popen
254.647 -CLASS Popen3
254.648 -CLASS Popen4
254.649 -CLASS PopupMenu
254.650 -CLASS PortableUnixMailbox
254.651 -CLASS Power
254.652 -CLASS PreprocessError
254.653 -CLASS PrettyPrinter
254.654 -CLASS Print
254.655 -CLASS Printnl
254.656 -CLASS Process
254.657 -CLASS ProcessingInstruction
254.658 -CLASS Profile
254.659 -CLASS ProgressBar
254.660 -CLASS Prompt
254.661 -CLASS ProtocolError
254.662 -CLASS ProxyBasicAuthHandler
254.663 -CLASS ProxyDigestAuthHandler
254.664 -CLASS ProxyHandler
254.665 -CLASS PullDOM
254.666 -CLASS PureProxy
254.667 -CLASS PyCompileError
254.668 -CLASS PyDLL
254.669 -CLASS PyDialog
254.670 -CLASS PyFlowGraph
254.671 -CLASS PyHKEY
254.672 -CLASS PyZipFile
254.673 -CLASS QDPoint
254.674 -CLASS QDRectangle
254.675 -CLASS QName
254.676 -CLASS Queue
254.677 -CLASS RExec
254.678 -CLASS RGBColor
254.679 -CLASS RLock
254.680 -CLASS RadioButtonGroup
254.681 -CLASS Raise
254.682 -CLASS Random
254.683 -CLASS Range
254.684 -CLASS RangeException
254.685 -CLASS Rational
254.686 -CLASS RawIOBase
254.687 -CLASS RawTurtle
254.688 -CLASS ReadOnlySequentialNamedNodeMap
254.689 -CLASS Real
254.690 -CLASS Record
254.691 -CLASS ReferenceError
254.692 -CLASS ReferenceError
254.693 -CLASS Repr
254.694 -CLASS Request
254.695 -CLASS ResponseError
254.696 -CLASS ResponseNotReady
254.697 -CLASS ResultSet
254.698 -CLASS ResultSetRow
254.699 -CLASS Return
254.700 -CLASS RightShift
254.701 -CLASS RobotFileParser
254.702 -CLASS RootLogger
254.703 -CLASS RotatingFileHandler
254.704 -CLASS Rounded
254.705 -CLASS Row
254.706 -CLASS RuntimeError
254.707 -CLASS RuntimeError
254.708 -CLASS RuntimeWarning
254.709 -CLASS RuntimeWarning
254.710 -CLASS SAX2DOM
254.711 -CLASS SAXException
254.712 -CLASS SAXNotRecognizedException
254.713 -CLASS SAXNotSupportedException
254.714 -CLASS SAXParseException
254.715 -CLASS SAXReaderNotAvailable
254.716 -CLASS SGMLParseError
254.717 -CLASS SGMLParser
254.718 -CLASS SMTP
254.719 -CLASS SMTPAuthenticationError
254.720 -CLASS SMTPConnectError
254.721 -CLASS SMTPDataError
254.722 -CLASS SMTPException
254.723 -CLASS SMTPHandler
254.724 -CLASS SMTPHeloError
254.725 -CLASS SMTPRecipientsRefused
254.726 -CLASS SMTPResponseException
254.727 -CLASS SMTPSenderRefused
254.728 -CLASS SMTPServer
254.729 -CLASS SMTPServerDisconnected
254.730 -CLASS SQLServerSPTest
254.731 -CLASS SQLTestCase
254.732 -CLASS SSLError
254.733 -CLASS SSLSocket
254.734 -CLASS ST
254.735 -CLASS SafeConfigParser
254.736 -CLASS SafeTransport
254.737 -CLASS Schema
254.738 -CLASS Scope
254.739 -CLASS Screen
254.740 -CLASS ScrolledCavas
254.741 -CLASS ScrolledText
254.742 -CLASS ScrolledWindow
254.743 -CLASS Select
254.744 -CLASS Semaphore
254.745 -CLASS SequenceMatcher
254.746 -CLASS SerialCookie
254.747 -CLASS Server
254.748 -CLASS ServerHTMLDoc
254.749 -CLASS ServerProxy
254.750 -CLASS Set
254.751 -CLASS SgmlopParser
254.752 -CLASS Shape
254.753 -CLASS Shelf
254.754 -CLASS SimpleCookie
254.755 -CLASS SimpleHTTPRequestHandler
254.756 -CLASS SimpleHandler
254.757 -CLASS SimpleLocator
254.758 -CLASS SimpleXMLRPCDispatcher
254.759 -CLASS SimpleXMLRPCRequestHandler
254.760 -CLASS SimpleXMLRPCServer
254.761 -CLASS Slice
254.762 -CLASS Sliceobj
254.763 -CLASS SlowParser
254.764 -CLASS SmartCookie
254.765 -CLASS Sniffer
254.766 -CLASS SocketHandler
254.767 -CLASS SocketType
254.768 -CLASS Stack
254.769 -CLASS StackDepthTracker
254.770 -CLASS StandardError
254.771 -CLASS StandardError
254.772 -CLASS StartBoundaryNotFoundDefect
254.773 -CLASS Stats
254.774 -CLASS StdButtonBox
254.775 -CLASS Stmt
254.776 -CLASS StopIteration
254.777 -CLASS StopIteration
254.778 -CLASS StopTokenizing
254.779 -CLASS Strange
254.780 -CLASS StreamConverter
254.781 -CLASS StreamHandler
254.782 -CLASS StreamReader
254.783 -CLASS StreamRequestHandler
254.784 -CLASS StreamWriter
254.785 -CLASS StrictVersion
254.786 -CLASS StringIO
254.787 -CLASS Struct
254.788 -CLASS Structure
254.789 -CLASS StyledText
254.790 -CLASS Sub
254.791 -CLASS SubPattern
254.792 -CLASS Subnormal
254.793 -CLASS Subscript
254.794 -CLASS SummaryInformation
254.795 -CLASS Super
254.796 -CLASS SuperSuper
254.797 -CLASS SvFormContentDict
254.798 -CLASS Symbol
254.799 -CLASS SymbolTable
254.800 -CLASS SymbolVisitor
254.801 -CLASS SyncManager
254.802 -CLASS SyntaxErr
254.803 -CLASS SyntaxError
254.804 -CLASS SyntaxError
254.805 -CLASS SyntaxErrorChecker
254.806 -CLASS SyntaxWarning
254.807 -CLASS SyntaxWarning
254.808 -CLASS SysLogHandler
254.809 -CLASS SystemError
254.810 -CLASS SystemError
254.811 -CLASS SystemExit
254.812 -CLASS SystemExit
254.813 -CLASS SystemRandom
254.814 -CLASS TCPServer
254.815 -CLASS TList
254.816 -CLASS TalkTo
254.817 -CLASS TarError
254.818 -CLASS TarFile
254.819 -CLASS TarInfo
254.820 -CLASS Telnet
254.821 -CLASS TempdirManager
254.822 -CLASS Template
254.823 -CLASS Test
254.824 -CLASS TestCase
254.825 -CLASS TestClass
254.826 -CLASS TestCrispinTorture
254.827 -CLASS TestDistribution
254.828 -CLASS TestLoader
254.829 -CLASS TestResult
254.830 -CLASS TestSuite
254.831 -CLASS TestThread
254.832 -CLASS TestXMLParser
254.833 -CLASS Testcase
254.834 -CLASS Tester
254.835 -CLASS Text
254.836 -CLASS TextDoc
254.837 -CLASS TextFile
254.838 -CLASS TextIOBase
254.839 -CLASS TextIOWrapper
254.840 -CLASS TextRepr
254.841 -CLASS TextTestRunner
254.842 -CLASS TextWrapper
254.843 -CLASS Textbox
254.844 -CLASS Thread
254.845 -CLASS ThreadingMixIn
254.846 -CLASS ThreadingTCPServer
254.847 -CLASS ThreadingUDPServer
254.848 -CLASS ThreadingUnixDatagramServer
254.849 -CLASS ThreadingUnixStreamServer
254.850 -CLASS TimedRotatingFileHandler
254.851 -CLASS Timer
254.852 -CLASS TitledHelpFormatter
254.853 -CLASS Tix
254.854 -CLASS Tk
254.855 -CLASS TokenError
254.856 -CLASS Tokenizer
254.857 -CLASS TortureBase
254.858 -CLASS Trace
254.859 -CLASS Transformer
254.860 -CLASS Transport
254.861 -CLASS Tree
254.862 -CLASS TreeBuilder
254.863 -CLASS TryExcept
254.864 -CLASS TryFinally
254.865 -CLASS Tuple
254.866 -CLASS TupleArg
254.867 -CLASS Turtle
254.868 -CLASS TurtleScreen
254.869 -CLASS Type
254.870 -CLASS TypeError
254.871 -CLASS TypeError
254.872 -CLASS TypeInfo
254.873 -CLASS UDPServer
254.874 -CLASS URLError
254.875 -CLASS UUID
254.876 -CLASS UnaryAdd
254.877 -CLASS UnarySub
254.878 -CLASS UnboundLocalError
254.879 -CLASS UnboundLocalError
254.880 -CLASS Underflow
254.881 -CLASS UnexpectedException
254.882 -CLASS UnicodeDecodeError
254.883 -CLASS UnicodeDecodeError
254.884 -CLASS UnicodeEncodeError
254.885 -CLASS UnicodeEncodeError
254.886 -CLASS UnicodeError
254.887 -CLASS UnicodeError
254.888 -CLASS UnicodeTranslateError
254.889 -CLASS UnicodeTranslateError
254.890 -CLASS UnicodeWarning
254.891 -CLASS UnicodeWarning
254.892 -CLASS UnimplementedFileMode
254.893 -CLASS Union
254.894 -CLASS UnixCCompiler
254.895 -CLASS UnixDatagramServer
254.896 -CLASS UnixMailbox
254.897 -CLASS UnixStreamServer
254.898 -CLASS Unknown
254.899 -CLASS UnknownFileError
254.900 -CLASS UnknownHandler
254.901 -CLASS UnknownProtocol
254.902 -CLASS UnknownTransferEncoding
254.903 -CLASS Unload
254.904 -CLASS Unmarshaller
254.905 -CLASS Unpacker
254.906 -CLASS Unpickler
254.907 -CLASS UnpicklingError
254.908 -CLASS UnspecifiedEventTypeErr
254.909 -CLASS UnsupportedOperation
254.910 -CLASS UserDataHandler
254.911 -CLASS UserDict
254.912 -CLASS UserList
254.913 -CLASS UserString
254.914 -CLASS UserWarning
254.915 -CLASS UserWarning
254.916 -CLASS ValidationErr
254.917 -CLASS ValueError
254.918 -CLASS ValueError
254.919 -CLASS Values
254.920 -CLASS Vec2D
254.921 -CLASS Vendor
254.922 -CLASS Version
254.923 -CLASS VersionPredicate
254.924 -CLASS View
254.925 -CLASS WSGIRequestHandler
254.926 -CLASS WSGIServer
254.927 -CLASS Warning
254.928 -CLASS Warning
254.929 -CLASS Wave_read
254.930 -CLASS Wave_write
254.931 -CLASS WeakKeyDictionary
254.932 -CLASS WeakValueDictionary
254.933 -CLASS While
254.934 -CLASS WichmannHill
254.935 -CLASS WinDLL
254.936 -CLASS Window
254.937 -CLASS WindowsError
254.938 -CLASS WindowsError
254.939 -CLASS With
254.940 -CLASS WrongDocumentErr
254.941 -CLASS X
254.942 -CLASS XMLFilter
254.943 -CLASS XMLFilterBase
254.944 -CLASS XMLFilterImpl
254.945 -CLASS XMLGenerator
254.946 -CLASS XMLParser
254.947 -CLASS XMLRPCDocGenerator
254.948 -CLASS XMLReader
254.949 -CLASS XMLTreeBuilder
254.950 -CLASS XmlParseErr
254.951 -CLASS Yield
254.952 -CLASS Yuck
254.953 -CLASS ZeroDivisionError
254.954 -CLASS ZeroDivisionError
254.955 -CLASS ZipFile
254.956 -CLASS ZipImportError
254.957 -CLASS ZipInfo
254.958 -CLASS _CData [PROTECTE
254.959 -CLASS _FuncPtr [PROTECTE
254.960 -CLASS _SimpleCData [PROTECTE
254.961 -CLASS _posixfile_
254.962 -CLASS array
254.963 -CLASS async_chat
254.964 -CLASS bdist
254.965 -CLASS bdist_dumb
254.966 -CLASS bdist_msi
254.967 -CLASS bdist_rpm
254.968 -CLASS bdist_wininst
254.969 -CLASS bool
254.970 -CLASS bsddbobject
254.971 -CLASS build
254.972 -CLASS build_clib
254.973 -CLASS build_ext
254.974 -CLASS build_py
254.975 -CLASS build_scripts
254.976 -CLASS c_bool
254.977 -CLASS c_byte
254.978 -CLASS c_char
254.979 -CLASS c_char_p
254.980 -CLASS c_double
254.981 -CLASS c_float
254.982 -CLASS c_int
254.983 -CLASS c_int16
254.984 -CLASS c_int32
254.985 -CLASS c_int64
254.986 -CLASS c_int8
254.987 -CLASS c_long
254.988 -CLASS c_longdouble
254.989 -CLASS c_longlong
254.990 -CLASS c_short
254.991 -CLASS c_size_t
254.992 -CLASS c_ubyte
254.993 -CLASS c_uint
254.994 -CLASS c_uint16
254.995 -CLASS c_uint32
254.996 -CLASS c_uint64
254.997 -CLASS c_uint8
254.998 -CLASS c_ulong
254.999 -CLASS c_ulonglong
254.1000 -CLASS c_ushort
254.1001 -CLASS c_void_p
254.1002 -CLASS c_wchar
254.1003 -CLASS c_wchar_p
254.1004 -CLASS class
254.1005 -CLASS class
254.1006 -CLASS clean
254.1007 -CLASS closing
254.1008 -CLASS complex
254.1009 -CLASS compressobj
254.1010 -CLASS config
254.1011 -CLASS container
254.1012 -CLASS container
254.1013 -CLASS contextmanager
254.1014 -CLASS contextmanager
254.1015 -CLASS controller
254.1016 -CLASS date
254.1017 -CLASS datetime
254.1018 -CLASS dbexts
254.1019 -CLASS dbextsTestCase
254.1020 -CLASS dbhash
254.1021 -CLASS decompressobj
254.1022 -CLASS deque
254.1023 -CLASS dict
254.1024 -CLASS dict
254.1025 -CLASS dircmp
254.1026 -CLASS dispatcher
254.1027 -CLASS dispatcher_with_send
254.1028 -CLASS dl
254.1029 -CLASS error
254.1030 -CLASS error_data
254.1031 -CLASS error_reply
254.1032 -CLASS error_temp
254.1033 -CLASS excel
254.1034 -CLASS excel_tab
254.1035 -CLASS executor
254.1036 -CLASS fifo
254.1037 -CLASS file
254.1038 -CLASS file
254.1039 -CLASS file_dispatcher
254.1040 -CLASS file_wrapper
254.1041 -CLASS float
254.1042 -CLASS float
254.1043 -CLASS foo
254.1044 -CLASS gaierror
254.1045 -CLASS herror
254.1046 -CLASS install
254.1047 -CLASS install_data
254.1048 -CLASS install_egg_info
254.1049 -CLASS install_headers
254.1050 -CLASS install_lib
254.1051 -CLASS install_misc
254.1052 -CLASS install_scripts
254.1053 -CLASS instance
254.1054 -CLASS instance
254.1055 -CLASS int
254.1056 -CLASS iterator
254.1057 -CLASS iterator
254.1058 -CLASS list
254.1059 -CLASS local
254.1060 -CLASS lock
254.1061 -CLASS long
254.1062 -CLASS main
254.1063 -CLASS mbox
254.1064 -CLASS mboxMessage
254.1065 -CLASS mllib
254.1066 -CLASS mmap
254.1067 -CLASS multiprocessing.Pool
254.1068 -CLASS mutex
254.1069 -CLASS mxODBCProxy
254.1070 -CLASS netrc
254.1071 -CLASS object
254.1072 -CLASS object
254.1073 -CLASS oss_audio_device
254.1074 -CLASS oss_mixer_device
254.1075 -CLASS poll
254.1076 -CLASS py_object
254.1077 -CLASS register
254.1078 -CLASS scheduler
254.1079 -CLASS sdist
254.1080 -CLASS set
254.1081 -CLASS set
254.1082 -CLASS shlex
254.1083 -CLASS simple_producer
254.1084 -CLASS socket
254.1085 -CLASS stat_result
254.1086 -CLASS str
254.1087 -CLASS str
254.1088 -CLASS test_dist
254.1089 -CLASS test_zxjdbc
254.1090 -CLASS time
254.1091 -CLASS timedelta
254.1092 -CLASS timeout
254.1093 -CLASS tixCommand
254.1094 -CLASS tmxxx
254.1095 -CLASS tuple
254.1096 -CLASS tzinfo
254.1097 -CLASS unicode
254.1098 -CLASS unicode
254.1099 -CLASS upload
254.1100 -CLASS window
254.1101 -CLASS xmlparser
254.1102 -CLASS zipimporter
254.1103 -CLASS zxAPITestCase
254.1104 -CLASS zxCoreTestCase
254.1105 -CLASS zxJDBCTestCase
254.1106 -METHOD __import__(name, globals, loca
254.1107 -METHOD abs(x)
254.1108 -METHOD all(iterable)
254.1109 -METHOD any(iterable)
254.1110 -METHOD ---apply(function, args, ke---
254.1111 -METHOD basestring()
254.1112 -METHOD bin(x)
254.1113 -METHOD bool(x)
254.1114 -METHOD buffer(object, offset, size)
254.1115 -METHOD callable(object)
254.1116 -METHOD chr(i)
254.1117 -METHOD classmethod(function)
254.1118 -METHOD cmp(x, y)
254.1119 -METHOD coerce(x, y)
254.1120 -METHOD compile(source, filename, mode
254.1121 -METHOD complex(real, imag)
254.1122 -METHOD delattr(object, name)
254.1123 -METHOD dict(arg)
254.1124 -METHOD dir(object)
254.1125 -METHOD divmod(a, b)
254.1126 -METHOD enumerate(sequence, start)
254.1127 -METHOD eval(expression, globals, loca
254.1128 -METHOD execfile(filename, globals, lo
254.1129 -METHOD exit(code)
254.1130 -METHOD file(filename, mode, bufsize)
254.1131 -METHOD filter(function, iterable)
254.1132 -METHOD float(x)
254.1133 -METHOD frozenset(iterable)
254.1134 -METHOD getattr(object, name, default)
254.1135 -METHOD globals()
254.1136 -METHOD hasattr(object, name)
254.1137 -METHOD hash(object)
254.1138 -METHOD help(object)
254.1139 -METHOD hex(x)
254.1140 -METHOD id(object)
254.1141 -METHOD input(prompt)
254.1142 -METHOD int(x, radix)
254.1143 -METHOD intern(string)
254.1144 -METHOD isinstance(object, classinfo)
254.1145 -METHOD issubclass(class, classinfo)
254.1146 -METHOD iter(o, sentinel)
254.1147 -METHOD len(s)
254.1148 -METHOD list(iterable)
254.1149 -METHOD locals()
254.1150 -METHOD long(x, radix)
254.1151 -METHOD map(function, iterable)
254.1152 -METHOD max(iterable, argskey)
254.1153 -METHOD min(iterable, argskey)
254.1154 -METHOD next(iterator, default)
254.1155 -METHOD object()
254.1156 -METHOD oct(x)
254.1157 -METHOD open(filename, mode, bufsize)
254.1158 -METHOD ord(c)
254.1159 -METHOD pow(x, y, z)
254.1160 -METHOD print(object, sep, end, file)
254.1161 -METHOD property(fget, fset, fdel, doc
254.1162 -METHOD quit(code)
254.1163 -METHOD range(start, stop, step)
254.1164 -METHOD raw_input(prompt)
254.1165 -METHOD reduce(function, iterable, ini
254.1166 -METHOD reload(module)
254.1167 -METHOD repr(object)
254.1168 -METHOD reversed(seq)
254.1169 -METHOD round(x, n)
254.1170 -METHOD set(iterable)
254.1171 -METHOD setattr(object, name, value)
254.1172 -METHOD slice(start, stop, step)
254.1173 -METHOD sorted(iterable, cmp, key, rev
254.1174 -METHOD staticmethod(function)
254.1175 -METHOD str(object)
254.1176 -METHOD sum(iterable, start)
254.1177 -METHOD super(type, object-or-type)
254.1178 -METHOD tuple(iterable)
254.1179 -METHOD type(name, bases, dict)
254.1180 -METHOD type(object)
254.1181 -METHOD unichr(i)
254.1182 -METHOD unicode(object, encoding, erro
254.1183 -METHOD vars(object)
254.1184 -METHOD xrange(start, stop, step)
254.1185 -METHOD zip(iterable)
254.1186 -VARIABLE Ellipsis
254.1187 -VARIABLE False
254.1188 -VARIABLE None
254.1189 -VARIABLE NotImplemented
254.1190 -VARIABLE True
254.1191 -VARIABLE __debug__
254.1192 -VARIABLE copyright
254.1193 -KEYWORD and
254.1194 -KEYWORD as
254.1195 -KEYWORD assert
254.1196 -KEYWORD break
254.1197 -KEYWORD class
254.1198 -KEYWORD continue
254.1199 -KEYWORD def
254.1200 -KEYWORD del
254.1201 -KEYWORD elif
254.1202 -KEYWORD else
254.1203 -KEYWORD except
254.1204 -KEYWORD exec
254.1205 -KEYWORD finally
254.1206 -KEYWORD for
254.1207 -KEYWORD from
254.1208 -KEYWORD global
254.1209 -KEYWORD if
254.1210 -KEYWORD import
254.1211 -KEYWORD in
254.1212 -KEYWORD is
254.1213 -KEYWORD lambda
254.1214 -KEYWORD not
254.1215 -KEYWORD or
254.1216 -KEYWORD pass
254.1217 -KEYWORD print
254.1218 -KEYWORD raise
254.1219 -KEYWORD return
254.1220 -KEYWORD try
254.1221 -KEYWORD while
254.1222 -KEYWORD with
254.1223 -KEYWORD yield
255.1 --- a/python.editor/test/unit/data/testfiles/emptydecorators.py Sun Jan 04 13:11:53 2015 -0600
255.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
255.3 @@ -1,1 +0,0 @@
255.4 -@
256.1 --- a/python.editor/test/unit/data/testfiles/emptydecorators.py.testDecorators1.completion Sun Jan 04 13:11:53 2015 -0600
256.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
256.3 @@ -1,11 +0,0 @@
256.4 -Code completion result for source line:
256.5 -@|
256.6 -(QueryType=COMPLETION, NameKind=PREFIX)
256.7 -METHOD abstractmethod
256.8 -METHOD classmethod
256.9 -METHOD contextmanager
256.10 -METHOD getargspec
256.11 -METHOD setprofile
256.12 -METHOD settrace
256.13 -METHOD staticmethod
256.14 -METHOD wrapper
257.1 --- a/python.editor/test/unit/data/testfiles/errors1.py Sun Jan 04 13:11:53 2015 -0600
257.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
257.3 @@ -1,12 +0,0 @@
257.4 -class A:
257.5 - def foo():
257.6 - self.filename = filename
257.7 -
257.8 -def toplevel(x,y,z):
257.9 - print "hello"
257.10 -
257.11 -def toplevel2():
257.12 - print "hello"
257.13 -
257.14 -class Bar:
257.15 - def noargs():
258.1 --- a/python.editor/test/unit/data/testfiles/errors1.py.errors Sun Jan 04 13:11:53 2015 -0600
258.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
258.3 @@ -1,2 +0,0 @@
258.4 -169-169:mismatched input '' expecting INDENT
258.5 -170-170:mismatched input '' expecting INDENT
259.1 --- a/python.editor/test/unit/data/testfiles/errors10.py Sun Jan 04 13:11:53 2015 -0600
259.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
259.3 @@ -1,6 +0,0 @@
259.4 -def myFunc(p):
259.5 - if p
259.6 - pass
259.7 - else:
259.8 - pass
259.9 -
260.1 --- a/python.editor/test/unit/data/testfiles/errors10.py.errors Sun Jan 04 13:11:53 2015 -0600
260.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
260.3 @@ -1,1 +0,0 @@
260.4 -23-23:mismatched input '\n' expecting COLON
261.1 --- a/python.editor/test/unit/data/testfiles/errors11.py Sun Jan 04 13:11:53 2015 -0600
261.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
261.3 @@ -1,12 +0,0 @@
261.4 -def myFunc(p):
261.5 - if p:
261.6 - pass
261.7 - else
261.8 - pass
261.9 -
261.10 -def myFunc(p):
261.11 - try
261.12 - p
261.13 - except
261.14 - pass
261.15 -
262.1 --- a/python.editor/test/unit/data/testfiles/errors11.py.errors Sun Jan 04 13:11:53 2015 -0600
262.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
262.3 @@ -1,3 +0,0 @@
262.4 -104-104:mismatched input '\n' expecting COLON
262.5 -46-46:mismatched input '\n' expecting COLON
262.6 -83-83:mismatched input '\n' expecting COLON
263.1 --- a/python.editor/test/unit/data/testfiles/errors12.py Sun Jan 04 13:11:53 2015 -0600
263.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
263.3 @@ -1,4 +0,0 @@
263.4 -from Module import ABC,DEF
263.5 -ABC()
263.6 -DEF()
263.7 -
264.1 --- a/python.editor/test/unit/data/testfiles/errors13.py Sun Jan 04 13:11:53 2015 -0600
264.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
264.3 @@ -1,8 +0,0 @@
264.4 -class Test:
264.5 - def myfunc(self, newparam,bla):
264.6 - print 'bla'
264.7 - pass
264.8 -
264.9 - def myfunct_two(self):
264.10 - pass
264.11 -
265.1 --- a/python.editor/test/unit/data/testfiles/errors2.py Sun Jan 04 13:11:53 2015 -0600
265.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
265.3 @@ -1,618 +0,0 @@
265.4 -"""Configuration file parser.
265.5 -
265.6 -A setup file consists of sections, lead by a "[section]" header,
265.7 -and followed by "name: value" entries, with continuations and such in
265.8 -the style of RFC 822.
265.9 -
265.10 - the same section, or values in a special [DEFAULT] section.
265.11 -
265.12 -For example:
265.13 -
265.14 - something: %(dir)s/whatever
265.15 -
265.16 -would resolve the "%(dir)s" to the value of dir. All reference
265.17 -expansions are done late, on demand.
265.18 -
265.19 -Intrinsic defaults can be specified by passing them into the
265.20 -ConfigParser constructor as a dictionary.
265.21 -
265.22 -class:
265.23 -
265.24 -ConfigParser -- responsible for parsing a list of
265.25 - configuration files, and managing the parsed database.
265.26 -
265.27 - methods:
265.28 -
265.29 - __init__(defaults=None)
265.30 - create the parser and specify a dictionary of intrinsic defaults. The
265.31 - keys must be strings, the values must be appropriate for %()s string
265.32 - interpolation. Note that `__name__' is always an intrinsic default;
265.33 - it's value is the section's name.
265.34 -
265.35 - sections()
265.36 - return all the configuration section names, sans DEFAULT
265.37 -
265.38 - has_section(section)
265.39 - return whether the given section exists
265.40 -
265.41 - has_option(section, option)
265.42 - return whether the given option exists in the given section
265.43 -
265.44 - options(section)
265.45 - return list of configuration options for the named section
265.46 -
265.47 - read(filenames)
265.48 - read and parse the list of named configuration files, given by
265.49 - name. A single filename is also allowed. Non-existing files
265.50 - are ignored.
265.51 -
265.52 - readfp(fp, filename=None)
265.53 - read and parse one configuration file, given as a file object.
265.54 - The filename defaults to fp.name; it is only used in error
265.55 - messages (if fp has no `name' attribute, the string `<???>' is used).
265.56 -
265.57 - get(section, option, raw=False, vars=None)
265.58 - return a string value for the named option. All % interpolations are
265.59 - expanded in the return values, based on the defaults passed into the
265.60 - constructor and the DEFAULT section. Additional substitutions may be
265.61 - provided using the `vars' argument, which must be a dictionary whose
265.62 - contents override any pre-existing defaults.
265.63 -
265.64 - getint(section, options)
265.65 - like get(), but convert value to an integer
265.66 -
265.67 - getfloat(section, options)
265.68 - like get(), but convert value to a float
265.69 -
265.70 - getboolean(section, options)
265.71 - like get(), but convert value to a boolean (currently case
265.72 - insensitively defined as 0, false, no, off for False, and 1, true,
265.73 - yes, on for True). Returns False or True.
265.74 -
265.75 - items(section, raw=False, vars=None)
265.76 - return a list of tuples with (name, value) for each option
265.77 - in the section.
265.78 -
265.79 - remove_section(section)
265.80 - remove the given file section and all its options
265.81 -
265.82 - remove_option(section, option)
265.83 - remove the given option from the given section
265.84 -
265.85 - set(section, option, value)
265.86 - set the given option
265.87 -
265.88 - write(fp)
265.89 - write the configuration state in .ini format
265.90 -"""
265.91 -
265.92 -import re
265.93 -
265.94 -__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
265.95 - "InterpolationError", "InterpolationDepthError",
265.96 - "InterpolationSyntaxError", "ParsingError",
265.97 - "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser",
265.98 - "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
265.99 -
265.100 -DEFAULTSECT = "DEFAULT"
265.101 -
265.102 -MAX_INTERPOLATION_DEPTH = 10
265.103 -
265.104 -
265.105 -
265.106 -# exception classes
265.107 -class Error(Exception):
265.108 - """Base class for ConfigParser exceptions."""
265.109 -
265.110 - def __init__(self, msg=''):
265.111 - self.message = msg
265.112 - Exception.__init__(self, msg)
265.113 -
265.114 - def __repr__(self):
265.115 - return self.message
265.116 -
265.117 - __str__ = __repr__
265.118 -
265.119 -class NoSectionError(Error):
265.120 - """Rasssised when no section matches a requested option."""
265.121 -
265.122 - def __init__(self, section):
265.123 - Error.__init__(self, 'No section: ' + `section`)
265.124 - self.section = section
265.125 -
265.126 -class DuplicateSectionError(Error):
265.127 - """Raised when a section is multiply-created."""
265.128 -
265.129 - def __init__(self, section):
265.130 - Error.__init__(self, "Section %r already exists" % section)
265.131 - self.section = section
265.132 -
265.133 -class NoOptionError(Error):
265.134 - """A requested option was not found."""
265.135 -
265.136 - def __init__(self, option, section):
265.137 - Error.__init__(self, "No option %r in section: %r" %
265.138 - (option, section))
265.139 - self.option = option
265.140 - self.section = section
265.141 -
265.142 -class InterpolationError(Error):
265.143 - """Base class for interpolation-related exceptions."""
265.144 -
265.145 - def __init__(self, option, section, msg):
265.146 - Error.__init__(self, msg)
265.147 - self.option = option
265.148 - self.section = section
265.149 -
265.150 -class InterpolationMissingOptionError(InterpolationError):
265.151 - """A string substitution required a setting which was not available."""
265.152 -
265.153 - def __init__(self, option, section, rawval, reference):
265.154 - msg = ("Bad value substitution:\n"
265.155 - "\tsection: [%s]\n"
265.156 - "\toption : %s\n"
265.157 - "\tkey : %s\n"
265.158 - "\trawval : %s\n"
265.159 - % (section, option, reference, rawval))
265.160 - InterpolationError.__init__(self, option, section, msg)
265.161 - self.reference = reference
265.162 -
265.163 -class InterpolationSyntaxError(InterpolationError):
265.164 - """Raised when the source text into which substitutions are made
265.165 - does not conform to the required syntax."""
265.166 -
265.167 -class InterpolationDepthError(InterpolationError):
265.168 - """Raised when substitutions are nested too deeply."""
265.169 -
265.170 - def __init__(self, option, section, rawval):
265.171 - msg = ("Value interpolation too deeply recursive:\n"
265.172 - "\tsection: [%s]\n"
265.173 - "\toption : %s\n"
265.174 - "\trawval : %s\n"
265.175 - % (section, option, rawval))
265.176 - InterpolationError.__init__(self, option, section, msg)
265.177 -
265.178 -class ParsingError(Error):
265.179 - """Raised when a configuration file does not follow legal syntax."""
265.180 -
265.181 - def __init__(self, filename):
265.182 - Error.__init__(self, 'File contains parsing errors: %s' % filename)
265.183 - self.filename = filename
265.184 - self.errors = []
265.185 -
265.186 - def append(self, lineno, line):
265.187 - self.errors.append((lineno, line))
265.188 - self.message += '\n\t[line %2d]: %s' % (lineno, line)
265.189 -
265.190 -class MissingSectionHeaderError(ParsingError):
265.191 - """Raised when a key-value pair is found before any section header."""
265.192 -
265.193 - def __init__(self, filename, lineno, line):
265.194 - Error.__init__(
265.195 - self,
265.196 - 'File contains no section headers.\nfile: %s, line: %d\n%s' %
265.197 - (filename, lineno, line))
265.198 - self.filename = filename
265.199 - self.lineno = lineno
265.200 - self.line = line
265.201 -
265.202 -
265.203 -
265.204 -class RawConfigParser:
265.205 - def __init__(self, defaults=None):
265.206 - self._sections = {}
265.207 - if defaults is None:
265.208 - self._defaults = {}
265.209 - else:
265.210 - self._defaults = defaults
265.211 -
265.212 - def defaults(self):
265.213 - return self._defaults
265.214 -
265.215 - def sections(self):
265.216 - """Return a list of section names, excluding [DEFAULT]"""
265.217 - # self._sections will never have [DEFAULT] in it
265.218 - return self._sections.keys()
265.219 -
265.220 - def add_section(self, section):
265.221 - """Create a new section in the configuration.
265.222 -
265.223 - Raise DuplicateSectionError if a section by the specified name
265.224 - already exists.
265.225 - """
265.226 - if section in self._sections:
265.227 - raise DuplicateSectionError(section)
265.228 - self._sections[section] = {}
265.229 -
265.230 - def has_section(self, section):
265.231 - """Indicate whether the named section is present in the configuration.
265.232 -
265.233 - The DEFAULT section is not acknowledged.
265.234 - """
265.235 - return section in self._sections
265.236 -
265.237 - def options(self, section):
265.238 - """Return a list of option names for the given section name."""
265.239 - try:
265.240 - opts = self._sections[section].copy()
265.241 - except KeyError:
265.242 - raise NoSectionError(section)
265.243 - opts.update(self._defaults)
265.244 - if '__name__' in opts:
265.245 - del opts['__name__']
265.246 - return opts.keys()
265.247 -
265.248 - def read(self, filenames):
265.249 - """Read and parse a filename or a list of filenames.
265.250 -
265.251 - Files that cannot be opened are silently ignored; this is
265.252 - designed so that you can specify a list of potential
265.253 - configuration file locations (e.g. current directory, user's
265.254 - home directory, systemwide directory), and all existing
265.255 - configuration files in the list will be read. A single
265.256 - filename may also be given.
265.257 - """
265.258 - if isinstance(filenames, basestring):
265.259 - filenames = [filenames]
265.260 - for filename in filenames:
265.261 - try:
265.262 - name = open(filename)
265.263 - fp = open(filename)
265.264 - except IOError:
265.265 - continue
265.266 - var = self._read(fp, filename)
265.267 - fp.close()
265.268 -
265.269 - def readfp(self, fp, filename=None):
265.270 - """Like read() but the argument must be a file-like object.
265.271 -
265.272 - The `fp' argument must have a `readline' method. Optional
265.273 - second argument is the `filename', which if not given, is
265.274 - taken from fp.name. If fp has no `name' attribute, `<???>' is
265.275 - used.
265.276 -
265.277 - """
265.278 - if filename is None:
265.279 - try:
265.280 - filename = fp.name
265.281 - except AttributeError:
265.282 - filename = '<???>'
265.283 - self._read(fp, filename)
265.284 -
265.285 - def get(self, section, option):
265.286 - opt = self.optionxform(option)
265.287 - if section not in self._sections:
265.288 - if section != DEFAULTSECT:
265.289 - raise NoSectionError(section)
265.290 - if opt in self._defaults:
265.291 - return self._defaults[opt]
265.292 - else:
265.293 - raise NoOptionError(option, section)
265.294 - elif opt in self._sections[section]:
265.295 - return self._sections[section][opt]
265.296 - elif opt in self._defaults:
265.297 - return self._defaults[opt]
265.298 - else:
265.299 - raise NoOptionError(option, section)
265.300 -
265.301 - def items(self, section):
265.302 - try:
265.303 - d2 = self._sections[section]
265.304 - except KeyError:
265.305 - if section != DEFAULTSECT:
265.306 - raise NoSectionError(section)
265.307 - d2 = {}
265.308 - d = self._defaults.copy()
265.309 - d.update(d2)
265.310 - if "__name__" in d:
265.311 - del d["__name__"]
265.312 - return d.items()
265.313 -
265.314 - def _get(self, section, conv, option):
265.315 - return conv(self.get(section, option))
265.316 -
265.317 - def getint(self, section, option):
265.318 - return self._get(section, int, option)
265.319 -
265.320 - def getfloat(self, section, option):
265.321 - return self._get(section, float, option)
265.322 -
265.323 - _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
265.324 - '0': False, 'no': False, 'false': False, 'off': False}
265.325 -
265.326 - def getboolean(self, section, option):
265.327 - v = self.get(section, option)
265.328 - if v.lower() not in self._boolean_states:
265.329 - raise ValueError, 'Not a boolean: %s' % v
265.330 - return self._boolean_states[v.lower()]
265.331 -
265.332 - def optionxform(self, optionstr):
265.333 - return optionstr.lower()
265.334 -
265.335 - def has_option(self, section, option):
265.336 - """Check for the existence of a given option in a given section."""
265.337 - if not section or section == DEFAULTSECT:
265.338 - option = self.optionxform(option)
265.339 - return option in self._defaults
265.340 - elif section not in self._sections:
265.341 - return False
265.342 - else:
265.343 - option = self.optionxform(option)
265.344 - return (option in self._sections[section]
265.345 - or option in self._defaults)
265.346 -
265.347 - def set(self, section, option, value):
265.348 - """Set an option."""
265.349 - if not section or section == DEFAULTSECT:
265.350 - sectdict = self._defaults
265.351 - else:
265.352 - try:
265.353 - sectdict = self._sections[section]
265.354 - except KeyError:
265.355 - raise NoSectionError(section)
265.356 - sectdict[self.optionxform(option)] = value
265.357 -
265.358 - def write(self, fp):
265.359 - """Write an .ini-format representation of the configuration state."""
265.360 - if self._defaults:
265.361 - fp.write("[%s]\n" % DEFAULTSECT)
265.362 - for (key, value) in self._defaults.items():
265.363 - fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
265.364 - fp.write("\n")
265.365 - for section in self._sections:
265.366 - fp.write("[%s]\n" % section)
265.367 - for (key, value) in self._sections[section].items():
265.368 - if key != "__name__":
265.369 - fp.write("%s = %s\n" %
265.370 - (key, str(value).replace('\n', '\n\t')))
265.371 - fp.write("\n")
265.372 -
265.373 - def remove_option(self, section, option):
265.374 - """Remove an option."""
265.375 - if not section or section == DEFAULTSECT:
265.376 - sectdict = self._defaults
265.377 - else:
265.378 - try:
265.379 - sectdict = self._sections[section]
265.380 - except KeyError:
265.381 - raise NoSectionError(section)
265.382 - option = self.optionxform(option)
265.383 - existed = option in sectdict
265.384 - if existed:
265.385 - del sectdict[option]
265.386 - return existed
265.387 -
265.388 - def remove_section(self, section):
265.389 - """Remove a file section."""
265.390 - existed = section in self._sections
265.391 - if existed:
265.392 - del self._sections[section]
265.393 - return existed
265.394 -
265.395 - #
265.396 - # Regular expressions for parsing section headers and options.
265.397 - #
265.398 - SECTCRE = re.compile(
265.399 - r'\[' # [
265.400 - r'(?P<header>[^]]+)' # very permissive!
265.401 - r'\]' # ]
265.402 - )
265.403 - OPTCRE = re.compile(
265.404 - r'(?P<option>[^:=\s][^:=]*)' # very permissive!
265.405 - r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
265.406 - # followed by separator
265.407 - # (either : or =), followed
265.408 - # by any # space/tab
265.409 - r'(?P<value>.*)$' # everything up to eol
265.410 - )
265.411 -
265.412 - def _read(self, fp, fpname):
265.413 - """Parse a sectioned setup file.
265.414 -
265.415 - The sections in setup file contains a title line at the top,
265.416 - indicated by a name in square brackets (`[]'), plus key/value
265.417 - options lines, indicated by `name: value' format lines.
265.418 - Continuations are represented by an embedded newline then
265.419 - leading whitespace. Blank lines, lines beginning with a '#',
265.420 - and just about everything else are ignored.
265.421 - """
265.422 - cursect = None # None, or a dictionary
265.423 - optname = None
265.424 - lineno = 0
265.425 - e = None # None, or an exception
265.426 - while True:
265.427 - line = fp.readline()
265.428 - if not line:
265.429 - break
265.430 - lineno +
265.431 - 1
265.432 - lineno = lineno + 1
265.433 - # comment or blank line?
265.434 - if line.strip() == '' or line[0] in '#;':
265.435 - continue
265.436 - if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
265.437 - # no leading whitespace
265.438 - continue
265.439 - # continuation line?
265.440 - if line[0].isspace() and cursect is not None and optname:
265.441 - value = line.strip()
265.442 - if value:
265.443 - cursect[optname] = "%s\n%s" % (cursect[optname], value)
265.444 - # a section header or option header?
265.445 - else:
265.446 - # is it a section header?
265.447 - mo = self.SECTCRE.match(line)
265.448 - if mo:
265.449 - sectname = mo.group('header')
265.450 - if sectname in self._sections:
265.451 - cursect = self._sections[sectname]
265.452 - elif sectname == DEFAULTSECT:
265.453 - cursect = self._defaults
265.454 - else:
265.455 - cursect = {'__name__': sectname}
265.456 - self._sections[sectname] = cursect
265.457 - # So sections can't start with a continuation line
265.458 - optname = None
265.459 - # no section header in the file?
265.460 - elif cursect is None:
265.461 - raise MissingSectionHeaderError(fpname, lineno, `line`)
265.462 - # an option line?
265.463 - else:
265.464 - mo = self.OPTCRE.match(line)
265.465 - if mo:
265.466 - optname, vi, optval = mo.group('option', 'vi', 'value')
265.467 - if vi in ('=', ':') and ';' in optval:
265.468 - # ';' is a comment delimiter only if it follows
265.469 - # a spacing character
265.470 - pos = optval.find(';')
265.471 - if pos != -1 and optval[pos-1].isspace():
265.472 - optval = optval[:pos]
265.473 - optval = optval.strip()
265.474 - # allow empty values
265.475 - if optval == '""':
265.476 - optval = ''
265.477 - optname = self.optionxform(optname.rstrip())
265.478 - cursect[optname] = optval
265.479 - else:
265.480 - # a non-fatal parsing error occurred. set up the
265.481 - # exception but keep going. the exception will be
265.482 - # raised at the end of the file and will contain a
265.483 - # list of all bogus lines
265.484 - if not e:
265.485 - e = ParsingError(fpname)
265.486 - e.append(lineno, `line`)
265.487 - # if any parsing errors occurred, raise an exception
265.488 - if e:
265.489 - raise e
265.490 -
265.491 -
265.492 -class ConfigParser(RawConfigParser):
265.493 -
265.494 - def get(self, section, option, raw=False, vars=None):
265.495 - """Get an option value for a given section.
265.496 -
265.497 - All % interpolations are expanded in the return values, based on the
265.498 - defaults passed into the constructor, unless the optional argument
265.499 - `raw' is true. Additional substitutions may be provided using the
265.500 - `vars' argument, which must be a dictionary whose contents overrides
265.501 - any pre-existing defaults.
265.502 -
265.503 - The section DEFAULT is special.
265.504 - """
265.505 - d = self._defaults.copy()
265.506 - try:
265.507 - d.update(self._sections[section])
265.508 - except KeyError:
265.509 - if section != DEFAULTSECT:
265.510 - raise NoSectionError(section)
265.511 - # Update with the entry specific variables
265.512 - if vars is not None:
265.513 - d.update(vars)
265.514 - option = self.optionxform(option)
265.515 - try:
265.516 - value = d[option]
265.517 - except KeyError:
265.518 - raise NoOptionError(option, section)
265.519 -
265.520 - if raw:
265.521 - return value
265.522 - else:
265.523 - return self._interpolate(section, option, value, d)
265.524 -
265.525 - def items(self, section, raw=False, vars=None):
265.526 - """Return a list of tuples with (name, value) for each option
265.527 - in the section.
265.528 -
265.529 - All % interpolations are expanded in the return values, based on the
265.530 - defaults passed into the constructor, unless the optional argument
265.531 - `raw' is true. Additional substitutions may be provided using the
265.532 - `vars' argument, which must be a dictionary whose contents overrides
265.533 - any pre-existing defaults.
265.534 -
265.535 - The section DEFAULT is special.
265.536 - """
265.537 - d = self._defaults.copy()
265.538 - try:
265.539 - d.update(self._sections[section])
265.540 - except KeyError:
265.541 - if section != DEFAULTSECT:
265.542 - raise NoSectionError(section)
265.543 - # Update with the entry specific variables
265.544 - if vars:
265.545 - d.update(vars)
265.546 - options = d.keys()
265.547 - if "__name__" in options:
265.548 - options.remove("__name__")
265.549 - if raw:
265.550 - return [(option, d[option])
265.551 - for option in options]
265.552 - else:
265.553 - return [(option, self._interpolate(section, option, d[option], d))
265.554 - for option in options]
265.555 -
265.556 - def _interpolate(self, section, option, rawval, vars):
265.557 - # do the string interpolation
265.558 - value = rawval
265.559 - depth = MAX_INTERPOLATION_DEPTH
265.560 - while depth: # Loop through this until it's done
265.561 - depth -= 1
265.562 - if value.find("%(") != -1:
265.563 - try:
265.564 - value = value % vars
265.565 - except KeyError, e:
265.566 - raise InterpolationMissingOptionError(
265.567 - option, section, rawval, e[0])
265.568 - else:
265.569 - break
265.570 - if value.find("%(") != -1:
265.571 - raise InterpolationDepthError(option, section, rawval)
265.572 - return value
265.573 -
265.574 -
265.575 -class SafeConfigParser(ConfigParser):
265.576 -
265.577 - def _interpolate(self, section, option, rawval, vars):
265.578 - # do the string interpolation
265.579 - L = []
265.580 - self._interpolate_some(option, L, rawval, section, vars, 1)
265.581 - return ''.join(L)
265.582 -
265.583 - _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
265.584 -
265.585 - def _interpolate_some(self, option, accum, rest, section, map, depth):
265.586 - if depth > MAX_INTERPOLATION_DEPTH:
265.587 - raise InterpolationDepthError(option, section, rest)
265.588 - while rest:
265.589 - p = rest.find("%")
265.590 - if p < 0:
265.591 - accum.append(rest)
265.592 - return
265.593 - if p > 0:
265.594 - accum.append(rest[:p])
265.595 - rest = rest[p:]
265.596 - # p is no longer used
265.597 - c = rest[1:2]
265.598 - if c == "%":
265.599 - accum.append("%")
265.600 - rest = rest[2:]
265.601 - elif c == "(":
265.602 - m = self._interpvar_match(rest)
265.603 - if m is None:
265.604 - raise InterpolationSyntaxError(option, section,
265.605 - "bad interpolation variable reference %r" % rest)
265.606 - var = m.group(1)
265.607 - rest = rest[m.end():]
265.608 - try:
265.609 - v = map[var]
265.610 - except KeyError:
265.611 - raise InterpolationMissingOptionError(
265.612 - option, section, rest, var)
265.613 - if "%" in v:
265.614 - self._interpolate_some(option, accum, v,
265.615 - section, map, depth + 1)
265.616 - else:
265.617 - accum.append(v)
265.618 - else:
265.619 - raise InterpolationSyntaxError(
265.620 - option, section,
265.621 - "'%' must be followed by '%' or '(', found: " + `ret`)
266.1 --- a/python.editor/test/unit/data/testfiles/errors2.py.errors Sun Jan 04 13:11:53 2015 -0600
266.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
266.3 @@ -1,1 +0,0 @@
266.4 -14596-14596:no viable alternative at input '\n'
267.1 --- a/python.editor/test/unit/data/testfiles/errors3.py Sun Jan 04 13:11:53 2015 -0600
267.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
267.3 @@ -1,32 +0,0 @@
267.4 -class A:
267.5 - def foo():
267.6 - self.filename = filename
267.7 -
267.8 -def toplevel(x,y,z):
267.9 - print "hello"
267.10 -
267.11 -def toplevel2():
267.12 - print "hello
267.13 -
267.14 -class Bar:
267.15 - def noargs():
267.16 - print "hello"
267.17 -
267.18 - def okay1(self):
267.19 - print "hello"
267.20 -
267.21 - def okay2(cls):
267.22 - print "hello"
267.23 -
267.24 - def okay3(self, bar):
267.25 - print "hello"
267.26 -
267.27 - def okay4(cls, bar):
267.28 - print "hello"
267.29 -
267.30 - def bad1():
267.31 - print "hello"
267.32 -
267.33 - def bad2(filename):
267.34 - print "hello"
267.35 -
268.1 --- a/python.editor/test/unit/data/testfiles/errors3.py.errors Sun Jan 04 13:11:53 2015 -0600
268.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
268.3 @@ -1,1 +0,0 @@
268.4 -135-135:mismatched character '\n' expecting '"'
269.1 --- a/python.editor/test/unit/data/testfiles/errors4.py Sun Jan 04 13:11:53 2015 -0600
269.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
269.3 @@ -1,32 +0,0 @@
269.4 -class A:
269.5 - def foo():
269.6 - self.filename = filename
269.7 -
269.8 -def toplevel(x,y,z):
269.9 - """Missing end markers
269.10 -
269.11 -def toplevel2():
269.12 - print "hello"
269.13 -
269.14 -class Bar:
269.15 - def noargs():
269.16 - print "hello"
269.17 -
269.18 - def okay1(self):
269.19 - print "hello"
269.20 -
269.21 - def okay2(cls):
269.22 - print "hello"
269.23 -
269.24 - def okay3(self, bar):
269.25 - print "hello"
269.26 -
269.27 - def okay4(cls, bar):
269.28 - print "hello"
269.29 -
269.30 - def bad1():
269.31 - print "hello"
269.32 -
269.33 - def bad2(filename):
269.34 - print "hello"
269.35 -
270.1 --- a/python.editor/test/unit/data/testfiles/errors4.py.errors Sun Jan 04 13:11:53 2015 -0600
270.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
270.3 @@ -1,4 +0,0 @@
270.4 -83-105:rule STRINGPART failed predicate: {partial}?
270.5 -86-86:mismatched input 'Missing' expecting NEWLINE
270.6 -94-94:mismatched input 'end' expecting NEWLINE
270.7 -98-98:mismatched input 'markers' expecting NEWLINE
271.1 --- a/python.editor/test/unit/data/testfiles/errors5.py Sun Jan 04 13:11:53 2015 -0600
271.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
271.3 @@ -1,20 +0,0 @@
271.4 -
271.5 -__author__="tor"
271.6 -__date__ ="$Oct 16, 2008 4:19:21 PM$"
271.7 -
271.8 -if __name__ == "__main__":
271.9 - print "Hello";
271.10 -
271.11 -class C
271.12 -def foo():
271.13 - doc = "The foo property."
271.14 - def fget(self):
271.15 - return self._foo
271.16 - def fset(self, value):
271.17 - self._foo = value
271.18 - def fdel(self):
271.19 - del self._foo
271.20 - return locals()
271.21 - foo = property(**foo())
271.22 -
271.23 -print foo
272.1 --- a/python.editor/test/unit/data/testfiles/errors6.py Sun Jan 04 13:11:53 2015 -0600
272.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
272.3 @@ -1,13 +0,0 @@
272.4 -from unittest import failUnlessRaises
272.5 -import unittest
272.6 -
272.7 -class MyTest(unittest.TestCase):
272.8 - quit([code=None])
272.9 - def f
272.10 -
272.11 -
272.12 -x = MyTest()
272.13 -
272.14 -
272.15 -
272.16 -
273.1 --- a/python.editor/test/unit/data/testfiles/errors7.py Sun Jan 04 13:11:53 2015 -0600
273.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
273.3 @@ -1,6 +0,0 @@
273.4 -# From issue http://www.netbeans.org/issues/show_bug.cgi?id=155904
273.5 -def main():
273.6 - if "hallo" == "hallo":
273.7 - pass
273.8 - elif 1 =
273.9 -
274.1 --- a/python.editor/test/unit/data/testfiles/errors8.py Sun Jan 04 13:11:53 2015 -0600
274.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
274.3 @@ -1,218 +0,0 @@
274.4 -##############################################################################
274.5 -# Test Runner for NetBeans, based on the unittest TextTestRunner (but prints
274.6 -# out more information during execution that is parsed and swallowed by the
274.7 -# NetBeans test runner GUI.)
274.8 -#
274.9 -# Tor Norbye <tor@netbeans.org> Dec 20 2008
274.10 -##############################################################################
274.11 -
274.12 -import sys
274.13 -import time
274.14 -from optparse import OptionParser
274.15 -import os
274.16 -from unittest import TestResult
274.17 -
274.18 -class _NbWritelnDecorator:
274.19 - """Used to decorate file-like objects with a handy 'writeln' method"""
274.20 - def __init__(self, stream):
274.21 - self.stream = stream
274.22 -
274.23 - def __getattr__(self, attr):
274.24 - return getattr(self.stream, attr)
274.25 -
274.26 - def writeln(self, arg=None):
274.27 - if arg: self.write(arg)
274.28 - self.write('\n') # text-mode streams translate to \r\n if needed
274.29 -
274.30 -class _NbTextTestResult(TestResult):
274.31 - """
274.32 - A test result class that can print specially formatted test status messages for use by
274.33 - the GUI test runner in the NetBeans IDE.
274.34 - """
274.35 -
274.36 - def __init__(self, stream):
274.37 - TestResult.__init__(self)
274.38 - self.stream = stream
274.39 - self._start_time = None
274.40 -
274.41 - def getDescription(self, test):
274.42 - return str(test)
274.43 -
274.44 - def startTest(self, test):
274.45 - TestResult.startTest(self, test)
274.46 - self.stream.writeln("%%TEST_STARTED%% %s" % self.getDescription(test))
274.47 - self._start_time = time.time()
274.48 -
274.49 -
274.50 - def addSuccess(self, test):
274.51 - time_taken = time.time() - self._start_time
274.52 - TestResult.addSuccess(self, test)
274.53 - self.stream.writeln("%%TEST_FINISHED%% time=%.6f %s" % (time_taken, self.getDescription(test)))
274.54 -
274.55 - def _generate_stack(self, tb):
274.56 - # Default stack format:
274.57 - #stack = traceback.format_tb(tb)
274.58 - #stackstr = ""
274.59 - #for line in stack:
274.60 - # stackstr += line
274.61 - #stackstr = stackstr.replace('\n', '%BR%')
274.62 -
274.63 - # More compact stack format
274.64 - stackstr = ""
274.65 - stack = []
274.66 - while tb:
274.67 - stack.append(tb.tb_frame)
274.68 - tb = tb.tb_next
274.69 - stack.reverse()
274.70 - for frame in stack:
274.71 - stackstr += "%s() in %s:%s%%BR%%" % (frame.f_code.co_name,
274.72 - frame.f_code.co_filename,
274.73 - frame.f_lineno)
274.74 -
274.75 - return stackstr
274.76 -
274.77 - def _handle_doctest(self, message, stackstr):
274.78 - if x.startswith("Failed doctest test for "
274.79 -
274.80 - return (message, stackstr)
274.81 -
274.82 - def addError(self, test, err):
274.83 - time_taken = time.time() - self._start_time
274.84 - TestResult.addError(self, test, err)
274.85 - (error, message, tb) = err
274.86 - stackstr = self._generate_stack(tb)
274.87 - (message, stackstr) = self._handle_doctest(message, stackstr)
274.88 - self.stream.writeln("%%TEST_ERROR%% time=%.6f testname=%s message=%s location=%s" %
274.89 - (time_taken, self.getDescription(test), str(message).replace('\n', '%BR%'), stackstr))
274.90 -
274.91 - def addFailure(self, test, err):
274.92 - time_taken = time.time() - self._start_time
274.93 - TestResult.addFailure(self, test, err)
274.94 -
274.95 - (error, message, tb) = err
274.96 - stackstr = self._generate_stack(tb)
274.97 - self.stream.writeln("%%TEST_FAILED%% time=%.6f testname=%s message=%s location=%s" %
274.98 - (time_taken, self.getDescription(test), str(message).replace('\n', '%BR%'), stackstr))
274.99 -
274.100 - def printErrors(self):
274.101 - pass
274.102 -
274.103 - def printErrorList(self, flavour, errors):
274.104 - pass
274.105 -
274.106 -
274.107 -class _NetBeansTestRunner:
274.108 - """A test runner class that displays results in textual form.
274.109 -
274.110 - It prints out the names of tests as they are run, errors as they
274.111 - occur, and a summary of the results at the end of the test run.
274.112 - """
274.113 - def __init__(self, stream=sys.stdout):
274.114 - self.stream = _NbWritelnDecorator(stream)
274.115 -
274.116 -
274.117 - def _makeResult(self):
274.118 - return _NbTextTestResult(self.stream)
274.119 -
274.120 - def _get_suite_name(self, test):
274.121 - if (hasattr(test, "_tests")):
274.122 - name_set = set()
274.123 - for o in test._tests:
274.124 - for s in o._tests:
274.125 - name_set.add(s.__class__)
274.126 - name = ""
274.127 - for s in name_set:
274.128 - if (len(name) > 0):
274.129 - name += ","
274.130 - #name += s.__module__ + '.' + s.__name__
274.131 - name += s.__name__
274.132 - return name;
274.133 - else:
274.134 - class_ = test.__class__
274.135 - classname = class_.__module__ + "." + class_.__name__
274.136 - return classname
274.137 -
274.138 - def run(self, test):
274.139 - "Run the given test case or test suite."
274.140 - suite_name = self._get_suite_name(test)
274.141 - self.stream.writeln("%%SUITE_STARTING%% %s" % suite_name)
274.142 - result = self._makeResult()
274.143 - startTime = time.time()
274.144 - test(result)
274.145 - stopTime = time.time()
274.146 - timeTaken = stopTime - startTime
274.147 - result.printErrors()
274.148 - if not result.wasSuccessful():
274.149 - failed, errored = map(len, (result.failures, result.errors))
274.150 - if failed:
274.151 - self.stream.writeln("%%SUITE_FAILURES%% %d" % failed)
274.152 - if errored:
274.153 - self.stream.writeln("%%SUITE_ERRORS%% %d" % errored)
274.154 - else:
274.155 - print "%SUITE_SUCCESS%"
274.156 - self.stream.writeln("%%SUITE_FINISHED%% time=%.4f" % timeTaken)
274.157 - return result
274.158 -
274.159 -##############################################################################
274.160 -# Driver for running tests from NetBeans
274.161 -##############################################################################
274.162 -if __name__ == '__main__':
274.163 - import unittest
274.164 - import doctest
274.165 -
274.166 - parser = OptionParser(usage="%prog <[--method <name> ]--file|--directory> <files/directories...>", version="%prog 1.0")
274.167 - parser.add_option("-f", "--file",
274.168 - action="store_true", dest="filename",
274.169 - help="Test the given file")
274.170 - parser.add_option("-m", "--method",
274.171 - action="store", type="string", dest="method",
274.172 - help="Test the given method")
274.173 - parser.add_option("-d", "--directory",
274.174 - action="store_true", dest="directory",
274.175 - help="Test the given directory")
274.176 - (options, args) = parser.parse_args()
274.177 - if len(args) == 0:
274.178 - parser.error("Don't forget to specify files/directories")
274.179 - if (options.method and not options.filename):
274.180 - parser.error("must specify --file if you specify --method")
274.181 - if (options.filename and options.directory):
274.182 - parser.error("--directory and --file are mutually exclusive")
274.183 - if (not options.filename and not options.directory):
274.184 - parser.error("You must specify at least one of --file, --method and --directory")
274.185 -
274.186 - if options.filename or options.method:
274.187 - if len(args) > 1:
274.188 - parser.error("You can only specify one file with --file")
274.189 - file_name = args[0]
274.190 - module_name = os.path.splitext(file_name)[0:-1][0]
274.191 - module = __import__(module_name, globals(), locals(), module_name)
274.192 - if (options.method):
274.193 - suite = unittest.TestLoader().loadTestsFromName(options.method, module)
274.194 - else:
274.195 - suite = unittest.TestLoader().loadTestsFromModule(module)
274.196 - # Doctest
274.197 - suite.addTest(doctest.DocTestSuite(module))
274.198 -
274.199 - else:
274.200 - assert options.directory;
274.201 - test_modules = []
274.202 - for dir in args:
274.203 - file_list = os.listdir(dir)
274.204 - for file_name in file_list:
274.205 - extension = os.path.splitext(file_name)[-1]
274.206 - if extension == '.py':
274.207 - test_module_name = os.path.splitext(file_name)[0:-1][0]
274.208 - try:
274.209 - module = __import__(test_module_name, globals(), locals(), test_module_name)
274.210 - test_modules.append(module)
274.211 - except:
274.212 - # No complaints - just test the files we can (user may have run
274.213 - # test project on an unfinished project where not all files are valid)
274.214 - pass
274.215 - suite = unittest.TestSuite(map(unittest.defaultTestLoader.loadTestsFromModule, test_modules))
274.216 - # Doctest
274.217 - for module in test_modules:
274.218 - suite.addTest(doctest.DocTestSuite(module))
274.219 -
274.220 - # Run all the tests
274.221 - _NetBeansTestRunner().run(suite)
275.1 --- a/python.editor/test/unit/data/testfiles/errors9.py Sun Jan 04 13:11:53 2015 -0600
275.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
275.3 @@ -1,265 +0,0 @@
275.4 -##############################################################################
275.5 -# Test Runner for NetBeans, based on the unittest TextTestRunner (but prints
275.6 -# out more information during execution that is parsed and swallowed by the
275.7 -# NetBeans test runner GUI.)
275.8 -#
275.9 -# Tor Norbye <tor@netbeans.org> Dec 20 2008
275.10 -##############################################################################
275.11 -
275.12 -import sys
275.13 -import time
275.14 -from optparse import OptionParser
275.15 -import os
275.16 -import re
275.17 -from unittest import TestResult
275.18 -
275.19 -class _NbWritelnDecorator:
275.20 - """Used to decorate file-like objects with a handy 'writeln' method"""
275.21 - def __init__(self, stream):
275.22 - self.stream = stream
275.23 -
275.24 - def __getattr__(self, attr):
275.25 - return getattr(self.stream, attr)
275.26 -
275.27 - def writeln(self, arg=None):
275.28 - if arg: self.write(arg)
275.29 - self.write('\n') # text-mode streams translate to \r\n if needed
275.30 -
275.31 -class _NbTextTestResult(TestResult):
275.32 - """
275.33 - A test result class that can print specially formatted test status messages for use by
275.34 - the GUI test runner in the NetBeans IDE.
275.35 - """
275.36 -
275.37 - def __init__(self, stream):
275.38 - TestResult.__init__(self)
275.39 - self.stream = stream
275.40 - self._start_time = None
275.41 -
275.42 - def getDescription(self, test):
275.43 - return str(test)
275.44 -
275.45 - def startTest(self, test):
275.46 - TestResult.startTest(self, test)
275.47 - self.stream.writeln("%%TEST_STARTED%% %s" % self.getDescription(test))
275.48 - self._start_time = time.time()
275.49 -
275.50 -
275.51 - def addSuccess(self, test):
275.52 - time_taken = time.time() - self._start_time
275.53 - TestResult.addSuccess(self, test)
275.54 - self.stream.writeln("%%TEST_FINISHED%% time=%.6f %s" % (time_taken, self.getDescription(test)))
275.55 -
275.56 - def _generate_stack(self, tb):
275.57 - # Default stack format:
275.58 - #stack = traceback.format_tb(tb)
275.59 - #stackstr = ""
275.60 - #for line in stack:
275.61 - # stackstr += line
275.62 - #stackstr = stackstr.replace('\n', '%BR%')
275.63 -
275.64 - # More compact stack format
275.65 - stackstr = ""
275.66 - stack = []
275.67 - while tb:
275.68 - stack.append(tb.tb_frame)
275.69 - tb = tb.tb_next
275.70 - stack.reverse()
275.71 - for frame in stack:
275.72 - stackstr += "%s() in %s:%s%%BR%%" % (frame.f_code.co_name,
275.73 - frame.f_code.co_filename,
275.74 - frame.f_lineno)
275.75 -
275.76 - return stackstr
275.77 -
275.78 - def _handle_doctest(self, message, stackstr):
275.79 - message_str = str(message)
275.80 - if message_str.startswith("Failed doctest test for "):
275.81 - # From doctest.py:
275.82 - #return ('Failed doctest test for %s\n'
275.83 - # ' File "%s", line %s, in %s\n\n%s'
275.84 - # % (test.name, test.filename, lineno, lname, err)
275.85 -
275.86 - m = re.match('Failed doctest test for (.*)\n'
275.87 - ' File "(.*)", line (.*), in (.*)\n\n(.*)', message_str)
275.88 - print "Match was " + str(m)
275.89 - if m:
275.90 - test_name = m.group(1)
275.91 - filename = m.group(2)
275.92 - lineno = m.group(3)
275.93 - lname = m.group(4)
275.94 - err = m.group(5)
275.95 -
275.96 - print "test_name = " + test_name
275.97 - print "filename = " + filename
275.98 - print "lineno = " + lineno
275.99 - print "lname = " + lname
275.100 -# print "err = " + err
275.101 -
275.102 - # From output_difference() in doctest
275.103 -----------------------------------------------------------------------
275.104 -File "/Users/tor/Downloads/diveintopython-5.4/py/roman/stage9/pythontest.py", line 20, in pythontest.factorial
275.105 -Failed example:
275.106 - factorial(30L)
275.107 -Expected:
275.108 - 265252859812191058636308480000000L
275.109 -Got:
275.110 - 132626429906095529318154240000000L
275.111 -
275.112 -
275.113 - if want and got:
275.114 - return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
275.115 - elif want:
275.116 - return 'Expected:\n%sGot nothing\n' % _indent(want)
275.117 - elif got:
275.118 - return 'Expected nothing\nGot:\n%s' % _indent(got)
275.119 - else:
275.120 - return 'Expected nothing\nGot nothing\n'
275.121 -
275.122 -
275.123 - # Modify stack and message
275.124 - message = message_str[m.start(5):]
275.125 - stackstr = test_name + "() in " + filename + ":" + lineno + "%BR%"
275.126 -
275.127 - return (message, stackstr)
275.128 -
275.129 - def addError(self, test, err):
275.130 - time_taken = time.time() - self._start_time
275.131 - TestResult.addError(self, test, err)
275.132 - (error, message, tb) = err
275.133 - stackstr = self._generate_stack(tb)
275.134 - self.stream.writeln("%%TEST_ERROR%% time=%.6f testname=%s message=%s location=%s" %
275.135 - (time_taken, self.getDescription(test), str(message).replace('\n', '%BR%'), stackstr))
275.136 -
275.137 - def addFailure(self, test, err):
275.138 - time_taken = time.time() - self._start_time
275.139 - TestResult.addFailure(self, test, err)
275.140 -
275.141 - (error, message, tb) = err
275.142 - stackstr = self._generate_stack(tb)
275.143 - (message, stackstr) = self._handle_doctest(message, stackstr)
275.144 - self.stream.writeln("%%TEST_FAILED%% time=%.6f testname=%s message=%s location=%s" %
275.145 - (time_taken, self.getDescription(test), str(message).replace('\n', '%BR%'), stackstr))
275.146 -
275.147 - def printErrors(self):
275.148 - pass
275.149 -
275.150 - def printErrorList(self, flavour, errors):
275.151 - pass
275.152 -
275.153 -
275.154 -class _NetBeansTestRunner:
275.155 - """A test runner class that displays results in textual form.
275.156 -
275.157 - It prints out the names of tests as they are run, errors as they
275.158 - occur, and a summary of the results at the end of the test run.
275.159 - """
275.160 - def __init__(self, stream=sys.stdout):
275.161 - self.stream = _NbWritelnDecorator(stream)
275.162 -
275.163 -
275.164 - def _makeResult(self):
275.165 - return _NbTextTestResult(self.stream)
275.166 -
275.167 - def _get_suite_name(self, test):
275.168 - if (hasattr(test, "_tests")):
275.169 - name_set = set()
275.170 - for o in test._tests:
275.171 - for s in o._tests:
275.172 - name_set.add(s.__class__)
275.173 - name = ""
275.174 - for s in name_set:
275.175 - if (len(name) > 0):
275.176 - name += ","
275.177 - #name += s.__module__ + '.' + s.__name__
275.178 - name += s.__name__
275.179 - return name;
275.180 - else:
275.181 - class_ = test.__class__
275.182 - classname = class_.__module__ + "." + class_.__name__
275.183 - return classname
275.184 -
275.185 - def run(self, test):
275.186 - "Run the given test case or test suite."
275.187 - suite_name = self._get_suite_name(test)
275.188 - self.stream.writeln("%%SUITE_STARTING%% %s" % suite_name)
275.189 - result = self._makeResult()
275.190 - startTime = time.time()
275.191 - test(result)
275.192 - stopTime = time.time()
275.193 - timeTaken = stopTime - startTime
275.194 - result.printErrors()
275.195 - if not result.wasSuccessful():
275.196 - failed, errored = map(len, (result.failures, result.errors))
275.197 - if failed:
275.198 - self.stream.writeln("%%SUITE_FAILURES%% %d" % failed)
275.199 - if errored:
275.200 - self.stream.writeln("%%SUITE_ERRORS%% %d" % errored)
275.201 - else:
275.202 - print "%SUITE_SUCCESS%"
275.203 - self.stream.writeln("%%SUITE_FINISHED%% time=%.4f" % timeTaken)
275.204 - return result
275.205 -
275.206 -##############################################################################
275.207 -# Driver for running tests from NetBeans
275.208 -##############################################################################
275.209 -if __name__ == '__main__':
275.210 - import unittest
275.211 - import doctest
275.212 -
275.213 - parser = OptionParser(usage="%prog <[--method <name> ]--file|--directory> <files/directories...>", version="%prog 1.0")
275.214 - parser.add_option("-f", "--file",
275.215 - action="store_true", dest="filename",
275.216 - help="Test the given file")
275.217 - parser.add_option("-m", "--method",
275.218 - action="store", type="string", dest="method",
275.219 - help="Test the given method")
275.220 - parser.add_option("-d", "--directory",
275.221 - action="store_true", dest="directory",
275.222 - help="Test the given directory")
275.223 - (options, args) = parser.parse_args()
275.224 - if len(args) == 0:
275.225 - parser.error("Don't forget to specify files/directories")
275.226 - if (options.method and not options.filename):
275.227 - parser.error("must specify --file if you specify --method")
275.228 - if (options.filename and options.directory):
275.229 - parser.error("--directory and --file are mutually exclusive")
275.230 - if (not options.filename and not options.directory):
275.231 - parser.error("You must specify at least one of --file, --method and --directory")
275.232 -
275.233 - if options.filename or options.method:
275.234 - if len(args) > 1:
275.235 - parser.error("You can only specify one file with --file")
275.236 - file_name = args[0]
275.237 - module_name = os.path.splitext(file_name)[0:-1][0]
275.238 - module = __import__(module_name, globals(), locals(), module_name)
275.239 - if (options.method):
275.240 - suite = unittest.TestLoader().loadTestsFromName(options.method, module)
275.241 - else:
275.242 - suite = unittest.TestLoader().loadTestsFromModule(module)
275.243 - # Doctest
275.244 - suite.addTest(doctest.DocTestSuite(module))
275.245 -
275.246 - else:
275.247 - assert options.directory;
275.248 - test_modules = []
275.249 - for dir in args:
275.250 - file_list = os.listdir(dir)
275.251 - for file_name in file_list:
275.252 - extension = os.path.splitext(file_name)[-1]
275.253 - if extension == '.py':
275.254 - test_module_name = os.path.splitext(file_name)[0:-1][0]
275.255 - try:
275.256 - module = __import__(test_module_name, globals(), locals(), test_module_name)
275.257 - test_modules.append(module)
275.258 - except:
275.259 - # No complaints - just test the files we can (user may have run
275.260 - # test project on an unfinished project where not all files are valid)
275.261 - pass
275.262 - suite = unittest.TestSuite(map(unittest.defaultTestLoader.loadTestsFromModule, test_modules))
275.263 - # Doctest
275.264 - for module in test_modules:
275.265 - suite.addTest(doctest.DocTestSuite(module))
275.266 -
275.267 - # Run all the tests
275.268 - _NetBeansTestRunner().run(suite)
276.1 --- a/python.editor/test/unit/data/testfiles/exceptas.py Sun Jan 04 13:11:53 2015 -0600
276.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
276.3 @@ -1,32 +0,0 @@
276.4 -import sys
276.5 -print "Hello from " + sys.version
276.6 -def foo():
276.7 - pass
276.8 -def bar():
276.9 - pass
276.10 -
276.11 -try:
276.12 - foo()
276.13 -except Foo as x:
276.14 - bar()
276.15 -finally:
276.16 - pass
276.17 -
276.18 -class MyError(Exception):
276.19 - def extra(self):
276.20 - pass
276.21 -
276.22 -def test1():
276.23 - try:
276.24 - pass
276.25 - except EOFError:
276.26 - print "No var"
276.27 - except MyError, ex:
276.28 - print "Got error with %" % ex.e
276.29 -
276.30 -def test2():
276.31 - try:
276.32 - pass
276.33 - except MyError as ex2:
276.34 - print "Got error with %" % ex2.e
276.35 -
277.1 --- a/python.editor/test/unit/data/testfiles/extract1.py Sun Jan 04 13:11:53 2015 -0600
277.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
277.3 @@ -1,25 +0,0 @@
277.4 -class ExtractTest:
277.5 - def extract_test1(self, param_read_in_block, param_read_after_block, default_param=4):
277.6 - local1 = 1
277.7 - local2 = local1
277.8 - not_used_in_block = 1
277.9 - reassigned_in_block_before_read = 2
277.10 - read_in_block_only = 3
277.11 - read_after_block_only = 4
277.12 -
277.13 - # Beginning of extraction segment
277.14 - read_after_block = 5
277.15 - reassigned_after_block = 6
277.16 - reassigned_in_block_before_read = 7
277.17 - print reassigned_in_block_before_read
277.18 - print read_in_block_only
277.19 - print param_read_in_block
277.20 - # End of extraction segment
277.21 -
277.22 - print local1
277.23 - print read_after_block
277.24 - reassigned_after_block = 7
277.25 - print reassigned_after_block
277.26 - print not_used_in_block
277.27 - print param_read_after_block
277.28 -
278.1 --- a/python.editor/test/unit/data/testfiles/extract1.py.testFix1.fixed Sun Jan 04 13:11:53 2015 -0600
278.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
278.3 @@ -1,31 +0,0 @@
278.4 -class ExtractTest:
278.5 - def extract_test1(self, param_read_in_block, param_read_after_block, default_param=4):
278.6 - local1 = 1
278.7 - local2 = local1
278.8 - not_used_in_block = 1
278.9 - reassigned_in_block_before_read = 2
278.10 - read_in_block_only = 3
278.11 - read_after_block_only = 4
278.12 -
278.13 - read_after_block = |>new_name<|(self, param_read_in_block, read_in_block_only)
278.14 -
278.15 - print local1
278.16 - print read_after_block
278.17 - reassigned_after_block = 7
278.18 - print reassigned_after_block
278.19 - print not_used_in_block
278.20 - print param_read_after_block
278.21 -
278.22 - def |>^new_name<|(self, param_read_in_block, read_in_block_only):
278.23 - # Beginning of extraction segment
278.24 - read_after_block = 5
278.25 - reassigned_after_block = 6
278.26 - reassigned_in_block_before_read = 7
278.27 - print reassigned_in_block_before_read
278.28 - print read_in_block_only
278.29 - print param_read_in_block
278.30 - # End of extraction segment
278.31 -
278.32 - return read_after_block
278.33 -
278.34 -
279.1 --- a/python.editor/test/unit/data/testfiles/extract1.py.testFix1b.fixed Sun Jan 04 13:11:53 2015 -0600
279.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
279.3 @@ -1,31 +0,0 @@
279.4 -class ExtractTest:
279.5 - def extract_test1(self, param_read_in_block, param_read_after_block, default_param=4):
279.6 - local1 = 1
279.7 - local2 = local1
279.8 - not_used_in_block = 1
279.9 - reassigned_in_block_before_read = 2
279.10 - read_in_block_only = 3
279.11 - read_after_block_only = 4
279.12 -
279.13 - read_after_block = |>new_name<|(self, param_read_in_block, read_in_block_only)
279.14 -
279.15 - print local1
279.16 - print read_after_block
279.17 - reassigned_after_block = 7
279.18 - print reassigned_after_block
279.19 - print not_used_in_block
279.20 - print param_read_after_block
279.21 -
279.22 - def |>^new_name<|(self, param_read_in_block, read_in_block_only):
279.23 - # Beginning of extraction segment
279.24 - read_after_block = 5
279.25 - reassigned_after_block = 6
279.26 - reassigned_in_block_before_read = 7
279.27 - print reassigned_in_block_before_read
279.28 - print read_in_block_only
279.29 - print param_read_in_block
279.30 - # End of extraction segment
279.31 -
279.32 - return read_after_block
279.33 -
279.34 -
280.1 --- a/python.editor/test/unit/data/testfiles/extract1.py.testFix7.fixed Sun Jan 04 13:11:53 2015 -0600
280.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
280.3 @@ -1,31 +0,0 @@
280.4 -class ExtractTest:
280.5 - def extract_test1(self, param_read_in_block, param_read_after_block, default_param=4):
280.6 - local1 = 1
280.7 - local2 = local1
280.8 - not_used_in_block,read_in_block_only = |>new_name<|(self)
280.9 -
280.10 - # Beginning of extraction segment
280.11 - read_after_block = 5
280.12 - reassigned_after_block = 6
280.13 - reassigned_in_block_before_read = 7
280.14 - print reassigned_in_block_before_read
280.15 - print read_in_block_only
280.16 - print param_read_in_block
280.17 - # End of extraction segment
280.18 -
280.19 - print local1
280.20 - print read_after_block
280.21 - reassigned_after_block = 7
280.22 - print reassigned_after_block
280.23 - print not_used_in_block
280.24 - print param_read_after_block
280.25 -
280.26 - def |>^new_name<|(self):
280.27 - not_used_in_block = 1
280.28 - reassigned_in_block_before_read = 2
280.29 - read_in_block_only = 3
280.30 - read_after_block_only = 4
280.31 -
280.32 - return not_used_in_block,read_in_block_only
280.33 -
280.34 -
281.1 --- a/python.editor/test/unit/data/testfiles/extract1.py.testHint1.hints Sun Jan 04 13:11:53 2015 -0600
281.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
281.3 @@ -1,5 +0,0 @@
281.4 - # Beginning of extraction segment
281.5 -
281.6 -HINT:Extract Code
281.7 -FIX:Extract Method
281.8 - # End of extraction segment^
282.1 --- a/python.editor/test/unit/data/testfiles/extract2.py Sun Jan 04 13:11:53 2015 -0600
282.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
282.3 @@ -1,5 +0,0 @@
282.4 -not_used = 1
282.5 -simple_code = 1
282.6 -simple_code = simple_code+1
282.7 -print simple_code + not_used
282.8 -
283.1 --- a/python.editor/test/unit/data/testfiles/extract2.py.testFix2.fixed Sun Jan 04 13:11:53 2015 -0600
283.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
283.3 @@ -1,11 +0,0 @@
283.4 -not_used = 1
283.5 -
283.6 -def |>^new_name<|():
283.7 - simple_code = 1
283.8 - simple_code = simple_code+1
283.9 -
283.10 - return simple_code
283.11 -
283.12 -simple_code = |>new_name<|()
283.13 -print simple_code + not_used
283.14 -
284.1 --- a/python.editor/test/unit/data/testfiles/extract2.py.testFix3.fixed Sun Jan 04 13:11:53 2015 -0600
284.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
284.3 @@ -1,9 +0,0 @@
284.4 -
284.5 -def |>^new_name<|():
284.6 - not_used = 1
284.7 - simple_code = 1
284.8 - simple_code = simple_code+1
284.9 - print simple_code + not_used
284.10 -
284.11 -|>new_name<|()
284.12 -
285.1 --- a/python.editor/test/unit/data/testfiles/extract3.py Sun Jan 04 13:11:53 2015 -0600
285.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
285.3 @@ -1,10 +0,0 @@
285.4 -
285.5 -__author__="tor"
285.6 -__date__ ="$Oct 12, 2008 7:19:09 PM$"
285.7 -
285.8 -if __name__ == "__main__":
285.9 - print "Hello";
285.10 - preprocess(foo, source, output_file, macros, include_dirs, extra_preargs, extra_postargs);
285.11 - get_preprocess(self, source, output_file, macros, include_dirs, extra_preargs, extra_postargs)
285.12 -
285.13 -
286.1 --- a/python.editor/test/unit/data/testfiles/extract4.py Sun Jan 04 13:11:53 2015 -0600
286.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
286.3 @@ -1,10 +0,0 @@
286.4 -
286.5 -__author__="tor"
286.6 -__date__ ="$Oct 22, 2008 2:06:12 PM$"
286.7 -
286.8 -if __name__ == "__main__":
286.9 - if _a >a:
286.10 - c = a
286.11 - else
286.12 - c = b
286.13 -
287.1 --- a/python.editor/test/unit/data/testfiles/extract4.py.testFix5.fixed Sun Jan 04 13:11:53 2015 -0600
287.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
287.3 @@ -1,14 +0,0 @@
287.4 -
287.5 -__author__="tor"
287.6 -__date__ ="$Oct 22, 2008 2:06:12 PM$"
287.7 -
287.8 -
287.9 -def |>^new_name<|(_a, a, b):
287.10 - if _a >a:
287.11 - c = a
287.12 - else
287.13 - c = b
287.14 -
287.15 -if __name__ == "__main__":
287.16 - |>new_name<|(_a, a, b)
287.17 -
288.1 --- a/python.editor/test/unit/data/testfiles/extract5.py Sun Jan 04 13:11:53 2015 -0600
288.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
288.3 @@ -1,4 +0,0 @@
288.4 -if _a >a:
288.5 - c = a
288.6 -else
288.7 - c = b
289.1 --- a/python.editor/test/unit/data/testfiles/extract5.py.testFix6.fixed Sun Jan 04 13:11:53 2015 -0600
289.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
289.3 @@ -1,8 +0,0 @@
289.4 -
289.5 -def |>^new_name<|(_a, a, b):
289.6 - if _a >a:
289.7 - c = a
289.8 - else
289.9 - c = b
289.10 -
289.11 -|>new_name<|(_a, a, b)
290.1 --- a/python.editor/test/unit/data/testfiles/formatting.py Sun Jan 04 13:11:53 2015 -0600
290.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
290.3 @@ -1,40 +0,0 @@
290.4 -def func( args , without , commas, arg=3,arg = 4):
290.5 - if pos!=-1 and optval[ pos-1 ].isspace():
290.6 - pass
290.7 -def func2( aargs ):
290.8 - pass
290.9 -
290.10 -def func3( arrrrgs, arg2 ):
290.11 - pass
290.12 -
290.13 -x+=1
290.14 -y+=2
290.15 -z=3
290.16 -d = 4
290.17 -if d==4:
290.18 - pass
290.19 -x = `foo`
290.20 -
290.21 -class Test:
290.22 - @property
290.23 - def scheme(self):
290.24 - return self[ 0 ]
290.25 -
290.26 -x = ((500+30)*(470))
290.27 -# x=1,y=2
290.28 -modeDict = { 'r' : 'rb', 'w' : 'wb', 'a': 'r+b' }
290.29 -modeDict2 = {'r':'rb', 'w':'wb', 'a': 'r+b'}
290.30 -x = 2 ; y=3 ; z = 5
290.31 -
290.32 -if d==5:
290.33 - pass
290.34 -
290.35 -output=`dmesg | grep hda`
290.36 -
290.37 -SECTCRE = re.compile(
290.38 - r'\[' # [
290.39 - r'(?P<header>[^]]+)' # very permissive!
290.40 - r'\]' # ]
290.41 - )
290.42 -
290.43 -
291.1 --- a/python.editor/test/unit/data/testfiles/formatting.py.formatted Sun Jan 04 13:11:53 2015 -0600
291.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
291.3 @@ -1,40 +0,0 @@
291.4 -def func(args, without, commas, arg=3, arg=4):
291.5 - if pos != -1 and optval[pos-1].isspace():
291.6 - pass
291.7 -def func2(aargs):
291.8 - pass
291.9 -
291.10 -def func3(arrrrgs, arg2):
291.11 - pass
291.12 -
291.13 -x += 1
291.14 -y += 2
291.15 -z = 3
291.16 -d = 4
291.17 -if d == 4:
291.18 - pass
291.19 -x = `foo`
291.20 -
291.21 -class Test:
291.22 - @property
291.23 - def scheme(self):
291.24 - return self[0]
291.25 -
291.26 -x = ((500 + 30) * (470))
291.27 -# x=1,y=2
291.28 -modeDict = {'r': 'rb', 'w': 'wb', 'a': 'r+b'}
291.29 -modeDict2 = {'r':'rb', 'w':'wb', 'a': 'r+b'}
291.30 -x = 2; y = 3; z = 5
291.31 -
291.32 -if d == 5:
291.33 - pass
291.34 -
291.35 -output = `dmesg | grep hda`
291.36 -
291.37 -SECTCRE = re.compile(
291.38 - r'\[' # [
291.39 - r'(?P<header>[^]]+)' # very permissive!
291.40 - r'\]' # ]
291.41 - )
291.42 -
291.43 -
292.1 --- a/python.editor/test/unit/data/testfiles/formatting.py.scopes Sun Jan 04 13:11:53 2015 -0600
292.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
292.3 @@ -1,46 +0,0 @@
292.4 -=============================================
292.5 -<file-top>: Module : OffsetRange[0,691>
292.6 -SECTCRE [bound][data][node=Name]
292.7 -Test [bound][class][def][node=ClassDef]
292.8 -d [bound][data][read][node=Name]
292.9 -dmesg [read][UNRESOLVED][node=Name]
292.10 -foo [read][UNRESOLVED][node=Name]
292.11 -func [bound][function][def][node=FunctionDef]
292.12 -func2 [bound][function][def][node=FunctionDef]
292.13 -func3 [bound][function][def][node=FunctionDef]
292.14 -grep [read][UNRESOLVED][node=Name]
292.15 -modeDict [bound][data][node=Name]
292.16 -modeDict2 [bound][data][node=Name]
292.17 -output [bound][data][node=Name]
292.18 -re [read][UNRESOLVED][node=Name]
292.19 -x [bound][data][node=Name]
292.20 -y [bound][data][node=Name]
292.21 -z [bound][data][node=Name]
292.22 -
292.23 - =============================================
292.24 - func: FunctionDef : OffsetRange[0,119>
292.25 - arg [bound][param][data][unused][node=Name]
292.26 - args [bound][param][data][unused][node=Name]
292.27 - commas [bound][param][data][unused][node=Name]
292.28 - optval [free][read][node=Name]
292.29 - pos [free][read][node=Name]
292.30 - without [bound][param][data][unused][node=Name]
292.31 -
292.32 - =============================================
292.33 - func2: FunctionDef : OffsetRange[119,149>
292.34 - aargs [bound][param][data][unused][node=Name]
292.35 -
292.36 - =============================================
292.37 - func3: FunctionDef : OffsetRange[149,190>
292.38 - arg2 [bound][param][data][unused][node=Name]
292.39 - arrrrgs [bound][param][data][unused][node=Name]
292.40 -
292.41 - =============================================
292.42 - class Test: ClassDef : OffsetRange[243,317>
292.43 - property [free][read][node=Name]
292.44 - scheme [bound][function][def][node=FunctionDef]
292.45 -
292.46 - =============================================
292.47 - scheme: FunctionDef : OffsetRange[259,317>
292.48 - self [bound][param][data][read][node=Name]
292.49 -
293.1 --- a/python.editor/test/unit/data/testfiles/fromimports.py Sun Jan 04 13:11:53 2015 -0600
293.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
293.3 @@ -1,3 +0,0 @@
293.4 -from distutils import core
293.5 -core.g
293.6 -
294.1 --- a/python.editor/test/unit/data/testfiles/fromimports.py.testFromImports.completion Sun Jan 04 13:11:53 2015 -0600
294.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
294.3 @@ -1,17 +0,0 @@
294.4 -Code completion result for source line:
294.5 -core.|g
294.6 -(QueryType=COMPLETION, NameKind=PREFIX)
294.7 -MODULE Command
294.8 -MODULE DEBUG
294.9 -MODULE Distribution
294.10 -MODULE Extension
294.11 -MODULE grok_environment_error
294.12 -MODULE os
294.13 -MODULE sys
294.14 -METHOD gen_usage(script_name)
294.15 -METHOD run_setup(script_name, script_
294.16 -METHOD setup(attrs)
294.17 -VARIABLE USAGE
294.18 -VARIABLE __revision__
294.19 -VARIABLE extension_keywords
294.20 -VARIABLE setup_keywords
295.1 --- a/python.editor/test/unit/data/testfiles/futureimport.py Sun Jan 04 13:11:53 2015 -0600
295.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
295.3 @@ -1,4 +0,0 @@
295.4 -# Ensure that the future imports here aren't shown as unused or imported symbols for code completion
295.5 -from __future__ import absolute_imports, with_statement
295.6 -with_stateme # Call
295.7 -
296.1 --- a/python.editor/test/unit/data/testfiles/futureimport.py.testFutureImport1.completion Sun Jan 04 13:11:53 2015 -0600
296.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
296.3 @@ -1,3 +0,0 @@
296.4 -Code completion result for source line:
296.5 -from __future__ import |absolute_imports, with_statement
296.6 -(QueryType=COMPLETION, NameKind=PREFIX)
297.1 --- a/python.editor/test/unit/data/testfiles/getopt.py Sun Jan 04 13:11:53 2015 -0600
297.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
297.3 @@ -1,211 +0,0 @@
297.4 -# -*- coding: iso-8859-1 -*-
297.5 -"""Parser for command line options.
297.6 -
297.7 -This module helps scripts to parse the command line arguments in
297.8 -sys.argv. It supports the same conventions as the Unix getopt()
297.9 -function (including the special meanings of arguments of the form `-'
297.10 -and `--'). Long options similar to those supported by GNU software
297.11 -may be used as well via an optional third argument. This module
297.12 -provides two functions and an exception:
297.13 -
297.14 -getopt() -- Parse command line options
297.15 -gnu_getopt() -- Like getopt(), but allow option and non-option arguments
297.16 -to be intermixed.
297.17 -GetoptError -- exception (class) raised with 'opt' attribute, which is the
297.18 -option involved with the exception.
297.19 -"""
297.20 -
297.21 -# Long option support added by Lars Wirzenius <liw@iki.fi>.
297.22 -#
297.23 -# Gerrit Holl <gerrit@nl.linux.org> moved the string-based exceptions
297.24 -# to class-based exceptions.
297.25 -#
297.26 -# Peter Åstrand <astrand@lysator.liu.se> added gnu_getopt().
297.27 -#
297.28 -# TODO for gnu_getopt():
297.29 -#
297.30 -# - GNU getopt_long_only mechanism
297.31 -# - allow the caller to specify ordering
297.32 -# - RETURN_IN_ORDER option
297.33 -# - GNU extension with '-' as first character of option string
297.34 -# - optional arguments, specified by double colons
297.35 -# - a option string with a W followed by semicolon should
297.36 -# treat "-W foo" as "--foo"
297.37 -
297.38 -__all__ = ["GetoptError","error","getopt","gnu_getopt"]
297.39 -
297.40 -import os
297.41 -
297.42 -class GetoptError(Exception):
297.43 - opt = ''
297.44 - msg = ''
297.45 - def __init__(self, msg, opt=''):
297.46 - self.msg = msg
297.47 - self.opt = opt
297.48 - Exception.__init__(self, msg, opt)
297.49 -
297.50 - def __str__(self):
297.51 - return self.msg
297.52 -
297.53 -error = GetoptError # backward compatibility
297.54 -
297.55 -def getopt(args, shortopts, longopts = []):
297.56 - """getopt(args, options[, long_options]) -> opts, args
297.57 -
297.58 - Parses command line options and parameter list. args is the
297.59 - argument list to be parsed, without the leading reference to the
297.60 - running program. Typically, this means "sys.argv[1:]". shortopts
297.61 - is the string of option letters that the script wants to
297.62 - recognize, with options that require an argument followed by a
297.63 - colon (i.e., the same format that Unix getopt() uses). If
297.64 - specified, longopts is a list of strings with the names of the
297.65 - long options which should be supported. The leading '--'
297.66 - characters should not be included in the option name. Options
297.67 - which require an argument should be followed by an equal sign
297.68 - ('=').
297.69 -
297.70 - The return value consists of two elements: the first is a list of
297.71 - (option, value) pairs; the second is the list of program arguments
297.72 - left after the option list was stripped (this is a trailing slice
297.73 - of the first argument). Each option-and-value pair returned has
297.74 - the option as its first element, prefixed with a hyphen (e.g.,
297.75 - '-x'), and the option argument as its second element, or an empty
297.76 - string if the option has no argument. The options occur in the
297.77 - list in the same order in which they were found, thus allowing
297.78 - multiple occurrences. Long and short options may be mixed.
297.79 -
297.80 - """
297.81 -
297.82 - opts = []
297.83 - if type(longopts) == type(""):
297.84 - longopts = [longopts]
297.85 - else:
297.86 - longopts = list(longopts)
297.87 - while args and args[0].startswith('-') and args[0] != '-':
297.88 - if args[0] == '--':
297.89 - args = args[1:]
297.90 - break
297.91 - if args[0].startswith('--'):
297.92 - opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
297.93 - else:
297.94 - opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
297.95 -
297.96 - return opts, args
297.97 -
297.98 -def gnu_getopt(args, shortopts, longopts = []):
297.99 - """getopt(args, options[, long_options]) -> opts, args
297.100 -
297.101 - This function works like getopt(), except that GNU style scanning
297.102 - mode is used by default. This means that option and non-option
297.103 - arguments may be intermixed. The getopt() function stops
297.104 - processing options as soon as a non-option argument is
297.105 - encountered.
297.106 -
297.107 - If the first character of the option string is `+', or if the
297.108 - environment variable POSIXLY_CORRECT is set, then option
297.109 - processing stops as soon as a non-option argument is encountered.
297.110 -
297.111 - """
297.112 -
297.113 - opts = []
297.114 - prog_args = []
297.115 - if isinstance(longopts, str):
297.116 - longopts = [longopts]
297.117 - else:
297.118 - longopts = list(longopts)
297.119 -
297.120 - # Allow options after non-option arguments?
297.121 - if shortopts.startswith('+'):
297.122 - shortopts = shortopts[1:]
297.123 - all_options_first = True
297.124 - elif os.environ.get("POSIXLY_CORRECT"):
297.125 - all_options_first = True
297.126 - else:
297.127 - all_options_first = False
297.128 -
297.129 - while args:
297.130 - if args[0] == '--':
297.131 - prog_args += args[1:]
297.132 - break
297.133 -
297.134 - if args[0][:2] == '--':
297.135 - opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
297.136 - elif args[0][:1] == '-':
297.137 - opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
297.138 - else:
297.139 - if all_options_first:
297.140 - prog_args += args
297.141 - break
297.142 - else:
297.143 - prog_args.append(args[0])
297.144 - args = args[1:]
297.145 -
297.146 - return opts, prog_args
297.147 -
297.148 -def do_longs(opts, opt, longopts, args):
297.149 - try:
297.150 - i = opt.index('=')
297.151 - except ValueError:
297.152 - optarg = None
297.153 - else:
297.154 - opt, optarg = opt[:i], opt[i+1:]
297.155 -
297.156 - has_arg, opt = long_has_args(opt, longopts)
297.157 - if has_arg:
297.158 - if optarg is None:
297.159 - if not args:
297.160 - raise GetoptError('option --%s requires argument' % opt, opt)
297.161 - optarg, args = args[0], args[1:]
297.162 - elif optarg:
297.163 - raise GetoptError('option --%s must not have an argument' % opt, opt)
297.164 - opts.append(('--' + opt, optarg or ''))
297.165 - return opts, args
297.166 -
297.167 -# Return:
297.168 -# has_arg?
297.169 -# full option name
297.170 -def long_has_args(opt, longopts):
297.171 - possibilities = [o for o in longopts if o.startswith(opt)]
297.172 - if not possibilities:
297.173 - raise GetoptError('option --%s not recognized' % opt, opt)
297.174 - # Is there an exact match?
297.175 - if opt in possibilities:
297.176 - return False, opt
297.177 - elif opt + '=' in possibilities:
297.178 - return True, opt
297.179 - # No exact match, so better be unique.
297.180 - if len(possibilities) > 1:
297.181 - # XXX since possibilities contains all valid continuations, might be
297.182 - # nice to work them into the error msg
297.183 - raise GetoptError('option --%s not a unique prefix' % opt, opt)
297.184 - assert len(possibilities) == 1
297.185 - unique_match = possibilities[0]
297.186 - has_arg = unique_match.endswith('=')
297.187 - if has_arg:
297.188 - unique_match = unique_match[:-1]
297.189 - return has_arg, unique_match
297.190 -
297.191 -def do_shorts(opts, optstring, shortopts, args):
297.192 - while optstring != '':
297.193 - opt, optstring = optstring[0], optstring[1:]
297.194 - if short_has_arg(opt, shortopts):
297.195 - if optstring == '':
297.196 - if not args:
297.197 - raise GetoptError('option -%s requires argument' % opt,
297.198 - opt)
297.199 - optstring, args = args[0], args[1:]
297.200 - optarg, optstring = optstring, ''
297.201 - else:
297.202 - optarg = ''
297.203 - opts.append(('-' + opt, optarg))
297.204 - return opts, args
297.205 -
297.206 -def short_has_arg(opt, shortopts):
297.207 - for i in range(len(shortopts)):
297.208 - if opt == shortopts[i] != ':':
297.209 - return shortopts.startswith(':', i+1)
297.210 - raise GetoptError('option -%s not recognized' % opt, opt)
297.211 -
297.212 -if __name__ == '__main__':
297.213 - import sys
297.214 - print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])
298.1 --- a/python.editor/test/unit/data/testfiles/getopt.py.folds Sun Jan 04 13:11:53 2015 -0600
298.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
298.3 @@ -1,212 +0,0 @@
298.4 - # -*- coding: iso-8859-1 -*-
298.5 -+ """Parser for command line options.
298.6 -|
298.7 -| This module helps scripts to parse the command line arguments in
298.8 -| sys.argv. It supports the same conventions as the Unix getopt()
298.9 -| function (including the special meanings of arguments of the form `-'
298.10 -| and `--'). Long options similar to those supported by GNU software
298.11 -| may be used as well via an optional third argument. This module
298.12 -| provides two functions and an exception:
298.13 -|
298.14 -| getopt() -- Parse command line options
298.15 -| gnu_getopt() -- Like getopt(), but allow option and non-option arguments
298.16 -| to be intermixed.
298.17 -| GetoptError -- exception (class) raised with 'opt' attribute, which is the
298.18 -| option involved with the exception.
298.19 -- """
298.20 -
298.21 - # Long option support added by Lars Wirzenius <liw@iki.fi>.
298.22 - #
298.23 - # Gerrit Holl <gerrit@nl.linux.org> moved the string-based exceptions
298.24 - # to class-based exceptions.
298.25 - #
298.26 - # Peter Åstrand <astrand@lysator.liu.se> added gnu_getopt().
298.27 - #
298.28 - # TODO for gnu_getopt():
298.29 - #
298.30 - # - GNU getopt_long_only mechanism
298.31 - # - allow the caller to specify ordering
298.32 - # - RETURN_IN_ORDER option
298.33 - # - GNU extension with '-' as first character of option string
298.34 - # - optional arguments, specified by double colons
298.35 - # - a option string with a W followed by semicolon should
298.36 - # treat "-W foo" as "--foo"
298.37 -
298.38 - __all__ = ["GetoptError","error","getopt","gnu_getopt"]
298.39 -
298.40 - import os
298.41 -
298.42 -+ class GetoptError(Exception):
298.43 -| opt = ''
298.44 -| msg = ''
298.45 -+ def __init__(self, msg, opt=''):
298.46 -| self.msg = msg
298.47 -| self.opt = opt
298.48 -| Exception.__init__(self, msg, opt)
298.49 --
298.50 -+ def __str__(self):
298.51 -| return self.msg
298.52 --
298.53 - error = GetoptError # backward compatibility
298.54 -
298.55 -+ def getopt(args, shortopts, longopts = []):
298.56 -+ """getopt(args, options[, long_options]) -> opts, args
298.57 -|
298.58 -| Parses command line options and parameter list. args is the
298.59 -| argument list to be parsed, without the leading reference to the
298.60 -| running program. Typically, this means "sys.argv[1:]". shortopts
298.61 -| is the string of option letters that the script wants to
298.62 -| recognize, with options that require an argument followed by a
298.63 -| colon (i.e., the same format that Unix getopt() uses). If
298.64 -| specified, longopts is a list of strings with the names of the
298.65 -| long options which should be supported. The leading '--'
298.66 -| characters should not be included in the option name. Options
298.67 -| which require an argument should be followed by an equal sign
298.68 -| ('=').
298.69 -|
298.70 -| The return value consists of two elements: the first is a list of
298.71 -| (option, value) pairs; the second is the list of program arguments
298.72 -| left after the option list was stripped (this is a trailing slice
298.73 -| of the first argument). Each option-and-value pair returned has
298.74 -| the option as its first element, prefixed with a hyphen (e.g.,
298.75 -| '-x'), and the option argument as its second element, or an empty
298.76 -| string if the option has no argument. The options occur in the
298.77 -| list in the same order in which they were found, thus allowing
298.78 -| multiple occurrences. Long and short options may be mixed.
298.79 -|
298.80 -- """
298.81 -|
298.82 -| opts = []
298.83 -| if type(longopts) == type(""):
298.84 -| longopts = [longopts]
298.85 -| else:
298.86 -| longopts = list(longopts)
298.87 -| while args and args[0].startswith('-') and args[0] != '-':
298.88 -| if args[0] == '--':
298.89 -| args = args[1:]
298.90 -| break
298.91 -| if args[0].startswith('--'):
298.92 -| opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
298.93 -| else:
298.94 -| opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
298.95 -|
298.96 -| return opts, args
298.97 --
298.98 -+ def gnu_getopt(args, shortopts, longopts = []):
298.99 -+ """getopt(args, options[, long_options]) -> opts, args
298.100 -|
298.101 -| This function works like getopt(), except that GNU style scanning
298.102 -| mode is used by default. This means that option and non-option
298.103 -| arguments may be intermixed. The getopt() function stops
298.104 -| processing options as soon as a non-option argument is
298.105 -| encountered.
298.106 -|
298.107 -| If the first character of the option string is `+', or if the
298.108 -| environment variable POSIXLY_CORRECT is set, then option
298.109 -| processing stops as soon as a non-option argument is encountered.
298.110 -|
298.111 -- """
298.112 -|
298.113 -| opts = []
298.114 -| prog_args = []
298.115 -| if isinstance(longopts, str):
298.116 -| longopts = [longopts]
298.117 -| else:
298.118 -| longopts = list(longopts)
298.119 -|
298.120 -| # Allow options after non-option arguments?
298.121 -| if shortopts.startswith('+'):
298.122 -| shortopts = shortopts[1:]
298.123 -| all_options_first = True
298.124 -| elif os.environ.get("POSIXLY_CORRECT"):
298.125 -| all_options_first = True
298.126 -| else:
298.127 -| all_options_first = False
298.128 -|
298.129 -| while args:
298.130 -| if args[0] == '--':
298.131 -| prog_args += args[1:]
298.132 -| break
298.133 -|
298.134 -| if args[0][:2] == '--':
298.135 -| opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
298.136 -| elif args[0][:1] == '-':
298.137 -| opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
298.138 -| else:
298.139 -| if all_options_first:
298.140 -| prog_args += args
298.141 -| break
298.142 -| else:
298.143 -| prog_args.append(args[0])
298.144 -| args = args[1:]
298.145 -|
298.146 -| return opts, prog_args
298.147 --
298.148 -+ def do_longs(opts, opt, longopts, args):
298.149 -| try:
298.150 -| i = opt.index('=')
298.151 -| except ValueError:
298.152 -| optarg = None
298.153 -| else:
298.154 -| opt, optarg = opt[:i], opt[i+1:]
298.155 -|
298.156 -| has_arg, opt = long_has_args(opt, longopts)
298.157 -| if has_arg:
298.158 -| if optarg is None:
298.159 -| if not args:
298.160 -| raise GetoptError('option --%s requires argument' % opt, opt)
298.161 -| optarg, args = args[0], args[1:]
298.162 -| elif optarg:
298.163 -| raise GetoptError('option --%s must not have an argument' % opt, opt)
298.164 -| opts.append(('--' + opt, optarg or ''))
298.165 -| return opts, args
298.166 -|
298.167 -| # Return:
298.168 -| # has_arg?
298.169 -- # full option name
298.170 -+ def long_has_args(opt, longopts):
298.171 -| possibilities = [o for o in longopts if o.startswith(opt)]
298.172 -| if not possibilities:
298.173 -| raise GetoptError('option --%s not recognized' % opt, opt)
298.174 -| # Is there an exact match?
298.175 -| if opt in possibilities:
298.176 -| return False, opt
298.177 -| elif opt + '=' in possibilities:
298.178 -| return True, opt
298.179 -| # No exact match, so better be unique.
298.180 -| if len(possibilities) > 1:
298.181 -| # XXX since possibilities contains all valid continuations, might be
298.182 -| # nice to work them into the error msg
298.183 -| raise GetoptError('option --%s not a unique prefix' % opt, opt)
298.184 -| assert len(possibilities) == 1
298.185 -| unique_match = possibilities[0]
298.186 -| has_arg = unique_match.endswith('=')
298.187 -| if has_arg:
298.188 -| unique_match = unique_match[:-1]
298.189 -| return has_arg, unique_match
298.190 --
298.191 -+ def do_shorts(opts, optstring, shortopts, args):
298.192 -| while optstring != '':
298.193 -| opt, optstring = optstring[0], optstring[1:]
298.194 -| if short_has_arg(opt, shortopts):
298.195 -| if optstring == '':
298.196 -| if not args:
298.197 -| raise GetoptError('option -%s requires argument' % opt,
298.198 -| opt)
298.199 -| optstring, args = args[0], args[1:]
298.200 -| optarg, optstring = optstring, ''
298.201 -| else:
298.202 -| optarg = ''
298.203 -| opts.append(('-' + opt, optarg))
298.204 -| return opts, args
298.205 --
298.206 -+ def short_has_arg(opt, shortopts):
298.207 -| for i in range(len(shortopts)):
298.208 -| if opt == shortopts[i] != ':':
298.209 -| return shortopts.startswith(':', i+1)
298.210 -| raise GetoptError('option -%s not recognized' % opt, opt)
298.211 --
298.212 - if __name__ == '__main__':
298.213 - import sys
298.214 - print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])
298.215 -
299.1 --- a/python.editor/test/unit/data/testfiles/getopt.py.nameoffsets Sun Jan 04 13:11:53 2015 -0600
299.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
299.3 @@ -1,212 +0,0 @@
299.4 -
299.5 -# -*- coding: iso-8859-1 -*-
299.6 -"""Parser for command line options.
299.7 -
299.8 -This module helps scripts to parse the command line arguments in
299.9 -sys.argv. It supports the same conventions as the Unix getopt()
299.10 -function (including the special meanings of arguments of the form `-'
299.11 -and `--'). Long options similar to those supported by GNU software
299.12 -may be used as well via an optional third argument. This module
299.13 -provides two functions and an exception:
299.14 -
299.15 -getopt() -- Parse command line options
299.16 -gnu_getopt() -- Like getopt(), but allow option and non-option arguments
299.17 -to be intermixed.
299.18 -GetoptError -- exception (class) raised with 'opt' attribute, which is the
299.19 -option involved with the exception.
299.20 -"""
299.21 -
299.22 -# Long option support added by Lars Wirzenius <liw@iki.fi>.
299.23 -#
299.24 -# Gerrit Holl <gerrit@nl.linux.org> moved the string-based exceptions
299.25 -# to class-based exceptions.
299.26 -#
299.27 -# Peter Åstrand <astrand@lysator.liu.se> added gnu_getopt().
299.28 -#
299.29 -# TODO for gnu_getopt():
299.30 -#
299.31 -# - GNU getopt_long_only mechanism
299.32 -# - allow the caller to specify ordering
299.33 -# - RETURN_IN_ORDER option
299.34 -# - GNU extension with '-' as first character of option string
299.35 -# - optional arguments, specified by double colons
299.36 -# - a option string with a W followed by semicolon should
299.37 -# treat "-W foo" as "--foo"
299.38 -
299.39 -<Name>__all__</Name> = ["GetoptError","error","getopt","gnu_getopt"]
299.40 -
299.41 -import os
299.42 -
299.43 -class <ClassDef>GetoptError</ClassDef>(<Name>Exception</Name>):
299.44 - <Name>opt</Name> = ''
299.45 - <Name>msg</Name> = ''
299.46 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>, <Name>msg</Name>, <Name>opt</Name>=''):
299.47 - <Attribute><Name>self</Name></Attribute>.msg = <Name>msg</Name>
299.48 - <Attribute><Name>self</Name></Attribute>.opt = <Name>opt</Name>
299.49 - <Attribute><Name>Exception</Name></Attribute>.<Call>__init__</Call>(<Name>self</Name>, <Name>msg</Name>, <Name>opt</Name>)
299.50 -
299.51 - def <FunctionDef>__str__</FunctionDef>(<Name>self</Name>):
299.52 - return <Attribute><Name>self</Name></Attribute>.msg
299.53 -
299.54 -<Name>error</Name> = <Name>GetoptError</Name> # backward compatibility
299.55 -
299.56 -def <FunctionDef>getopt</FunctionDef>(<Name>args</Name>, <Name>shortopts</Name>, <Name>longopts</Name> = []):
299.57 - """getopt(args, options[, long_options]) -> opts, args
299.58 -
299.59 - Parses command line options and parameter list. args is the
299.60 - argument list to be parsed, without the leading reference to the
299.61 - running program. Typically, this means "sys.argv[1:]". shortopts
299.62 - is the string of option letters that the script wants to
299.63 - recognize, with options that require an argument followed by a
299.64 - colon (i.e., the same format that Unix getopt() uses). If
299.65 - specified, longopts is a list of strings with the names of the
299.66 - long options which should be supported. The leading '--'
299.67 - characters should not be included in the option name. Options
299.68 - which require an argument should be followed by an equal sign
299.69 - ('=').
299.70 -
299.71 - The return value consists of two elements: the first is a list of
299.72 - (option, value) pairs; the second is the list of program arguments
299.73 - left after the option list was stripped (this is a trailing slice
299.74 - of the first argument). Each option-and-value pair returned has
299.75 - the option as its first element, prefixed with a hyphen (e.g.,
299.76 - '-x'), and the option argument as its second element, or an empty
299.77 - string if the option has no argument. The options occur in the
299.78 - list in the same order in which they were found, thus allowing
299.79 - multiple occurrences. Long and short options may be mixed.
299.80 -
299.81 - """
299.82 -
299.83 - <Name>opts</Name> = []
299.84 - if <Call><Name>type</Name></Call>(<Name>longopts</Name>) == <Call><Name>type</Name></Call>(""):
299.85 - <Name>longopts</Name> = [<Name>longopts</Name>]
299.86 - else:
299.87 - <Name>longopts</Name> = <Call><Name>list</Name></Call>(<Name>longopts</Name>)
299.88 - while <Name>args</Name> and <Name>args</Name><Attribute>[0]</Attribute>.<Call>startswith</Call>('-') and <Name>args</Name>[0] != '-':
299.89 - if <Name>args</Name>[0] == '--':
299.90 - <Name>args</Name> = <Name>args</Name>[1:]
299.91 - break
299.92 - if <Name>args</Name><Attribute>[0]</Attribute>.<Call>startswith</Call>('--'):
299.93 - <Name>opts</Name>, <Name>args</Name> = <Call><Name>do_longs</Name></Call>(<Name>opts</Name>, <Name>args</Name>[0][2:], <Name>longopts</Name>, <Name>args</Name>[1:])
299.94 - else:
299.95 - <Name>opts</Name>, <Name>args</Name> = <Call><Name>do_shorts</Name></Call>(<Name>opts</Name>, <Name>args</Name>[0][1:], <Name>shortopts</Name>, <Name>args</Name>[1:])
299.96 -
299.97 - return <Name>opts</Name>, <Name>args</Name>
299.98 -
299.99 -def <FunctionDef>gnu_getopt</FunctionDef>(<Name>args</Name>, <Name>shortopts</Name>, <Name>longopts</Name> = []):
299.100 - """getopt(args, options[, long_options]) -> opts, args
299.101 -
299.102 - This function works like getopt(), except that GNU style scanning
299.103 - mode is used by default. This means that option and non-option
299.104 - arguments may be intermixed. The getopt() function stops
299.105 - processing options as soon as a non-option argument is
299.106 - encountered.
299.107 -
299.108 - If the first character of the option string is `+', or if the
299.109 - environment variable POSIXLY_CORRECT is set, then option
299.110 - processing stops as soon as a non-option argument is encountered.
299.111 -
299.112 - """
299.113 -
299.114 - <Name>opts</Name> = []
299.115 - <Name>prog_args</Name> = []
299.116 - if <Call><Name>isinstance</Name></Call>(<Name>longopts</Name>, <Name>str</Name>):
299.117 - <Name>longopts</Name> = [<Name>longopts</Name>]
299.118 - else:
299.119 - <Name>longopts</Name> = <Call><Name>list</Name></Call>(<Name>longopts</Name>)
299.120 -
299.121 - # Allow options after non-option arguments?
299.122 - if <Attribute><Name>shortopts</Name></Attribute>.<Call>startswith</Call>('+'):
299.123 - <Name>shortopts</Name> = <Name>shortopts</Name>[1:]
299.124 - <Name>all_options_first</Name> = <Name>True</Name>
299.125 - elif <Attribute><Attribute><Name>os</Name></Attribute></Attribute>.environ.<Call>get</Call>("POSIXLY_CORRECT"):
299.126 - <Name>all_options_first</Name> = <Name>True</Name>
299.127 - else:
299.128 - <Name>all_options_first</Name> = <Name>False</Name>
299.129 -
299.130 - while <Name>args</Name>:
299.131 - if <Name>args</Name>[0] == '--':
299.132 - <Name>prog_args</Name> += <Name>args</Name>[1:]
299.133 - break
299.134 -
299.135 - if <Name>args</Name>[0][:2] == '--':
299.136 - <Name>opts</Name>, <Name>args</Name> = <Call><Name>do_longs</Name></Call>(<Name>opts</Name>, <Name>args</Name>[0][2:], <Name>longopts</Name>, <Name>args</Name>[1:])
299.137 - elif <Name>args</Name>[0][:1] == '-':
299.138 - <Name>opts</Name>, <Name>args</Name> = <Call><Name>do_shorts</Name></Call>(<Name>opts</Name>, <Name>args</Name>[0][1:], <Name>shortopts</Name>, <Name>args</Name>[1:])
299.139 - else:
299.140 - if <Name>all_options_first</Name>:
299.141 - <Name>prog_args</Name> += <Name>args</Name>
299.142 - break
299.143 - else:
299.144 - <Attribute><Name>prog_args</Name></Attribute>.<Call>append</Call>(<Name>args</Name>[0])
299.145 - <Name>args</Name> = <Name>args</Name>[1:]
299.146 -
299.147 - return <Name>opts</Name>, <Name>prog_args</Name>
299.148 -
299.149 -def <FunctionDef>do_longs</FunctionDef>(<Name>opts</Name>, <Name>opt</Name>, <Name>longopts</Name>, <Name>args</Name>):
299.150 - try:
299.151 - <Name>i</Name> = <Attribute><Name>opt</Name></Attribute>.<Call>index</Call>('=')
299.152 - except <Name>ValueError</Name>:
299.153 - <Name>optarg</Name> = <Name>None</Name>
299.154 - else:
299.155 - <Name>opt</Name>, <Name>optarg</Name> = <Name>opt</Name>[:<Name>i</Name>], <Name>opt</Name>[<Name>i</Name>+1:]
299.156 -
299.157 - <Name>has_arg</Name>, <Name>opt</Name> = <Call><Name>long_has_args</Name></Call>(<Name>opt</Name>, <Name>longopts</Name>)
299.158 - if <Name>has_arg</Name>:
299.159 - if <Name>optarg</Name> is <Name>None</Name>:
299.160 - if not <Name>args</Name>:
299.161 - raise <Call><Name>GetoptError</Name></Call>('option --%s requires argument' % <Name>opt</Name>, <Name>opt</Name>)
299.162 - <Name>optarg</Name>, <Name>args</Name> = <Name>args</Name>[0], <Name>args</Name>[1:]
299.163 - elif <Name>optarg</Name>:
299.164 - raise <Call><Name>GetoptError</Name></Call>('option --%s must not have an argument' % <Name>opt</Name>, <Name>opt</Name>)
299.165 - <Attribute><Name>opts</Name></Attribute>.<Call>append</Call>(('--' + <Name>opt</Name>, <Name>optarg</Name> or ''))
299.166 - return <Name>opts</Name>, <Name>args</Name>
299.167 -
299.168 -# Return:
299.169 -# has_arg?
299.170 -# full option name
299.171 -def <FunctionDef>long_has_args</FunctionDef>(<Name>opt</Name>, <Name>longopts</Name>):
299.172 - <Name>possibilities</Name> = [<Name>o</Name> for <Name>o</Name> in <Name>longopts</Name> if <Attribute><Name>o</Name></Attribute>.<Call>startswith</Call>(<Name>opt</Name>)]
299.173 - if not <Name>possibilities</Name>:
299.174 - raise <Call><Name>GetoptError</Name></Call>('option --%s not recognized' % <Name>opt</Name>, <Name>opt</Name>)
299.175 - # Is there an exact match?
299.176 - if <Name>opt</Name> in <Name>possibilities</Name>:
299.177 - return <Name>False</Name>, <Name>opt</Name>
299.178 - elif <Name>opt</Name> + '=' in <Name>possibilities</Name>:
299.179 - return <Name>True</Name>, <Name>opt</Name>
299.180 - # No exact match, so better be unique.
299.181 - if <Call><Name>len</Name></Call>(<Name>possibilities</Name>) > 1:
299.182 - # XXX since possibilities contains all valid continuations, might be
299.183 - # nice to work them into the error msg
299.184 - raise <Call><Name>GetoptError</Name></Call>('option --%s not a unique prefix' % <Name>opt</Name>, <Name>opt</Name>)
299.185 - assert <Call><Name>len</Name></Call>(<Name>possibilities</Name>) == 1
299.186 - <Name>unique_match</Name> = <Name>possibilities</Name>[0]
299.187 - <Name>has_arg</Name> = <Attribute><Name>unique_match</Name></Attribute>.<Call>endswith</Call>('=')
299.188 - if <Name>has_arg</Name>:
299.189 - <Name>unique_match</Name> = <Name>unique_match</Name>[:-1]
299.190 - return <Name>has_arg</Name>, <Name>unique_match</Name>
299.191 -
299.192 -def <FunctionDef>do_shorts</FunctionDef>(<Name>opts</Name>, <Name>optstring</Name>, <Name>shortopts</Name>, <Name>args</Name>):
299.193 - while <Name>optstring</Name> != '':
299.194 - <Name>opt</Name>, <Name>optstring</Name> = <Name>optstring</Name>[0], <Name>optstring</Name>[1:]
299.195 - if <Call><Name>short_has_arg</Name></Call>(<Name>opt</Name>, <Name>shortopts</Name>):
299.196 - if <Name>optstring</Name> == '':
299.197 - if not <Name>args</Name>:
299.198 - raise <Call><Name>GetoptError</Name></Call>('option -%s requires argument' % <Name>opt</Name>,
299.199 - <Name>opt</Name>)
299.200 - <Name>optstring</Name>, <Name>args</Name> = <Name>args</Name>[0], <Name>args</Name>[1:]
299.201 - <Name>optarg</Name>, <Name>optstring</Name> = <Name>optstring</Name>, ''
299.202 - else:
299.203 - <Name>optarg</Name> = ''
299.204 - <Attribute><Name>opts</Name></Attribute>.<Call>append</Call>(('-' + <Name>opt</Name>, <Name>optarg</Name>))
299.205 - return <Name>opts</Name>, <Name>args</Name>
299.206 -
299.207 -def <FunctionDef>short_has_arg</FunctionDef>(<Name>opt</Name>, <Name>shortopts</Name>):
299.208 - for <Name>i</Name> in <Call><Name>range</Name></Call>(<Call><Name>len</Name></Call>(<Name>shortopts</Name>)):
299.209 - if <Name>opt</Name> == <Name>shortopts</Name>[<Name>i</Name>] != ':':
299.210 - return <Attribute><Name>shortopts</Name></Attribute>.<Call>startswith</Call>(':', <Name>i</Name>+1)
299.211 - raise <Call><Name>GetoptError</Name></Call>('option -%s not recognized' % <Name>opt</Name>, <Name>opt</Name>)
299.212 -
299.213 -if <Name>__name__</Name> == '__main__':
299.214 - import sys
299.215 - print <Call><Name>getopt</Name></Call>(<Attribute><Name>sys</Name></Attribute>.argv[1:], "a:b", ["alpha=", "beta"])
300.1 --- a/python.editor/test/unit/data/testfiles/getopt.py.offsets Sun Jan 04 13:11:53 2015 -0600
300.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
300.3 @@ -1,212 +0,0 @@
300.4 -
300.5 -# -*- coding: iso-8859-1 -*-
300.6 -<Module><Expr><Str>"""Parser for command line options.
300.7 -
300.8 -This module helps scripts to parse the command line arguments in
300.9 -sys.argv. It supports the same conventions as the Unix getopt()
300.10 -function (including the special meanings of arguments of the form `-'
300.11 -and `--'). Long options similar to those supported by GNU software
300.12 -may be used as well via an optional third argument. This module
300.13 -provides two functions and an exception:
300.14 -
300.15 -getopt() -- Parse command line options
300.16 -gnu_getopt() -- Like getopt(), but allow option and non-option arguments
300.17 -to be intermixed.
300.18 -GetoptError -- exception (class) raised with 'opt' attribute, which is the
300.19 -option involved with the exception.
300.20 -"""</Str></Expr>
300.21 -
300.22 -# Long option support added by Lars Wirzenius <liw@iki.fi>.
300.23 -#
300.24 -# Gerrit Holl <gerrit@nl.linux.org> moved the string-based exceptions
300.25 -# to class-based exceptions.
300.26 -#
300.27 -# Peter Åstrand <astrand@lysator.liu.se> added gnu_getopt().
300.28 -#
300.29 -# TODO for gnu_getopt():
300.30 -#
300.31 -# - GNU getopt_long_only mechanism
300.32 -# - allow the caller to specify ordering
300.33 -# - RETURN_IN_ORDER option
300.34 -# - GNU extension with '-' as first character of option string
300.35 -# - optional arguments, specified by double colons
300.36 -# - a option string with a W followed by semicolon should
300.37 -# treat "-W foo" as "--foo"
300.38 -
300.39 -<Assign><Name>__all__</Name> = <List>[<Str>"GetoptError"</Str>,<Str>"error"</Str>,<Str>"getopt"</Str>,<Str>"gnu_getopt"</Str>]</List></Assign>
300.40 -
300.41 -<Import>import os</Import>
300.42 -
300.43 -<ClassDef>class GetoptError(<Name>Exception</Name>):
300.44 - <Assign><Name>opt</Name> = <Str>''</Str></Assign>
300.45 - <Assign><Name>msg</Name> = <Str>''</Str></Assign>
300.46 - <FunctionDef>def __init__(<Name>self</Name>, <Name>msg</Name>, <Name>opt</Name>=<Str>''</Str>):
300.47 - <Assign><Attribute><Name>self</Name>.msg</Attribute> = <Name>msg</Name></Assign>
300.48 - <Assign><Attribute><Name>self</Name>.opt</Attribute> = <Name>opt</Name></Assign>
300.49 - <Expr><Call><Attribute><Name>Exception</Name>.__init__</Attribute>(<Name>self</Name>, <Name>msg</Name>, <Name>opt</Name>)</Call></Expr>
300.50 -
300.51 - </FunctionDef> <FunctionDef>def __str__(<Name>self</Name>):
300.52 - <Return>return <Attribute><Name>self</Name>.msg</Attribute></Return>
300.53 -
300.54 -</FunctionDef></ClassDef><Assign><Name>error</Name> = <Name>GetoptError</Name></Assign> # backward compatibility
300.55 -
300.56 -<FunctionDef>def getopt(<Name>args</Name>, <Name>shortopts</Name>, <Name>longopts</Name> = <List>[]</List>):
300.57 - <Expr><Str>"""getopt(args, options[, long_options]) -> opts, args
300.58 -
300.59 - Parses command line options and parameter list. args is the
300.60 - argument list to be parsed, without the leading reference to the
300.61 - running program. Typically, this means "sys.argv[1:]". shortopts
300.62 - is the string of option letters that the script wants to
300.63 - recognize, with options that require an argument followed by a
300.64 - colon (i.e., the same format that Unix getopt() uses). If
300.65 - specified, longopts is a list of strings with the names of the
300.66 - long options which should be supported. The leading '--'
300.67 - characters should not be included in the option name. Options
300.68 - which require an argument should be followed by an equal sign
300.69 - ('=').
300.70 -
300.71 - The return value consists of two elements: the first is a list of
300.72 - (option, value) pairs; the second is the list of program arguments
300.73 - left after the option list was stripped (this is a trailing slice
300.74 - of the first argument). Each option-and-value pair returned has
300.75 - the option as its first element, prefixed with a hyphen (e.g.,
300.76 - '-x'), and the option argument as its second element, or an empty
300.77 - string if the option has no argument. The options occur in the
300.78 - list in the same order in which they were found, thus allowing
300.79 - multiple occurrences. Long and short options may be mixed.
300.80 -
300.81 - """</Str></Expr>
300.82 -
300.83 - <Assign><Name>opts</Name> = <List>[]</List></Assign>
300.84 - <If>if <Compare><Call><Name>type</Name>(<Name>longopts</Name>)</Call> == <Call><Name>type</Name>(<Str>""</Str>)</Call></Compare>:
300.85 - <Assign><Name>longopts</Name> = <List>[<Name>longopts</Name>]</List></Assign>
300.86 - else:
300.87 - <Assign><Name>longopts</Name> = <Call><Name>list</Name>(<Name>longopts</Name>)</Call></Assign>
300.88 - </If> <While>while <BoolOp><Name>args</Name> and <Call><Name>args</Name><Attribute><Subscript>[<Index><Num>0</Num></Index>]</Subscript>.startswith</Attribute>(<Str>'-'</Str>)</Call> and <Compare><Subscript><Name>args</Name>[<Index><Num>0</Num></Index>]</Subscript> != <Str>'-'</Str></Compare></BoolOp>:
300.89 - <If>if <Compare><Subscript><Name>args</Name>[<Index><Num>0</Num></Index>]</Subscript> == <Str>'--'</Str></Compare>:
300.90 - <Assign><Name>args</Name> = <Subscript><Name>args</Name>[<Slice><Num>1</Num>:</Slice>]</Subscript></Assign>
300.91 - <Break>break</Break>
300.92 - </If> <If>if <Call><Name>args</Name><Attribute><Subscript>[<Index><Num>0</Num></Index>]</Subscript>.startswith</Attribute>(<Str>'--'</Str>)</Call>:
300.93 - <Assign><Tuple><Name>opts</Name>, <Name>args</Name></Tuple> = <Call><Name>do_longs</Name>(<Name>opts</Name>, <Subscript><Name>args</Name><Subscript>[<Index><Num>0</Num></Index>]</Subscript>[<Slice><Num>2</Num>:</Slice>]</Subscript>, <Name>longopts</Name>, <Subscript><Name>args</Name>[<Slice><Num>1</Num>:</Slice>]</Subscript>)</Call></Assign>
300.94 - else:
300.95 - <Assign><Tuple><Name>opts</Name>, <Name>args</Name></Tuple> = <Call><Name>do_shorts</Name>(<Name>opts</Name>, <Subscript><Name>args</Name><Subscript>[<Index><Num>0</Num></Index>]</Subscript>[<Slice><Num>1</Num>:</Slice>]</Subscript>, <Name>shortopts</Name>, <Subscript><Name>args</Name>[<Slice><Num>1</Num>:</Slice>]</Subscript>)</Call></Assign>
300.96 -
300.97 - </If></While> <Return>return <Tuple><Name>opts</Name>, <Name>args</Name></Tuple></Return>
300.98 -
300.99 -</FunctionDef><FunctionDef>def gnu_getopt(<Name>args</Name>, <Name>shortopts</Name>, <Name>longopts</Name> = <List>[]</List>):
300.100 - <Expr><Str>"""getopt(args, options[, long_options]) -> opts, args
300.101 -
300.102 - This function works like getopt(), except that GNU style scanning
300.103 - mode is used by default. This means that option and non-option
300.104 - arguments may be intermixed. The getopt() function stops
300.105 - processing options as soon as a non-option argument is
300.106 - encountered.
300.107 -
300.108 - If the first character of the option string is `+', or if the
300.109 - environment variable POSIXLY_CORRECT is set, then option
300.110 - processing stops as soon as a non-option argument is encountered.
300.111 -
300.112 - """</Str></Expr>
300.113 -
300.114 - <Assign><Name>opts</Name> = <List>[]</List></Assign>
300.115 - <Assign><Name>prog_args</Name> = <List>[]</List></Assign>
300.116 - <If>if <Call><Name>isinstance</Name>(<Name>longopts</Name>, <Name>str</Name>)</Call>:
300.117 - <Assign><Name>longopts</Name> = <List>[<Name>longopts</Name>]</List></Assign>
300.118 - else:
300.119 - <Assign><Name>longopts</Name> = <Call><Name>list</Name>(<Name>longopts</Name>)</Call></Assign>
300.120 -
300.121 - # Allow options after non-option arguments?
300.122 - </If> <If>if <Call><Attribute><Name>shortopts</Name>.startswith</Attribute>(<Str>'+'</Str>)</Call>:
300.123 - <Assign><Name>shortopts</Name> = <Subscript><Name>shortopts</Name>[<Slice><Num>1</Num>:</Slice>]</Subscript></Assign>
300.124 - <Assign><Name>all_options_first</Name> = <Name>True</Name></Assign>
300.125 - <If>elif <Call><Attribute><Attribute><Name>os</Name>.environ</Attribute>.get</Attribute>(<Str>"POSIXLY_CORRECT"</Str>)</Call>:
300.126 - <Assign><Name>all_options_first</Name> = <Name>True</Name></Assign>
300.127 - else:
300.128 - <Assign><Name>all_options_first</Name> = <Name>False</Name></Assign>
300.129 -
300.130 - </If></If> <While>while <Name>args</Name>:
300.131 - <If>if <Compare><Subscript><Name>args</Name>[<Index><Num>0</Num></Index>]</Subscript> == <Str>'--'</Str></Compare>:
300.132 - <AugAssign><Name>prog_args</Name> += <Subscript><Name>args</Name>[<Slice><Num>1</Num>:</Slice>]</Subscript></AugAssign>
300.133 - <Break>break</Break>
300.134 -
300.135 - </If> <If>if <Compare><Subscript><Name>args</Name><Subscript>[<Index><Num>0</Num></Index>]</Subscript>[<Slice>:<Num>2</Num></Slice>]</Subscript> == <Str>'--'</Str></Compare>:
300.136 - <Assign><Tuple><Name>opts</Name>, <Name>args</Name></Tuple> = <Call><Name>do_longs</Name>(<Name>opts</Name>, <Subscript><Name>args</Name><Subscript>[<Index><Num>0</Num></Index>]</Subscript>[<Slice><Num>2</Num>:</Slice>]</Subscript>, <Name>longopts</Name>, <Subscript><Name>args</Name>[<Slice><Num>1</Num>:</Slice>]</Subscript>)</Call></Assign>
300.137 - <If>elif <Compare><Subscript><Name>args</Name><Subscript>[<Index><Num>0</Num></Index>]</Subscript>[<Slice>:<Num>1</Num></Slice>]</Subscript> == <Str>'-'</Str></Compare>:
300.138 - <Assign><Tuple><Name>opts</Name>, <Name>args</Name></Tuple> = <Call><Name>do_shorts</Name>(<Name>opts</Name>, <Subscript><Name>args</Name><Subscript>[<Index><Num>0</Num></Index>]</Subscript>[<Slice><Num>1</Num>:</Slice>]</Subscript>, <Name>shortopts</Name>, <Subscript><Name>args</Name>[<Slice><Num>1</Num>:</Slice>]</Subscript>)</Call></Assign>
300.139 - else:
300.140 - <If>if <Name>all_options_first</Name>:
300.141 - <AugAssign><Name>prog_args</Name> += <Name>args</Name></AugAssign>
300.142 - <Break>break</Break>
300.143 - else:
300.144 - <Expr><Call><Attribute><Name>prog_args</Name>.append</Attribute>(<Subscript><Name>args</Name>[<Index><Num>0</Num></Index>]</Subscript>)</Call></Expr>
300.145 - <Assign><Name>args</Name> = <Subscript><Name>args</Name>[<Slice><Num>1</Num>:</Slice>]</Subscript></Assign>
300.146 -
300.147 - </If></If></If></While> <Return>return <Tuple><Name>opts</Name>, <Name>prog_args</Name></Tuple></Return>
300.148 -
300.149 -</FunctionDef><FunctionDef>def do_longs(<Name>opts</Name>, <Name>opt</Name>, <Name>longopts</Name>, <Name>args</Name>):
300.150 - <TryExcept>try:
300.151 - <Assign><Name>i</Name> = <Call><Attribute><Name>opt</Name>.index</Attribute>(<Str>'='</Str>)</Call></Assign>
300.152 - <ExceptHandler>except <Name>ValueError</Name>:
300.153 - <Assign><Name>optarg</Name> = <Name>None</Name></Assign>
300.154 - </ExceptHandler> else:
300.155 - <Assign><Tuple><Name>opt</Name>, <Name>optarg</Name></Tuple> = <Tuple><Subscript><Name>opt</Name>[<Slice>:<Name>i</Name></Slice>]</Subscript>, <Subscript><Name>opt</Name>[<Slice><BinOp><Name>i</Name>+<Num>1</Num></BinOp>:</Slice>]</Subscript></Tuple></Assign>
300.156 -
300.157 - </TryExcept> <Assign><Tuple><Name>has_arg</Name>, <Name>opt</Name></Tuple> = <Call><Name>long_has_args</Name>(<Name>opt</Name>, <Name>longopts</Name>)</Call></Assign>
300.158 - <If>if <Name>has_arg</Name>:
300.159 - <If>if <Compare><Name>optarg</Name> is <Name>None</Name></Compare>:
300.160 - <If>if <UnaryOp>not <Name>args</Name></UnaryOp>:
300.161 - <Raise>raise <Call><Name>GetoptError</Name>(<BinOp><Str>'option --%s requires argument'</Str> % <Name>opt</Name></BinOp>, <Name>opt</Name>)</Call></Raise>
300.162 - </If> <Assign><Tuple><Name>optarg</Name>, <Name>args</Name></Tuple> = <Tuple><Subscript><Name>args</Name>[<Index><Num>0</Num></Index>]</Subscript>, <Subscript><Name>args</Name>[<Slice><Num>1</Num>:</Slice>]</Subscript></Tuple></Assign>
300.163 - </If> <If>elif <Name>optarg</Name>:
300.164 - <Raise>raise <Call><Name>GetoptError</Name>(<BinOp><Str>'option --%s must not have an argument'</Str> % <Name>opt</Name></BinOp>, <Name>opt</Name>)</Call></Raise>
300.165 - </If></If> <Expr><Call><Attribute><Name>opts</Name>.append</Attribute>(<Tuple>(<BinOp><Str>'--'</Str> + <Name>opt</Name></BinOp>, <BoolOp><Name>optarg</Name> or <Str>''</Str></BoolOp>)</Tuple>)</Call></Expr>
300.166 - <Return>return <Tuple><Name>opts</Name>, <Name>args</Name></Tuple></Return>
300.167 -
300.168 -# Return:
300.169 -# has_arg?
300.170 -# full option name
300.171 -</FunctionDef><FunctionDef>def long_has_args(<Name>opt</Name>, <Name>longopts</Name>):
300.172 - <Assign><Name>possibilities</Name> = <ListComp>[<Name>o</Name> for <Name>o</Name> in <Name>longopts</Name> if <Call><Attribute><Name>o</Name>.startswith</Attribute>(<Name>opt</Name>)</Call>]</ListComp></Assign>
300.173 - <If>if <UnaryOp>not <Name>possibilities</Name></UnaryOp>:
300.174 - <Raise>raise <Call><Name>GetoptError</Name>(<BinOp><Str>'option --%s not recognized'</Str> % <Name>opt</Name></BinOp>, <Name>opt</Name>)</Call></Raise>
300.175 - # Is there an exact match?
300.176 - </If> <If>if <Compare><Name>opt</Name> in <Name>possibilities</Name></Compare>:
300.177 - <Return>return <Tuple><Name>False</Name>, <Name>opt</Name></Tuple></Return>
300.178 - <If>elif <Compare><BinOp><Name>opt</Name> + <Str>'='</Str></BinOp> in <Name>possibilities</Name></Compare>:
300.179 - <Return>return <Tuple><Name>True</Name>, <Name>opt</Name></Tuple></Return>
300.180 - # No exact match, so better be unique.
300.181 - </If></If> <If>if <Compare><Call><Name>len</Name>(<Name>possibilities</Name>)</Call> > <Num>1</Num></Compare>:
300.182 - # XXX since possibilities contains all valid continuations, might be
300.183 - # nice to work them into the error msg
300.184 - <Raise>raise <Call><Name>GetoptError</Name>(<BinOp><Str>'option --%s not a unique prefix'</Str> % <Name>opt</Name></BinOp>, <Name>opt</Name>)</Call></Raise>
300.185 - </If> <Assert>assert <Compare><Call><Name>len</Name>(<Name>possibilities</Name>)</Call> == <Num>1</Num></Compare></Assert>
300.186 - <Assign><Name>unique_match</Name> = <Subscript><Name>possibilities</Name>[<Index><Num>0</Num></Index>]</Subscript></Assign>
300.187 - <Assign><Name>has_arg</Name> = <Call><Attribute><Name>unique_match</Name>.endswith</Attribute>(<Str>'='</Str>)</Call></Assign>
300.188 - <If>if <Name>has_arg</Name>:
300.189 - <Assign><Name>unique_match</Name> = <Subscript><Name>unique_match</Name>[<Slice>:<Num>-1</Num></Slice>]</Subscript></Assign>
300.190 - </If> <Return>return <Tuple><Name>has_arg</Name>, <Name>unique_match</Name></Tuple></Return>
300.191 -
300.192 -</FunctionDef><FunctionDef>def do_shorts(<Name>opts</Name>, <Name>optstring</Name>, <Name>shortopts</Name>, <Name>args</Name>):
300.193 - <While>while <Compare><Name>optstring</Name> != <Str>''</Str></Compare>:
300.194 - <Assign><Tuple><Name>opt</Name>, <Name>optstring</Name></Tuple> = <Tuple><Subscript><Name>optstring</Name>[<Index><Num>0</Num></Index>]</Subscript>, <Subscript><Name>optstring</Name>[<Slice><Num>1</Num>:</Slice>]</Subscript></Tuple></Assign>
300.195 - <If>if <Call><Name>short_has_arg</Name>(<Name>opt</Name>, <Name>shortopts</Name>)</Call>:
300.196 - <If>if <Compare><Name>optstring</Name> == <Str>''</Str></Compare>:
300.197 - <If>if <UnaryOp>not <Name>args</Name></UnaryOp>:
300.198 - <Raise>raise <Call><Name>GetoptError</Name>(<BinOp><Str>'option -%s requires argument'</Str> % <Name>opt</Name></BinOp>,
300.199 - <Name>opt</Name>)</Call></Raise>
300.200 - </If> <Assign><Tuple><Name>optstring</Name>, <Name>args</Name></Tuple> = <Tuple><Subscript><Name>args</Name>[<Index><Num>0</Num></Index>]</Subscript>, <Subscript><Name>args</Name>[<Slice><Num>1</Num>:</Slice>]</Subscript></Tuple></Assign>
300.201 - </If> <Assign><Tuple><Name>optarg</Name>, <Name>optstring</Name></Tuple> = <Tuple><Name>optstring</Name>, <Str>''</Str></Tuple></Assign>
300.202 - else:
300.203 - <Assign><Name>optarg</Name> = <Str>''</Str></Assign>
300.204 - </If> <Expr><Call><Attribute><Name>opts</Name>.append</Attribute>(<Tuple>(<BinOp><Str>'-'</Str> + <Name>opt</Name></BinOp>, <Name>optarg</Name>)</Tuple>)</Call></Expr>
300.205 - </While> <Return>return <Tuple><Name>opts</Name>, <Name>args</Name></Tuple></Return>
300.206 -
300.207 -</FunctionDef><FunctionDef>def short_has_arg(<Name>opt</Name>, <Name>shortopts</Name>):
300.208 - <For>for <Name>i</Name> in <Call><Name>range</Name>(<Call><Name>len</Name>(<Name>shortopts</Name>)</Call>)</Call>:
300.209 - <If>if <Compare><Name>opt</Name> == <Subscript><Name>shortopts</Name>[<Index><Name>i</Name></Index>]</Subscript> != <Str>':'</Str></Compare>:
300.210 - <Return>return <Call><Attribute><Name>shortopts</Name>.startswith</Attribute>(<Str>':'</Str>, <BinOp><Name>i</Name>+<Num>1</Num></BinOp>)</Call></Return>
300.211 - </If></For> <Raise>raise <Call><Name>GetoptError</Name>(<BinOp><Str>'option -%s not recognized'</Str> % <Name>opt</Name></BinOp>, <Name>opt</Name>)</Call></Raise>
300.212 -
300.213 -</FunctionDef><If>if <Compare><Name>__name__</Name> == <Str>'__main__'</Str></Compare>:
300.214 - <Import>import sys</Import>
300.215 - <Print>print <Call><Name>getopt</Name>(<Subscript><Attribute><Name>sys</Name>.argv</Attribute>[<Slice><Num>1</Num>:</Slice>]</Subscript>, <Str>"a:b"</Str>, <List>[<Str>"alpha="</Str>, <Str>"beta"</Str>]</List>)</Call></Print></If></Module>
301.1 --- a/python.editor/test/unit/data/testfiles/getopt.py.semantic Sun Jan 04 13:11:53 2015 -0600
301.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
301.3 @@ -1,211 +0,0 @@
301.4 -# -*- coding: iso-8859-1 -*-
301.5 -"""Parser for command line options.
301.6 -
301.7 -This module helps scripts to parse the command line arguments in
301.8 -sys.argv. It supports the same conventions as the Unix getopt()
301.9 -function (including the special meanings of arguments of the form `-'
301.10 -and `--'). Long options similar to those supported by GNU software
301.11 -may be used as well via an optional third argument. This module
301.12 -provides two functions and an exception:
301.13 -
301.14 -getopt() -- Parse command line options
301.15 -gnu_getopt() -- Like getopt(), but allow option and non-option arguments
301.16 -to be intermixed.
301.17 -GetoptError -- exception (class) raised with 'opt' attribute, which is the
301.18 -option involved with the exception.
301.19 -"""
301.20 -
301.21 -# Long option support added by Lars Wirzenius <liw@iki.fi>.
301.22 -#
301.23 -# Gerrit Holl <gerrit@nl.linux.org> moved the string-based exceptions
301.24 -# to class-based exceptions.
301.25 -#
301.26 -# Peter Åstrand <astrand@lysator.liu.se> added gnu_getopt().
301.27 -#
301.28 -# TODO for gnu_getopt():
301.29 -#
301.30 -# - GNU getopt_long_only mechanism
301.31 -# - allow the caller to specify ordering
301.32 -# - RETURN_IN_ORDER option
301.33 -# - GNU extension with '-' as first character of option string
301.34 -# - optional arguments, specified by double colons
301.35 -# - a option string with a W followed by semicolon should
301.36 -# treat "-W foo" as "--foo"
301.37 -
301.38 -__all__ = ["GetoptError","error","getopt","gnu_getopt"]
301.39 -
301.40 -import os
301.41 -
301.42 -class GetoptError(Exception):
301.43 - opt = ''
301.44 - msg = ''
301.45 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:msg<|, |>PARAMETER:opt<|=''):
301.46 - |>PARAMETER:self<|.msg = |>PARAMETER:msg<|
301.47 - |>PARAMETER:self<|.opt = |>PARAMETER:opt<|
301.48 - Exception.__init__(|>PARAMETER:self<|, |>PARAMETER:msg<|, |>PARAMETER:opt<|)
301.49 -
301.50 - def |>METHOD:__str__<|(|>PARAMETER:self<|):
301.51 - return |>PARAMETER:self<|.msg
301.52 -
301.53 -error = GetoptError # backward compatibility
301.54 -
301.55 -def |>METHOD:getopt<|(|>PARAMETER:args<|, |>PARAMETER:shortopts<|, |>PARAMETER:longopts<| = []):
301.56 - """getopt(args, options[, long_options]) -> opts, args
301.57 -
301.58 - Parses command line options and parameter list. args is the
301.59 - argument list to be parsed, without the leading reference to the
301.60 - running program. Typically, this means "sys.argv[1:]". shortopts
301.61 - is the string of option letters that the script wants to
301.62 - recognize, with options that require an argument followed by a
301.63 - colon (i.e., the same format that Unix getopt() uses). If
301.64 - specified, longopts is a list of strings with the names of the
301.65 - long options which should be supported. The leading '--'
301.66 - characters should not be included in the option name. Options
301.67 - which require an argument should be followed by an equal sign
301.68 - ('=').
301.69 -
301.70 - The return value consists of two elements: the first is a list of
301.71 - (option, value) pairs; the second is the list of program arguments
301.72 - left after the option list was stripped (this is a trailing slice
301.73 - of the first argument). Each option-and-value pair returned has
301.74 - the option as its first element, prefixed with a hyphen (e.g.,
301.75 - '-x'), and the option argument as its second element, or an empty
301.76 - string if the option has no argument. The options occur in the
301.77 - list in the same order in which they were found, thus allowing
301.78 - multiple occurrences. Long and short options may be mixed.
301.79 -
301.80 - """
301.81 -
301.82 - opts = []
301.83 - if type(|>PARAMETER:longopts<|) == type(""):
301.84 - |>PARAMETER:longopts<| = [|>PARAMETER:longopts<|]
301.85 - else:
301.86 - |>PARAMETER:longopts<| = list(|>PARAMETER:longopts<|)
301.87 - while |>PARAMETER:args<| and |>PARAMETER:args<|[0].startswith('-') and |>PARAMETER:args<|[0] != '-':
301.88 - if |>PARAMETER:args<|[0] == '--':
301.89 - |>PARAMETER:args<| = |>PARAMETER:args<|[1:]
301.90 - break
301.91 - if |>PARAMETER:args<|[0].startswith('--'):
301.92 - opts, |>PARAMETER:args<| = do_longs(opts, |>PARAMETER:args<|[0][2:], |>PARAMETER:longopts<|, |>PARAMETER:args<|[1:])
301.93 - else:
301.94 - opts, |>PARAMETER:args<| = do_shorts(opts, |>PARAMETER:args<|[0][1:], |>PARAMETER:shortopts<|, |>PARAMETER:args<|[1:])
301.95 -
301.96 - return opts, |>PARAMETER:args<|
301.97 -
301.98 -def |>METHOD:gnu_getopt<|(|>PARAMETER:args<|, |>PARAMETER:shortopts<|, |>PARAMETER:longopts<| = []):
301.99 - """getopt(args, options[, long_options]) -> opts, args
301.100 -
301.101 - This function works like getopt(), except that GNU style scanning
301.102 - mode is used by default. This means that option and non-option
301.103 - arguments may be intermixed. The getopt() function stops
301.104 - processing options as soon as a non-option argument is
301.105 - encountered.
301.106 -
301.107 - If the first character of the option string is `+', or if the
301.108 - environment variable POSIXLY_CORRECT is set, then option
301.109 - processing stops as soon as a non-option argument is encountered.
301.110 -
301.111 - """
301.112 -
301.113 - opts = []
301.114 - prog_args = []
301.115 - if isinstance(|>PARAMETER:longopts<|, str):
301.116 - |>PARAMETER:longopts<| = [|>PARAMETER:longopts<|]
301.117 - else:
301.118 - |>PARAMETER:longopts<| = list(|>PARAMETER:longopts<|)
301.119 -
301.120 - # Allow options after non-option arguments?
301.121 - if |>PARAMETER:shortopts<|.startswith('+'):
301.122 - |>PARAMETER:shortopts<| = |>PARAMETER:shortopts<|[1:]
301.123 - all_options_first = True
301.124 - elif os.environ.get("POSIXLY_CORRECT"):
301.125 - all_options_first = True
301.126 - else:
301.127 - all_options_first = False
301.128 -
301.129 - while |>PARAMETER:args<|:
301.130 - if |>PARAMETER:args<|[0] == '--':
301.131 - prog_args += |>PARAMETER:args<|[1:]
301.132 - break
301.133 -
301.134 - if |>PARAMETER:args<|[0][:2] == '--':
301.135 - opts, |>PARAMETER:args<| = do_longs(opts, |>PARAMETER:args<|[0][2:], |>PARAMETER:longopts<|, |>PARAMETER:args<|[1:])
301.136 - elif |>PARAMETER:args<|[0][:1] == '-':
301.137 - opts, |>PARAMETER:args<| = do_shorts(opts, |>PARAMETER:args<|[0][1:], |>PARAMETER:shortopts<|, |>PARAMETER:args<|[1:])
301.138 - else:
301.139 - if all_options_first:
301.140 - prog_args += |>PARAMETER:args<|
301.141 - break
301.142 - else:
301.143 - prog_args.append(|>PARAMETER:args<|[0])
301.144 - |>PARAMETER:args<| = |>PARAMETER:args<|[1:]
301.145 -
301.146 - return opts, prog_args
301.147 -
301.148 -def |>METHOD:do_longs<|(|>PARAMETER:opts<|, |>PARAMETER:opt<|, |>PARAMETER:longopts<|, |>PARAMETER:args<|):
301.149 - try:
301.150 - i = |>PARAMETER:opt<|.index('=')
301.151 - except ValueError:
301.152 - optarg = None
301.153 - else:
301.154 - |>PARAMETER:opt<|, optarg = |>PARAMETER:opt<|[:i], |>PARAMETER:opt<|[i+1:]
301.155 -
301.156 - has_arg, |>PARAMETER:opt<| = long_has_args(|>PARAMETER:opt<|, |>PARAMETER:longopts<|)
301.157 - if has_arg:
301.158 - if optarg is None:
301.159 - if not |>PARAMETER:args<|:
301.160 - raise GetoptError('option --%s requires argument' % |>PARAMETER:opt<|, |>PARAMETER:opt<|)
301.161 - optarg, |>PARAMETER:args<| = |>PARAMETER:args<|[0], |>PARAMETER:args<|[1:]
301.162 - elif optarg:
301.163 - raise GetoptError('option --%s must not have an argument' % |>PARAMETER:opt<|, |>PARAMETER:opt<|)
301.164 - |>PARAMETER:opts<|.append(('--' + |>PARAMETER:opt<|, optarg or ''))
301.165 - return |>PARAMETER:opts<|, |>PARAMETER:args<|
301.166 -
301.167 -# Return:
301.168 -# has_arg?
301.169 -# full option name
301.170 -def |>METHOD:long_has_args<|(|>PARAMETER:opt<|, |>PARAMETER:longopts<|):
301.171 - possibilities = [o for o in |>PARAMETER:longopts<| if o.startswith(|>PARAMETER:opt<|)]
301.172 - if not possibilities:
301.173 - raise GetoptError('option --%s not recognized' % |>PARAMETER:opt<|, |>PARAMETER:opt<|)
301.174 - # Is there an exact match?
301.175 - if |>PARAMETER:opt<| in possibilities:
301.176 - return False, |>PARAMETER:opt<|
301.177 - elif |>PARAMETER:opt<| + '=' in possibilities:
301.178 - return True, |>PARAMETER:opt<|
301.179 - # No exact match, so better be unique.
301.180 - if len(possibilities) > 1:
301.181 - # XXX since possibilities contains all valid continuations, might be
301.182 - # nice to work them into the error msg
301.183 - raise GetoptError('option --%s not a unique prefix' % |>PARAMETER:opt<|, |>PARAMETER:opt<|)
301.184 - assert len(possibilities) == 1
301.185 - unique_match = possibilities[0]
301.186 - has_arg = unique_match.endswith('=')
301.187 - if has_arg:
301.188 - unique_match = unique_match[:-1]
301.189 - return has_arg, unique_match
301.190 -
301.191 -def |>METHOD:do_shorts<|(|>PARAMETER:opts<|, |>PARAMETER:optstring<|, |>PARAMETER:shortopts<|, |>PARAMETER:args<|):
301.192 - while |>PARAMETER:optstring<| != '':
301.193 - opt, |>PARAMETER:optstring<| = |>PARAMETER:optstring<|[0], |>PARAMETER:optstring<|[1:]
301.194 - if short_has_arg(opt, |>PARAMETER:shortopts<|):
301.195 - if |>PARAMETER:optstring<| == '':
301.196 - if not |>PARAMETER:args<|:
301.197 - raise GetoptError('option -%s requires argument' % opt,
301.198 - opt)
301.199 - |>PARAMETER:optstring<|, |>PARAMETER:args<| = |>PARAMETER:args<|[0], |>PARAMETER:args<|[1:]
301.200 - optarg, |>PARAMETER:optstring<| = |>PARAMETER:optstring<|, ''
301.201 - else:
301.202 - optarg = ''
301.203 - |>PARAMETER:opts<|.append(('-' + opt, optarg))
301.204 - return |>PARAMETER:opts<|, |>PARAMETER:args<|
301.205 -
301.206 -def |>METHOD:short_has_arg<|(|>PARAMETER:opt<|, |>PARAMETER:shortopts<|):
301.207 - for i in range(len(|>PARAMETER:shortopts<|)):
301.208 - if |>PARAMETER:opt<| == |>PARAMETER:shortopts<|[i] != ':':
301.209 - return |>PARAMETER:shortopts<|.startswith(':', i+1)
301.210 - raise GetoptError('option -%s not recognized' % |>PARAMETER:opt<|, |>PARAMETER:opt<|)
301.211 -
301.212 -if __name__ == '__main__':
301.213 - import sys
301.214 - print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])
302.1 --- a/python.editor/test/unit/data/testfiles/getopt.py.structure Sun Jan 04 13:11:53 2015 -0600
302.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
302.3 @@ -1,11 +0,0 @@
302.4 -GetoptError:CLASS:[]:ESCAPED{GetoptError}:
302.5 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{msg}ESCAPED{,}ESCAPED{opt}}):
302.6 - __str__:METHOD:[]:ESCAPED{__str__}(PARAMETERS{ESCAPED{self}}):
302.7 - msg:ATTRIBUTE:[]:ESCAPED{msg}:
302.8 - opt:ATTRIBUTE:[]:ESCAPED{opt}:
302.9 -getopt:METHOD:[]:ESCAPED{getopt}(PARAMETERS{ESCAPED{args}ESCAPED{,}ESCAPED{shortopts}ESCAPED{,}ESCAPED{longopts}}):
302.10 -gnu_getopt:METHOD:[]:ESCAPED{gnu_getopt}(PARAMETERS{ESCAPED{args}ESCAPED{,}ESCAPED{shortopts}ESCAPED{,}ESCAPED{longopts}}):
302.11 -do_longs:METHOD:[PRIVATE]:ESCAPED{do_longs}(PARAMETERS{ESCAPED{opts}ESCAPED{,}ESCAPED{opt}ESCAPED{,}ESCAPED{longopts}ESCAPED{,}ESCAPED{args}}):
302.12 -long_has_args:METHOD:[PRIVATE]:ESCAPED{long_has_args}(PARAMETERS{ESCAPED{opt}ESCAPED{,}ESCAPED{longopts}}):
302.13 -do_shorts:METHOD:[PRIVATE]:ESCAPED{do_shorts}(PARAMETERS{ESCAPED{opts}ESCAPED{,}ESCAPED{optstring}ESCAPED{,}ESCAPED{shortopts}ESCAPED{,}ESCAPED{args}}):
302.14 -short_has_arg:METHOD:[PRIVATE]:ESCAPED{short_has_arg}(PARAMETERS{ESCAPED{opt}ESCAPED{,}ESCAPED{shortopts}}):
303.1 --- a/python.editor/test/unit/data/testfiles/gotolocal.py Sun Jan 04 13:11:53 2015 -0600
303.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
303.3 @@ -1,3 +0,0 @@
303.4 -def ggg(name):
303.5 - print name;
303.6 -
304.1 --- a/python.editor/test/unit/data/testfiles/hanging_indent.py Sun Jan 04 13:11:53 2015 -0600
304.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
304.3 @@ -1,8 +0,0 @@
304.4 -class LSimpleXMLRPCServer(LSimpleXMLRPCDispatcher, SimpleXMLRPCServer):
304.5 - def __init__(self, addr, requestHandler=LSimpleXMLRPCRequestHandler,
304.6 - logRequests=1, allow_none=0):
304.7 - SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests)
304.8 - LSimpleXMLRPCDispatcher.__init__(self)
304.9 -
304.10 - self.allow_none = allow_none
304.11 -
305.1 --- a/python.editor/test/unit/data/testfiles/hanging_indent.py.formatted Sun Jan 04 13:11:53 2015 -0600
305.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
305.3 @@ -1,8 +0,0 @@
305.4 -class LSimpleXMLRPCServer(LSimpleXMLRPCDispatcher, SimpleXMLRPCServer):
305.5 - def __init__(self, addr, requestHandler=LSimpleXMLRPCRequestHandler,
305.6 - logRequests=1, allow_none=0):
305.7 - SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests)
305.8 - LSimpleXMLRPCDispatcher.__init__(self)
305.9 -
305.10 - self.allow_none = allow_none
305.11 -
306.1 --- a/python.editor/test/unit/data/testfiles/hanging_indent2.py Sun Jan 04 13:11:53 2015 -0600
306.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
306.3 @@ -1,15 +0,0 @@
306.4 -class Rectangle(Blob):
306.5 -
306.6 - def __init__(self, width, height,
306.7 - color='black', emphasis=None, highlight=0):
306.8 - if width == 0 and height == 0 and \
306.9 - color == 'red' and emphasis == 'strong' or \
306.10 - highlight > 100:
306.11 - raise ValueError("sorry, you lose")
306.12 - if width == 0 and height == 0 and (color == 'red' or
306.13 - emphasis is None):
306.14 - raise ValueError("I don't think so -- values are %s, %s" %
306.15 - (width, height))
306.16 - Blob.__init__(self, width, height,
306.17 - color, emphasis, highlight)
306.18 -
307.1 --- a/python.editor/test/unit/data/testfiles/hanging_indent2.py.formatted Sun Jan 04 13:11:53 2015 -0600
307.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
307.3 @@ -1,15 +0,0 @@
307.4 -class Rectangle(Blob):
307.5 -
307.6 - def __init__(self, width, height,
307.7 - color='black', emphasis=None, highlight=0):
307.8 - if width == 0 and height == 0 and \
307.9 - color == 'red' and emphasis == 'strong' or \
307.10 - highlight > 100:
307.11 - raise ValueError("sorry, you lose")
307.12 - if width == 0 and height == 0 and (color == 'red' or
307.13 - emphasis is None):
307.14 - raise ValueError("I don't think so -- values are %s, %s" %
307.15 - (width, height))
307.16 - Blob.__init__(self, width, height,
307.17 - color, emphasis, highlight)
307.18 -
308.1 --- a/python.editor/test/unit/data/testfiles/httplib.py Sun Jan 04 13:11:53 2015 -0600
308.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
308.3 @@ -1,1432 +0,0 @@
308.4 -"""HTTP/1.1 client library
308.5 -
308.6 -<intro stuff goes here>
308.7 -<other stuff, too>
308.8 -
308.9 -HTTPConnection goes through a number of "states", which define when a client
308.10 -may legally make another request or fetch the response for a particular
308.11 -request. This diagram details these state transitions:
308.12 -
308.13 - (null)
308.14 - |
308.15 - | HTTPConnection()
308.16 - v
308.17 - Idle
308.18 - |
308.19 - | putrequest()
308.20 - v
308.21 - Request-started
308.22 - |
308.23 - | ( putheader() )* endheaders()
308.24 - v
308.25 - Request-sent
308.26 - |
308.27 - | response = getresponse()
308.28 - v
308.29 - Unread-response [Response-headers-read]
308.30 - |\____________________
308.31 - | |
308.32 - | response.read() | putrequest()
308.33 - v v
308.34 - Idle Req-started-unread-response
308.35 - ______/|
308.36 - / |
308.37 - response.read() | | ( putheader() )* endheaders()
308.38 - v v
308.39 - Request-started Req-sent-unread-response
308.40 - |
308.41 - | response.read()
308.42 - v
308.43 - Request-sent
308.44 -
308.45 -This diagram presents the following rules:
308.46 - -- a second request may not be started until {response-headers-read}
308.47 - -- a response [object] cannot be retrieved until {request-sent}
308.48 - -- there is no differentiation between an unread response body and a
308.49 - partially read response body
308.50 -
308.51 -Note: this enforcement is applied by the HTTPConnection class. The
308.52 - HTTPResponse class does not enforce this state machine, which
308.53 - implies sophisticated clients may accelerate the request/response
308.54 - pipeline. Caution should be taken, though: accelerating the states
308.55 - beyond the above pattern may imply knowledge of the server's
308.56 - connection-close behavior for certain requests. For example, it
308.57 - is impossible to tell whether the server will close the connection
308.58 - UNTIL the response headers have been read; this means that further
308.59 - requests cannot be placed into the pipeline until it is known that
308.60 - the server will NOT be closing the connection.
308.61 -
308.62 -Logical State __state __response
308.63 -------------- ------- ----------
308.64 -Idle _CS_IDLE None
308.65 -Request-started _CS_REQ_STARTED None
308.66 -Request-sent _CS_REQ_SENT None
308.67 -Unread-response _CS_IDLE <response_class>
308.68 -Req-started-unread-response _CS_REQ_STARTED <response_class>
308.69 -Req-sent-unread-response _CS_REQ_SENT <response_class>
308.70 -"""
308.71 -
308.72 -import errno
308.73 -import mimetools
308.74 -import socket
308.75 -from urlparse import urlsplit
308.76 -
308.77 -try:
308.78 - from cStringIO import StringIO
308.79 -except ImportError:
308.80 - from StringIO import StringIO
308.81 -
308.82 -__all__ = ["HTTP", "HTTPResponse", "HTTPConnection", "HTTPSConnection",
308.83 - "HTTPException", "NotConnected", "UnknownProtocol",
308.84 - "UnknownTransferEncoding", "UnimplementedFileMode",
308.85 - "IncompleteRead", "InvalidURL", "ImproperConnectionState",
308.86 - "CannotSendRequest", "CannotSendHeader", "ResponseNotReady",
308.87 - "BadStatusLine", "error", "responses"]
308.88 -
308.89 -HTTP_PORT = 80
308.90 -HTTPS_PORT = 443
308.91 -
308.92 -_UNKNOWN = 'UNKNOWN'
308.93 -
308.94 -# connection states
308.95 -_CS_IDLE = 'Idle'
308.96 -_CS_REQ_STARTED = 'Request-started'
308.97 -_CS_REQ_SENT = 'Request-sent'
308.98 -
308.99 -# status codes
308.100 -# informational
308.101 -CONTINUE = 100
308.102 -SWITCHING_PROTOCOLS = 101
308.103 -PROCESSING = 102
308.104 -
308.105 -# successful
308.106 -OK = 200
308.107 -CREATED = 201
308.108 -ACCEPTED = 202
308.109 -NON_AUTHORITATIVE_INFORMATION = 203
308.110 -NO_CONTENT = 204
308.111 -RESET_CONTENT = 205
308.112 -PARTIAL_CONTENT = 206
308.113 -MULTI_STATUS = 207
308.114 -IM_USED = 226
308.115 -
308.116 -# redirection
308.117 -MULTIPLE_CHOICES = 300
308.118 -MOVED_PERMANENTLY = 301
308.119 -FOUND = 302
308.120 -SEE_OTHER = 303
308.121 -NOT_MODIFIED = 304
308.122 -USE_PROXY = 305
308.123 -TEMPORARY_REDIRECT = 307
308.124 -
308.125 -# client error
308.126 -BAD_REQUEST = 400
308.127 -UNAUTHORIZED = 401
308.128 -PAYMENT_REQUIRED = 402
308.129 -FORBIDDEN = 403
308.130 -NOT_FOUND = 404
308.131 -METHOD_NOT_ALLOWED = 405
308.132 -NOT_ACCEPTABLE = 406
308.133 -PROXY_AUTHENTICATION_REQUIRED = 407
308.134 -REQUEST_TIMEOUT = 408
308.135 -CONFLICT = 409
308.136 -GONE = 410
308.137 -LENGTH_REQUIRED = 411
308.138 -PRECONDITION_FAILED = 412
308.139 -REQUEST_ENTITY_TOO_LARGE = 413
308.140 -REQUEST_URI_TOO_LONG = 414
308.141 -UNSUPPORTED_MEDIA_TYPE = 415
308.142 -REQUESTED_RANGE_NOT_SATISFIABLE = 416
308.143 -EXPECTATION_FAILED = 417
308.144 -UNPROCESSABLE_ENTITY = 422
308.145 -LOCKED = 423
308.146 -FAILED_DEPENDENCY = 424
308.147 -UPGRADE_REQUIRED = 426
308.148 -
308.149 -# server error
308.150 -INTERNAL_SERVER_ERROR = 500
308.151 -NOT_IMPLEMENTED = 501
308.152 -BAD_GATEWAY = 502
308.153 -SERVICE_UNAVAILABLE = 503
308.154 -GATEWAY_TIMEOUT = 504
308.155 -HTTP_VERSION_NOT_SUPPORTED = 505
308.156 -INSUFFICIENT_STORAGE = 507
308.157 -NOT_EXTENDED = 510
308.158 -
308.159 -# Mapping status codes to official W3C names
308.160 -responses = {
308.161 - 100: 'Continue',
308.162 - 101: 'Switching Protocols',
308.163 -
308.164 - 200: 'OK',
308.165 - 201: 'Created',
308.166 - 202: 'Accepted',
308.167 - 203: 'Non-Authoritative Information',
308.168 - 204: 'No Content',
308.169 - 205: 'Reset Content',
308.170 - 206: 'Partial Content',
308.171 -
308.172 - 300: 'Multiple Choices',
308.173 - 301: 'Moved Permanently',
308.174 - 302: 'Found',
308.175 - 303: 'See Other',
308.176 - 304: 'Not Modified',
308.177 - 305: 'Use Proxy',
308.178 - 306: '(Unused)',
308.179 - 307: 'Temporary Redirect',
308.180 -
308.181 - 400: 'Bad Request',
308.182 - 401: 'Unauthorized',
308.183 - 402: 'Payment Required',
308.184 - 403: 'Forbidden',
308.185 - 404: 'Not Found',
308.186 - 405: 'Method Not Allowed',
308.187 - 406: 'Not Acceptable',
308.188 - 407: 'Proxy Authentication Required',
308.189 - 408: 'Request Timeout',
308.190 - 409: 'Conflict',
308.191 - 410: 'Gone',
308.192 - 411: 'Length Required',
308.193 - 412: 'Precondition Failed',
308.194 - 413: 'Request Entity Too Large',
308.195 - 414: 'Request-URI Too Long',
308.196 - 415: 'Unsupported Media Type',
308.197 - 416: 'Requested Range Not Satisfiable',
308.198 - 417: 'Expectation Failed',
308.199 -
308.200 - 500: 'Internal Server Error',
308.201 - 501: 'Not Implemented',
308.202 - 502: 'Bad Gateway',
308.203 - 503: 'Service Unavailable',
308.204 - 504: 'Gateway Timeout',
308.205 - 505: 'HTTP Version Not Supported',
308.206 -}
308.207 -
308.208 -# maximal amount of data to read at one time in _safe_read
308.209 -MAXAMOUNT = 1048576
308.210 -
308.211 -class HTTPMessage(mimetools.Message):
308.212 -
308.213 - def addheader(self, key, value):
308.214 - """Add header for field key handling repeats."""
308.215 - prev = self.dict.get(key)
308.216 - if prev is None:
308.217 - self.dict[key] = value
308.218 - else:
308.219 - combined = ", ".join((prev, value))
308.220 - self.dict[key] = combined
308.221 -
308.222 - def addcontinue(self, key, more):
308.223 - """Add more field data from a continuation line."""
308.224 - prev = self.dict[key]
308.225 - self.dict[key] = prev + "\n " + more
308.226 -
308.227 - def readheaders(self):
308.228 - """Read header lines.
308.229 -
308.230 - Read header lines up to the entirely blank line that terminates them.
308.231 - The (normally blank) line that ends the headers is skipped, but not
308.232 - included in the returned list. If a non-header line ends the headers,
308.233 - (which is an error), an attempt is made to backspace over it; it is
308.234 - never included in the returned list.
308.235 -
308.236 - The variable self.status is set to the empty string if all went well,
308.237 - otherwise it is an error message. The variable self.headers is a
308.238 - completely uninterpreted list of lines contained in the header (so
308.239 - printing them will reproduce the header exactly as it appears in the
308.240 - file).
308.241 -
308.242 - If multiple header fields with the same name occur, they are combined
308.243 - according to the rules in RFC 2616 sec 4.2:
308.244 -
308.245 - Appending each subsequent field-value to the first, each separated
308.246 - by a comma. The order in which header fields with the same field-name
308.247 - are received is significant to the interpretation of the combined
308.248 - field value.
308.249 - """
308.250 - # XXX The implementation overrides the readheaders() method of
308.251 - # rfc822.Message. The base class design isn't amenable to
308.252 - # customized behavior here so the method here is a copy of the
308.253 - # base class code with a few small changes.
308.254 -
308.255 - self.dict = {}
308.256 - self.unixfrom = ''
308.257 - self.headers = hlist = []
308.258 - self.status = ''
308.259 - headerseen = ""
308.260 - firstline = 1
308.261 - startofline = unread = tell = None
308.262 - if hasattr(self.fp, 'unread'):
308.263 - unread = self.fp.unread
308.264 - elif self.seekable:
308.265 - tell = self.fp.tell
308.266 - while True:
308.267 - if tell:
308.268 - try:
308.269 - startofline = tell()
308.270 - except IOError:
308.271 - startofline = tell = None
308.272 - self.seekable = 0
308.273 - line = self.fp.readline()
308.274 - if not line:
308.275 - self.status = 'EOF in headers'
308.276 - break
308.277 - # Skip unix From name time lines
308.278 - if firstline and line.startswith('From '):
308.279 - self.unixfrom = self.unixfrom + line
308.280 - continue
308.281 - firstline = 0
308.282 - if headerseen and line[0] in ' \t':
308.283 - # XXX Not sure if continuation lines are handled properly
308.284 - # for http and/or for repeating headers
308.285 - # It's a continuation line.
308.286 - hlist.append(line)
308.287 - self.addcontinue(headerseen, line.strip())
308.288 - continue
308.289 - elif self.iscomment(line):
308.290 - # It's a comment. Ignore it.
308.291 - continue
308.292 - elif self.islast(line):
308.293 - # Note! No pushback here! The delimiter line gets eaten.
308.294 - break
308.295 - headerseen = self.isheader(line)
308.296 - if headerseen:
308.297 - # It's a legal header line, save it.
308.298 - hlist.append(line)
308.299 - self.addheader(headerseen, line[len(headerseen)+1:].strip())
308.300 - continue
308.301 - else:
308.302 - # It's not a header line; throw it back and stop here.
308.303 - if not self.dict:
308.304 - self.status = 'No headers'
308.305 - else:
308.306 - self.status = 'Non-header line where header expected'
308.307 - # Try to undo the read.
308.308 - if unread:
308.309 - unread(line)
308.310 - elif tell:
308.311 - self.fp.seek(startofline)
308.312 - else:
308.313 - self.status = self.status + '; bad seek'
308.314 - break
308.315 -
308.316 -class HTTPResponse:
308.317 -
308.318 - # strict: If true, raise BadStatusLine if the status line can't be
308.319 - # parsed as a valid HTTP/1.0 or 1.1 status line. By default it is
308.320 - # false because it prevents clients from talking to HTTP/0.9
308.321 - # servers. Note that a response with a sufficiently corrupted
308.322 - # status line will look like an HTTP/0.9 response.
308.323 -
308.324 - # See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details.
308.325 -
308.326 - def __init__(self, sock, debuglevel=0, strict=0, method=None):
308.327 - self.fp = sock.makefile('rb', 0)
308.328 - self.debuglevel = debuglevel
308.329 - self.strict = strict
308.330 - self._method = method
308.331 -
308.332 - self.msg = None
308.333 -
308.334 - # from the Status-Line of the response
308.335 - self.version = _UNKNOWN # HTTP-Version
308.336 - self.status = _UNKNOWN # Status-Code
308.337 - self.reason = _UNKNOWN # Reason-Phrase
308.338 -
308.339 - self.chunked = _UNKNOWN # is "chunked" being used?
308.340 - self.chunk_left = _UNKNOWN # bytes left to read in current chunk
308.341 - self.length = _UNKNOWN # number of bytes left in response
308.342 - self.will_close = _UNKNOWN # conn will close at end of response
308.343 -
308.344 - def _read_status(self):
308.345 - # Initialize with Simple-Response defaults
308.346 - line = self.fp.readline()
308.347 - if self.debuglevel > 0:
308.348 - print "reply:", repr(line)
308.349 - if not line:
308.350 - # Presumably, the server closed the connection before
308.351 - # sending a valid response.
308.352 - raise BadStatusLine(line)
308.353 - try:
308.354 - [version, status, reason] = line.split(None, 2)
308.355 - except ValueError:
308.356 - try:
308.357 - [version, status] = line.split(None, 1)
308.358 - reason = ""
308.359 - except ValueError:
308.360 - # empty version will cause next test to fail and status
308.361 - # will be treated as 0.9 response.
308.362 - version = ""
308.363 - if not version.startswith('HTTP/'):
308.364 - if self.strict:
308.365 - self.close()
308.366 - raise BadStatusLine(line)
308.367 - else:
308.368 - # assume it's a Simple-Response from an 0.9 server
308.369 - self.fp = LineAndFileWrapper(line, self.fp)
308.370 - return "HTTP/0.9", 200, ""
308.371 -
308.372 - # The status code is a three-digit number
308.373 - try:
308.374 - status = int(status)
308.375 - if status < 100 or status > 999:
308.376 - raise BadStatusLine(line)
308.377 - except ValueError:
308.378 - raise BadStatusLine(line)
308.379 - return version, status, reason
308.380 -
308.381 - def begin(self):
308.382 - if self.msg is not None:
308.383 - # we've already started reading the response
308.384 - return
308.385 -
308.386 - # read until we get a non-100 response
308.387 - while True:
308.388 - version, status, reason = self._read_status()
308.389 - if status != CONTINUE:
308.390 - break
308.391 - # skip the header from the 100 response
308.392 - while True:
308.393 - skip = self.fp.readline().strip()
308.394 - if not skip:
308.395 - break
308.396 - if self.debuglevel > 0:
308.397 - print "header:", skip
308.398 -
308.399 - self.status = status
308.400 - self.reason = reason.strip()
308.401 - if version == 'HTTP/1.0':
308.402 - self.version = 10
308.403 - elif version.startswith('HTTP/1.'):
308.404 - self.version = 11 # use HTTP/1.1 code for HTTP/1.x where x>=1
308.405 - elif version == 'HTTP/0.9':
308.406 - self.version = 9
308.407 - else:
308.408 - raise UnknownProtocol(version)
308.409 -
308.410 - if self.version == 9:
308.411 - self.length = None
308.412 - self.chunked = 0
308.413 - self.will_close = 1
308.414 - self.msg = HTTPMessage(StringIO())
308.415 - return
308.416 -
308.417 - self.msg = HTTPMessage(self.fp, 0)
308.418 - if self.debuglevel > 0:
308.419 - for hdr in self.msg.headers:
308.420 - print "header:", hdr,
308.421 -
308.422 - # don't let the msg keep an fp
308.423 - self.msg.fp = None
308.424 -
308.425 - # are we using the chunked-style of transfer encoding?
308.426 - tr_enc = self.msg.getheader('transfer-encoding')
308.427 - if tr_enc and tr_enc.lower() == "chunked":
308.428 - self.chunked = 1
308.429 - self.chunk_left = None
308.430 - else:
308.431 - self.chunked = 0
308.432 -
308.433 - # will the connection close at the end of the response?
308.434 - self.will_close = self._check_close()
308.435 -
308.436 - # do we have a Content-Length?
308.437 - # NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
308.438 - length = self.msg.getheader('content-length')
308.439 - if length and not self.chunked:
308.440 - try:
308.441 - self.length = int(length)
308.442 - except ValueError:
308.443 - self.length = None
308.444 - else:
308.445 - self.length = None
308.446 -
308.447 - # does the body have a fixed length? (of zero)
308.448 - if (status == NO_CONTENT or status == NOT_MODIFIED or
308.449 - 100 <= status < 200 or # 1xx codes
308.450 - self._method == 'HEAD'):
308.451 - self.length = 0
308.452 -
308.453 - # if the connection remains open, and we aren't using chunked, and
308.454 - # a content-length was not provided, then assume that the connection
308.455 - # WILL close.
308.456 - if not self.will_close and \
308.457 - not self.chunked and \
308.458 - self.length is None:
308.459 - self.will_close = 1
308.460 -
308.461 - def _check_close(self):
308.462 - conn = self.msg.getheader('connection')
308.463 - if self.version == 11:
308.464 - # An HTTP/1.1 proxy is assumed to stay open unless
308.465 - # explicitly closed.
308.466 - conn = self.msg.getheader('connection')
308.467 - if conn and "close" in conn.lower():
308.468 - return True
308.469 - return False
308.470 -
308.471 - # Some HTTP/1.0 implementations have support for persistent
308.472 - # connections, using rules different than HTTP/1.1.
308.473 -
308.474 - # For older HTTP, Keep-Alive indiciates persistent connection.
308.475 - if self.msg.getheader('keep-alive'):
308.476 - return False
308.477 -
308.478 - # At least Akamai returns a "Connection: Keep-Alive" header,
308.479 - # which was supposed to be sent by the client.
308.480 - if conn and "keep-alive" in conn.lower():
308.481 - return False
308.482 -
308.483 - # Proxy-Connection is a netscape hack.
308.484 - pconn = self.msg.getheader('proxy-connection')
308.485 - if pconn and "keep-alive" in pconn.lower():
308.486 - return False
308.487 -
308.488 - # otherwise, assume it will close
308.489 - return True
308.490 -
308.491 - def close(self):
308.492 - if self.fp:
308.493 - self.fp.close()
308.494 - self.fp = None
308.495 -
308.496 - def isclosed(self):
308.497 - # NOTE: it is possible that we will not ever call self.close(). This
308.498 - # case occurs when will_close is TRUE, length is None, and we
308.499 - # read up to the last byte, but NOT past it.
308.500 - #
308.501 - # IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
308.502 - # called, meaning self.isclosed() is meaningful.
308.503 - return self.fp is None
308.504 -
308.505 - # XXX It would be nice to have readline and __iter__ for this, too.
308.506 -
308.507 - def read(self, amt=None):
308.508 - if self.fp is None:
308.509 - return ''
308.510 -
308.511 - if self.chunked:
308.512 - return self._read_chunked(amt)
308.513 -
308.514 - if amt is None:
308.515 - # unbounded read
308.516 - if self.length is None:
308.517 - s = self.fp.read()
308.518 - else:
308.519 - s = self._safe_read(self.length)
308.520 - self.length = 0
308.521 - self.close() # we read everything
308.522 - return s
308.523 -
308.524 - if self.length is not None:
308.525 - if amt > self.length:
308.526 - # clip the read to the "end of response"
308.527 - amt = self.length
308.528 -
308.529 - # we do not use _safe_read() here because this may be a .will_close
308.530 - # connection, and the user is reading more bytes than will be provided
308.531 - # (for example, reading in 1k chunks)
308.532 - s = self.fp.read(amt)
308.533 - if self.length is not None:
308.534 - self.length -= len(s)
308.535 -
308.536 - return s
308.537 -
308.538 - def _read_chunked(self, amt):
308.539 - assert self.chunked != _UNKNOWN
308.540 - chunk_left = self.chunk_left
308.541 - value = ''
308.542 -
308.543 - # XXX This accumulates chunks by repeated string concatenation,
308.544 - # which is not efficient as the number or size of chunks gets big.
308.545 - while True:
308.546 - if chunk_left is None:
308.547 - line = self.fp.readline()
308.548 - i = line.find(';')
308.549 - if i >= 0:
308.550 - line = line[:i] # strip chunk-extensions
308.551 - chunk_left = int(line, 16)
308.552 - if chunk_left == 0:
308.553 - break
308.554 - if amt is None:
308.555 - value += self._safe_read(chunk_left)
308.556 - elif amt < chunk_left:
308.557 - value += self._safe_read(amt)
308.558 - self.chunk_left = chunk_left - amt
308.559 - return value
308.560 - elif amt == chunk_left:
308.561 - value += self._safe_read(amt)
308.562 - self._safe_read(2) # toss the CRLF at the end of the chunk
308.563 - self.chunk_left = None
308.564 - return value
308.565 - else:
308.566 - value += self._safe_read(chunk_left)
308.567 - amt -= chunk_left
308.568 -
308.569 - # we read the whole chunk, get another
308.570 - self._safe_read(2) # toss the CRLF at the end of the chunk
308.571 - chunk_left = None
308.572 -
308.573 - # read and discard trailer up to the CRLF terminator
308.574 - ### note: we shouldn't have any trailers!
308.575 - while True:
308.576 - line = self.fp.readline()
308.577 - if not line:
308.578 - # a vanishingly small number of sites EOF without
308.579 - # sending the trailer
308.580 - break
308.581 - if line == '\r\n':
308.582 - break
308.583 -
308.584 - # we read everything; close the "file"
308.585 - self.close()
308.586 -
308.587 - return value
308.588 -
308.589 - def _safe_read(self, amt):
308.590 - """Read the number of bytes requested, compensating for partial reads.
308.591 -
308.592 - Normally, we have a blocking socket, but a read() can be interrupted
308.593 - by a signal (resulting in a partial read).
308.594 -
308.595 - Note that we cannot distinguish between EOF and an interrupt when zero
308.596 - bytes have been read. IncompleteRead() will be raised in this
308.597 - situation.
308.598 -
308.599 - This function should be used when <amt> bytes "should" be present for
308.600 - reading. If the bytes are truly not available (due to EOF), then the
308.601 - IncompleteRead exception can be used to detect the problem.
308.602 - """
308.603 - s = []
308.604 - while amt > 0:
308.605 - chunk = self.fp.read(min(amt, MAXAMOUNT))
308.606 - if not chunk:
308.607 - raise IncompleteRead(s)
308.608 - s.append(chunk)
308.609 - amt -= len(chunk)
308.610 - return ''.join(s)
308.611 -
308.612 - def getheader(self, name, default=None):
308.613 - if self.msg is None:
308.614 - raise ResponseNotReady()
308.615 - return self.msg.getheader(name, default)
308.616 -
308.617 - def getheaders(self):
308.618 - """Return list of (header, value) tuples."""
308.619 - if self.msg is None:
308.620 - raise ResponseNotReady()
308.621 - return self.msg.items()
308.622 -
308.623 -
308.624 -class HTTPConnection:
308.625 -
308.626 - _http_vsn = 11
308.627 - _http_vsn_str = 'HTTP/1.1'
308.628 -
308.629 - response_class = HTTPResponse
308.630 - default_port = HTTP_PORT
308.631 - auto_open = 1
308.632 - debuglevel = 0
308.633 - strict = 0
308.634 -
308.635 - def __init__(self, host, port=None, strict=None):
308.636 - self.sock = None
308.637 - self._buffer = []
308.638 - self.__response = None
308.639 - self.__state = _CS_IDLE
308.640 - self._method = None
308.641 -
308.642 - self._set_hostport(host, port)
308.643 - if strict is not None:
308.644 - self.strict = strict
308.645 -
308.646 - def _set_hostport(self, host, port):
308.647 - if port is None:
308.648 - i = host.rfind(':')
308.649 - j = host.rfind(']') # ipv6 addresses have [...]
308.650 - if i > j:
308.651 - try:
308.652 - port = int(host[i+1:])
308.653 - except ValueError:
308.654 - raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
308.655 - host = host[:i]
308.656 - else:
308.657 - port = self.default_port
308.658 - if host and host[0] == '[' and host[-1] == ']':
308.659 - host = host[1:-1]
308.660 - self.host = host
308.661 - self.port = port
308.662 -
308.663 - def set_debuglevel(self, level):
308.664 - self.debuglevel = level
308.665 -
308.666 - def connect(self):
308.667 - """Connect to the host and port specified in __init__."""
308.668 - msg = "getaddrinfo returns an empty list"
308.669 - for res in socket.getaddrinfo(self.host, self.port, 0,
308.670 - socket.SOCK_STREAM):
308.671 - af, socktype, proto, canonname, sa = res
308.672 - try:
308.673 - self.sock = socket.socket(af, socktype, proto)
308.674 - if self.debuglevel > 0:
308.675 - print "connect: (%s, %s)" % (self.host, self.port)
308.676 - self.sock.connect(sa)
308.677 - except socket.error, msg:
308.678 - if self.debuglevel > 0:
308.679 - print 'connect fail:', (self.host, self.port)
308.680 - if self.sock:
308.681 - self.sock.close()
308.682 - self.sock = None
308.683 - continue
308.684 - break
308.685 - if not self.sock:
308.686 - raise socket.error, msg
308.687 -
308.688 - def close(self):
308.689 - """Close the connection to the HTTP server."""
308.690 - if self.sock:
308.691 - self.sock.close() # close it manually... there may be other refs
308.692 - self.sock = None
308.693 - if self.__response:
308.694 - self.__response.close()
308.695 - self.__response = None
308.696 - self.__state = _CS_IDLE
308.697 -
308.698 - def send(self, str):
308.699 - """Send `str' to the server."""
308.700 - if self.sock is None:
308.701 - if self.auto_open:
308.702 - self.connect()
308.703 - else:
308.704 - raise NotConnected()
308.705 -
308.706 - # send the data to the server. if we get a broken pipe, then close
308.707 - # the socket. we want to reconnect when somebody tries to send again.
308.708 - #
308.709 - # NOTE: we DO propagate the error, though, because we cannot simply
308.710 - # ignore the error... the caller will know if they can retry.
308.711 - if self.debuglevel > 0:
308.712 - print "send:", repr(str)
308.713 - try:
308.714 - self.sock.sendall(str)
308.715 - except socket.error, v:
308.716 - if v[0] == 32: # Broken pipe
308.717 - self.close()
308.718 - raise
308.719 -
308.720 - def _output(self, s):
308.721 - """Add a line of output to the current request buffer.
308.722 -
308.723 - Assumes that the line does *not* end with \\r\\n.
308.724 - """
308.725 - self._buffer.append(s)
308.726 -
308.727 - def _send_output(self):
308.728 - """Send the currently buffered request and clear the buffer.
308.729 -
308.730 - Appends an extra \\r\\n to the buffer.
308.731 - """
308.732 - self._buffer.extend(("", ""))
308.733 - msg = "\r\n".join(self._buffer)
308.734 - del self._buffer[:]
308.735 - self.send(msg)
308.736 -
308.737 - def putrequest(self, method, url, skip_host=0, skip_accept_encoding=0):
308.738 - """Send a request to the server.
308.739 -
308.740 - `method' specifies an HTTP request method, e.g. 'GET'.
308.741 - `url' specifies the object being requested, e.g. '/index.html'.
308.742 - `skip_host' if True does not add automatically a 'Host:' header
308.743 - `skip_accept_encoding' if True does not add automatically an
308.744 - 'Accept-Encoding:' header
308.745 - """
308.746 -
308.747 - # if a prior response has been completed, then forget about it.
308.748 - if self.__response and self.__response.isclosed():
308.749 - self.__response = None
308.750 -
308.751 -
308.752 - # in certain cases, we cannot issue another request on this connection.
308.753 - # this occurs when:
308.754 - # 1) we are in the process of sending a request. (_CS_REQ_STARTED)
308.755 - # 2) a response to a previous request has signalled that it is going
308.756 - # to close the connection upon completion.
308.757 - # 3) the headers for the previous response have not been read, thus
308.758 - # we cannot determine whether point (2) is true. (_CS_REQ_SENT)
308.759 - #
308.760 - # if there is no prior response, then we can request at will.
308.761 - #
308.762 - # if point (2) is true, then we will have passed the socket to the
308.763 - # response (effectively meaning, "there is no prior response"), and
308.764 - # will open a new one when a new request is made.
308.765 - #
308.766 - # Note: if a prior response exists, then we *can* start a new request.
308.767 - # We are not allowed to begin fetching the response to this new
308.768 - # request, however, until that prior response is complete.
308.769 - #
308.770 - if self.__state == _CS_IDLE:
308.771 - self.__state = _CS_REQ_STARTED
308.772 - else:
308.773 - raise CannotSendRequest()
308.774 -
308.775 - # Save the method we use, we need it later in the response phase
308.776 - self._method = method
308.777 - if not url:
308.778 - url = '/'
308.779 - str = '%s %s %s' % (method, url, self._http_vsn_str)
308.780 -
308.781 - self._output(str)
308.782 -
308.783 - if self._http_vsn == 11:
308.784 - # Issue some standard headers for better HTTP/1.1 compliance
308.785 -
308.786 - if not skip_host:
308.787 - # this header is issued *only* for HTTP/1.1
308.788 - # connections. more specifically, this means it is
308.789 - # only issued when the client uses the new
308.790 - # HTTPConnection() class. backwards-compat clients
308.791 - # will be using HTTP/1.0 and those clients may be
308.792 - # issuing this header themselves. we should NOT issue
308.793 - # it twice; some web servers (such as Apache) barf
308.794 - # when they see two Host: headers
308.795 -
308.796 - # If we need a non-standard port,include it in the
308.797 - # header. If the request is going through a proxy,
308.798 - # but the host of the actual URL, not the host of the
308.799 - # proxy.
308.800 -
308.801 - netloc = ''
308.802 - if url.startswith('http'):
308.803 - nil, netloc, nil, nil, nil = urlsplit(url)
308.804 -
308.805 - if netloc:
308.806 - try:
308.807 - netloc_enc = netloc.encode("ascii")
308.808 - except UnicodeEncodeError:
308.809 - netloc_enc = netloc.encode("idna")
308.810 - self.putheader('Host', netloc_enc)
308.811 - else:
308.812 - try:
308.813 - host_enc = self.host.encode("ascii")
308.814 - except UnicodeEncodeError:
308.815 - host_enc = self.host.encode("idna")
308.816 - if self.port == HTTP_PORT:
308.817 - self.putheader('Host', host_enc)
308.818 - else:
308.819 - self.putheader('Host', "%s:%s" % (host_enc, self.port))
308.820 -
308.821 - # note: we are assuming that clients will not attempt to set these
308.822 - # headers since *this* library must deal with the
308.823 - # consequences. this also means that when the supporting
308.824 - # libraries are updated to recognize other forms, then this
308.825 - # code should be changed (removed or updated).
308.826 -
308.827 - # we only want a Content-Encoding of "identity" since we don't
308.828 - # support encodings such as x-gzip or x-deflate.
308.829 - if not skip_accept_encoding:
308.830 - self.putheader('Accept-Encoding', 'identity')
308.831 -
308.832 - # we can accept "chunked" Transfer-Encodings, but no others
308.833 - # NOTE: no TE header implies *only* "chunked"
308.834 - #self.putheader('TE', 'chunked')
308.835 -
308.836 - # if TE is supplied in the header, then it must appear in a
308.837 - # Connection header.
308.838 - #self.putheader('Connection', 'TE')
308.839 -
308.840 - else:
308.841 - # For HTTP/1.0, the server will assume "not chunked"
308.842 - pass
308.843 -
308.844 - def putheader(self, header, value):
308.845 - """Send a request header line to the server.
308.846 -
308.847 - For example: h.putheader('Accept', 'text/html')
308.848 - """
308.849 - if self.__state != _CS_REQ_STARTED:
308.850 - raise CannotSendHeader()
308.851 -
308.852 - str = '%s: %s' % (header, value)
308.853 - self._output(str)
308.854 -
308.855 - def endheaders(self):
308.856 - """Indicate that the last header line has been sent to the server."""
308.857 -
308.858 - if self.__state == _CS_REQ_STARTED:
308.859 - self.__state = _CS_REQ_SENT
308.860 - else:
308.861 - raise CannotSendHeader()
308.862 -
308.863 - self._send_output()
308.864 -
308.865 - def request(self, method, url, body=None, headers={}):
308.866 - """Send a complete request to the server."""
308.867 -
308.868 - try:
308.869 - self._send_request(method, url, body, headers)
308.870 - except socket.error, v:
308.871 - # trap 'Broken pipe' if we're allowed to automatically reconnect
308.872 - if v[0] != 32 or not self.auto_open:
308.873 - raise
308.874 - # try one more time
308.875 - self._send_request(method, url, body, headers)
308.876 -
308.877 - def _send_request(self, method, url, body, headers):
308.878 - # honour explicitly requested Host: and Accept-Encoding headers
308.879 - header_names = dict.fromkeys([k.lower() for k in headers])
308.880 - skips = {}
308.881 - if 'host' in header_names:
308.882 - skips['skip_host'] = 1
308.883 - if 'accept-encoding' in header_names:
308.884 - skips['skip_accept_encoding'] = 1
308.885 -
308.886 - self.putrequest(method, url, **skips)
308.887 -
308.888 - if body and ('content-length' not in header_names):
308.889 - self.putheader('Content-Length', str(len(body)))
308.890 - for hdr, value in headers.iteritems():
308.891 - self.putheader(hdr, value)
308.892 - self.endheaders()
308.893 -
308.894 - if body:
308.895 - self.send(body)
308.896 -
308.897 - def getresponse(self):
308.898 - "Get the response from the server."
308.899 -
308.900 - # if a prior response has been completed, then forget about it.
308.901 - if self.__response and self.__response.isclosed():
308.902 - self.__response = None
308.903 -
308.904 - #
308.905 - # if a prior response exists, then it must be completed (otherwise, we
308.906 - # cannot read this response's header to determine the connection-close
308.907 - # behavior)
308.908 - #
308.909 - # note: if a prior response existed, but was connection-close, then the
308.910 - # socket and response were made independent of this HTTPConnection
308.911 - # object since a new request requires that we open a whole new
308.912 - # connection
308.913 - #
308.914 - # this means the prior response had one of two states:
308.915 - # 1) will_close: this connection was reset and the prior socket and
308.916 - # response operate independently
308.917 - # 2) persistent: the response was retained and we await its
308.918 - # isclosed() status to become true.
308.919 - #
308.920 - if self.__state != _CS_REQ_SENT or self.__response:
308.921 - raise ResponseNotReady()
308.922 -
308.923 - if self.debuglevel > 0:
308.924 - response = self.response_class(self.sock, self.debuglevel,
308.925 - strict=self.strict,
308.926 - method=self._method)
308.927 - else:
308.928 - response = self.response_class(self.sock, strict=self.strict,
308.929 - method=self._method)
308.930 -
308.931 - response.begin()
308.932 - assert response.will_close != _UNKNOWN
308.933 - self.__state = _CS_IDLE
308.934 -
308.935 - if response.will_close:
308.936 - # this effectively passes the connection to the response
308.937 - self.close()
308.938 - else:
308.939 - # remember this, so we can tell when it is complete
308.940 - self.__response = response
308.941 -
308.942 - return response
308.943 -
308.944 -# The next several classes are used to define FakeSocket, a socket-like
308.945 -# interface to an SSL connection.
308.946 -
308.947 -# The primary complexity comes from faking a makefile() method. The
308.948 -# standard socket makefile() implementation calls dup() on the socket
308.949 -# file descriptor. As a consequence, clients can call close() on the
308.950 -# parent socket and its makefile children in any order. The underlying
308.951 -# socket isn't closed until they are all closed.
308.952 -
308.953 -# The implementation uses reference counting to keep the socket open
308.954 -# until the last client calls close(). SharedSocket keeps track of
308.955 -# the reference counting and SharedSocketClient provides an constructor
308.956 -# and close() method that call incref() and decref() correctly.
308.957 -
308.958 -class SharedSocket:
308.959 -
308.960 - def __init__(self, sock):
308.961 - self.sock = sock
308.962 - self._refcnt = 0
308.963 -
308.964 - def incref(self):
308.965 - self._refcnt += 1
308.966 -
308.967 - def decref(self):
308.968 - self._refcnt -= 1
308.969 - assert self._refcnt >= 0
308.970 - if self._refcnt == 0:
308.971 - self.sock.close()
308.972 -
308.973 - def __del__(self):
308.974 - self.sock.close()
308.975 -
308.976 -class SharedSocketClient:
308.977 -
308.978 - def __init__(self, shared):
308.979 - self._closed = 0
308.980 - self._shared = shared
308.981 - self._shared.incref()
308.982 - self._sock = shared.sock
308.983 -
308.984 - def close(self):
308.985 - if not self._closed:
308.986 - self._shared.decref()
308.987 - self._closed = 1
308.988 - self._shared = None
308.989 -
308.990 -class SSLFile(SharedSocketClient):
308.991 - """File-like object wrapping an SSL socket."""
308.992 -
308.993 - BUFSIZE = 8192
308.994 -
308.995 - def __init__(self, sock, ssl, bufsize=None):
308.996 - SharedSocketClient.__init__(self, sock)
308.997 - self._ssl = ssl
308.998 - self._buf = ''
308.999 - self._bufsize = bufsize or self.__class__.BUFSIZE
308.1000 -
308.1001 - def _read(self):
308.1002 - buf = ''
308.1003 - # put in a loop so that we retry on transient errors
308.1004 - while True:
308.1005 - try:
308.1006 - buf = self._ssl.read(self._bufsize)
308.1007 - except socket.sslerror, err:
308.1008 - if (err[0] == socket.SSL_ERROR_WANT_READ
308.1009 - or err[0] == socket.SSL_ERROR_WANT_WRITE):
308.1010 - continue
308.1011 - if (err[0] == socket.SSL_ERROR_ZERO_RETURN
308.1012 - or err[0] == socket.SSL_ERROR_EOF):
308.1013 - break
308.1014 - raise
308.1015 - except socket.error, err:
308.1016 - if err[0] == errno.EINTR:
308.1017 - continue
308.1018 - if err[0] == errno.EBADF:
308.1019 - # XXX socket was closed?
308.1020 - break
308.1021 - raise
308.1022 - else:
308.1023 - break
308.1024 - return buf
308.1025 -
308.1026 - def read(self, size=None):
308.1027 - L = [self._buf]
308.1028 - avail = len(self._buf)
308.1029 - while size is None or avail < size:
308.1030 - s = self._read()
308.1031 - if s == '':
308.1032 - break
308.1033 - L.append(s)
308.1034 - avail += len(s)
308.1035 - all = "".join(L)
308.1036 - if size is None:
308.1037 - self._buf = ''
308.1038 - return all
308.1039 - else:
308.1040 - self._buf = all[size:]
308.1041 - return all[:size]
308.1042 -
308.1043 - def readline(self):
308.1044 - L = [self._buf]
308.1045 - self._buf = ''
308.1046 - while 1:
308.1047 - i = L[-1].find("\n")
308.1048 - if i >= 0:
308.1049 - break
308.1050 - s = self._read()
308.1051 - if s == '':
308.1052 - break
308.1053 - L.append(s)
308.1054 - if i == -1:
308.1055 - # loop exited because there is no more data
308.1056 - return "".join(L)
308.1057 - else:
308.1058 - all = "".join(L)
308.1059 - # XXX could do enough bookkeeping not to do a 2nd search
308.1060 - i = all.find("\n") + 1
308.1061 - line = all[:i]
308.1062 - self._buf = all[i:]
308.1063 - return line
308.1064 -
308.1065 - def readlines(self, sizehint=0):
308.1066 - total = 0
308.1067 - list = []
308.1068 - while True:
308.1069 - line = self.readline()
308.1070 - if not line:
308.1071 - break
308.1072 - list.append(line)
308.1073 - total += len(line)
308.1074 - if sizehint and total >= sizehint:
308.1075 - break
308.1076 - return list
308.1077 -
308.1078 - def fileno(self):
308.1079 - return self._sock.fileno()
308.1080 -
308.1081 - def __iter__(self):
308.1082 - return self
308.1083 -
308.1084 - def next(self):
308.1085 - line = self.readline()
308.1086 - if not line:
308.1087 - raise StopIteration
308.1088 - return line
308.1089 -
308.1090 -class FakeSocket(SharedSocketClient):
308.1091 -
308.1092 - class _closedsocket:
308.1093 - def __getattr__(self, name):
308.1094 - raise error(9, 'Bad file descriptor')
308.1095 -
308.1096 - def __init__(self, sock, ssl):
308.1097 - sock = SharedSocket(sock)
308.1098 - SharedSocketClient.__init__(self, sock)
308.1099 - self._ssl = ssl
308.1100 -
308.1101 - def close(self):
308.1102 - SharedSocketClient.close(self)
308.1103 - self._sock = self.__class__._closedsocket()
308.1104 -
308.1105 - def makefile(self, mode, bufsize=None):
308.1106 - if mode != 'r' and mode != 'rb':
308.1107 - raise UnimplementedFileMode()
308.1108 - return SSLFile(self._shared, self._ssl, bufsize)
308.1109 -
308.1110 - def send(self, stuff, flags = 0):
308.1111 - return self._ssl.write(stuff)
308.1112 -
308.1113 - sendall = send
308.1114 -
308.1115 - def recv(self, len = 1024, flags = 0):
308.1116 - return self._ssl.read(len)
308.1117 -
308.1118 - def __getattr__(self, attr):
308.1119 - return getattr(self._sock, attr)
308.1120 -
308.1121 -
308.1122 -class HTTPSConnection(HTTPConnection):
308.1123 - "This class allows communication via SSL."
308.1124 -
308.1125 - default_port = HTTPS_PORT
308.1126 -
308.1127 - def __init__(self, host, port=None, key_file=None, cert_file=None,
308.1128 - strict=None):
308.1129 - HTTPConnection.__init__(self, host, port, strict)
308.1130 - self.key_file = key_file
308.1131 - self.cert_file = cert_file
308.1132 -
308.1133 - def connect(self):
308.1134 - "Connect to a host on a given (SSL) port."
308.1135 -
308.1136 - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
308.1137 - sock.connect((self.host, self.port))
308.1138 - ssl = socket.ssl(sock, self.key_file, self.cert_file)
308.1139 - self.sock = FakeSocket(sock, ssl)
308.1140 -
308.1141 -
308.1142 -class HTTP:
308.1143 - "Compatibility class with httplib.py from 1.5."
308.1144 -
308.1145 - _http_vsn = 10
308.1146 - _http_vsn_str = 'HTTP/1.0'
308.1147 -
308.1148 - debuglevel = 0
308.1149 -
308.1150 - _connection_class = HTTPConnection
308.1151 -
308.1152 - def __init__(self, host='', port=None, strict=None):
308.1153 - "Provide a default host, since the superclass requires one."
308.1154 -
308.1155 - # some joker passed 0 explicitly, meaning default port
308.1156 - if port == 0:
308.1157 - port = None
308.1158 -
308.1159 - # Note that we may pass an empty string as the host; this will throw
308.1160 - # an error when we attempt to connect. Presumably, the client code
308.1161 - # will call connect before then, with a proper host.
308.1162 - self._setup(self._connection_class(host, port, strict))
308.1163 -
308.1164 - def _setup(self, conn):
308.1165 - self._conn = conn
308.1166 -
308.1167 - # set up delegation to flesh out interface
308.1168 - self.send = conn.send
308.1169 - self.putrequest = conn.putrequest
308.1170 - self.endheaders = conn.endheaders
308.1171 - self.set_debuglevel = conn.set_debuglevel
308.1172 -
308.1173 - conn._http_vsn = self._http_vsn
308.1174 - conn._http_vsn_str = self._http_vsn_str
308.1175 -
308.1176 - self.file = None
308.1177 -
308.1178 - def connect(self, host=None, port=None):
308.1179 - "Accept arguments to set the host/port, since the superclass doesn't."
308.1180 -
308.1181 - if host is not None:
308.1182 - self._conn._set_hostport(host, port)
308.1183 - self._conn.connect()
308.1184 -
308.1185 - def getfile(self):
308.1186 - "Provide a getfile, since the superclass' does not use this concept."
308.1187 - return self.file
308.1188 -
308.1189 - def putheader(self, header, *values):
308.1190 - "The superclass allows only one value argument."
308.1191 - self._conn.putheader(header, '\r\n\t'.join(values))
308.1192 -
308.1193 - def getreply(self):
308.1194 - """Compat definition since superclass does not define it.
308.1195 -
308.1196 - Returns a tuple consisting of:
308.1197 - - server status code (e.g. '200' if all goes well)
308.1198 - - server "reason" corresponding to status code
308.1199 - - any RFC822 headers in the response from the server
308.1200 - """
308.1201 - try:
308.1202 - response = self._conn.getresponse()
308.1203 - except BadStatusLine, e:
308.1204 - ### hmm. if getresponse() ever closes the socket on a bad request,
308.1205 - ### then we are going to have problems with self.sock
308.1206 -
308.1207 - ### should we keep this behavior? do people use it?
308.1208 - # keep the socket open (as a file), and return it
308.1209 - self.file = self._conn.sock.makefile('rb', 0)
308.1210 -
308.1211 - # close our socket -- we want to restart after any protocol error
308.1212 - self.close()
308.1213 -
308.1214 - self.headers = None
308.1215 - return -1, e.line, None
308.1216 -
308.1217 - self.headers = response.msg
308.1218 - self.file = response.fp
308.1219 - return response.status, response.reason, response.msg
308.1220 -
308.1221 - def close(self):
308.1222 - self._conn.close()
308.1223 -
308.1224 - # note that self.file == response.fp, which gets closed by the
308.1225 - # superclass. just clear the object ref here.
308.1226 - ### hmm. messy. if status==-1, then self.file is owned by us.
308.1227 - ### well... we aren't explicitly closing, but losing this ref will
308.1228 - ### do it
308.1229 - self.file = None
308.1230 -
308.1231 -if hasattr(socket, 'ssl'):
308.1232 - class HTTPS(HTTP):
308.1233 - """Compatibility with 1.5 httplib interface
308.1234 -
308.1235 - Python 1.5.2 did not have an HTTPS class, but it defined an
308.1236 - interface for sending http requests that is also useful for
308.1237 - https.
308.1238 - """
308.1239 -
308.1240 - _connection_class = HTTPSConnection
308.1241 -
308.1242 - def __init__(self, host='', port=None, key_file=None, cert_file=None,
308.1243 - strict=None):
308.1244 - # provide a default host, pass the X509 cert info
308.1245 -
308.1246 - # urf. compensate for bad input.
308.1247 - if port == 0:
308.1248 - port = None
308.1249 - self._setup(self._connection_class(host, port, key_file,
308.1250 - cert_file, strict))
308.1251 -
308.1252 - # we never actually use these for anything, but we keep them
308.1253 - # here for compatibility with post-1.5.2 CVS.
308.1254 - self.key_file = key_file
308.1255 - self.cert_file = cert_file
308.1256 -
308.1257 -
308.1258 -class HTTPException(Exception):
308.1259 - # Subclasses that define an __init__ must call Exception.__init__
308.1260 - # or define self.args. Otherwise, str() will fail.
308.1261 - pass
308.1262 -
308.1263 -class NotConnected(HTTPException):
308.1264 - pass
308.1265 -
308.1266 -class InvalidURL(HTTPException):
308.1267 - pass
308.1268 -
308.1269 -class UnknownProtocol(HTTPException):
308.1270 - def __init__(self, version):
308.1271 - self.args = version,
308.1272 - self.version = version
308.1273 -
308.1274 -class UnknownTransferEncoding(HTTPException):
308.1275 - pass
308.1276 -
308.1277 -class UnimplementedFileMode(HTTPException):
308.1278 - pass
308.1279 -
308.1280 -class IncompleteRead(HTTPException):
308.1281 - def __init__(self, partial):
308.1282 - self.args = partial,
308.1283 - self.partial = partial
308.1284 -
308.1285 -class ImproperConnectionState(HTTPException):
308.1286 - pass
308.1287 -
308.1288 -class CannotSendRequest(ImproperConnectionState):
308.1289 - pass
308.1290 -
308.1291 -class CannotSendHeader(ImproperConnectionState):
308.1292 - pass
308.1293 -
308.1294 -class ResponseNotReady(ImproperConnectionState):
308.1295 - pass
308.1296 -
308.1297 -class BadStatusLine(HTTPException):
308.1298 - def __init__(self, line):
308.1299 - self.args = line,
308.1300 - self.line = line
308.1301 -
308.1302 -# for backwards compatibility
308.1303 -error = HTTPException
308.1304 -
308.1305 -class LineAndFileWrapper:
308.1306 - """A limited file-like object for HTTP/0.9 responses."""
308.1307 -
308.1308 - # The status-line parsing code calls readline(), which normally
308.1309 - # get the HTTP status line. For a 0.9 response, however, this is
308.1310 - # actually the first line of the body! Clients need to get a
308.1311 - # readable file object that contains that line.
308.1312 -
308.1313 - def __init__(self, line, file):
308.1314 - self._line = line
308.1315 - self._file = file
308.1316 - self._line_consumed = 0
308.1317 - self._line_offset = 0
308.1318 - self._line_left = len(line)
308.1319 -
308.1320 - def __getattr__(self, attr):
308.1321 - return getattr(self._file, attr)
308.1322 -
308.1323 - def _done(self):
308.1324 - # called when the last byte is read from the line. After the
308.1325 - # call, all read methods are delegated to the underlying file
308.1326 - # object.
308.1327 - self._line_consumed = 1
308.1328 - self.read = self._file.read
308.1329 - self.readline = self._file.readline
308.1330 - self.readlines = self._file.readlines
308.1331 -
308.1332 - def read(self, amt=None):
308.1333 - if self._line_consumed:
308.1334 - return self._file.read(amt)
308.1335 - assert self._line_left
308.1336 - if amt is None or amt > self._line_left:
308.1337 - s = self._line[self._line_offset:]
308.1338 - self._done()
308.1339 - if amt is None:
308.1340 - return s + self._file.read()
308.1341 - else:
308.1342 - return s + self._file.read(amt - len(s))
308.1343 - else:
308.1344 - assert amt <= self._line_left
308.1345 - i = self._line_offset
308.1346 - j = i + amt
308.1347 - s = self._line[i:j]
308.1348 - self._line_offset = j
308.1349 - self._line_left -= amt
308.1350 - if self._line_left == 0:
308.1351 - self._done()
308.1352 - return s
308.1353 -
308.1354 - def readline(self):
308.1355 - if self._line_consumed:
308.1356 - return self._file.readline()
308.1357 - assert self._line_left
308.1358 - s = self._line[self._line_offset:]
308.1359 - self._done()
308.1360 - return s
308.1361 -
308.1362 - def readlines(self, size=None):
308.1363 - if self._line_consumed:
308.1364 - return self._file.readlines(size)
308.1365 - assert self._line_left
308.1366 - L = [self._line[self._line_offset:]]
308.1367 - self._done()
308.1368 - if size is None:
308.1369 - return L + self._file.readlines()
308.1370 - else:
308.1371 - return L + self._file.readlines(size)
308.1372 -
308.1373 -def test():
308.1374 - """Test this module.
308.1375 -
308.1376 - A hodge podge of tests collected here, because they have too many
308.1377 - external dependencies for the regular test suite.
308.1378 - """
308.1379 -
308.1380 - import sys
308.1381 - import getopt
308.1382 - opts, args = getopt.getopt(sys.argv[1:], 'd')
308.1383 - dl = 0
308.1384 - for o, a in opts:
308.1385 - if o == '-d': dl = dl + 1
308.1386 - host = 'www.python.org'
308.1387 - selector = '/'
308.1388 - if args[0:]: host = args[0]
308.1389 - if args[1:]: selector = args[1]
308.1390 - h = HTTP()
308.1391 - h.set_debuglevel(dl)
308.1392 - h.connect(host)
308.1393 - h.putrequest('GET', selector)
308.1394 - h.endheaders()
308.1395 - status, reason, headers = h.getreply()
308.1396 - print 'status =', status
308.1397 - print 'reason =', reason
308.1398 - print "read", len(h.getfile().read())
308.1399 - print
308.1400 - if headers:
308.1401 - for header in headers.headers: print header.strip()
308.1402 - print
308.1403 -
308.1404 - # minimal test that code to extract host from url works
308.1405 - class HTTP11(HTTP):
308.1406 - _http_vsn = 11
308.1407 - _http_vsn_str = 'HTTP/1.1'
308.1408 -
308.1409 - h = HTTP11('www.python.org')
308.1410 - h.putrequest('GET', 'http://www.python.org/~jeremy/')
308.1411 - h.endheaders()
308.1412 - h.getreply()
308.1413 - h.close()
308.1414 -
308.1415 - if hasattr(socket, 'ssl'):
308.1416 -
308.1417 - for host, selector in (('sourceforge.net', '/projects/python'),
308.1418 - ):
308.1419 - print "https://%s%s" % (host, selector)
308.1420 - hs = HTTPS()
308.1421 - hs.set_debuglevel(dl)
308.1422 - hs.connect(host)
308.1423 - hs.putrequest('GET', selector)
308.1424 - hs.endheaders()
308.1425 - status, reason, headers = hs.getreply()
308.1426 - print 'status =', status
308.1427 - print 'reason =', reason
308.1428 - print "read", len(hs.getfile().read())
308.1429 - print
308.1430 - if headers:
308.1431 - for header in headers.headers: print header.strip()
308.1432 - print
308.1433 -
308.1434 -if __name__ == '__main__':
308.1435 - test()
309.1 --- a/python.editor/test/unit/data/testfiles/httplib.py.indexed Sun Jan 04 13:11:53 2015 -0600
309.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
309.3 @@ -1,481 +0,0 @@
309.4 -
309.5 -
309.6 -Document 0
309.7 -Searchable Keys:
309.8 - class : BadStatusLine
309.9 - class-ig : badstatusline
309.10 - extends : HTTPException
309.11 - in : httplib
309.12 - member : __init__;c;|CONSTRUCTOR|;self,line;
309.13 - member : args;D;;
309.14 - member : line;D;;
309.15 -
309.16 -Not Searchable Keys:
309.17 -
309.18 -
309.19 -Document 1
309.20 -Searchable Keys:
309.21 - class : CannotSendHeader
309.22 - class-ig : cannotsendheader
309.23 - extends : ImproperConnectionState
309.24 - in : httplib
309.25 -
309.26 -Not Searchable Keys:
309.27 -
309.28 -
309.29 -Document 2
309.30 -Searchable Keys:
309.31 - class : CannotSendRequest
309.32 - class-ig : cannotsendrequest
309.33 - extends : ImproperConnectionState
309.34 - in : httplib
309.35 -
309.36 -Not Searchable Keys:
309.37 -
309.38 -
309.39 -Document 3
309.40 -Searchable Keys:
309.41 - class : FakeSocket
309.42 - class-ig : fakesocket
309.43 - extends : SharedSocketClient
309.44 - in : httplib
309.45 - item : _closedsocket;C;|PRIVATE|;
309.46 - member : __getattr__;F;|PRIVATE|;self,attr;
309.47 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,sock,ssl;
309.48 - member : _sock;D;|PRIVATE|;
309.49 - member : _ssl;D;|PRIVATE|;
309.50 - member : close;F;|PRIVATE|;self;
309.51 - member : makefile;F;|PRIVATE|;self,mode,bufsize;
309.52 - member : recv;F;|PRIVATE|;self,len,flags;
309.53 - member : send;F;|PRIVATE|;self,stuff,flags;
309.54 - member : sendall;F;|PRIVATE|;self,stuff,flags;
309.55 -
309.56 -Not Searchable Keys:
309.57 - clzattrs : ;|PRIVATE|;
309.58 -
309.59 -
309.60 -Document 4
309.61 -Searchable Keys:
309.62 - class : HTTP
309.63 - class-ig : http
309.64 - in : httplib
309.65 - member : __init__;c;|CONSTRUCTOR|;self,host,port,strict;
309.66 - member : _conn;D;|PRIVATE|;
309.67 - member : _connection_class;D;|PRIVATE|;
309.68 - member : _http_vsn;D;|PRIVATE|;
309.69 - member : _http_vsn_str;D;|PRIVATE|;
309.70 - member : _setup;F;|PRIVATE|;self,conn;
309.71 - member : close;F;;self;
309.72 - member : connect;F;;self,host,port;
309.73 - member : debuglevel;D;;
309.74 - member : endheaders;D;;
309.75 - member : file;D;;
309.76 - member : getfile;F;;self;
309.77 - member : getreply;F;;self;
309.78 - member : headers;D;;
309.79 - member : putheader;F;;self,header,values;
309.80 - member : putrequest;D;;
309.81 - member : send;D;;
309.82 - member : set_debuglevel;D;;
309.83 -
309.84 -Not Searchable Keys:
309.85 -
309.86 -
309.87 -Document 5
309.88 -Searchable Keys:
309.89 - class : HTTPConnection
309.90 - class-ig : httpconnection
309.91 - in : httplib
309.92 - member : __init__;c;|CONSTRUCTOR|;self,host,port,strict;
309.93 - member : __response;D;|PRIVATE|;
309.94 - member : __state;D;|PRIVATE|;
309.95 - member : _buffer;D;|PRIVATE|;
309.96 - member : _http_vsn;D;|PRIVATE|;
309.97 - member : _http_vsn_str;D;|PRIVATE|;
309.98 - member : _method;D;|PRIVATE|;
309.99 - member : _output;F;|PRIVATE|;self,s;
309.100 - member : _send_output;F;|PRIVATE|;self;
309.101 - member : _send_request;F;|PRIVATE|;self,method,url,body,headers;
309.102 - member : _set_hostport;F;|PRIVATE|;self,host,port;
309.103 - member : auto_open;D;;
309.104 - member : close;F;;self;
309.105 - member : connect;F;;self;
309.106 - member : debuglevel;D;;
309.107 - member : debuglevel;D;;
309.108 - member : default_port;D;;
309.109 - member : endheaders;F;;self;
309.110 - member : getresponse;F;;self;
309.111 - member : host;D;;
309.112 - member : port;D;;
309.113 - member : putheader;F;;self,header,value;
309.114 - member : putrequest;F;;self,method,url,skip_host,skip_accept_encoding;
309.115 - member : request;F;;self,method,url,body,headers;
309.116 - member : response_class;D;;
309.117 - member : send;F;;self,str;
309.118 - member : set_debuglevel;F;;self,level;
309.119 - member : sock;D;;
309.120 - member : strict;D;;
309.121 - member : strict;D;;
309.122 -
309.123 -Not Searchable Keys:
309.124 -
309.125 -
309.126 -Document 6
309.127 -Searchable Keys:
309.128 - class : HTTPException
309.129 - class-ig : httpexception
309.130 - extends : Exception
309.131 - in : httplib
309.132 -
309.133 -Not Searchable Keys:
309.134 -
309.135 -
309.136 -Document 7
309.137 -Searchable Keys:
309.138 - class : HTTPMessage
309.139 - class-ig : httpmessage
309.140 - extends : Message
309.141 - in : httplib
309.142 - member : addcontinue;F;|PRIVATE|;self,key,more;
309.143 - member : addheader;F;|PRIVATE|;self,key,value;
309.144 - member : dict;D;;
309.145 - member : headers;D;;
309.146 - member : readheaders;F;|PRIVATE|;self;
309.147 - member : seekable;D;;
309.148 - member : status;D;;
309.149 - member : unixfrom;D;;
309.150 -
309.151 -Not Searchable Keys:
309.152 - clzattrs : ;|PRIVATE|;
309.153 -
309.154 -
309.155 -Document 8
309.156 -Searchable Keys:
309.157 - class : HTTPResponse
309.158 - class-ig : httpresponse
309.159 - in : httplib
309.160 - member : __init__;c;|CONSTRUCTOR|;self,sock,debuglevel,strict,method;
309.161 - member : _check_close;F;|PRIVATE|;self;
309.162 - member : _method;D;|PRIVATE|;
309.163 - member : _read_chunked;F;|PRIVATE|;self,amt;
309.164 - member : _read_status;F;|PRIVATE|;self;
309.165 - member : _safe_read;F;|PRIVATE|;self,amt;
309.166 - member : begin;F;;self;
309.167 - member : chunk_left;D;;
309.168 - member : chunked;D;;
309.169 - member : close;F;;self;
309.170 - member : debuglevel;D;;
309.171 - member : fp;D;;
309.172 - member : getheader;F;;self,name,default;
309.173 - member : getheaders;F;;self;
309.174 - member : isclosed;F;;self;
309.175 - member : length;D;;
309.176 - member : msg;D;;
309.177 - member : read;F;;self,amt;
309.178 - member : reason;D;;
309.179 - member : status;D;;
309.180 - member : strict;D;;
309.181 - member : version;D;;
309.182 - member : will_close;D;;
309.183 -
309.184 -Not Searchable Keys:
309.185 -
309.186 -
309.187 -Document 9
309.188 -Searchable Keys:
309.189 - class : HTTPS
309.190 - class-ig : https
309.191 - extends : HTTP
309.192 - in : httplib
309.193 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,host,port,key_file,cert_file,strict;
309.194 - member : _connection_class;D;|PRIVATE|;
309.195 - member : cert_file;D;;
309.196 - member : key_file;D;;
309.197 -
309.198 -Not Searchable Keys:
309.199 - clzattrs : ;|PRIVATE|;
309.200 -
309.201 -
309.202 -Document 10
309.203 -Searchable Keys:
309.204 - class : HTTPSConnection
309.205 - class-ig : httpsconnection
309.206 - extends : HTTPConnection
309.207 - in : httplib
309.208 - member : __init__;c;|CONSTRUCTOR|;self,host,port,key_file,cert_file,strict;
309.209 - member : cert_file;D;;
309.210 - member : connect;F;;self;
309.211 - member : default_port;D;;
309.212 - member : key_file;D;;
309.213 - member : sock;D;;
309.214 -
309.215 -Not Searchable Keys:
309.216 -
309.217 -
309.218 -Document 11
309.219 -Searchable Keys:
309.220 - class : ImproperConnectionState
309.221 - class-ig : improperconnectionstate
309.222 - extends : HTTPException
309.223 - in : httplib
309.224 -
309.225 -Not Searchable Keys:
309.226 -
309.227 -
309.228 -Document 12
309.229 -Searchable Keys:
309.230 - class : IncompleteRead
309.231 - class-ig : incompleteread
309.232 - extends : HTTPException
309.233 - in : httplib
309.234 - member : __init__;c;|CONSTRUCTOR|;self,partial;
309.235 - member : args;D;;
309.236 - member : partial;D;;
309.237 -
309.238 -Not Searchable Keys:
309.239 -
309.240 -
309.241 -Document 13
309.242 -Searchable Keys:
309.243 - class : InvalidURL
309.244 - class-ig : invalidurl
309.245 - extends : HTTPException
309.246 - in : httplib
309.247 -
309.248 -Not Searchable Keys:
309.249 -
309.250 -
309.251 -Document 14
309.252 -Searchable Keys:
309.253 - class : LineAndFileWrapper
309.254 - class-ig : lineandfilewrapper
309.255 - in : httplib
309.256 - member : __getattr__;F;|PRIVATE|;self,attr;
309.257 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,line,file;
309.258 - member : _done;F;|PRIVATE|;self;
309.259 - member : _file;D;|PRIVATE|;
309.260 - member : _line;D;|PRIVATE|;
309.261 - member : _line_consumed;D;|PRIVATE|;
309.262 - member : _line_left;D;|PRIVATE|;
309.263 - member : _line_offset;D;|PRIVATE|;
309.264 - member : read;D;;
309.265 - member : read;F;|PRIVATE|;self,amt;
309.266 - member : readline;D;;
309.267 - member : readline;F;|PRIVATE|;self;
309.268 - member : readlines;D;;
309.269 - member : readlines;F;|PRIVATE|;self,size;
309.270 -
309.271 -Not Searchable Keys:
309.272 - clzattrs : ;|PRIVATE|;
309.273 -
309.274 -
309.275 -Document 15
309.276 -Searchable Keys:
309.277 - class : NotConnected
309.278 - class-ig : notconnected
309.279 - extends : HTTPException
309.280 - in : httplib
309.281 -
309.282 -Not Searchable Keys:
309.283 -
309.284 -
309.285 -Document 16
309.286 -Searchable Keys:
309.287 - class : ResponseNotReady
309.288 - class-ig : responsenotready
309.289 - extends : ImproperConnectionState
309.290 - in : httplib
309.291 -
309.292 -Not Searchable Keys:
309.293 -
309.294 -
309.295 -Document 17
309.296 -Searchable Keys:
309.297 - class : SSLFile
309.298 - class-ig : sslfile
309.299 - extends : SharedSocketClient
309.300 - in : httplib
309.301 - member : BUFSIZE;D;|PRIVATE|;
309.302 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,sock,ssl,bufsize;
309.303 - member : __iter__;F;|PRIVATE|;self;
309.304 - member : _buf;D;|PRIVATE|;
309.305 - member : _bufsize;D;|PRIVATE|;
309.306 - member : _read;F;|PRIVATE|;self;
309.307 - member : _ssl;D;|PRIVATE|;
309.308 - member : fileno;F;|PRIVATE|;self;
309.309 - member : next;F;|PRIVATE|;self;
309.310 - member : read;F;|PRIVATE|;self,size;
309.311 - member : readline;F;|PRIVATE|;self;
309.312 - member : readlines;F;|PRIVATE|;self,sizehint;
309.313 -
309.314 -Not Searchable Keys:
309.315 - clzattrs : ;|PRIVATE|;
309.316 -
309.317 -
309.318 -Document 18
309.319 -Searchable Keys:
309.320 - class : SharedSocket
309.321 - class-ig : sharedsocket
309.322 - in : httplib
309.323 - member : __del__;F;|PRIVATE|;self;
309.324 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,sock;
309.325 - member : _refcnt;D;|PRIVATE|;
309.326 - member : decref;F;|PRIVATE|;self;
309.327 - member : incref;F;|PRIVATE|;self;
309.328 - member : sock;D;;
309.329 -
309.330 -Not Searchable Keys:
309.331 - clzattrs : ;|PRIVATE|;
309.332 -
309.333 -
309.334 -Document 19
309.335 -Searchable Keys:
309.336 - class : SharedSocketClient
309.337 - class-ig : sharedsocketclient
309.338 - in : httplib
309.339 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,shared;
309.340 - member : _closed;D;|PRIVATE|;
309.341 - member : _shared;D;|PRIVATE|;
309.342 - member : _sock;D;|PRIVATE|;
309.343 - member : close;F;|PRIVATE|;self;
309.344 -
309.345 -Not Searchable Keys:
309.346 - clzattrs : ;|PRIVATE|;
309.347 -
309.348 -
309.349 -Document 20
309.350 -Searchable Keys:
309.351 - class : UnimplementedFileMode
309.352 - class-ig : unimplementedfilemode
309.353 - extends : HTTPException
309.354 - in : httplib
309.355 -
309.356 -Not Searchable Keys:
309.357 -
309.358 -
309.359 -Document 21
309.360 -Searchable Keys:
309.361 - class : UnknownProtocol
309.362 - class-ig : unknownprotocol
309.363 - extends : HTTPException
309.364 - in : httplib
309.365 - member : __init__;c;|CONSTRUCTOR|;self,version;
309.366 - member : args;D;;
309.367 - member : version;D;;
309.368 -
309.369 -Not Searchable Keys:
309.370 -
309.371 -
309.372 -Document 22
309.373 -Searchable Keys:
309.374 - class : UnknownTransferEncoding
309.375 - class-ig : unknowntransferencoding
309.376 - extends : HTTPException
309.377 - in : httplib
309.378 -
309.379 -Not Searchable Keys:
309.380 -
309.381 -
309.382 -Document 23
309.383 -Searchable Keys:
309.384 - class : error
309.385 - class-ig : error
309.386 - extends : Exception
309.387 - in : httplib
309.388 -
309.389 -Not Searchable Keys:
309.390 -
309.391 -
309.392 -Document 24
309.393 -Searchable Keys:
309.394 - item : ACCEPTED;D;|PRIVATE|;
309.395 - item : BAD_GATEWAY;D;|PRIVATE|;
309.396 - item : BAD_REQUEST;D;|PRIVATE|;
309.397 - item : BadStatusLine;C;;
309.398 - item : CONFLICT;D;|PRIVATE|;
309.399 - item : CONTINUE;D;|PRIVATE|;
309.400 - item : CREATED;D;|PRIVATE|;
309.401 - item : CannotSendHeader;C;;
309.402 - item : CannotSendRequest;C;;
309.403 - item : EXPECTATION_FAILED;D;|PRIVATE|;
309.404 - item : FAILED_DEPENDENCY;D;|PRIVATE|;
309.405 - item : FORBIDDEN;D;|PRIVATE|;
309.406 - item : FOUND;D;|PRIVATE|;
309.407 - item : FakeSocket;C;|PRIVATE|;
309.408 - item : GATEWAY_TIMEOUT;D;|PRIVATE|;
309.409 - item : GONE;D;|PRIVATE|;
309.410 - item : HTTP;C;;
309.411 - item : HTTPConnection;C;;
309.412 - item : HTTPException;C;;
309.413 - item : HTTPMessage;C;|PRIVATE|;
309.414 - item : HTTPResponse;C;;
309.415 - item : HTTPS;C;|PRIVATE|;
309.416 - item : HTTPSConnection;C;;
309.417 - item : HTTPS_PORT;D;|PRIVATE|;
309.418 - item : HTTP_PORT;D;|PRIVATE|;
309.419 - item : HTTP_VERSION_NOT_SUPPORTED;D;|PRIVATE|;
309.420 - item : IM_USED;D;|PRIVATE|;
309.421 - item : INSUFFICIENT_STORAGE;D;|PRIVATE|;
309.422 - item : INTERNAL_SERVER_ERROR;D;|PRIVATE|;
309.423 - item : ImproperConnectionState;C;;
309.424 - item : IncompleteRead;C;;
309.425 - item : InvalidURL;C;;
309.426 - item : LENGTH_REQUIRED;D;|PRIVATE|;
309.427 - item : LOCKED;D;|PRIVATE|;
309.428 - item : LineAndFileWrapper;C;|PRIVATE|;
309.429 - item : MAXAMOUNT;D;|PRIVATE|;
309.430 - item : METHOD_NOT_ALLOWED;D;|PRIVATE|;
309.431 - item : MOVED_PERMANENTLY;D;|PRIVATE|;
309.432 - item : MULTIPLE_CHOICES;D;|PRIVATE|;
309.433 - item : MULTI_STATUS;D;|PRIVATE|;
309.434 - item : NON_AUTHORITATIVE_INFORMATION;D;|PRIVATE|;
309.435 - item : NOT_ACCEPTABLE;D;|PRIVATE|;
309.436 - item : NOT_EXTENDED;D;|PRIVATE|;
309.437 - item : NOT_FOUND;D;|PRIVATE|;
309.438 - item : NOT_IMPLEMENTED;D;|PRIVATE|;
309.439 - item : NOT_MODIFIED;D;|PRIVATE|;
309.440 - item : NO_CONTENT;D;|PRIVATE|;
309.441 - item : NotConnected;C;;
309.442 - item : OK;D;|PRIVATE|;
309.443 - item : PARTIAL_CONTENT;D;|PRIVATE|;
309.444 - item : PAYMENT_REQUIRED;D;|PRIVATE|;
309.445 - item : PRECONDITION_FAILED;D;|PRIVATE|;
309.446 - item : PROCESSING;D;|PRIVATE|;
309.447 - item : PROXY_AUTHENTICATION_REQUIRED;D;|PRIVATE|;
309.448 - item : REQUESTED_RANGE_NOT_SATISFIABLE;D;|PRIVATE|;
309.449 - item : REQUEST_ENTITY_TOO_LARGE;D;|PRIVATE|;
309.450 - item : REQUEST_TIMEOUT;D;|PRIVATE|;
309.451 - item : REQUEST_URI_TOO_LONG;D;|PRIVATE|;
309.452 - item : RESET_CONTENT;D;|PRIVATE|;
309.453 - item : ResponseNotReady;C;;
309.454 - item : SEE_OTHER;D;|PRIVATE|;
309.455 - item : SERVICE_UNAVAILABLE;D;|PRIVATE|;
309.456 - item : SSLFile;C;|PRIVATE|;
309.457 - item : SWITCHING_PROTOCOLS;D;|PRIVATE|;
309.458 - item : SharedSocket;C;|PRIVATE|;
309.459 - item : SharedSocketClient;C;|PRIVATE|;
309.460 - item : StringIO;I;|PRIVATE|;
309.461 - item : TEMPORARY_REDIRECT;D;|PRIVATE|;
309.462 - item : UNAUTHORIZED;D;|PRIVATE|;
309.463 - item : UNPROCESSABLE_ENTITY;D;|PRIVATE|;
309.464 - item : UNSUPPORTED_MEDIA_TYPE;D;|PRIVATE|;
309.465 - item : UPGRADE_REQUIRED;D;|PRIVATE|;
309.466 - item : USE_PROXY;D;|PRIVATE|;
309.467 - item : UnimplementedFileMode;C;;
309.468 - item : UnknownProtocol;C;;
309.469 - item : UnknownTransferEncoding;C;;
309.470 - item : _CS_IDLE;D;|PRIVATE|;
309.471 - item : _CS_REQ_SENT;D;|PRIVATE|;
309.472 - item : _CS_REQ_STARTED;D;|PRIVATE|;
309.473 - item : _UNKNOWN;D;|PRIVATE|;
309.474 - item : __all__;D;;
309.475 - item : errno;I;|PRIVATE|;
309.476 - item : error;C;;
309.477 - item : mimetools;I;|PRIVATE|;
309.478 - item : responses;D;;
309.479 - item : socket;I;|PRIVATE|;
309.480 - item : test;F;|PRIVATE|;;
309.481 - item : urlsplit;I;|PRIVATE|;
309.482 - module : httplib
309.483 -
309.484 -Not Searchable Keys:
310.1 --- a/python.editor/test/unit/data/testfiles/imports/__init__.py Sun Jan 04 13:11:53 2015 -0600
310.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
310.3 @@ -1,5 +0,0 @@
310.4 -import efl
310.5 -import cocoa
310.6 -import console
310.7 -import curses
310.8 -
311.1 --- a/python.editor/test/unit/data/testfiles/imports/__init__.py.testFixInit2.imported Sun Jan 04 13:11:53 2015 -0600
311.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
311.3 @@ -1,6 +0,0 @@
311.4 -import curses
311.5 -
311.6 -import cocoa
311.7 -import console
311.8 -import efl
311.9 -
312.1 --- a/python.editor/test/unit/data/testfiles/imports/definitions.py Sun Jan 04 13:11:53 2015 -0600
312.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
312.3 @@ -1,9 +0,0 @@
312.4 -class DecimalException:
312.5 - def methodInClass(self):
312.6 - print foo
312.7 -
312.8 -
312.9 -class OtherClass:
312.10 - def otherMethodInClass(self,foo):
312.11 - print bar
312.12 -
313.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates1.py Sun Jan 04 13:11:53 2015 -0600
313.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
313.3 @@ -1,9 +0,0 @@
313.4 -"""My module"""
313.5 -import definitions
313.6 -import definitions
313.7 -import definitions
313.8 -import unused1
313.9 -import definitions
313.10 -
313.11 -x.otherMethodInClass()
313.12 -
314.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates1.py.imports Sun Jan 04 13:11:53 2015 -0600
314.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
314.3 @@ -1,5 +0,0 @@
314.4 -Requires user interaction: No
314.5 -Unused imports:
314.6 - unused1
314.7 -Duplicate imports:
314.8 - definitions
315.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates2.py Sun Jan 04 13:11:53 2015 -0600
315.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
315.3 @@ -1,9 +0,0 @@
315.4 -"""My module"""
315.5 -import definitions
315.6 -import definitions
315.7 -from definitions import Foo
315.8 -import unused1
315.9 -import definitions
315.10 -
315.11 -x.otherMethodInClass()
315.12 -
316.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates2.py.imports Sun Jan 04 13:11:53 2015 -0600
316.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
316.3 @@ -1,6 +0,0 @@
316.4 -Requires user interaction: No
316.5 -Unused imports:
316.6 - definitions:Foo
316.7 - unused1
316.8 -Duplicate imports:
316.9 - definitions
317.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates2.py.testFixDuplicates2b.imported Sun Jan 04 13:11:53 2015 -0600
317.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
317.3 @@ -1,7 +0,0 @@
317.4 -"""My module"""
317.5 -import definitions
317.6 -#from definitions import Foo
317.7 -#import unused1
317.8 -
317.9 -x.otherMethodInClass()
317.10 -
318.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates3.py Sun Jan 04 13:11:53 2015 -0600
318.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
318.3 @@ -1,9 +0,0 @@
318.4 -"""My module"""
318.5 -from definitions import Foo
318.6 -import definitions
318.7 -import definitions
318.8 -import unused1
318.9 -import definitions
318.10 -
318.11 -x.otherMethodInClass()
318.12 -
319.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates3.py.imports Sun Jan 04 13:11:53 2015 -0600
319.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
319.3 @@ -1,6 +0,0 @@
319.4 -Requires user interaction: No
319.5 -Unused imports:
319.6 - definitions:Foo
319.7 - unused1
319.8 -Duplicate imports:
319.9 - definitions
320.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates3.py.testFixDuplicates3b.imported Sun Jan 04 13:11:53 2015 -0600
320.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
320.3 @@ -1,7 +0,0 @@
320.4 -"""My module"""
320.5 -import definitions
320.6 -#from definitions import Foo
320.7 -#import unused1
320.8 -
320.9 -x.otherMethodInClass()
320.10 -
321.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates4.py Sun Jan 04 13:11:53 2015 -0600
321.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
321.3 @@ -1,9 +0,0 @@
321.4 -"""My module"""
321.5 -import unused1
321.6 -from definitions import Foo
321.7 -from definitions import Bar
321.8 -from definitions import Foo
321.9 -from definitions import Bar
321.10 -
321.11 -x.otherMethodInClass()
321.12 -
322.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates4.py.imports Sun Jan 04 13:11:53 2015 -0600
322.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
322.3 @@ -1,11 +0,0 @@
322.4 -Requires user interaction: No
322.5 -Unused imports:
322.6 - definitions:Bar
322.7 - definitions:Foo
322.8 - unused1
322.9 -Duplicate imports:
322.10 - definitions:Bar
322.11 - definitions:Foo
322.12 -Unresolved Symbols:
322.13 - otherMethodInClass
322.14 - *definitions
323.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates4.py.testFixDuplicates4b.imported Sun Jan 04 13:11:53 2015 -0600
323.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
323.3 @@ -1,8 +0,0 @@
323.4 -"""My module"""
323.5 -import definitions
323.6 -#from definitions import Bar
323.7 -#from definitions import Foo
323.8 -#import unused1
323.9 -
323.10 -x.otherMethodInClass()
323.11 -
324.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates5.py Sun Jan 04 13:11:53 2015 -0600
324.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
324.3 @@ -1,9 +0,0 @@
324.4 -"""My module"""
324.5 -import unused1
324.6 -from definitions import DecimalException
324.7 -from definitions import OtherClass, DecimalException
324.8 -
324.9 -x.otherMethodInClass()
324.10 -x = DecimalException();
324.11 -y = OtherClass();
324.12 -
325.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates5.py.imports Sun Jan 04 13:11:53 2015 -0600
325.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
325.3 @@ -1,8 +0,0 @@
325.4 -Requires user interaction: No
325.5 -Unused imports:
325.6 - unused1
325.7 -Duplicate imports:
325.8 - definitions:DecimalException
325.9 -Unresolved Symbols:
325.10 - otherMethodInClass
325.11 - *definitions
326.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates5.py.testFixDuplicates5b.imported Sun Jan 04 13:11:53 2015 -0600
326.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
326.3 @@ -1,10 +0,0 @@
326.4 -"""My module"""
326.5 -import definitions
326.6 -from definitions import DecimalException
326.7 -from definitions import OtherClass
326.8 -#import unused1
326.9 -
326.10 -x.otherMethodInClass()
326.11 -x = DecimalException();
326.12 -y = OtherClass();
326.13 -
327.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates6.py Sun Jan 04 13:11:53 2015 -0600
327.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
327.3 @@ -1,8 +0,0 @@
327.4 -"""My module"""
327.5 -import unused1
327.6 -from definitions import DecimalException
327.7 -from definitions import OtherClass, DecimalException
327.8 -
327.9 -x = DecimalException();
327.10 -y = OtherClass();
327.11 -
328.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates6.py.imports Sun Jan 04 13:11:53 2015 -0600
328.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
328.3 @@ -1,5 +0,0 @@
328.4 -Requires user interaction: No
328.5 -Unused imports:
328.6 - unused1
328.7 -Duplicate imports:
328.8 - definitions:DecimalException
329.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates6.py.testFixDuplicates6b.imported Sun Jan 04 13:11:53 2015 -0600
329.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
329.3 @@ -1,8 +0,0 @@
329.4 -"""My module"""
329.5 -from definitions import DecimalException
329.6 -from definitions import OtherClass
329.7 -#import unused1
329.8 -
329.9 -x = DecimalException();
329.10 -y = OtherClass();
329.11 -
330.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates7.py Sun Jan 04 13:11:53 2015 -0600
330.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
330.3 @@ -1,4 +0,0 @@
330.4 -import unused1
330.5 -from definitions import DecimalException, Unused
330.6 -
330.7 -x = DecimalException();
331.1 --- a/python.editor/test/unit/data/testfiles/imports/duplicates7.py.testFixDuplicates7.imported Sun Jan 04 13:11:53 2015 -0600
331.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
331.3 @@ -1,5 +0,0 @@
331.4 -from definitions import DecimalException
331.5 -#from definitions import Unused
331.6 -#import unused1
331.7 -
331.8 -x = DecimalException();
332.1 --- a/python.editor/test/unit/data/testfiles/imports/futures.py Sun Jan 04 13:11:53 2015 -0600
332.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
332.3 @@ -1,8 +0,0 @@
332.4 -# Ensure that the future imports here aren't shown as unused or imported symbols for code completion
332.5 -import ghi
332.6 -from abc import whatever
332.7 -from __future__ import with_statement, absolute_imports
332.8 -from __future__ import with_statement
332.9 -from def import whatever
332.10 -import jkl
332.11 -
333.1 --- a/python.editor/test/unit/data/testfiles/imports/futures.py.testSortFutureImports.imported Sun Jan 04 13:11:53 2015 -0600
333.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
333.3 @@ -1,8 +0,0 @@
333.4 -# Ensure that the future imports here aren't shown as unused or imported symbols for code completion
333.5 -from __future__ import absolute_imports
333.6 -from __future__ import with_statement
333.7 -import ghi
333.8 -from abc import whatever
333.9 -from def import whatever
333.10 -import jkl
333.11 -
334.1 --- a/python.editor/test/unit/data/testfiles/imports/imports1.py Sun Jan 04 13:11:53 2015 -0600
334.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
334.3 @@ -1,6 +0,0 @@
334.4 -import foo
334.5 -import bar as BAR
334.6 -import module1, module2, module3
334.7 -from module4 import Class1
334.8 -from module5 import Class2 as Class3
334.9 -
335.1 --- a/python.editor/test/unit/data/testfiles/imports/imports1.py.imports Sun Jan 04 13:11:53 2015 -0600
335.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
335.3 @@ -1,9 +0,0 @@
335.4 -Requires user interaction: No
335.5 -Unused imports:
335.6 - bar
335.7 - foo
335.8 - module1
335.9 - module2
335.10 - module3
335.11 - module4:Class1
335.12 - module5:Class2:Class3
336.1 --- a/python.editor/test/unit/data/testfiles/imports/imports1.py.testFixImports1.imported Sun Jan 04 13:11:53 2015 -0600
336.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
336.3 @@ -1,3 +0,0 @@
336.4 -import module2
336.5 -import module3
336.6 -
337.1 --- a/python.editor/test/unit/data/testfiles/imports/imports1.py.testFixImports2.imported Sun Jan 04 13:11:53 2015 -0600
337.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
337.3 @@ -1,8 +0,0 @@
337.4 -import module2
337.5 -import module3
337.6 -#import bar as BAR
337.7 -#import foo
337.8 -#import module1
337.9 -#from module4 import Class1
337.10 -#from module5 import Class2 as Class3
337.11 -
338.1 --- a/python.editor/test/unit/data/testfiles/imports/imports1.py.testFixOrganize6.imported Sun Jan 04 13:11:53 2015 -0600
338.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
338.3 @@ -1,8 +0,0 @@
338.4 -import bar as BAR
338.5 -import foo
338.6 -import module1
338.7 -import module2
338.8 -import module3
338.9 -from module4 import Class1
338.10 -from module5 import Class2 as Class3
338.11 -
339.1 --- a/python.editor/test/unit/data/testfiles/imports/imports2.py Sun Jan 04 13:11:53 2015 -0600
339.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
339.3 @@ -1,4 +0,0 @@
339.4 -"""My module"""
339.5 -
339.6 -x = DecimalException();
339.7 -
340.1 --- a/python.editor/test/unit/data/testfiles/imports/imports2.py.imports Sun Jan 04 13:11:53 2015 -0600
340.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
340.3 @@ -1,4 +0,0 @@
340.4 -Requires user interaction: No
340.5 -Unresolved Symbols:
340.6 - DecimalException
340.7 - *definitions
341.1 --- a/python.editor/test/unit/data/testfiles/imports/imports2.py.testFixImports3.imported Sun Jan 04 13:11:53 2015 -0600
341.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
341.3 @@ -1,4 +0,0 @@
341.4 -"""My module"""
341.5 -import decimal
341.6 -x = DecimalException();
341.7 -
342.1 --- a/python.editor/test/unit/data/testfiles/imports/imports3.py Sun Jan 04 13:11:53 2015 -0600
342.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
342.3 @@ -1,5 +0,0 @@
342.4 -"""My module"""
342.5 -import unused1
342.6 -
342.7 -x.otherMethodInClass()
342.8 -
343.1 --- a/python.editor/test/unit/data/testfiles/imports/imports3.py.imports Sun Jan 04 13:11:53 2015 -0600
343.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
343.3 @@ -1,6 +0,0 @@
343.4 -Requires user interaction: No
343.5 -Unused imports:
343.6 - unused1
343.7 -Unresolved Symbols:
343.8 - otherMethodInClass
343.9 - *definitions
344.1 --- a/python.editor/test/unit/data/testfiles/imports/imports3.py.testFixImports4.imported Sun Jan 04 13:11:53 2015 -0600
344.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
344.3 @@ -1,6 +0,0 @@
344.4 -"""My module"""
344.5 -import definitions
344.6 -#import unused1
344.7 -
344.8 -x.otherMethodInClass()
344.9 -
345.1 --- a/python.editor/test/unit/data/testfiles/imports/organize1.py Sun Jan 04 13:11:53 2015 -0600
345.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
345.3 @@ -1,30 +0,0 @@
345.4 -# Copyright 2008
345.5 -# Here we are
345.6 -"""Docs here"""
345.7 -
345.8 -__author__ = 'Tor Norbye'
345.9 -
345.10 -
345.11 -import sys
345.12 -import wsgiref.handlers
345.13 -from google.appengine.ext.webapp.util import run_wsgi_app
345.14 -from google.appengine.ext import webapp
345.15 -from google.appengine.ext import db
345.16 -import os
345.17 -from google.appengine.api import users
345.18 -from google.appengine.api import users
345.19 -from google.appengine.api import users
345.20 -import string
345.21 -from google.appengine.ext.webapp import template
345.22 -from google.appengine.ext.webapp.util import login_required
345.23 -import random
345.24 -import datetime
345.25 -
345.26 -def codehere():
345.27 - print "some code"
345.28 -
345.29 -if (true):
345.30 - import dont_touch_me
345.31 -
345.32 -
345.33 -
346.1 --- a/python.editor/test/unit/data/testfiles/imports/organize1.py.formatted Sun Jan 04 13:11:53 2015 -0600
346.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
346.3 @@ -1,29 +0,0 @@
346.4 -# Copyright 2008
346.5 -# Here we are
346.6 -"""Docs here"""
346.7 -
346.8 -__author__ = 'Tor Norbye'
346.9 -
346.10 -
346.11 -import datetime
346.12 -import os
346.13 -import random
346.14 -import string
346.15 -import sys
346.16 -import wsgiref.handlers
346.17 -
346.18 -from google.appengine.api import users
346.19 -from google.appengine.ext import db
346.20 -from google.appengine.ext import webapp
346.21 -from google.appengine.ext.webapp import template
346.22 -from google.appengine.ext.webapp.util import login_required
346.23 -from google.appengine.ext.webapp.util import run_wsgi_app
346.24 -
346.25 -def codehere():
346.26 - print "some code"
346.27 -
346.28 -if (true):
346.29 - import dont_touch_me
346.30 -
346.31 -
346.32 -
347.1 --- a/python.editor/test/unit/data/testfiles/imports/organize1.py.testFixOrganize1.imported Sun Jan 04 13:11:53 2015 -0600
347.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
347.3 @@ -1,29 +0,0 @@
347.4 -# Copyright 2008
347.5 -# Here we are
347.6 -"""Docs here"""
347.7 -
347.8 -__author__ = 'Tor Norbye'
347.9 -
347.10 -
347.11 -import datetime
347.12 -import os
347.13 -import random
347.14 -import string
347.15 -import sys
347.16 -import wsgiref.handlers
347.17 -
347.18 -from google.appengine.api import users
347.19 -from google.appengine.ext import db
347.20 -from google.appengine.ext import webapp
347.21 -from google.appengine.ext.webapp import template
347.22 -from google.appengine.ext.webapp.util import login_required
347.23 -from google.appengine.ext.webapp.util import run_wsgi_app
347.24 -
347.25 -def codehere():
347.26 - print "some code"
347.27 -
347.28 -if (true):
347.29 - import dont_touch_me
347.30 -
347.31 -
347.32 -
348.1 --- a/python.editor/test/unit/data/testfiles/imports/organize1.py.testFixOrganize2.imported Sun Jan 04 13:11:53 2015 -0600
348.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
348.3 @@ -1,27 +0,0 @@
348.4 -# Copyright 2008
348.5 -# Here we are
348.6 -"""Docs here"""
348.7 -
348.8 -__author__ = 'Tor Norbye'
348.9 -
348.10 -
348.11 -import datetime
348.12 -import os
348.13 -import random
348.14 -import string
348.15 -import sys
348.16 -import wsgiref.handlers
348.17 -
348.18 -from google.appengine.api import users
348.19 -from google.appengine.ext import db, webapp
348.20 -from google.appengine.ext.webapp import template
348.21 -from google.appengine.ext.webapp.util import login_required, run_wsgi_app
348.22 -
348.23 -def codehere():
348.24 - print "some code"
348.25 -
348.26 -if (true):
348.27 - import dont_touch_me
348.28 -
348.29 -
348.30 -
349.1 --- a/python.editor/test/unit/data/testfiles/imports/organize1.py.testFixOrganize3.imported Sun Jan 04 13:11:53 2015 -0600
349.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
349.3 @@ -1,29 +0,0 @@
349.4 -# Copyright 2008
349.5 -# Here we are
349.6 -"""Docs here"""
349.7 -
349.8 -__author__ = 'Tor Norbye'
349.9 -
349.10 -
349.11 -import datetime
349.12 -import os
349.13 -import random
349.14 -import string
349.15 -import sys
349.16 -import wsgiref.handlers
349.17 -
349.18 -from google.appengine.api import users
349.19 -from google.appengine.ext import db
349.20 -from google.appengine.ext import webapp
349.21 -from google.appengine.ext.webapp import template
349.22 -from google.appengine.ext.webapp.util import login_required
349.23 -from google.appengine.ext.webapp.util import run_wsgi_app
349.24 -
349.25 -def codehere():
349.26 - print "some code"
349.27 -
349.28 -if (true):
349.29 - import dont_touch_me
349.30 -
349.31 -
349.32 -
350.1 --- a/python.editor/test/unit/data/testfiles/imports/organize1.py.testFixOrganize4.imported Sun Jan 04 13:11:53 2015 -0600
350.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
350.3 @@ -1,28 +0,0 @@
350.4 -# Copyright 2008
350.5 -# Here we are
350.6 -"""Docs here"""
350.7 -
350.8 -__author__ = 'Tor Norbye'
350.9 -
350.10 -
350.11 -import datetime
350.12 -from google.appengine.api import users
350.13 -from google.appengine.ext import db
350.14 -from google.appengine.ext import webapp
350.15 -from google.appengine.ext.webapp import template
350.16 -from google.appengine.ext.webapp.util import login_required
350.17 -from google.appengine.ext.webapp.util import run_wsgi_app
350.18 -import os
350.19 -import random
350.20 -import string
350.21 -import sys
350.22 -import wsgiref.handlers
350.23 -
350.24 -def codehere():
350.25 - print "some code"
350.26 -
350.27 -if (true):
350.28 - import dont_touch_me
350.29 -
350.30 -
350.31 -
351.1 --- a/python.editor/test/unit/data/testfiles/imports/organize1.py.testFixOrganize5.imported Sun Jan 04 13:11:53 2015 -0600
351.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
351.3 @@ -1,27 +0,0 @@
351.4 -# Copyright 2008
351.5 -# Here we are
351.6 -"""Docs here"""
351.7 -
351.8 -__author__ = 'Tor Norbye'
351.9 -
351.10 -
351.11 -import datetime
351.12 -import os
351.13 -import random
351.14 -import string
351.15 -import sys
351.16 -import wsgiref.handlers
351.17 -
351.18 -from google.appengine.api import users
351.19 -from google.appengine.ext import db, webapp
351.20 -from google.appengine.ext.webapp import template
351.21 -from google.appengine.ext.webapp.util import login_required, run_wsgi_app
351.22 -
351.23 -def codehere():
351.24 - print "some code"
351.25 -
351.26 -if (true):
351.27 - import dont_touch_me
351.28 -
351.29 -
351.30 -
352.1 --- a/python.editor/test/unit/data/testfiles/imports/organize1.py.testFixOrganize7.imported Sun Jan 04 13:11:53 2015 -0600
352.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
352.3 @@ -1,29 +0,0 @@
352.4 -# Copyright 2008
352.5 -# Here we are
352.6 -"""Docs here"""
352.7 -
352.8 -__author__ = 'Tor Norbye'
352.9 -
352.10 -
352.11 -import sys
352.12 -import wsgiref.handlers
352.13 -import os
352.14 -import string
352.15 -import random
352.16 -import datetime
352.17 -
352.18 -from google.appengine.ext.webapp.util import run_wsgi_app
352.19 -from google.appengine.ext import webapp
352.20 -from google.appengine.ext import db
352.21 -from google.appengine.api import users
352.22 -from google.appengine.ext.webapp import template
352.23 -from google.appengine.ext.webapp.util import login_required
352.24 -
352.25 -def codehere():
352.26 - print "some code"
352.27 -
352.28 -if (true):
352.29 - import dont_touch_me
352.30 -
352.31 -
352.32 -
353.1 --- a/python.editor/test/unit/data/testfiles/imports/organize2.py Sun Jan 04 13:11:53 2015 -0600
353.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
353.3 @@ -1,5 +0,0 @@
353.4 -
353.5 -from bar import *
353.6 -from foo import *
353.7 -
353.8 -print "Hello"
354.1 --- a/python.editor/test/unit/data/testfiles/imports/organize2.py.testFixOrganize8.imported Sun Jan 04 13:11:53 2015 -0600
354.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
354.3 @@ -1,5 +0,0 @@
354.4 -
354.5 -from bar import *
354.6 -from foo import *
354.7 -
354.8 -print "Hello"
355.1 --- a/python.editor/test/unit/data/testfiles/imports/toplevel.py Sun Jan 04 13:11:53 2015 -0600
355.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
355.3 @@ -1,6 +0,0 @@
355.4 -try:
355.5 - import cStringIO as StringIO
355.6 -except ImportError:
355.7 - import StringIO
355.8 -
355.9 -
356.1 --- a/python.editor/test/unit/data/testfiles/imports3.py Sun Jan 04 13:11:53 2015 -0600
356.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
356.3 @@ -1,1 +0,0 @@
356.4 -import
357.1 --- a/python.editor/test/unit/data/testfiles/imports3.py.testImports3.completion Sun Jan 04 13:11:53 2015 -0600
357.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
357.3 @@ -1,634 +0,0 @@
357.4 -Code completion result for source line:
357.5 -import |
357.6 -(QueryType=COMPLETION, NameKind=PREFIX)
357.7 -------------------------------------
357.8 -KEYWORD BaseHTTPServer
357.9 -KEYWORD ---Bastion ---
357.10 -KEYWORD CGIHTTPServer
357.11 -KEYWORD ---Carbon.AE ---
357.12 -KEYWORD ---Carbon.AH ---
357.13 -KEYWORD ---Carbon.App ---
357.14 -KEYWORD ---Carbon.CF ---
357.15 -KEYWORD ---Carbon.CG ---
357.16 -KEYWORD ---Carbon.CarbonEvt ---
357.17 -KEYWORD ---Carbon.Cm ---
357.18 -KEYWORD ---Carbon.Ctl ---
357.19 -KEYWORD ---Carbon.Dlg ---
357.20 -KEYWORD ---Carbon.Evt ---
357.21 -KEYWORD ---Carbon.Fm ---
357.22 -KEYWORD ---Carbon.Folder ---
357.23 -KEYWORD ---Carbon.Help ---
357.24 -KEYWORD ---Carbon.List ---
357.25 -KEYWORD ---Carbon.Menu ---
357.26 -KEYWORD ---Carbon.Mlte ---
357.27 -KEYWORD ---Carbon.Qd ---
357.28 -KEYWORD ---Carbon.Qdoffs ---
357.29 -KEYWORD ---Carbon.Qt ---
357.30 -KEYWORD ---Carbon.Res ---
357.31 -KEYWORD ---Carbon.Scrap ---
357.32 -KEYWORD ---Carbon.Snd ---
357.33 -KEYWORD ---Carbon.TE ---
357.34 -KEYWORD ---Carbon.Win ---
357.35 -KEYWORD ---ColorPicker ---
357.36 -KEYWORD ConfigParser
357.37 -KEYWORD Cookie
357.38 -KEYWORD DocXMLRPCServer
357.39 -KEYWORD ---EasyDialogs ---
357.40 -KEYWORD ---FrameWork ---
357.41 -KEYWORD HTMLParser
357.42 -KEYWORD ---MacOS ---
357.43 -KEYWORD ---MimeWriter ---
357.44 -KEYWORD MiniAEFrame
357.45 -KEYWORD ---Nav ---
357.46 -KEYWORD ---PixMapWrapper ---
357.47 -KEYWORD Queue
357.48 -KEYWORD ScrolledText
357.49 -KEYWORD SimpleHTTPServer
357.50 -KEYWORD SimpleXMLRPCServer
357.51 -KEYWORD SocketServer
357.52 -KEYWORD StringIO
357.53 -KEYWORD Tix
357.54 -KEYWORD Tkinter
357.55 -KEYWORD UserDict
357.56 -KEYWORD UserList
357.57 -KEYWORD UserString
357.58 -KEYWORD ---W ---
357.59 -KEYWORD _LWPCookieJar
357.60 -KEYWORD _MozillaCookieJar
357.61 -KEYWORD __builtin__
357.62 -KEYWORD __future__
357.63 -KEYWORD __main__
357.64 -KEYWORD _ast
357.65 -KEYWORD _rawffi
357.66 -KEYWORD _strptime
357.67 -KEYWORD _threading_local
357.68 -KEYWORD _winreg
357.69 -KEYWORD abc
357.70 -KEYWORD ---aepack ---
357.71 -KEYWORD ---aetools ---
357.72 -KEYWORD ---aetypes ---
357.73 -KEYWORD aifc
357.74 -KEYWORD anydbm
357.75 -KEYWORD ---applesingle ---
357.76 -KEYWORD array
357.77 -KEYWORD ast
357.78 -KEYWORD asynchat
357.79 -KEYWORD asyncore
357.80 -KEYWORD atexit
357.81 -KEYWORD audioop
357.82 -KEYWORD ---autoGIL ---
357.83 -KEYWORD base64
357.84 -KEYWORD bdb
357.85 -KEYWORD binascii
357.86 -KEYWORD binhex
357.87 -KEYWORD bisect
357.88 -KEYWORD bsddb
357.89 -KEYWORD ---buildtools ---
357.90 -KEYWORD bz2
357.91 -KEYWORD calendar
357.92 -KEYWORD ---cfmfile ---
357.93 -KEYWORD cgi
357.94 -KEYWORD cgitb
357.95 -KEYWORD chunk
357.96 -KEYWORD cmath
357.97 -KEYWORD cmd
357.98 -KEYWORD code
357.99 -KEYWORD codecs
357.100 -KEYWORD codeop
357.101 -KEYWORD collections
357.102 -KEYWORD colorsys
357.103 -KEYWORD commands
357.104 -KEYWORD compileall
357.105 -KEYWORD compiler
357.106 -KEYWORD compiler.ast
357.107 -KEYWORD compiler.consts
357.108 -KEYWORD compiler.future
357.109 -KEYWORD compiler.misc
357.110 -KEYWORD compiler.pyassem
357.111 -KEYWORD compiler.pycodegen
357.112 -KEYWORD compiler.symbols
357.113 -KEYWORD compiler.syntax
357.114 -KEYWORD compiler.transformer
357.115 -KEYWORD compiler.visitor
357.116 -KEYWORD compl
357.117 -KEYWORD compl2
357.118 -KEYWORD compl3
357.119 -KEYWORD compl4
357.120 -KEYWORD compl5
357.121 -KEYWORD constants
357.122 -KEYWORD contextlib
357.123 -KEYWORD cookielib
357.124 -KEYWORD copy
357.125 -KEYWORD copy_reg
357.126 -KEYWORD crypt
357.127 -KEYWORD csv
357.128 -KEYWORD ctypes
357.129 -KEYWORD curses
357.130 -KEYWORD curses.ascii
357.131 -KEYWORD curses.panel
357.132 -KEYWORD curses.textpad
357.133 -KEYWORD curses.wrapper
357.134 -KEYWORD datetime
357.135 -KEYWORD dbexts
357.136 -KEYWORD dbhash
357.137 -KEYWORD dbm
357.138 -KEYWORD decimal
357.139 -KEYWORD difflib
357.140 -KEYWORD dircache
357.141 -KEYWORD dis
357.142 -KEYWORD distutils
357.143 -KEYWORD distutils.archive_util
357.144 -KEYWORD distutils.bcppcompiler
357.145 -KEYWORD distutils.ccompiler
357.146 -KEYWORD distutils.cmd
357.147 -KEYWORD distutils.command
357.148 -KEYWORD distutils.command.bdist
357.149 -KEYWORD distutils.command.bdist_dumb
357.150 -KEYWORD distutils.command.bdist_msi
357.151 -KEYWORD distutils.command.bdist_rpm
357.152 -KEYWORD distutils.command.bdist_winins
357.153 -KEYWORD distutils.command.build
357.154 -KEYWORD distutils.command.build_clib
357.155 -KEYWORD distutils.command.build_ext
357.156 -KEYWORD distutils.command.build_py
357.157 -KEYWORD distutils.command.build_script
357.158 -KEYWORD distutils.command.clean
357.159 -KEYWORD distutils.command.config
357.160 -KEYWORD distutils.command.install
357.161 -KEYWORD distutils.command.install_data
357.162 -KEYWORD distutils.command.install_egg_
357.163 -KEYWORD distutils.command.install_head
357.164 -KEYWORD distutils.command.install_lib
357.165 -KEYWORD distutils.command.install_scri
357.166 -KEYWORD distutils.command.register
357.167 -KEYWORD distutils.command.sdist
357.168 -KEYWORD distutils.command.upload
357.169 -KEYWORD distutils.core
357.170 -KEYWORD distutils.cygwinccompiler
357.171 -KEYWORD distutils.debug
357.172 -KEYWORD distutils.dep_util
357.173 -KEYWORD distutils.dir_util
357.174 -KEYWORD distutils.dist
357.175 -KEYWORD distutils.emxccompiler
357.176 -KEYWORD distutils.errors
357.177 -KEYWORD distutils.extension
357.178 -KEYWORD distutils.fancy_getopt
357.179 -KEYWORD distutils.file_util
357.180 -KEYWORD distutils.filelist
357.181 -KEYWORD distutils.jythoncompiler
357.182 -KEYWORD distutils.log
357.183 -KEYWORD distutils.msvccompiler
357.184 -KEYWORD distutils.mwerkscompiler
357.185 -KEYWORD distutils.spawn
357.186 -KEYWORD distutils.sysconfig
357.187 -KEYWORD distutils.tests
357.188 -KEYWORD distutils.tests.support
357.189 -KEYWORD distutils.tests.test_build_py
357.190 -KEYWORD distutils.tests.test_build_scr
357.191 -KEYWORD distutils.tests.test_dist
357.192 -KEYWORD distutils.tests.test_install
357.193 -KEYWORD distutils.tests.test_install_s
357.194 -KEYWORD distutils.tests.test_versionpr
357.195 -KEYWORD distutils.text_file
357.196 -KEYWORD distutils.unixccompiler
357.197 -KEYWORD distutils.util
357.198 -KEYWORD distutils.version
357.199 -KEYWORD distutils.versionpredicate
357.200 -KEYWORD ---dl ---
357.201 -KEYWORD doctest
357.202 -KEYWORD dumbdbm
357.203 -KEYWORD dummy_thread
357.204 -KEYWORD dummy_threading
357.205 -KEYWORD email
357.206 -KEYWORD email._parseaddr
357.207 -KEYWORD email.base64mime
357.208 -KEYWORD email.charset
357.209 -KEYWORD email.encoders
357.210 -KEYWORD email.errors
357.211 -KEYWORD email.feedparser
357.212 -KEYWORD email.generator
357.213 -KEYWORD email.header
357.214 -KEYWORD email.iterators
357.215 -KEYWORD email.message
357.216 -KEYWORD email.mime
357.217 -KEYWORD email.mime.application
357.218 -KEYWORD email.mime.audio
357.219 -KEYWORD email.mime.base
357.220 -KEYWORD email.mime.image
357.221 -KEYWORD email.mime.message
357.222 -KEYWORD email.mime.multipart
357.223 -KEYWORD email.mime.nonmultipart
357.224 -KEYWORD email.mime.text
357.225 -KEYWORD email.parser
357.226 -KEYWORD email.quoprimime
357.227 -KEYWORD email.test.test_email_torture
357.228 -KEYWORD email.utils
357.229 -KEYWORD encodings
357.230 -KEYWORD encodings.aliases
357.231 -KEYWORD encodings.ascii
357.232 -KEYWORD encodings.base64_codec
357.233 -KEYWORD encodings.big5
357.234 -KEYWORD encodings.big5hkscs
357.235 -KEYWORD encodings.bz2_codec
357.236 -KEYWORD encodings.charmap
357.237 -KEYWORD encodings.cp037
357.238 -KEYWORD encodings.cp1006
357.239 -KEYWORD encodings.cp1026
357.240 -KEYWORD encodings.cp1140
357.241 -KEYWORD encodings.cp1250
357.242 -KEYWORD encodings.cp1251
357.243 -KEYWORD encodings.cp1252
357.244 -KEYWORD encodings.cp1253
357.245 -KEYWORD encodings.cp1254
357.246 -KEYWORD encodings.cp1255
357.247 -KEYWORD encodings.cp1256
357.248 -KEYWORD encodings.cp1257
357.249 -KEYWORD encodings.cp1258
357.250 -KEYWORD encodings.cp424
357.251 -KEYWORD encodings.cp437
357.252 -KEYWORD encodings.cp500
357.253 -KEYWORD encodings.cp737
357.254 -KEYWORD encodings.cp775
357.255 -KEYWORD encodings.cp850
357.256 -KEYWORD encodings.cp852
357.257 -KEYWORD encodings.cp855
357.258 -KEYWORD encodings.cp856
357.259 -KEYWORD encodings.cp857
357.260 -KEYWORD encodings.cp860
357.261 -KEYWORD encodings.cp861
357.262 -KEYWORD encodings.cp862
357.263 -KEYWORD encodings.cp863
357.264 -KEYWORD encodings.cp864
357.265 -KEYWORD encodings.cp865
357.266 -KEYWORD encodings.cp866
357.267 -KEYWORD encodings.cp869
357.268 -KEYWORD encodings.cp874
357.269 -KEYWORD encodings.cp875
357.270 -KEYWORD encodings.cp932
357.271 -KEYWORD encodings.cp949
357.272 -KEYWORD encodings.cp950
357.273 -KEYWORD encodings.euc_jis_2004
357.274 -KEYWORD encodings.euc_jisx0213
357.275 -KEYWORD encodings.euc_jp
357.276 -KEYWORD encodings.euc_kr
357.277 -KEYWORD encodings.gb18030
357.278 -KEYWORD encodings.gb2312
357.279 -KEYWORD encodings.gbk
357.280 -KEYWORD encodings.hex_codec
357.281 -KEYWORD encodings.hp_roman8
357.282 -KEYWORD encodings.hz
357.283 -KEYWORD encodings.idna
357.284 -KEYWORD encodings.iso2022_jp
357.285 -KEYWORD encodings.iso2022_jp_1
357.286 -KEYWORD encodings.iso2022_jp_2
357.287 -KEYWORD encodings.iso2022_jp_2004
357.288 -KEYWORD encodings.iso2022_jp_3
357.289 -KEYWORD encodings.iso2022_jp_ext
357.290 -KEYWORD encodings.iso2022_kr
357.291 -KEYWORD encodings.iso8859_1
357.292 -KEYWORD encodings.iso8859_10
357.293 -KEYWORD encodings.iso8859_11
357.294 -KEYWORD encodings.iso8859_13
357.295 -KEYWORD encodings.iso8859_14
357.296 -KEYWORD encodings.iso8859_15
357.297 -KEYWORD encodings.iso8859_16
357.298 -KEYWORD encodings.iso8859_2
357.299 -KEYWORD encodings.iso8859_3
357.300 -KEYWORD encodings.iso8859_4
357.301 -KEYWORD encodings.iso8859_5
357.302 -KEYWORD encodings.iso8859_6
357.303 -KEYWORD encodings.iso8859_7
357.304 -KEYWORD encodings.iso8859_8
357.305 -KEYWORD encodings.iso8859_9
357.306 -KEYWORD encodings.johab
357.307 -KEYWORD encodings.koi8_r
357.308 -KEYWORD encodings.koi8_u
357.309 -KEYWORD encodings.latin_1
357.310 -KEYWORD encodings.mac_arabic
357.311 -KEYWORD encodings.mac_centeuro
357.312 -KEYWORD encodings.mac_croatian
357.313 -KEYWORD encodings.mac_cyrillic
357.314 -KEYWORD encodings.mac_farsi
357.315 -KEYWORD encodings.mac_greek
357.316 -KEYWORD encodings.mac_iceland
357.317 -KEYWORD encodings.mac_latin2
357.318 -KEYWORD encodings.mac_roman
357.319 -KEYWORD encodings.mac_romanian
357.320 -KEYWORD encodings.mac_turkish
357.321 -KEYWORD encodings.mbcs
357.322 -KEYWORD encodings.palmos
357.323 -KEYWORD encodings.ptcp154
357.324 -KEYWORD encodings.punycode
357.325 -KEYWORD encodings.quopri_codec
357.326 -KEYWORD encodings.raw_unicode_escape
357.327 -KEYWORD encodings.rot_13
357.328 -KEYWORD encodings.shift_jis
357.329 -KEYWORD encodings.shift_jis_2004
357.330 -KEYWORD encodings.shift_jisx0213
357.331 -KEYWORD encodings.string_escape
357.332 -KEYWORD encodings.tis_620
357.333 -KEYWORD encodings.undefined
357.334 -KEYWORD encodings.unicode_escape
357.335 -KEYWORD encodings.unicode_internal
357.336 -KEYWORD encodings.utf_16
357.337 -KEYWORD encodings.utf_16_be
357.338 -KEYWORD encodings.utf_16_le
357.339 -KEYWORD encodings.utf_7
357.340 -KEYWORD encodings.utf_8
357.341 -KEYWORD encodings.utf_8_sig
357.342 -KEYWORD encodings.uu_codec
357.343 -KEYWORD encodings.zlib_codec
357.344 -KEYWORD errno
357.345 -KEYWORD exceptions
357.346 -KEYWORD fcntl
357.347 -KEYWORD filecmp
357.348 -KEYWORD fileinput
357.349 -KEYWORD findertools
357.350 -KEYWORD fnmatch
357.351 -KEYWORD formatter
357.352 -KEYWORD fpectl
357.353 -KEYWORD fpformat
357.354 -KEYWORD fractions
357.355 -KEYWORD ftplib
357.356 -KEYWORD functions
357.357 -KEYWORD functools
357.358 -KEYWORD future_builtins
357.359 -KEYWORD gc
357.360 -KEYWORD gdbm
357.361 -KEYWORD gensuitemodule
357.362 -KEYWORD getopt
357.363 -KEYWORD getpass
357.364 -KEYWORD gettext
357.365 -KEYWORD glob
357.366 -KEYWORD ---gopherlib ---
357.367 -KEYWORD grp
357.368 -KEYWORD gzip
357.369 -KEYWORD hashlib
357.370 -KEYWORD heapq
357.371 -KEYWORD hmac
357.372 -KEYWORD hotshot
357.373 -KEYWORD hotshot.stats
357.374 -KEYWORD htmlentitydefs
357.375 -KEYWORD htmllib
357.376 -KEYWORD httplib
357.377 -KEYWORD ---ic ---
357.378 -KEYWORD ---icopen ---
357.379 -KEYWORD ihooks
357.380 -KEYWORD ---imageop ---
357.381 -KEYWORD imaplib
357.382 -KEYWORD imghdr
357.383 -KEYWORD imp
357.384 -KEYWORD imports3
357.385 -KEYWORD imports7
357.386 -KEYWORD imports8
357.387 -KEYWORD imports9
357.388 -KEYWORD ---imputil ---
357.389 -KEYWORD inspect
357.390 -KEYWORD io
357.391 -KEYWORD isql
357.392 -KEYWORD itertools
357.393 -KEYWORD javapath
357.394 -KEYWORD javashell
357.395 -KEYWORD jreload
357.396 -KEYWORD json
357.397 -KEYWORD keyword
357.398 -KEYWORD lib2to3
357.399 -KEYWORD linecache
357.400 -KEYWORD locale
357.401 -KEYWORD logging
357.402 -KEYWORD logging.config
357.403 -KEYWORD logging.handlers
357.404 -KEYWORD ---macerrors ---
357.405 -KEYWORD ---macostools ---
357.406 -KEYWORD macpath
357.407 -KEYWORD ---macresource ---
357.408 -KEYWORD macurl2path
357.409 -KEYWORD mailbox
357.410 -KEYWORD mailcap
357.411 -KEYWORD markupbase
357.412 -KEYWORD marshal
357.413 -KEYWORD math
357.414 -KEYWORD ---md5 ---
357.415 -KEYWORD mhlib
357.416 -KEYWORD ---mimetools ---
357.417 -KEYWORD mimetypes
357.418 -KEYWORD ---mimify ---
357.419 -KEYWORD mmap
357.420 -KEYWORD modulefinder
357.421 -KEYWORD msilib
357.422 -KEYWORD msvcrt
357.423 -KEYWORD ---multifile ---
357.424 -KEYWORD multiprocessing
357.425 -KEYWORD multiprocessing.connection
357.426 -KEYWORD multiprocessing.dummy
357.427 -KEYWORD multiprocessing.managers
357.428 -KEYWORD multiprocessing.pool
357.429 -KEYWORD multiprocessing.sharedctypes
357.430 -KEYWORD mutex
357.431 -KEYWORD netrc
357.432 -KEYWORD new
357.433 -KEYWORD nis
357.434 -KEYWORD nntplib
357.435 -KEYWORD ntpath
357.436 -KEYWORD nturl2path
357.437 -KEYWORD numbers
357.438 -KEYWORD occurrences2
357.439 -KEYWORD opcode
357.440 -KEYWORD operator
357.441 -KEYWORD optparse
357.442 -KEYWORD os
357.443 -KEYWORD os.path
357.444 -KEYWORD ossaudiodev
357.445 -KEYWORD parser
357.446 -KEYWORD pawt
357.447 -KEYWORD pawt.colors
357.448 -KEYWORD pawt.swing
357.449 -KEYWORD pdb
357.450 -KEYWORD pickle
357.451 -KEYWORD pickletools
357.452 -KEYWORD pipes
357.453 -KEYWORD pkgutil
357.454 -KEYWORD platform
357.455 -KEYWORD plistlib
357.456 -KEYWORD popen2
357.457 -KEYWORD poplib
357.458 -KEYWORD posix
357.459 -KEYWORD ---posixfile ---
357.460 -KEYWORD posixpath
357.461 -KEYWORD pprint
357.462 -KEYWORD profile
357.463 -KEYWORD pstats
357.464 -KEYWORD pty
357.465 -KEYWORD pwd
357.466 -KEYWORD py_compile
357.467 -KEYWORD pyclbr
357.468 -KEYWORD pydoc
357.469 -KEYWORD quopri
357.470 -KEYWORD random
357.471 -KEYWORD re
357.472 -KEYWORD readline
357.473 -KEYWORD repr
357.474 -KEYWORD resource
357.475 -KEYWORD ---rexec ---
357.476 -KEYWORD ---rfc822 ---
357.477 -KEYWORD rlcompleter
357.478 -KEYWORD robotparser
357.479 -KEYWORD runpy
357.480 -KEYWORD sched
357.481 -KEYWORD select
357.482 -KEYWORD ---sets ---
357.483 -KEYWORD sgmllib
357.484 -KEYWORD ---sha ---
357.485 -KEYWORD shelve
357.486 -KEYWORD shlex
357.487 -KEYWORD shutil
357.488 -KEYWORD signal
357.489 -KEYWORD site
357.490 -KEYWORD smtpd
357.491 -KEYWORD smtplib
357.492 -KEYWORD sndhdr
357.493 -KEYWORD socket
357.494 -KEYWORD spwd
357.495 -KEYWORD sqlite3
357.496 -KEYWORD sre
357.497 -KEYWORD sre_compile
357.498 -KEYWORD sre_constants
357.499 -KEYWORD sre_parse
357.500 -KEYWORD ssl
357.501 -KEYWORD stat
357.502 -KEYWORD ---statvfs ---
357.503 -KEYWORD stdtypes
357.504 -KEYWORD string
357.505 -KEYWORD ---stringprep ---
357.506 -KEYWORD struct
357.507 -KEYWORD subprocess
357.508 -KEYWORD symbol
357.509 -KEYWORD symtable
357.510 -KEYWORD sys
357.511 -KEYWORD syslog
357.512 -KEYWORD tabnanny
357.513 -KEYWORD tarfile
357.514 -KEYWORD telnetlib
357.515 -KEYWORD tempfile
357.516 -KEYWORD termios
357.517 -KEYWORD test.bugs.bugs100
357.518 -KEYWORD test.bugs.bugs101
357.519 -KEYWORD test.bugs.jdkbugs
357.520 -KEYWORD test.bugs.pr101
357.521 -KEYWORD test.bugs.pr104
357.522 -KEYWORD test.bugs.pr112
357.523 -KEYWORD test.bugs.pr119
357.524 -KEYWORD test.bugs.pr127
357.525 -KEYWORD test.bugs.pr133
357.526 -KEYWORD test.bugs.pr133.test
357.527 -KEYWORD test.bugs.pr134
357.528 -KEYWORD test.bugs.pr139
357.529 -KEYWORD test.bugs.pr142
357.530 -KEYWORD test.bugs.pr144
357.531 -KEYWORD test.bugs.pr148
357.532 -KEYWORD test.bugs.pr149
357.533 -KEYWORD test.bugs.pr155
357.534 -KEYWORD test.bugs.pr170
357.535 -KEYWORD test.bugs.pr171
357.536 -KEYWORD test.bugs.pr174
357.537 -KEYWORD test.bugs.pr178
357.538 -KEYWORD test.bugs.pr183
357.539 -KEYWORD test.bugs.pr186
357.540 -KEYWORD test.bugs.pr191
357.541 -KEYWORD test.bugs.pr192
357.542 -KEYWORD test.bugs.pr195
357.543 -KEYWORD test.bugs.pr208
357.544 -KEYWORD test.bugs.pr233
357.545 -KEYWORD test.bugs.pr234
357.546 -KEYWORD test.bugs.pr235
357.547 -KEYWORD test.bugs.pr239
357.548 -KEYWORD test.bugs.pr241
357.549 -KEYWORD test.bugs.pr242
357.550 -KEYWORD test.crashers.bogus_code_obj
357.551 -KEYWORD test.crashers.borrowed_ref_1
357.552 -KEYWORD test.crashers.borrowed_ref_2
357.553 -KEYWORD test.crashers.gc_inspection
357.554 -KEYWORD test.crashers.infinite_rec_1
357.555 -KEYWORD test.crashers.infinite_rec_2
357.556 -KEYWORD test.crashers.infinite_rec_4
357.557 -KEYWORD test.crashers.infinite_rec_5
357.558 -KEYWORD test.crashers.loosing_dict_ref
357.559 -KEYWORD test.crashers.nasty_eq_vs_dict
357.560 -KEYWORD test.crashers.recursion_limit_
357.561 -KEYWORD test.crashers.recursive_call
357.562 -KEYWORD test.leakers
357.563 -KEYWORD test.leakers.test_ctypes
357.564 -KEYWORD test.leakers.test_gestalt
357.565 -KEYWORD test.leakers.test_selftype
357.566 -KEYWORD test.test_metaclass_support
357.567 -KEYWORD test.test_metaclass_support.me
357.568 -KEYWORD test.test_metaclass_support.si
357.569 -KEYWORD test.xmltests
357.570 -KEYWORD test.zxjdbc.dbextstest
357.571 -KEYWORD test.zxjdbc.jndi
357.572 -KEYWORD test.zxjdbc.runner
357.573 -KEYWORD test.zxjdbc.sptest
357.574 -KEYWORD test.zxjdbc.test_zxjdbc_dbapi2
357.575 -KEYWORD test.zxjdbc.zxtest
357.576 -KEYWORD textwrap
357.577 -KEYWORD this
357.578 -KEYWORD thread
357.579 -KEYWORD threading
357.580 -KEYWORD time
357.581 -KEYWORD timeit
357.582 -KEYWORD token
357.583 -KEYWORD tokenize
357.584 -KEYWORD trace
357.585 -KEYWORD traceback
357.586 -KEYWORD tty
357.587 -KEYWORD turtle
357.588 -KEYWORD types
357.589 -KEYWORD unicodedata
357.590 -KEYWORD unittest
357.591 -KEYWORD urllib
357.592 -KEYWORD urllib2
357.593 -KEYWORD urlparse
357.594 -KEYWORD user
357.595 -KEYWORD uu
357.596 -KEYWORD uuid
357.597 -KEYWORD ---videoreader ---
357.598 -KEYWORD warnings
357.599 -KEYWORD wave
357.600 -KEYWORD weakref
357.601 -KEYWORD webbrowser
357.602 -KEYWORD whichdb
357.603 -KEYWORD winsound
357.604 -KEYWORD wsgiref
357.605 -KEYWORD wsgiref.handlers
357.606 -KEYWORD wsgiref.headers
357.607 -KEYWORD wsgiref.simple_server
357.608 -KEYWORD wsgiref.util
357.609 -KEYWORD wsgiref.validate
357.610 -KEYWORD xdrlib
357.611 -KEYWORD xml
357.612 -KEYWORD xml.FtCore
357.613 -KEYWORD xml.Uri
357.614 -KEYWORD xml.dom
357.615 -KEYWORD xml.dom.MessageSource
357.616 -KEYWORD xml.dom.NodeFilter
357.617 -KEYWORD xml.dom.domreg
357.618 -KEYWORD xml.dom.minicompat
357.619 -KEYWORD xml.dom.minidom
357.620 -KEYWORD xml.dom.pulldom
357.621 -KEYWORD xml.dom.xmlbuilder
357.622 -KEYWORD xml.etree
357.623 -KEYWORD xml.etree.ElementTree
357.624 -KEYWORD xml.parsers.expat
357.625 -KEYWORD xml.sax
357.626 -KEYWORD xml.sax._exceptions
357.627 -KEYWORD xml.sax.drivers2
357.628 -KEYWORD xml.sax.drivers2.drv_javasax
357.629 -KEYWORD xml.sax.handler
357.630 -KEYWORD xml.sax.saxlib
357.631 -KEYWORD xml.sax.saxutils
357.632 -KEYWORD xml.sax.xmlreader
357.633 -KEYWORD xmllib
357.634 -KEYWORD xmlrpclib
357.635 -KEYWORD zipfile
357.636 -KEYWORD zipimport
357.637 -KEYWORD zlib
358.1 --- a/python.editor/test/unit/data/testfiles/imports4.py Sun Jan 04 13:11:53 2015 -0600
358.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
358.3 @@ -1,4 +0,0 @@
358.4 -import
358.5 -
358.6 -
358.7 -
359.1 --- a/python.editor/test/unit/data/testfiles/imports4.py.testImports4.completion Sun Jan 04 13:11:53 2015 -0600
359.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
359.3 @@ -1,635 +0,0 @@
359.4 -Code completion result for source line:
359.5 -import |
359.6 -(QueryType=COMPLETION, NameKind=PREFIX)
359.7 -------------------------------------
359.8 -KEYWORD BaseHTTPServer
359.9 -KEYWORD ---Bastion ---
359.10 -KEYWORD CGIHTTPServer
359.11 -KEYWORD ---Carbon.AE ---
359.12 -KEYWORD ---Carbon.AH ---
359.13 -KEYWORD ---Carbon.App ---
359.14 -KEYWORD ---Carbon.CF ---
359.15 -KEYWORD ---Carbon.CG ---
359.16 -KEYWORD ---Carbon.CarbonEvt ---
359.17 -KEYWORD ---Carbon.Cm ---
359.18 -KEYWORD ---Carbon.Ctl ---
359.19 -KEYWORD ---Carbon.Dlg ---
359.20 -KEYWORD ---Carbon.Evt ---
359.21 -KEYWORD ---Carbon.Fm ---
359.22 -KEYWORD ---Carbon.Folder ---
359.23 -KEYWORD ---Carbon.Help ---
359.24 -KEYWORD ---Carbon.List ---
359.25 -KEYWORD ---Carbon.Menu ---
359.26 -KEYWORD ---Carbon.Mlte ---
359.27 -KEYWORD ---Carbon.Qd ---
359.28 -KEYWORD ---Carbon.Qdoffs ---
359.29 -KEYWORD ---Carbon.Qt ---
359.30 -KEYWORD ---Carbon.Res ---
359.31 -KEYWORD ---Carbon.Scrap ---
359.32 -KEYWORD ---Carbon.Snd ---
359.33 -KEYWORD ---Carbon.TE ---
359.34 -KEYWORD ---Carbon.Win ---
359.35 -KEYWORD ---ColorPicker ---
359.36 -KEYWORD ConfigParser
359.37 -KEYWORD Cookie
359.38 -KEYWORD DocXMLRPCServer
359.39 -KEYWORD ---EasyDialogs ---
359.40 -KEYWORD ---FrameWork ---
359.41 -KEYWORD HTMLParser
359.42 -KEYWORD ---MacOS ---
359.43 -KEYWORD ---MimeWriter ---
359.44 -KEYWORD MiniAEFrame
359.45 -KEYWORD ---Nav ---
359.46 -KEYWORD ---PixMapWrapper ---
359.47 -KEYWORD Queue
359.48 -KEYWORD ScrolledText
359.49 -KEYWORD SimpleHTTPServer
359.50 -KEYWORD SimpleXMLRPCServer
359.51 -KEYWORD SocketServer
359.52 -KEYWORD StringIO
359.53 -KEYWORD Tix
359.54 -KEYWORD Tkinter
359.55 -KEYWORD UserDict
359.56 -KEYWORD UserList
359.57 -KEYWORD UserString
359.58 -KEYWORD ---W ---
359.59 -KEYWORD _LWPCookieJar
359.60 -KEYWORD _MozillaCookieJar
359.61 -KEYWORD __builtin__
359.62 -KEYWORD __future__
359.63 -KEYWORD __main__
359.64 -KEYWORD _ast
359.65 -KEYWORD _rawffi
359.66 -KEYWORD _strptime
359.67 -KEYWORD _threading_local
359.68 -KEYWORD _winreg
359.69 -KEYWORD abc
359.70 -KEYWORD ---aepack ---
359.71 -KEYWORD ---aetools ---
359.72 -KEYWORD ---aetypes ---
359.73 -KEYWORD aifc
359.74 -KEYWORD anydbm
359.75 -KEYWORD ---applesingle ---
359.76 -KEYWORD array
359.77 -KEYWORD ast
359.78 -KEYWORD asynchat
359.79 -KEYWORD asyncore
359.80 -KEYWORD atexit
359.81 -KEYWORD audioop
359.82 -KEYWORD ---autoGIL ---
359.83 -KEYWORD base64
359.84 -KEYWORD bdb
359.85 -KEYWORD binascii
359.86 -KEYWORD binhex
359.87 -KEYWORD bisect
359.88 -KEYWORD bsddb
359.89 -KEYWORD ---buildtools ---
359.90 -KEYWORD bz2
359.91 -KEYWORD calendar
359.92 -KEYWORD ---cfmfile ---
359.93 -KEYWORD cgi
359.94 -KEYWORD cgitb
359.95 -KEYWORD chunk
359.96 -KEYWORD cmath
359.97 -KEYWORD cmd
359.98 -KEYWORD code
359.99 -KEYWORD codecs
359.100 -KEYWORD codeop
359.101 -KEYWORD collections
359.102 -KEYWORD colorsys
359.103 -KEYWORD commands
359.104 -KEYWORD compileall
359.105 -KEYWORD compiler
359.106 -KEYWORD compiler.ast
359.107 -KEYWORD compiler.consts
359.108 -KEYWORD compiler.future
359.109 -KEYWORD compiler.misc
359.110 -KEYWORD compiler.pyassem
359.111 -KEYWORD compiler.pycodegen
359.112 -KEYWORD compiler.symbols
359.113 -KEYWORD compiler.syntax
359.114 -KEYWORD compiler.transformer
359.115 -KEYWORD compiler.visitor
359.116 -KEYWORD compl
359.117 -KEYWORD compl2
359.118 -KEYWORD compl3
359.119 -KEYWORD compl4
359.120 -KEYWORD compl5
359.121 -KEYWORD constants
359.122 -KEYWORD contextlib
359.123 -KEYWORD cookielib
359.124 -KEYWORD copy
359.125 -KEYWORD copy_reg
359.126 -KEYWORD crypt
359.127 -KEYWORD csv
359.128 -KEYWORD ctypes
359.129 -KEYWORD curses
359.130 -KEYWORD curses.ascii
359.131 -KEYWORD curses.panel
359.132 -KEYWORD curses.textpad
359.133 -KEYWORD curses.wrapper
359.134 -KEYWORD datetime
359.135 -KEYWORD dbexts
359.136 -KEYWORD dbhash
359.137 -KEYWORD dbm
359.138 -KEYWORD decimal
359.139 -KEYWORD difflib
359.140 -KEYWORD dircache
359.141 -KEYWORD dis
359.142 -KEYWORD distutils
359.143 -KEYWORD distutils.archive_util
359.144 -KEYWORD distutils.bcppcompiler
359.145 -KEYWORD distutils.ccompiler
359.146 -KEYWORD distutils.cmd
359.147 -KEYWORD distutils.command
359.148 -KEYWORD distutils.command.bdist
359.149 -KEYWORD distutils.command.bdist_dumb
359.150 -KEYWORD distutils.command.bdist_msi
359.151 -KEYWORD distutils.command.bdist_rpm
359.152 -KEYWORD distutils.command.bdist_winins
359.153 -KEYWORD distutils.command.build
359.154 -KEYWORD distutils.command.build_clib
359.155 -KEYWORD distutils.command.build_ext
359.156 -KEYWORD distutils.command.build_py
359.157 -KEYWORD distutils.command.build_script
359.158 -KEYWORD distutils.command.clean
359.159 -KEYWORD distutils.command.config
359.160 -KEYWORD distutils.command.install
359.161 -KEYWORD distutils.command.install_data
359.162 -KEYWORD distutils.command.install_egg_
359.163 -KEYWORD distutils.command.install_head
359.164 -KEYWORD distutils.command.install_lib
359.165 -KEYWORD distutils.command.install_scri
359.166 -KEYWORD distutils.command.register
359.167 -KEYWORD distutils.command.sdist
359.168 -KEYWORD distutils.command.upload
359.169 -KEYWORD distutils.core
359.170 -KEYWORD distutils.cygwinccompiler
359.171 -KEYWORD distutils.debug
359.172 -KEYWORD distutils.dep_util
359.173 -KEYWORD distutils.dir_util
359.174 -KEYWORD distutils.dist
359.175 -KEYWORD distutils.emxccompiler
359.176 -KEYWORD distutils.errors
359.177 -KEYWORD distutils.extension
359.178 -KEYWORD distutils.fancy_getopt
359.179 -KEYWORD distutils.file_util
359.180 -KEYWORD distutils.filelist
359.181 -KEYWORD distutils.jythoncompiler
359.182 -KEYWORD distutils.log
359.183 -KEYWORD distutils.msvccompiler
359.184 -KEYWORD distutils.mwerkscompiler
359.185 -KEYWORD distutils.spawn
359.186 -KEYWORD distutils.sysconfig
359.187 -KEYWORD distutils.tests
359.188 -KEYWORD distutils.tests.support
359.189 -KEYWORD distutils.tests.test_build_py
359.190 -KEYWORD distutils.tests.test_build_scr
359.191 -KEYWORD distutils.tests.test_dist
359.192 -KEYWORD distutils.tests.test_install
359.193 -KEYWORD distutils.tests.test_install_s
359.194 -KEYWORD distutils.tests.test_versionpr
359.195 -KEYWORD distutils.text_file
359.196 -KEYWORD distutils.unixccompiler
359.197 -KEYWORD distutils.util
359.198 -KEYWORD distutils.version
359.199 -KEYWORD distutils.versionpredicate
359.200 -KEYWORD ---dl ---
359.201 -KEYWORD doctest
359.202 -KEYWORD dumbdbm
359.203 -KEYWORD dummy_thread
359.204 -KEYWORD dummy_threading
359.205 -KEYWORD email
359.206 -KEYWORD email._parseaddr
359.207 -KEYWORD email.base64mime
359.208 -KEYWORD email.charset
359.209 -KEYWORD email.encoders
359.210 -KEYWORD email.errors
359.211 -KEYWORD email.feedparser
359.212 -KEYWORD email.generator
359.213 -KEYWORD email.header
359.214 -KEYWORD email.iterators
359.215 -KEYWORD email.message
359.216 -KEYWORD email.mime
359.217 -KEYWORD email.mime.application
359.218 -KEYWORD email.mime.audio
359.219 -KEYWORD email.mime.base
359.220 -KEYWORD email.mime.image
359.221 -KEYWORD email.mime.message
359.222 -KEYWORD email.mime.multipart
359.223 -KEYWORD email.mime.nonmultipart
359.224 -KEYWORD email.mime.text
359.225 -KEYWORD email.parser
359.226 -KEYWORD email.quoprimime
359.227 -KEYWORD email.test.test_email_torture
359.228 -KEYWORD email.utils
359.229 -KEYWORD encodings
359.230 -KEYWORD encodings.aliases
359.231 -KEYWORD encodings.ascii
359.232 -KEYWORD encodings.base64_codec
359.233 -KEYWORD encodings.big5
359.234 -KEYWORD encodings.big5hkscs
359.235 -KEYWORD encodings.bz2_codec
359.236 -KEYWORD encodings.charmap
359.237 -KEYWORD encodings.cp037
359.238 -KEYWORD encodings.cp1006
359.239 -KEYWORD encodings.cp1026
359.240 -KEYWORD encodings.cp1140
359.241 -KEYWORD encodings.cp1250
359.242 -KEYWORD encodings.cp1251
359.243 -KEYWORD encodings.cp1252
359.244 -KEYWORD encodings.cp1253
359.245 -KEYWORD encodings.cp1254
359.246 -KEYWORD encodings.cp1255
359.247 -KEYWORD encodings.cp1256
359.248 -KEYWORD encodings.cp1257
359.249 -KEYWORD encodings.cp1258
359.250 -KEYWORD encodings.cp424
359.251 -KEYWORD encodings.cp437
359.252 -KEYWORD encodings.cp500
359.253 -KEYWORD encodings.cp737
359.254 -KEYWORD encodings.cp775
359.255 -KEYWORD encodings.cp850
359.256 -KEYWORD encodings.cp852
359.257 -KEYWORD encodings.cp855
359.258 -KEYWORD encodings.cp856
359.259 -KEYWORD encodings.cp857
359.260 -KEYWORD encodings.cp860
359.261 -KEYWORD encodings.cp861
359.262 -KEYWORD encodings.cp862
359.263 -KEYWORD encodings.cp863
359.264 -KEYWORD encodings.cp864
359.265 -KEYWORD encodings.cp865
359.266 -KEYWORD encodings.cp866
359.267 -KEYWORD encodings.cp869
359.268 -KEYWORD encodings.cp874
359.269 -KEYWORD encodings.cp875
359.270 -KEYWORD encodings.cp932
359.271 -KEYWORD encodings.cp949
359.272 -KEYWORD encodings.cp950
359.273 -KEYWORD encodings.euc_jis_2004
359.274 -KEYWORD encodings.euc_jisx0213
359.275 -KEYWORD encodings.euc_jp
359.276 -KEYWORD encodings.euc_kr
359.277 -KEYWORD encodings.gb18030
359.278 -KEYWORD encodings.gb2312
359.279 -KEYWORD encodings.gbk
359.280 -KEYWORD encodings.hex_codec
359.281 -KEYWORD encodings.hp_roman8
359.282 -KEYWORD encodings.hz
359.283 -KEYWORD encodings.idna
359.284 -KEYWORD encodings.iso2022_jp
359.285 -KEYWORD encodings.iso2022_jp_1
359.286 -KEYWORD encodings.iso2022_jp_2
359.287 -KEYWORD encodings.iso2022_jp_2004
359.288 -KEYWORD encodings.iso2022_jp_3
359.289 -KEYWORD encodings.iso2022_jp_ext
359.290 -KEYWORD encodings.iso2022_kr
359.291 -KEYWORD encodings.iso8859_1
359.292 -KEYWORD encodings.iso8859_10
359.293 -KEYWORD encodings.iso8859_11
359.294 -KEYWORD encodings.iso8859_13
359.295 -KEYWORD encodings.iso8859_14
359.296 -KEYWORD encodings.iso8859_15
359.297 -KEYWORD encodings.iso8859_16
359.298 -KEYWORD encodings.iso8859_2
359.299 -KEYWORD encodings.iso8859_3
359.300 -KEYWORD encodings.iso8859_4
359.301 -KEYWORD encodings.iso8859_5
359.302 -KEYWORD encodings.iso8859_6
359.303 -KEYWORD encodings.iso8859_7
359.304 -KEYWORD encodings.iso8859_8
359.305 -KEYWORD encodings.iso8859_9
359.306 -KEYWORD encodings.johab
359.307 -KEYWORD encodings.koi8_r
359.308 -KEYWORD encodings.koi8_u
359.309 -KEYWORD encodings.latin_1
359.310 -KEYWORD encodings.mac_arabic
359.311 -KEYWORD encodings.mac_centeuro
359.312 -KEYWORD encodings.mac_croatian
359.313 -KEYWORD encodings.mac_cyrillic
359.314 -KEYWORD encodings.mac_farsi
359.315 -KEYWORD encodings.mac_greek
359.316 -KEYWORD encodings.mac_iceland
359.317 -KEYWORD encodings.mac_latin2
359.318 -KEYWORD encodings.mac_roman
359.319 -KEYWORD encodings.mac_romanian
359.320 -KEYWORD encodings.mac_turkish
359.321 -KEYWORD encodings.mbcs
359.322 -KEYWORD encodings.palmos
359.323 -KEYWORD encodings.ptcp154
359.324 -KEYWORD encodings.punycode
359.325 -KEYWORD encodings.quopri_codec
359.326 -KEYWORD encodings.raw_unicode_escape
359.327 -KEYWORD encodings.rot_13
359.328 -KEYWORD encodings.shift_jis
359.329 -KEYWORD encodings.shift_jis_2004
359.330 -KEYWORD encodings.shift_jisx0213
359.331 -KEYWORD encodings.string_escape
359.332 -KEYWORD encodings.tis_620
359.333 -KEYWORD encodings.undefined
359.334 -KEYWORD encodings.unicode_escape
359.335 -KEYWORD encodings.unicode_internal
359.336 -KEYWORD encodings.utf_16
359.337 -KEYWORD encodings.utf_16_be
359.338 -KEYWORD encodings.utf_16_le
359.339 -KEYWORD encodings.utf_7
359.340 -KEYWORD encodings.utf_8
359.341 -KEYWORD encodings.utf_8_sig
359.342 -KEYWORD encodings.uu_codec
359.343 -KEYWORD encodings.zlib_codec
359.344 -KEYWORD errno
359.345 -KEYWORD exceptions
359.346 -KEYWORD fcntl
359.347 -KEYWORD filecmp
359.348 -KEYWORD fileinput
359.349 -KEYWORD findertools
359.350 -KEYWORD fnmatch
359.351 -KEYWORD formatter
359.352 -KEYWORD fpectl
359.353 -KEYWORD fpformat
359.354 -KEYWORD fractions
359.355 -KEYWORD ftplib
359.356 -KEYWORD functions
359.357 -KEYWORD functools
359.358 -KEYWORD future_builtins
359.359 -KEYWORD gc
359.360 -KEYWORD gdbm
359.361 -KEYWORD gensuitemodule
359.362 -KEYWORD getopt
359.363 -KEYWORD getpass
359.364 -KEYWORD gettext
359.365 -KEYWORD glob
359.366 -KEYWORD ---gopherlib ---
359.367 -KEYWORD grp
359.368 -KEYWORD gzip
359.369 -KEYWORD hashlib
359.370 -KEYWORD heapq
359.371 -KEYWORD hmac
359.372 -KEYWORD hotshot
359.373 -KEYWORD hotshot.stats
359.374 -KEYWORD htmlentitydefs
359.375 -KEYWORD htmllib
359.376 -KEYWORD httplib
359.377 -KEYWORD ---ic ---
359.378 -KEYWORD ---icopen ---
359.379 -KEYWORD ihooks
359.380 -KEYWORD ---imageop ---
359.381 -KEYWORD imaplib
359.382 -KEYWORD imghdr
359.383 -KEYWORD imp
359.384 -KEYWORD imports3
359.385 -KEYWORD imports4
359.386 -KEYWORD imports7
359.387 -KEYWORD imports8
359.388 -KEYWORD imports9
359.389 -KEYWORD ---imputil ---
359.390 -KEYWORD inspect
359.391 -KEYWORD io
359.392 -KEYWORD isql
359.393 -KEYWORD itertools
359.394 -KEYWORD javapath
359.395 -KEYWORD javashell
359.396 -KEYWORD jreload
359.397 -KEYWORD json
359.398 -KEYWORD keyword
359.399 -KEYWORD lib2to3
359.400 -KEYWORD linecache
359.401 -KEYWORD locale
359.402 -KEYWORD logging
359.403 -KEYWORD logging.config
359.404 -KEYWORD logging.handlers
359.405 -KEYWORD ---macerrors ---
359.406 -KEYWORD ---macostools ---
359.407 -KEYWORD macpath
359.408 -KEYWORD ---macresource ---
359.409 -KEYWORD macurl2path
359.410 -KEYWORD mailbox
359.411 -KEYWORD mailcap
359.412 -KEYWORD markupbase
359.413 -KEYWORD marshal
359.414 -KEYWORD math
359.415 -KEYWORD ---md5 ---
359.416 -KEYWORD mhlib
359.417 -KEYWORD ---mimetools ---
359.418 -KEYWORD mimetypes
359.419 -KEYWORD ---mimify ---
359.420 -KEYWORD mmap
359.421 -KEYWORD modulefinder
359.422 -KEYWORD msilib
359.423 -KEYWORD msvcrt
359.424 -KEYWORD ---multifile ---
359.425 -KEYWORD multiprocessing
359.426 -KEYWORD multiprocessing.connection
359.427 -KEYWORD multiprocessing.dummy
359.428 -KEYWORD multiprocessing.managers
359.429 -KEYWORD multiprocessing.pool
359.430 -KEYWORD multiprocessing.sharedctypes
359.431 -KEYWORD mutex
359.432 -KEYWORD netrc
359.433 -KEYWORD new
359.434 -KEYWORD nis
359.435 -KEYWORD nntplib
359.436 -KEYWORD ntpath
359.437 -KEYWORD nturl2path
359.438 -KEYWORD numbers
359.439 -KEYWORD occurrences2
359.440 -KEYWORD opcode
359.441 -KEYWORD operator
359.442 -KEYWORD optparse
359.443 -KEYWORD os
359.444 -KEYWORD os.path
359.445 -KEYWORD ossaudiodev
359.446 -KEYWORD parser
359.447 -KEYWORD pawt
359.448 -KEYWORD pawt.colors
359.449 -KEYWORD pawt.swing
359.450 -KEYWORD pdb
359.451 -KEYWORD pickle
359.452 -KEYWORD pickletools
359.453 -KEYWORD pipes
359.454 -KEYWORD pkgutil
359.455 -KEYWORD platform
359.456 -KEYWORD plistlib
359.457 -KEYWORD popen2
359.458 -KEYWORD poplib
359.459 -KEYWORD posix
359.460 -KEYWORD ---posixfile ---
359.461 -KEYWORD posixpath
359.462 -KEYWORD pprint
359.463 -KEYWORD profile
359.464 -KEYWORD pstats
359.465 -KEYWORD pty
359.466 -KEYWORD pwd
359.467 -KEYWORD py_compile
359.468 -KEYWORD pyclbr
359.469 -KEYWORD pydoc
359.470 -KEYWORD quopri
359.471 -KEYWORD random
359.472 -KEYWORD re
359.473 -KEYWORD readline
359.474 -KEYWORD repr
359.475 -KEYWORD resource
359.476 -KEYWORD ---rexec ---
359.477 -KEYWORD ---rfc822 ---
359.478 -KEYWORD rlcompleter
359.479 -KEYWORD robotparser
359.480 -KEYWORD runpy
359.481 -KEYWORD sched
359.482 -KEYWORD select
359.483 -KEYWORD ---sets ---
359.484 -KEYWORD sgmllib
359.485 -KEYWORD ---sha ---
359.486 -KEYWORD shelve
359.487 -KEYWORD shlex
359.488 -KEYWORD shutil
359.489 -KEYWORD signal
359.490 -KEYWORD site
359.491 -KEYWORD smtpd
359.492 -KEYWORD smtplib
359.493 -KEYWORD sndhdr
359.494 -KEYWORD socket
359.495 -KEYWORD spwd
359.496 -KEYWORD sqlite3
359.497 -KEYWORD sre
359.498 -KEYWORD sre_compile
359.499 -KEYWORD sre_constants
359.500 -KEYWORD sre_parse
359.501 -KEYWORD ssl
359.502 -KEYWORD stat
359.503 -KEYWORD ---statvfs ---
359.504 -KEYWORD stdtypes
359.505 -KEYWORD string
359.506 -KEYWORD ---stringprep ---
359.507 -KEYWORD struct
359.508 -KEYWORD subprocess
359.509 -KEYWORD symbol
359.510 -KEYWORD symtable
359.511 -KEYWORD sys
359.512 -KEYWORD syslog
359.513 -KEYWORD tabnanny
359.514 -KEYWORD tarfile
359.515 -KEYWORD telnetlib
359.516 -KEYWORD tempfile
359.517 -KEYWORD termios
359.518 -KEYWORD test.bugs.bugs100
359.519 -KEYWORD test.bugs.bugs101
359.520 -KEYWORD test.bugs.jdkbugs
359.521 -KEYWORD test.bugs.pr101
359.522 -KEYWORD test.bugs.pr104
359.523 -KEYWORD test.bugs.pr112
359.524 -KEYWORD test.bugs.pr119
359.525 -KEYWORD test.bugs.pr127
359.526 -KEYWORD test.bugs.pr133
359.527 -KEYWORD test.bugs.pr133.test
359.528 -KEYWORD test.bugs.pr134
359.529 -KEYWORD test.bugs.pr139
359.530 -KEYWORD test.bugs.pr142
359.531 -KEYWORD test.bugs.pr144
359.532 -KEYWORD test.bugs.pr148
359.533 -KEYWORD test.bugs.pr149
359.534 -KEYWORD test.bugs.pr155
359.535 -KEYWORD test.bugs.pr170
359.536 -KEYWORD test.bugs.pr171
359.537 -KEYWORD test.bugs.pr174
359.538 -KEYWORD test.bugs.pr178
359.539 -KEYWORD test.bugs.pr183
359.540 -KEYWORD test.bugs.pr186
359.541 -KEYWORD test.bugs.pr191
359.542 -KEYWORD test.bugs.pr192
359.543 -KEYWORD test.bugs.pr195
359.544 -KEYWORD test.bugs.pr208
359.545 -KEYWORD test.bugs.pr233
359.546 -KEYWORD test.bugs.pr234
359.547 -KEYWORD test.bugs.pr235
359.548 -KEYWORD test.bugs.pr239
359.549 -KEYWORD test.bugs.pr241
359.550 -KEYWORD test.bugs.pr242
359.551 -KEYWORD test.crashers.bogus_code_obj
359.552 -KEYWORD test.crashers.borrowed_ref_1
359.553 -KEYWORD test.crashers.borrowed_ref_2
359.554 -KEYWORD test.crashers.gc_inspection
359.555 -KEYWORD test.crashers.infinite_rec_1
359.556 -KEYWORD test.crashers.infinite_rec_2
359.557 -KEYWORD test.crashers.infinite_rec_4
359.558 -KEYWORD test.crashers.infinite_rec_5
359.559 -KEYWORD test.crashers.loosing_dict_ref
359.560 -KEYWORD test.crashers.nasty_eq_vs_dict
359.561 -KEYWORD test.crashers.recursion_limit_
359.562 -KEYWORD test.crashers.recursive_call
359.563 -KEYWORD test.leakers
359.564 -KEYWORD test.leakers.test_ctypes
359.565 -KEYWORD test.leakers.test_gestalt
359.566 -KEYWORD test.leakers.test_selftype
359.567 -KEYWORD test.test_metaclass_support
359.568 -KEYWORD test.test_metaclass_support.me
359.569 -KEYWORD test.test_metaclass_support.si
359.570 -KEYWORD test.xmltests
359.571 -KEYWORD test.zxjdbc.dbextstest
359.572 -KEYWORD test.zxjdbc.jndi
359.573 -KEYWORD test.zxjdbc.runner
359.574 -KEYWORD test.zxjdbc.sptest
359.575 -KEYWORD test.zxjdbc.test_zxjdbc_dbapi2
359.576 -KEYWORD test.zxjdbc.zxtest
359.577 -KEYWORD textwrap
359.578 -KEYWORD this
359.579 -KEYWORD thread
359.580 -KEYWORD threading
359.581 -KEYWORD time
359.582 -KEYWORD timeit
359.583 -KEYWORD token
359.584 -KEYWORD tokenize
359.585 -KEYWORD trace
359.586 -KEYWORD traceback
359.587 -KEYWORD tty
359.588 -KEYWORD turtle
359.589 -KEYWORD types
359.590 -KEYWORD unicodedata
359.591 -KEYWORD unittest
359.592 -KEYWORD urllib
359.593 -KEYWORD urllib2
359.594 -KEYWORD urlparse
359.595 -KEYWORD user
359.596 -KEYWORD uu
359.597 -KEYWORD uuid
359.598 -KEYWORD ---videoreader ---
359.599 -KEYWORD warnings
359.600 -KEYWORD wave
359.601 -KEYWORD weakref
359.602 -KEYWORD webbrowser
359.603 -KEYWORD whichdb
359.604 -KEYWORD winsound
359.605 -KEYWORD wsgiref
359.606 -KEYWORD wsgiref.handlers
359.607 -KEYWORD wsgiref.headers
359.608 -KEYWORD wsgiref.simple_server
359.609 -KEYWORD wsgiref.util
359.610 -KEYWORD wsgiref.validate
359.611 -KEYWORD xdrlib
359.612 -KEYWORD xml
359.613 -KEYWORD xml.FtCore
359.614 -KEYWORD xml.Uri
359.615 -KEYWORD xml.dom
359.616 -KEYWORD xml.dom.MessageSource
359.617 -KEYWORD xml.dom.NodeFilter
359.618 -KEYWORD xml.dom.domreg
359.619 -KEYWORD xml.dom.minicompat
359.620 -KEYWORD xml.dom.minidom
359.621 -KEYWORD xml.dom.pulldom
359.622 -KEYWORD xml.dom.xmlbuilder
359.623 -KEYWORD xml.etree
359.624 -KEYWORD xml.etree.ElementTree
359.625 -KEYWORD xml.parsers.expat
359.626 -KEYWORD xml.sax
359.627 -KEYWORD xml.sax._exceptions
359.628 -KEYWORD xml.sax.drivers2
359.629 -KEYWORD xml.sax.drivers2.drv_javasax
359.630 -KEYWORD xml.sax.handler
359.631 -KEYWORD xml.sax.saxlib
359.632 -KEYWORD xml.sax.saxutils
359.633 -KEYWORD xml.sax.xmlreader
359.634 -KEYWORD xmllib
359.635 -KEYWORD xmlrpclib
359.636 -KEYWORD zipfile
359.637 -KEYWORD zipimport
359.638 -KEYWORD zlib
360.1 --- a/python.editor/test/unit/data/testfiles/imports5.py Sun Jan 04 13:11:53 2015 -0600
360.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
360.3 @@ -1,1 +0,0 @@
360.4 -import im
361.1 --- a/python.editor/test/unit/data/testfiles/imports5.py.testImports5.completion Sun Jan 04 13:11:53 2015 -0600
361.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
361.3 @@ -1,22 +0,0 @@
361.4 -Code completion result for source line:
361.5 -import i|m
361.6 -(QueryType=COMPLETION, NameKind=PREFIX)
361.7 -------------------------------------
361.8 -KEYWORD ---ic ---
361.9 -KEYWORD ---icopen ---
361.10 -KEYWORD ihooks
361.11 -KEYWORD ---imageop ---
361.12 -KEYWORD imaplib
361.13 -KEYWORD imghdr
361.14 -KEYWORD imp
361.15 -KEYWORD imports3
361.16 -KEYWORD imports4
361.17 -KEYWORD imports5
361.18 -KEYWORD imports7
361.19 -KEYWORD imports8
361.20 -KEYWORD imports9
361.21 -KEYWORD ---imputil ---
361.22 -KEYWORD inspect
361.23 -KEYWORD io
361.24 -KEYWORD isql
361.25 -KEYWORD itertools
362.1 --- a/python.editor/test/unit/data/testfiles/imports6.py Sun Jan 04 13:11:53 2015 -0600
362.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
362.3 @@ -1,1 +0,0 @@
362.4 -from i
363.1 --- a/python.editor/test/unit/data/testfiles/imports6.py.testImports6.completion Sun Jan 04 13:11:53 2015 -0600
363.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
363.3 @@ -1,637 +0,0 @@
363.4 -Code completion result for source line:
363.5 -from |i
363.6 -(QueryType=COMPLETION, NameKind=PREFIX)
363.7 -------------------------------------
363.8 -KEYWORD BaseHTTPServer
363.9 -KEYWORD ---Bastion ---
363.10 -KEYWORD CGIHTTPServer
363.11 -KEYWORD ---Carbon.AE ---
363.12 -KEYWORD ---Carbon.AH ---
363.13 -KEYWORD ---Carbon.App ---
363.14 -KEYWORD ---Carbon.CF ---
363.15 -KEYWORD ---Carbon.CG ---
363.16 -KEYWORD ---Carbon.CarbonEvt ---
363.17 -KEYWORD ---Carbon.Cm ---
363.18 -KEYWORD ---Carbon.Ctl ---
363.19 -KEYWORD ---Carbon.Dlg ---
363.20 -KEYWORD ---Carbon.Evt ---
363.21 -KEYWORD ---Carbon.Fm ---
363.22 -KEYWORD ---Carbon.Folder ---
363.23 -KEYWORD ---Carbon.Help ---
363.24 -KEYWORD ---Carbon.List ---
363.25 -KEYWORD ---Carbon.Menu ---
363.26 -KEYWORD ---Carbon.Mlte ---
363.27 -KEYWORD ---Carbon.Qd ---
363.28 -KEYWORD ---Carbon.Qdoffs ---
363.29 -KEYWORD ---Carbon.Qt ---
363.30 -KEYWORD ---Carbon.Res ---
363.31 -KEYWORD ---Carbon.Scrap ---
363.32 -KEYWORD ---Carbon.Snd ---
363.33 -KEYWORD ---Carbon.TE ---
363.34 -KEYWORD ---Carbon.Win ---
363.35 -KEYWORD ---ColorPicker ---
363.36 -KEYWORD ConfigParser
363.37 -KEYWORD Cookie
363.38 -KEYWORD DocXMLRPCServer
363.39 -KEYWORD ---EasyDialogs ---
363.40 -KEYWORD ---FrameWork ---
363.41 -KEYWORD HTMLParser
363.42 -KEYWORD ---MacOS ---
363.43 -KEYWORD ---MimeWriter ---
363.44 -KEYWORD MiniAEFrame
363.45 -KEYWORD ---Nav ---
363.46 -KEYWORD ---PixMapWrapper ---
363.47 -KEYWORD Queue
363.48 -KEYWORD ScrolledText
363.49 -KEYWORD SimpleHTTPServer
363.50 -KEYWORD SimpleXMLRPCServer
363.51 -KEYWORD SocketServer
363.52 -KEYWORD StringIO
363.53 -KEYWORD Tix
363.54 -KEYWORD Tkinter
363.55 -KEYWORD UserDict
363.56 -KEYWORD UserList
363.57 -KEYWORD UserString
363.58 -KEYWORD ---W ---
363.59 -KEYWORD _LWPCookieJar
363.60 -KEYWORD _MozillaCookieJar
363.61 -KEYWORD __builtin__
363.62 -KEYWORD __future__
363.63 -KEYWORD __main__
363.64 -KEYWORD _ast
363.65 -KEYWORD _rawffi
363.66 -KEYWORD _strptime
363.67 -KEYWORD _threading_local
363.68 -KEYWORD _winreg
363.69 -KEYWORD abc
363.70 -KEYWORD ---aepack ---
363.71 -KEYWORD ---aetools ---
363.72 -KEYWORD ---aetypes ---
363.73 -KEYWORD aifc
363.74 -KEYWORD anydbm
363.75 -KEYWORD ---applesingle ---
363.76 -KEYWORD array
363.77 -KEYWORD ast
363.78 -KEYWORD asynchat
363.79 -KEYWORD asyncore
363.80 -KEYWORD atexit
363.81 -KEYWORD audioop
363.82 -KEYWORD ---autoGIL ---
363.83 -KEYWORD base64
363.84 -KEYWORD bdb
363.85 -KEYWORD binascii
363.86 -KEYWORD binhex
363.87 -KEYWORD bisect
363.88 -KEYWORD bsddb
363.89 -KEYWORD ---buildtools ---
363.90 -KEYWORD bz2
363.91 -KEYWORD calendar
363.92 -KEYWORD ---cfmfile ---
363.93 -KEYWORD cgi
363.94 -KEYWORD cgitb
363.95 -KEYWORD chunk
363.96 -KEYWORD cmath
363.97 -KEYWORD cmd
363.98 -KEYWORD code
363.99 -KEYWORD codecs
363.100 -KEYWORD codeop
363.101 -KEYWORD collections
363.102 -KEYWORD colorsys
363.103 -KEYWORD commands
363.104 -KEYWORD compileall
363.105 -KEYWORD compiler
363.106 -KEYWORD compiler.ast
363.107 -KEYWORD compiler.consts
363.108 -KEYWORD compiler.future
363.109 -KEYWORD compiler.misc
363.110 -KEYWORD compiler.pyassem
363.111 -KEYWORD compiler.pycodegen
363.112 -KEYWORD compiler.symbols
363.113 -KEYWORD compiler.syntax
363.114 -KEYWORD compiler.transformer
363.115 -KEYWORD compiler.visitor
363.116 -KEYWORD compl
363.117 -KEYWORD compl2
363.118 -KEYWORD compl3
363.119 -KEYWORD compl4
363.120 -KEYWORD compl5
363.121 -KEYWORD constants
363.122 -KEYWORD contextlib
363.123 -KEYWORD cookielib
363.124 -KEYWORD copy
363.125 -KEYWORD copy_reg
363.126 -KEYWORD crypt
363.127 -KEYWORD csv
363.128 -KEYWORD ctypes
363.129 -KEYWORD curses
363.130 -KEYWORD curses.ascii
363.131 -KEYWORD curses.panel
363.132 -KEYWORD curses.textpad
363.133 -KEYWORD curses.wrapper
363.134 -KEYWORD datetime
363.135 -KEYWORD dbexts
363.136 -KEYWORD dbhash
363.137 -KEYWORD dbm
363.138 -KEYWORD decimal
363.139 -KEYWORD difflib
363.140 -KEYWORD dircache
363.141 -KEYWORD dis
363.142 -KEYWORD distutils
363.143 -KEYWORD distutils.archive_util
363.144 -KEYWORD distutils.bcppcompiler
363.145 -KEYWORD distutils.ccompiler
363.146 -KEYWORD distutils.cmd
363.147 -KEYWORD distutils.command
363.148 -KEYWORD distutils.command.bdist
363.149 -KEYWORD distutils.command.bdist_dumb
363.150 -KEYWORD distutils.command.bdist_msi
363.151 -KEYWORD distutils.command.bdist_rpm
363.152 -KEYWORD distutils.command.bdist_winins
363.153 -KEYWORD distutils.command.build
363.154 -KEYWORD distutils.command.build_clib
363.155 -KEYWORD distutils.command.build_ext
363.156 -KEYWORD distutils.command.build_py
363.157 -KEYWORD distutils.command.build_script
363.158 -KEYWORD distutils.command.clean
363.159 -KEYWORD distutils.command.config
363.160 -KEYWORD distutils.command.install
363.161 -KEYWORD distutils.command.install_data
363.162 -KEYWORD distutils.command.install_egg_
363.163 -KEYWORD distutils.command.install_head
363.164 -KEYWORD distutils.command.install_lib
363.165 -KEYWORD distutils.command.install_scri
363.166 -KEYWORD distutils.command.register
363.167 -KEYWORD distutils.command.sdist
363.168 -KEYWORD distutils.command.upload
363.169 -KEYWORD distutils.core
363.170 -KEYWORD distutils.cygwinccompiler
363.171 -KEYWORD distutils.debug
363.172 -KEYWORD distutils.dep_util
363.173 -KEYWORD distutils.dir_util
363.174 -KEYWORD distutils.dist
363.175 -KEYWORD distutils.emxccompiler
363.176 -KEYWORD distutils.errors
363.177 -KEYWORD distutils.extension
363.178 -KEYWORD distutils.fancy_getopt
363.179 -KEYWORD distutils.file_util
363.180 -KEYWORD distutils.filelist
363.181 -KEYWORD distutils.jythoncompiler
363.182 -KEYWORD distutils.log
363.183 -KEYWORD distutils.msvccompiler
363.184 -KEYWORD distutils.mwerkscompiler
363.185 -KEYWORD distutils.spawn
363.186 -KEYWORD distutils.sysconfig
363.187 -KEYWORD distutils.tests
363.188 -KEYWORD distutils.tests.support
363.189 -KEYWORD distutils.tests.test_build_py
363.190 -KEYWORD distutils.tests.test_build_scr
363.191 -KEYWORD distutils.tests.test_dist
363.192 -KEYWORD distutils.tests.test_install
363.193 -KEYWORD distutils.tests.test_install_s
363.194 -KEYWORD distutils.tests.test_versionpr
363.195 -KEYWORD distutils.text_file
363.196 -KEYWORD distutils.unixccompiler
363.197 -KEYWORD distutils.util
363.198 -KEYWORD distutils.version
363.199 -KEYWORD distutils.versionpredicate
363.200 -KEYWORD ---dl ---
363.201 -KEYWORD doctest
363.202 -KEYWORD dumbdbm
363.203 -KEYWORD dummy_thread
363.204 -KEYWORD dummy_threading
363.205 -KEYWORD email
363.206 -KEYWORD email._parseaddr
363.207 -KEYWORD email.base64mime
363.208 -KEYWORD email.charset
363.209 -KEYWORD email.encoders
363.210 -KEYWORD email.errors
363.211 -KEYWORD email.feedparser
363.212 -KEYWORD email.generator
363.213 -KEYWORD email.header
363.214 -KEYWORD email.iterators
363.215 -KEYWORD email.message
363.216 -KEYWORD email.mime
363.217 -KEYWORD email.mime.application
363.218 -KEYWORD email.mime.audio
363.219 -KEYWORD email.mime.base
363.220 -KEYWORD email.mime.image
363.221 -KEYWORD email.mime.message
363.222 -KEYWORD email.mime.multipart
363.223 -KEYWORD email.mime.nonmultipart
363.224 -KEYWORD email.mime.text
363.225 -KEYWORD email.parser
363.226 -KEYWORD email.quoprimime
363.227 -KEYWORD email.test.test_email_torture
363.228 -KEYWORD email.utils
363.229 -KEYWORD encodings
363.230 -KEYWORD encodings.aliases
363.231 -KEYWORD encodings.ascii
363.232 -KEYWORD encodings.base64_codec
363.233 -KEYWORD encodings.big5
363.234 -KEYWORD encodings.big5hkscs
363.235 -KEYWORD encodings.bz2_codec
363.236 -KEYWORD encodings.charmap
363.237 -KEYWORD encodings.cp037
363.238 -KEYWORD encodings.cp1006
363.239 -KEYWORD encodings.cp1026
363.240 -KEYWORD encodings.cp1140
363.241 -KEYWORD encodings.cp1250
363.242 -KEYWORD encodings.cp1251
363.243 -KEYWORD encodings.cp1252
363.244 -KEYWORD encodings.cp1253
363.245 -KEYWORD encodings.cp1254
363.246 -KEYWORD encodings.cp1255
363.247 -KEYWORD encodings.cp1256
363.248 -KEYWORD encodings.cp1257
363.249 -KEYWORD encodings.cp1258
363.250 -KEYWORD encodings.cp424
363.251 -KEYWORD encodings.cp437
363.252 -KEYWORD encodings.cp500
363.253 -KEYWORD encodings.cp737
363.254 -KEYWORD encodings.cp775
363.255 -KEYWORD encodings.cp850
363.256 -KEYWORD encodings.cp852
363.257 -KEYWORD encodings.cp855
363.258 -KEYWORD encodings.cp856
363.259 -KEYWORD encodings.cp857
363.260 -KEYWORD encodings.cp860
363.261 -KEYWORD encodings.cp861
363.262 -KEYWORD encodings.cp862
363.263 -KEYWORD encodings.cp863
363.264 -KEYWORD encodings.cp864
363.265 -KEYWORD encodings.cp865
363.266 -KEYWORD encodings.cp866
363.267 -KEYWORD encodings.cp869
363.268 -KEYWORD encodings.cp874
363.269 -KEYWORD encodings.cp875
363.270 -KEYWORD encodings.cp932
363.271 -KEYWORD encodings.cp949
363.272 -KEYWORD encodings.cp950
363.273 -KEYWORD encodings.euc_jis_2004
363.274 -KEYWORD encodings.euc_jisx0213
363.275 -KEYWORD encodings.euc_jp
363.276 -KEYWORD encodings.euc_kr
363.277 -KEYWORD encodings.gb18030
363.278 -KEYWORD encodings.gb2312
363.279 -KEYWORD encodings.gbk
363.280 -KEYWORD encodings.hex_codec
363.281 -KEYWORD encodings.hp_roman8
363.282 -KEYWORD encodings.hz
363.283 -KEYWORD encodings.idna
363.284 -KEYWORD encodings.iso2022_jp
363.285 -KEYWORD encodings.iso2022_jp_1
363.286 -KEYWORD encodings.iso2022_jp_2
363.287 -KEYWORD encodings.iso2022_jp_2004
363.288 -KEYWORD encodings.iso2022_jp_3
363.289 -KEYWORD encodings.iso2022_jp_ext
363.290 -KEYWORD encodings.iso2022_kr
363.291 -KEYWORD encodings.iso8859_1
363.292 -KEYWORD encodings.iso8859_10
363.293 -KEYWORD encodings.iso8859_11
363.294 -KEYWORD encodings.iso8859_13
363.295 -KEYWORD encodings.iso8859_14
363.296 -KEYWORD encodings.iso8859_15
363.297 -KEYWORD encodings.iso8859_16
363.298 -KEYWORD encodings.iso8859_2
363.299 -KEYWORD encodings.iso8859_3
363.300 -KEYWORD encodings.iso8859_4
363.301 -KEYWORD encodings.iso8859_5
363.302 -KEYWORD encodings.iso8859_6
363.303 -KEYWORD encodings.iso8859_7
363.304 -KEYWORD encodings.iso8859_8
363.305 -KEYWORD encodings.iso8859_9
363.306 -KEYWORD encodings.johab
363.307 -KEYWORD encodings.koi8_r
363.308 -KEYWORD encodings.koi8_u
363.309 -KEYWORD encodings.latin_1
363.310 -KEYWORD encodings.mac_arabic
363.311 -KEYWORD encodings.mac_centeuro
363.312 -KEYWORD encodings.mac_croatian
363.313 -KEYWORD encodings.mac_cyrillic
363.314 -KEYWORD encodings.mac_farsi
363.315 -KEYWORD encodings.mac_greek
363.316 -KEYWORD encodings.mac_iceland
363.317 -KEYWORD encodings.mac_latin2
363.318 -KEYWORD encodings.mac_roman
363.319 -KEYWORD encodings.mac_romanian
363.320 -KEYWORD encodings.mac_turkish
363.321 -KEYWORD encodings.mbcs
363.322 -KEYWORD encodings.palmos
363.323 -KEYWORD encodings.ptcp154
363.324 -KEYWORD encodings.punycode
363.325 -KEYWORD encodings.quopri_codec
363.326 -KEYWORD encodings.raw_unicode_escape
363.327 -KEYWORD encodings.rot_13
363.328 -KEYWORD encodings.shift_jis
363.329 -KEYWORD encodings.shift_jis_2004
363.330 -KEYWORD encodings.shift_jisx0213
363.331 -KEYWORD encodings.string_escape
363.332 -KEYWORD encodings.tis_620
363.333 -KEYWORD encodings.undefined
363.334 -KEYWORD encodings.unicode_escape
363.335 -KEYWORD encodings.unicode_internal
363.336 -KEYWORD encodings.utf_16
363.337 -KEYWORD encodings.utf_16_be
363.338 -KEYWORD encodings.utf_16_le
363.339 -KEYWORD encodings.utf_7
363.340 -KEYWORD encodings.utf_8
363.341 -KEYWORD encodings.utf_8_sig
363.342 -KEYWORD encodings.uu_codec
363.343 -KEYWORD encodings.zlib_codec
363.344 -KEYWORD errno
363.345 -KEYWORD exceptions
363.346 -KEYWORD fcntl
363.347 -KEYWORD filecmp
363.348 -KEYWORD fileinput
363.349 -KEYWORD findertools
363.350 -KEYWORD fnmatch
363.351 -KEYWORD formatter
363.352 -KEYWORD fpectl
363.353 -KEYWORD fpformat
363.354 -KEYWORD fractions
363.355 -KEYWORD ftplib
363.356 -KEYWORD functions
363.357 -KEYWORD functools
363.358 -KEYWORD future_builtins
363.359 -KEYWORD gc
363.360 -KEYWORD gdbm
363.361 -KEYWORD gensuitemodule
363.362 -KEYWORD getopt
363.363 -KEYWORD getpass
363.364 -KEYWORD gettext
363.365 -KEYWORD glob
363.366 -KEYWORD ---gopherlib ---
363.367 -KEYWORD grp
363.368 -KEYWORD gzip
363.369 -KEYWORD hashlib
363.370 -KEYWORD heapq
363.371 -KEYWORD hmac
363.372 -KEYWORD hotshot
363.373 -KEYWORD hotshot.stats
363.374 -KEYWORD htmlentitydefs
363.375 -KEYWORD htmllib
363.376 -KEYWORD httplib
363.377 -KEYWORD ---ic ---
363.378 -KEYWORD ---icopen ---
363.379 -KEYWORD ihooks
363.380 -KEYWORD ---imageop ---
363.381 -KEYWORD imaplib
363.382 -KEYWORD imghdr
363.383 -KEYWORD imp
363.384 -KEYWORD imports3
363.385 -KEYWORD imports4
363.386 -KEYWORD imports5
363.387 -KEYWORD imports6
363.388 -KEYWORD imports7
363.389 -KEYWORD imports8
363.390 -KEYWORD imports9
363.391 -KEYWORD ---imputil ---
363.392 -KEYWORD inspect
363.393 -KEYWORD io
363.394 -KEYWORD isql
363.395 -KEYWORD itertools
363.396 -KEYWORD javapath
363.397 -KEYWORD javashell
363.398 -KEYWORD jreload
363.399 -KEYWORD json
363.400 -KEYWORD keyword
363.401 -KEYWORD lib2to3
363.402 -KEYWORD linecache
363.403 -KEYWORD locale
363.404 -KEYWORD logging
363.405 -KEYWORD logging.config
363.406 -KEYWORD logging.handlers
363.407 -KEYWORD ---macerrors ---
363.408 -KEYWORD ---macostools ---
363.409 -KEYWORD macpath
363.410 -KEYWORD ---macresource ---
363.411 -KEYWORD macurl2path
363.412 -KEYWORD mailbox
363.413 -KEYWORD mailcap
363.414 -KEYWORD markupbase
363.415 -KEYWORD marshal
363.416 -KEYWORD math
363.417 -KEYWORD ---md5 ---
363.418 -KEYWORD mhlib
363.419 -KEYWORD ---mimetools ---
363.420 -KEYWORD mimetypes
363.421 -KEYWORD ---mimify ---
363.422 -KEYWORD mmap
363.423 -KEYWORD modulefinder
363.424 -KEYWORD msilib
363.425 -KEYWORD msvcrt
363.426 -KEYWORD ---multifile ---
363.427 -KEYWORD multiprocessing
363.428 -KEYWORD multiprocessing.connection
363.429 -KEYWORD multiprocessing.dummy
363.430 -KEYWORD multiprocessing.managers
363.431 -KEYWORD multiprocessing.pool
363.432 -KEYWORD multiprocessing.sharedctypes
363.433 -KEYWORD mutex
363.434 -KEYWORD netrc
363.435 -KEYWORD new
363.436 -KEYWORD nis
363.437 -KEYWORD nntplib
363.438 -KEYWORD ntpath
363.439 -KEYWORD nturl2path
363.440 -KEYWORD numbers
363.441 -KEYWORD occurrences2
363.442 -KEYWORD opcode
363.443 -KEYWORD operator
363.444 -KEYWORD optparse
363.445 -KEYWORD os
363.446 -KEYWORD os.path
363.447 -KEYWORD ossaudiodev
363.448 -KEYWORD parser
363.449 -KEYWORD pawt
363.450 -KEYWORD pawt.colors
363.451 -KEYWORD pawt.swing
363.452 -KEYWORD pdb
363.453 -KEYWORD pickle
363.454 -KEYWORD pickletools
363.455 -KEYWORD pipes
363.456 -KEYWORD pkgutil
363.457 -KEYWORD platform
363.458 -KEYWORD plistlib
363.459 -KEYWORD popen2
363.460 -KEYWORD poplib
363.461 -KEYWORD posix
363.462 -KEYWORD ---posixfile ---
363.463 -KEYWORD posixpath
363.464 -KEYWORD pprint
363.465 -KEYWORD profile
363.466 -KEYWORD pstats
363.467 -KEYWORD pty
363.468 -KEYWORD pwd
363.469 -KEYWORD py_compile
363.470 -KEYWORD pyclbr
363.471 -KEYWORD pydoc
363.472 -KEYWORD quopri
363.473 -KEYWORD random
363.474 -KEYWORD re
363.475 -KEYWORD readline
363.476 -KEYWORD repr
363.477 -KEYWORD resource
363.478 -KEYWORD ---rexec ---
363.479 -KEYWORD ---rfc822 ---
363.480 -KEYWORD rlcompleter
363.481 -KEYWORD robotparser
363.482 -KEYWORD runpy
363.483 -KEYWORD sched
363.484 -KEYWORD select
363.485 -KEYWORD ---sets ---
363.486 -KEYWORD sgmllib
363.487 -KEYWORD ---sha ---
363.488 -KEYWORD shelve
363.489 -KEYWORD shlex
363.490 -KEYWORD shutil
363.491 -KEYWORD signal
363.492 -KEYWORD site
363.493 -KEYWORD smtpd
363.494 -KEYWORD smtplib
363.495 -KEYWORD sndhdr
363.496 -KEYWORD socket
363.497 -KEYWORD spwd
363.498 -KEYWORD sqlite3
363.499 -KEYWORD sre
363.500 -KEYWORD sre_compile
363.501 -KEYWORD sre_constants
363.502 -KEYWORD sre_parse
363.503 -KEYWORD ssl
363.504 -KEYWORD stat
363.505 -KEYWORD ---statvfs ---
363.506 -KEYWORD stdtypes
363.507 -KEYWORD string
363.508 -KEYWORD ---stringprep ---
363.509 -KEYWORD struct
363.510 -KEYWORD subprocess
363.511 -KEYWORD symbol
363.512 -KEYWORD symtable
363.513 -KEYWORD sys
363.514 -KEYWORD syslog
363.515 -KEYWORD tabnanny
363.516 -KEYWORD tarfile
363.517 -KEYWORD telnetlib
363.518 -KEYWORD tempfile
363.519 -KEYWORD termios
363.520 -KEYWORD test.bugs.bugs100
363.521 -KEYWORD test.bugs.bugs101
363.522 -KEYWORD test.bugs.jdkbugs
363.523 -KEYWORD test.bugs.pr101
363.524 -KEYWORD test.bugs.pr104
363.525 -KEYWORD test.bugs.pr112
363.526 -KEYWORD test.bugs.pr119
363.527 -KEYWORD test.bugs.pr127
363.528 -KEYWORD test.bugs.pr133
363.529 -KEYWORD test.bugs.pr133.test
363.530 -KEYWORD test.bugs.pr134
363.531 -KEYWORD test.bugs.pr139
363.532 -KEYWORD test.bugs.pr142
363.533 -KEYWORD test.bugs.pr144
363.534 -KEYWORD test.bugs.pr148
363.535 -KEYWORD test.bugs.pr149
363.536 -KEYWORD test.bugs.pr155
363.537 -KEYWORD test.bugs.pr170
363.538 -KEYWORD test.bugs.pr171
363.539 -KEYWORD test.bugs.pr174
363.540 -KEYWORD test.bugs.pr178
363.541 -KEYWORD test.bugs.pr183
363.542 -KEYWORD test.bugs.pr186
363.543 -KEYWORD test.bugs.pr191
363.544 -KEYWORD test.bugs.pr192
363.545 -KEYWORD test.bugs.pr195
363.546 -KEYWORD test.bugs.pr208
363.547 -KEYWORD test.bugs.pr233
363.548 -KEYWORD test.bugs.pr234
363.549 -KEYWORD test.bugs.pr235
363.550 -KEYWORD test.bugs.pr239
363.551 -KEYWORD test.bugs.pr241
363.552 -KEYWORD test.bugs.pr242
363.553 -KEYWORD test.crashers.bogus_code_obj
363.554 -KEYWORD test.crashers.borrowed_ref_1
363.555 -KEYWORD test.crashers.borrowed_ref_2
363.556 -KEYWORD test.crashers.gc_inspection
363.557 -KEYWORD test.crashers.infinite_rec_1
363.558 -KEYWORD test.crashers.infinite_rec_2
363.559 -KEYWORD test.crashers.infinite_rec_4
363.560 -KEYWORD test.crashers.infinite_rec_5
363.561 -KEYWORD test.crashers.loosing_dict_ref
363.562 -KEYWORD test.crashers.nasty_eq_vs_dict
363.563 -KEYWORD test.crashers.recursion_limit_
363.564 -KEYWORD test.crashers.recursive_call
363.565 -KEYWORD test.leakers
363.566 -KEYWORD test.leakers.test_ctypes
363.567 -KEYWORD test.leakers.test_gestalt
363.568 -KEYWORD test.leakers.test_selftype
363.569 -KEYWORD test.test_metaclass_support
363.570 -KEYWORD test.test_metaclass_support.me
363.571 -KEYWORD test.test_metaclass_support.si
363.572 -KEYWORD test.xmltests
363.573 -KEYWORD test.zxjdbc.dbextstest
363.574 -KEYWORD test.zxjdbc.jndi
363.575 -KEYWORD test.zxjdbc.runner
363.576 -KEYWORD test.zxjdbc.sptest
363.577 -KEYWORD test.zxjdbc.test_zxjdbc_dbapi2
363.578 -KEYWORD test.zxjdbc.zxtest
363.579 -KEYWORD textwrap
363.580 -KEYWORD this
363.581 -KEYWORD thread
363.582 -KEYWORD threading
363.583 -KEYWORD time
363.584 -KEYWORD timeit
363.585 -KEYWORD token
363.586 -KEYWORD tokenize
363.587 -KEYWORD trace
363.588 -KEYWORD traceback
363.589 -KEYWORD tty
363.590 -KEYWORD turtle
363.591 -KEYWORD types
363.592 -KEYWORD unicodedata
363.593 -KEYWORD unittest
363.594 -KEYWORD urllib
363.595 -KEYWORD urllib2
363.596 -KEYWORD urlparse
363.597 -KEYWORD user
363.598 -KEYWORD uu
363.599 -KEYWORD uuid
363.600 -KEYWORD ---videoreader ---
363.601 -KEYWORD warnings
363.602 -KEYWORD wave
363.603 -KEYWORD weakref
363.604 -KEYWORD webbrowser
363.605 -KEYWORD whichdb
363.606 -KEYWORD winsound
363.607 -KEYWORD wsgiref
363.608 -KEYWORD wsgiref.handlers
363.609 -KEYWORD wsgiref.headers
363.610 -KEYWORD wsgiref.simple_server
363.611 -KEYWORD wsgiref.util
363.612 -KEYWORD wsgiref.validate
363.613 -KEYWORD xdrlib
363.614 -KEYWORD xml
363.615 -KEYWORD xml.FtCore
363.616 -KEYWORD xml.Uri
363.617 -KEYWORD xml.dom
363.618 -KEYWORD xml.dom.MessageSource
363.619 -KEYWORD xml.dom.NodeFilter
363.620 -KEYWORD xml.dom.domreg
363.621 -KEYWORD xml.dom.minicompat
363.622 -KEYWORD xml.dom.minidom
363.623 -KEYWORD xml.dom.pulldom
363.624 -KEYWORD xml.dom.xmlbuilder
363.625 -KEYWORD xml.etree
363.626 -KEYWORD xml.etree.ElementTree
363.627 -KEYWORD xml.parsers.expat
363.628 -KEYWORD xml.sax
363.629 -KEYWORD xml.sax._exceptions
363.630 -KEYWORD xml.sax.drivers2
363.631 -KEYWORD xml.sax.drivers2.drv_javasax
363.632 -KEYWORD xml.sax.handler
363.633 -KEYWORD xml.sax.saxlib
363.634 -KEYWORD xml.sax.saxutils
363.635 -KEYWORD xml.sax.xmlreader
363.636 -KEYWORD xmllib
363.637 -KEYWORD xmlrpclib
363.638 -KEYWORD zipfile
363.639 -KEYWORD zipimport
363.640 -KEYWORD zlib
364.1 --- a/python.editor/test/unit/data/testfiles/imports6.py.testImports6b.completion Sun Jan 04 13:11:53 2015 -0600
364.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
364.3 @@ -1,23 +0,0 @@
364.4 -Code completion result for source line:
364.5 -from i|
364.6 -(QueryType=COMPLETION, NameKind=PREFIX)
364.7 -------------------------------------
364.8 -KEYWORD ---ic ---
364.9 -KEYWORD ---icopen ---
364.10 -KEYWORD ihooks
364.11 -KEYWORD ---imageop ---
364.12 -KEYWORD imaplib
364.13 -KEYWORD imghdr
364.14 -KEYWORD imp
364.15 -KEYWORD imports3
364.16 -KEYWORD imports4
364.17 -KEYWORD imports5
364.18 -KEYWORD imports6
364.19 -KEYWORD imports7
364.20 -KEYWORD imports8
364.21 -KEYWORD imports9
364.22 -KEYWORD ---imputil ---
364.23 -KEYWORD inspect
364.24 -KEYWORD io
364.25 -KEYWORD isql
364.26 -KEYWORD itertools
365.1 --- a/python.editor/test/unit/data/testfiles/imports7.py Sun Jan 04 13:11:53 2015 -0600
365.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
365.3 @@ -1,2 +0,0 @@
365.4 -from sys import r
365.5 -
366.1 --- a/python.editor/test/unit/data/testfiles/imports7.py.testImports7.completion Sun Jan 04 13:11:53 2015 -0600
366.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
366.3 @@ -1,60 +0,0 @@
366.4 -Code completion result for source line:
366.5 -from sys import |r
366.6 -(QueryType=COMPLETION, NameKind=PREFIX)
366.7 -METHOD displayhook(value)
366.8 -METHOD exc_clear()
366.9 -METHOD exc_info()
366.10 -METHOD excepthook(type, value, traceb
366.11 -METHOD exit(arg)
366.12 -METHOD getcheckinterval()
366.13 -METHOD getdefaultencoding()
366.14 -METHOD getdlopenflags()
366.15 -METHOD getfilesystemencoding()
366.16 -METHOD getprofile()
366.17 -METHOD getrecursionlimit()
366.18 -METHOD getrefcount(object)
366.19 -METHOD getsizeof(object, default)
366.20 -METHOD gettrace()
366.21 -METHOD getwindowsversion()
366.22 -METHOD setcheckinterval(interval)
366.23 -METHOD setdefaultencoding(name)
366.24 -METHOD setdlopenflags(n)
366.25 -METHOD setprofile(profilefunc)
366.26 -METHOD setrecursionlimit(limit)
366.27 -METHOD settrace(tracefunc)
366.28 -METHOD settscdump(on_flag)
366.29 -VARIABLE __displayhook__
366.30 -VARIABLE __stdin__
366.31 -VARIABLE api_version
366.32 -VARIABLE argv
366.33 -VARIABLE builtin_module_names
366.34 -VARIABLE byteorder
366.35 -VARIABLE copyright
366.36 -VARIABLE dllhandle
366.37 -VARIABLE dont_write_bytecode
366.38 -VARIABLE ---exc_type ---
366.39 -VARIABLE exec_prefix
366.40 -VARIABLE executable
366.41 -VARIABLE ---exitfunc ---
366.42 -VARIABLE flags
366.43 -VARIABLE float_info
366.44 -VARIABLE hexversion
366.45 -VARIABLE last_type
366.46 -VARIABLE maxint
366.47 -VARIABLE maxsize
366.48 -VARIABLE maxunicode
366.49 -VARIABLE modules
366.50 -VARIABLE path
366.51 -VARIABLE platform
366.52 -VARIABLE prefix
366.53 -VARIABLE ps1
366.54 -VARIABLE py3kwarning
366.55 -VARIABLE stdin
366.56 -VARIABLE subversion
366.57 -VARIABLE tracebacklimit
366.58 -VARIABLE version
366.59 -VARIABLE version_info
366.60 -VARIABLE warnoptions
366.61 -VARIABLE winver
366.62 -------------------------------------
366.63 -KEYWORD * Import All Exported Symbols
367.1 --- a/python.editor/test/unit/data/testfiles/imports8.py Sun Jan 04 13:11:53 2015 -0600
367.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
367.3 @@ -1,2 +0,0 @@
367.4 -import distutils.command
367.5 -
368.1 --- a/python.editor/test/unit/data/testfiles/imports8.py.testImports8.completion Sun Jan 04 13:11:53 2015 -0600
368.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
368.3 @@ -1,26 +0,0 @@
368.4 -Code completion result for source line:
368.5 -import distutils.com|mand
368.6 -(QueryType=COMPLETION, NameKind=PREFIX)
368.7 -------------------------------------
368.8 -KEYWORD distutils.command
368.9 -KEYWORD distutils.command.bdist
368.10 -KEYWORD distutils.command.bdist_dumb
368.11 -KEYWORD distutils.command.bdist_msi
368.12 -KEYWORD distutils.command.bdist_rpm
368.13 -KEYWORD distutils.command.bdist_winins
368.14 -KEYWORD distutils.command.build
368.15 -KEYWORD distutils.command.build_clib
368.16 -KEYWORD distutils.command.build_ext
368.17 -KEYWORD distutils.command.build_py
368.18 -KEYWORD distutils.command.build_script
368.19 -KEYWORD distutils.command.clean
368.20 -KEYWORD distutils.command.config
368.21 -KEYWORD distutils.command.install
368.22 -KEYWORD distutils.command.install_data
368.23 -KEYWORD distutils.command.install_egg_
368.24 -KEYWORD distutils.command.install_head
368.25 -KEYWORD distutils.command.install_lib
368.26 -KEYWORD distutils.command.install_scri
368.27 -KEYWORD distutils.command.register
368.28 -KEYWORD distutils.command.sdist
368.29 -KEYWORD distutils.command.upload
369.1 --- a/python.editor/test/unit/data/testfiles/imports9.py Sun Jan 04 13:11:53 2015 -0600
369.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
369.3 @@ -1,2 +0,0 @@
369.4 -from difflib import c
369.5 -
370.1 --- a/python.editor/test/unit/data/testfiles/imports9.py.testImports9.completion Sun Jan 04 13:11:53 2015 -0600
370.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
370.3 @@ -1,16 +0,0 @@
370.4 -Code completion result for source line:
370.5 -from difflib import |c
370.6 -(QueryType=COMPLETION, NameKind=PREFIX)
370.7 -CLASS Differ
370.8 -CLASS HtmlDiff
370.9 -CLASS SequenceMatcher
370.10 -METHOD IS_CHARACTER_JUNK(ch, ws)
370.11 -METHOD IS_LINE_JUNK(line, pat)
370.12 -METHOD context_diff(a, b, fromfile, t
370.13 -METHOD get_close_matches(word, possib
370.14 -METHOD ndiff(a, b, linejunk, charjunk
370.15 -METHOD restore(delta, which)
370.16 -METHOD unified_diff(a, b, fromfile, t
370.17 -VARIABLE __all__
370.18 -------------------------------------
370.19 -KEYWORD * Import All Exported Symbols
371.1 --- a/python.editor/test/unit/data/testfiles/issue149618.py Sun Jan 04 13:11:53 2015 -0600
371.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
371.3 @@ -1,5 +0,0 @@
371.4 -def loadstable(name,theglobals=None,thelocals=None,fromlist=None,level=-1):
371.5 - if name.split('.')[0]!="tools"
371.6 - print "Python"
371.7 -
371.8 -
372.1 --- a/python.editor/test/unit/data/testfiles/issue149618.py.offsets Sun Jan 04 13:11:53 2015 -0600
372.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
372.3 @@ -1,6 +0,0 @@
372.4 -
372.5 -<Module><FunctionDef>def loadstable(<Name>name</Name>,<Name>theglobals</Name>=<Name>None</Name>,<Name>thelocals</Name>=<Name>None</Name>,<Name>fromlist</Name>=<Name>None</Name>,<Name>level</Name>=<Num>-1</Num>):
372.6 - <If>if <Compare><Subscript><Attribute><Name>name</Name>.split</Attribute><Call>(<Str>'.'</Str>)</Call>[<Index><Num>0</Num></Index>]</Subscript>!=<Str>"tools"</Str></Compare>
372.7 - <Print>print <Str>"Python"</Str></Print>
372.8 -
372.9 -</If></FunctionDef></Module>
373.1 --- a/python.editor/test/unit/data/testfiles/jreload.py Sun Jan 04 13:11:53 2015 -0600
373.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
373.3 @@ -1,119 +0,0 @@
373.4 -# java classes reload support (experimental)
373.5 -# Copyright 2000 Samuele Pedroni
373.6 -
373.7 -# ?? could have problem with import pkg.jclass.inner (this should not be used in any case)
373.8 -# ?? using import * with a load-set together with reloading can be confusing
373.9 -# cannot be fixed => anyway import * is not for production code
373.10 -
373.11 -__version__ = "0.3"
373.12 -
373.13 -import sys
373.14 -from org.python.core import imp,PyJavaPackage,PyJavaClass
373.15 -from _jython import is_lazy as _is_lazy
373.16 -
373.17 -import jxxload_help
373.18 -
373.19 -
373.20 -class _LoaderFactory(jxxload_help.JavaLoaderFactory):
373.21 - def __init__(self,path):
373.22 - vfs = jxxload_help.PathVFS()
373.23 - for fname in path:
373.24 - vfs.addVFS(fname)
373.25 - self.vfs = vfs
373.26 -
373.27 - def makeLoader(self):
373.28 - return jxxload_help.PathVFSJavaLoader(self.vfs,imp.getSyspathJavaLoader())
373.29 -
373.30 -class _Unload:
373.31 -
373.32 - def __init__(self,ls):
373.33 - self.ls = ls
373.34 - self.ls_name = ls._name
373.35 - self.loader = ls._mgr.loader
373.36 -
373.37 - def do_unload(self,pkg):
373.38 - for n in pkg.__dict__.keys():
373.39 - e = pkg.__dict__[n]
373.40 - if isinstance(e,PyJavaClass):
373.41 - if _is_lazy(e): continue
373.42 - if e.classLoader is self.loader:
373.43 - del pkg.__dict__[n]
373.44 - if pkg.__name__:
373.45 - n = self.ls_name + '.' + pkg.__name__ + '.' +n
373.46 - else:
373.47 - n = self.ls_name + '.' + n
373.48 - if sys.modules.has_key(n): del sys.modules[n]
373.49 -
373.50 - elif isinstance(e,PyJavaPackage):
373.51 - self.do_unload(e)
373.52 -
373.53 - def __call__(self):
373.54 - if self.loader:
373.55 - if self.ls._mgr.checkLoader() is self.loader:
373.56 - self.do_unload(self.ls._top)
373.57 - self.ls._mgr.resetLoader()
373.58 - loader = self.loader
373.59 - jxxload_help.DiscardHelp.discard(loader,loader.interfaces)
373.60 - self.loader = None
373.61 -
373.62 -class LoadSet:
373.63 -# ?? for the moment from import * and dir do not work for LoadSet, but work for
373.64 -# contained pkgs
373.65 -# need java impl as PyObject
373.66 -
373.67 - def __init__(self,name,path):
373.68 - mgr = jxxload_help.PackageManager(path,_LoaderFactory(path))
373.69 - self._name = name
373.70 - self._mgr = mgr
373.71 - self._top = mgr.topLevelPackage
373.72 -
373.73 - def __getattr__(self,name):
373.74 - try:
373.75 - return getattr(self._top,name)
373.76 - except:
373.77 - if name == 'unload': return _Unload(self)
373.78 - raise
373.79 -
373.80 -
373.81 - def __repr__(self):
373.82 - return "<java load-set %s>" % self._name
373.83 -
373.84 -def unloadf(ls):
373.85 - if not isinstance(ls,LoadSet): raise TypeError,"unloadf(): arg is not a load-set"
373.86 - return _Unload(ls)
373.87 -
373.88 -def makeLoadSet(name,path):
373.89 - if sys.modules.has_key(name): return sys.modules[name]
373.90 - sys.modules[name] = ls = LoadSet(name,path)
373.91 - return ls
373.92 -
373.93 -_reload = reload
373.94 -
373.95 -def _do_reload(ls_name,mgr,pkg):
373.96 - pkg_name = pkg.__name__
373.97 - for n in pkg.__dict__.keys():
373.98 - e = pkg.__dict__[n]
373.99 - if isinstance(e,PyJavaClass):
373.100 - if _is_lazy(e): continue
373.101 - del pkg.__dict__[n]
373.102 - try :
373.103 - c = mgr.findClass(pkg_name,n);
373.104 - if c:
373.105 - pkg.__dict__[n] = c
373.106 - if pkg_name:
373.107 - n = ls_name + '.' + pkg_name + '.' + n
373.108 - else:
373.109 - n = ls_name + '.' + n
373.110 - if sys.modules.has_key(n): sys.modules[n] = c
373.111 - except:
373.112 - pass
373.113 - elif isinstance(e,PyJavaPackage):
373.114 - _do_reload(ls_name,mgr,e)
373.115 -
373.116 -def reload(ls):
373.117 - if isinstance(ls,LoadSet):
373.118 - ls._mgr.resetLoader()
373.119 - _do_reload(ls._name,ls._mgr,ls._top)
373.120 - return ls
373.121 - else:
373.122 - return _reload(ls)
374.1 --- a/python.editor/test/unit/data/testfiles/jreload.py.indexed Sun Jan 04 13:11:53 2015 -0600
374.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
374.3 @@ -1,67 +0,0 @@
374.4 -
374.5 -
374.6 -Document 0
374.7 -Searchable Keys:
374.8 - class : LoadSet
374.9 - class-ig : loadset
374.10 - in : jreload
374.11 - member : __getattr__;F;;self,name;
374.12 - member : __init__;c;|CONSTRUCTOR|;self,name,path;
374.13 - member : __repr__;F;;self;
374.14 - member : _mgr;D;|PRIVATE|;
374.15 - member : _name;D;|PRIVATE|;
374.16 - member : _top;D;|PRIVATE|;
374.17 -
374.18 -Not Searchable Keys:
374.19 -
374.20 -
374.21 -Document 1
374.22 -Searchable Keys:
374.23 - class : _LoaderFactory
374.24 - class-ig : _loaderfactory
374.25 - extends : JavaLoaderFactory
374.26 - in : jreload
374.27 - member : __init__;c;|CONSTRUCTOR|;self,path;
374.28 - member : makeLoader;F;;self;
374.29 - member : vfs;D;;
374.30 -
374.31 -Not Searchable Keys:
374.32 - clzattrs : ;|PRIVATE|;
374.33 -
374.34 -
374.35 -Document 2
374.36 -Searchable Keys:
374.37 - class : _Unload
374.38 - class-ig : _unload
374.39 - in : jreload
374.40 - member : __call__;F;;self;
374.41 - member : __init__;c;|CONSTRUCTOR|;self,ls;
374.42 - member : do_unload;F;;self,pkg;
374.43 - member : loader;D;;
374.44 - member : ls;D;;
374.45 - member : ls_name;D;;
374.46 -
374.47 -Not Searchable Keys:
374.48 - clzattrs : ;|PRIVATE|;
374.49 -
374.50 -
374.51 -Document 3
374.52 -Searchable Keys:
374.53 - item : LoadSet;C;;
374.54 - item : PyJavaClass;I;;
374.55 - item : PyJavaPackage;I;;
374.56 - item : _LoaderFactory;C;|PRIVATE|;
374.57 - item : _Unload;C;|PRIVATE|;
374.58 - item : __version__;D;;
374.59 - item : _do_reload;F;|PRIVATE|;ls_name,mgr,pkg;
374.60 - item : _is_lazy;I;|PRIVATE|;
374.61 - item : _reload;D;|PRIVATE|;
374.62 - item : imp;I;;
374.63 - item : jxxload_help;I;;
374.64 - item : makeLoadSet;F;;name,path;
374.65 - item : reload;F;;ls;
374.66 - item : sys;I;;
374.67 - item : unloadf;F;;ls;
374.68 - module : jreload
374.69 -
374.70 -Not Searchable Keys:
375.1 --- a/python.editor/test/unit/data/testfiles/lib-old/Para.py Sun Jan 04 13:11:53 2015 -0600
375.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
375.3 @@ -1,343 +0,0 @@
375.4 -# Text formatting abstractions
375.5 -# Note -- this module is obsolete, it's too slow anyway
375.6 -
375.7 -
375.8 -# Oft-used type object
375.9 -Int = type(0)
375.10 -
375.11 -
375.12 -# Represent a paragraph. This is a list of words with associated
375.13 -# font and size information, plus indents and justification for the
375.14 -# entire paragraph.
375.15 -# Once the words have been added to a paragraph, it can be laid out
375.16 -# for different line widths. Once laid out, it can be rendered at
375.17 -# different screen locations. Once rendered, it can be queried
375.18 -# for mouse hits, and parts of the text can be highlighted
375.19 -class Para:
375.20 - #
375.21 - def __init__(self):
375.22 - self.words = [] # The words
375.23 - self.just = 'l' # Justification: 'l', 'r', 'lr' or 'c'
375.24 - self.indent_left = self.indent_right = self.indent_hang = 0
375.25 - # Final lay-out parameters, may change
375.26 - self.left = self.top = self.right = self.bottom = \
375.27 - self.width = self.height = self.lines = None
375.28 - #
375.29 - # Add a word, computing size information for it.
375.30 - # Words may also be added manually by appending to self.words
375.31 - # Each word should be a 7-tuple:
375.32 - # (font, text, width, space, stretch, ascent, descent)
375.33 - def addword(self, d, font, text, space, stretch):
375.34 - if font is not None:
375.35 - d.setfont(font)
375.36 - width = d.textwidth(text)
375.37 - ascent = d.baseline()
375.38 - descent = d.lineheight() - ascent
375.39 - spw = d.textwidth(' ')
375.40 - space = space * spw
375.41 - stretch = stretch * spw
375.42 - tuple = (font, text, width, space, stretch, ascent, descent)
375.43 - self.words.append(tuple)
375.44 - #
375.45 - # Hooks to begin and end anchors -- insert numbers in the word list!
375.46 - def bgn_anchor(self, id):
375.47 - self.words.append(id)
375.48 - #
375.49 - def end_anchor(self, id):
375.50 - self.words.append(0)
375.51 - #
375.52 - # Return the total length (width) of the text added so far, in pixels
375.53 - def getlength(self):
375.54 - total = 0
375.55 - for word in self.words:
375.56 - if type(word) is not Int:
375.57 - total = total + word[2] + word[3]
375.58 - return total
375.59 - #
375.60 - # Tab to a given position (relative to the current left indent):
375.61 - # remove all stretch, add fixed space up to the new indent.
375.62 - # If the current position is already at the tab stop,
375.63 - # don't add any new space (but still remove the stretch)
375.64 - def tabto(self, tab):
375.65 - total = 0
375.66 - as, de = 1, 0
375.67 - for i in range(len(self.words)):
375.68 - word = self.words[i]
375.69 - if type(word) is Int: continue
375.70 - (fo, te, wi, sp, st, as, de) = word
375.71 - self.words[i] = (fo, te, wi, sp, 0, as, de)
375.72 - total = total + wi + sp
375.73 - if total < tab:
375.74 - self.words.append((None, '', 0, tab-total, 0, as, de))
375.75 - #
375.76 - # Make a hanging tag: tab to hang, increment indent_left by hang,
375.77 - # and reset indent_hang to -hang
375.78 - def makehangingtag(self, hang):
375.79 - self.tabto(hang)
375.80 - self.indent_left = self.indent_left + hang
375.81 - self.indent_hang = -hang
375.82 - #
375.83 - # Decide where the line breaks will be given some screen width
375.84 - def layout(self, linewidth):
375.85 - self.width = linewidth
375.86 - height = 0
375.87 - self.lines = lines = []
375.88 - avail1 = self.width - self.indent_left - self.indent_right
375.89 - avail = avail1 - self.indent_hang
375.90 - words = self.words
375.91 - i = 0
375.92 - n = len(words)
375.93 - lastfont = None
375.94 - while i < n:
375.95 - firstfont = lastfont
375.96 - charcount = 0
375.97 - width = 0
375.98 - stretch = 0
375.99 - ascent = 0
375.100 - descent = 0
375.101 - lsp = 0
375.102 - j = i
375.103 - while i < n:
375.104 - word = words[i]
375.105 - if type(word) is Int:
375.106 - if word > 0 and width >= avail:
375.107 - break
375.108 - i = i+1
375.109 - continue
375.110 - fo, te, wi, sp, st, as, de = word
375.111 - if width + wi > avail and width > 0 and wi > 0:
375.112 - break
375.113 - if fo is not None:
375.114 - lastfont = fo
375.115 - if width == 0:
375.116 - firstfont = fo
375.117 - charcount = charcount + len(te) + (sp > 0)
375.118 - width = width + wi + sp
375.119 - lsp = sp
375.120 - stretch = stretch + st
375.121 - lst = st
375.122 - ascent = max(ascent, as)
375.123 - descent = max(descent, de)
375.124 - i = i+1
375.125 - while i > j and type(words[i-1]) is Int and \
375.126 - words[i-1] > 0: i = i-1
375.127 - width = width - lsp
375.128 - if i < n:
375.129 - stretch = stretch - lst
375.130 - else:
375.131 - stretch = 0
375.132 - tuple = i-j, firstfont, charcount, width, stretch, \
375.133 - ascent, descent
375.134 - lines.append(tuple)
375.135 - height = height + ascent + descent
375.136 - avail = avail1
375.137 - self.height = height
375.138 - #
375.139 - # Call a function for all words in a line
375.140 - def visit(self, wordfunc, anchorfunc):
375.141 - avail1 = self.width - self.indent_left - self.indent_right
375.142 - avail = avail1 - self.indent_hang
375.143 - v = self.top
375.144 - i = 0
375.145 - for tuple in self.lines:
375.146 - wordcount, firstfont, charcount, width, stretch, \
375.147 - ascent, descent = tuple
375.148 - h = self.left + self.indent_left
375.149 - if i == 0: h = h + self.indent_hang
375.150 - extra = 0
375.151 - if self.just == 'r': h = h + avail - width
375.152 - elif self.just == 'c': h = h + (avail - width) / 2
375.153 - elif self.just == 'lr' and stretch > 0:
375.154 - extra = avail - width
375.155 - v2 = v + ascent + descent
375.156 - for j in range(i, i+wordcount):
375.157 - word = self.words[j]
375.158 - if type(word) is Int:
375.159 - ok = anchorfunc(self, tuple, word, \
375.160 - h, v)
375.161 - if ok is not None: return ok
375.162 - continue
375.163 - fo, te, wi, sp, st, as, de = word
375.164 - if extra > 0 and stretch > 0:
375.165 - ex = extra * st / stretch
375.166 - extra = extra - ex
375.167 - stretch = stretch - st
375.168 - else:
375.169 - ex = 0
375.170 - h2 = h + wi + sp + ex
375.171 - ok = wordfunc(self, tuple, word, h, v, \
375.172 - h2, v2, (j==i), (j==i+wordcount-1))
375.173 - if ok is not None: return ok
375.174 - h = h2
375.175 - v = v2
375.176 - i = i + wordcount
375.177 - avail = avail1
375.178 - #
375.179 - # Render a paragraph in "drawing object" d, using the rectangle
375.180 - # given by (left, top, right) with an unspecified bottom.
375.181 - # Return the computed bottom of the text.
375.182 - def render(self, d, left, top, right):
375.183 - if self.width != right-left:
375.184 - self.layout(right-left)
375.185 - self.left = left
375.186 - self.top = top
375.187 - self.right = right
375.188 - self.bottom = self.top + self.height
375.189 - self.anchorid = 0
375.190 - try:
375.191 - self.d = d
375.192 - self.visit(self.__class__._renderword, \
375.193 - self.__class__._renderanchor)
375.194 - finally:
375.195 - self.d = None
375.196 - return self.bottom
375.197 - #
375.198 - def _renderword(self, tuple, word, h, v, h2, v2, isfirst, islast):
375.199 - if word[0] is not None: self.d.setfont(word[0])
375.200 - baseline = v + tuple[5]
375.201 - self.d.text((h, baseline - word[5]), word[1])
375.202 - if self.anchorid > 0:
375.203 - self.d.line((h, baseline+2), (h2, baseline+2))
375.204 - #
375.205 - def _renderanchor(self, tuple, word, h, v):
375.206 - self.anchorid = word
375.207 - #
375.208 - # Return which anchor(s) was hit by the mouse
375.209 - def hitcheck(self, mouseh, mousev):
375.210 - self.mouseh = mouseh
375.211 - self.mousev = mousev
375.212 - self.anchorid = 0
375.213 - self.hits = []
375.214 - self.visit(self.__class__._hitcheckword, \
375.215 - self.__class__._hitcheckanchor)
375.216 - return self.hits
375.217 - #
375.218 - def _hitcheckword(self, tuple, word, h, v, h2, v2, isfirst, islast):
375.219 - if self.anchorid > 0 and h <= self.mouseh <= h2 and \
375.220 - v <= self.mousev <= v2:
375.221 - self.hits.append(self.anchorid)
375.222 - #
375.223 - def _hitcheckanchor(self, tuple, word, h, v):
375.224 - self.anchorid = word
375.225 - #
375.226 - # Return whether the given anchor id is present
375.227 - def hasanchor(self, id):
375.228 - return id in self.words or -id in self.words
375.229 - #
375.230 - # Extract the raw text from the word list, substituting one space
375.231 - # for non-empty inter-word space, and terminating with '\n'
375.232 - def extract(self):
375.233 - text = ''
375.234 - for w in self.words:
375.235 - if type(w) is not Int:
375.236 - word = w[1]
375.237 - if w[3]: word = word + ' '
375.238 - text = text + word
375.239 - return text + '\n'
375.240 - #
375.241 - # Return which character position was hit by the mouse, as
375.242 - # an offset in the entire text as returned by extract().
375.243 - # Return None if the mouse was not in this paragraph
375.244 - def whereis(self, d, mouseh, mousev):
375.245 - if mousev < self.top or mousev > self.bottom:
375.246 - return None
375.247 - self.mouseh = mouseh
375.248 - self.mousev = mousev
375.249 - self.lastfont = None
375.250 - self.charcount = 0
375.251 - try:
375.252 - self.d = d
375.253 - return self.visit(self.__class__._whereisword, \
375.254 - self.__class__._whereisanchor)
375.255 - finally:
375.256 - self.d = None
375.257 - #
375.258 - def _whereisword(self, tuple, word, h1, v1, h2, v2, isfirst, islast):
375.259 - fo, te, wi, sp, st, as, de = word
375.260 - if fo is not None: self.lastfont = fo
375.261 - h = h1
375.262 - if isfirst: h1 = 0
375.263 - if islast: h2 = 999999
375.264 - if not (v1 <= self.mousev <= v2 and h1 <= self.mouseh <= h2):
375.265 - self.charcount = self.charcount + len(te) + (sp > 0)
375.266 - return
375.267 - if self.lastfont is not None:
375.268 - self.d.setfont(self.lastfont)
375.269 - cc = 0
375.270 - for c in te:
375.271 - cw = self.d.textwidth(c)
375.272 - if self.mouseh <= h + cw/2:
375.273 - return self.charcount + cc
375.274 - cc = cc+1
375.275 - h = h+cw
375.276 - self.charcount = self.charcount + cc
375.277 - if self.mouseh <= (h+h2) / 2:
375.278 - return self.charcount
375.279 - else:
375.280 - return self.charcount + 1
375.281 - #
375.282 - def _whereisanchor(self, tuple, word, h, v):
375.283 - pass
375.284 - #
375.285 - # Return screen position corresponding to position in paragraph.
375.286 - # Return tuple (h, vtop, vbaseline, vbottom).
375.287 - # This is more or less the inverse of whereis()
375.288 - def screenpos(self, d, pos):
375.289 - if pos < 0:
375.290 - ascent, descent = self.lines[0][5:7]
375.291 - return self.left, self.top, self.top + ascent, \
375.292 - self.top + ascent + descent
375.293 - self.pos = pos
375.294 - self.lastfont = None
375.295 - try:
375.296 - self.d = d
375.297 - ok = self.visit(self.__class__._screenposword, \
375.298 - self.__class__._screenposanchor)
375.299 - finally:
375.300 - self.d = None
375.301 - if ok is None:
375.302 - ascent, descent = self.lines[-1][5:7]
375.303 - ok = self.right, self.bottom - ascent - descent, \
375.304 - self.bottom - descent, self.bottom
375.305 - return ok
375.306 - #
375.307 - def _screenposword(self, tuple, word, h1, v1, h2, v2, isfirst, islast):
375.308 - fo, te, wi, sp, st, as, de = word
375.309 - if fo is not None: self.lastfont = fo
375.310 - cc = len(te) + (sp > 0)
375.311 - if self.pos > cc:
375.312 - self.pos = self.pos - cc
375.313 - return
375.314 - if self.pos < cc:
375.315 - self.d.setfont(self.lastfont)
375.316 - h = h1 + self.d.textwidth(te[:self.pos])
375.317 - else:
375.318 - h = h2
375.319 - ascent, descent = tuple[5:7]
375.320 - return h, v1, v1+ascent, v2
375.321 - #
375.322 - def _screenposanchor(self, tuple, word, h, v):
375.323 - pass
375.324 - #
375.325 - # Invert the stretch of text between pos1 and pos2.
375.326 - # If pos1 is None, the beginning is implied;
375.327 - # if pos2 is None, the end is implied.
375.328 - # Undoes its own effect when called again with the same arguments
375.329 - def invert(self, d, pos1, pos2):
375.330 - if pos1 is None:
375.331 - pos1 = self.left, self.top, self.top, self.top
375.332 - else:
375.333 - pos1 = self.screenpos(d, pos1)
375.334 - if pos2 is None:
375.335 - pos2 = self.right, self.bottom,self.bottom,self.bottom
375.336 - else:
375.337 - pos2 = self.screenpos(d, pos2)
375.338 - h1, top1, baseline1, bottom1 = pos1
375.339 - h2, top2, baseline2, bottom2 = pos2
375.340 - if bottom1 <= top2:
375.341 - d.invert((h1, top1), (self.right, bottom1))
375.342 - h1 = self.left
375.343 - if bottom1 < top2:
375.344 - d.invert((h1, bottom1), (self.right, top2))
375.345 - top1, bottom1 = top2, bottom2
375.346 - d.invert((h1, top1), (h2, bottom2))
376.1 --- a/python.editor/test/unit/data/testfiles/md5.py Sun Jan 04 13:11:53 2015 -0600
376.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
376.3 @@ -1,10 +0,0 @@
376.4 -# $Id: md5.py 39316 2005-08-21 18:45:59Z greg $
376.5 -#
376.6 -# Copyright (C) 2005 Gregory P. Smith (greg@electricrain.com)
376.7 -# Licensed to PSF under a Contributor Agreement.
376.8 -
376.9 -from hashlib import md5
376.10 -new = md5
376.11 -
376.12 -blocksize = 1 # legacy value (wrong in any useful sense)
376.13 -digest_size = 16
377.1 --- a/python.editor/test/unit/data/testfiles/md5.py.indexed Sun Jan 04 13:11:53 2015 -0600
377.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
377.3 @@ -1,12 +0,0 @@
377.4 -
377.5 -
377.6 -Document 0
377.7 -Searchable Keys:
377.8 - item : blocksize;D;;
377.9 - item : digest_size;D;;
377.10 - item : md5;I;;
377.11 - item : new;D;;
377.12 - module : md5
377.13 -
377.14 -Not Searchable Keys:
377.15 - modattrs : D
378.1 --- a/python.editor/test/unit/data/testfiles/mimetypes.py Sun Jan 04 13:11:53 2015 -0600
378.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
378.3 @@ -1,533 +0,0 @@
378.4 -"""Guess the MIME type of a file.
378.5 -
378.6 -This module defines two useful functions:
378.7 -
378.8 -guess_type(url, strict=1) -- guess the MIME type and encoding of a URL.
378.9 -
378.10 -guess_extension(type, strict=1) -- guess the extension for a given MIME type.
378.11 -
378.12 -It also contains the following, for tuning the behavior:
378.13 -
378.14 -Data:
378.15 -
378.16 -knownfiles -- list of files to parse
378.17 -inited -- flag set when init() has been called
378.18 -suffix_map -- dictionary mapping suffixes to suffixes
378.19 -encodings_map -- dictionary mapping suffixes to encodings
378.20 -types_map -- dictionary mapping suffixes to types
378.21 -
378.22 -Functions:
378.23 -
378.24 -init([files]) -- parse a list of files, default knownfiles
378.25 -read_mime_types(file) -- parse one file, return a dictionary or None
378.26 -"""
378.27 -
378.28 -import os
378.29 -import posixpath
378.30 -import urllib
378.31 -
378.32 -__all__ = [
378.33 - "guess_type","guess_extension","guess_all_extensions",
378.34 - "add_type","read_mime_types","init"
378.35 -]
378.36 -
378.37 -knownfiles = [
378.38 - "/etc/mime.types",
378.39 - "/etc/httpd/mime.types", # Mac OS X
378.40 - "/etc/httpd/conf/mime.types", # Apache
378.41 - "/etc/apache/mime.types", # Apache 1
378.42 - "/etc/apache2/mime.types", # Apache 2
378.43 - "/usr/local/etc/httpd/conf/mime.types",
378.44 - "/usr/local/lib/netscape/mime.types",
378.45 - "/usr/local/etc/httpd/conf/mime.types", # Apache 1.2
378.46 - "/usr/local/etc/mime.types", # Apache 1.3
378.47 - ]
378.48 -
378.49 -inited = False
378.50 -
378.51 -
378.52 -class MimeTypes:
378.53 - """MIME-types datastore.
378.54 -
378.55 - This datastore can handle information from mime.types-style files
378.56 - and supports basic determination of MIME type from a filename or
378.57 - URL, and can guess a reasonable extension given a MIME type.
378.58 - """
378.59 -
378.60 - def __init__(self, filenames=(), strict=True):
378.61 - if not inited:
378.62 - init()
378.63 - self.encodings_map = encodings_map.copy()
378.64 - self.suffix_map = suffix_map.copy()
378.65 - self.types_map = ({}, {}) # dict for (non-strict, strict)
378.66 - self.types_map_inv = ({}, {})
378.67 - for (ext, type) in types_map.items():
378.68 - self.add_type(type, ext, True)
378.69 - for (ext, type) in common_types.items():
378.70 - self.add_type(type, ext, False)
378.71 - for name in filenames:
378.72 - self.read(name, strict)
378.73 -
378.74 - def add_type(self, type, ext, strict=True):
378.75 - """Add a mapping between a type and an extension.
378.76 -
378.77 - When the extension is already known, the new
378.78 - type will replace the old one. When the type
378.79 - is already known the extension will be added
378.80 - to the list of known extensions.
378.81 -
378.82 - If strict is true, information will be added to
378.83 - list of standard types, else to the list of non-standard
378.84 - types.
378.85 - """
378.86 - self.types_map[strict][ext] = type
378.87 - exts = self.types_map_inv[strict].setdefault(type, [])
378.88 - if ext not in exts:
378.89 - exts.append(ext)
378.90 -
378.91 - def guess_type(self, url, strict=True):
378.92 - """Guess the type of a file based on its URL.
378.93 -
378.94 - Return value is a tuple (type, encoding) where type is None if
378.95 - the type can't be guessed (no or unknown suffix) or a string
378.96 - of the form type/subtype, usable for a MIME Content-type
378.97 - header; and encoding is None for no encoding or the name of
378.98 - the program used to encode (e.g. compress or gzip). The
378.99 - mappings are table driven. Encoding suffixes are case
378.100 - sensitive; type suffixes are first tried case sensitive, then
378.101 - case insensitive.
378.102 -
378.103 - The suffixes .tgz, .taz and .tz (case sensitive!) are all
378.104 - mapped to '.tar.gz'. (This is table-driven too, using the
378.105 - dictionary suffix_map.)
378.106 -
378.107 - Optional `strict' argument when False adds a bunch of commonly found,
378.108 - but non-standard types.
378.109 - """
378.110 - scheme, url = urllib.splittype(url)
378.111 - if scheme == 'data':
378.112 - # syntax of data URLs:
378.113 - # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
378.114 - # mediatype := [ type "/" subtype ] *( ";" parameter )
378.115 - # data := *urlchar
378.116 - # parameter := attribute "=" value
378.117 - # type/subtype defaults to "text/plain"
378.118 - comma = url.find(',')
378.119 - if comma < 0:
378.120 - # bad data URL
378.121 - return None, None
378.122 - semi = url.find(';', 0, comma)
378.123 - if semi >= 0:
378.124 - type = url[:semi]
378.125 - else:
378.126 - type = url[:comma]
378.127 - if '=' in type or '/' not in type:
378.128 - type = 'text/plain'
378.129 - return type, None # never compressed, so encoding is None
378.130 - base, ext = posixpath.splitext(url)
378.131 - while ext in self.suffix_map:
378.132 - base, ext = posixpath.splitext(base + self.suffix_map[ext])
378.133 - if ext in self.encodings_map:
378.134 - encoding = self.encodings_map[ext]
378.135 - base, ext = posixpath.splitext(base)
378.136 - else:
378.137 - encoding = None
378.138 - types_map = self.types_map[True]
378.139 - if ext in types_map:
378.140 - return types_map[ext], encoding
378.141 - elif ext.lower() in types_map:
378.142 - return types_map[ext.lower()], encoding
378.143 - elif strict:
378.144 - return None, encoding
378.145 - types_map = self.types_map[False]
378.146 - if ext in types_map:
378.147 - return types_map[ext], encoding
378.148 - elif ext.lower() in types_map:
378.149 - return types_map[ext.lower()], encoding
378.150 - else:
378.151 - return None, encoding
378.152 -
378.153 - def guess_all_extensions(self, type, strict=True):
378.154 - """Guess the extensions for a file based on its MIME type.
378.155 -
378.156 - Return value is a list of strings giving the possible filename
378.157 - extensions, including the leading dot ('.'). The extension is not
378.158 - guaranteed to have been associated with any particular data stream,
378.159 - but would be mapped to the MIME type `type' by guess_type().
378.160 -
378.161 - Optional `strict' argument when false adds a bunch of commonly found,
378.162 - but non-standard types.
378.163 - """
378.164 - type = type.lower()
378.165 - extensions = self.types_map_inv[True].get(type, [])
378.166 - if not strict:
378.167 - for ext in self.types_map_inv[False].get(type, []):
378.168 - if ext not in extensions:
378.169 - extensions.append(ext)
378.170 - return extensions
378.171 -
378.172 - def guess_extension(self, type, strict=True):
378.173 - """Guess the extension for a file based on its MIME type.
378.174 -
378.175 - Return value is a string giving a filename extension,
378.176 - including the leading dot ('.'). The extension is not
378.177 - guaranteed to have been associated with any particular data
378.178 - stream, but would be mapped to the MIME type `type' by
378.179 - guess_type(). If no extension can be guessed for `type', None
378.180 - is returned.
378.181 -
378.182 - Optional `strict' argument when false adds a bunch of commonly found,
378.183 - but non-standard types.
378.184 - """
378.185 - extensions = self.guess_all_extensions(type, strict)
378.186 - if not extensions:
378.187 - return None
378.188 - return extensions[0]
378.189 -
378.190 - def read(self, filename, strict=True):
378.191 - """
378.192 - Read a single mime.types-format file, specified by pathname.
378.193 -
378.194 - If strict is true, information will be added to
378.195 - list of standard types, else to the list of non-standard
378.196 - types.
378.197 - """
378.198 - fp = open(filename)
378.199 - self.readfp(fp, strict)
378.200 - fp.close()
378.201 -
378.202 - def readfp(self, fp, strict=True):
378.203 - """
378.204 - Read a single mime.types-format file.
378.205 -
378.206 - If strict is true, information will be added to
378.207 - list of standard types, else to the list of non-standard
378.208 - types.
378.209 - """
378.210 - while 1:
378.211 - line = fp.readline()
378.212 - if not line:
378.213 - break
378.214 - words = line.split()
378.215 - for i in range(len(words)):
378.216 - if words[i][0] == '#':
378.217 - del words[i:]
378.218 - break
378.219 - if not words:
378.220 - continue
378.221 - type, suffixes = words[0], words[1:]
378.222 - for suff in suffixes:
378.223 - self.add_type(type, '.' + suff, strict)
378.224 -
378.225 -def guess_type(url, strict=True):
378.226 - """Guess the type of a file based on its URL.
378.227 -
378.228 - Return value is a tuple (type, encoding) where type is None if the
378.229 - type can't be guessed (no or unknown suffix) or a string of the
378.230 - form type/subtype, usable for a MIME Content-type header; and
378.231 - encoding is None for no encoding or the name of the program used
378.232 - to encode (e.g. compress or gzip). The mappings are table
378.233 - driven. Encoding suffixes are case sensitive; type suffixes are
378.234 - first tried case sensitive, then case insensitive.
378.235 -
378.236 - The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped
378.237 - to ".tar.gz". (This is table-driven too, using the dictionary
378.238 - suffix_map).
378.239 -
378.240 - Optional `strict' argument when false adds a bunch of commonly found, but
378.241 - non-standard types.
378.242 - """
378.243 - init()
378.244 - return guess_type(url, strict)
378.245 -
378.246 -
378.247 -def guess_all_extensions(type, strict=True):
378.248 - """Guess the extensions for a file based on its MIME type.
378.249 -
378.250 - Return value is a list of strings giving the possible filename
378.251 - extensions, including the leading dot ('.'). The extension is not
378.252 - guaranteed to have been associated with any particular data
378.253 - stream, but would be mapped to the MIME type `type' by
378.254 - guess_type(). If no extension can be guessed for `type', None
378.255 - is returned.
378.256 -
378.257 - Optional `strict' argument when false adds a bunch of commonly found,
378.258 - but non-standard types.
378.259 - """
378.260 - init()
378.261 - return guess_all_extensions(type, strict)
378.262 -
378.263 -def guess_extension(type, strict=True):
378.264 - """Guess the extension for a file based on its MIME type.
378.265 -
378.266 - Return value is a string giving a filename extension, including the
378.267 - leading dot ('.'). The extension is not guaranteed to have been
378.268 - associated with any particular data stream, but would be mapped to the
378.269 - MIME type `type' by guess_type(). If no extension can be guessed for
378.270 - `type', None is returned.
378.271 -
378.272 - Optional `strict' argument when false adds a bunch of commonly found,
378.273 - but non-standard types.
378.274 - """
378.275 - init()
378.276 - return guess_extension(type, strict)
378.277 -
378.278 -def add_type(type, ext, strict=True):
378.279 - """Add a mapping between a type and an extension.
378.280 -
378.281 - When the extension is already known, the new
378.282 - type will replace the old one. When the type
378.283 - is already known the extension will be added
378.284 - to the list of known extensions.
378.285 -
378.286 - If strict is true, information will be added to
378.287 - list of standard types, else to the list of non-standard
378.288 - types.
378.289 - """
378.290 - init()
378.291 - return add_type(type, ext, strict)
378.292 -
378.293 -
378.294 -def init(files=None):
378.295 - global guess_all_extensions, guess_extension, guess_type
378.296 - global suffix_map, types_map, encodings_map, common_types
378.297 - global add_type, inited
378.298 - inited = True
378.299 - db = MimeTypes()
378.300 - if files is None:
378.301 - files = knownfiles
378.302 - for file in files:
378.303 - if os.path.isfile(file):
378.304 - db.readfp(open(file))
378.305 - encodings_map = db.encodings_map
378.306 - suffix_map = db.suffix_map
378.307 - types_map = db.types_map[True]
378.308 - guess_all_extensions = db.guess_all_extensions
378.309 - guess_extension = db.guess_extension
378.310 - guess_type = db.guess_type
378.311 - add_type = db.add_type
378.312 - common_types = db.types_map[False]
378.313 -
378.314 -
378.315 -def read_mime_types(file):
378.316 - try:
378.317 - f = open(file)
378.318 - except IOError:
378.319 - return None
378.320 - db = MimeTypes()
378.321 - db.readfp(f, True)
378.322 - return db.types_map[True]
378.323 -
378.324 -
378.325 -def _default_mime_types():
378.326 - global suffix_map
378.327 - global encodings_map
378.328 - global types_map
378.329 - global common_types
378.330 -
378.331 - suffix_map = {
378.332 - '.tgz': '.tar.gz',
378.333 - '.taz': '.tar.gz',
378.334 - '.tz': '.tar.gz',
378.335 - }
378.336 -
378.337 - encodings_map = {
378.338 - '.gz': 'gzip',
378.339 - '.Z': 'compress',
378.340 - }
378.341 -
378.342 - # Before adding new types, make sure they are either registered with IANA,
378.343 - # at http://www.isi.edu/in-notes/iana/assignments/media-types
378.344 - # or extensions, i.e. using the x- prefix
378.345 -
378.346 - # If you add to these, please keep them sorted!
378.347 - types_map = {
378.348 - '.a' : 'application/octet-stream',
378.349 - '.ai' : 'application/postscript',
378.350 - '.aif' : 'audio/x-aiff',
378.351 - '.aifc' : 'audio/x-aiff',
378.352 - '.aiff' : 'audio/x-aiff',
378.353 - '.au' : 'audio/basic',
378.354 - '.avi' : 'video/x-msvideo',
378.355 - '.bat' : 'text/plain',
378.356 - '.bcpio' : 'application/x-bcpio',
378.357 - '.bin' : 'application/octet-stream',
378.358 - '.bmp' : 'image/x-ms-bmp',
378.359 - '.c' : 'text/plain',
378.360 - # Duplicates :(
378.361 - '.cdf' : 'application/x-cdf',
378.362 - '.cdf' : 'application/x-netcdf',
378.363 - '.cpio' : 'application/x-cpio',
378.364 - '.csh' : 'application/x-csh',
378.365 - '.css' : 'text/css',
378.366 - '.dll' : 'application/octet-stream',
378.367 - '.doc' : 'application/msword',
378.368 - '.dot' : 'application/msword',
378.369 - '.dvi' : 'application/x-dvi',
378.370 - '.eml' : 'message/rfc822',
378.371 - '.eps' : 'application/postscript',
378.372 - '.etx' : 'text/x-setext',
378.373 - '.exe' : 'application/octet-stream',
378.374 - '.gif' : 'image/gif',
378.375 - '.gtar' : 'application/x-gtar',
378.376 - '.h' : 'text/plain',
378.377 - '.hdf' : 'application/x-hdf',
378.378 - '.htm' : 'text/html',
378.379 - '.html' : 'text/html',
378.380 - '.ief' : 'image/ief',
378.381 - '.jpe' : 'image/jpeg',
378.382 - '.jpeg' : 'image/jpeg',
378.383 - '.jpg' : 'image/jpeg',
378.384 - '.js' : 'application/x-javascript',
378.385 - '.ksh' : 'text/plain',
378.386 - '.latex' : 'application/x-latex',
378.387 - '.m1v' : 'video/mpeg',
378.388 - '.man' : 'application/x-troff-man',
378.389 - '.me' : 'application/x-troff-me',
378.390 - '.mht' : 'message/rfc822',
378.391 - '.mhtml' : 'message/rfc822',
378.392 - '.mif' : 'application/x-mif',
378.393 - '.mov' : 'video/quicktime',
378.394 - '.movie' : 'video/x-sgi-movie',
378.395 - '.mp2' : 'audio/mpeg',
378.396 - '.mp3' : 'audio/mpeg',
378.397 - '.mpa' : 'video/mpeg',
378.398 - '.mpe' : 'video/mpeg',
378.399 - '.mpeg' : 'video/mpeg',
378.400 - '.mpg' : 'video/mpeg',
378.401 - '.ms' : 'application/x-troff-ms',
378.402 - '.nc' : 'application/x-netcdf',
378.403 - '.nws' : 'message/rfc822',
378.404 - '.o' : 'application/octet-stream',
378.405 - '.obj' : 'application/octet-stream',
378.406 - '.oda' : 'application/oda',
378.407 - '.p12' : 'application/x-pkcs12',
378.408 - '.p7c' : 'application/pkcs7-mime',
378.409 - '.pbm' : 'image/x-portable-bitmap',
378.410 - '.pdf' : 'application/pdf',
378.411 - '.pfx' : 'application/x-pkcs12',
378.412 - '.pgm' : 'image/x-portable-graymap',
378.413 - '.pl' : 'text/plain',
378.414 - '.png' : 'image/png',
378.415 - '.pnm' : 'image/x-portable-anymap',
378.416 - '.pot' : 'application/vnd.ms-powerpoint',
378.417 - '.ppa' : 'application/vnd.ms-powerpoint',
378.418 - '.ppm' : 'image/x-portable-pixmap',
378.419 - '.pps' : 'application/vnd.ms-powerpoint',
378.420 - '.ppt' : 'application/vnd.ms-powerpoint',
378.421 - '.ps' : 'application/postscript',
378.422 - '.pwz' : 'application/vnd.ms-powerpoint',
378.423 - '.py' : 'text/x-python',
378.424 - '.pyc' : 'application/x-python-code',
378.425 - '.pyo' : 'application/x-python-code',
378.426 - '.qt' : 'video/quicktime',
378.427 - '.ra' : 'audio/x-pn-realaudio',
378.428 - '.ram' : 'application/x-pn-realaudio',
378.429 - '.ras' : 'image/x-cmu-raster',
378.430 - '.rdf' : 'application/xml',
378.431 - '.rgb' : 'image/x-rgb',
378.432 - '.roff' : 'application/x-troff',
378.433 - '.rtx' : 'text/richtext',
378.434 - '.sgm' : 'text/x-sgml',
378.435 - '.sgml' : 'text/x-sgml',
378.436 - '.sh' : 'application/x-sh',
378.437 - '.shar' : 'application/x-shar',
378.438 - '.snd' : 'audio/basic',
378.439 - '.so' : 'application/octet-stream',
378.440 - '.src' : 'application/x-wais-source',
378.441 - '.sv4cpio': 'application/x-sv4cpio',
378.442 - '.sv4crc' : 'application/x-sv4crc',
378.443 - '.swf' : 'application/x-shockwave-flash',
378.444 - '.t' : 'application/x-troff',
378.445 - '.tar' : 'application/x-tar',
378.446 - '.tcl' : 'application/x-tcl',
378.447 - '.tex' : 'application/x-tex',
378.448 - '.texi' : 'application/x-texinfo',
378.449 - '.texinfo': 'application/x-texinfo',
378.450 - '.tif' : 'image/tiff',
378.451 - '.tiff' : 'image/tiff',
378.452 - '.tr' : 'application/x-troff',
378.453 - '.tsv' : 'text/tab-separated-values',
378.454 - '.txt' : 'text/plain',
378.455 - '.ustar' : 'application/x-ustar',
378.456 - '.vcf' : 'text/x-vcard',
378.457 - '.wav' : 'audio/x-wav',
378.458 - '.wiz' : 'application/msword',
378.459 - '.wsdl' : 'application/xml',
378.460 - '.xbm' : 'image/x-xbitmap',
378.461 - '.xlb' : 'application/vnd.ms-excel',
378.462 - # Duplicates :(
378.463 - '.xls' : 'application/excel',
378.464 - '.xls' : 'application/vnd.ms-excel',
378.465 - '.xml' : 'text/xml',
378.466 - '.xpdl' : 'application/xml',
378.467 - '.xpm' : 'image/x-xpixmap',
378.468 - '.xsl' : 'application/xml',
378.469 - '.xwd' : 'image/x-xwindowdump',
378.470 - '.zip' : 'application/zip',
378.471 - }
378.472 -
378.473 - # These are non-standard types, commonly found in the wild. They will
378.474 - # only match if strict=0 flag is given to the API methods.
378.475 -
378.476 - # Please sort these too
378.477 - common_types = {
378.478 - '.jpg' : 'image/jpg',
378.479 - '.mid' : 'audio/midi',
378.480 - '.midi': 'audio/midi',
378.481 - '.pct' : 'image/pict',
378.482 - '.pic' : 'image/pict',
378.483 - '.pict': 'image/pict',
378.484 - '.rtf' : 'application/rtf',
378.485 - '.xul' : 'text/xul'
378.486 - }
378.487 -
378.488 -
378.489 -_default_mime_types()
378.490 -
378.491 -
378.492 -if __name__ == '__main__':
378.493 - import sys
378.494 - import getopt
378.495 -
378.496 - USAGE = """\
378.497 -Usage: mimetypes.py [options] type
378.498 -
378.499 -Options:
378.500 - --help / -h -- print this message and exit
378.501 - --lenient / -l -- additionally search of some common, but non-standard
378.502 - types.
378.503 - --extension / -e -- guess extension instead of type
378.504 -
378.505 -More than one type argument may be given.
378.506 -"""
378.507 -
378.508 - def usage(code, msg=''):
378.509 - print USAGE
378.510 - if msg: print msg
378.511 - sys.exit(code)
378.512 -
378.513 - try:
378.514 - opts, args = getopt.getopt(sys.argv[1:], 'hle',
378.515 - ['help', 'lenient', 'extension'])
378.516 - except getopt.error, msg:
378.517 - usage(1, msg)
378.518 -
378.519 - strict = 1
378.520 - extension = 0
378.521 - for opt, arg in opts:
378.522 - if opt in ('-h', '--help'):
378.523 - usage(0)
378.524 - elif opt in ('-l', '--lenient'):
378.525 - strict = 0
378.526 - elif opt in ('-e', '--extension'):
378.527 - extension = 1
378.528 - for gtype in args:
378.529 - if extension:
378.530 - guess = guess_extension(gtype, strict)
378.531 - if not guess: print "I don't know anything about type", gtype
378.532 - else: print guess
378.533 - else:
378.534 - guess, encoding = guess_type(gtype, strict)
378.535 - if not guess: print "I don't know anything about type", gtype
378.536 - else: print 'type:', guess, 'encoding:', encoding
379.1 --- a/python.editor/test/unit/data/testfiles/mimetypes.py.scopes Sun Jan 04 13:11:53 2015 -0600
379.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
379.3 @@ -1,229 +0,0 @@
379.4 -=============================================
379.5 -<file-top>: Module : OffsetRange[0,18689>
379.6 -False [private][read][UNRESOLVED][node=Name]
379.7 -MimeTypes [bound][private][class][def][read][called][node=ClassDef]
379.8 -None [private][read][UNRESOLVED][node=Name]
379.9 -True [private][read][UNRESOLVED][node=Name]
379.10 -USAGE [bound][private][data][read][node=Name]
379.11 -__all__ [bound][data][node=Name]
379.12 -__name__ [private][read][UNRESOLVED][node=Name]
379.13 -_default_mime_types [bound][private][function][def][read][called][node=FunctionDef]
379.14 -add_type [bound][function][def][read][called][node=FunctionDef]
379.15 -arg [bound][private][data][node=Name]
379.16 -args [bound][private][data][read][node=Name]
379.17 -encoding [bound][private][data][read][node=Name]
379.18 -extension [bound][private][data][read][node=Name]
379.19 -getopt [bound][imported][private][data][read][node=Import]
379.20 -gtype [bound][private][data][read][node=Name]
379.21 -guess [bound][private][data][read][node=Name]
379.22 -guess_all_extensions [bound][function][def][read][called][node=FunctionDef]
379.23 -guess_extension [bound][function][def][read][called][node=FunctionDef]
379.24 -guess_type [bound][function][def][read][called][node=FunctionDef]
379.25 -init [bound][function][def][node=FunctionDef]
379.26 -inited [bound][private][data][read][node=Name]
379.27 -knownfiles [bound][private][data][read][node=Name]
379.28 -msg [bound][private][data][read][node=Name]
379.29 -opt [bound][private][data][read][node=Name]
379.30 -opts [bound][private][data][read][node=Name]
379.31 -os [bound][imported][private][data][read][node=Import]
379.32 -posixpath [bound][imported][private][data][read][node=Import]
379.33 -read_mime_types [bound][function][def][node=FunctionDef]
379.34 -strict [bound][private][data][read][node=Name]
379.35 -sys [bound][imported][private][data][read][node=Import]
379.36 -urllib [bound][imported][private][data][read][node=Import]
379.37 -usage [bound][private][function][def][read][called][node=FunctionDef]
379.38 -
379.39 - =============================================
379.40 - class MimeTypes: ClassDef : OffsetRange[1347,7937>
379.41 - True [free][private][read][node=Name]
379.42 - __init__ [bound][private][function][def][node=FunctionDef]
379.43 - add_type [bound][private][function][def][node=FunctionDef]
379.44 - guess_all_extensions [bound][private][function][def][node=FunctionDef]
379.45 - guess_extension [bound][private][function][def][node=FunctionDef]
379.46 - guess_type [bound][private][function][def][node=FunctionDef]
379.47 - read [bound][private][function][def][node=FunctionDef]
379.48 - readfp [bound][private][function][def][node=FunctionDef]
379.49 - ------ Attributes ---------------------------------------
379.50 - encodings_map : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
379.51 - suffix_map : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
379.52 - types_map : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
379.53 - types_map_inv : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
379.54 -
379.55 - =============================================
379.56 - __init__: FunctionDef : OffsetRange[1611,2151>
379.57 - False [free][private][read][node=Name]
379.58 - True [free][private][read][node=Name]
379.59 - common_types [free][private][read][node=Name]
379.60 - encodings_map [free][private][read][node=Name]
379.61 - ext [bound][private][data][read][node=Name]
379.62 - filenames [bound][param][private][data][read][node=Name]
379.63 - init [free][private][read][called][node=Name]
379.64 - inited [free][private][read][node=Name]
379.65 - name [bound][private][data][read][node=Name]
379.66 - self [bound][param][private][data][read][node=Name]
379.67 - strict [bound][param][private][data][read][node=Name]
379.68 - suffix_map [free][private][read][node=Name]
379.69 - type [bound][private][data][read][node=Name]
379.70 - types_map [free][private][read][node=Name]
379.71 - ------ Attributes ---------------------------------------
379.72 - add_type : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
379.73 - read : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
379.74 -
379.75 - =============================================
379.76 - add_type: FunctionDef : OffsetRange[2152,2771>
379.77 - ext [bound][param][private][data][read][node=Name]
379.78 - exts [bound][private][data][read][node=Name]
379.79 - self [bound][param][private][data][read][node=Name]
379.80 - strict [bound][param][private][data][read][node=Name]
379.81 - type [bound][param][private][data][read][node=Name]
379.82 - ------ Attributes ---------------------------------------
379.83 - types_map : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
379.84 - types_map_inv : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
379.85 -
379.86 - =============================================
379.87 - guess_type: FunctionDef : OffsetRange[2772,5327>
379.88 - False [free][private][read][node=Name]
379.89 - None [free][private][read][node=Name]
379.90 - True [free][private][read][node=Name]
379.91 - base [bound][private][data][read][node=Name]
379.92 - comma [bound][private][data][read][node=Name]
379.93 - encoding [bound][private][data][read][node=Name]
379.94 - ext [bound][private][data][read][node=Name]
379.95 - posixpath [free][private][read][node=Name]
379.96 - scheme [bound][private][data][read][node=Name]
379.97 - self [bound][param][private][data][read][node=Name]
379.98 - semi [bound][private][data][read][node=Name]
379.99 - strict [bound][param][private][data][read][node=Name]
379.100 - type [bound][private][data][read][node=Name]
379.101 - types_map [bound][private][data][read][node=Name]
379.102 - url [bound][param][private][data][read][node=Name]
379.103 - urllib [free][private][read][node=Name]
379.104 - ------ Attributes ---------------------------------------
379.105 - encodings_map : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
379.106 - suffix_map : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
379.107 - types_map : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
379.108 -
379.109 - =============================================
379.110 - guess_all_extensions: FunctionDef : OffsetRange[5328,6151>
379.111 - False [free][private][read][node=Name]
379.112 - True [free][private][read][node=Name]
379.113 - ext [bound][private][data][read][node=Name]
379.114 - extensions [bound][private][data][read][node=Name]
379.115 - self [bound][param][private][data][read][node=Name]
379.116 - strict [bound][param][private][data][read][node=Name]
379.117 - type [bound][param][private][data][read][node=Name]
379.118 - ------ Attributes ---------------------------------------
379.119 - types_map_inv : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
379.120 -
379.121 - =============================================
379.122 - guess_extension: FunctionDef : OffsetRange[6152,6881>
379.123 - None [free][private][read][node=Name]
379.124 - extensions [bound][private][data][read][node=Name]
379.125 - self [bound][param][private][data][read][node=Name]
379.126 - strict [bound][param][private][data][read][node=Name]
379.127 - type [bound][param][private][data][read][node=Name]
379.128 - ------ Attributes ---------------------------------------
379.129 - guess_all_extensions : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
379.130 -
379.131 - =============================================
379.132 - read: FunctionDef : OffsetRange[6882,7234>
379.133 - filename [bound][param][private][data][read][node=Name]
379.134 - fp [bound][private][data][read][node=Name]
379.135 - open [free][private][read][called][node=Name]
379.136 - self [bound][param][private][data][read][node=Name]
379.137 - strict [bound][param][private][data][read][node=Name]
379.138 - ------ Attributes ---------------------------------------
379.139 - readfp : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
379.140 -
379.141 - =============================================
379.142 - readfp: FunctionDef : OffsetRange[7235,7937>
379.143 - fp [bound][param][private][data][read][node=Name]
379.144 - i [bound][private][data][read][node=Name]
379.145 - len [free][private][read][called][node=Name]
379.146 - line [bound][private][data][read][node=Name]
379.147 - range [free][private][read][called][node=Name]
379.148 - self [bound][param][private][data][read][node=Name]
379.149 - strict [bound][param][private][data][read][node=Name]
379.150 - suff [bound][private][data][read][node=Name]
379.151 - suffixes [bound][private][data][read][node=Name]
379.152 - type [bound][private][data][read][node=Name]
379.153 - words [bound][private][data][read][node=Name]
379.154 - ------ Attributes ---------------------------------------
379.155 - add_type : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
379.156 -
379.157 - =============================================
379.158 - guess_type: FunctionDef : OffsetRange[7937,8796>
379.159 - guess_type [free][read][called][node=Name]
379.160 - init [free][read][called][node=Name]
379.161 - strict [bound][param][data][read][node=Name]
379.162 - url [bound][param][data][read][node=Name]
379.163 -
379.164 - =============================================
379.165 - guess_all_extensions: FunctionDef : OffsetRange[8796,9419>
379.166 - guess_all_extensions [free][read][called][node=Name]
379.167 - init [free][read][called][node=Name]
379.168 - strict [bound][param][data][read][node=Name]
379.169 - type [bound][param][data][read][node=Name]
379.170 -
379.171 - =============================================
379.172 - guess_extension: FunctionDef : OffsetRange[9419,10006>
379.173 - guess_extension [free][read][called][node=Name]
379.174 - init [free][read][called][node=Name]
379.175 - strict [bound][param][data][read][node=Name]
379.176 - type [bound][param][data][read][node=Name]
379.177 -
379.178 - =============================================
379.179 - add_type: FunctionDef : OffsetRange[10006,10468>
379.180 - add_type [free][read][called][node=Name]
379.181 - ext [bound][param][data][read][node=Name]
379.182 - init [free][read][called][node=Name]
379.183 - strict [bound][param][data][read][node=Name]
379.184 - type [bound][param][data][read][node=Name]
379.185 -
379.186 - =============================================
379.187 - init: FunctionDef : OffsetRange[10468,11113>
379.188 - False [free][read][node=Name]
379.189 - MimeTypes [free][read][called][node=Name]
379.190 - None [free][read][node=Name]
379.191 - True [free][read][node=Name]
379.192 - add_type [bound][func-global][data][unused][node=Global]
379.193 - common_types [bound][func-global][data][unused][node=Global]
379.194 - db [bound][data][read][node=Name]
379.195 - encodings_map [bound][func-global][data][unused][node=Global]
379.196 - file [bound][data][read][node=Name]
379.197 - files [bound][param][data][read][node=Name]
379.198 - guess_all_extensions [bound][func-global][data][unused][node=Global]
379.199 - guess_extension [bound][func-global][data][unused][node=Global]
379.200 - guess_type [bound][func-global][data][unused][node=Global]
379.201 - inited [bound][func-global][data][unused][node=Global]
379.202 - knownfiles [free][read][node=Name]
379.203 - open [free][read][called][node=Name]
379.204 - os [free][read][node=Name]
379.205 - suffix_map [bound][func-global][data][unused][node=Global]
379.206 - types_map [bound][func-global][data][unused][node=Global]
379.207 -
379.208 - =============================================
379.209 - read_mime_types: FunctionDef : OffsetRange[11113,11288>
379.210 - IOError [free][read][node=Name]
379.211 - MimeTypes [free][read][called][node=Name]
379.212 - None [free][read][node=Name]
379.213 - True [free][read][node=Name]
379.214 - db [bound][data][read][node=Name]
379.215 - f [bound][data][read][node=Name]
379.216 - file [bound][param][data][read][node=Name]
379.217 - open [free][read][called][node=Name]
379.218 -
379.219 - =============================================
379.220 - _default_mime_types: FunctionDef : OffsetRange[11288,17334>
379.221 - common_types [bound][func-global][private][data][unused][node=Global]
379.222 - encodings_map [bound][func-global][private][data][unused][node=Global]
379.223 - suffix_map [bound][func-global][private][data][unused][node=Global]
379.224 - types_map [bound][func-global][private][data][unused][node=Global]
379.225 -
379.226 - =============================================
379.227 - usage: FunctionDef : OffsetRange[17753,17851>
379.228 - USAGE [free][private][read][node=Name]
379.229 - code [bound][param][private][data][read][node=Name]
379.230 - msg [bound][param][private][data][read][node=Name]
379.231 - sys [free][private][read][node=Name]
379.232 -
380.1 --- a/python.editor/test/unit/data/testfiles/minicompat.py Sun Jan 04 13:11:53 2015 -0600
380.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
380.3 @@ -1,184 +0,0 @@
380.4 -"""Python version compatibility support for minidom."""
380.5 -
380.6 -# This module should only be imported using "import *".
380.7 -#
380.8 -# The following names are defined:
380.9 -#
380.10 -# isinstance -- version of the isinstance() function that accepts
380.11 -# tuples as the second parameter regardless of the
380.12 -# Python version
380.13 -#
380.14 -# NodeList -- lightest possible NodeList implementation
380.15 -#
380.16 -# EmptyNodeList -- lightest possible NodeList that is guarateed to
380.17 -# remain empty (immutable)
380.18 -#
380.19 -# StringTypes -- tuple of defined string types
380.20 -#
380.21 -# GetattrMagic -- base class used to make _get_<attr> be magically
380.22 -# invoked when available
380.23 -# defproperty -- function used in conjunction with GetattrMagic;
380.24 -# using these together is needed to make them work
380.25 -# as efficiently as possible in both Python 2.2+
380.26 -# and older versions. For example:
380.27 -#
380.28 -# class MyClass(GetattrMagic):
380.29 -# def _get_myattr(self):
380.30 -# return something
380.31 -#
380.32 -# defproperty(MyClass, "myattr",
380.33 -# "return some value")
380.34 -#
380.35 -# For Python 2.2 and newer, this will construct a
380.36 -# property object on the class, which avoids
380.37 -# needing to override __getattr__(). It will only
380.38 -# work for read-only attributes.
380.39 -#
380.40 -# For older versions of Python, inheriting from
380.41 -# GetattrMagic will use the traditional
380.42 -# __getattr__() hackery to achieve the same effect,
380.43 -# but less efficiently.
380.44 -#
380.45 -# defproperty() should be used for each version of
380.46 -# the relevant _get_<property>() function.
380.47 -#
380.48 -# NewStyle -- base class to cause __slots__ to be honored in
380.49 -# the new world
380.50 -#
380.51 -# True, False -- only for Python 2.2 and earlier
380.52 -
380.53 -__all__ = ["NodeList", "EmptyNodeList", "NewStyle",
380.54 - "StringTypes", "defproperty", "GetattrMagic"]
380.55 -
380.56 -import xml.dom
380.57 -
380.58 -try:
380.59 - unicode
380.60 -except NameError:
380.61 - StringTypes = type(''),
380.62 -else:
380.63 - StringTypes = type(''), type(unicode(''))
380.64 -
380.65 -
380.66 -# define True and False only if not defined as built-ins
380.67 -try:
380.68 - True
380.69 -except NameError:
380.70 - True = 1
380.71 - False = 0
380.72 - __all__.extend(["True", "False"])
380.73 -
380.74 -
380.75 -try:
380.76 - isinstance('', StringTypes)
380.77 -except TypeError:
380.78 - #
380.79 - # Wrap isinstance() to make it compatible with the version in
380.80 - # Python 2.2 and newer.
380.81 - #
380.82 - _isinstance = isinstance
380.83 - def isinstance(obj, type_or_seq):
380.84 - try:
380.85 - return _isinstance(obj, type_or_seq)
380.86 - except TypeError:
380.87 - for t in type_or_seq:
380.88 - if _isinstance(obj, t):
380.89 - return 1
380.90 - return 0
380.91 - __all__.append("isinstance")
380.92 -
380.93 -
380.94 -if list is type([]):
380.95 - class NodeList(list):
380.96 - __slots__ = ()
380.97 -
380.98 - def item(self, index):
380.99 - if 0 <= index < len(self):
380.100 - return self[index]
380.101 -
380.102 - def _get_length(self):
380.103 - return len(self)
380.104 -
380.105 - def _set_length(self, value):
380.106 - raise xml.dom.NoModificationAllowedErr(
380.107 - "attempt to modify read-only attribute 'length'")
380.108 -
380.109 - length = property(_get_length, _set_length,
380.110 - doc="The number of nodes in the NodeList.")
380.111 -
380.112 - def __getstate__(self):
380.113 - return list(self)
380.114 -
380.115 - def __setstate__(self, state):
380.116 - self[:] = state
380.117 -
380.118 - class EmptyNodeList(tuple):
380.119 - __slots__ = ()
380.120 -
380.121 - def __add__(self, other):
380.122 - NL = NodeList()
380.123 - NL.extend(other)
380.124 - return NL
380.125 -
380.126 - def __radd__(self, other):
380.127 - NL = NodeList()
380.128 - NL.extend(other)
380.129 - return NL
380.130 -
380.131 - def item(self, index):
380.132 - return None
380.133 -
380.134 - def _get_length(self):
380.135 - return 0
380.136 -
380.137 - def _set_length(self, value):
380.138 - raise xml.dom.NoModificationAllowedErr(
380.139 - "attempt to modify read-only attribute 'length'")
380.140 -
380.141 - length = property(_get_length, _set_length,
380.142 - doc="The number of nodes in the NodeList.")
380.143 -
380.144 -else:
380.145 - def NodeList():
380.146 - return []
380.147 -
380.148 - def EmptyNodeList():
380.149 - return []
380.150 -
380.151 -
380.152 -try:
380.153 - property
380.154 -except NameError:
380.155 - def defproperty(klass, name, doc):
380.156 - # taken care of by the base __getattr__()
380.157 - pass
380.158 -
380.159 - class GetattrMagic:
380.160 - def __getattr__(self, key):
380.161 - if key.startswith("_"):
380.162 - raise AttributeError, key
380.163 -
380.164 - try:
380.165 - get = getattr(self, "_get_" + key)
380.166 - except AttributeError:
380.167 - raise AttributeError, key
380.168 - return get()
380.169 -
380.170 - class NewStyle:
380.171 - pass
380.172 -
380.173 -else:
380.174 - def defproperty(klass, name, doc):
380.175 - get = getattr(klass, ("_get_" + name)).im_func
380.176 - def set(self, value, name=name):
380.177 - raise xml.dom.NoModificationAllowedErr(
380.178 - "attempt to modify read-only attribute " + repr(name))
380.179 - assert not hasattr(klass, "_set_" + name), \
380.180 - "expected not to find _set_" + name
380.181 - prop = property(get, set, doc=doc)
380.182 - setattr(klass, name, prop)
380.183 -
380.184 - class GetattrMagic:
380.185 - pass
380.186 -
380.187 - NewStyle = object
381.1 --- a/python.editor/test/unit/data/testfiles/minicompat.py.indexed Sun Jan 04 13:11:53 2015 -0600
381.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
381.3 @@ -1,37 +0,0 @@
381.4 -
381.5 -
381.6 -Document 0
381.7 -Searchable Keys:
381.8 - class : GetattrMagic
381.9 - class-ig : getattrmagic
381.10 - in : minicompat
381.11 -
381.12 -Not Searchable Keys:
381.13 -
381.14 -
381.15 -Document 1
381.16 -Searchable Keys:
381.17 - class : NewStyle
381.18 - class-ig : newstyle
381.19 - in : minicompat
381.20 -
381.21 -Not Searchable Keys:
381.22 -
381.23 -
381.24 -Document 2
381.25 -Searchable Keys:
381.26 - item : EmptyNodeList;C;;
381.27 - item : False;D;;
381.28 - item : GetattrMagic;C;;
381.29 - item : NewStyle;C;;
381.30 - item : NodeList;C;;
381.31 - item : StringTypes;D;;
381.32 - item : True;D;;
381.33 - item : __all__;D;;
381.34 - item : _isinstance;D;|PRIVATE|;
381.35 - item : defproperty;F;;klass,name,doc;
381.36 - item : isinstance;F;;obj,type_or_seq;
381.37 - item : xml;I;|PRIVATE|;
381.38 - module : minicompat
381.39 -
381.40 -Not Searchable Keys:
382.1 --- a/python.editor/test/unit/data/testfiles/modifiers.py Sun Jan 04 13:11:53 2015 -0600
382.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
382.3 @@ -1,12 +0,0 @@
382.4 -class ParsingError(Error):
382.5 - """Raised when a configuration file does not follow legal syntax."""
382.6 -
382.7 - def __init__(self, filename):
382.8 - Error.__init__(self, 'File contains parsing errors: %s' % filename)
382.9 - self.filename = filename
382.10 - self.errors = []
382.11 -
382.12 - def __i_am_private(self, lineno, line):
382.13 - self.errors.append((lineno, line))
382.14 - self.message += '\n\t[line %2d]: %s' % (lineno, line)
382.15 -
383.1 --- a/python.editor/test/unit/data/testfiles/modifiers.py.structure Sun Jan 04 13:11:53 2015 -0600
383.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
383.3 @@ -1,5 +0,0 @@
383.4 -ParsingError:CLASS:[]:ESCAPED{ParsingError}:
383.5 - __i_am_private:METHOD:[PRIVATE]:ESCAPED{__i_am_private}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{lineno}ESCAPED{,}ESCAPED{line}}):
383.6 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{filename}}):
383.7 - errors:ATTRIBUTE:[]:ESCAPED{errors}:
383.8 - filename:ATTRIBUTE:[]:ESCAPED{filename}:
384.1 --- a/python.editor/test/unit/data/testfiles/names.py Sun Jan 04 13:11:53 2015 -0600
384.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
384.3 @@ -1,615 +0,0 @@
384.4 -"""Configuration file parser.
384.5 -
384.6 -A setup file consists of sections, lead by a "[section]" header,
384.7 -and followed by "name: value" entries, with continuations and such in
384.8 -the style of RFC 822.
384.9 -
384.10 - the same section, or values in a special [DEFAULT] section.
384.11 -
384.12 -For example:
384.13 -
384.14 - something: %(dir)s/whatever
384.15 -
384.16 -would resolve the "%(dir)s" to the value of dir. All reference
384.17 -expansions are done late, on demand.
384.18 -
384.19 -Intrinsic defaults can be specified by passing them into the
384.20 -ConfigParser constructor as a dictionary.
384.21 -
384.22 -class:
384.23 -
384.24 -ConfigParser -- responsible for parsing a list of
384.25 - configuration files, and managing the parsed database.
384.26 -
384.27 - methods:
384.28 -
384.29 - __init__(defaults=None)
384.30 - create the parser and specify a dictionary of intrinsic defaults. The
384.31 - keys must be strings, the values must be appropriate for %()s string
384.32 - interpolation. Note that `__name__' is always an intrinsic default;
384.33 - it's value is the section's name.
384.34 -
384.35 - sections()
384.36 - return all the configuration section names, sans DEFAULT
384.37 -
384.38 - has_section(section)
384.39 - return whether the given section exists
384.40 -
384.41 - has_option(section, option)
384.42 - return whether the given option exists in the given section
384.43 -
384.44 - options(section)
384.45 - return list of configuration options for the named section
384.46 -
384.47 - read(filenames)
384.48 - read and parse the list of named configuration files, given by
384.49 - name. A single filename is also allowed. Non-existing files
384.50 - are ignored.
384.51 -
384.52 - readfp(fp, filename=None)
384.53 - read and parse one configuration file, given as a file object.
384.54 - The filename defaults to fp.name; it is only used in error
384.55 - messages (if fp has no `name' attribute, the string `<???>' is used).
384.56 -
384.57 - get(section, option, raw=False, vars=None)
384.58 - return a string value for the named option. All % interpolations are
384.59 - expanded in the return values, based on the defaults passed into the
384.60 - constructor and the DEFAULT section. Additional substitutions may be
384.61 - provided using the `vars' argument, which must be a dictionary whose
384.62 - contents override any pre-existing defaults.
384.63 -
384.64 - getint(section, options)
384.65 - like get(), but convert value to an integer
384.66 -
384.67 - getfloat(section, options)
384.68 - like get(), but convert value to a float
384.69 -
384.70 - getboolean(section, options)
384.71 - like get(), but convert value to a boolean (currently case
384.72 - insensitively defined as 0, false, no, off for False, and 1, true,
384.73 - yes, on for True). Returns False or True.
384.74 -
384.75 - items(section, raw=False, vars=None)
384.76 - return a list of tuples with (name, value) for each option
384.77 - in the section.
384.78 -
384.79 - remove_section(section)
384.80 - remove the given file section and all its options
384.81 -
384.82 - remove_option(section, option)
384.83 - remove the given option from the given section
384.84 -
384.85 - set(section, option, value)
384.86 - set the given option
384.87 -
384.88 - write(fp)
384.89 - write the configuration state in .ini format
384.90 -"""
384.91 -
384.92 -import re
384.93 -
384.94 -__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
384.95 - "InterpolationError", "InterpolationDepthError",
384.96 - "InterpolationSyntaxError", "ParsingError",
384.97 - "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser",
384.98 - "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
384.99 -
384.100 -DEFAULTSECT = "DEFAULT"
384.101 -
384.102 -MAX_INTERPOLATION_DEPTH = 10
384.103 -
384.104 -
384.105 -
384.106 -# exception classes
384.107 -class Error(Exception):
384.108 - """Base class for ConfigParser exceptions."""
384.109 -
384.110 - def __init__(self, msg=''):
384.111 - self.message = msg
384.112 - Exception.__init__(self, msg)
384.113 -
384.114 - def __repr__(self):
384.115 - return self.message
384.116 -
384.117 - __str__ = __repr__
384.118 -
384.119 -class NoSectionError(Error):
384.120 - """Rasssised when no section matches a requested option."""
384.121 -
384.122 - def __init__(self, section):
384.123 - Error.__init__(self, 'No section: ' + `section`)
384.124 - self.section = section
384.125 -
384.126 -class duplicateSectionError(Error):
384.127 - """Raised when a section is multiply-created."""
384.128 -
384.129 - def __Init__(self, section):
384.130 - Error.__init__(self, "Section %r already exists" % section)
384.131 - self.section = section
384.132 -
384.133 -class _noOptionError(Error):
384.134 - """A requested option was not found."""
384.135 -
384.136 - def __init__(self, option, section):
384.137 - Error.__init__(self, "No option %r in section: %r" %
384.138 - (option, section))
384.139 - self.option = option
384.140 - self.section = section
384.141 -
384.142 -class _interpolationError(Error):
384.143 - """Base class for interpolation-related exceptions."""
384.144 -
384.145 - def __init__(self, option, section, msg):
384.146 - Error.__init__(self, msg)
384.147 - self.option = option
384.148 - self.section = section
384.149 -
384.150 -class InterpolationMissingOptionError(InterpolationError):
384.151 - """A string substitution required a setting which was not available."""
384.152 -
384.153 - def __init__(self, option, section, rawval, reference):
384.154 - msg = ("Bad value substitution:\n"
384.155 - "\tsection: [%s]\n"
384.156 - "\toption : %s\n"
384.157 - "\tkey : %s\n"
384.158 - "\trawval : %s\n"
384.159 - % (section, option, reference, rawval))
384.160 - InterpolationError.__init__(self, option, section, msg)
384.161 - self.reference = reference
384.162 -
384.163 -class InterpolationSyntaxError(InterpolationError):
384.164 - """Raised when the source text into which substitutions are made
384.165 - does not conform to the required syntax."""
384.166 -
384.167 -class InterpolationDepthError(InterpolationError):
384.168 - """Raised when substitutions are nested too deeply."""
384.169 -
384.170 - def __init__(self, option, section, rawval):
384.171 - msg = ("Value interpolation too deeply recursive:\n"
384.172 - "\tsection: [%s]\n"
384.173 - "\toption : %s\n"
384.174 - "\trawval : %s\n"
384.175 - % (section, option, rawval))
384.176 - InterpolationError.__init__(self, option, section, msg)
384.177 -
384.178 -class ParsingError(Error):
384.179 - """Raised when a configuration file does not follow legal syntax."""
384.180 -
384.181 - def __init__(self, filename):
384.182 - Error.__init__(self, 'File contains parsing errors: %s' % filename)
384.183 - self.filename = filename
384.184 - self.errors = []
384.185 -
384.186 - def append(self, lineno, line):
384.187 - self.errors.append((lineno, line))
384.188 - self.message += '\n\t[line %2d]: %s' % (lineno, line)
384.189 -
384.190 -class MissingSectionHeaderError(ParsingError):
384.191 - """Raised when a key-value pair is found before any section header."""
384.192 -
384.193 - def __init__(self, filename, lineno, line):
384.194 - Error.__init__(
384.195 - self,
384.196 - 'File contains no section headers.\nfile: %s, line: %d\n%s' %
384.197 - (filename, lineno, line))
384.198 - self.filename = filename
384.199 - self.lineno = lineno
384.200 - self.line = line
384.201 -
384.202 -
384.203 -
384.204 -class RawConfigParser:
384.205 - def __init__(self, defaults=None):
384.206 - self._sections = {}
384.207 - if defaults is None:
384.208 - self._defaults = {}
384.209 - else:
384.210 - self._defaults = defaults
384.211 -
384.212 - def Defaults(self):
384.213 - return self._defaults
384.214 -
384.215 - def _Sections(self):
384.216 - """Return a list of section names, excluding [DEFAULT]"""
384.217 - # self._sections will never have [DEFAULT] in it
384.218 - return self._sections.keys()
384.219 -
384.220 - def add_section(self, section):
384.221 - """Create a new section in the configuration.
384.222 -
384.223 - Raise DuplicateSectionError if a section by the specified name
384.224 - already exists.
384.225 - """
384.226 - if section in self._sections:
384.227 - raise DuplicateSectionError(section)
384.228 - self._sections[section] = {}
384.229 -
384.230 - def has_section(self, section):
384.231 - """Indicate whether the named section is present in the configuration.
384.232 -
384.233 - The DEFAULT section is not acknowledged.
384.234 - """
384.235 - return section in self._sections
384.236 -
384.237 - def options(self, section):
384.238 - """Return a list of option names for the given section name."""
384.239 - try:
384.240 - opts = self._sections[section].copy()
384.241 - except KeyError:
384.242 - raise NoSectionError(section)
384.243 - opts.update(self._defaults)
384.244 - if '__name__' in opts:
384.245 - del opts['__name__']
384.246 - return opts.keys()
384.247 -
384.248 - def read(self, filenames):
384.249 - """Read and parse a filename or a list of filenames.
384.250 -
384.251 - Files that cannot be opened are silently ignored; this is
384.252 - designed so that you can specify a list of potential
384.253 - configuration file locations (e.g. current directory, user's
384.254 - home directory, systemwide directory), and all existing
384.255 - configuration files in the list will be read. A single
384.256 - filename may also be given.
384.257 - """
384.258 - if isinstance(filenames, basestring):
384.259 - filenames = [filenames]
384.260 - for filename in filenames:
384.261 - try:
384.262 - fp = open(filename)
384.263 - except IOError:
384.264 - continue
384.265 - self._read(fp, filename)
384.266 - fp.close()
384.267 -
384.268 - def readfp(self, fp, filename=None):
384.269 - """Like read() but the argument must be a file-like object.
384.270 -
384.271 - The `fp' argument must have a `readline' method. Optional
384.272 - second argument is the `filename', which if not given, is
384.273 - taken from fp.name. If fp has no `name' attribute, `<???>' is
384.274 - used.
384.275 -
384.276 - """
384.277 - if filename is None:
384.278 - try:
384.279 - filename = fp.name
384.280 - except AttributeError:
384.281 - filename = '<???>'
384.282 - self._read(fp, filename)
384.283 -
384.284 - def get(self, section, option):
384.285 - opt = self.optionxform(option)
384.286 - if section not in self._sections:
384.287 - if section != DEFAULTSECT:
384.288 - raise NoSectionError(section)
384.289 - if opt in self._defaults:
384.290 - return self._defaults[opt]
384.291 - else:
384.292 - raise NoOptionError(option, section)
384.293 - elif opt in self._sections[section]:
384.294 - return self._sections[section][opt]
384.295 - elif opt in self._defaults:
384.296 - return self._defaults[opt]
384.297 - else:
384.298 - raise NoOptionError(option, section)
384.299 -
384.300 - def items(self, section):
384.301 - try:
384.302 - d2 = self._sections[section]
384.303 - except KeyError:
384.304 - if section != DEFAULTSECT:
384.305 - raise NoSectionError(section)
384.306 - d2 = {}
384.307 - d = self._defaults.copy()
384.308 - d.update(d2)
384.309 - if "__name__" in d:
384.310 - del d["__name__"]
384.311 - return d.items()
384.312 -
384.313 - def _get(self, section, conv, option):
384.314 - return conv(self.get(section, option))
384.315 -
384.316 - def getint(self, section, option):
384.317 - return self._get(section, int, option)
384.318 -
384.319 - def getfloat(self, section, option):
384.320 - return self._get(section, float, option)
384.321 -
384.322 - _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
384.323 - '0': False, 'no': False, 'false': False, 'off': False}
384.324 -
384.325 - def getboolean(self, section, option):
384.326 - v = self.get(section, option)
384.327 - if v.lower() not in self._boolean_states:
384.328 - raise ValueError, 'Not a boolean: %s' % v
384.329 - return self._boolean_states[v.lower()]
384.330 -
384.331 - def optionxform(self, optionstr):
384.332 - return optionstr.lower()
384.333 -
384.334 - def has_option(self, section, option):
384.335 - """Check for the existence of a given option in a given section."""
384.336 - if not section or section == DEFAULTSECT:
384.337 - option = self.optionxform(option)
384.338 - return option in self._defaults
384.339 - elif section not in self._sections:
384.340 - return False
384.341 - else:
384.342 - option = self.optionxform(option)
384.343 - return (option in self._sections[section]
384.344 - or option in self._defaults)
384.345 -
384.346 - def set(self, section, option, value):
384.347 - """Set an option."""
384.348 - if not section or section == DEFAULTSECT:
384.349 - sectdict = self._defaults
384.350 - else:
384.351 - try:
384.352 - sectdict = self._sections[section]
384.353 - except KeyError:
384.354 - raise NoSectionError(section)
384.355 - sectdict[self.optionxform(option)] = value
384.356 -
384.357 - def write(self, fp):
384.358 - """Write an .ini-format representation of the configuration state."""
384.359 - if self._defaults:
384.360 - fp.write("[%s]\n" % DEFAULTSECT)
384.361 - for (key, value) in self._defaults.items():
384.362 - fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
384.363 - fp.write("\n")
384.364 - for section in self._sections:
384.365 - fp.write("[%s]\n" % section)
384.366 - for (key, value) in self._sections[section].items():
384.367 - if key != "__name__":
384.368 - fp.write("%s = %s\n" %
384.369 - (key, str(value).replace('\n', '\n\t')))
384.370 - fp.write("\n")
384.371 -
384.372 - def remove_option(self, section, option):
384.373 - """Remove an option."""
384.374 - if not section or section == DEFAULTSECT:
384.375 - sectdict = self._defaults
384.376 - else:
384.377 - try:
384.378 - sectdict = self._sections[section]
384.379 - except KeyError:
384.380 - raise NoSectionError(section)
384.381 - option = self.optionxform(option)
384.382 - existed = option in sectdict
384.383 - if existed:
384.384 - del sectdict[option]
384.385 - return existed
384.386 -
384.387 - def remove_section(self, section):
384.388 - """Remove a file section."""
384.389 - existed = section in self._sections
384.390 - if existed:
384.391 - del self._sections[section]
384.392 - return existed
384.393 -
384.394 - #
384.395 - # Regular expressions for parsing section headers and options.
384.396 - #
384.397 - SECTCRE = re.compile(
384.398 - r'\[' # [
384.399 - r'(?P<header>[^]]+)' # very permissive!
384.400 - r'\]' # ]
384.401 - )
384.402 - OPTCRE = re.compile(
384.403 - r'(?P<option>[^:=\s][^:=]*)' # very permissive!
384.404 - r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
384.405 - # followed by separator
384.406 - # (either : or =), followed
384.407 - # by any # space/tab
384.408 - r'(?P<value>.*)$' # everything up to eol
384.409 - )
384.410 -
384.411 - def _read(self, fp, fpname):
384.412 - """Parse a sectioned setup file.
384.413 -
384.414 - The sections in setup file contains a title line at the top,
384.415 - indicated by a name in square brackets (`[]'), plus key/value
384.416 - options lines, indicated by `name: value' format lines.
384.417 - Continuations are represented by an embedded newline then
384.418 - leading whitespace. Blank lines, lines beginning with a '#',
384.419 - and just about everything else are ignored.
384.420 - """
384.421 - cursect = None # None, or a dictionary
384.422 - optname = None
384.423 - lineno = 0
384.424 - e = None # None, or an exception
384.425 - while True:
384.426 - line = fp.readline()
384.427 - if not line:
384.428 - break
384.429 - lineno = lineno + 1
384.430 - # comment or blank line?
384.431 - if line.strip() == '' or line[0] in '#;':
384.432 - continue
384.433 - if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
384.434 - # no leading whitespace
384.435 - continue
384.436 - # continuation line?
384.437 - if line[0].isspace() and cursect is not None and optname:
384.438 - value = line.strip()
384.439 - if value:
384.440 - cursect[optname] = "%s\n%s" % (cursect[optname], value)
384.441 - # a section header or option header?
384.442 - else:
384.443 - # is it a section header?
384.444 - mo = self.SECTCRE.match(line)
384.445 - if mo:
384.446 - sectname = mo.group('header')
384.447 - if sectname in self._sections:
384.448 - cursect = self._sections[sectname]
384.449 - elif sectname == DEFAULTSECT:
384.450 - cursect = self._defaults
384.451 - else:
384.452 - cursect = {'__name__': sectname}
384.453 - self._sections[sectname] = cursect
384.454 - # So sections can't start with a continuation line
384.455 - optname = None
384.456 - # no section header in the file?
384.457 - elif cursect is None:
384.458 - raise MissingSectionHeaderError(fpname, lineno, `line`)
384.459 - # an option line?
384.460 - else:
384.461 - mo = self.OPTCRE.match(line)
384.462 - if mo:
384.463 - optname, vi, optval = mo.group('option', 'vi', 'value')
384.464 - if vi in ('=', ':') and ';' in optval:
384.465 - # ';' is a comment delimiter only if it follows
384.466 - # a spacing character
384.467 - pos = optval.find(';')
384.468 - if pos != -1 and optval[pos-1].isspace():
384.469 - optval = optval[:pos]
384.470 - optval = optval.strip()
384.471 - # allow empty values
384.472 - if optval == '""':
384.473 - optval = ''
384.474 - optname = self.optionxform(optname.rstrip())
384.475 - cursect[optname] = optval
384.476 - else:
384.477 - # a non-fatal parsing error occurred. set up the
384.478 - # exception but keep going. the exception will be
384.479 - # raised at the end of the file and will contain a
384.480 - # list of all bogus lines
384.481 - if not e:
384.482 - e = ParsingError(fpname)
384.483 - e.append(lineno, `line`)
384.484 - # if any parsing errors occurred, raise an exception
384.485 - if e:
384.486 - raise e
384.487 -
384.488 -
384.489 -class ConfigParser(RawConfigParser):
384.490 -
384.491 - def get(self, section, option, raw=False, vars=None):
384.492 - """Get an option value for a given section.
384.493 -
384.494 - All % interpolations are expanded in the return values, based on the
384.495 - defaults passed into the constructor, unless the optional argument
384.496 - `raw' is true. Additional substitutions may be provided using the
384.497 - `vars' argument, which must be a dictionary whose contents overrides
384.498 - any pre-existing defaults.
384.499 -
384.500 - The section DEFAULT is special.
384.501 - """
384.502 - d = self._defaults.copy()
384.503 - try:
384.504 - d.update(self._sections[section])
384.505 - except KeyError:
384.506 - if section != DEFAULTSECT:
384.507 - raise NoSectionError(section)
384.508 - # Update with the entry specific variables
384.509 - if vars is not None:
384.510 - d.update(vars)
384.511 - option = self.optionxform(option)
384.512 - try:
384.513 - value = d[option]
384.514 - except KeyError:
384.515 - raise NoOptionError(option, section)
384.516 -
384.517 - if raw:
384.518 - return value
384.519 - else:
384.520 - return self._interpolate(section, option, value, d)
384.521 -
384.522 - def items(self, section, raw=False, vars=None):
384.523 - """Return a list of tuples with (name, value) for each option
384.524 - in the section.
384.525 -
384.526 - All % interpolations are expanded in the return values, based on the
384.527 - defaults passed into the constructor, unless the optional argument
384.528 - `raw' is true. Additional substitutions may be provided using the
384.529 - `vars' argument, which must be a dictionary whose contents overrides
384.530 - any pre-existing defaults.
384.531 -
384.532 - The section DEFAULT is special.
384.533 - """
384.534 - d = self._defaults.copy()
384.535 - try:
384.536 - d.update(self._sections[section])
384.537 - except KeyError:
384.538 - if section != DEFAULTSECT:
384.539 - raise NoSectionError(section)
384.540 - # Update with the entry specific variables
384.541 - if vars:
384.542 - d.update(vars)
384.543 - options = d.keys()
384.544 - if "__name__" in options:
384.545 - options.remove("__name__")
384.546 - if raw:
384.547 - return [(option, d[option])
384.548 - for option in options]
384.549 - else:
384.550 - return [(option, self._interpolate(section, option, d[option], d))
384.551 - for option in options]
384.552 -
384.553 - def _interpolate(self, section, option, rawval, vars):
384.554 - # do the string interpolation
384.555 - value = rawval
384.556 - depth = MAX_INTERPOLATION_DEPTH
384.557 - while depth: # Loop through this until it's done
384.558 - depth -= 1
384.559 - if value.find("%(") != -1:
384.560 - try:
384.561 - value = value % vars
384.562 - except KeyError, e:
384.563 - raise InterpolationMissingOptionError(
384.564 - option, section, rawval, e[0])
384.565 - else:
384.566 - break
384.567 - if value.find("%(") != -1:
384.568 - raise InterpolationDepthError(option, section, rawval)
384.569 - return value
384.570 -
384.571 -
384.572 -class SafeConfigParser(ConfigParser):
384.573 -
384.574 - def _interpolate(self, section, option, rawval, vars):
384.575 - # do the string interpolation
384.576 - L = []
384.577 - self._interpolate_some(option, L, rawval, section, vars, 1)
384.578 - return ''.join(L)
384.579 -
384.580 - _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
384.581 -
384.582 - def _interpolate_some(self, option, accum, rest, section, map, depth):
384.583 - if depth > MAX_INTERPOLATION_DEPTH:
384.584 - raise InterpolationDepthError(option, section, rest)
384.585 - while rest:
384.586 - p = rest.find("%")
384.587 - if p < 0:
384.588 - accum.append(rest)
384.589 - return
384.590 - if p > 0:
384.591 - accum.append(rest[:p])
384.592 - rest = rest[p:]
384.593 - # p is no longer used
384.594 - c = rest[1:2]
384.595 - if c == "%":
384.596 - accum.append("%")
384.597 - rest = rest[2:]
384.598 - elif c == "(":
384.599 - m = self._interpvar_match(rest)
384.600 - if m is None:
384.601 - raise InterpolationSyntaxError(option, section,
384.602 - "bad interpolation variable reference %r" % rest)
384.603 - var = m.group(1)
384.604 - rest = rest[m.end():]
384.605 - try:
384.606 - v = map[var]
384.607 - except KeyError:
384.608 - raise InterpolationMissingOptionError(
384.609 - option, section, rest, var)
384.610 - if "%" in v:
384.611 - self._interpolate_some(option, accum, v,
384.612 - section, map, depth + 1)
384.613 - else:
384.614 - accum.append(v)
384.615 - else:
384.616 - raise InterpolationSyntaxError(
384.617 - option, section,
384.618 - "'%' must be followed by '%' or '(', found: " + `ret`)
385.1 --- a/python.editor/test/unit/data/testfiles/names.py.testHint2.hints Sun Jan 04 13:11:53 2015 -0600
385.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
385.3 @@ -1,39 +0,0 @@
385.4 -class duplicateSectionError(Error):
385.5 - ---------------------
385.6 -HINT:Name "duplicateSectionError" is not a valid class name according to your code style (CapitalizedWords)
385.7 -FIX:Ignore name violations for "duplicateSectionError"
385.8 -FIX:Change preferred class name style to mixedCase
385.9 -FIX:Turn off class name style checks
385.10 - def __Init__(self, section):
385.11 - --------
385.12 -HINT:Name "__Init__" is not a valid function name according to your code style (lowercase_with_underscores)
385.13 -FIX:Ignore name violations for "__Init__"
385.14 -FIX:Change preferred function name style to CapitalizedWords
385.15 -FIX:Change preferred function name style to Capitalized_With_Underscores
385.16 -FIX:Turn off function name style checks
385.17 -class _noOptionError(Error):
385.18 - --------------
385.19 -HINT:Name "_noOptionError" is not a valid class name according to your code style (CapitalizedWords)
385.20 -FIX:Ignore name violations for "_noOptionError"
385.21 -FIX:Change preferred class name style to mixedCase
385.22 -FIX:Turn off class name style checks
385.23 -class _interpolationError(Error):
385.24 - -------------------
385.25 -HINT:Name "_interpolationError" is not a valid class name according to your code style (CapitalizedWords)
385.26 -FIX:Ignore name violations for "_interpolationError"
385.27 -FIX:Change preferred class name style to mixedCase
385.28 -FIX:Turn off class name style checks
385.29 - def Defaults(self):
385.30 - --------
385.31 -HINT:Name "Defaults" is not a valid function name according to your code style (lowercase_with_underscores)
385.32 -FIX:Ignore name violations for "Defaults"
385.33 -FIX:Change preferred function name style to CapitalizedWords
385.34 -FIX:Change preferred function name style to Capitalized_With_Underscores
385.35 -FIX:Turn off function name style checks
385.36 - def _Sections(self):
385.37 - ---------
385.38 -HINT:Name "_Sections" is not a valid function name according to your code style (lowercase_with_underscores)
385.39 -FIX:Ignore name violations for "_Sections"
385.40 -FIX:Change preferred function name style to CapitalizedWords
385.41 -FIX:Change preferred function name style to Capitalized_With_Underscores
385.42 -FIX:Turn off function name style checks
386.1 --- a/python.editor/test/unit/data/testfiles/names2.py Sun Jan 04 13:11:53 2015 -0600
386.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
386.3 @@ -1,31 +0,0 @@
386.4 -class A:
386.5 - def foo():
386.6 - self.filename = filename
386.7 -
386.8 -def toplevel(x,y,z):
386.9 - print "hello"
386.10 -
386.11 -def toplevel2():
386.12 - print "hello"
386.13 -
386.14 -class Bar:
386.15 - def noargs():
386.16 - print "hello"
386.17 -
386.18 - def okay1(self):
386.19 - print "hello"
386.20 -
386.21 - def okay2(cls):
386.22 - print "hello"
386.23 -
386.24 - def okay3(self, bar):
386.25 - print "hello"
386.26 -
386.27 - def okay4(cls, bar):
386.28 - print "hello"
386.29 -
386.30 - def bad1():
386.31 - print "hello"
386.32 -
386.33 - def bad2(filename):
386.34 - print "hello"
387.1 --- a/python.editor/test/unit/data/testfiles/names2.py.testFix1.fixed Sun Jan 04 13:11:53 2015 -0600
387.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
387.3 @@ -1,31 +0,0 @@
387.4 -class A:
387.5 - def foo():
387.6 - self.filename = filename
387.7 -
387.8 -def toplevel(x,y,z):
387.9 - print "hello"
387.10 -
387.11 -def toplevel2():
387.12 - print "hello"
387.13 -
387.14 -class Bar:
387.15 - def noargs(self):
387.16 - print "hello"
387.17 -
387.18 - def okay1(self):
387.19 - print "hello"
387.20 -
387.21 - def okay2(cls):
387.22 - print "hello"
387.23 -
387.24 - def okay3(self, bar):
387.25 - print "hello"
387.26 -
387.27 - def okay4(cls, bar):
387.28 - print "hello"
387.29 -
387.30 - def bad1():
387.31 - print "hello"
387.32 -
387.33 - def bad2(filename):
387.34 - print "hello"
388.1 --- a/python.editor/test/unit/data/testfiles/names2.py.testFix2.fixed Sun Jan 04 13:11:53 2015 -0600
388.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
388.3 @@ -1,31 +0,0 @@
388.4 -class A:
388.5 - def foo():
388.6 - self.filename = filename
388.7 -
388.8 -def toplevel(x,y,z):
388.9 - print "hello"
388.10 -
388.11 -def toplevel2():
388.12 - print "hello"
388.13 -
388.14 -class Bar:
388.15 - def noargs():
388.16 - print "hello"
388.17 -
388.18 - def okay1(self):
388.19 - print "hello"
388.20 -
388.21 - def okay2(cls):
388.22 - print "hello"
388.23 -
388.24 - def okay3(self, bar):
388.25 - print "hello"
388.26 -
388.27 - def okay4(cls, bar):
388.28 - print "hello"
388.29 -
388.30 - def bad1():
388.31 - print "hello"
388.32 -
388.33 - def bad2(self):
388.34 - print "hello"
389.1 --- a/python.editor/test/unit/data/testfiles/names2.py.testHint3.hints Sun Jan 04 13:11:53 2015 -0600
389.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
389.3 @@ -1,17 +0,0 @@
389.4 - def foo():
389.5 - -
389.6 -HINT:First argument should be 'self' or 'cls'
389.7 -FIX:Insert a new first parameter "self"
389.8 - def noargs():
389.9 - -
389.10 -HINT:First argument should be 'self' or 'cls'
389.11 -FIX:Insert a new first parameter "self"
389.12 - def bad1():
389.13 - -
389.14 -HINT:First argument should be 'self' or 'cls'
389.15 -FIX:Insert a new first parameter "self"
389.16 - def bad2(filename):
389.17 - --------
389.18 -HINT:First argument (filename) should be self or cls
389.19 -FIX:Insert a new first parameter "self"
389.20 -FIX:Rename first parameter "filename" to self
390.1 --- a/python.editor/test/unit/data/testfiles/occurrences1.py Sun Jan 04 13:11:53 2015 -0600
390.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
390.3 @@ -1,6 +0,0 @@
390.4 -__builtin__.repr(x)
390.5 -x.repr(x)
390.6 -
390.7 -def repr(self)
390.8 - print "Test"
390.9 -
391.1 --- a/python.editor/test/unit/data/testfiles/occurrences1.py.test150581b.occurrences Sun Jan 04 13:11:53 2015 -0600
391.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
391.3 @@ -1,1 +0,0 @@
391.4 -__builtin__.|>MARK_OCCURRENCES:re^pr<|(x)
392.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py Sun Jan 04 13:11:53 2015 -0600
392.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
392.3 @@ -1,43 +0,0 @@
392.4 -import module1
392.5 -import module2
392.6 -import module3 as module4
392.7 -
392.8 -toplevelvar = 1
392.9 -toplevelvar2 = 2
392.10 -toplevelvar3 = 3
392.11 -toplevelvar4 = 4
392.12 -
392.13 -def myfunc(funcparam):
392.14 - localvar = 1
392.15 - toplevelvar4 = 6
392.16 - print toplevelvar4
392.17 - x = myfunc
392.18 - myfunc(5)
392.19 - x()
392.20 - pass
392.21 -
392.22 -class MyClass(SuperClass):
392.23 - var_in_class = 1
392.24 - def mymethod(self,param1,param2):
392.25 - in_method = 1
392.26 - in_method = 2
392.27 - print in_method
392.28 - print var_in_class
392.29 - print toplevelvar
392.30 - print toplevelvar2
392.31 - module1.x
392.32 - print param2
392.33 - module4.y
392.34 - toplevelvar3 = 3
392.35 - def myfunc():
392.36 - in_func = 1
392.37 - print in_method
392.38 - print in_func
392.39 - in_method = 2
392.40 - del toplevelvar2
392.41 - print toplevelvar2
392.42 - print toplevelvar3
392.43 - print toplevelvar4
392.44 -
392.45 - def othermethod(self,param3):
392.46 - pass
393.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testLocals3.completion Sun Jan 04 13:11:53 2015 -0600
393.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
393.3 @@ -1,7 +0,0 @@
393.4 -Code completion result for source line:
393.5 -tople|velvar = 1
393.6 -(QueryType=COMPLETION, NameKind=PREFIX)
393.7 -VARIABLE toplevelvar
393.8 -VARIABLE toplevelvar2
393.9 -VARIABLE toplevelvar3
393.10 -VARIABLE toplevelvar4
394.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testLocals4.completion Sun Jan 04 13:11:53 2015 -0600
394.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
394.3 @@ -1,1234 +0,0 @@
394.4 -Code completion result for source line:
394.5 -print |toplevelvar2
394.6 -(QueryType=COMPLETION, NameKind=PREFIX)
394.7 -MODULE module1
394.8 -MODULE module2
394.9 -MODULE module4
394.10 -CLASS MyClass
394.11 -METHOD myfunc()
394.12 -VARIABLE in_method
394.13 -VARIABLE param1
394.14 -VARIABLE param2
394.15 -VARIABLE self
394.16 -VARIABLE toplevelvar
394.17 -VARIABLE toplevelvar2
394.18 -VARIABLE toplevelvar3
394.19 -VARIABLE toplevelvar4
394.20 -------------------------------------
394.21 -CLASS A
394.22 -CLASS ABCMeta
394.23 -CLASS AEServer
394.24 -CLASS AEText
394.25 -CLASS ASTVisitor
394.26 -CLASS AbstractBasicAuthHandler
394.27 -CLASS AbstractClassCode
394.28 -CLASS AbstractCompileMode
394.29 -CLASS AbstractDigestAuthHandler
394.30 -CLASS AbstractFormatter
394.31 -CLASS AbstractFunctionCode
394.32 -CLASS AbstractHTTPHandler
394.33 -CLASS AbstractWriter
394.34 -CLASS Add
394.35 -CLASS And
394.36 -CLASS Application
394.37 -CLASS ArgumentError
394.38 -CLASS ArithmeticError
394.39 -CLASS ArithmeticError
394.40 -CLASS Array
394.41 -CLASS ArrayInstance
394.42 -CLASS AssAttr
394.43 -CLASS AssList
394.44 -CLASS AssName
394.45 -CLASS AssTuple
394.46 -CLASS Assert
394.47 -CLASS AssertionError
394.48 -CLASS AssertionError
394.49 -CLASS Assign
394.50 -CLASS AsyncResult
394.51 -CLASS Attr
394.52 -CLASS AttributeError
394.53 -CLASS AttributeError
394.54 -CLASS AttributeList
394.55 -CLASS AttributeMap
394.56 -CLASS Attributes
394.57 -CLASS AttributesImpl
394.58 -CLASS AttributesNS
394.59 -CLASS AttributesNSImpl
394.60 -CLASS AugAssign
394.61 -CLASS AugGetattr
394.62 -CLASS AugName
394.63 -CLASS AugSlice
394.64 -CLASS AugSubscript
394.65 -CLASS AuthenticationError
394.66 -CLASS AutoGILError
394.67 -CLASS B
394.68 -CLASS BCPPCompiler
394.69 -CLASS BCPTestCase
394.70 -CLASS BZ2Compressor
394.71 -CLASS BZ2Decompressor
394.72 -CLASS BZ2File
394.73 -CLASS Babyl
394.74 -CLASS BabylMailbox
394.75 -CLASS BabylMessage
394.76 -CLASS Backquote
394.77 -CLASS BadBoundaryPointsErr
394.78 -CLASS BadFutureParser
394.79 -CLASS BadOptionError
394.80 -CLASS BadStatusLine
394.81 -CLASS BadZipfile
394.82 -CLASS Balloon
394.83 -CLASS Bar
394.84 -CLASS BaseCGIHandler
394.85 -CLASS BaseCookie
394.86 -CLASS BaseException
394.87 -CLASS BaseException
394.88 -CLASS BaseHTTPRequestHandler
394.89 -CLASS BaseHandler
394.90 -CLASS BaseIncrementalParser
394.91 -CLASS BaseManager
394.92 -CLASS BaseProxy
394.93 -CLASS BaseRequestHandler
394.94 -CLASS BaseRotatingHandler
394.95 -CLASS BaseSet
394.96 -CLASS BasicModuleImporter
394.97 -CLASS BasicModuleLoader
394.98 -CLASS BastionClass
394.99 -CLASS Baz
394.100 -CLASS Bdb
394.101 -CLASS BdbQuit
394.102 -CLASS BigEndianStructure
394.103 -CLASS Binary
394.104 -CLASS Bitand
394.105 -CLASS Bitor
394.106 -CLASS Bitxor
394.107 -CLASS Block
394.108 -CLASS BlockFinder
394.109 -CLASS BlockingIOError
394.110 -CLASS Boolean
394.111 -CLASS BoundaryError
394.112 -CLASS BoundedSemaphore
394.113 -CLASS Break
394.114 -CLASS Breakpoint
394.115 -CLASS BsdDbShelf
394.116 -CLASS BufferTooShort
394.117 -CLASS BufferedIOBase
394.118 -CLASS BufferedRWPair
394.119 -CLASS BufferedRandom
394.120 -CLASS BufferedReader
394.121 -CLASS BufferedWriter
394.122 -CLASS BufferingFormatter
394.123 -CLASS BufferingHandler
394.124 -CLASS BuildPyTestCase
394.125 -CLASS BuildScriptsTestCase
394.126 -CLASS BuiltinImporter
394.127 -CLASS Bulkcopy
394.128 -CLASS ButtonBox
394.129 -CLASS BytesIO
394.130 -CLASS C
394.131 -CLASS CAB
394.132 -CLASS CCompiler
394.133 -CLASS CCompilerError
394.134 -CLASS CDATASection
394.135 -CLASS CDLL
394.136 -CLASS CGIHTTPRequestHandler
394.137 -CLASS CGIHandler
394.138 -CLASS CGIXMLRPCRequestHandler
394.139 -CLASS CacheFTPHandler
394.140 -CLASS CallFunc
394.141 -CLASS CalledProcessError
394.142 -CLASS CannotSendHeader
394.143 -CLASS CannotSendRequest
394.144 -CLASS Canonizer
394.145 -CLASS CharacterData
394.146 -CLASS Charset
394.147 -CLASS CharsetError
394.148 -CLASS CheckList
394.149 -CLASS Childless
394.150 -CLASS Chunk
394.151 -CLASS Clamped
394.152 -CLASS Class
394.153 -CLASS ClassCodeGenerator
394.154 -CLASS ClassScope
394.155 -CLASS Cmd
394.156 -CLASS CodeGenerator
394.157 -CLASS Codec
394.158 -CLASS CodecRegistryError
394.159 -CLASS ComboBox
394.160 -CLASS Command
394.161 -CLASS CommandCompiler
394.162 -CLASS Comment
394.163 -CLASS Compare
394.164 -CLASS Comparison
394.165 -CLASS Compile
394.166 -CLASS CompileError
394.167 -CLASS Completer
394.168 -CLASS Complex
394.169 -CLASS ComponentItem
394.170 -CLASS Condition
394.171 -CLASS ConfigParser
394.172 -CLASS Connection
394.173 -CLASS Const
394.174 -CLASS ContentGenerator
394.175 -CLASS ContentHandler
394.176 -CLASS Context
394.177 -CLASS Continue
394.178 -CLASS Control
394.179 -CLASS ControlsWindow
394.180 -CLASS ConversionError
394.181 -CLASS Cookie
394.182 -CLASS CookieError
394.183 -CLASS CookieJar
394.184 -CLASS CookiePolicy
394.185 -CLASS CoverageResults
394.186 -CLASS Cursor
394.187 -CLASS CygwinCCompiler
394.188 -CLASS D
394.189 -CLASS DOMBuilder
394.190 -CLASS DOMEntityResolver
394.191 -CLASS DOMError
394.192 -CLASS DOMEventStream
394.193 -CLASS DOMException
394.194 -CLASS DOMImplementation
394.195 -CLASS DOMInputSource
394.196 -CLASS DOMStringSizeErr
394.197 -CLASS DTDHandler
394.198 -CLASS Data
394.199 -CLASS Database
394.200 -CLASS DatagramHandler
394.201 -CLASS DatagramRequestHandler
394.202 -CLASS DateTime
394.203 -CLASS DbfilenameShelf
394.204 -CLASS DebugRunner
394.205 -CLASS DebuggingServer
394.206 -CLASS Decimal
394.207 -CLASS DecimalException
394.208 -CLASS DeclHandler
394.209 -CLASS DecodedGenerator
394.210 -CLASS Decorators
394.211 -CLASS DefaultCookiePolicy
394.212 -CLASS DefaultHandler
394.213 -CLASS Delegator
394.214 -CLASS DeprecationWarning
394.215 -CLASS DeprecationWarning
394.216 -CLASS Dialect
394.217 -CLASS Dialog
394.218 -CLASS DialogWindow
394.219 -CLASS Dict
394.220 -CLASS DictMixin
394.221 -CLASS DictReader
394.222 -CLASS DictWriter
394.223 -CLASS Differ
394.224 -CLASS DirList
394.225 -CLASS DirSelectBox
394.226 -CLASS DirSelectDialog
394.227 -CLASS DirTree
394.228 -CLASS Directory
394.229 -CLASS Discard
394.230 -CLASS Distribution
394.231 -CLASS DistributionMetadata
394.232 -CLASS DistributionTestCase
394.233 -CLASS DistutilsArgError
394.234 -CLASS DistutilsClassError
394.235 -CLASS DistutilsError
394.236 -CLASS DistutilsExecError
394.237 -CLASS DistutilsFileError
394.238 -CLASS DistutilsGetoptError
394.239 -CLASS DistutilsInternalError
394.240 -CLASS DistutilsModuleError
394.241 -CLASS DistutilsOptionError
394.242 -CLASS DistutilsPlatformError
394.243 -CLASS DistutilsSetupError
394.244 -CLASS DistutilsTemplateError
394.245 -CLASS Div
394.246 -CLASS DivisionByZero
394.247 -CLASS Doc
394.248 -CLASS DocCGIXMLRPCRequestHandler
394.249 -CLASS DocTest
394.250 -CLASS DocTestFailure
394.251 -CLASS DocTestFinder
394.252 -CLASS DocTestParser
394.253 -CLASS DocTestRunner
394.254 -CLASS DocXMLRPCRequestHandler
394.255 -CLASS DocXMLRPCServer
394.256 -CLASS Document
394.257 -CLASS DocumentFragment
394.258 -CLASS DocumentHandler
394.259 -CLASS DocumentType
394.260 -CLASS DomstringSizeErr
394.261 -CLASS DumbWriter
394.262 -CLASS DummyCommand
394.263 -CLASS DuplicateSectionError
394.264 -CLASS DynLoadSuffixImporter
394.265 -CLASS EMXCCompiler
394.266 -CLASS EOFError
394.267 -CLASS EOFError
394.268 -CLASS ESISDocHandler
394.269 -CLASS Element
394.270 -CLASS ElementInfo
394.271 -CLASS ElementTree
394.272 -CLASS Ellipsis
394.273 -CLASS Empty
394.274 -CLASS EmptyNode
394.275 -CLASS EndOfBlock
394.276 -CLASS Entity
394.277 -CLASS EntityResolver
394.278 -CLASS Enum
394.279 -CLASS EnvironmentError
394.280 -CLASS EnvironmentError
394.281 -CLASS Error
394.282 -CLASS ErrorDuringImport
394.283 -CLASS ErrorHandler
394.284 -CLASS ErrorPrinter
394.285 -CLASS ErrorRaiser
394.286 -CLASS Event
394.287 -CLASS EventBroadcaster
394.288 -CLASS EventException
394.289 -CLASS ExFileSelectBox
394.290 -CLASS Example
394.291 -CLASS ExampleASTVisitor
394.292 -CLASS Exception
394.293 -CLASS Exception
394.294 -CLASS Exec
394.295 -CLASS ExitNow
394.296 -CLASS ExpatError
394.297 -CLASS ExpatParser
394.298 -CLASS Expression
394.299 -CLASS ExpressionCodeGenerator
394.300 -CLASS Extension
394.301 -CLASS F
394.302 -CLASS FTP
394.303 -CLASS FTPHandler
394.304 -CLASS Factory
394.305 -CLASS FancyGetopt
394.306 -CLASS FancyModuleLoader
394.307 -CLASS FancyURLopener
394.308 -CLASS Fault
394.309 -CLASS Feature
394.310 -CLASS FeedParser
394.311 -CLASS FieldStorage
394.312 -CLASS FileCookieJar
394.313 -CLASS FileEntry
394.314 -CLASS FileHandler
394.315 -CLASS FileIO
394.316 -CLASS FileInput
394.317 -CLASS FileList
394.318 -CLASS FileSelectBox
394.319 -CLASS FileWrapper
394.320 -CLASS Filter
394.321 -CLASS Filterer
394.322 -CLASS FingerHandler
394.323 -CLASS FirstHeaderLineIsContinuationD
394.324 -CLASS FloatingPointError
394.325 -CLASS FloatingPointError
394.326 -CLASS FloorDiv
394.327 -CLASS FlowGraph
394.328 -CLASS Folder
394.329 -CLASS Foo
394.330 -CLASS For
394.331 -CLASS ForkingMixIn
394.332 -CLASS ForkingTCPServer
394.333 -CLASS ForkingUDPServer
394.334 -CLASS Form
394.335 -CLASS FormContent
394.336 -CLASS FormContentDict
394.337 -CLASS Formatter
394.338 -CLASS Fraction
394.339 -CLASS From
394.340 -CLASS FtException
394.341 -CLASS Full
394.342 -CLASS FuncPtr
394.343 -CLASS Function
394.344 -CLASS FunctionCodeGenerator
394.345 -CLASS FunctionScope
394.346 -CLASS FunctionTestCase
394.347 -CLASS FutureParser
394.348 -CLASS FutureWarning
394.349 -CLASS FutureWarning
394.350 -CLASS GNUTranslations
394.351 -CLASS GenExpr
394.352 -CLASS GenExprFor
394.353 -CLASS GenExprIf
394.354 -CLASS GenExprInner
394.355 -CLASS GenExprScope
394.356 -CLASS Generator
394.357 -CLASS GeneratorExit
394.358 -CLASS GeneratorExit
394.359 -CLASS Getattr
394.360 -CLASS GetattrMagic
394.361 -CLASS GetoptError
394.362 -CLASS Global
394.363 -CLASS GopherError
394.364 -CLASS GopherHandler
394.365 -CLASS GridBag
394.366 -CLASS GzipFile
394.367 -CLASS HList
394.368 -CLASS HMAC
394.369 -CLASS HRESULT
394.370 -CLASS HTMLDoc
394.371 -CLASS HTMLParseError
394.372 -CLASS HTMLParser
394.373 -CLASS HTMLRepr
394.374 -CLASS HTTP
394.375 -CLASS HTTPBasicAuthHandler
394.376 -CLASS HTTPConnection
394.377 -CLASS HTTPCookieProcessor
394.378 -CLASS HTTPDefaultErrorHandler
394.379 -CLASS HTTPDigestAuthHandler
394.380 -CLASS HTTPError
394.381 -CLASS HTTPErrorProcessor
394.382 -CLASS HTTPException
394.383 -CLASS HTTPHandler
394.384 -CLASS HTTPPasswordMgr
394.385 -CLASS HTTPPasswordMgrWithDefaultReal
394.386 -CLASS HTTPRedirectHandler
394.387 -CLASS HTTPResponse
394.388 -CLASS HTTPSConnection
394.389 -CLASS HTTPSHandler
394.390 -CLASS HTTPServer
394.391 -CLASS Handler
394.392 -CLASS HandlerBase
394.393 -CLASS Header
394.394 -CLASS HeaderParseError
394.395 -CLASS HeaderParser
394.396 -CLASS Headers
394.397 -CLASS HelpFormatter
394.398 -CLASS Helper
394.399 -CLASS HierarchyRequestErr
394.400 -CLASS Hook
394.401 -CLASS Hooks
394.402 -CLASS HtmlDiff
394.403 -CLASS IC
394.404 -CLASS IMAP4
394.405 -CLASS IMAP4_SSL
394.406 -CLASS IMAP4_stream
394.407 -CLASS IOBase
394.408 -CLASS IOError
394.409 -CLASS IOError
394.410 -CLASS Identified
394.411 -CLASS If
394.412 -CLASS IfExp
394.413 -CLASS Ignore
394.414 -CLASS IllegalMonthError
394.415 -CLASS IllegalWeekdayError
394.416 -CLASS ImmutableSet
394.417 -CLASS ImpImporter
394.418 -CLASS ImpLoader
394.419 -CLASS Import
394.420 -CLASS ImportError
394.421 -CLASS ImportError
394.422 -CLASS ImportManager
394.423 -CLASS ImportWarning
394.424 -CLASS ImportWarning
394.425 -CLASS Importer
394.426 -CLASS ImproperConnectionState
394.427 -CLASS Incomplete
394.428 -CLASS IncompleteRead
394.429 -CLASS IncrementalDecoder
394.430 -CLASS IncrementalEncoder
394.431 -CLASS IncrementalNewlineDecoder
394.432 -CLASS IncrementalParser
394.433 -CLASS IndentedHelpFormatter
394.434 -CLASS IndexError
394.435 -CLASS IndexError
394.436 -CLASS IndexSizeErr
394.437 -CLASS Inexact
394.438 -CLASS IniParser
394.439 -CLASS InputOnly
394.440 -CLASS InputSource
394.441 -CLASS InsertionLoc
394.442 -CLASS InstallScriptsTestCase
394.443 -CLASS InstallTestCase
394.444 -CLASS Integral
394.445 -CLASS Interactive
394.446 -CLASS InteractiveCodeGenerator
394.447 -CLASS InteractiveConsole
394.448 -CLASS InteractiveInterpreter
394.449 -CLASS InterpFormContentDict
394.450 -CLASS InterpolationDepthError
394.451 -CLASS InterpolationError
394.452 -CLASS InterpolationSyntaxError
394.453 -CLASS IntlText
394.454 -CLASS IntlWritingCode
394.455 -CLASS InuseAttributeErr
394.456 -CLASS InvalidAccessErr
394.457 -CLASS InvalidCharacterErr
394.458 -CLASS InvalidModificationErr
394.459 -CLASS InvalidNodeTypeErr
394.460 -CLASS InvalidOperation
394.461 -CLASS InvalidStateErr
394.462 -CLASS InvalidURL
394.463 -CLASS Invert
394.464 -CLASS IsqlCmd
394.465 -CLASS IsqlExit
394.466 -CLASS IterableUserDict
394.467 -CLASS JSONDecoder
394.468 -CLASS JSONEncoder
394.469 -CLASS JavaSAXParser
394.470 -CLASS JoinableQueue
394.471 -CLASS JyDTDHandlerWrapper
394.472 -CLASS JyEntityResolverWrapper
394.473 -CLASS JyErrorHandlerWrapper
394.474 -CLASS JyInputSourceWrapper
394.475 -CLASS JythonCompiler
394.476 -CLASS JythonSignalHandler
394.477 -CLASS KeyError
394.478 -CLASS KeyError
394.479 -CLASS KeyboardInterrupt
394.480 -CLASS KeyboardInterrupt
394.481 -CLASS Keyword
394.482 -CLASS LOBTestCase
394.483 -CLASS LWPCookieJar
394.484 -CLASS LabelEntry
394.485 -CLASS LabelFrame
394.486 -CLASS Lambda
394.487 -CLASS LambdaScope
394.488 -CLASS LargeZipFile
394.489 -CLASS LeftShift
394.490 -CLASS LexicalHandler
394.491 -CLASS LexicalXMLGenerator
394.492 -CLASS LibError
394.493 -CLASS LibraryLoader
394.494 -CLASS LineAddrTable
394.495 -CLASS LinkError
394.496 -CLASS List
394.497 -CLASS ListComp
394.498 -CLASS ListCompFor
394.499 -CLASS ListCompIf
394.500 -CLASS ListNoteBook
394.501 -CLASS Listener
394.502 -CLASS LittleEndianStructure
394.503 -CLASS LoadError
394.504 -CLASS LocalNameFinder
394.505 -CLASS Location
394.506 -CLASS Locator
394.507 -CLASS Lock
394.508 -CLASS Log
394.509 -CLASS LogRecord
394.510 -CLASS Logger
394.511 -CLASS LoggingSilencer
394.512 -CLASS Logical
394.513 -CLASS LookupError
394.514 -CLASS LookupError
394.515 -CLASS LooseVersion
394.516 -CLASS MH
394.517 -CLASS MHMailbox
394.518 -CLASS MHMessage
394.519 -CLASS MIMEApplication
394.520 -CLASS MIMEAudio
394.521 -CLASS MIMEBase
394.522 -CLASS MIMEImage
394.523 -CLASS MIMEMessage
394.524 -CLASS MIMEMultipart
394.525 -CLASS MIMENonMultipart
394.526 -CLASS MIMEText
394.527 -CLASS MMDF
394.528 -CLASS MMDFMessage
394.529 -CLASS MSVCCompiler
394.530 -CLASS MWerksCompiler
394.531 -CLASS MacroExpander
394.532 -CLASS Mailbox
394.533 -CLASS Maildir
394.534 -CLASS MaildirMessage
394.535 -CLASS MailmanProxy
394.536 -CLASS MalformedHeaderDefect
394.537 -CLASS Manager
394.538 -CLASS Marshaller
394.539 -CLASS MemoryError
394.540 -CLASS MemoryError
394.541 -CLASS MemoryHandler
394.542 -CLASS Message
394.543 -CLASS MessageDefect
394.544 -CLASS MessageError
394.545 -CLASS MessageParseError
394.546 -CLASS MetadataTestCase
394.547 -CLASS Meter
394.548 -CLASS MimeWriter
394.549 -CLASS Mingw32CCompiler
394.550 -CLASS MiniApplication
394.551 -CLASS MiniFieldStorage
394.552 -CLASS MisplacedEnvelopeHeaderDefect
394.553 -CLASS MissingSectionHeaderError
394.554 -CLASS MmdfMailbox
394.555 -CLASS Mod
394.556 -CLASS Model
394.557 -CLASS Module
394.558 -CLASS ModuleCodeGenerator
394.559 -CLASS ModuleFinder
394.560 -CLASS ModuleImporter
394.561 -CLASS ModuleLoader
394.562 -CLASS ModuleScanner
394.563 -CLASS ModuleScope
394.564 -CLASS MozillaCookieJar
394.565 -CLASS Mul
394.566 -CLASS MultiCall
394.567 -CLASS MultiCallIterator
394.568 -CLASS MultiFile
394.569 -CLASS MultipartConversionError
394.570 -CLASS MultipartInvariantViolationDef
394.571 -CLASS MutableString
394.572 -CLASS MyClass
394.573 -CLASS MyTest
394.574 -CLASS NNTP
394.575 -CLASS NNTPDataError
394.576 -CLASS NNTPPermanentError
394.577 -CLASS NNTPProtocolError
394.578 -CLASS NNTPReplyError
394.579 -CLASS NNTPTemporaryError
394.580 -CLASS NProperty
394.581 -CLASS NTEventLogHandler
394.582 -CLASS NULL
394.583 -CLASS Name
394.584 -CLASS NameError
394.585 -CLASS NameError
394.586 -CLASS NamedNodeMap
394.587 -CLASS NamespaceErr
394.588 -CLASS NannyNag
394.589 -CLASS NestedScopeMixin
394.590 -CLASS Netrc
394.591 -CLASS NetrcParseError
394.592 -CLASS NewStyle
394.593 -CLASS NoBoundaryInMultipartDefect
394.594 -CLASS NoDataAllowedErr
394.595 -CLASS NoModificationAllowedErr
394.596 -CLASS NoOpMetaClass
394.597 -CLASS NoOptionError
394.598 -CLASS NoSectionError
394.599 -CLASS Node
394.600 -CLASS NodeFilter
394.601 -CLASS NodeTransformer
394.602 -CLASS NodeVisitor
394.603 -CLASS Not
394.604 -CLASS NotANumber
394.605 -CLASS NotConnected
394.606 -CLASS NotFoundErr
394.607 -CLASS NotImplementedError
394.608 -CLASS NotImplementedError
394.609 -CLASS NotSupportedErr
394.610 -CLASS Notation
394.611 -CLASS NoteBook
394.612 -CLASS NullFormatter
394.613 -CLASS NullImporter
394.614 -CLASS NullTranslations
394.615 -CLASS NullWriter
394.616 -CLASS Number
394.617 -CLASS OSError
394.618 -CLASS OSError
394.619 -CLASS OSSAudioError
394.620 -CLASS ObjectSpecifier
394.621 -CLASS OleDLL
394.622 -CLASS OpFinder
394.623 -CLASS OpenerDirector
394.624 -CLASS OptParseError
394.625 -CLASS Option
394.626 -CLASS OptionConflictError
394.627 -CLASS OptionContainer
394.628 -CLASS OptionDummy
394.629 -CLASS OptionError
394.630 -CLASS OptionGroup
394.631 -CLASS OptionMenu
394.632 -CLASS OptionParser
394.633 -CLASS OptionValueError
394.634 -CLASS Or
394.635 -CLASS OracleSPTest
394.636 -CLASS Ordinal
394.637 -CLASS OutputChecker
394.638 -CLASS Overflow
394.639 -CLASS OverflowError
394.640 -CLASS OverflowError
394.641 -CLASS POP3
394.642 -CLASS POP3_SSL
394.643 -CLASS Packer
394.644 -CLASS PanedWindow
394.645 -CLASS Panel
394.646 -CLASS Parser
394.647 -CLASS ParserBase
394.648 -CLASS ParserError
394.649 -CLASS ParsingError
394.650 -CLASS Pass
394.651 -CLASS Pattern
394.652 -CLASS Pdb
394.653 -CLASS PendingDeprecationWarning
394.654 -CLASS PendingDeprecationWarning
394.655 -CLASS PickleError
394.656 -CLASS Pickler
394.657 -CLASS PicklingError
394.658 -CLASS PlaceHolder
394.659 -CLASS Popen
394.660 -CLASS Popen3
394.661 -CLASS Popen4
394.662 -CLASS PopupMenu
394.663 -CLASS PortableUnixMailbox
394.664 -CLASS Power
394.665 -CLASS PreprocessError
394.666 -CLASS PrettyPrinter
394.667 -CLASS Print
394.668 -CLASS Printnl
394.669 -CLASS Process
394.670 -CLASS ProcessingInstruction
394.671 -CLASS Profile
394.672 -CLASS ProgressBar
394.673 -CLASS Prompt
394.674 -CLASS ProtocolError
394.675 -CLASS ProxyBasicAuthHandler
394.676 -CLASS ProxyDigestAuthHandler
394.677 -CLASS ProxyHandler
394.678 -CLASS PullDOM
394.679 -CLASS PureProxy
394.680 -CLASS PyCompileError
394.681 -CLASS PyDLL
394.682 -CLASS PyDialog
394.683 -CLASS PyFlowGraph
394.684 -CLASS PyHKEY
394.685 -CLASS PyZipFile
394.686 -CLASS QDPoint
394.687 -CLASS QDRectangle
394.688 -CLASS QName
394.689 -CLASS Queue
394.690 -CLASS RExec
394.691 -CLASS RGBColor
394.692 -CLASS RLock
394.693 -CLASS RadioButtonGroup
394.694 -CLASS Raise
394.695 -CLASS Random
394.696 -CLASS Range
394.697 -CLASS RangeException
394.698 -CLASS Rational
394.699 -CLASS RawConfigParser
394.700 -CLASS RawIOBase
394.701 -CLASS RawTurtle
394.702 -CLASS ReadOnlySequentialNamedNodeMap
394.703 -CLASS Real
394.704 -CLASS Record
394.705 -CLASS ReferenceError
394.706 -CLASS ReferenceError
394.707 -CLASS Repr
394.708 -CLASS Request
394.709 -CLASS ResponseError
394.710 -CLASS ResponseNotReady
394.711 -CLASS ResultSet
394.712 -CLASS ResultSetRow
394.713 -CLASS Return
394.714 -CLASS RightShift
394.715 -CLASS RobotFileParser
394.716 -CLASS RootLogger
394.717 -CLASS RotatingFileHandler
394.718 -CLASS Rounded
394.719 -CLASS Row
394.720 -CLASS RuntimeError
394.721 -CLASS RuntimeError
394.722 -CLASS RuntimeWarning
394.723 -CLASS RuntimeWarning
394.724 -CLASS SAX2DOM
394.725 -CLASS SAXException
394.726 -CLASS SAXNotRecognizedException
394.727 -CLASS SAXNotSupportedException
394.728 -CLASS SAXParseException
394.729 -CLASS SAXReaderNotAvailable
394.730 -CLASS SGMLParseError
394.731 -CLASS SGMLParser
394.732 -CLASS SMTP
394.733 -CLASS SMTPAuthenticationError
394.734 -CLASS SMTPConnectError
394.735 -CLASS SMTPDataError
394.736 -CLASS SMTPException
394.737 -CLASS SMTPHandler
394.738 -CLASS SMTPHeloError
394.739 -CLASS SMTPRecipientsRefused
394.740 -CLASS SMTPResponseException
394.741 -CLASS SMTPSenderRefused
394.742 -CLASS SMTPServer
394.743 -CLASS SMTPServerDisconnected
394.744 -CLASS SQLServerSPTest
394.745 -CLASS SQLTestCase
394.746 -CLASS SSLError
394.747 -CLASS SSLSocket
394.748 -CLASS ST
394.749 -CLASS SafeConfigParser
394.750 -CLASS SafeTransport
394.751 -CLASS Schema
394.752 -CLASS Scope
394.753 -CLASS Screen
394.754 -CLASS ScrolledCavas
394.755 -CLASS ScrolledText
394.756 -CLASS ScrolledWindow
394.757 -CLASS Select
394.758 -CLASS Semaphore
394.759 -CLASS SequenceMatcher
394.760 -CLASS SerialCookie
394.761 -CLASS Server
394.762 -CLASS ServerHTMLDoc
394.763 -CLASS ServerProxy
394.764 -CLASS Set
394.765 -CLASS SgmlopParser
394.766 -CLASS Shape
394.767 -CLASS Shelf
394.768 -CLASS SimpleCookie
394.769 -CLASS SimpleHTTPRequestHandler
394.770 -CLASS SimpleHandler
394.771 -CLASS SimpleLocator
394.772 -CLASS SimpleXMLRPCDispatcher
394.773 -CLASS SimpleXMLRPCRequestHandler
394.774 -CLASS SimpleXMLRPCServer
394.775 -CLASS Slice
394.776 -CLASS Sliceobj
394.777 -CLASS SlowParser
394.778 -CLASS SmartCookie
394.779 -CLASS Sniffer
394.780 -CLASS SocketHandler
394.781 -CLASS SocketType
394.782 -CLASS Stack
394.783 -CLASS StackDepthTracker
394.784 -CLASS StandardError
394.785 -CLASS StandardError
394.786 -CLASS StartBoundaryNotFoundDefect
394.787 -CLASS Stats
394.788 -CLASS StdButtonBox
394.789 -CLASS Stmt
394.790 -CLASS StopIteration
394.791 -CLASS StopIteration
394.792 -CLASS StopTokenizing
394.793 -CLASS Strange
394.794 -CLASS StreamConverter
394.795 -CLASS StreamHandler
394.796 -CLASS StreamReader
394.797 -CLASS StreamRequestHandler
394.798 -CLASS StreamWriter
394.799 -CLASS StrictVersion
394.800 -CLASS StringIO
394.801 -CLASS Struct
394.802 -CLASS Structure
394.803 -CLASS StyledText
394.804 -CLASS Sub
394.805 -CLASS SubPattern
394.806 -CLASS Subnormal
394.807 -CLASS Subscript
394.808 -CLASS SummaryInformation
394.809 -CLASS Super
394.810 -CLASS SuperSuper
394.811 -CLASS SvFormContentDict
394.812 -CLASS Symbol
394.813 -CLASS SymbolTable
394.814 -CLASS SymbolVisitor
394.815 -CLASS SyncManager
394.816 -CLASS SyntaxErr
394.817 -CLASS SyntaxError
394.818 -CLASS SyntaxError
394.819 -CLASS SyntaxErrorChecker
394.820 -CLASS SyntaxWarning
394.821 -CLASS SyntaxWarning
394.822 -CLASS SysLogHandler
394.823 -CLASS SystemError
394.824 -CLASS SystemError
394.825 -CLASS SystemExit
394.826 -CLASS SystemExit
394.827 -CLASS SystemRandom
394.828 -CLASS TCPServer
394.829 -CLASS TList
394.830 -CLASS TalkTo
394.831 -CLASS TarError
394.832 -CLASS TarFile
394.833 -CLASS TarInfo
394.834 -CLASS Telnet
394.835 -CLASS TempdirManager
394.836 -CLASS Template
394.837 -CLASS Test
394.838 -CLASS TestCase
394.839 -CLASS TestClass
394.840 -CLASS TestCrispinTorture
394.841 -CLASS TestDistribution
394.842 -CLASS TestLoader
394.843 -CLASS TestResult
394.844 -CLASS TestSuite
394.845 -CLASS TestThread
394.846 -CLASS TestXMLParser
394.847 -CLASS Testcase
394.848 -CLASS Tester
394.849 -CLASS Text
394.850 -CLASS TextDoc
394.851 -CLASS TextFile
394.852 -CLASS TextIOBase
394.853 -CLASS TextIOWrapper
394.854 -CLASS TextRepr
394.855 -CLASS TextTestRunner
394.856 -CLASS TextWrapper
394.857 -CLASS Textbox
394.858 -CLASS Thread
394.859 -CLASS ThreadingMixIn
394.860 -CLASS ThreadingTCPServer
394.861 -CLASS ThreadingUDPServer
394.862 -CLASS ThreadingUnixDatagramServer
394.863 -CLASS ThreadingUnixStreamServer
394.864 -CLASS TimedRotatingFileHandler
394.865 -CLASS Timer
394.866 -CLASS TitledHelpFormatter
394.867 -CLASS Tix
394.868 -CLASS Tk
394.869 -CLASS TokenError
394.870 -CLASS Tokenizer
394.871 -CLASS TortureBase
394.872 -CLASS Trace
394.873 -CLASS Transformer
394.874 -CLASS Transport
394.875 -CLASS Tree
394.876 -CLASS TreeBuilder
394.877 -CLASS TryExcept
394.878 -CLASS TryFinally
394.879 -CLASS Tuple
394.880 -CLASS TupleArg
394.881 -CLASS Turtle
394.882 -CLASS TurtleScreen
394.883 -CLASS Type
394.884 -CLASS TypeError
394.885 -CLASS TypeError
394.886 -CLASS TypeInfo
394.887 -CLASS UDPServer
394.888 -CLASS URLError
394.889 -CLASS UUID
394.890 -CLASS UnaryAdd
394.891 -CLASS UnarySub
394.892 -CLASS UnboundLocalError
394.893 -CLASS UnboundLocalError
394.894 -CLASS Underflow
394.895 -CLASS UnexpectedException
394.896 -CLASS UnicodeDecodeError
394.897 -CLASS UnicodeDecodeError
394.898 -CLASS UnicodeEncodeError
394.899 -CLASS UnicodeEncodeError
394.900 -CLASS UnicodeError
394.901 -CLASS UnicodeError
394.902 -CLASS UnicodeTranslateError
394.903 -CLASS UnicodeTranslateError
394.904 -CLASS UnicodeWarning
394.905 -CLASS UnicodeWarning
394.906 -CLASS UnimplementedFileMode
394.907 -CLASS Union
394.908 -CLASS UnixCCompiler
394.909 -CLASS UnixDatagramServer
394.910 -CLASS UnixMailbox
394.911 -CLASS UnixStreamServer
394.912 -CLASS Unknown
394.913 -CLASS UnknownFileError
394.914 -CLASS UnknownHandler
394.915 -CLASS UnknownProtocol
394.916 -CLASS UnknownTransferEncoding
394.917 -CLASS Unload
394.918 -CLASS Unmarshaller
394.919 -CLASS Unpacker
394.920 -CLASS Unpickler
394.921 -CLASS UnpicklingError
394.922 -CLASS UnspecifiedEventTypeErr
394.923 -CLASS UnsupportedOperation
394.924 -CLASS UserDataHandler
394.925 -CLASS UserDict
394.926 -CLASS UserList
394.927 -CLASS UserString
394.928 -CLASS UserWarning
394.929 -CLASS UserWarning
394.930 -CLASS ValidationErr
394.931 -CLASS ValueError
394.932 -CLASS ValueError
394.933 -CLASS Values
394.934 -CLASS Vec2D
394.935 -CLASS Vendor
394.936 -CLASS Version
394.937 -CLASS VersionPredicate
394.938 -CLASS View
394.939 -CLASS WSGIRequestHandler
394.940 -CLASS WSGIServer
394.941 -CLASS Warning
394.942 -CLASS Warning
394.943 -CLASS Wave_read
394.944 -CLASS Wave_write
394.945 -CLASS WeakKeyDictionary
394.946 -CLASS WeakValueDictionary
394.947 -CLASS While
394.948 -CLASS WichmannHill
394.949 -CLASS WinDLL
394.950 -CLASS Window
394.951 -CLASS WindowsError
394.952 -CLASS WindowsError
394.953 -CLASS With
394.954 -CLASS WrongDocumentErr
394.955 -CLASS X
394.956 -CLASS XMLFilter
394.957 -CLASS XMLFilterBase
394.958 -CLASS XMLFilterImpl
394.959 -CLASS XMLGenerator
394.960 -CLASS XMLParser
394.961 -CLASS XMLRPCDocGenerator
394.962 -CLASS XMLReader
394.963 -CLASS XMLTreeBuilder
394.964 -CLASS XmlParseErr
394.965 -CLASS Yield
394.966 -CLASS Yuck
394.967 -CLASS ZeroDivisionError
394.968 -CLASS ZeroDivisionError
394.969 -CLASS ZipFile
394.970 -CLASS ZipImportError
394.971 -CLASS ZipInfo
394.972 -CLASS _CData [PROTECTE
394.973 -CLASS _FuncPtr [PROTECTE
394.974 -CLASS _SimpleCData [PROTECTE
394.975 -CLASS _posixfile_
394.976 -CLASS array
394.977 -CLASS async_chat
394.978 -CLASS bdist
394.979 -CLASS bdist_dumb
394.980 -CLASS bdist_msi
394.981 -CLASS bdist_rpm
394.982 -CLASS bdist_wininst
394.983 -CLASS bool
394.984 -CLASS bsddbobject
394.985 -CLASS build
394.986 -CLASS build_clib
394.987 -CLASS build_ext
394.988 -CLASS build_py
394.989 -CLASS build_scripts
394.990 -CLASS c_bool
394.991 -CLASS c_byte
394.992 -CLASS c_char
394.993 -CLASS c_char_p
394.994 -CLASS c_double
394.995 -CLASS c_float
394.996 -CLASS c_int
394.997 -CLASS c_int16
394.998 -CLASS c_int32
394.999 -CLASS c_int64
394.1000 -CLASS c_int8
394.1001 -CLASS c_long
394.1002 -CLASS c_longdouble
394.1003 -CLASS c_longlong
394.1004 -CLASS c_short
394.1005 -CLASS c_size_t
394.1006 -CLASS c_ubyte
394.1007 -CLASS c_uint
394.1008 -CLASS c_uint16
394.1009 -CLASS c_uint32
394.1010 -CLASS c_uint64
394.1011 -CLASS c_uint8
394.1012 -CLASS c_ulong
394.1013 -CLASS c_ulonglong
394.1014 -CLASS c_ushort
394.1015 -CLASS c_void_p
394.1016 -CLASS c_wchar
394.1017 -CLASS c_wchar_p
394.1018 -CLASS class
394.1019 -CLASS class
394.1020 -CLASS clean
394.1021 -CLASS closing
394.1022 -CLASS complex
394.1023 -CLASS compressobj
394.1024 -CLASS config
394.1025 -CLASS container
394.1026 -CLASS container
394.1027 -CLASS contextmanager
394.1028 -CLASS contextmanager
394.1029 -CLASS controller
394.1030 -CLASS date
394.1031 -CLASS datetime
394.1032 -CLASS dbexts
394.1033 -CLASS dbextsTestCase
394.1034 -CLASS dbhash
394.1035 -CLASS decompressobj
394.1036 -CLASS deque
394.1037 -CLASS dict
394.1038 -CLASS dict
394.1039 -CLASS dircmp
394.1040 -CLASS dispatcher
394.1041 -CLASS dispatcher_with_send
394.1042 -CLASS dl
394.1043 -CLASS error
394.1044 -CLASS error_data
394.1045 -CLASS error_proto
394.1046 -CLASS error_reply
394.1047 -CLASS excel
394.1048 -CLASS excel_tab
394.1049 -CLASS executor
394.1050 -CLASS fifo
394.1051 -CLASS file
394.1052 -CLASS file
394.1053 -CLASS file_dispatcher
394.1054 -CLASS file_wrapper
394.1055 -CLASS float
394.1056 -CLASS float
394.1057 -CLASS foo
394.1058 -CLASS gaierror
394.1059 -CLASS herror
394.1060 -CLASS install
394.1061 -CLASS install_data
394.1062 -CLASS install_egg_info
394.1063 -CLASS install_headers
394.1064 -CLASS install_lib
394.1065 -CLASS install_misc
394.1066 -CLASS install_scripts
394.1067 -CLASS instance
394.1068 -CLASS instance
394.1069 -CLASS int
394.1070 -CLASS iterator
394.1071 -CLASS iterator
394.1072 -CLASS list
394.1073 -CLASS local
394.1074 -CLASS lock
394.1075 -CLASS long
394.1076 -CLASS main
394.1077 -CLASS mbox
394.1078 -CLASS mboxMessage
394.1079 -CLASS mllib
394.1080 -CLASS mmap
394.1081 -CLASS multiprocessing.Pool
394.1082 -CLASS mutex
394.1083 -CLASS mxODBCProxy
394.1084 -CLASS netrc
394.1085 -CLASS object
394.1086 -CLASS object
394.1087 -CLASS oss_audio_device
394.1088 -CLASS oss_mixer_device
394.1089 -CLASS poll
394.1090 -CLASS py_object
394.1091 -CLASS register
394.1092 -CLASS scheduler
394.1093 -CLASS sdist
394.1094 -CLASS set
394.1095 -CLASS set
394.1096 -CLASS shlex
394.1097 -CLASS simple_producer
394.1098 -CLASS socket
394.1099 -CLASS stat_result
394.1100 -CLASS str
394.1101 -CLASS str
394.1102 -CLASS test_dist
394.1103 -CLASS test_zxjdbc
394.1104 -CLASS time
394.1105 -CLASS timedelta
394.1106 -CLASS timeout
394.1107 -CLASS tixCommand
394.1108 -CLASS tmxxx
394.1109 -CLASS tuple
394.1110 -CLASS tzinfo
394.1111 -CLASS unicode
394.1112 -CLASS unicode
394.1113 -CLASS upload
394.1114 -CLASS window
394.1115 -CLASS xmlparser
394.1116 -CLASS zipimporter
394.1117 -CLASS zxAPITestCase
394.1118 -CLASS zxCoreTestCase
394.1119 -CLASS zxJDBCTestCase
394.1120 -METHOD __import__(name, globals, loca
394.1121 -METHOD abs(x)
394.1122 -METHOD all(iterable)
394.1123 -METHOD any(iterable)
394.1124 -METHOD ---apply(function, args, ke---
394.1125 -METHOD basestring()
394.1126 -METHOD bin(x)
394.1127 -METHOD bool(x)
394.1128 -METHOD buffer(object, offset, size)
394.1129 -METHOD callable(object)
394.1130 -METHOD chr(i)
394.1131 -METHOD classmethod(function)
394.1132 -METHOD cmp(x, y)
394.1133 -METHOD coerce(x, y)
394.1134 -METHOD compile(source, filename, mode
394.1135 -METHOD complex(real, imag)
394.1136 -METHOD delattr(object, name)
394.1137 -METHOD dict(arg)
394.1138 -METHOD dir(object)
394.1139 -METHOD divmod(a, b)
394.1140 -METHOD enumerate(sequence, start)
394.1141 -METHOD eval(expression, globals, loca
394.1142 -METHOD execfile(filename, globals, lo
394.1143 -METHOD exit(code)
394.1144 -METHOD file(filename, mode, bufsize)
394.1145 -METHOD filter(function, iterable)
394.1146 -METHOD float(x)
394.1147 -METHOD frozenset(iterable)
394.1148 -METHOD getattr(object, name, default)
394.1149 -METHOD globals()
394.1150 -METHOD hasattr(object, name)
394.1151 -METHOD hash(object)
394.1152 -METHOD help(object)
394.1153 -METHOD hex(x)
394.1154 -METHOD id(object)
394.1155 -METHOD input(prompt)
394.1156 -METHOD int(x, radix)
394.1157 -METHOD intern(string)
394.1158 -METHOD isinstance(object, classinfo)
394.1159 -METHOD issubclass(class, classinfo)
394.1160 -METHOD iter(o, sentinel)
394.1161 -METHOD len(s)
394.1162 -METHOD list(iterable)
394.1163 -METHOD locals()
394.1164 -METHOD long(x, radix)
394.1165 -METHOD map(function, iterable)
394.1166 -METHOD max(iterable, argskey)
394.1167 -METHOD min(iterable, argskey)
394.1168 -METHOD next(iterator, default)
394.1169 -METHOD object()
394.1170 -METHOD oct(x)
394.1171 -METHOD open(filename, mode, bufsize)
394.1172 -METHOD ord(c)
394.1173 -METHOD pow(x, y, z)
394.1174 -METHOD print(object, sep, end, file)
394.1175 -METHOD property(fget, fset, fdel, doc
394.1176 -METHOD quit(code)
394.1177 -METHOD range(start, stop, step)
394.1178 -METHOD raw_input(prompt)
394.1179 -METHOD reduce(function, iterable, ini
394.1180 -METHOD reload(module)
394.1181 -METHOD repr(object)
394.1182 -METHOD reversed(seq)
394.1183 -METHOD round(x, n)
394.1184 -METHOD set(iterable)
394.1185 -METHOD setattr(object, name, value)
394.1186 -METHOD slice(start, stop, step)
394.1187 -METHOD sorted(iterable, cmp, key, rev
394.1188 -METHOD staticmethod(function)
394.1189 -METHOD str(object)
394.1190 -METHOD sum(iterable, start)
394.1191 -METHOD super(type, object-or-type)
394.1192 -METHOD tuple(iterable)
394.1193 -METHOD type(name, bases, dict)
394.1194 -METHOD type(object)
394.1195 -METHOD unichr(i)
394.1196 -METHOD unicode(object, encoding, erro
394.1197 -METHOD vars(object)
394.1198 -METHOD xrange(start, stop, step)
394.1199 -METHOD zip(iterable)
394.1200 -VARIABLE Ellipsis
394.1201 -VARIABLE False
394.1202 -VARIABLE None
394.1203 -VARIABLE NotImplemented
394.1204 -VARIABLE True
394.1205 -VARIABLE __debug__
394.1206 -VARIABLE copyright
394.1207 -KEYWORD and
394.1208 -KEYWORD as
394.1209 -KEYWORD assert
394.1210 -KEYWORD break
394.1211 -KEYWORD class
394.1212 -KEYWORD continue
394.1213 -KEYWORD def
394.1214 -KEYWORD del
394.1215 -KEYWORD elif
394.1216 -KEYWORD else
394.1217 -KEYWORD except
394.1218 -KEYWORD exec
394.1219 -KEYWORD finally
394.1220 -KEYWORD for
394.1221 -KEYWORD from
394.1222 -KEYWORD global
394.1223 -KEYWORD if
394.1224 -KEYWORD import
394.1225 -KEYWORD in
394.1226 -KEYWORD is
394.1227 -KEYWORD lambda
394.1228 -KEYWORD not
394.1229 -KEYWORD or
394.1230 -KEYWORD pass
394.1231 -KEYWORD print
394.1232 -KEYWORD raise
394.1233 -KEYWORD return
394.1234 -KEYWORD try
394.1235 -KEYWORD while
394.1236 -KEYWORD with
394.1237 -KEYWORD yield
395.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testLocals5.completion Sun Jan 04 13:11:53 2015 -0600
395.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
395.3 @@ -1,1236 +0,0 @@
395.4 -Code completion result for source line:
395.5 -x = |myfunc
395.6 -(QueryType=COMPLETION, NameKind=PREFIX)
395.7 -MODULE module1
395.8 -MODULE module2
395.9 -MODULE module4
395.10 -CLASS MyClass
395.11 -METHOD myfunc(funcparam)
395.12 -VARIABLE funcparam
395.13 -VARIABLE localvar
395.14 -VARIABLE toplevelvar
395.15 -VARIABLE toplevelvar2
395.16 -VARIABLE toplevelvar3
395.17 -VARIABLE toplevelvar4
395.18 -VARIABLE x
395.19 -------------------------------------
395.20 -CLASS A
395.21 -CLASS ABCMeta
395.22 -CLASS AEServer
395.23 -CLASS AEText
395.24 -CLASS ASTVisitor
395.25 -CLASS AbstractBasicAuthHandler
395.26 -CLASS AbstractClassCode
395.27 -CLASS AbstractCompileMode
395.28 -CLASS AbstractDigestAuthHandler
395.29 -CLASS AbstractFormatter
395.30 -CLASS AbstractFunctionCode
395.31 -CLASS AbstractHTTPHandler
395.32 -CLASS AbstractWriter
395.33 -CLASS Add
395.34 -CLASS AddressList
395.35 -CLASS And
395.36 -CLASS Application
395.37 -CLASS ArgumentError
395.38 -CLASS ArithmeticError
395.39 -CLASS ArithmeticError
395.40 -CLASS Array
395.41 -CLASS ArrayInstance
395.42 -CLASS AssAttr
395.43 -CLASS AssList
395.44 -CLASS AssName
395.45 -CLASS AssTuple
395.46 -CLASS Assert
395.47 -CLASS AssertionError
395.48 -CLASS AssertionError
395.49 -CLASS Assign
395.50 -CLASS AsyncResult
395.51 -CLASS Attr
395.52 -CLASS AttributeError
395.53 -CLASS AttributeError
395.54 -CLASS AttributeList
395.55 -CLASS AttributeMap
395.56 -CLASS Attributes
395.57 -CLASS AttributesImpl
395.58 -CLASS AttributesNS
395.59 -CLASS AttributesNSImpl
395.60 -CLASS AugAssign
395.61 -CLASS AugGetattr
395.62 -CLASS AugName
395.63 -CLASS AugSlice
395.64 -CLASS AugSubscript
395.65 -CLASS AuthenticationError
395.66 -CLASS AutoGILError
395.67 -CLASS B
395.68 -CLASS BCPPCompiler
395.69 -CLASS BCPTestCase
395.70 -CLASS BZ2Compressor
395.71 -CLASS BZ2Decompressor
395.72 -CLASS BZ2File
395.73 -CLASS Babyl
395.74 -CLASS BabylMailbox
395.75 -CLASS BabylMessage
395.76 -CLASS Backquote
395.77 -CLASS BadBoundaryPointsErr
395.78 -CLASS BadFutureParser
395.79 -CLASS BadOptionError
395.80 -CLASS BadStatusLine
395.81 -CLASS BadZipfile
395.82 -CLASS Balloon
395.83 -CLASS Bar
395.84 -CLASS BaseCGIHandler
395.85 -CLASS BaseCookie
395.86 -CLASS BaseException
395.87 -CLASS BaseException
395.88 -CLASS BaseHTTPRequestHandler
395.89 -CLASS BaseHandler
395.90 -CLASS BaseIncrementalParser
395.91 -CLASS BaseManager
395.92 -CLASS BaseProxy
395.93 -CLASS BaseRequestHandler
395.94 -CLASS BaseRotatingHandler
395.95 -CLASS BaseSet
395.96 -CLASS BasicModuleImporter
395.97 -CLASS BasicModuleLoader
395.98 -CLASS BastionClass
395.99 -CLASS Baz
395.100 -CLASS Bdb
395.101 -CLASS BdbQuit
395.102 -CLASS BigEndianStructure
395.103 -CLASS Binary
395.104 -CLASS Bitand
395.105 -CLASS Bitor
395.106 -CLASS Bitxor
395.107 -CLASS Block
395.108 -CLASS BlockFinder
395.109 -CLASS BlockingIOError
395.110 -CLASS Boolean
395.111 -CLASS BoundaryError
395.112 -CLASS BoundedSemaphore
395.113 -CLASS Break
395.114 -CLASS Breakpoint
395.115 -CLASS BsdDbShelf
395.116 -CLASS BufferTooShort
395.117 -CLASS BufferedIOBase
395.118 -CLASS BufferedRWPair
395.119 -CLASS BufferedRandom
395.120 -CLASS BufferedReader
395.121 -CLASS BufferedWriter
395.122 -CLASS BufferingFormatter
395.123 -CLASS BufferingHandler
395.124 -CLASS BuildPyTestCase
395.125 -CLASS BuildScriptsTestCase
395.126 -CLASS BuiltinImporter
395.127 -CLASS Bulkcopy
395.128 -CLASS ButtonBox
395.129 -CLASS BytesIO
395.130 -CLASS C
395.131 -CLASS CAB
395.132 -CLASS CCompiler
395.133 -CLASS CCompilerError
395.134 -CLASS CDATASection
395.135 -CLASS CDLL
395.136 -CLASS CGIHTTPRequestHandler
395.137 -CLASS CGIHandler
395.138 -CLASS CGIXMLRPCRequestHandler
395.139 -CLASS CacheFTPHandler
395.140 -CLASS CallFunc
395.141 -CLASS CalledProcessError
395.142 -CLASS CannotSendHeader
395.143 -CLASS CannotSendRequest
395.144 -CLASS Canonizer
395.145 -CLASS CharacterData
395.146 -CLASS Charset
395.147 -CLASS CharsetError
395.148 -CLASS CheckList
395.149 -CLASS Childless
395.150 -CLASS Chunk
395.151 -CLASS Clamped
395.152 -CLASS Class
395.153 -CLASS ClassCodeGenerator
395.154 -CLASS ClassScope
395.155 -CLASS Cmd
395.156 -CLASS CodeGenerator
395.157 -CLASS Codec
395.158 -CLASS CodecRegistryError
395.159 -CLASS ComboBox
395.160 -CLASS Command
395.161 -CLASS CommandCompiler
395.162 -CLASS Comment
395.163 -CLASS Compare
395.164 -CLASS Comparison
395.165 -CLASS Compile
395.166 -CLASS CompileError
395.167 -CLASS Completer
395.168 -CLASS Complex
395.169 -CLASS ComponentItem
395.170 -CLASS Condition
395.171 -CLASS ConfigParser
395.172 -CLASS Connection
395.173 -CLASS Const
395.174 -CLASS ContentGenerator
395.175 -CLASS ContentHandler
395.176 -CLASS Context
395.177 -CLASS Continue
395.178 -CLASS Control
395.179 -CLASS ControlsWindow
395.180 -CLASS ConversionError
395.181 -CLASS Cookie
395.182 -CLASS CookieError
395.183 -CLASS CookieJar
395.184 -CLASS CookiePolicy
395.185 -CLASS CoverageResults
395.186 -CLASS Cursor
395.187 -CLASS CygwinCCompiler
395.188 -CLASS D
395.189 -CLASS DOMBuilder
395.190 -CLASS DOMEntityResolver
395.191 -CLASS DOMError
395.192 -CLASS DOMEventStream
395.193 -CLASS DOMException
395.194 -CLASS DOMImplementation
395.195 -CLASS DOMInputSource
395.196 -CLASS DOMStringSizeErr
395.197 -CLASS DTDHandler
395.198 -CLASS Data
395.199 -CLASS Database
395.200 -CLASS DatagramHandler
395.201 -CLASS DatagramRequestHandler
395.202 -CLASS DateTime
395.203 -CLASS DbfilenameShelf
395.204 -CLASS DebugRunner
395.205 -CLASS DebuggingServer
395.206 -CLASS Decimal
395.207 -CLASS DecimalException
395.208 -CLASS DeclHandler
395.209 -CLASS DecodedGenerator
395.210 -CLASS Decorators
395.211 -CLASS DefaultCookiePolicy
395.212 -CLASS DefaultHandler
395.213 -CLASS Delegator
395.214 -CLASS DeprecationWarning
395.215 -CLASS DeprecationWarning
395.216 -CLASS Dialect
395.217 -CLASS Dialog
395.218 -CLASS DialogWindow
395.219 -CLASS Dict
395.220 -CLASS DictMixin
395.221 -CLASS DictReader
395.222 -CLASS DictWriter
395.223 -CLASS Differ
395.224 -CLASS DirList
395.225 -CLASS DirSelectBox
395.226 -CLASS DirSelectDialog
395.227 -CLASS DirTree
395.228 -CLASS Directory
395.229 -CLASS Discard
395.230 -CLASS Distribution
395.231 -CLASS DistributionMetadata
395.232 -CLASS DistributionTestCase
395.233 -CLASS DistutilsArgError
395.234 -CLASS DistutilsClassError
395.235 -CLASS DistutilsError
395.236 -CLASS DistutilsExecError
395.237 -CLASS DistutilsFileError
395.238 -CLASS DistutilsGetoptError
395.239 -CLASS DistutilsInternalError
395.240 -CLASS DistutilsModuleError
395.241 -CLASS DistutilsOptionError
395.242 -CLASS DistutilsPlatformError
395.243 -CLASS DistutilsSetupError
395.244 -CLASS DistutilsTemplateError
395.245 -CLASS Div
395.246 -CLASS DivisionByZero
395.247 -CLASS Doc
395.248 -CLASS DocCGIXMLRPCRequestHandler
395.249 -CLASS DocTest
395.250 -CLASS DocTestFailure
395.251 -CLASS DocTestFinder
395.252 -CLASS DocTestParser
395.253 -CLASS DocTestRunner
395.254 -CLASS DocXMLRPCRequestHandler
395.255 -CLASS DocXMLRPCServer
395.256 -CLASS Document
395.257 -CLASS DocumentFragment
395.258 -CLASS DocumentHandler
395.259 -CLASS DocumentType
395.260 -CLASS DomstringSizeErr
395.261 -CLASS DumbWriter
395.262 -CLASS DummyCommand
395.263 -CLASS DuplicateSectionError
395.264 -CLASS DynLoadSuffixImporter
395.265 -CLASS EMXCCompiler
395.266 -CLASS EOFError
395.267 -CLASS EOFError
395.268 -CLASS ESISDocHandler
395.269 -CLASS Element
395.270 -CLASS ElementInfo
395.271 -CLASS ElementTree
395.272 -CLASS Ellipsis
395.273 -CLASS Empty
395.274 -CLASS EmptyNode
395.275 -CLASS EndOfBlock
395.276 -CLASS Entity
395.277 -CLASS EntityResolver
395.278 -CLASS Enum
395.279 -CLASS EnvironmentError
395.280 -CLASS EnvironmentError
395.281 -CLASS Error
395.282 -CLASS ErrorDuringImport
395.283 -CLASS ErrorHandler
395.284 -CLASS ErrorPrinter
395.285 -CLASS ErrorRaiser
395.286 -CLASS Event
395.287 -CLASS EventBroadcaster
395.288 -CLASS EventException
395.289 -CLASS ExFileSelectBox
395.290 -CLASS Example
395.291 -CLASS ExampleASTVisitor
395.292 -CLASS Exception
395.293 -CLASS Exception
395.294 -CLASS Exec
395.295 -CLASS ExitNow
395.296 -CLASS ExpatError
395.297 -CLASS ExpatParser
395.298 -CLASS Expression
395.299 -CLASS ExpressionCodeGenerator
395.300 -CLASS Extension
395.301 -CLASS F
395.302 -CLASS FTP
395.303 -CLASS FTPHandler
395.304 -CLASS Factory
395.305 -CLASS FancyGetopt
395.306 -CLASS FancyModuleLoader
395.307 -CLASS FancyURLopener
395.308 -CLASS Fault
395.309 -CLASS Feature
395.310 -CLASS FeedParser
395.311 -CLASS FieldStorage
395.312 -CLASS FileCookieJar
395.313 -CLASS FileEntry
395.314 -CLASS FileHandler
395.315 -CLASS FileIO
395.316 -CLASS FileInput
395.317 -CLASS FileList
395.318 -CLASS FileSelectBox
395.319 -CLASS FileWrapper
395.320 -CLASS Filter
395.321 -CLASS Filterer
395.322 -CLASS FingerHandler
395.323 -CLASS FirstHeaderLineIsContinuationD
395.324 -CLASS FloatingPointError
395.325 -CLASS FloatingPointError
395.326 -CLASS FloorDiv
395.327 -CLASS FlowGraph
395.328 -CLASS Folder
395.329 -CLASS Foo
395.330 -CLASS For
395.331 -CLASS ForkingMixIn
395.332 -CLASS ForkingTCPServer
395.333 -CLASS ForkingUDPServer
395.334 -CLASS Form
395.335 -CLASS FormContent
395.336 -CLASS FormContentDict
395.337 -CLASS Formatter
395.338 -CLASS Fraction
395.339 -CLASS From
395.340 -CLASS FtException
395.341 -CLASS Full
395.342 -CLASS FuncPtr
395.343 -CLASS Function
395.344 -CLASS FunctionCodeGenerator
395.345 -CLASS FunctionScope
395.346 -CLASS FunctionTestCase
395.347 -CLASS FutureParser
395.348 -CLASS FutureWarning
395.349 -CLASS FutureWarning
395.350 -CLASS GNUTranslations
395.351 -CLASS GenExpr
395.352 -CLASS GenExprFor
395.353 -CLASS GenExprIf
395.354 -CLASS GenExprInner
395.355 -CLASS GenExprScope
395.356 -CLASS Generator
395.357 -CLASS GeneratorExit
395.358 -CLASS GeneratorExit
395.359 -CLASS Getattr
395.360 -CLASS GetattrMagic
395.361 -CLASS GetoptError
395.362 -CLASS Global
395.363 -CLASS GopherError
395.364 -CLASS GopherHandler
395.365 -CLASS GridBag
395.366 -CLASS GzipFile
395.367 -CLASS HList
395.368 -CLASS HMAC
395.369 -CLASS HRESULT
395.370 -CLASS HTMLDoc
395.371 -CLASS HTMLParseError
395.372 -CLASS HTMLParser
395.373 -CLASS HTMLRepr
395.374 -CLASS HTTP
395.375 -CLASS HTTPBasicAuthHandler
395.376 -CLASS HTTPConnection
395.377 -CLASS HTTPCookieProcessor
395.378 -CLASS HTTPDefaultErrorHandler
395.379 -CLASS HTTPDigestAuthHandler
395.380 -CLASS HTTPError
395.381 -CLASS HTTPErrorProcessor
395.382 -CLASS HTTPException
395.383 -CLASS HTTPHandler
395.384 -CLASS HTTPPasswordMgr
395.385 -CLASS HTTPPasswordMgrWithDefaultReal
395.386 -CLASS HTTPRedirectHandler
395.387 -CLASS HTTPResponse
395.388 -CLASS HTTPSConnection
395.389 -CLASS HTTPSHandler
395.390 -CLASS HTTPServer
395.391 -CLASS Handler
395.392 -CLASS HandlerBase
395.393 -CLASS Header
395.394 -CLASS HeaderParseError
395.395 -CLASS HeaderParser
395.396 -CLASS Headers
395.397 -CLASS HelpFormatter
395.398 -CLASS Helper
395.399 -CLASS HierarchyRequestErr
395.400 -CLASS Hook
395.401 -CLASS Hooks
395.402 -CLASS HtmlDiff
395.403 -CLASS IC
395.404 -CLASS IMAP4
395.405 -CLASS IMAP4_SSL
395.406 -CLASS IMAP4_stream
395.407 -CLASS IOBase
395.408 -CLASS IOError
395.409 -CLASS IOError
395.410 -CLASS Identified
395.411 -CLASS If
395.412 -CLASS IfExp
395.413 -CLASS Ignore
395.414 -CLASS IllegalMonthError
395.415 -CLASS IllegalWeekdayError
395.416 -CLASS ImmutableSet
395.417 -CLASS ImpImporter
395.418 -CLASS ImpLoader
395.419 -CLASS Import
395.420 -CLASS ImportError
395.421 -CLASS ImportError
395.422 -CLASS ImportManager
395.423 -CLASS ImportWarning
395.424 -CLASS ImportWarning
395.425 -CLASS Importer
395.426 -CLASS ImproperConnectionState
395.427 -CLASS Incomplete
395.428 -CLASS IncompleteRead
395.429 -CLASS IncrementalDecoder
395.430 -CLASS IncrementalEncoder
395.431 -CLASS IncrementalNewlineDecoder
395.432 -CLASS IncrementalParser
395.433 -CLASS IndentedHelpFormatter
395.434 -CLASS IndexError
395.435 -CLASS IndexError
395.436 -CLASS IndexSizeErr
395.437 -CLASS Inexact
395.438 -CLASS IniParser
395.439 -CLASS InputOnly
395.440 -CLASS InputSource
395.441 -CLASS InsertionLoc
395.442 -CLASS InstallScriptsTestCase
395.443 -CLASS InstallTestCase
395.444 -CLASS Integral
395.445 -CLASS Interactive
395.446 -CLASS InteractiveCodeGenerator
395.447 -CLASS InteractiveConsole
395.448 -CLASS InteractiveInterpreter
395.449 -CLASS InterpFormContentDict
395.450 -CLASS InterpolationDepthError
395.451 -CLASS InterpolationError
395.452 -CLASS InterpolationSyntaxError
395.453 -CLASS IntlText
395.454 -CLASS IntlWritingCode
395.455 -CLASS InuseAttributeErr
395.456 -CLASS InvalidAccessErr
395.457 -CLASS InvalidCharacterErr
395.458 -CLASS InvalidModificationErr
395.459 -CLASS InvalidNodeTypeErr
395.460 -CLASS InvalidOperation
395.461 -CLASS InvalidStateErr
395.462 -CLASS InvalidURL
395.463 -CLASS Invert
395.464 -CLASS IsqlCmd
395.465 -CLASS IsqlExit
395.466 -CLASS IterableUserDict
395.467 -CLASS JSONDecoder
395.468 -CLASS JSONEncoder
395.469 -CLASS JavaSAXParser
395.470 -CLASS JoinableQueue
395.471 -CLASS JyDTDHandlerWrapper
395.472 -CLASS JyEntityResolverWrapper
395.473 -CLASS JyErrorHandlerWrapper
395.474 -CLASS JyInputSourceWrapper
395.475 -CLASS JythonCompiler
395.476 -CLASS JythonSignalHandler
395.477 -CLASS KeyError
395.478 -CLASS KeyError
395.479 -CLASS KeyboardInterrupt
395.480 -CLASS KeyboardInterrupt
395.481 -CLASS Keyword
395.482 -CLASS LOBTestCase
395.483 -CLASS LWPCookieJar
395.484 -CLASS LabelEntry
395.485 -CLASS LabelFrame
395.486 -CLASS Lambda
395.487 -CLASS LambdaScope
395.488 -CLASS LargeZipFile
395.489 -CLASS LeftShift
395.490 -CLASS LexicalHandler
395.491 -CLASS LexicalXMLGenerator
395.492 -CLASS LibError
395.493 -CLASS LibraryLoader
395.494 -CLASS LineAddrTable
395.495 -CLASS LinkError
395.496 -CLASS List
395.497 -CLASS ListComp
395.498 -CLASS ListCompFor
395.499 -CLASS ListCompIf
395.500 -CLASS ListNoteBook
395.501 -CLASS Listener
395.502 -CLASS LittleEndianStructure
395.503 -CLASS LoadError
395.504 -CLASS LocalNameFinder
395.505 -CLASS Location
395.506 -CLASS Locator
395.507 -CLASS Lock
395.508 -CLASS Log
395.509 -CLASS LogRecord
395.510 -CLASS Logger
395.511 -CLASS LoggingSilencer
395.512 -CLASS Logical
395.513 -CLASS LookupError
395.514 -CLASS LookupError
395.515 -CLASS LooseVersion
395.516 -CLASS MH
395.517 -CLASS MHMailbox
395.518 -CLASS MHMessage
395.519 -CLASS MIMEApplication
395.520 -CLASS MIMEAudio
395.521 -CLASS MIMEBase
395.522 -CLASS MIMEImage
395.523 -CLASS MIMEMessage
395.524 -CLASS MIMEMultipart
395.525 -CLASS MIMENonMultipart
395.526 -CLASS MIMEText
395.527 -CLASS MMDF
395.528 -CLASS MMDFMessage
395.529 -CLASS MSVCCompiler
395.530 -CLASS MWerksCompiler
395.531 -CLASS MacroExpander
395.532 -CLASS Mailbox
395.533 -CLASS Maildir
395.534 -CLASS MaildirMessage
395.535 -CLASS MailmanProxy
395.536 -CLASS MalformedHeaderDefect
395.537 -CLASS Manager
395.538 -CLASS Marshaller
395.539 -CLASS MemoryError
395.540 -CLASS MemoryError
395.541 -CLASS MemoryHandler
395.542 -CLASS Message
395.543 -CLASS MessageDefect
395.544 -CLASS MessageError
395.545 -CLASS MessageParseError
395.546 -CLASS MetadataTestCase
395.547 -CLASS Meter
395.548 -CLASS MimeWriter
395.549 -CLASS Mingw32CCompiler
395.550 -CLASS MiniApplication
395.551 -CLASS MiniFieldStorage
395.552 -CLASS MisplacedEnvelopeHeaderDefect
395.553 -CLASS MissingSectionHeaderError
395.554 -CLASS MmdfMailbox
395.555 -CLASS Mod
395.556 -CLASS Model
395.557 -CLASS Module
395.558 -CLASS ModuleCodeGenerator
395.559 -CLASS ModuleFinder
395.560 -CLASS ModuleImporter
395.561 -CLASS ModuleLoader
395.562 -CLASS ModuleScanner
395.563 -CLASS ModuleScope
395.564 -CLASS MozillaCookieJar
395.565 -CLASS Mul
395.566 -CLASS MultiCall
395.567 -CLASS MultiCallIterator
395.568 -CLASS MultiFile
395.569 -CLASS MultipartConversionError
395.570 -CLASS MultipartInvariantViolationDef
395.571 -CLASS MutableString
395.572 -CLASS MyClass
395.573 -CLASS MyTest
395.574 -CLASS NNTP
395.575 -CLASS NNTPDataError
395.576 -CLASS NNTPPermanentError
395.577 -CLASS NNTPProtocolError
395.578 -CLASS NNTPReplyError
395.579 -CLASS NNTPTemporaryError
395.580 -CLASS NProperty
395.581 -CLASS NTEventLogHandler
395.582 -CLASS NULL
395.583 -CLASS Name
395.584 -CLASS NameError
395.585 -CLASS NameError
395.586 -CLASS NamedNodeMap
395.587 -CLASS NamespaceErr
395.588 -CLASS NannyNag
395.589 -CLASS NestedScopeMixin
395.590 -CLASS Netrc
395.591 -CLASS NetrcParseError
395.592 -CLASS NewStyle
395.593 -CLASS NoBoundaryInMultipartDefect
395.594 -CLASS NoDataAllowedErr
395.595 -CLASS NoModificationAllowedErr
395.596 -CLASS NoOpMetaClass
395.597 -CLASS NoOptionError
395.598 -CLASS NoSectionError
395.599 -CLASS Node
395.600 -CLASS NodeFilter
395.601 -CLASS NodeTransformer
395.602 -CLASS NodeVisitor
395.603 -CLASS Not
395.604 -CLASS NotANumber
395.605 -CLASS NotConnected
395.606 -CLASS NotFoundErr
395.607 -CLASS NotImplementedError
395.608 -CLASS NotImplementedError
395.609 -CLASS NotSupportedErr
395.610 -CLASS Notation
395.611 -CLASS NoteBook
395.612 -CLASS NullFormatter
395.613 -CLASS NullImporter
395.614 -CLASS NullTranslations
395.615 -CLASS NullWriter
395.616 -CLASS Number
395.617 -CLASS OSError
395.618 -CLASS OSError
395.619 -CLASS OSSAudioError
395.620 -CLASS ObjectSpecifier
395.621 -CLASS OleDLL
395.622 -CLASS OpFinder
395.623 -CLASS OpenerDirector
395.624 -CLASS OptParseError
395.625 -CLASS Option
395.626 -CLASS OptionConflictError
395.627 -CLASS OptionContainer
395.628 -CLASS OptionDummy
395.629 -CLASS OptionError
395.630 -CLASS OptionGroup
395.631 -CLASS OptionMenu
395.632 -CLASS OptionParser
395.633 -CLASS OptionValueError
395.634 -CLASS Or
395.635 -CLASS OracleSPTest
395.636 -CLASS Ordinal
395.637 -CLASS OutputChecker
395.638 -CLASS Overflow
395.639 -CLASS OverflowError
395.640 -CLASS OverflowError
395.641 -CLASS POP3
395.642 -CLASS POP3_SSL
395.643 -CLASS Packer
395.644 -CLASS PanedWindow
395.645 -CLASS Panel
395.646 -CLASS Parser
395.647 -CLASS ParserBase
395.648 -CLASS ParserError
395.649 -CLASS ParsingError
395.650 -CLASS Pass
395.651 -CLASS Pattern
395.652 -CLASS Pdb
395.653 -CLASS PendingDeprecationWarning
395.654 -CLASS PendingDeprecationWarning
395.655 -CLASS PickleError
395.656 -CLASS Pickler
395.657 -CLASS PicklingError
395.658 -CLASS PlaceHolder
395.659 -CLASS Popen
395.660 -CLASS Popen3
395.661 -CLASS Popen4
395.662 -CLASS PopupMenu
395.663 -CLASS PortableUnixMailbox
395.664 -CLASS Power
395.665 -CLASS PreprocessError
395.666 -CLASS PrettyPrinter
395.667 -CLASS Print
395.668 -CLASS Printnl
395.669 -CLASS Process
395.670 -CLASS ProcessingInstruction
395.671 -CLASS Profile
395.672 -CLASS ProgressBar
395.673 -CLASS Prompt
395.674 -CLASS ProtocolError
395.675 -CLASS ProxyBasicAuthHandler
395.676 -CLASS ProxyDigestAuthHandler
395.677 -CLASS ProxyHandler
395.678 -CLASS PullDOM
395.679 -CLASS PureProxy
395.680 -CLASS PyCompileError
395.681 -CLASS PyDLL
395.682 -CLASS PyDialog
395.683 -CLASS PyFlowGraph
395.684 -CLASS PyHKEY
395.685 -CLASS PyZipFile
395.686 -CLASS QDPoint
395.687 -CLASS QDRectangle
395.688 -CLASS QName
395.689 -CLASS Queue
395.690 -CLASS RExec
395.691 -CLASS RGBColor
395.692 -CLASS RLock
395.693 -CLASS RadioButtonGroup
395.694 -CLASS Raise
395.695 -CLASS Random
395.696 -CLASS Range
395.697 -CLASS RangeException
395.698 -CLASS Rational
395.699 -CLASS RawConfigParser
395.700 -CLASS RawIOBase
395.701 -CLASS RawTurtle
395.702 -CLASS ReadOnlySequentialNamedNodeMap
395.703 -CLASS Real
395.704 -CLASS Record
395.705 -CLASS ReferenceError
395.706 -CLASS ReferenceError
395.707 -CLASS Repr
395.708 -CLASS Request
395.709 -CLASS ResponseError
395.710 -CLASS ResponseNotReady
395.711 -CLASS ResultSet
395.712 -CLASS ResultSetRow
395.713 -CLASS Return
395.714 -CLASS RightShift
395.715 -CLASS RobotFileParser
395.716 -CLASS RootLogger
395.717 -CLASS RotatingFileHandler
395.718 -CLASS Rounded
395.719 -CLASS Row
395.720 -CLASS RuntimeError
395.721 -CLASS RuntimeError
395.722 -CLASS RuntimeWarning
395.723 -CLASS RuntimeWarning
395.724 -CLASS SAX2DOM
395.725 -CLASS SAXException
395.726 -CLASS SAXNotRecognizedException
395.727 -CLASS SAXNotSupportedException
395.728 -CLASS SAXParseException
395.729 -CLASS SAXReaderNotAvailable
395.730 -CLASS SGMLParseError
395.731 -CLASS SGMLParser
395.732 -CLASS SMTP
395.733 -CLASS SMTPAuthenticationError
395.734 -CLASS SMTPConnectError
395.735 -CLASS SMTPDataError
395.736 -CLASS SMTPException
395.737 -CLASS SMTPHandler
395.738 -CLASS SMTPHeloError
395.739 -CLASS SMTPRecipientsRefused
395.740 -CLASS SMTPResponseException
395.741 -CLASS SMTPSenderRefused
395.742 -CLASS SMTPServer
395.743 -CLASS SMTPServerDisconnected
395.744 -CLASS SQLServerSPTest
395.745 -CLASS SQLTestCase
395.746 -CLASS SSLError
395.747 -CLASS SSLSocket
395.748 -CLASS ST
395.749 -CLASS SafeConfigParser
395.750 -CLASS SafeTransport
395.751 -CLASS Scanner
395.752 -CLASS Schema
395.753 -CLASS Scope
395.754 -CLASS Screen
395.755 -CLASS ScrolledCavas
395.756 -CLASS ScrolledText
395.757 -CLASS ScrolledWindow
395.758 -CLASS Select
395.759 -CLASS Semaphore
395.760 -CLASS SequenceMatcher
395.761 -CLASS SerialCookie
395.762 -CLASS Server
395.763 -CLASS ServerHTMLDoc
395.764 -CLASS ServerProxy
395.765 -CLASS Set
395.766 -CLASS SgmlopParser
395.767 -CLASS Shape
395.768 -CLASS Shelf
395.769 -CLASS SimpleCookie
395.770 -CLASS SimpleHTTPRequestHandler
395.771 -CLASS SimpleHandler
395.772 -CLASS SimpleLocator
395.773 -CLASS SimpleXMLRPCDispatcher
395.774 -CLASS SimpleXMLRPCRequestHandler
395.775 -CLASS SimpleXMLRPCServer
395.776 -CLASS Slice
395.777 -CLASS Sliceobj
395.778 -CLASS SlowParser
395.779 -CLASS SmartCookie
395.780 -CLASS Sniffer
395.781 -CLASS SocketHandler
395.782 -CLASS SocketType
395.783 -CLASS Stack
395.784 -CLASS StackDepthTracker
395.785 -CLASS StandardError
395.786 -CLASS StandardError
395.787 -CLASS StartBoundaryNotFoundDefect
395.788 -CLASS Stats
395.789 -CLASS StdButtonBox
395.790 -CLASS Stmt
395.791 -CLASS StopIteration
395.792 -CLASS StopIteration
395.793 -CLASS StopTokenizing
395.794 -CLASS Strange
395.795 -CLASS StreamConverter
395.796 -CLASS StreamHandler
395.797 -CLASS StreamReader
395.798 -CLASS StreamRequestHandler
395.799 -CLASS StreamWriter
395.800 -CLASS StrictVersion
395.801 -CLASS StringIO
395.802 -CLASS Struct
395.803 -CLASS Structure
395.804 -CLASS StyledText
395.805 -CLASS Sub
395.806 -CLASS SubPattern
395.807 -CLASS Subnormal
395.808 -CLASS Subscript
395.809 -CLASS SummaryInformation
395.810 -CLASS Super
395.811 -CLASS SuperSuper
395.812 -CLASS SvFormContentDict
395.813 -CLASS Symbol
395.814 -CLASS SymbolTable
395.815 -CLASS SymbolVisitor
395.816 -CLASS SyncManager
395.817 -CLASS SyntaxErr
395.818 -CLASS SyntaxError
395.819 -CLASS SyntaxError
395.820 -CLASS SyntaxErrorChecker
395.821 -CLASS SyntaxWarning
395.822 -CLASS SyntaxWarning
395.823 -CLASS SysLogHandler
395.824 -CLASS SystemError
395.825 -CLASS SystemError
395.826 -CLASS SystemExit
395.827 -CLASS SystemExit
395.828 -CLASS SystemRandom
395.829 -CLASS TCPServer
395.830 -CLASS TList
395.831 -CLASS TalkTo
395.832 -CLASS TarError
395.833 -CLASS TarFile
395.834 -CLASS TarInfo
395.835 -CLASS Telnet
395.836 -CLASS TempdirManager
395.837 -CLASS Template
395.838 -CLASS Test
395.839 -CLASS TestCase
395.840 -CLASS TestClass
395.841 -CLASS TestCrispinTorture
395.842 -CLASS TestDistribution
395.843 -CLASS TestLoader
395.844 -CLASS TestResult
395.845 -CLASS TestSuite
395.846 -CLASS TestThread
395.847 -CLASS TestXMLParser
395.848 -CLASS Testcase
395.849 -CLASS Tester
395.850 -CLASS Text
395.851 -CLASS TextDoc
395.852 -CLASS TextFile
395.853 -CLASS TextIOBase
395.854 -CLASS TextIOWrapper
395.855 -CLASS TextRepr
395.856 -CLASS TextTestRunner
395.857 -CLASS TextWrapper
395.858 -CLASS Textbox
395.859 -CLASS Thread
395.860 -CLASS ThreadingMixIn
395.861 -CLASS ThreadingTCPServer
395.862 -CLASS ThreadingUDPServer
395.863 -CLASS ThreadingUnixDatagramServer
395.864 -CLASS ThreadingUnixStreamServer
395.865 -CLASS TimedRotatingFileHandler
395.866 -CLASS Timer
395.867 -CLASS TitledHelpFormatter
395.868 -CLASS Tix
395.869 -CLASS Tk
395.870 -CLASS TokenError
395.871 -CLASS Tokenizer
395.872 -CLASS TortureBase
395.873 -CLASS Trace
395.874 -CLASS Transformer
395.875 -CLASS Transport
395.876 -CLASS Tree
395.877 -CLASS TreeBuilder
395.878 -CLASS TryExcept
395.879 -CLASS TryFinally
395.880 -CLASS Tuple
395.881 -CLASS TupleArg
395.882 -CLASS Turtle
395.883 -CLASS TurtleScreen
395.884 -CLASS Type
395.885 -CLASS TypeError
395.886 -CLASS TypeError
395.887 -CLASS TypeInfo
395.888 -CLASS UDPServer
395.889 -CLASS URLError
395.890 -CLASS URLopener
395.891 -CLASS UUID
395.892 -CLASS UnaryAdd
395.893 -CLASS UnarySub
395.894 -CLASS UnboundLocalError
395.895 -CLASS UnboundLocalError
395.896 -CLASS Underflow
395.897 -CLASS UnexpectedException
395.898 -CLASS UnicodeDecodeError
395.899 -CLASS UnicodeDecodeError
395.900 -CLASS UnicodeEncodeError
395.901 -CLASS UnicodeEncodeError
395.902 -CLASS UnicodeError
395.903 -CLASS UnicodeError
395.904 -CLASS UnicodeTranslateError
395.905 -CLASS UnicodeTranslateError
395.906 -CLASS UnicodeWarning
395.907 -CLASS UnicodeWarning
395.908 -CLASS UnimplementedFileMode
395.909 -CLASS Union
395.910 -CLASS UnixCCompiler
395.911 -CLASS UnixDatagramServer
395.912 -CLASS UnixMailbox
395.913 -CLASS UnixStreamServer
395.914 -CLASS Unknown
395.915 -CLASS UnknownFileError
395.916 -CLASS UnknownHandler
395.917 -CLASS UnknownProtocol
395.918 -CLASS UnknownTransferEncoding
395.919 -CLASS Unload
395.920 -CLASS Unmarshaller
395.921 -CLASS Unpacker
395.922 -CLASS Unpickler
395.923 -CLASS UnpicklingError
395.924 -CLASS UnspecifiedEventTypeErr
395.925 -CLASS UnsupportedOperation
395.926 -CLASS UserDataHandler
395.927 -CLASS UserDict
395.928 -CLASS UserList
395.929 -CLASS UserString
395.930 -CLASS UserWarning
395.931 -CLASS UserWarning
395.932 -CLASS ValidationErr
395.933 -CLASS ValueError
395.934 -CLASS ValueError
395.935 -CLASS Values
395.936 -CLASS Vec2D
395.937 -CLASS Vendor
395.938 -CLASS Version
395.939 -CLASS VersionPredicate
395.940 -CLASS View
395.941 -CLASS WSGIRequestHandler
395.942 -CLASS WSGIServer
395.943 -CLASS Warning
395.944 -CLASS Warning
395.945 -CLASS Wave_read
395.946 -CLASS Wave_write
395.947 -CLASS WeakKeyDictionary
395.948 -CLASS WeakValueDictionary
395.949 -CLASS While
395.950 -CLASS WichmannHill
395.951 -CLASS WinDLL
395.952 -CLASS Window
395.953 -CLASS WindowsError
395.954 -CLASS WindowsError
395.955 -CLASS With
395.956 -CLASS WrongDocumentErr
395.957 -CLASS X
395.958 -CLASS XMLFilter
395.959 -CLASS XMLFilterBase
395.960 -CLASS XMLFilterImpl
395.961 -CLASS XMLGenerator
395.962 -CLASS XMLParser
395.963 -CLASS XMLRPCDocGenerator
395.964 -CLASS XMLReader
395.965 -CLASS XMLTreeBuilder
395.966 -CLASS XmlParseErr
395.967 -CLASS Yield
395.968 -CLASS Yuck
395.969 -CLASS ZeroDivisionError
395.970 -CLASS ZeroDivisionError
395.971 -CLASS ZipFile
395.972 -CLASS ZipImportError
395.973 -CLASS ZipInfo
395.974 -CLASS _CData [PROTECTE
395.975 -CLASS _FuncPtr [PROTECTE
395.976 -CLASS _SimpleCData [PROTECTE
395.977 -CLASS _posixfile_
395.978 -CLASS array
395.979 -CLASS async_chat
395.980 -CLASS bdist
395.981 -CLASS bdist_dumb
395.982 -CLASS bdist_msi
395.983 -CLASS bdist_rpm
395.984 -CLASS bdist_wininst
395.985 -CLASS bool
395.986 -CLASS bsddbobject
395.987 -CLASS build
395.988 -CLASS build_clib
395.989 -CLASS build_ext
395.990 -CLASS build_py
395.991 -CLASS build_scripts
395.992 -CLASS c_bool
395.993 -CLASS c_byte
395.994 -CLASS c_char
395.995 -CLASS c_char_p
395.996 -CLASS c_double
395.997 -CLASS c_float
395.998 -CLASS c_int
395.999 -CLASS c_int16
395.1000 -CLASS c_int32
395.1001 -CLASS c_int64
395.1002 -CLASS c_int8
395.1003 -CLASS c_long
395.1004 -CLASS c_longdouble
395.1005 -CLASS c_longlong
395.1006 -CLASS c_short
395.1007 -CLASS c_size_t
395.1008 -CLASS c_ubyte
395.1009 -CLASS c_uint
395.1010 -CLASS c_uint16
395.1011 -CLASS c_uint32
395.1012 -CLASS c_uint64
395.1013 -CLASS c_uint8
395.1014 -CLASS c_ulong
395.1015 -CLASS c_ulonglong
395.1016 -CLASS c_ushort
395.1017 -CLASS c_void_p
395.1018 -CLASS c_wchar
395.1019 -CLASS c_wchar_p
395.1020 -CLASS class
395.1021 -CLASS class
395.1022 -CLASS clean
395.1023 -CLASS closing
395.1024 -CLASS complex
395.1025 -CLASS compressobj
395.1026 -CLASS config
395.1027 -CLASS container
395.1028 -CLASS container
395.1029 -CLASS contextmanager
395.1030 -CLASS contextmanager
395.1031 -CLASS controller
395.1032 -CLASS date
395.1033 -CLASS datetime
395.1034 -CLASS dbexts
395.1035 -CLASS dbextsTestCase
395.1036 -CLASS dbhash
395.1037 -CLASS decompressobj
395.1038 -CLASS deque
395.1039 -CLASS dict
395.1040 -CLASS dict
395.1041 -CLASS dircmp
395.1042 -CLASS dispatcher
395.1043 -CLASS dispatcher_with_send
395.1044 -CLASS dl
395.1045 -CLASS error
395.1046 -CLASS error_data
395.1047 -CLASS error_proto
395.1048 -CLASS error_reply
395.1049 -CLASS excel
395.1050 -CLASS excel_tab
395.1051 -CLASS executor
395.1052 -CLASS fifo
395.1053 -CLASS file
395.1054 -CLASS file
395.1055 -CLASS file_dispatcher
395.1056 -CLASS file_wrapper
395.1057 -CLASS float
395.1058 -CLASS float
395.1059 -CLASS foo
395.1060 -CLASS gaierror
395.1061 -CLASS herror
395.1062 -CLASS install
395.1063 -CLASS install_data
395.1064 -CLASS install_egg_info
395.1065 -CLASS install_headers
395.1066 -CLASS install_lib
395.1067 -CLASS install_misc
395.1068 -CLASS install_scripts
395.1069 -CLASS instance
395.1070 -CLASS instance
395.1071 -CLASS int
395.1072 -CLASS iterator
395.1073 -CLASS iterator
395.1074 -CLASS list
395.1075 -CLASS local
395.1076 -CLASS lock
395.1077 -CLASS long
395.1078 -CLASS main
395.1079 -CLASS mbox
395.1080 -CLASS mboxMessage
395.1081 -CLASS mllib
395.1082 -CLASS mmap
395.1083 -CLASS multiprocessing.Pool
395.1084 -CLASS mutex
395.1085 -CLASS mxODBCProxy
395.1086 -CLASS netrc
395.1087 -CLASS object
395.1088 -CLASS object
395.1089 -CLASS oss_audio_device
395.1090 -CLASS oss_mixer_device
395.1091 -CLASS poll
395.1092 -CLASS py_object
395.1093 -CLASS register
395.1094 -CLASS scheduler
395.1095 -CLASS sdist
395.1096 -CLASS set
395.1097 -CLASS set
395.1098 -CLASS shlex
395.1099 -CLASS simple_producer
395.1100 -CLASS socket
395.1101 -CLASS stat_result
395.1102 -CLASS str
395.1103 -CLASS str
395.1104 -CLASS test_dist
395.1105 -CLASS test_zxjdbc
395.1106 -CLASS time
395.1107 -CLASS timedelta
395.1108 -CLASS timeout
395.1109 -CLASS tixCommand
395.1110 -CLASS tmxxx
395.1111 -CLASS tuple
395.1112 -CLASS tzinfo
395.1113 -CLASS unicode
395.1114 -CLASS unicode
395.1115 -CLASS upload
395.1116 -CLASS window
395.1117 -CLASS xmlparser
395.1118 -CLASS zipimporter
395.1119 -CLASS zxAPITestCase
395.1120 -CLASS zxCoreTestCase
395.1121 -CLASS zxJDBCTestCase
395.1122 -METHOD __import__(name, globals, loca
395.1123 -METHOD abs(x)
395.1124 -METHOD all(iterable)
395.1125 -METHOD any(iterable)
395.1126 -METHOD ---apply(function, args, ke---
395.1127 -METHOD basestring()
395.1128 -METHOD bin(x)
395.1129 -METHOD bool(x)
395.1130 -METHOD buffer(object, offset, size)
395.1131 -METHOD callable(object)
395.1132 -METHOD chr(i)
395.1133 -METHOD classmethod(function)
395.1134 -METHOD cmp(x, y)
395.1135 -METHOD coerce(x, y)
395.1136 -METHOD compile(source, filename, mode
395.1137 -METHOD complex(real, imag)
395.1138 -METHOD delattr(object, name)
395.1139 -METHOD dict(arg)
395.1140 -METHOD dir(object)
395.1141 -METHOD divmod(a, b)
395.1142 -METHOD enumerate(sequence, start)
395.1143 -METHOD eval(expression, globals, loca
395.1144 -METHOD execfile(filename, globals, lo
395.1145 -METHOD exit(code)
395.1146 -METHOD file(filename, mode, bufsize)
395.1147 -METHOD filter(function, iterable)
395.1148 -METHOD float(x)
395.1149 -METHOD frozenset(iterable)
395.1150 -METHOD getattr(object, name, default)
395.1151 -METHOD globals()
395.1152 -METHOD hasattr(object, name)
395.1153 -METHOD hash(object)
395.1154 -METHOD help(object)
395.1155 -METHOD hex(x)
395.1156 -METHOD id(object)
395.1157 -METHOD input(prompt)
395.1158 -METHOD int(x, radix)
395.1159 -METHOD intern(string)
395.1160 -METHOD isinstance(object, classinfo)
395.1161 -METHOD issubclass(class, classinfo)
395.1162 -METHOD iter(o, sentinel)
395.1163 -METHOD len(s)
395.1164 -METHOD list(iterable)
395.1165 -METHOD locals()
395.1166 -METHOD long(x, radix)
395.1167 -METHOD map(function, iterable)
395.1168 -METHOD max(iterable, argskey)
395.1169 -METHOD min(iterable, argskey)
395.1170 -METHOD next(iterator, default)
395.1171 -METHOD object()
395.1172 -METHOD oct(x)
395.1173 -METHOD open(filename, mode, bufsize)
395.1174 -METHOD ord(c)
395.1175 -METHOD pow(x, y, z)
395.1176 -METHOD print(object, sep, end, file)
395.1177 -METHOD property(fget, fset, fdel, doc
395.1178 -METHOD quit(code)
395.1179 -METHOD range(start, stop, step)
395.1180 -METHOD raw_input(prompt)
395.1181 -METHOD reduce(function, iterable, ini
395.1182 -METHOD reload(module)
395.1183 -METHOD repr(object)
395.1184 -METHOD reversed(seq)
395.1185 -METHOD round(x, n)
395.1186 -METHOD set(iterable)
395.1187 -METHOD setattr(object, name, value)
395.1188 -METHOD slice(start, stop, step)
395.1189 -METHOD sorted(iterable, cmp, key, rev
395.1190 -METHOD staticmethod(function)
395.1191 -METHOD str(object)
395.1192 -METHOD sum(iterable, start)
395.1193 -METHOD super(type, object-or-type)
395.1194 -METHOD tuple(iterable)
395.1195 -METHOD type(name, bases, dict)
395.1196 -METHOD type(object)
395.1197 -METHOD unichr(i)
395.1198 -METHOD unicode(object, encoding, erro
395.1199 -METHOD vars(object)
395.1200 -METHOD xrange(start, stop, step)
395.1201 -METHOD zip(iterable)
395.1202 -VARIABLE Ellipsis
395.1203 -VARIABLE False
395.1204 -VARIABLE None
395.1205 -VARIABLE NotImplemented
395.1206 -VARIABLE True
395.1207 -VARIABLE __debug__
395.1208 -VARIABLE copyright
395.1209 -KEYWORD and
395.1210 -KEYWORD as
395.1211 -KEYWORD assert
395.1212 -KEYWORD break
395.1213 -KEYWORD class
395.1214 -KEYWORD continue
395.1215 -KEYWORD def
395.1216 -KEYWORD del
395.1217 -KEYWORD elif
395.1218 -KEYWORD else
395.1219 -KEYWORD except
395.1220 -KEYWORD exec
395.1221 -KEYWORD finally
395.1222 -KEYWORD for
395.1223 -KEYWORD from
395.1224 -KEYWORD global
395.1225 -KEYWORD if
395.1226 -KEYWORD import
395.1227 -KEYWORD in
395.1228 -KEYWORD is
395.1229 -KEYWORD lambda
395.1230 -KEYWORD not
395.1231 -KEYWORD or
395.1232 -KEYWORD pass
395.1233 -KEYWORD print
395.1234 -KEYWORD raise
395.1235 -KEYWORD return
395.1236 -KEYWORD try
395.1237 -KEYWORD while
395.1238 -KEYWORD with
395.1239 -KEYWORD yield
396.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testLocals7.completion Sun Jan 04 13:11:53 2015 -0600
396.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
396.3 @@ -1,12 +0,0 @@
396.4 -Code completion result for source line:
396.5 -print t|oplevelvar2
396.6 -(QueryType=COMPLETION, NameKind=PREFIX)
396.7 -VARIABLE toplevelvar
396.8 -VARIABLE toplevelvar2
396.9 -VARIABLE toplevelvar3
396.10 -VARIABLE toplevelvar4
396.11 -------------------------------------
396.12 -METHOD tuple(iterable)
396.13 -METHOD type(name, bases, dict)
396.14 -METHOD type(object)
396.15 -KEYWORD try
397.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testMarks4.occurrences Sun Jan 04 13:11:53 2015 -0600
397.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
397.3 @@ -1,3 +0,0 @@
397.4 -def |>MARK_OCCURRENCES:myfunc<|(funcparam):
397.5 - x = |>MARK_OCCURRENCES:myf^unc<|
397.6 - |>MARK_OCCURRENCES:myfunc<|(5)
398.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testMarks5.occurrences Sun Jan 04 13:11:53 2015 -0600
398.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
398.3 @@ -1,2 +0,0 @@
398.4 -import |>MARK_OCCURRENCES:m^odule1<|
398.5 - |>MARK_OCCURRENCES:module1<|.x
399.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testMarks6.occurrences Sun Jan 04 13:11:53 2015 -0600
399.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
399.3 @@ -1,2 +0,0 @@
399.4 -import module3 as |>MARK_OCCURRENCES:modu^le4<|
399.5 - |>MARK_OCCURRENCES:module4<|.y
400.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testMarks7.occurrences Sun Jan 04 13:11:53 2015 -0600
400.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
400.3 @@ -1,2 +0,0 @@
400.4 -|>MARK_OCCURRENCES:toplevelv^ar2<| = 2
400.5 - print |>MARK_OCCURRENCES:toplevelvar2<|
401.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testMarks8.occurrences Sun Jan 04 13:11:53 2015 -0600
401.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
401.3 @@ -1,2 +0,0 @@
401.4 - def mymethod(self,param1,|>MARK_OCCURRENCES:pa^ram2<|):
401.5 - print |>MARK_OCCURRENCES:param2<|
402.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testRename4.rename Sun Jan 04 13:11:53 2015 -0600
402.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
402.3 @@ -1,2 +0,0 @@
402.4 -12: |>toplevelvar4<| = 6
402.5 -13: print |>toplevelvar4<|
403.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testRename5.rename Sun Jan 04 13:11:53 2015 -0600
403.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
403.3 @@ -1,1 +0,0 @@
403.4 -Requires Interactive Refactoring
404.1 --- a/python.editor/test/unit/data/testfiles/occurrences2.py.testRename6.rename Sun Jan 04 13:11:53 2015 -0600
404.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
404.3 @@ -1,1 +0,0 @@
404.4 -Requires Interactive Refactoring
405.1 --- a/python.editor/test/unit/data/testfiles/old-decorators1.py Sun Jan 04 13:11:53 2015 -0600
405.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
405.3 @@ -1,4 +0,0 @@
405.4 -def foo(self):
405.5 - perform method operation
405.6 -foo = classmethod(foo)
405.7 -
406.1 --- a/python.editor/test/unit/data/testfiles/old-decorators1.py.scopes Sun Jan 04 13:11:53 2015 -0600
406.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
406.3 @@ -1,11 +0,0 @@
406.4 -=============================================
406.5 -<file-top>: Module : OffsetRange[0,66>
406.6 -classmethod [read][called][UNRESOLVED][node=Name]
406.7 -foo [bound][function][def][read][node=FunctionDef]
406.8 -
406.9 - =============================================
406.10 - foo: FunctionDef : OffsetRange[0,44>
406.11 - method [free][read][node=Name]
406.12 - perform [free][read][node=Name]
406.13 - self [bound][param][data][unused][node=Name]
406.14 -
407.1 --- a/python.editor/test/unit/data/testfiles/old-decorators2.py Sun Jan 04 13:11:53 2015 -0600
407.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
407.3 @@ -1,5 +0,0 @@
407.4 -def foo(cls):
407.5 - pass
407.6 -foo = synchronized(lock)(foo)
407.7 -foo = classmethod(foo)
407.8 -
408.1 --- a/python.editor/test/unit/data/testfiles/old-decorators2.py.scopes Sun Jan 04 13:11:53 2015 -0600
408.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
408.3 @@ -1,11 +0,0 @@
408.4 -=============================================
408.5 -<file-top>: Module : OffsetRange[0,75>
408.6 -classmethod [read][called][UNRESOLVED][node=Name]
408.7 -foo [bound][function][def][read][node=FunctionDef]
408.8 -lock [read][UNRESOLVED][node=Name]
408.9 -synchronized [read][called][UNRESOLVED][node=Name]
408.10 -
408.11 - =============================================
408.12 - foo: FunctionDef : OffsetRange[0,23>
408.13 - cls [bound][param][data][unused][node=Name]
408.14 -
409.1 --- a/python.editor/test/unit/data/testfiles/org.py Sun Jan 04 13:11:53 2015 -0600
409.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
409.3 @@ -1,1 +0,0 @@
409.4 -from or
410.1 --- a/python.editor/test/unit/data/testfiles/org.py.testKeywordFrom.completion Sun Jan 04 13:11:53 2015 -0600
410.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
410.3 @@ -1,5 +0,0 @@
410.4 -Code completion result for source line:
410.5 -from or|
410.6 -(QueryType=COMPLETION, NameKind=PREFIX)
410.7 -------------------------------------
410.8 -KEYWORD org
411.1 --- a/python.editor/test/unit/data/testfiles/os.py Sun Jan 04 13:11:53 2015 -0600
411.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
411.3 @@ -1,738 +0,0 @@
411.4 -r"""OS routines for Mac, NT, or Posix depending on what system we're on.
411.5 -
411.6 -This exports:
411.7 - - all functions from posix, nt, os2, mac, or ce, e.g. unlink, stat, etc.
411.8 - - os.path is one of the modules posixpath, ntpath, or macpath
411.9 - - os.name is 'posix', 'nt', 'os2', 'mac', 'ce' or 'riscos'
411.10 - - os.curdir is a string representing the current directory ('.' or ':')
411.11 - - os.pardir is a string representing the parent directory ('..' or '::')
411.12 - - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
411.13 - - os.extsep is the extension separator ('.' or '/')
411.14 - - os.altsep is the alternate pathname separator (None or '/')
411.15 - - os.pathsep is the component separator used in $PATH etc
411.16 - - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
411.17 - - os.defpath is the default search path for executables
411.18 - - os.devnull is the file path of the null device ('/dev/null', etc.)
411.19 -
411.20 -Programs that import and use 'os' stand a better chance of being
411.21 -portable between different platforms. Of course, they must then
411.22 -only use functions that are defined by all platforms (e.g., unlink
411.23 -and opendir), and leave all pathname manipulation to os.path
411.24 -(e.g., split and join).
411.25 -"""
411.26 -
411.27 -#'
411.28 -
411.29 -import sys
411.30 -
411.31 -_names = sys.builtin_module_names
411.32 -
411.33 -# Note: more names are added to __all__ later.
411.34 -__all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep",
411.35 - "defpath", "name", "path", "devnull",
411.36 - "SEEK_SET", "SEEK_CUR", "SEEK_END"]
411.37 -
411.38 -def _get_exports_list(module):
411.39 - try:
411.40 - return list(module.__all__)
411.41 - except AttributeError:
411.42 - return [n for n in dir(module) if n[0] != '_']
411.43 -
411.44 -if 'posix' in _names:
411.45 - name = 'posix'
411.46 - linesep = '\n'
411.47 - from posix import *
411.48 - try:
411.49 - from posix import _exit
411.50 - except ImportError:
411.51 - pass
411.52 - import posixpath as path
411.53 -
411.54 - import posix
411.55 - __all__.extend(_get_exports_list(posix))
411.56 - del posix
411.57 -
411.58 -elif 'nt' in _names:
411.59 - name = 'nt'
411.60 - linesep = '\r\n'
411.61 - from nt import *
411.62 - try:
411.63 - from nt import _exit
411.64 - except ImportError:
411.65 - pass
411.66 - import ntpath as path
411.67 -
411.68 - import nt
411.69 - __all__.extend(_get_exports_list(nt))
411.70 - del nt
411.71 -
411.72 -elif 'os2' in _names:
411.73 - name = 'os2'
411.74 - linesep = '\r\n'
411.75 - from os2 import *
411.76 - try:
411.77 - from os2 import _exit
411.78 - except ImportError:
411.79 - pass
411.80 - if sys.version.find('EMX GCC') == -1:
411.81 - import ntpath as path
411.82 - else:
411.83 - import os2emxpath as path
411.84 - from _emx_link import link
411.85 -
411.86 - import os2
411.87 - __all__.extend(_get_exports_list(os2))
411.88 - del os2
411.89 -
411.90 -elif 'mac' in _names:
411.91 - name = 'mac'
411.92 - linesep = '\r'
411.93 - from mac import *
411.94 - try:
411.95 - from mac import _exit
411.96 - except ImportError:
411.97 - pass
411.98 - import macpath as path
411.99 -
411.100 - import mac
411.101 - __all__.extend(_get_exports_list(mac))
411.102 - del mac
411.103 -
411.104 -elif 'ce' in _names:
411.105 - name = 'ce'
411.106 - linesep = '\r\n'
411.107 - from ce import *
411.108 - try:
411.109 - from ce import _exit
411.110 - except ImportError:
411.111 - pass
411.112 - # We can use the standard Windows path.
411.113 - import ntpath as path
411.114 -
411.115 - import ce
411.116 - __all__.extend(_get_exports_list(ce))
411.117 - del ce
411.118 -
411.119 -elif 'riscos' in _names:
411.120 - name = 'riscos'
411.121 - linesep = '\n'
411.122 - from riscos import *
411.123 - try:
411.124 - from riscos import _exit
411.125 - except ImportError:
411.126 - pass
411.127 - import riscospath as path
411.128 -
411.129 - import riscos
411.130 - __all__.extend(_get_exports_list(riscos))
411.131 - del riscos
411.132 -
411.133 -else:
411.134 - raise ImportError, 'no os specific module found'
411.135 -
411.136 -sys.modules['os.path'] = path
411.137 -from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,
411.138 - devnull)
411.139 -
411.140 -del _names
411.141 -
411.142 -# Python uses fixed values for the SEEK_ constants; they are mapped
411.143 -# to native constants if necessary in posixmodule.c
411.144 -SEEK_SET = 0
411.145 -SEEK_CUR = 1
411.146 -SEEK_END = 2
411.147 -
411.148 -#'
411.149 -
411.150 -# Super directory utilities.
411.151 -# (Inspired by Eric Raymond; the doc strings are mostly his)
411.152 -
411.153 -def makedirs(name, mode=0777):
411.154 - """makedirs(path [, mode=0777])
411.155 -
411.156 - Super-mkdir; create a leaf directory and all intermediate ones.
411.157 - Works like mkdir, except that any intermediate path segment (not
411.158 - just the rightmost) will be created if it does not exist. This is
411.159 - recursive.
411.160 -
411.161 - """
411.162 - from errno import EEXIST
411.163 - head, tail = path.split(name)
411.164 - if not tail:
411.165 - head, tail = path.split(head)
411.166 - if head and tail and not path.exists(head):
411.167 - try:
411.168 - makedirs(head, mode)
411.169 - except OSError, e:
411.170 - # be happy if someone already created the path
411.171 - if e.errno != EEXIST:
411.172 - raise
411.173 - if tail == curdir: # xxx/newdir/. exists if xxx/newdir exists
411.174 - return
411.175 - mkdir(name, mode)
411.176 -
411.177 -def removedirs(name):
411.178 - """removedirs(path)
411.179 -
411.180 - Super-rmdir; remove a leaf directory and all empty intermediate
411.181 - ones. Works like rmdir except that, if the leaf directory is
411.182 - successfully removed, directories corresponding to rightmost path
411.183 - segments will be pruned away until either the whole path is
411.184 - consumed or an error occurs. Errors during this latter phase are
411.185 - ignored -- they generally mean that a directory was not empty.
411.186 -
411.187 - """
411.188 - rmdir(name)
411.189 - head, tail = path.split(name)
411.190 - if not tail:
411.191 - head, tail = path.split(head)
411.192 - while head and tail:
411.193 - try:
411.194 - rmdir(head)
411.195 - except error:
411.196 - break
411.197 - head, tail = path.split(head)
411.198 -
411.199 -def renames(old, new):
411.200 - """renames(old, new)
411.201 -
411.202 - Super-rename; create directories as necessary and delete any left
411.203 - empty. Works like rename, except creation of any intermediate
411.204 - directories needed to make the new pathname good is attempted
411.205 - first. After the rename, directories corresponding to rightmost
411.206 - path segments of the old name will be pruned way until either the
411.207 - whole path is consumed or a nonempty directory is found.
411.208 -
411.209 - Note: this function can fail with the new directory structure made
411.210 - if you lack permissions needed to unlink the leaf directory or
411.211 - file.
411.212 -
411.213 - """
411.214 - head, tail = path.split(new)
411.215 - if head and tail and not path.exists(head):
411.216 - makedirs(head)
411.217 - rename(old, new)
411.218 - head, tail = path.split(old)
411.219 - if head and tail:
411.220 - try:
411.221 - removedirs(head)
411.222 - except error:
411.223 - pass
411.224 -
411.225 -__all__.extend(["makedirs", "removedirs", "renames"])
411.226 -
411.227 -def walk(top, topdown=True, onerror=None):
411.228 - """Directory tree generator.
411.229 -
411.230 - For each directory in the directory tree rooted at top (including top
411.231 - itself, but excluding '.' and '..'), yields a 3-tuple
411.232 -
411.233 - dirpath, dirnames, filenames
411.234 -
411.235 - dirpath is a string, the path to the directory. dirnames is a list of
411.236 - the names of the subdirectories in dirpath (excluding '.' and '..').
411.237 - filenames is a list of the names of the non-directory files in dirpath.
411.238 - Note that the names in the lists are just names, with no path components.
411.239 - To get a full path (which begins with top) to a file or directory in
411.240 - dirpath, do os.path.join(dirpath, name).
411.241 -
411.242 - If optional arg 'topdown' is true or not specified, the triple for a
411.243 - directory is generated before the triples for any of its subdirectories
411.244 - (directories are generated top down). If topdown is false, the triple
411.245 - for a directory is generated after the triples for all of its
411.246 - subdirectories (directories are generated bottom up).
411.247 -
411.248 - When topdown is true, the caller can modify the dirnames list in-place
411.249 - (e.g., via del or slice assignment), and walk will only recurse into the
411.250 - subdirectories whose names remain in dirnames; this can be used to prune
411.251 - the search, or to impose a specific order of visiting. Modifying
411.252 - dirnames when topdown is false is ineffective, since the directories in
411.253 - dirnames have already been generated by the time dirnames itself is
411.254 - generated.
411.255 -
411.256 - By default errors from the os.listdir() call are ignored. If
411.257 - optional arg 'onerror' is specified, it should be a function; it
411.258 - will be called with one argument, an os.error instance. It can
411.259 - report the error to continue with the walk, or raise the exception
411.260 - to abort the walk. Note that the filename is available as the
411.261 - filename attribute of the exception object.
411.262 -
411.263 - Caution: if you pass a relative pathname for top, don't change the
411.264 - current working directory between resumptions of walk. walk never
411.265 - changes the current directory, and assumes that the client doesn't
411.266 - either.
411.267 -
411.268 - Example:
411.269 -
411.270 - from os.path import join, getsize
411.271 - for root, dirs, files in walk('python/Lib/email'):
411.272 - print root, "consumes",
411.273 - print sum([getsize(join(root, name)) for name in files]),
411.274 - print "bytes in", len(files), "non-directory files"
411.275 - if 'CVS' in dirs:
411.276 - dirs.remove('CVS') # don't visit CVS directories
411.277 - """
411.278 -
411.279 - from os.path import join, isdir, islink
411.280 -
411.281 - # We may not have read permission for top, in which case we can't
411.282 - # get a list of the files the directory contains. os.path.walk
411.283 - # always suppressed the exception then, rather than blow up for a
411.284 - # minor reason when (say) a thousand readable directories are still
411.285 - # left to visit. That logic is copied here.
411.286 - try:
411.287 - # Note that listdir and error are globals in this module due
411.288 - # to earlier import-*.
411.289 - names = listdir(top)
411.290 - except error, err:
411.291 - if onerror is not None:
411.292 - onerror(err)
411.293 - return
411.294 -
411.295 - dirs, nondirs = [], []
411.296 - for name in names:
411.297 - if isdir(join(top, name)):
411.298 - dirs.append(name)
411.299 - else:
411.300 - nondirs.append(name)
411.301 -
411.302 - if topdown:
411.303 - yield top, dirs, nondirs
411.304 - for name in dirs:
411.305 - path = join(top, name)
411.306 - if not islink(path):
411.307 - for x in walk(path, topdown, onerror):
411.308 - yield x
411.309 - if not topdown:
411.310 - yield top, dirs, nondirs
411.311 -
411.312 -__all__.append("walk")
411.313 -
411.314 -# Make sure os.environ exists, at least
411.315 -try:
411.316 - environ
411.317 -except NameError:
411.318 - environ = {}
411.319 -
411.320 -def execl(file, *args):
411.321 - """execl(file, *args)
411.322 -
411.323 - Execute the executable file with argument list args, replacing the
411.324 - current process. """
411.325 - execv(file, args)
411.326 -
411.327 -def execle(file, *args):
411.328 - """execle(file, *args, env)
411.329 -
411.330 - Execute the executable file with argument list args and
411.331 - environment env, replacing the current process. """
411.332 - env = args[-1]
411.333 - execve(file, args[:-1], env)
411.334 -
411.335 -def execlp(file, *args):
411.336 - """execlp(file, *args)
411.337 -
411.338 - Execute the executable file (which is searched for along $PATH)
411.339 - with argument list args, replacing the current process. """
411.340 - execvp(file, args)
411.341 -
411.342 -def execlpe(file, *args):
411.343 - """execlpe(file, *args, env)
411.344 -
411.345 - Execute the executable file (which is searched for along $PATH)
411.346 - with argument list args and environment env, replacing the current
411.347 - process. """
411.348 - env = args[-1]
411.349 - execvpe(file, args[:-1], env)
411.350 -
411.351 -def execvp(file, args):
411.352 - """execp(file, args)
411.353 -
411.354 - Execute the executable file (which is searched for along $PATH)
411.355 - with argument list args, replacing the current process.
411.356 - args may be a list or tuple of strings. """
411.357 - _execvpe(file, args)
411.358 -
411.359 -def execvpe(file, args, env):
411.360 - """execvpe(file, args, env)
411.361 -
411.362 - Execute the executable file (which is searched for along $PATH)
411.363 - with argument list args and environment env , replacing the
411.364 - current process.
411.365 - args may be a list or tuple of strings. """
411.366 - _execvpe(file, args, env)
411.367 -
411.368 -__all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"])
411.369 -
411.370 -def _execvpe(file, args, env=None):
411.371 - from errno import ENOENT, ENOTDIR
411.372 -
411.373 - if env is not None:
411.374 - func = execve
411.375 - argrest = (args, env)
411.376 - else:
411.377 - func = execv
411.378 - argrest = (args,)
411.379 - env = environ
411.380 -
411.381 - head, tail = path.split(file)
411.382 - if head:
411.383 - func(file, *argrest)
411.384 - return
411.385 - if 'PATH' in env:
411.386 - envpath = env['PATH']
411.387 - else:
411.388 - envpath = defpath
411.389 - PATH = envpath.split(pathsep)
411.390 - saved_exc = None
411.391 - saved_tb = None
411.392 - for dir in PATH:
411.393 - fullname = path.join(dir, file)
411.394 - try:
411.395 - func(fullname, *argrest)
411.396 - except error, e:
411.397 - tb = sys.exc_info()[2]
411.398 - if (e.errno != ENOENT and e.errno != ENOTDIR
411.399 - and saved_exc is None):
411.400 - saved_exc = e
411.401 - saved_tb = tb
411.402 - if saved_exc:
411.403 - raise error, saved_exc, saved_tb
411.404 - raise error, e, tb
411.405 -
411.406 -# Change environ to automatically call putenv() if it exists
411.407 -try:
411.408 - # This will fail if there's no putenv
411.409 - putenv
411.410 -except NameError:
411.411 - pass
411.412 -else:
411.413 - import UserDict
411.414 -
411.415 - # Fake unsetenv() for Windows
411.416 - # not sure about os2 here but
411.417 - # I'm guessing they are the same.
411.418 -
411.419 - if name in ('os2', 'nt'):
411.420 - def unsetenv(key):
411.421 - putenv(key, "")
411.422 -
411.423 - if name == "riscos":
411.424 - # On RISC OS, all env access goes through getenv and putenv
411.425 - from riscosenviron import _Environ
411.426 - elif name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE
411.427 - # But we store them as upper case
411.428 - class _Environ(UserDict.IterableUserDict):
411.429 - def __init__(self, environ):
411.430 - UserDict.UserDict.__init__(self)
411.431 - data = self.data
411.432 - for k, v in environ.items():
411.433 - data[k.upper()] = v
411.434 - def __setitem__(self, key, item):
411.435 - putenv(key, item)
411.436 - self.data[key.upper()] = item
411.437 - def __getitem__(self, key):
411.438 - return self.data[key.upper()]
411.439 - try:
411.440 - unsetenv
411.441 - except NameError:
411.442 - def __delitem__(self, key):
411.443 - del self.data[key.upper()]
411.444 - else:
411.445 - def __delitem__(self, key):
411.446 - unsetenv(key)
411.447 - del self.data[key.upper()]
411.448 - def has_key(self, key):
411.449 - return key.upper() in self.data
411.450 - def __contains__(self, key):
411.451 - return key.upper() in self.data
411.452 - def get(self, key, failobj=None):
411.453 - return self.data.get(key.upper(), failobj)
411.454 - def update(self, dict=None, **kwargs):
411.455 - if dict:
411.456 - try:
411.457 - keys = dict.keys()
411.458 - except AttributeError:
411.459 - # List of (key, value)
411.460 - for k, v in dict:
411.461 - self[k] = v
411.462 - else:
411.463 - # got keys
411.464 - # cannot use items(), since mappings
411.465 - # may not have them.
411.466 - for k in keys:
411.467 - self[k] = dict[k]
411.468 - if kwargs:
411.469 - self.update(kwargs)
411.470 - def copy(self):
411.471 - return dict(self)
411.472 -
411.473 - else: # Where Env Var Names Can Be Mixed Case
411.474 - class _Environ(UserDict.IterableUserDict):
411.475 - def __init__(self, environ):
411.476 - UserDict.UserDict.__init__(self)
411.477 - self.data = environ
411.478 - def __setitem__(self, key, item):
411.479 - putenv(key, item)
411.480 - self.data[key] = item
411.481 - def update(self, dict=None, **kwargs):
411.482 - if dict:
411.483 - try:
411.484 - keys = dict.keys()
411.485 - except AttributeError:
411.486 - # List of (key, value)
411.487 - for k, v in dict:
411.488 - self[k] = v
411.489 - else:
411.490 - # got keys
411.491 - # cannot use items(), since mappings
411.492 - # may not have them.
411.493 - for k in keys:
411.494 - self[k] = dict[k]
411.495 - if kwargs:
411.496 - self.update(kwargs)
411.497 - try:
411.498 - unsetenv
411.499 - except NameError:
411.500 - pass
411.501 - else:
411.502 - def __delitem__(self, key):
411.503 - unsetenv(key)
411.504 - del self.data[key]
411.505 - def copy(self):
411.506 - return dict(self)
411.507 -
411.508 -
411.509 - environ = _Environ(environ)
411.510 -
411.511 -def getenv(key, default=None):
411.512 - """Get an environment variable, return None if it doesn't exist.
411.513 - The optional second argument can specify an alternate default."""
411.514 - return environ.get(key, default)
411.515 -__all__.append("getenv")
411.516 -
411.517 -def _exists(name):
411.518 - try:
411.519 - eval(name)
411.520 - return True
411.521 - except NameError:
411.522 - return False
411.523 -
411.524 -# Supply spawn*() (probably only for Unix)
411.525 -if _exists("fork") and not _exists("spawnv") and _exists("execv"):
411.526 -
411.527 - P_WAIT = 0
411.528 - P_NOWAIT = P_NOWAITO = 1
411.529 -
411.530 - # XXX Should we support P_DETACH? I suppose it could fork()**2
411.531 - # and close the std I/O streams. Also, P_OVERLAY is the same
411.532 - # as execv*()?
411.533 -
411.534 - def _spawnvef(mode, file, args, env, func):
411.535 - # Internal helper; func is the exec*() function to use
411.536 - pid = fork()
411.537 - if not pid:
411.538 - # Child
411.539 - try:
411.540 - if env is None:
411.541 - func(file, args)
411.542 - else:
411.543 - func(file, args, env)
411.544 - except:
411.545 - _exit(127)
411.546 - else:
411.547 - # Parent
411.548 - if mode == P_NOWAIT:
411.549 - return pid # Caller is responsible for waiting!
411.550 - while 1:
411.551 - wpid, sts = waitpid(pid, 0)
411.552 - if WIFSTOPPED(sts):
411.553 - continue
411.554 - elif WIFSIGNALED(sts):
411.555 - return -WTERMSIG(sts)
411.556 - elif WIFEXITED(sts):
411.557 - return WEXITSTATUS(sts)
411.558 - else:
411.559 - raise error, "Not stopped, signaled or exited???"
411.560 -
411.561 - def spawnv(mode, file, args):
411.562 - """spawnv(mode, file, args) -> integer
411.563 -
411.564 -Execute file with arguments from args in a subprocess.
411.565 -If mode == P_NOWAIT return the pid of the process.
411.566 -If mode == P_WAIT return the process's exit code if it exits normally;
411.567 -otherwise return -SIG, where SIG is the signal that killed it. """
411.568 - return _spawnvef(mode, file, args, None, execv)
411.569 -
411.570 - def spawnve(mode, file, args, env):
411.571 - """spawnve(mode, file, args, env) -> integer
411.572 -
411.573 -Execute file with arguments from args in a subprocess with the
411.574 -specified environment.
411.575 -If mode == P_NOWAIT return the pid of the process.
411.576 -If mode == P_WAIT return the process's exit code if it exits normally;
411.577 -otherwise return -SIG, where SIG is the signal that killed it. """
411.578 - return _spawnvef(mode, file, args, env, execve)
411.579 -
411.580 - # Note: spawnvp[e] is't currently supported on Windows
411.581 -
411.582 - def spawnvp(mode, file, args):
411.583 - """spawnvp(mode, file, args) -> integer
411.584 -
411.585 -Execute file (which is looked for along $PATH) with arguments from
411.586 -args in a subprocess.
411.587 -If mode == P_NOWAIT return the pid of the process.
411.588 -If mode == P_WAIT return the process's exit code if it exits normally;
411.589 -otherwise return -SIG, where SIG is the signal that killed it. """
411.590 - return _spawnvef(mode, file, args, None, execvp)
411.591 -
411.592 - def spawnvpe(mode, file, args, env):
411.593 - """spawnvpe(mode, file, args, env) -> integer
411.594 -
411.595 -Execute file (which is looked for along $PATH) with arguments from
411.596 -args in a subprocess with the supplied environment.
411.597 -If mode == P_NOWAIT return the pid of the process.
411.598 -If mode == P_WAIT return the process's exit code if it exits normally;
411.599 -otherwise return -SIG, where SIG is the signal that killed it. """
411.600 - return _spawnvef(mode, file, args, env, execvpe)
411.601 -
411.602 -if _exists("spawnv"):
411.603 - # These aren't supplied by the basic Windows code
411.604 - # but can be easily implemented in Python
411.605 -
411.606 - def spawnl(mode, file, *args):
411.607 - """spawnl(mode, file, *args) -> integer
411.608 -
411.609 -Execute file with arguments from args in a subprocess.
411.610 -If mode == P_NOWAIT return the pid of the process.
411.611 -If mode == P_WAIT return the process's exit code if it exits normally;
411.612 -otherwise return -SIG, where SIG is the signal that killed it. """
411.613 - return spawnv(mode, file, args)
411.614 -
411.615 - def spawnle(mode, file, *args):
411.616 - """spawnle(mode, file, *args, env) -> integer
411.617 -
411.618 -Execute file with arguments from args in a subprocess with the
411.619 -supplied environment.
411.620 -If mode == P_NOWAIT return the pid of the process.
411.621 -If mode == P_WAIT return the process's exit code if it exits normally;
411.622 -otherwise return -SIG, where SIG is the signal that killed it. """
411.623 - env = args[-1]
411.624 - return spawnve(mode, file, args[:-1], env)
411.625 -
411.626 -
411.627 - __all__.extend(["spawnv", "spawnve", "spawnl", "spawnle",])
411.628 -
411.629 -
411.630 -if _exists("spawnvp"):
411.631 - # At the moment, Windows doesn't implement spawnvp[e],
411.632 - # so it won't have spawnlp[e] either.
411.633 - def spawnlp(mode, file, *args):
411.634 - """spawnlp(mode, file, *args) -> integer
411.635 -
411.636 -Execute file (which is looked for along $PATH) with arguments from
411.637 -args in a subprocess with the supplied environment.
411.638 -If mode == P_NOWAIT return the pid of the process.
411.639 -If mode == P_WAIT return the process's exit code if it exits normally;
411.640 -otherwise return -SIG, where SIG is the signal that killed it. """
411.641 - return spawnvp(mode, file, args)
411.642 -
411.643 - def spawnlpe(mode, file, *args):
411.644 - """spawnlpe(mode, file, *args, env) -> integer
411.645 -
411.646 -Execute file (which is looked for along $PATH) with arguments from
411.647 -args in a subprocess with the supplied environment.
411.648 -If mode == P_NOWAIT return the pid of the process.
411.649 -If mode == P_WAIT return the process's exit code if it exits normally;
411.650 -otherwise return -SIG, where SIG is the signal that killed it. """
411.651 - env = args[-1]
411.652 - return spawnvpe(mode, file, args[:-1], env)
411.653 -
411.654 -
411.655 - __all__.extend(["spawnvp", "spawnvpe", "spawnlp", "spawnlpe",])
411.656 -
411.657 -
411.658 -# Supply popen2 etc. (for Unix)
411.659 -if _exists("fork"):
411.660 - if not _exists("popen2"):
411.661 - def popen2(cmd, mode="t", bufsize=-1):
411.662 - """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd'
411.663 - may be a sequence, in which case arguments will be passed directly to
411.664 - the program without shell intervention (as with os.spawnv()). If 'cmd'
411.665 - is a string it will be passed to the shell (as with os.system()). If
411.666 - 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
411.667 - file objects (child_stdin, child_stdout) are returned."""
411.668 - import popen2
411.669 - stdout, stdin = popen2.popen2(cmd, bufsize)
411.670 - return stdin, stdout
411.671 - __all__.append("popen2")
411.672 -
411.673 - if not _exists("popen3"):
411.674 - def popen3(cmd, mode="t", bufsize=-1):
411.675 - """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd'
411.676 - may be a sequence, in which case arguments will be passed directly to
411.677 - the program without shell intervention (as with os.spawnv()). If 'cmd'
411.678 - is a string it will be passed to the shell (as with os.system()). If
411.679 - 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
411.680 - file objects (child_stdin, child_stdout, child_stderr) are returned."""
411.681 - import popen2
411.682 - stdout, stdin, stderr = popen2.popen3(cmd, bufsize)
411.683 - return stdin, stdout, stderr
411.684 - __all__.append("popen3")
411.685 -
411.686 - if not _exists("popen4"):
411.687 - def popen4(cmd, mode="t", bufsize=-1):
411.688 - """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd'
411.689 - may be a sequence, in which case arguments will be passed directly to
411.690 - the program without shell intervention (as with os.spawnv()). If 'cmd'
411.691 - is a string it will be passed to the shell (as with os.system()). If
411.692 - 'bufsize' is specified, it sets the buffer size for the I/O pipes. The
411.693 - file objects (child_stdin, child_stdout_stderr) are returned."""
411.694 - import popen2
411.695 - stdout, stdin = popen2.popen4(cmd, bufsize)
411.696 - return stdin, stdout
411.697 - __all__.append("popen4")
411.698 -
411.699 -import copy_reg as _copy_reg
411.700 -
411.701 -def _make_stat_result(tup, dict):
411.702 - return stat_result(tup, dict)
411.703 -
411.704 -def _pickle_stat_result(sr):
411.705 - (type, args) = sr.__reduce__()
411.706 - return (_make_stat_result, args)
411.707 -
411.708 -try:
411.709 - _copy_reg.pickle(stat_result, _pickle_stat_result, _make_stat_result)
411.710 -except NameError: # stat_result may not exist
411.711 - pass
411.712 -
411.713 -def _make_statvfs_result(tup, dict):
411.714 - return statvfs_result(tup, dict)
411.715 -
411.716 -def _pickle_statvfs_result(sr):
411.717 - (type, args) = sr.__reduce__()
411.718 - return (_make_statvfs_result, args)
411.719 -
411.720 -try:
411.721 - _copy_reg.pickle(statvfs_result, _pickle_statvfs_result,
411.722 - _make_statvfs_result)
411.723 -except NameError: # statvfs_result may not exist
411.724 - pass
411.725 -
411.726 -if not _exists("urandom"):
411.727 - def urandom(n):
411.728 - """urandom(n) -> str
411.729 -
411.730 - Return a string of n random bytes suitable for cryptographic use.
411.731 -
411.732 - """
411.733 - try:
411.734 - _urandomfd = open("/dev/urandom", O_RDONLY)
411.735 - except (OSError, IOError):
411.736 - raise NotImplementedError("/dev/urandom (or equivalent) not found")
411.737 - bytes = ""
411.738 - while len(bytes) < n:
411.739 - bytes += read(_urandomfd, n - len(bytes))
411.740 - close(_urandomfd)
411.741 - return bytes
412.1 --- a/python.editor/test/unit/data/testfiles/os.py.indexed Sun Jan 04 13:11:53 2015 -0600
412.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
412.3 @@ -1,88 +0,0 @@
412.4 -
412.5 -
412.6 -Document 0
412.7 -Searchable Keys:
412.8 - class : _Environ
412.9 - class-ig : _environ
412.10 - extends : IterableUserDict
412.11 - in : os
412.12 - member : __delitem__;F;;self,key;
412.13 - member : __init__;c;|CONSTRUCTOR|;self,environ;
412.14 - member : __setitem__;F;;self,key,item;
412.15 - member : copy;F;;self;
412.16 - member : data;D;;
412.17 - member : update;F;;self,dict,kwargs;
412.18 -
412.19 -Not Searchable Keys:
412.20 - clzattrs : ;|PRIVATE|;
412.21 -
412.22 -
412.23 -Document 1
412.24 -Searchable Keys:
412.25 - item : P_NOWAIT;D;;
412.26 - item : P_NOWAITO;D;;
412.27 - item : P_WAIT;D;;
412.28 - item : SEEK_CUR;D;;
412.29 - item : SEEK_END;D;;
412.30 - item : SEEK_SET;D;;
412.31 - item : UserDict;I;;
412.32 - item : _Environ;C;|PRIVATE|;
412.33 - item : __all__;D;;
412.34 - item : _copy_reg;I;|PRIVATE|;
412.35 - item : _execvpe;F;|PRIVATE|;file,args,env;
412.36 - item : _exists;F;|PRIVATE|;name;
412.37 - item : _exit;I;|PRIVATE|;
412.38 - item : _get_exports_list;F;|PRIVATE|;module;
412.39 - item : _make_stat_result;F;|PRIVATE|;tup,dict;
412.40 - item : _make_statvfs_result;F;|PRIVATE|;tup,dict;
412.41 - item : _names;D;|PRIVATE|;
412.42 - item : _pickle_stat_result;F;|PRIVATE|;sr;
412.43 - item : _pickle_statvfs_result;F;|PRIVATE|;sr;
412.44 - item : _spawnvef;F;|PRIVATE|;mode,file,args,env,func;
412.45 - item : altsep;I;;
412.46 - item : ce;I;;
412.47 - item : curdir;I;;
412.48 - item : defpath;I;;
412.49 - item : devnull;I;;
412.50 - item : environ;D;;
412.51 - item : execl;F;;file,args;
412.52 - item : execle;F;;file,args;
412.53 - item : execlp;F;;file,args;
412.54 - item : execlpe;F;;file,args;
412.55 - item : execvp;F;;file,args;
412.56 - item : execvpe;F;;file,args,env;
412.57 - item : extsep;I;;
412.58 - item : getenv;F;;key,default;
412.59 - item : linesep;D;;
412.60 - item : link;I;;
412.61 - item : mac;I;;
412.62 - item : makedirs;F;;name,mode;
412.63 - item : name;D;;
412.64 - item : nt;I;;
412.65 - item : os2;I;;
412.66 - item : pardir;I;;
412.67 - item : path;I;;
412.68 - item : pathsep;I;;
412.69 - item : popen2;F;;cmd,mode,bufsize;
412.70 - item : popen3;F;;cmd,mode,bufsize;
412.71 - item : popen4;F;;cmd,mode,bufsize;
412.72 - item : posix;I;;
412.73 - item : removedirs;F;;name;
412.74 - item : renames;F;;old,new;
412.75 - item : riscos;I;;
412.76 - item : sep;I;;
412.77 - item : spawnl;F;;mode,file,args;
412.78 - item : spawnle;F;;mode,file,args;
412.79 - item : spawnlp;F;;mode,file,args;
412.80 - item : spawnlpe;F;;mode,file,args;
412.81 - item : spawnv;F;;mode,file,args;
412.82 - item : spawnve;F;;mode,file,args,env;
412.83 - item : spawnvp;F;;mode,file,args;
412.84 - item : spawnvpe;F;;mode,file,args,env;
412.85 - item : sys;I;;
412.86 - item : unsetenv;F;;key;
412.87 - item : urandom;F;;n;
412.88 - item : walk;F;;top,topdown,onerror;
412.89 - module : os
412.90 -
412.91 -Not Searchable Keys:
413.1 --- a/python.editor/test/unit/data/testfiles/os.py.scopes Sun Jan 04 13:11:53 2015 -0600
413.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
413.3 @@ -1,531 +0,0 @@
413.4 -=============================================
413.5 -<file-top>: Module : OffsetRange[0,24666>
413.6 -* [bound][imported][data][node=ImportFrom]
413.7 -ImportError [read][UNRESOLVED][node=Name]
413.8 -NameError [read][UNRESOLVED][node=Name]
413.9 -None [read][UNRESOLVED][node=Name]
413.10 -P_NOWAIT [bound][data][read][node=Name]
413.11 -P_NOWAITO [bound][data][node=Name]
413.12 -P_WAIT [bound][data][node=Name]
413.13 -SEEK_CUR [bound][data][node=Name]
413.14 -SEEK_END [bound][data][node=Name]
413.15 -SEEK_SET [bound][data][node=Name]
413.16 -True [read][UNRESOLVED][node=Name]
413.17 -UserDict [bound][imported][data][read][node=Import]
413.18 -_Environ [bound][imported][private][class][def][read][called][node=ClassDef]
413.19 -__all__ [bound][data][read][node=Name]
413.20 -_copy_reg [bound][imported][private][data][read][node=Import]
413.21 -_execvpe [bound][private][function][def][node=FunctionDef]
413.22 -_exists [bound][private][function][def][read][called][node=FunctionDef]
413.23 -_exit [bound][imported][private][data][read][called][node=ImportFrom]
413.24 -_get_exports_list [bound][private][function][def][read][called][node=FunctionDef]
413.25 -_make_stat_result [bound][private][function][def][read][node=FunctionDef]
413.26 -_make_statvfs_result [bound][private][function][def][read][node=FunctionDef]
413.27 -_names [bound][private][data][read][node=Name]
413.28 -_pickle_stat_result [bound][private][function][def][read][node=FunctionDef]
413.29 -_pickle_statvfs_result [bound][private][function][def][read][node=FunctionDef]
413.30 -_spawnvef [bound][private][function][def][read][called][node=FunctionDef]
413.31 -altsep [bound][imported][data][node=ImportFrom]
413.32 -ce [bound][imported][data][read][node=Import]
413.33 -curdir [bound][imported][data][read][node=ImportFrom]
413.34 -defpath [bound][imported][data][read][node=ImportFrom]
413.35 -devnull [bound][imported][data][node=ImportFrom]
413.36 -environ [bound][data][read][node=Name]
413.37 -execl [bound][function][def][node=FunctionDef]
413.38 -execle [bound][function][def][node=FunctionDef]
413.39 -execlp [bound][function][def][node=FunctionDef]
413.40 -execlpe [bound][function][def][node=FunctionDef]
413.41 -execvp [bound][function][def][read][node=FunctionDef]
413.42 -execvpe [bound][function][def][read][node=FunctionDef]
413.43 -extsep [bound][imported][data][node=ImportFrom]
413.44 -getenv [bound][function][def][node=FunctionDef]
413.45 -linesep [bound][data][node=Name]
413.46 -link [bound][imported][data][node=ImportFrom]
413.47 -mac [bound][imported][data][read][node=Import]
413.48 -makedirs [bound][function][def][read][called][node=FunctionDef]
413.49 -name [bound][data][read][node=Name]
413.50 -nt [bound][imported][data][read][node=Import]
413.51 -os2 [bound][imported][data][read][node=Import]
413.52 -pardir [bound][imported][data][node=ImportFrom]
413.53 -path [bound][imported][data][read][node=Import]
413.54 -pathsep [bound][imported][data][read][node=ImportFrom]
413.55 -popen2 [bound][function][def][node=FunctionDef]
413.56 -popen3 [bound][function][def][node=FunctionDef]
413.57 -popen4 [bound][function][def][node=FunctionDef]
413.58 -posix [bound][imported][data][read][node=Import]
413.59 -putenv [read][UNRESOLVED][node=Name]
413.60 -removedirs [bound][function][def][read][called][node=FunctionDef]
413.61 -renames [bound][function][def][node=FunctionDef]
413.62 -riscos [bound][imported][data][read][node=Import]
413.63 -sep [bound][imported][data][node=ImportFrom]
413.64 -spawnl [bound][function][def][node=FunctionDef]
413.65 -spawnle [bound][function][def][node=FunctionDef]
413.66 -spawnlp [bound][function][def][node=FunctionDef]
413.67 -spawnlpe [bound][function][def][node=FunctionDef]
413.68 -spawnv [bound][function][def][read][called][node=FunctionDef]
413.69 -spawnve [bound][function][def][read][called][node=FunctionDef]
413.70 -spawnvp [bound][function][def][read][called][node=FunctionDef]
413.71 -spawnvpe [bound][function][def][read][called][node=FunctionDef]
413.72 -stat_result [read][UNRESOLVED][node=Name]
413.73 -statvfs_result [read][UNRESOLVED][node=Name]
413.74 -sys [bound][imported][data][read][node=Import]
413.75 -unsetenv [bound][function][def][read][called][node=FunctionDef]
413.76 -urandom [bound][function][def][node=FunctionDef]
413.77 -walk [bound][function][def][read][called][node=FunctionDef]
413.78 -
413.79 - =============================================
413.80 - _get_exports_list: FunctionDef : OffsetRange[1451,1610>
413.81 - AttributeError [free][read][node=Name]
413.82 - _[39_16] [bound][private][data][unused][node=ListComp]
413.83 - dir [free][read][called][node=Name]
413.84 - list [free][read][called][node=Name]
413.85 - module [bound][param][data][read][node=Name]
413.86 - n [bound][data][read][node=Name]
413.87 -
413.88 - =============================================
413.89 - makedirs: FunctionDef : OffsetRange[3783,4559>
413.90 - EEXIST [bound][imported][data][read][node=ImportFrom]
413.91 - OSError [free][read][node=Name]
413.92 - curdir [free][read][node=Name]
413.93 - e [bound][data][read][node=Name]
413.94 - head [bound][data][read][node=Name]
413.95 - makedirs [free][read][called][node=Name]
413.96 - mkdir [free][read][called][node=Name]
413.97 - mode [bound][param][data][read][node=Name]
413.98 - name [bound][param][data][read][node=Name]
413.99 - path [free][read][node=Name]
413.100 - tail [bound][data][read][node=Name]
413.101 -
413.102 - =============================================
413.103 - removedirs: FunctionDef : OffsetRange[4559,5266>
413.104 - error [free][read][node=Name]
413.105 - head [bound][data][read][node=Name]
413.106 - name [bound][param][data][read][node=Name]
413.107 - path [free][read][node=Name]
413.108 - rmdir [free][read][called][node=Name]
413.109 - tail [bound][data][read][node=Name]
413.110 -
413.111 - =============================================
413.112 - renames: FunctionDef : OffsetRange[5266,6138>
413.113 - error [free][read][node=Name]
413.114 - head [bound][data][read][node=Name]
413.115 - makedirs [free][read][called][node=Name]
413.116 - new [bound][param][data][read][node=Name]
413.117 - old [bound][param][data][read][node=Name]
413.118 - path [free][read][node=Name]
413.119 - removedirs [free][read][called][node=Name]
413.120 - rename [free][read][called][node=Name]
413.121 - tail [bound][data][read][node=Name]
413.122 -
413.123 - =============================================
413.124 - walk: FunctionDef : OffsetRange[6193,9684>
413.125 - None [free][read][node=Name]
413.126 - dirs [bound][data][read][node=Name]
413.127 - err [bound][data][read][node=Name]
413.128 - error [free][read][node=Name]
413.129 - isdir [bound][imported][data][read][called][node=ImportFrom]
413.130 - islink [bound][imported][data][read][called][node=ImportFrom]
413.131 - join [bound][imported][data][read][called][node=ImportFrom]
413.132 - listdir [free][read][called][node=Name]
413.133 - name [bound][data][read][node=Name]
413.134 - names [bound][data][read][node=Name]
413.135 - nondirs [bound][data][read][node=Name]
413.136 - onerror [bound][param][data][read][called][node=Name]
413.137 - path [bound][data][read][node=Name]
413.138 - top [bound][param][data][read][node=Name]
413.139 - topdown [bound][param][data][read][node=Name]
413.140 - walk [free][read][called][node=Name]
413.141 - x [bound][data][read][node=Name]
413.142 -
413.143 - =============================================
413.144 - execl: FunctionDef : OffsetRange[9801,9971>
413.145 - args [bound][param][data][read][node=arguments]
413.146 - execv [free][read][called][node=Name]
413.147 - file [bound][param][data][read][node=Name]
413.148 -
413.149 - =============================================
413.150 - execle: FunctionDef : OffsetRange[9971,10198>
413.151 - args [bound][param][data][read][node=arguments]
413.152 - env [bound][data][read][node=Name]
413.153 - execve [free][read][called][node=Name]
413.154 - file [bound][param][data][read][node=Name]
413.155 -
413.156 - =============================================
413.157 - execlp: FunctionDef : OffsetRange[10198,10407>
413.158 - args [bound][param][data][read][node=arguments]
413.159 - execvp [free][read][called][node=Name]
413.160 - file [bound][param][data][read][node=Name]
413.161 -
413.162 - =============================================
413.163 - execlpe: FunctionDef : OffsetRange[10407,10677>
413.164 - args [bound][param][data][read][node=arguments]
413.165 - env [bound][data][read][node=Name]
413.166 - execvpe [free][read][called][node=Name]
413.167 - file [bound][param][data][read][node=Name]
413.168 -
413.169 - =============================================
413.170 - execvp: FunctionDef : OffsetRange[10677,10929>
413.171 - _execvpe [free][read][called][node=Name]
413.172 - args [bound][param][data][read][node=Name]
413.173 - file [bound][param][data][read][node=Name]
413.174 -
413.175 - =============================================
413.176 - execvpe: FunctionDef : OffsetRange[10929,11224>
413.177 - _execvpe [free][read][called][node=Name]
413.178 - args [bound][param][data][read][node=Name]
413.179 - env [bound][param][data][read][node=Name]
413.180 - file [bound][param][data][read][node=Name]
413.181 -
413.182 - =============================================
413.183 - _execvpe: FunctionDef : OffsetRange[11298,12255>
413.184 - ENOENT [bound][imported][data][read][node=ImportFrom]
413.185 - ENOTDIR [bound][imported][data][read][node=ImportFrom]
413.186 - None [free][read][node=Name]
413.187 - PATH [bound][data][read][node=Name]
413.188 - argrest [bound][data][read][node=Name]
413.189 - args [bound][param][data][read][node=Name]
413.190 - defpath [free][read][node=Name]
413.191 - dir [bound][data][read][node=Name]
413.192 - e [bound][data][read][node=Name]
413.193 - env [bound][param][data][read][node=Name]
413.194 - environ [free][read][node=Name]
413.195 - envpath [bound][data][read][node=Name]
413.196 - error [free][read][node=Name]
413.197 - execv [free][read][node=Name]
413.198 - execve [free][read][node=Name]
413.199 - file [bound][param][data][read][node=Name]
413.200 - fullname [bound][data][read][node=Name]
413.201 - func [bound][data][read][called][node=Name]
413.202 - head [bound][data][read][node=Name]
413.203 - path [free][read][node=Name]
413.204 - pathsep [free][read][node=Name]
413.205 - saved_exc [bound][data][read][node=Name]
413.206 - saved_tb [bound][data][read][node=Name]
413.207 - sys [free][read][node=Name]
413.208 - tail [bound][data][unused][node=Name]
413.209 - tb [bound][data][read][node=Name]
413.210 -
413.211 - =============================================
413.212 - unsetenv: FunctionDef : OffsetRange[12512,12563>
413.213 - key [bound][param][data][read][node=Name]
413.214 - putenv [free][read][called][node=Name]
413.215 -
413.216 - =============================================
413.217 - class _Environ: ClassDef : OffsetRange[12819,14567>
413.218 - NameError [free][read][node=Name]
413.219 - None [free][read][node=Name]
413.220 - __contains__ [bound][function][def][node=FunctionDef]
413.221 - __delitem__ [bound][function][def][node=FunctionDef]
413.222 - __getitem__ [bound][function][def][node=FunctionDef]
413.223 - __init__ [bound][function][def][node=FunctionDef]
413.224 - __setitem__ [bound][function][def][node=FunctionDef]
413.225 - copy [bound][function][def][node=FunctionDef]
413.226 - get [bound][function][def][node=FunctionDef]
413.227 - has_key [bound][function][def][node=FunctionDef]
413.228 - unsetenv [free][read][node=Name]
413.229 - update [bound][function][def][node=FunctionDef]
413.230 -
413.231 - =============================================
413.232 - __init__: FunctionDef : OffsetRange[12874,13081>
413.233 - UserDict [free][read][node=Name]
413.234 - data [bound][data][read][node=Name]
413.235 - environ [bound][param][data][read][node=Name]
413.236 - k [bound][data][read][node=Name]
413.237 - self [bound][param][data][read][node=Name]
413.238 - v [bound][data][read][node=Name]
413.239 - ------ Attributes ---------------------------------------
413.240 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
413.241 -
413.242 - =============================================
413.243 - __setitem__: FunctionDef : OffsetRange[13082,13207>
413.244 - item [bound][param][data][read][node=Name]
413.245 - key [bound][param][data][read][node=Name]
413.246 - putenv [free][read][called][node=Name]
413.247 - self [bound][param][data][read][node=Name]
413.248 - ------ Attributes ---------------------------------------
413.249 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
413.250 -
413.251 - =============================================
413.252 - __getitem__: FunctionDef : OffsetRange[13208,13293>
413.253 - key [bound][param][data][read][node=Name]
413.254 - self [bound][param][data][read][node=Name]
413.255 - ------ Attributes ---------------------------------------
413.256 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
413.257 -
413.258 - =============================================
413.259 - __delitem__: FunctionDef : OffsetRange[13370,13456>
413.260 - key [bound][param][data][read][node=Name]
413.261 - self [bound][param][data][read][node=Name]
413.262 - ------ Attributes ---------------------------------------
413.263 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
413.264 -
413.265 - =============================================
413.266 - __delitem__: FunctionDef : OffsetRange[13479,13599>
413.267 - key [bound][param][data][read][node=Name]
413.268 - self [bound][param][data][read][node=Name]
413.269 - unsetenv [free][read][called][node=Name]
413.270 - ------ Attributes ---------------------------------------
413.271 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
413.272 -
413.273 - =============================================
413.274 - has_key: FunctionDef : OffsetRange[13600,13683>
413.275 - key [bound][param][data][read][node=Name]
413.276 - self [bound][param][data][read][node=Name]
413.277 - ------ Attributes ---------------------------------------
413.278 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
413.279 -
413.280 - =============================================
413.281 - __contains__: FunctionDef : OffsetRange[13684,13772>
413.282 - key [bound][param][data][read][node=Name]
413.283 - self [bound][param][data][read][node=Name]
413.284 - ------ Attributes ---------------------------------------
413.285 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
413.286 -
413.287 - =============================================
413.288 - get: FunctionDef : OffsetRange[13773,13877>
413.289 - failobj [bound][param][data][read][node=Name]
413.290 - key [bound][param][data][read][node=Name]
413.291 - self [bound][param][data][read][node=Name]
413.292 - ------ Attributes ---------------------------------------
413.293 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
413.294 -
413.295 - =============================================
413.296 - update: FunctionDef : OffsetRange[13878,14512>
413.297 - AttributeError [free][read][node=Name]
413.298 - dict [bound][param][data][read][node=Name]
413.299 - k [bound][data][read][node=Name]
413.300 - keys [bound][data][read][node=Name]
413.301 - kwargs [bound][param][data][read][node=arguments]
413.302 - self [bound][param][data][read][node=Name]
413.303 - v [bound][data][read][node=Name]
413.304 - ------ Attributes ---------------------------------------
413.305 - update : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
413.306 -
413.307 - =============================================
413.308 - copy: FunctionDef : OffsetRange[14513,14567>
413.309 - dict [free][read][called][node=Name]
413.310 - self [bound][param][data][read][node=Name]
413.311 -
413.312 - =============================================
413.313 - class _Environ: ClassDef : OffsetRange[14623,15841>
413.314 - NameError [free][read][node=Name]
413.315 - None [free][read][node=Name]
413.316 - __delitem__ [bound][function][def][node=FunctionDef]
413.317 - __init__ [bound][function][def][node=FunctionDef]
413.318 - __setitem__ [bound][function][def][node=FunctionDef]
413.319 - copy [bound][function][def][node=FunctionDef]
413.320 - unsetenv [free][read][node=Name]
413.321 - update [bound][function][def][node=FunctionDef]
413.322 - ------ Attributes ---------------------------------------
413.323 - data : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
413.324 -
413.325 - =============================================
413.326 - __init__: FunctionDef : OffsetRange[14678,14803>
413.327 - UserDict [free][read][node=Name]
413.328 - environ [bound][param][data][read][node=Name]
413.329 - self [bound][param][data][read][node=Name]
413.330 -
413.331 - =============================================
413.332 - __setitem__: FunctionDef : OffsetRange[14804,14921>
413.333 - item [bound][param][data][read][node=Name]
413.334 - key [bound][param][data][read][node=Name]
413.335 - putenv [free][read][called][node=Name]
413.336 - self [bound][param][data][read][node=Name]
413.337 - ------ Attributes ---------------------------------------
413.338 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
413.339 -
413.340 - =============================================
413.341 - update: FunctionDef : OffsetRange[14922,15557>
413.342 - AttributeError [free][read][node=Name]
413.343 - dict [bound][param][data][read][node=Name]
413.344 - k [bound][data][read][node=Name]
413.345 - keys [bound][data][read][node=Name]
413.346 - kwargs [bound][param][data][read][node=arguments]
413.347 - self [bound][param][data][read][node=Name]
413.348 - v [bound][data][read][node=Name]
413.349 - ------ Attributes ---------------------------------------
413.350 - update : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
413.351 -
413.352 - =============================================
413.353 - __delitem__: FunctionDef : OffsetRange[15673,15785>
413.354 - key [bound][param][data][read][node=Name]
413.355 - self [bound][param][data][read][node=Name]
413.356 - unsetenv [free][read][called][node=Name]
413.357 - ------ Attributes ---------------------------------------
413.358 - data : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
413.359 -
413.360 - =============================================
413.361 - copy: FunctionDef : OffsetRange[15786,15841>
413.362 - dict [free][read][called][node=Name]
413.363 - self [bound][param][data][read][node=Name]
413.364 -
413.365 - =============================================
413.366 - getenv: FunctionDef : OffsetRange[15871,16078>
413.367 - default [bound][param][data][read][node=Name]
413.368 - environ [free][read][node=Name]
413.369 - key [bound][param][data][read][node=Name]
413.370 -
413.371 - =============================================
413.372 - _exists: FunctionDef : OffsetRange[16104,16258>
413.373 - False [free][read][node=Name]
413.374 - NameError [free][read][node=Name]
413.375 - True [free][read][node=Name]
413.376 - eval [free][read][called][node=Name]
413.377 - name [bound][param][data][read][node=Name]
413.378 -
413.379 - =============================================
413.380 - _spawnvef: FunctionDef : OffsetRange[16529,17414>
413.381 - None [free][read][node=Name]
413.382 - P_NOWAIT [free][read][node=Name]
413.383 - WEXITSTATUS [free][read][called][node=Name]
413.384 - WIFEXITED [free][read][called][node=Name]
413.385 - WIFSIGNALED [free][read][called][node=Name]
413.386 - WIFSTOPPED [free][read][called][node=Name]
413.387 - WTERMSIG [free][read][called][node=Name]
413.388 - _exit [free][read][called][node=Name]
413.389 - args [bound][param][data][read][node=Name]
413.390 - env [bound][param][data][read][node=Name]
413.391 - error [free][read][node=Name]
413.392 - file [bound][param][data][read][node=Name]
413.393 - fork [free][read][called][node=Name]
413.394 - func [bound][param][data][read][called][node=Name]
413.395 - mode [bound][param][data][read][node=Name]
413.396 - pid [bound][data][read][node=Name]
413.397 - sts [bound][data][read][node=Name]
413.398 - waitpid [free][read][called][node=Name]
413.399 - wpid [bound][data][unused][node=Name]
413.400 -
413.401 - =============================================
413.402 - spawnv: FunctionDef : OffsetRange[17415,17797>
413.403 - None [free][read][node=Name]
413.404 - _spawnvef [free][read][called][node=Name]
413.405 - args [bound][param][data][read][node=Name]
413.406 - execv [free][read][node=Name]
413.407 - file [bound][param][data][read][node=Name]
413.408 - mode [bound][param][data][read][node=Name]
413.409 -
413.410 - =============================================
413.411 - spawnve: FunctionDef : OffsetRange[17798,18283>
413.412 - _spawnvef [free][read][called][node=Name]
413.413 - args [bound][param][data][read][node=Name]
413.414 - env [bound][param][data][read][node=Name]
413.415 - execve [free][read][node=Name]
413.416 - file [bound][param][data][read][node=Name]
413.417 - mode [bound][param][data][read][node=Name]
413.418 -
413.419 - =============================================
413.420 - spawnvp: FunctionDef : OffsetRange[18284,18703>
413.421 - None [free][read][node=Name]
413.422 - _spawnvef [free][read][called][node=Name]
413.423 - args [bound][param][data][read][node=Name]
413.424 - execvp [free][read][node=Name]
413.425 - file [bound][param][data][read][node=Name]
413.426 - mode [bound][param][data][read][node=Name]
413.427 -
413.428 - =============================================
413.429 - spawnvpe: FunctionDef : OffsetRange[18704,19162>
413.430 - _spawnvef [free][read][called][node=Name]
413.431 - args [bound][param][data][read][node=Name]
413.432 - env [bound][param][data][read][node=Name]
413.433 - execvpe [free][read][node=Name]
413.434 - file [bound][param][data][read][node=Name]
413.435 - mode [bound][param][data][read][node=Name]
413.436 -
413.437 - =============================================
413.438 - spawnl: FunctionDef : OffsetRange[19289,19657>
413.439 - args [bound][param][data][read][node=arguments]
413.440 - file [bound][param][data][read][node=Name]
413.441 - mode [bound][param][data][read][node=Name]
413.442 - spawnv [free][read][called][node=Name]
413.443 -
413.444 - =============================================
413.445 - spawnle: FunctionDef : OffsetRange[19658,20098>
413.446 - args [bound][param][data][read][node=arguments]
413.447 - env [bound][data][read][node=Name]
413.448 - file [bound][param][data][read][node=Name]
413.449 - mode [bound][param][data][read][node=Name]
413.450 - spawnve [free][read][called][node=Name]
413.451 -
413.452 - =============================================
413.453 - spawnlp: FunctionDef : OffsetRange[20289,20724>
413.454 - args [bound][param][data][read][node=arguments]
413.455 - file [bound][param][data][read][node=Name]
413.456 - mode [bound][param][data][read][node=Name]
413.457 - spawnvp [free][read][called][node=Name]
413.458 -
413.459 - =============================================
413.460 - spawnlpe: FunctionDef : OffsetRange[20725,21202>
413.461 - args [bound][param][data][read][node=arguments]
413.462 - env [bound][data][read][node=Name]
413.463 - file [bound][param][data][read][node=Name]
413.464 - mode [bound][param][data][read][node=Name]
413.465 - spawnvpe [free][read][called][node=Name]
413.466 -
413.467 - =============================================
413.468 - popen2: FunctionDef : OffsetRange[21359,22002>
413.469 - bufsize [bound][param][data][read][node=Name]
413.470 - cmd [bound][param][data][read][node=Name]
413.471 - mode [bound][param][data][unused][node=Name]
413.472 - popen2 [bound][imported][data][read][node=Import]
413.473 - stdin [bound][data][read][node=Name]
413.474 - stdout [bound][data][read][node=Name]
413.475 -
413.476 - =============================================
413.477 - popen3: FunctionDef : OffsetRange[22067,22740>
413.478 - bufsize [bound][param][data][read][node=Name]
413.479 - cmd [bound][param][data][read][node=Name]
413.480 - mode [bound][param][data][unused][node=Name]
413.481 - popen2 [bound][imported][data][read][node=Import]
413.482 - stderr [bound][data][read][node=Name]
413.483 - stdin [bound][data][read][node=Name]
413.484 - stdout [bound][data][read][node=Name]
413.485 -
413.486 - =============================================
413.487 - popen4: FunctionDef : OffsetRange[22805,23455>
413.488 - bufsize [bound][param][data][read][node=Name]
413.489 - cmd [bound][param][data][read][node=Name]
413.490 - mode [bound][param][data][unused][node=Name]
413.491 - popen2 [bound][imported][data][read][node=Import]
413.492 - stdin [bound][data][read][node=Name]
413.493 - stdout [bound][data][read][node=Name]
413.494 -
413.495 - =============================================
413.496 - _make_stat_result: FunctionDef : OffsetRange[23512,23581>
413.497 - dict [bound][param][data][read][node=Name]
413.498 - stat_result [free][read][called][node=Name]
413.499 - tup [bound][param][data][read][node=Name]
413.500 -
413.501 - =============================================
413.502 - _pickle_stat_result: FunctionDef : OffsetRange[23581,23683>
413.503 - _make_stat_result [free][read][node=Name]
413.504 - args [bound][data][read][node=Name]
413.505 - sr [bound][param][data][read][node=Name]
413.506 - type [bound][data][unused][node=Name]
413.507 -
413.508 - =============================================
413.509 - _make_statvfs_result: FunctionDef : OffsetRange[23818,23893>
413.510 - dict [bound][param][data][read][node=Name]
413.511 - statvfs_result [free][read][called][node=Name]
413.512 - tup [bound][param][data][read][node=Name]
413.513 -
413.514 - =============================================
413.515 - _pickle_statvfs_result: FunctionDef : OffsetRange[23893,24001>
413.516 - _make_statvfs_result [free][read][node=Name]
413.517 - args [bound][data][read][node=Name]
413.518 - sr [bound][param][data][read][node=Name]
413.519 - type [bound][data][unused][node=Name]
413.520 -
413.521 - =============================================
413.522 - urandom: FunctionDef : OffsetRange[24200,24666>
413.523 - IOError [free][read][node=Name]
413.524 - NotImplementedError [free][read][called][node=Name]
413.525 - OSError [free][read][node=Name]
413.526 - O_RDONLY [free][read][node=Name]
413.527 - _urandomfd [bound][private][data][read][node=Name]
413.528 - bytes [bound][data][read][node=Name]
413.529 - close [free][read][called][node=Name]
413.530 - len [free][read][called][node=Name]
413.531 - n [bound][param][data][read][node=Name]
413.532 - open [free][read][called][node=Name]
413.533 - read [free][read][called][node=Name]
413.534 -
414.1 --- a/python.editor/test/unit/data/testfiles/overrides.py Sun Jan 04 13:11:53 2015 -0600
414.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
414.3 @@ -1,23 +0,0 @@
414.4 -class Ancestor:
414.5 - def overridden_method1(self, a, b):
414.6 - pass
414.7 - def overridden_method2(self, c, d):
414.8 - pass
414.9 -
414.10 -class Middle(Ancestor):
414.11 - def overridden_method1(self, a, b):
414.12 - pass
414.13 -
414.14 -class Middle2(Ancestor):
414.15 - def overridden_method2(self, a, b):
414.16 - pass
414.17 -
414.18 - def overridden_method1(self, a, b):
414.19 - pass
414.20 -
414.21 -class Child(Middle, Middle2):
414.22 - def overridden_method1(self, a, b): # Final
414.23 - pass
414.24 - def overridden_method2(self, c, d): # Final
414.25 - pass
414.26 -
415.1 --- a/python.editor/test/unit/data/testfiles/overrides.py.testDeclaration8.declarations Sun Jan 04 13:11:53 2015 -0600
415.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
415.3 @@ -1,24 +0,0 @@
415.4 -overrides.py:288:
415.5 - def |overridden_method1(self, a, b):
415.6 - pass
415.7 -
415.8 -
415.9 -Alternative Locations:
415.10 -overridden_method1(self, a, b) in Middle in overrides.py
415.11 -overrides.py:151:class Middle(Ancestor):
415.12 - |def overridden_method1(self, a, b):
415.13 - pass
415.14 -
415.15 -
415.16 -overridden_method1(self, a, b) in Ancestor in overrides.py
415.17 -overrides.py:20:class Ancestor:
415.18 - |def overridden_method1(self, a, b):
415.19 - pass
415.20 -
415.21 -
415.22 -overridden_method1(self, a, b) in Middle2 in overrides.py
415.23 -overrides.py:284:
415.24 - |def overridden_method1(self, a, b):
415.25 - pass
415.26 -
415.27 -
416.1 --- a/python.editor/test/unit/data/testfiles/overrides.py.testDeclaration9.declarations Sun Jan 04 13:11:53 2015 -0600
416.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
416.3 @@ -1,18 +0,0 @@
416.4 -overrides.py:234:class Middle2(Ancestor):
416.5 - def |overridden_method2(self, a, b):
416.6 - pass
416.7 -
416.8 -
416.9 -Alternative Locations:
416.10 -overridden_method2(self, a, b) in Middle2 in overrides.py
416.11 -overrides.py:230:class Middle2(Ancestor):
416.12 - |def overridden_method2(self, a, b):
416.13 - pass
416.14 -
416.15 -
416.16 -overridden_method2(self, c, d) in Ancestor in overrides.py
416.17 -overrides.py:73: pass
416.18 - |def overridden_method2(self, c, d):
416.19 - pass
416.20 -
416.21 -
417.1 --- a/python.editor/test/unit/data/testfiles/package/subpackage1/__init__.py Sun Jan 04 13:11:53 2015 -0600
417.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
417.3 @@ -1,9 +0,0 @@
417.4 -from .moduleY import spam
417.5 -from .moduleY import spam as ham
417.6 -from . import moduleY
417.7 -from ..subpackage1 import moduleY
417.8 -from ..subpackage2.moduleZ import eggs
417.9 -from ..moduleA import foo
417.10 -from ...package import bar
417.11 -from ...sys import path
417.12 -
418.1 --- a/python.editor/test/unit/data/testfiles/package/subpackage1/__init__.py.testFixInit.imported Sun Jan 04 13:11:53 2015 -0600
418.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
418.3 @@ -1,9 +0,0 @@
418.4 -from . import moduleY
418.5 -from ...package import bar
418.6 -from ...sys import path
418.7 -from ..moduleA import foo
418.8 -from ..subpackage1 import moduleY
418.9 -from ..subpackage2.moduleZ import eggs
418.10 -from .moduleY import spam as ham
418.11 -from .moduleY import spam
418.12 -
419.1 --- a/python.editor/test/unit/data/testfiles/package/subpackage1/moduleX.py Sun Jan 04 13:11:53 2015 -0600
419.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
419.3 @@ -1,9 +0,0 @@
419.4 -from .moduleY import spam
419.5 -from .moduleY import spam as ham
419.6 -from . import moduleY
419.7 -from ..subpackage1 import moduleY
419.8 -from ..subpackage2.moduleZ import eggs
419.9 -from ..moduleA import foo
419.10 -from ...package import bar
419.11 -from ...sys import path
419.12 -
420.1 --- a/python.editor/test/unit/data/testfiles/package/subpackage1/moduleX.py.testFix4.fixed Sun Jan 04 13:11:53 2015 -0600
420.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
420.3 @@ -1,9 +0,0 @@
420.4 -from .moduleY import spam
420.5 -from .moduleY import spam as ham
420.6 -from package.subpackage1 import moduleY
420.7 -from ..subpackage1 import moduleY
420.8 -from ..subpackage2.moduleZ import eggs
420.9 -from ..moduleA import foo
420.10 -from ...package import bar
420.11 -from ...sys import path
420.12 -
421.1 --- a/python.editor/test/unit/data/testfiles/package/subpackage1/moduleX.py.testFix5.fixed Sun Jan 04 13:11:53 2015 -0600
421.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
421.3 @@ -1,9 +0,0 @@
421.4 -from package.subpackage1.moduleY import spam
421.5 -from .moduleY import spam as ham
421.6 -from . import moduleY
421.7 -from ..subpackage1 import moduleY
421.8 -from ..subpackage2.moduleZ import eggs
421.9 -from ..moduleA import foo
421.10 -from ...package import bar
421.11 -from ...sys import path
421.12 -
422.1 --- a/python.editor/test/unit/data/testfiles/package/subpackage1/moduleX.py.testHint2.hints Sun Jan 04 13:11:53 2015 -0600
422.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
422.3 @@ -1,32 +0,0 @@
422.4 -from .moduleY import spam
422.5 --------------------------
422.6 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
422.7 -FIX:Replace with absolute import
422.8 -from .moduleY import spam as ham
422.9 ---------------------------------
422.10 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
422.11 -FIX:Replace with absolute import
422.12 -from . import moduleY
422.13 ----------------------
422.14 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
422.15 -FIX:Replace with absolute import
422.16 -from ..subpackage1 import moduleY
422.17 ----------------------------------
422.18 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
422.19 -FIX:Replace with absolute import
422.20 -from ..subpackage2.moduleZ import eggs
422.21 ---------------------------------------
422.22 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
422.23 -FIX:Replace with absolute import
422.24 -from ..moduleA import foo
422.25 --------------------------
422.26 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
422.27 -FIX:Replace with absolute import
422.28 -from ...package import bar
422.29 ---------------------------
422.30 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
422.31 -FIX:Replace with absolute import
422.32 -from ...sys import path
422.33 ------------------------
422.34 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
422.35 -FIX:Replace with absolute import
423.1 --- a/python.editor/test/unit/data/testfiles/pickle.py Sun Jan 04 13:11:53 2015 -0600
423.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
423.3 @@ -1,1383 +0,0 @@
423.4 -"""Create portable serialized representations of Python objects.
423.5 -
423.6 -See module cPickle for a (much) faster implementation.
423.7 -See module copy_reg for a mechanism for registering custom picklers.
423.8 -See module pickletools source for extensive comments.
423.9 -
423.10 -Classes:
423.11 -
423.12 - Pickler
423.13 - Unpickler
423.14 -
423.15 -Functions:
423.16 -
423.17 - dump(object, file)
423.18 - dumps(object) -> string
423.19 - load(file) -> object
423.20 - loads(string) -> object
423.21 -
423.22 -Misc variables:
423.23 -
423.24 - __version__
423.25 - format_version
423.26 - compatible_formats
423.27 -
423.28 -"""
423.29 -
423.30 -__version__ = "$Revision: 38432 $" # Code version
423.31 -
423.32 -from types import *
423.33 -from copy_reg import dispatch_table
423.34 -from copy_reg import _extension_registry, _inverted_registry, _extension_cache
423.35 -import marshal
423.36 -import sys
423.37 -import struct
423.38 -import re
423.39 -
423.40 -__all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
423.41 - "Unpickler", "dump", "dumps", "load", "loads"]
423.42 -
423.43 -# These are purely informational; no code uses these.
423.44 -format_version = "2.0" # File format version we write
423.45 -compatible_formats = ["1.0", # Original protocol 0
423.46 - "1.1", # Protocol 0 with INST added
423.47 - "1.2", # Original protocol 1
423.48 - "1.3", # Protocol 1 with BINFLOAT added
423.49 - "2.0", # Protocol 2
423.50 - ] # Old format versions we can read
423.51 -
423.52 -# Keep in synch with cPickle. This is the highest protocol number we
423.53 -# know how to read.
423.54 -HIGHEST_PROTOCOL = 2
423.55 -
423.56 -# Why use struct.pack() for pickling but marshal.loads() for
423.57 -# unpickling? struct.pack() is 40% faster than marshal.dumps(), but
423.58 -# marshal.loads() is twice as fast as struct.unpack()!
423.59 -mloads = marshal.loads
423.60 -
423.61 -class PickleError(Exception):
423.62 - """A common base class for the other pickling exceptions."""
423.63 - pass
423.64 -
423.65 -class PicklingError(PickleError):
423.66 - """This exception is raised when an unpicklable object is passed to the
423.67 - dump() method.
423.68 -
423.69 - """
423.70 - pass
423.71 -
423.72 -class UnpicklingError(PickleError):
423.73 - """This exception is raised when there is a problem unpickling an object,
423.74 - such as a security violation.
423.75 -
423.76 - Note that other exceptions may also be raised during unpickling, including
423.77 - (but not necessarily limited to) AttributeError, EOFError, ImportError,
423.78 - and IndexError.
423.79 -
423.80 - """
423.81 - pass
423.82 -
423.83 -# An instance of _Stop is raised by Unpickler.load_stop() in response to
423.84 -# the STOP opcode, passing the object that is the result of unpickling.
423.85 -class _Stop(Exception):
423.86 - def __init__(self, value):
423.87 - self.value = value
423.88 -
423.89 -# Jython has PyStringMap; it's a dict subclass with string keys
423.90 -try:
423.91 - from org.python.core import PyStringMap
423.92 -except ImportError:
423.93 - PyStringMap = None
423.94 -
423.95 -# UnicodeType may or may not be exported (normally imported from types)
423.96 -try:
423.97 - UnicodeType
423.98 -except NameError:
423.99 - UnicodeType = None
423.100 -
423.101 -# Pickle opcodes. See pickletools.py for extensive docs. The listing
423.102 -# here is in kind-of alphabetical order of 1-character pickle code.
423.103 -# pickletools groups them by purpose.
423.104 -
423.105 -MARK = '(' # push special markobject on stack
423.106 -STOP = '.' # every pickle ends with STOP
423.107 -POP = '0' # discard topmost stack item
423.108 -POP_MARK = '1' # discard stack top through topmost markobject
423.109 -DUP = '2' # duplicate top stack item
423.110 -FLOAT = 'F' # push float object; decimal string argument
423.111 -INT = 'I' # push integer or bool; decimal string argument
423.112 -BININT = 'J' # push four-byte signed int
423.113 -BININT1 = 'K' # push 1-byte unsigned int
423.114 -LONG = 'L' # push long; decimal string argument
423.115 -BININT2 = 'M' # push 2-byte unsigned int
423.116 -NONE = 'N' # push None
423.117 -PERSID = 'P' # push persistent object; id is taken from string arg
423.118 -BINPERSID = 'Q' # " " " ; " " " " stack
423.119 -REDUCE = 'R' # apply callable to argtuple, both on stack
423.120 -STRING = 'S' # push string; NL-terminated string argument
423.121 -BINSTRING = 'T' # push string; counted binary string argument
423.122 -SHORT_BINSTRING = 'U' # " " ; " " " " < 256 bytes
423.123 -UNICODE = 'V' # push Unicode string; raw-unicode-escaped'd argument
423.124 -BINUNICODE = 'X' # " " " ; counted UTF-8 string argument
423.125 -APPEND = 'a' # append stack top to list below it
423.126 -BUILD = 'b' # call __setstate__ or __dict__.update()
423.127 -GLOBAL = 'c' # push self.find_class(modname, name); 2 string args
423.128 -DICT = 'd' # build a dict from stack items
423.129 -EMPTY_DICT = '}' # push empty dict
423.130 -APPENDS = 'e' # extend list on stack by topmost stack slice
423.131 -GET = 'g' # push item from memo on stack; index is string arg
423.132 -BINGET = 'h' # " " " " " " ; " " 1-byte arg
423.133 -INST = 'i' # build & push class instance
423.134 -LONG_BINGET = 'j' # push item from memo on stack; index is 4-byte arg
423.135 -LIST = 'l' # build list from topmost stack items
423.136 -EMPTY_LIST = ']' # push empty list
423.137 -OBJ = 'o' # build & push class instance
423.138 -PUT = 'p' # store stack top in memo; index is string arg
423.139 -BINPUT = 'q' # " " " " " ; " " 1-byte arg
423.140 -LONG_BINPUT = 'r' # " " " " " ; " " 4-byte arg
423.141 -SETITEM = 's' # add key+value pair to dict
423.142 -TUPLE = 't' # build tuple from topmost stack items
423.143 -EMPTY_TUPLE = ')' # push empty tuple
423.144 -SETITEMS = 'u' # modify dict by adding topmost key+value pairs
423.145 -BINFLOAT = 'G' # push float; arg is 8-byte float encoding
423.146 -
423.147 -TRUE = 'I01\n' # not an opcode; see INT docs in pickletools.py
423.148 -FALSE = 'I00\n' # not an opcode; see INT docs in pickletools.py
423.149 -
423.150 -# Protocol 2
423.151 -
423.152 -PROTO = '\x80' # identify pickle protocol
423.153 -NEWOBJ = '\x81' # build object by applying cls.__new__ to argtuple
423.154 -EXT1 = '\x82' # push object from extension registry; 1-byte index
423.155 -EXT2 = '\x83' # ditto, but 2-byte index
423.156 -EXT4 = '\x84' # ditto, but 4-byte index
423.157 -TUPLE1 = '\x85' # build 1-tuple from stack top
423.158 -TUPLE2 = '\x86' # build 2-tuple from two topmost stack items
423.159 -TUPLE3 = '\x87' # build 3-tuple from three topmost stack items
423.160 -NEWTRUE = '\x88' # push True
423.161 -NEWFALSE = '\x89' # push False
423.162 -LONG1 = '\x8a' # push long from < 256 bytes
423.163 -LONG4 = '\x8b' # push really big long
423.164 -
423.165 -_tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
423.166 -
423.167 -
423.168 -__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
423.169 -del x
423.170 -
423.171 -
423.172 -# Pickling machinery
423.173 -
423.174 -class Pickler:
423.175 -
423.176 - def __init__(self, file, protocol=None):
423.177 - """This takes a file-like object for writing a pickle data stream.
423.178 -
423.179 - The optional protocol argument tells the pickler to use the
423.180 - given protocol; supported protocols are 0, 1, 2. The default
423.181 - protocol is 0, to be backwards compatible. (Protocol 0 is the
423.182 - only protocol that can be written to a file opened in text
423.183 - mode and read back successfully. When using a protocol higher
423.184 - than 0, make sure the file is opened in binary mode, both when
423.185 - pickling and unpickling.)
423.186 -
423.187 - Protocol 1 is more efficient than protocol 0; protocol 2 is
423.188 - more efficient than protocol 1.
423.189 -
423.190 - Specifying a negative protocol version selects the highest
423.191 - protocol version supported. The higher the protocol used, the
423.192 - more recent the version of Python needed to read the pickle
423.193 - produced.
423.194 -
423.195 - The file parameter must have a write() method that accepts a single
423.196 - string argument. It can thus be an open file object, a StringIO
423.197 - object, or any other custom object that meets this interface.
423.198 -
423.199 - """
423.200 - if protocol is None:
423.201 - protocol = 0
423.202 - if protocol < 0:
423.203 - protocol = HIGHEST_PROTOCOL
423.204 - elif not 0 <= protocol <= HIGHEST_PROTOCOL:
423.205 - raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL)
423.206 - self.write = file.write
423.207 - self.memo = {}
423.208 - self.proto = int(protocol)
423.209 - self.bin = protocol >= 1
423.210 - self.fast = 0
423.211 -
423.212 - def clear_memo(self):
423.213 - """Clears the pickler's "memo".
423.214 -
423.215 - The memo is the data structure that remembers which objects the
423.216 - pickler has already seen, so that shared or recursive objects are
423.217 - pickled by reference and not by value. This method is useful when
423.218 - re-using picklers.
423.219 -
423.220 - """
423.221 - self.memo.clear()
423.222 -
423.223 - def dump(self, obj):
423.224 - """Write a pickled representation of obj to the open file."""
423.225 - if self.proto >= 2:
423.226 - self.write(PROTO + chr(self.proto))
423.227 - self.save(obj)
423.228 - self.write(STOP)
423.229 -
423.230 - def memoize(self, obj):
423.231 - """Store an object in the memo."""
423.232 -
423.233 - # The Pickler memo is a dictionary mapping object ids to 2-tuples
423.234 - # that contain the Unpickler memo key and the object being memoized.
423.235 - # The memo key is written to the pickle and will become
423.236 - # the key in the Unpickler's memo. The object is stored in the
423.237 - # Pickler memo so that transient objects are kept alive during
423.238 - # pickling.
423.239 -
423.240 - # The use of the Unpickler memo length as the memo key is just a
423.241 - # convention. The only requirement is that the memo values be unique.
423.242 - # But there appears no advantage to any other scheme, and this
423.243 - # scheme allows the Unpickler memo to be implemented as a plain (but
423.244 - # growable) array, indexed by memo key.
423.245 - if self.fast:
423.246 - return
423.247 - assert id(obj) not in self.memo
423.248 - memo_len = len(self.memo)
423.249 - self.write(self.put(memo_len))
423.250 - self.memo[id(obj)] = memo_len, obj
423.251 -
423.252 - # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
423.253 - def put(self, i, pack=struct.pack):
423.254 - if self.bin:
423.255 - if i < 256:
423.256 - return BINPUT + chr(i)
423.257 - else:
423.258 - return LONG_BINPUT + pack("<i", i)
423.259 -
423.260 - return PUT + repr(i) + '\n'
423.261 -
423.262 - # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
423.263 - def get(self, i, pack=struct.pack):
423.264 - if self.bin:
423.265 - if i < 256:
423.266 - return BINGET + chr(i)
423.267 - else:
423.268 - return LONG_BINGET + pack("<i", i)
423.269 -
423.270 - return GET + repr(i) + '\n'
423.271 -
423.272 - def save(self, obj):
423.273 - # Check for persistent id (defined by a subclass)
423.274 - pid = self.persistent_id(obj)
423.275 - if pid:
423.276 - self.save_pers(pid)
423.277 - return
423.278 -
423.279 - # Check the memo
423.280 - x = self.memo.get(id(obj))
423.281 - if x:
423.282 - self.write(self.get(x[0]))
423.283 - return
423.284 -
423.285 - # Check the type dispatch table
423.286 - t = type(obj)
423.287 - f = self.dispatch.get(t)
423.288 - if f:
423.289 - f(self, obj) # Call unbound method with explicit self
423.290 - return
423.291 -
423.292 - # Check for a class with a custom metaclass; treat as regular class
423.293 - try:
423.294 - issc = issubclass(t, TypeType)
423.295 - except TypeError: # t is not a class (old Boost; see SF #502085)
423.296 - issc = 0
423.297 - if issc:
423.298 - self.save_global(obj)
423.299 - return
423.300 -
423.301 - # Check copy_reg.dispatch_table
423.302 - reduce = dispatch_table.get(t)
423.303 - if reduce:
423.304 - rv = reduce(obj)
423.305 - else:
423.306 - # Check for a __reduce_ex__ method, fall back to __reduce__
423.307 - reduce = getattr(obj, "__reduce_ex__", None)
423.308 - if reduce:
423.309 - rv = reduce(self.proto)
423.310 - else:
423.311 - reduce = getattr(obj, "__reduce__", None)
423.312 - if reduce:
423.313 - rv = reduce()
423.314 - else:
423.315 - raise PicklingError("Can't pickle %r object: %r" %
423.316 - (t.__name__, obj))
423.317 -
423.318 - # Check for string returned by reduce(), meaning "save as global"
423.319 - if type(rv) is StringType:
423.320 - self.save_global(obj, rv)
423.321 - return
423.322 -
423.323 - # Assert that reduce() returned a tuple
423.324 - if type(rv) is not TupleType:
423.325 - raise PicklingError("%s must return string or tuple" % reduce)
423.326 -
423.327 - # Assert that it returned an appropriately sized tuple
423.328 - l = len(rv)
423.329 - if not (2 <= l <= 5):
423.330 - raise PicklingError("Tuple returned by %s must have "
423.331 - "two to five elements" % reduce)
423.332 -
423.333 - # Save the reduce() output and finally memoize the object
423.334 - self.save_reduce(obj=obj, *rv)
423.335 -
423.336 - def persistent_id(self, obj):
423.337 - # This exists so a subclass can override it
423.338 - return None
423.339 -
423.340 - def save_pers(self, pid):
423.341 - # Save a persistent id reference
423.342 - if self.bin:
423.343 - self.save(pid)
423.344 - self.write(BINPERSID)
423.345 - else:
423.346 - self.write(PERSID + str(pid) + '\n')
423.347 -
423.348 - def save_reduce(self, func, args, state=None,
423.349 - listitems=None, dictitems=None, obj=None):
423.350 - # This API is called by some subclasses
423.351 -
423.352 - # Assert that args is a tuple or None
423.353 - if not isinstance(args, TupleType):
423.354 - raise PicklingError("args from reduce() should be a tuple")
423.355 -
423.356 - # Assert that func is callable
423.357 - if not callable(func):
423.358 - raise PicklingError("func from reduce should be callable")
423.359 -
423.360 - save = self.save
423.361 - write = self.write
423.362 -
423.363 - # Protocol 2 special case: if func's name is __newobj__, use NEWOBJ
423.364 - if self.proto >= 2 and getattr(func, "__name__", "") == "__newobj__":
423.365 - # A __reduce__ implementation can direct protocol 2 to
423.366 - # use the more efficient NEWOBJ opcode, while still
423.367 - # allowing protocol 0 and 1 to work normally. For this to
423.368 - # work, the function returned by __reduce__ should be
423.369 - # called __newobj__, and its first argument should be a
423.370 - # new-style class. The implementation for __newobj__
423.371 - # should be as follows, although pickle has no way to
423.372 - # verify this:
423.373 - #
423.374 - # def __newobj__(cls, *args):
423.375 - # return cls.__new__(cls, *args)
423.376 - #
423.377 - # Protocols 0 and 1 will pickle a reference to __newobj__,
423.378 - # while protocol 2 (and above) will pickle a reference to
423.379 - # cls, the remaining args tuple, and the NEWOBJ code,
423.380 - # which calls cls.__new__(cls, *args) at unpickling time
423.381 - # (see load_newobj below). If __reduce__ returns a
423.382 - # three-tuple, the state from the third tuple item will be
423.383 - # pickled regardless of the protocol, calling __setstate__
423.384 - # at unpickling time (see load_build below).
423.385 - #
423.386 - # Note that no standard __newobj__ implementation exists;
423.387 - # you have to provide your own. This is to enforce
423.388 - # compatibility with Python 2.2 (pickles written using
423.389 - # protocol 0 or 1 in Python 2.3 should be unpicklable by
423.390 - # Python 2.2).
423.391 - cls = args[0]
423.392 - if not hasattr(cls, "__new__"):
423.393 - raise PicklingError(
423.394 - "args[0] from __newobj__ args has no __new__")
423.395 - if obj is not None and cls is not obj.__class__:
423.396 - raise PicklingError(
423.397 - "args[0] from __newobj__ args has the wrong class")
423.398 - args = args[1:]
423.399 - save(cls)
423.400 - save(args)
423.401 - write(NEWOBJ)
423.402 - else:
423.403 - save(func)
423.404 - save(args)
423.405 - write(REDUCE)
423.406 -
423.407 - if obj is not None:
423.408 - self.memoize(obj)
423.409 -
423.410 - # More new special cases (that work with older protocols as
423.411 - # well): when __reduce__ returns a tuple with 4 or 5 items,
423.412 - # the 4th and 5th item should be iterators that provide list
423.413 - # items and dict items (as (key, value) tuples), or None.
423.414 -
423.415 - if listitems is not None:
423.416 - self._batch_appends(listitems)
423.417 -
423.418 - if dictitems is not None:
423.419 - self._batch_setitems(dictitems)
423.420 -
423.421 - if state is not None:
423.422 - save(state)
423.423 - write(BUILD)
423.424 -
423.425 - # Methods below this point are dispatched through the dispatch table
423.426 -
423.427 - dispatch = {}
423.428 -
423.429 - def save_none(self, obj):
423.430 - self.write(NONE)
423.431 - dispatch[NoneType] = save_none
423.432 -
423.433 - def save_bool(self, obj):
423.434 - if self.proto >= 2:
423.435 - self.write(obj and NEWTRUE or NEWFALSE)
423.436 - else:
423.437 - self.write(obj and TRUE or FALSE)
423.438 - dispatch[bool] = save_bool
423.439 -
423.440 - def save_int(self, obj, pack=struct.pack):
423.441 - if self.bin:
423.442 - # If the int is small enough to fit in a signed 4-byte 2's-comp
423.443 - # format, we can store it more efficiently than the general
423.444 - # case.
423.445 - # First one- and two-byte unsigned ints:
423.446 - if obj >= 0:
423.447 - if obj <= 0xff:
423.448 - self.write(BININT1 + chr(obj))
423.449 - return
423.450 - if obj <= 0xffff:
423.451 - self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8))
423.452 - return
423.453 - # Next check for 4-byte signed ints:
423.454 - high_bits = obj >> 31 # note that Python shift sign-extends
423.455 - if high_bits == 0 or high_bits == -1:
423.456 - # All high bits are copies of bit 2**31, so the value
423.457 - # fits in a 4-byte signed int.
423.458 - self.write(BININT + pack("<i", obj))
423.459 - return
423.460 - # Text pickle, or int too big to fit in signed 4-byte format.
423.461 - self.write(INT + repr(obj) + '\n')
423.462 - dispatch[IntType] = save_int
423.463 -
423.464 - def save_long(self, obj, pack=struct.pack):
423.465 - if self.proto >= 2:
423.466 - bytes = encode_long(obj)
423.467 - n = len(bytes)
423.468 - if n < 256:
423.469 - self.write(LONG1 + chr(n) + bytes)
423.470 - else:
423.471 - self.write(LONG4 + pack("<i", n) + bytes)
423.472 - return
423.473 - self.write(LONG + repr(obj) + '\n')
423.474 - dispatch[LongType] = save_long
423.475 -
423.476 - def save_float(self, obj, pack=struct.pack):
423.477 - if self.bin:
423.478 - self.write(BINFLOAT + pack('>d', obj))
423.479 - else:
423.480 - self.write(FLOAT + repr(obj) + '\n')
423.481 - dispatch[FloatType] = save_float
423.482 -
423.483 - def save_string(self, obj, pack=struct.pack):
423.484 - if self.bin:
423.485 - n = len(obj)
423.486 - if n < 256:
423.487 - self.write(SHORT_BINSTRING + chr(n) + obj)
423.488 - else:
423.489 - self.write(BINSTRING + pack("<i", n) + obj)
423.490 - else:
423.491 - self.write(STRING + repr(obj) + '\n')
423.492 - self.memoize(obj)
423.493 - dispatch[StringType] = save_string
423.494 -
423.495 - def save_unicode(self, obj, pack=struct.pack):
423.496 - if self.bin:
423.497 - encoding = obj.encode('utf-8')
423.498 - n = len(encoding)
423.499 - self.write(BINUNICODE + pack("<i", n) + encoding)
423.500 - else:
423.501 - obj = obj.replace("\\", "\\u005c")
423.502 - obj = obj.replace("\n", "\\u000a")
423.503 - self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
423.504 - self.memoize(obj)
423.505 - dispatch[UnicodeType] = save_unicode
423.506 -
423.507 - if StringType == UnicodeType:
423.508 - # This is true for Jython
423.509 - def save_string(self, obj, pack=struct.pack):
423.510 - unicode = obj.isunicode()
423.511 -
423.512 - if self.bin:
423.513 - if unicode:
423.514 - obj = obj.encode("utf-8")
423.515 - l = len(obj)
423.516 - if l < 256 and not unicode:
423.517 - self.write(SHORT_BINSTRING + chr(l) + obj)
423.518 - else:
423.519 - s = pack("<i", l)
423.520 - if unicode:
423.521 - self.write(BINUNICODE + s + obj)
423.522 - else:
423.523 - self.write(BINSTRING + s + obj)
423.524 - else:
423.525 - if unicode:
423.526 - obj = obj.replace("\\", "\\u005c")
423.527 - obj = obj.replace("\n", "\\u000a")
423.528 - obj = obj.encode('raw-unicode-escape')
423.529 - self.write(UNICODE + obj + '\n')
423.530 - else:
423.531 - self.write(STRING + repr(obj) + '\n')
423.532 - self.memoize(obj)
423.533 - dispatch[StringType] = save_string
423.534 -
423.535 - def save_tuple(self, obj):
423.536 - write = self.write
423.537 - proto = self.proto
423.538 -
423.539 - n = len(obj)
423.540 - if n == 0:
423.541 - if proto:
423.542 - write(EMPTY_TUPLE)
423.543 - else:
423.544 - write(MARK + TUPLE)
423.545 - return
423.546 -
423.547 - save = self.save
423.548 - memo = self.memo
423.549 - if n <= 3 and proto >= 2:
423.550 - for element in obj:
423.551 - save(element)
423.552 - # Subtle. Same as in the big comment below.
423.553 - if id(obj) in memo:
423.554 - get = self.get(memo[id(obj)][0])
423.555 - write(POP * n + get)
423.556 - else:
423.557 - write(_tuplesize2code[n])
423.558 - self.memoize(obj)
423.559 - return
423.560 -
423.561 - # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
423.562 - # has more than 3 elements.
423.563 - write(MARK)
423.564 - for element in obj:
423.565 - save(element)
423.566 -
423.567 - if id(obj) in memo:
423.568 - # Subtle. d was not in memo when we entered save_tuple(), so
423.569 - # the process of saving the tuple's elements must have saved
423.570 - # the tuple itself: the tuple is recursive. The proper action
423.571 - # now is to throw away everything we put on the stack, and
423.572 - # simply GET the tuple (it's already constructed). This check
423.573 - # could have been done in the "for element" loop instead, but
423.574 - # recursive tuples are a rare thing.
423.575 - get = self.get(memo[id(obj)][0])
423.576 - if proto:
423.577 - write(POP_MARK + get)
423.578 - else: # proto 0 -- POP_MARK not available
423.579 - write(POP * (n+1) + get)
423.580 - return
423.581 -
423.582 - # No recursion.
423.583 - self.write(TUPLE)
423.584 - self.memoize(obj)
423.585 -
423.586 - dispatch[TupleType] = save_tuple
423.587 -
423.588 - # save_empty_tuple() isn't used by anything in Python 2.3. However, I
423.589 - # found a Pickler subclass in Zope3 that calls it, so it's not harmless
423.590 - # to remove it.
423.591 - def save_empty_tuple(self, obj):
423.592 - self.write(EMPTY_TUPLE)
423.593 -
423.594 - def save_list(self, obj):
423.595 - write = self.write
423.596 -
423.597 - if self.bin:
423.598 - write(EMPTY_LIST)
423.599 - else: # proto 0 -- can't use EMPTY_LIST
423.600 - write(MARK + LIST)
423.601 -
423.602 - self.memoize(obj)
423.603 - self._batch_appends(iter(obj))
423.604 -
423.605 - dispatch[ListType] = save_list
423.606 -
423.607 - # Keep in synch with cPickle's BATCHSIZE. Nothing will break if it gets
423.608 - # out of synch, though.
423.609 - _BATCHSIZE = 1000
423.610 -
423.611 - def _batch_appends(self, items):
423.612 - # Helper to batch up APPENDS sequences
423.613 - save = self.save
423.614 - write = self.write
423.615 -
423.616 - if not self.bin:
423.617 - for x in items:
423.618 - save(x)
423.619 - write(APPEND)
423.620 - return
423.621 -
423.622 - r = xrange(self._BATCHSIZE)
423.623 - while items is not None:
423.624 - tmp = []
423.625 - for i in r:
423.626 - try:
423.627 - x = items.next()
423.628 - tmp.append(x)
423.629 - except StopIteration:
423.630 - items = None
423.631 - break
423.632 - n = len(tmp)
423.633 - if n > 1:
423.634 - write(MARK)
423.635 - for x in tmp:
423.636 - save(x)
423.637 - write(APPENDS)
423.638 - elif n:
423.639 - save(tmp[0])
423.640 - write(APPEND)
423.641 - # else tmp is empty, and we're done
423.642 -
423.643 - def save_dict(self, obj):
423.644 - write = self.write
423.645 -
423.646 - if self.bin:
423.647 - write(EMPTY_DICT)
423.648 - else: # proto 0 -- can't use EMPTY_DICT
423.649 - write(MARK + DICT)
423.650 -
423.651 - self.memoize(obj)
423.652 - self._batch_setitems(obj.iteritems())
423.653 -
423.654 - dispatch[DictionaryType] = save_dict
423.655 - if not PyStringMap is None:
423.656 - dispatch[PyStringMap] = save_dict
423.657 -
423.658 - def _batch_setitems(self, items):
423.659 - # Helper to batch up SETITEMS sequences; proto >= 1 only
423.660 - save = self.save
423.661 - write = self.write
423.662 -
423.663 - if not self.bin:
423.664 - for k, v in items:
423.665 - save(k)
423.666 - save(v)
423.667 - write(SETITEM)
423.668 - return
423.669 -
423.670 - r = xrange(self._BATCHSIZE)
423.671 - while items is not None:
423.672 - tmp = []
423.673 - for i in r:
423.674 - try:
423.675 - tmp.append(items.next())
423.676 - except StopIteration:
423.677 - items = None
423.678 - break
423.679 - n = len(tmp)
423.680 - if n > 1:
423.681 - write(MARK)
423.682 - for k, v in tmp:
423.683 - save(k)
423.684 - save(v)
423.685 - write(SETITEMS)
423.686 - elif n:
423.687 - k, v = tmp[0]
423.688 - save(k)
423.689 - save(v)
423.690 - write(SETITEM)
423.691 - # else tmp is empty, and we're done
423.692 -
423.693 - def save_inst(self, obj):
423.694 - cls = obj.__class__
423.695 -
423.696 - memo = self.memo
423.697 - write = self.write
423.698 - save = self.save
423.699 -
423.700 - if hasattr(obj, '__getinitargs__'):
423.701 - args = obj.__getinitargs__()
423.702 - len(args) # XXX Assert it's a sequence
423.703 - _keep_alive(args, memo)
423.704 - else:
423.705 - args = ()
423.706 -
423.707 - write(MARK)
423.708 -
423.709 - if self.bin:
423.710 - save(cls)
423.711 - for arg in args:
423.712 - save(arg)
423.713 - write(OBJ)
423.714 - else:
423.715 - for arg in args:
423.716 - save(arg)
423.717 - write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
423.718 -
423.719 - self.memoize(obj)
423.720 -
423.721 - try:
423.722 - getstate = obj.__getstate__
423.723 - except AttributeError:
423.724 - stuff = obj.__dict__
423.725 - else:
423.726 - stuff = getstate()
423.727 - _keep_alive(stuff, memo)
423.728 - save(stuff)
423.729 - write(BUILD)
423.730 -
423.731 - dispatch[InstanceType] = save_inst
423.732 -
423.733 - def save_global(self, obj, name=None, pack=struct.pack):
423.734 - write = self.write
423.735 - memo = self.memo
423.736 -
423.737 - if name is None:
423.738 - name = obj.__name__
423.739 -
423.740 - module = getattr(obj, "__module__", None)
423.741 - if module is None:
423.742 - module = whichmodule(obj, name)
423.743 -
423.744 - try:
423.745 - __import__(module)
423.746 - mod = sys.modules[module]
423.747 - klass = getattr(mod, name)
423.748 - except (ImportError, KeyError, AttributeError):
423.749 - raise PicklingError(
423.750 - "Can't pickle %r: it's not found as %s.%s" %
423.751 - (obj, module, name))
423.752 - else:
423.753 - if klass is not obj:
423.754 - raise PicklingError(
423.755 - "Can't pickle %r: it's not the same object as %s.%s" %
423.756 - (obj, module, name))
423.757 -
423.758 - if self.proto >= 2:
423.759 - code = _extension_registry.get((module, name))
423.760 - if code:
423.761 - assert code > 0
423.762 - if code <= 0xff:
423.763 - write(EXT1 + chr(code))
423.764 - elif code <= 0xffff:
423.765 - write("%c%c%c" % (EXT2, code&0xff, code>>8))
423.766 - else:
423.767 - write(EXT4 + pack("<i", code))
423.768 - return
423.769 -
423.770 - write(GLOBAL + module + '\n' + name + '\n')
423.771 - self.memoize(obj)
423.772 -
423.773 - dispatch[ClassType] = save_global
423.774 - dispatch[FunctionType] = save_global
423.775 - dispatch[BuiltinFunctionType] = save_global
423.776 - dispatch[TypeType] = save_global
423.777 -
423.778 -# Pickling helpers
423.779 -
423.780 -def _keep_alive(x, memo):
423.781 - """Keeps a reference to the object x in the memo.
423.782 -
423.783 - Because we remember objects by their id, we have
423.784 - to assure that possibly temporary objects are kept
423.785 - alive by referencing them.
423.786 - We store a reference at the id of the memo, which should
423.787 - normally not be used unless someone tries to deepcopy
423.788 - the memo itself...
423.789 - """
423.790 - try:
423.791 - memo[id(memo)].append(x)
423.792 - except KeyError:
423.793 - # aha, this is the first one :-)
423.794 - memo[id(memo)]=[x]
423.795 -
423.796 -
423.797 -# A cache for whichmodule(), mapping a function object to the name of
423.798 -# the module in which the function was found.
423.799 -
423.800 -classmap = {} # called classmap for backwards compatibility
423.801 -
423.802 -def whichmodule(func, funcname):
423.803 - """Figure out the module in which a function occurs.
423.804 -
423.805 - Search sys.modules for the module.
423.806 - Cache in classmap.
423.807 - Return a module name.
423.808 - If the function cannot be found, return "__main__".
423.809 - """
423.810 - # Python functions should always get an __module__ from their globals.
423.811 - mod = getattr(func, "__module__", None)
423.812 - if mod is not None:
423.813 - return mod
423.814 - if func in classmap:
423.815 - return classmap[func]
423.816 -
423.817 - for name, module in sys.modules.items():
423.818 - if module is None:
423.819 - continue # skip dummy package entries
423.820 - if name != '__main__' and getattr(module, funcname, None) is func:
423.821 - break
423.822 - else:
423.823 - name = '__main__'
423.824 - classmap[func] = name
423.825 - return name
423.826 -
423.827 -
423.828 -# Unpickling machinery
423.829 -
423.830 -class Unpickler:
423.831 -
423.832 - def __init__(self, file):
423.833 - """This takes a file-like object for reading a pickle data stream.
423.834 -
423.835 - The protocol version of the pickle is detected automatically, so no
423.836 - proto argument is needed.
423.837 -
423.838 - The file-like object must have two methods, a read() method that
423.839 - takes an integer argument, and a readline() method that requires no
423.840 - arguments. Both methods should return a string. Thus file-like
423.841 - object can be a file object opened for reading, a StringIO object,
423.842 - or any other custom object that meets this interface.
423.843 - """
423.844 - self.readline = file.readline
423.845 - self.read = file.read
423.846 - self.memo = {}
423.847 -
423.848 - def load(self):
423.849 - """Read a pickled object representation from the open file.
423.850 -
423.851 - Return the reconstituted object hierarchy specified in the file.
423.852 - """
423.853 - self.mark = object() # any new unique object
423.854 - self.stack = []
423.855 - self.append = self.stack.append
423.856 - read = self.read
423.857 - dispatch = self.dispatch
423.858 - try:
423.859 - while 1:
423.860 - key = read(1)
423.861 - dispatch[key](self)
423.862 - except _Stop, stopinst:
423.863 - return stopinst.value
423.864 -
423.865 - # Return largest index k such that self.stack[k] is self.mark.
423.866 - # If the stack doesn't contain a mark, eventually raises IndexError.
423.867 - # This could be sped by maintaining another stack, of indices at which
423.868 - # the mark appears. For that matter, the latter stack would suffice,
423.869 - # and we wouldn't need to push mark objects on self.stack at all.
423.870 - # Doing so is probably a good thing, though, since if the pickle is
423.871 - # corrupt (or hostile) we may get a clue from finding self.mark embedded
423.872 - # in unpickled objects.
423.873 - def marker(self):
423.874 - stack = self.stack
423.875 - mark = self.mark
423.876 - k = len(stack)-1
423.877 - while stack[k] is not mark: k = k-1
423.878 - return k
423.879 -
423.880 - dispatch = {}
423.881 -
423.882 - def load_eof(self):
423.883 - raise EOFError
423.884 - dispatch[''] = load_eof
423.885 -
423.886 - def load_proto(self):
423.887 - proto = ord(self.read(1))
423.888 - if not 0 <= proto <= 2:
423.889 - raise ValueError, "unsupported pickle protocol: %d" % proto
423.890 - dispatch[PROTO] = load_proto
423.891 -
423.892 - def load_persid(self):
423.893 - pid = self.readline()[:-1]
423.894 - self.append(self.persistent_load(pid))
423.895 - dispatch[PERSID] = load_persid
423.896 -
423.897 - def load_binpersid(self):
423.898 - pid = self.stack.pop()
423.899 - self.append(self.persistent_load(pid))
423.900 - dispatch[BINPERSID] = load_binpersid
423.901 -
423.902 - def load_none(self):
423.903 - self.append(None)
423.904 - dispatch[NONE] = load_none
423.905 -
423.906 - def load_false(self):
423.907 - self.append(False)
423.908 - dispatch[NEWFALSE] = load_false
423.909 -
423.910 - def load_true(self):
423.911 - self.append(True)
423.912 - dispatch[NEWTRUE] = load_true
423.913 -
423.914 - def load_int(self):
423.915 - data = self.readline()
423.916 - if data == FALSE[1:]:
423.917 - val = False
423.918 - elif data == TRUE[1:]:
423.919 - val = True
423.920 - else:
423.921 - try:
423.922 - val = int(data)
423.923 - except ValueError:
423.924 - val = long(data)
423.925 - self.append(val)
423.926 - dispatch[INT] = load_int
423.927 -
423.928 - def load_binint(self):
423.929 - self.append(mloads('i' + self.read(4)))
423.930 - dispatch[BININT] = load_binint
423.931 -
423.932 - def load_binint1(self):
423.933 - self.append(ord(self.read(1)))
423.934 - dispatch[BININT1] = load_binint1
423.935 -
423.936 - def load_binint2(self):
423.937 - self.append(mloads('i' + self.read(2) + '\000\000'))
423.938 - dispatch[BININT2] = load_binint2
423.939 -
423.940 - def load_long(self):
423.941 - self.append(long(self.readline()[:-1], 0))
423.942 - dispatch[LONG] = load_long
423.943 -
423.944 - def load_long1(self):
423.945 - n = ord(self.read(1))
423.946 - bytes = self.read(n)
423.947 - self.append(decode_long(bytes))
423.948 - dispatch[LONG1] = load_long1
423.949 -
423.950 - def load_long4(self):
423.951 - n = mloads('i' + self.read(4))
423.952 - bytes = self.read(n)
423.953 - self.append(decode_long(bytes))
423.954 - dispatch[LONG4] = load_long4
423.955 -
423.956 - def load_float(self):
423.957 - self.append(float(self.readline()[:-1]))
423.958 - dispatch[FLOAT] = load_float
423.959 -
423.960 - def load_binfloat(self, unpack=struct.unpack):
423.961 - self.append(unpack('>d', self.read(8))[0])
423.962 - dispatch[BINFLOAT] = load_binfloat
423.963 -
423.964 - def load_string(self):
423.965 - rep = self.readline()[:-1]
423.966 - for q in "\"'": # double or single quote
423.967 - if rep.startswith(q):
423.968 - if not rep.endswith(q):
423.969 - raise ValueError, "insecure string pickle"
423.970 - rep = rep[len(q):-len(q)]
423.971 - break
423.972 - else:
423.973 - raise ValueError, "insecure string pickle"
423.974 - self.append(rep.decode("string-escape"))
423.975 - dispatch[STRING] = load_string
423.976 -
423.977 - def load_binstring(self):
423.978 - len = mloads('i' + self.read(4))
423.979 - self.append(self.read(len))
423.980 - dispatch[BINSTRING] = load_binstring
423.981 -
423.982 - def load_unicode(self):
423.983 - self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
423.984 - dispatch[UNICODE] = load_unicode
423.985 -
423.986 - def load_binunicode(self):
423.987 - len = mloads('i' + self.read(4))
423.988 - self.append(unicode(self.read(len),'utf-8'))
423.989 - dispatch[BINUNICODE] = load_binunicode
423.990 -
423.991 - def load_short_binstring(self):
423.992 - len = ord(self.read(1))
423.993 - self.append(self.read(len))
423.994 - dispatch[SHORT_BINSTRING] = load_short_binstring
423.995 -
423.996 - def load_tuple(self):
423.997 - k = self.marker()
423.998 - self.stack[k:] = [tuple(self.stack[k+1:])]
423.999 - dispatch[TUPLE] = load_tuple
423.1000 -
423.1001 - def load_empty_tuple(self):
423.1002 - self.stack.append(())
423.1003 - dispatch[EMPTY_TUPLE] = load_empty_tuple
423.1004 -
423.1005 - def load_tuple1(self):
423.1006 - self.stack[-1] = (self.stack[-1],)
423.1007 - dispatch[TUPLE1] = load_tuple1
423.1008 -
423.1009 - def load_tuple2(self):
423.1010 - self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
423.1011 - dispatch[TUPLE2] = load_tuple2
423.1012 -
423.1013 - def load_tuple3(self):
423.1014 - self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
423.1015 - dispatch[TUPLE3] = load_tuple3
423.1016 -
423.1017 - def load_empty_list(self):
423.1018 - self.stack.append([])
423.1019 - dispatch[EMPTY_LIST] = load_empty_list
423.1020 -
423.1021 - def load_empty_dictionary(self):
423.1022 - self.stack.append({})
423.1023 - dispatch[EMPTY_DICT] = load_empty_dictionary
423.1024 -
423.1025 - def load_list(self):
423.1026 - k = self.marker()
423.1027 - self.stack[k:] = [self.stack[k+1:]]
423.1028 - dispatch[LIST] = load_list
423.1029 -
423.1030 - def load_dict(self):
423.1031 - k = self.marker()
423.1032 - d = {}
423.1033 - items = self.stack[k+1:]
423.1034 - for i in range(0, len(items), 2):
423.1035 - key = items[i]
423.1036 - value = items[i+1]
423.1037 - d[key] = value
423.1038 - self.stack[k:] = [d]
423.1039 - dispatch[DICT] = load_dict
423.1040 -
423.1041 - # INST and OBJ differ only in how they get a class object. It's not
423.1042 - # only sensible to do the rest in a common routine, the two routines
423.1043 - # previously diverged and grew different bugs.
423.1044 - # klass is the class to instantiate, and k points to the topmost mark
423.1045 - # object, following which are the arguments for klass.__init__.
423.1046 - def _instantiate(self, klass, k):
423.1047 - args = tuple(self.stack[k+1:])
423.1048 - del self.stack[k:]
423.1049 - instantiated = 0
423.1050 - if (not args and
423.1051 - type(klass) is ClassType and
423.1052 - not hasattr(klass, "__getinitargs__")):
423.1053 - try:
423.1054 - value = _EmptyClass()
423.1055 - value.__class__ = klass
423.1056 - instantiated = 1
423.1057 - except RuntimeError:
423.1058 - # In restricted execution, assignment to inst.__class__ is
423.1059 - # prohibited
423.1060 - pass
423.1061 - if not instantiated:
423.1062 - try:
423.1063 - value = klass(*args)
423.1064 - except TypeError, err:
423.1065 - raise TypeError, "in constructor for %s: %s" % (
423.1066 - klass.__name__, str(err)), sys.exc_info()[2]
423.1067 - self.append(value)
423.1068 -
423.1069 - def load_inst(self):
423.1070 - module = self.readline()[:-1]
423.1071 - name = self.readline()[:-1]
423.1072 - klass = self.find_class(module, name)
423.1073 - self._instantiate(klass, self.marker())
423.1074 - dispatch[INST] = load_inst
423.1075 -
423.1076 - def load_obj(self):
423.1077 - # Stack is ... markobject classobject arg1 arg2 ...
423.1078 - k = self.marker()
423.1079 - klass = self.stack.pop(k+1)
423.1080 - self._instantiate(klass, k)
423.1081 - dispatch[OBJ] = load_obj
423.1082 -
423.1083 - def load_newobj(self):
423.1084 - args = self.stack.pop()
423.1085 - cls = self.stack[-1]
423.1086 - obj = cls.__new__(cls, *args)
423.1087 - self.stack[-1] = obj
423.1088 - dispatch[NEWOBJ] = load_newobj
423.1089 -
423.1090 - def load_global(self):
423.1091 - module = self.readline()[:-1]
423.1092 - name = self.readline()[:-1]
423.1093 - klass = self.find_class(module, name)
423.1094 - self.append(klass)
423.1095 - dispatch[GLOBAL] = load_global
423.1096 -
423.1097 - def load_ext1(self):
423.1098 - code = ord(self.read(1))
423.1099 - self.get_extension(code)
423.1100 - dispatch[EXT1] = load_ext1
423.1101 -
423.1102 - def load_ext2(self):
423.1103 - code = mloads('i' + self.read(2) + '\000\000')
423.1104 - self.get_extension(code)
423.1105 - dispatch[EXT2] = load_ext2
423.1106 -
423.1107 - def load_ext4(self):
423.1108 - code = mloads('i' + self.read(4))
423.1109 - self.get_extension(code)
423.1110 - dispatch[EXT4] = load_ext4
423.1111 -
423.1112 - def get_extension(self, code):
423.1113 - nil = []
423.1114 - obj = _extension_cache.get(code, nil)
423.1115 - if obj is not nil:
423.1116 - self.append(obj)
423.1117 - return
423.1118 - key = _inverted_registry.get(code)
423.1119 - if not key:
423.1120 - raise ValueError("unregistered extension code %d" % code)
423.1121 - obj = self.find_class(*key)
423.1122 - _extension_cache[code] = obj
423.1123 - self.append(obj)
423.1124 -
423.1125 - def find_class(self, module, name):
423.1126 - # Subclasses may override this
423.1127 - __import__(module)
423.1128 - mod = sys.modules[module]
423.1129 - klass = getattr(mod, name)
423.1130 - return klass
423.1131 -
423.1132 - def load_reduce(self):
423.1133 - stack = self.stack
423.1134 - args = stack.pop()
423.1135 - func = stack[-1]
423.1136 - value = func(*args)
423.1137 - stack[-1] = value
423.1138 - dispatch[REDUCE] = load_reduce
423.1139 -
423.1140 - def load_pop(self):
423.1141 - del self.stack[-1]
423.1142 - dispatch[POP] = load_pop
423.1143 -
423.1144 - def load_pop_mark(self):
423.1145 - k = self.marker()
423.1146 - del self.stack[k:]
423.1147 - dispatch[POP_MARK] = load_pop_mark
423.1148 -
423.1149 - def load_dup(self):
423.1150 - self.append(self.stack[-1])
423.1151 - dispatch[DUP] = load_dup
423.1152 -
423.1153 - def load_get(self):
423.1154 - self.append(self.memo[self.readline()[:-1]])
423.1155 - dispatch[GET] = load_get
423.1156 -
423.1157 - def load_binget(self):
423.1158 - i = ord(self.read(1))
423.1159 - self.append(self.memo[repr(i)])
423.1160 - dispatch[BINGET] = load_binget
423.1161 -
423.1162 - def load_long_binget(self):
423.1163 - i = mloads('i' + self.read(4))
423.1164 - self.append(self.memo[repr(i)])
423.1165 - dispatch[LONG_BINGET] = load_long_binget
423.1166 -
423.1167 - def load_put(self):
423.1168 - self.memo[self.readline()[:-1]] = self.stack[-1]
423.1169 - dispatch[PUT] = load_put
423.1170 -
423.1171 - def load_binput(self):
423.1172 - i = ord(self.read(1))
423.1173 - self.memo[repr(i)] = self.stack[-1]
423.1174 - dispatch[BINPUT] = load_binput
423.1175 -
423.1176 - def load_long_binput(self):
423.1177 - i = mloads('i' + self.read(4))
423.1178 - self.memo[repr(i)] = self.stack[-1]
423.1179 - dispatch[LONG_BINPUT] = load_long_binput
423.1180 -
423.1181 - def load_append(self):
423.1182 - stack = self.stack
423.1183 - value = stack.pop()
423.1184 - list = stack[-1]
423.1185 - list.append(value)
423.1186 - dispatch[APPEND] = load_append
423.1187 -
423.1188 - def load_appends(self):
423.1189 - stack = self.stack
423.1190 - mark = self.marker()
423.1191 - list = stack[mark - 1]
423.1192 - list.extend(stack[mark + 1:])
423.1193 - del stack[mark:]
423.1194 - dispatch[APPENDS] = load_appends
423.1195 -
423.1196 - def load_setitem(self):
423.1197 - stack = self.stack
423.1198 - value = stack.pop()
423.1199 - key = stack.pop()
423.1200 - dict = stack[-1]
423.1201 - dict[key] = value
423.1202 - dispatch[SETITEM] = load_setitem
423.1203 -
423.1204 - def load_setitems(self):
423.1205 - stack = self.stack
423.1206 - mark = self.marker()
423.1207 - dict = stack[mark - 1]
423.1208 - for i in range(mark + 1, len(stack), 2):
423.1209 - dict[stack[i]] = stack[i + 1]
423.1210 -
423.1211 - del stack[mark:]
423.1212 - dispatch[SETITEMS] = load_setitems
423.1213 -
423.1214 - def load_build(self):
423.1215 - stack = self.stack
423.1216 - state = stack.pop()
423.1217 - inst = stack[-1]
423.1218 - setstate = getattr(inst, "__setstate__", None)
423.1219 - if setstate:
423.1220 - setstate(state)
423.1221 - return
423.1222 - slotstate = None
423.1223 - if isinstance(state, tuple) and len(state) == 2:
423.1224 - state, slotstate = state
423.1225 - if state:
423.1226 - try:
423.1227 - inst.__dict__.update(state)
423.1228 - except RuntimeError:
423.1229 - # XXX In restricted execution, the instance's __dict__
423.1230 - # is not accessible. Use the old way of unpickling
423.1231 - # the instance variables. This is a semantic
423.1232 - # difference when unpickling in restricted
423.1233 - # vs. unrestricted modes.
423.1234 - # Note, however, that cPickle has never tried to do the
423.1235 - # .update() business, and always uses
423.1236 - # PyObject_SetItem(inst.__dict__, key, value) in a
423.1237 - # loop over state.items().
423.1238 - for k, v in state.items():
423.1239 - setattr(inst, k, v)
423.1240 - if slotstate:
423.1241 - for k, v in slotstate.items():
423.1242 - setattr(inst, k, v)
423.1243 - dispatch[BUILD] = load_build
423.1244 -
423.1245 - def load_mark(self):
423.1246 - self.append(self.mark)
423.1247 - dispatch[MARK] = load_mark
423.1248 -
423.1249 - def load_stop(self):
423.1250 - value = self.stack.pop()
423.1251 - raise _Stop(value)
423.1252 - dispatch[STOP] = load_stop
423.1253 -
423.1254 -# Helper class for load_inst/load_obj
423.1255 -
423.1256 -class _EmptyClass:
423.1257 - pass
423.1258 -
423.1259 -# Encode/decode longs in linear time.
423.1260 -
423.1261 -import binascii as _binascii
423.1262 -
423.1263 -def encode_long(x):
423.1264 - r"""Encode a long to a two's complement little-endian binary string.
423.1265 - Note that 0L is a special case, returning an empty string, to save a
423.1266 - byte in the LONG1 pickling context.
423.1267 -
423.1268 - >>> encode_long(0L)
423.1269 - ''
423.1270 - >>> encode_long(255L)
423.1271 - '\xff\x00'
423.1272 - >>> encode_long(32767L)
423.1273 - '\xff\x7f'
423.1274 - >>> encode_long(-256L)
423.1275 - '\x00\xff'
423.1276 - >>> encode_long(-32768L)
423.1277 - '\x00\x80'
423.1278 - >>> encode_long(-128L)
423.1279 - '\x80'
423.1280 - >>> encode_long(127L)
423.1281 - '\x7f'
423.1282 - >>>
423.1283 - """
423.1284 -
423.1285 - if x == 0:
423.1286 - return ''
423.1287 - if x > 0:
423.1288 - ashex = hex(x)
423.1289 - assert ashex.startswith("0x")
423.1290 - njunkchars = 2 + ashex.endswith('L')
423.1291 - nibbles = len(ashex) - njunkchars
423.1292 - if nibbles & 1:
423.1293 - # need an even # of nibbles for unhexlify
423.1294 - ashex = "0x0" + ashex[2:]
423.1295 - elif int(ashex[2], 16) >= 8:
423.1296 - # "looks negative", so need a byte of sign bits
423.1297 - ashex = "0x00" + ashex[2:]
423.1298 - else:
423.1299 - # Build the 256's-complement: (1L << nbytes) + x. The trick is
423.1300 - # to find the number of bytes in linear time (although that should
423.1301 - # really be a constant-time task).
423.1302 - ashex = hex(-x)
423.1303 - assert ashex.startswith("0x")
423.1304 - njunkchars = 2 + ashex.endswith('L')
423.1305 - nibbles = len(ashex) - njunkchars
423.1306 - if nibbles & 1:
423.1307 - # Extend to a full byte.
423.1308 - nibbles += 1
423.1309 - nbits = nibbles * 4
423.1310 - x += 1L << nbits
423.1311 - assert x > 0
423.1312 - ashex = hex(x)
423.1313 - njunkchars = 2 + ashex.endswith('L')
423.1314 - newnibbles = len(ashex) - njunkchars
423.1315 - if newnibbles < nibbles:
423.1316 - ashex = "0x" + "0" * (nibbles - newnibbles) + ashex[2:]
423.1317 - if int(ashex[2], 16) < 8:
423.1318 - # "looks positive", so need a byte of sign bits
423.1319 - ashex = "0xff" + ashex[2:]
423.1320 -
423.1321 - if ashex.endswith('L'):
423.1322 - ashex = ashex[2:-1]
423.1323 - else:
423.1324 - ashex = ashex[2:]
423.1325 - assert len(ashex) & 1 == 0, (x, ashex)
423.1326 - binary = _binascii.unhexlify(ashex)
423.1327 - return binary[::-1]
423.1328 -
423.1329 -def decode_long(data):
423.1330 - r"""Decode a long from a two's complement little-endian binary string.
423.1331 -
423.1332 - >>> decode_long('')
423.1333 - 0L
423.1334 - >>> decode_long("\xff\x00")
423.1335 - 255L
423.1336 - >>> decode_long("\xff\x7f")
423.1337 - 32767L
423.1338 - >>> decode_long("\x00\xff")
423.1339 - -256L
423.1340 - >>> decode_long("\x00\x80")
423.1341 - -32768L
423.1342 - >>> decode_long("\x80")
423.1343 - -128L
423.1344 - >>> decode_long("\x7f")
423.1345 - 127L
423.1346 - """
423.1347 -
423.1348 - nbytes = len(data)
423.1349 - if nbytes == 0:
423.1350 - return 0L
423.1351 - ashex = _binascii.hexlify(data[::-1])
423.1352 - n = long(ashex, 16) # quadratic time before Python 2.3; linear now
423.1353 - if data[-1] >= '\x80':
423.1354 - n -= 1L << (nbytes * 8)
423.1355 - return n
423.1356 -
423.1357 -# Shorthands
423.1358 -
423.1359 -try:
423.1360 - from cStringIO import StringIO
423.1361 -except ImportError:
423.1362 - from StringIO import StringIO
423.1363 -
423.1364 -def dump(obj, file, protocol=None):
423.1365 - Pickler(file, protocol).dump(obj)
423.1366 -
423.1367 -def dumps(obj, protocol=None):
423.1368 - file = StringIO()
423.1369 - Pickler(file, protocol).dump(obj)
423.1370 - return file.getvalue()
423.1371 -
423.1372 -def load(file):
423.1373 - return Unpickler(file).load()
423.1374 -
423.1375 -def loads(str):
423.1376 - file = StringIO(str)
423.1377 - return Unpickler(file).load()
423.1378 -
423.1379 -# Doctest
423.1380 -
423.1381 -def _test():
423.1382 - import doctest
423.1383 - return doctest.testmod()
423.1384 -
423.1385 -if __name__ == "__main__":
423.1386 - _test()
424.1 --- a/python.editor/test/unit/data/testfiles/pickle.py.testDoc3.html Sun Jan 04 13:11:53 2015 -0600
424.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
424.3 @@ -1,40 +0,0 @@
424.4 -<html><body>
424.5 -<pre>Code completion result for source line:
424.6 -import |re
424.7 -(QueryType=COMPLETION, NameKind=PREFIX)
424.8 -------------------------------------
424.9 -KEYWORD pickle null
424.10 -</pre><h2>Documentation:</h2><pre><b>pickle</b></pre>
424.11 -
424.12 -<hr>
424.13 -Create portable serialized representations of Python objects.
424.14 -
424.15 -<br><br>
424.16 -See module cPickle for a (much) faster implementation.
424.17 -See module copy_reg for a mechanism for registering custom picklers.
424.18 -See module pickletools source for extensive comments.
424.19 -
424.20 -<br><br>
424.21 -Classes:
424.22 -
424.23 -<br><br>
424.24 - Pickler
424.25 - Unpickler
424.26 -
424.27 -<br><br>
424.28 -Functions:
424.29 -
424.30 -<br><br>
424.31 - dump(object, file)
424.32 - dumps(object) -> string
424.33 - load(file) -> object
424.34 - loads(string) -> object
424.35 -
424.36 -<br><br>
424.37 -Misc variables:
424.38 -
424.39 -<br><br>
424.40 - __version__
424.41 - format_version
424.42 - compatible_formats
424.43 -</body></html>
425.1 --- a/python.editor/test/unit/data/testfiles/pickle.py.testDoc5.html Sun Jan 04 13:11:53 2015 -0600
425.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
425.3 @@ -1,14 +0,0 @@
425.4 -<html><body>
425.5 -<pre>Code completion result for source line:
425.6 -self.append(decode_lo|ng(bytes))
425.7 -(QueryType=COMPLETION, NameKind=PREFIX)
425.8 -METHOD decode_long(data) pickle
425.9 -</pre><h2>Documentation:</h2><pre><i>pickle</i><br><b>decode_long</b>(<font color="#808080">data</font>)</pre>
425.10 -
425.11 -<hr>
425.12 -Decode a long from a two's complement little-endian binary string.
425.13 -
425.14 -<br><br>
425.15 -<code>>>> <span style="">decode_long</span><span style="">(</span><span style="color:#ce7b00;">'</span><span style="color:#ce7b00;">'</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> 0L</code><br><code>>>> <span style="">decode_long</span><span style="">(</span><span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;font-weight:bold;">\x</span><span style="color:#ce7b00;">ff</span><span style="color:#ce7b00;font-weight:bold;">\x</span><span style="color:#ce7b00;">00</span></span><span style="color:#ce7b00;">"</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> 255L</code><br><code>>>> <span style="">decode_long</span><span style="">(</span><span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;font-weight:bold;">\x</span><span style="color:#ce7b00;">ff</span><span style="color:#ce7b00;font-weight:bold;">\x</span><span style="color:#ce7b00;">7f</span></span><span style="color:#ce7b00;">"</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> 32767L</code><br><code>>>> <span style="">decode_long</span><span style="">(</span><span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;font-weight:bold;">\x</span><span style="color:#ce7b00;">00</span><span style="color:#ce7b00;font-weight:bold;">\x</span><span style="color:#ce7b00;">ff</span></span><span style="color:#ce7b00;">"</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> -256L</code><br><code>>>> <span style="">decode_long</span><span style="">(</span><span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;font-weight:bold;">\x</span><span style="color:#ce7b00;">00</span><span style="color:#ce7b00;font-weight:bold;">\x</span><span style="color:#ce7b00;">80</span></span><span style="color:#ce7b00;">"</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> -32768L</code><br><code>>>> <span style="">decode_long</span><span style="">(</span><span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;font-weight:bold;">\x</span><span style="color:#ce7b00;">80</span></span><span style="color:#ce7b00;">"</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> -128L</code><br><code>>>> <span style="">decode_long</span><span style="">(</span><span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;font-weight:bold;">\x</span><span style="color:#ce7b00;">7f</span></span><span style="color:#ce7b00;">"</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> 127L</code><br>
425.16 -<br><br>
425.17 -</body></html>
426.1 --- a/python.editor/test/unit/data/testfiles/properties.py Sun Jan 04 13:11:53 2015 -0600
426.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
426.3 @@ -1,8 +0,0 @@
426.4 -class Foo(object):
426.5 - @property
426.6 - def bar(self):
426.7 - return "Foo:bar"
426.8 -
426.9 -x = Foo()
426.10 -x.bar
426.11 -
427.1 --- a/python.editor/test/unit/data/testfiles/properties.py.indexed Sun Jan 04 13:11:53 2015 -0600
427.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
427.3 @@ -1,20 +0,0 @@
427.4 -
427.5 -
427.6 -Document 0
427.7 -Searchable Keys:
427.8 - class : Foo
427.9 - class-ig : foo
427.10 - extends : object
427.11 - in : properties
427.12 - member : bar;A;;self;
427.13 -
427.14 -Not Searchable Keys:
427.15 -
427.16 -
427.17 -Document 1
427.18 -Searchable Keys:
427.19 - item : Foo;C;;
427.20 - item : x;D;;
427.21 - module : properties
427.22 -
427.23 -Not Searchable Keys:
428.1 --- a/python.editor/test/unit/data/testfiles/properties.py.testProperties.completion Sun Jan 04 13:11:53 2015 -0600
428.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
428.3 @@ -1,4 +0,0 @@
428.4 -Code completion result for source line:
428.5 -x.ba|r
428.6 -(QueryType=COMPLETION, NameKind=PREFIX)
428.7 -ATTRIBUTE bar
429.1 --- a/python.editor/test/unit/data/testfiles/rawstringdoc.py Sun Jan 04 13:11:53 2015 -0600
429.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
429.3 @@ -1,24 +0,0 @@
429.4 -r"""OS routines for Java, with some attempts to support NT, and Posix
429.5 -functionality.
429.6 -
429.7 -This exports:
429.8 - - all functions from posix, nt, dos, os2, mac, or ce, e.g. unlink, stat, etc.
429.9 - - os.path is one of the modules posixpath, ntpath, macpath, or dospath
429.10 - - os.name is 'posix', 'nt', 'dos', 'os2', 'mac', 'ce' or 'riscos'
429.11 - - os.curdir is a string representing the current directory ('.' or ':')
429.12 - - os.pardir is a string representing the parent directory ('..' or '::')
429.13 - - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
429.14 - - os.altsep is the alternate pathname separator (None or '/')
429.15 - - os.pathsep is the component separator used in $PATH etc
429.16 - - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
429.17 - - os.defpath is the default search path for executables
429.18 -
429.19 -Programs that import and use 'os' stand a better chance of being
429.20 -portable between different platforms. Of course, they must then
429.21 -only use functions that are defined by all platforms (e.g., unlink
429.22 -and opendir), and leave all pathname manipulation to os.path
429.23 -(e.g., split and join).
429.24 -"""
429.25 -
429.26 -import rawstringdoc
429.27 -
430.1 --- a/python.editor/test/unit/data/testfiles/rawstringdoc.py.html Sun Jan 04 13:11:53 2015 -0600
430.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
430.3 @@ -1,28 +0,0 @@
430.4 -<html><body>
430.5 -<h2 style="color: green">Next Comment</h2>
430.6 -<pre><b>rawstringdoc.py</b></pre>
430.7 -
430.8 -<hr>
430.9 -OS routines for Java, with some attempts to support NT, and Posix
430.10 -functionality.
430.11 -
430.12 -<br><br>
430.13 -This exports:
430.14 -<br> - all functions from posix, nt, dos, os2, mac, or ce, e.g. unlink, stat, etc.
430.15 -<br> - os.path is one of the modules posixpath, ntpath, macpath, or dospath
430.16 -<br> - os.name is 'posix', 'nt', 'dos', 'os2', 'mac', 'ce' or 'riscos'
430.17 -<br> - os.curdir is a string representing the current directory ('.' or ':')
430.18 -<br> - os.pardir is a string representing the parent directory ('..' or '::')
430.19 -<br> - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
430.20 -<br> - os.altsep is the alternate pathname separator (None or '/')
430.21 -<br> - os.pathsep is the component separator used in $PATH etc
430.22 -<br> - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
430.23 -<br> - os.defpath is the default search path for executables
430.24 -
430.25 -<br><br>
430.26 -Programs that import and use 'os' stand a better chance of being
430.27 -portable between different platforms. Of course, they must then
430.28 -only use functions that are defined by all platforms (e.g., unlink
430.29 -and opendir), and leave all pathname manipulation to os.path
430.30 -(e.g., split and join).
430.31 -</body></html>
431.1 --- a/python.editor/test/unit/data/testfiles/rst/bz2.rst Sun Jan 04 13:11:53 2015 -0600
431.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
431.3 @@ -1,197 +0,0 @@
431.4 -
431.5 -:mod:`bz2` --- Compression compatible with :program:`bzip2`
431.6 -===========================================================
431.7 -
431.8 -.. module:: bz2
431.9 - :synopsis: Interface to compression and decompression routines compatible with bzip2.
431.10 -.. moduleauthor:: Gustavo Niemeyer <niemeyer@conectiva.com>
431.11 -.. sectionauthor:: Gustavo Niemeyer <niemeyer@conectiva.com>
431.12 -
431.13 -
431.14 -.. versionadded:: 2.3
431.15 -
431.16 -This module provides a comprehensive interface for the bz2 compression library.
431.17 -It implements a complete file interface, one-shot (de)compression functions, and
431.18 -types for sequential (de)compression.
431.19 -
431.20 -For other archive formats, see the :mod:`gzip`, :mod:`zipfile`, and
431.21 -:mod:`tarfile` modules.
431.22 -
431.23 -Here is a summary of the features offered by the bz2 module:
431.24 -
431.25 -* :class:`BZ2File` class implements a complete file interface, including
431.26 - :meth:`readline`, :meth:`readlines`, :meth:`writelines`, :meth:`seek`, etc;
431.27 -
431.28 -* :class:`BZ2File` class implements emulated :meth:`seek` support;
431.29 -
431.30 -* :class:`BZ2File` class implements universal newline support;
431.31 -
431.32 -* :class:`BZ2File` class offers an optimized line iteration using the readahead
431.33 - algorithm borrowed from file objects;
431.34 -
431.35 -* Sequential (de)compression supported by :class:`BZ2Compressor` and
431.36 - :class:`BZ2Decompressor` classes;
431.37 -
431.38 -* One-shot (de)compression supported by :func:`compress` and :func:`decompress`
431.39 - functions;
431.40 -
431.41 -* Thread safety uses individual locking mechanism.
431.42 -
431.43 -
431.44 -(De)compression of files
431.45 -------------------------
431.46 -
431.47 -Handling of compressed files is offered by the :class:`BZ2File` class.
431.48 -
431.49 -
431.50 -.. class:: BZ2File(filename[, mode[, buffering[, compresslevel]]])
431.51 -
431.52 - Open a bz2 file. Mode can be either ``'r'`` or ``'w'``, for reading (default)
431.53 - or writing. When opened for writing, the file will be created if it doesn't
431.54 - exist, and truncated otherwise. If *buffering* is given, ``0`` means
431.55 - unbuffered, and larger numbers specify the buffer size; the default is
431.56 - ``0``. If *compresslevel* is given, it must be a number between ``1`` and
431.57 - ``9``; the default is ``9``. Add a ``'U'`` to mode to open the file for input
431.58 - with universal newline support. Any line ending in the input file will be
431.59 - seen as a ``'\n'`` in Python. Also, a file so opened gains the attribute
431.60 - :attr:`newlines`; the value for this attribute is one of ``None`` (no newline
431.61 - read yet), ``'\r'``, ``'\n'``, ``'\r\n'`` or a tuple containing all the
431.62 - newline types seen. Universal newlines are available only when
431.63 - reading. Instances support iteration in the same way as normal :class:`file`
431.64 - instances.
431.65 -
431.66 -
431.67 - .. method:: close()
431.68 -
431.69 - Close the file. Sets data attribute :attr:`closed` to true. A closed file
431.70 - cannot be used for further I/O operations. :meth:`close` may be called
431.71 - more than once without error.
431.72 -
431.73 -
431.74 - .. method:: read([size])
431.75 -
431.76 - Read at most *size* uncompressed bytes, returned as a string. If the
431.77 - *size* argument is negative or omitted, read until EOF is reached.
431.78 -
431.79 -
431.80 - .. method:: readline([size])
431.81 -
431.82 - Return the next line from the file, as a string, retaining newline. A
431.83 - non-negative *size* argument limits the maximum number of bytes to return
431.84 - (an incomplete line may be returned then). Return an empty string at EOF.
431.85 -
431.86 -
431.87 - .. method:: readlines([size])
431.88 -
431.89 - Return a list of lines read. The optional *size* argument, if given, is an
431.90 - approximate bound on the total number of bytes in the lines returned.
431.91 -
431.92 -
431.93 - .. method:: xreadlines()
431.94 -
431.95 - For backward compatibility. :class:`BZ2File` objects now include the
431.96 - performance optimizations previously implemented in the :mod:`xreadlines`
431.97 - module.
431.98 -
431.99 - .. deprecated:: 2.3
431.100 - This exists only for compatibility with the method by this name on
431.101 - :class:`file` objects, which is deprecated. Use ``for line in file``
431.102 - instead.
431.103 -
431.104 -
431.105 - .. method:: seek(offset[, whence])
431.106 -
431.107 - Move to new file position. Argument *offset* is a byte count. Optional
431.108 - argument *whence* defaults to ``os.SEEK_SET`` or ``0`` (offset from start
431.109 - of file; offset should be ``>= 0``); other values are ``os.SEEK_CUR`` or
431.110 - ``1`` (move relative to current position; offset can be positive or
431.111 - negative), and ``os.SEEK_END`` or ``2`` (move relative to end of file;
431.112 - offset is usually negative, although many platforms allow seeking beyond
431.113 - the end of a file).
431.114 -
431.115 - Note that seeking of bz2 files is emulated, and depending on the
431.116 - parameters the operation may be extremely slow.
431.117 -
431.118 -
431.119 - .. method:: tell()
431.120 -
431.121 - Return the current file position, an integer (may be a long integer).
431.122 -
431.123 -
431.124 - .. method:: write(data)
431.125 -
431.126 - Write string *data* to file. Note that due to buffering, :meth:`close` may
431.127 - be needed before the file on disk reflects the data written.
431.128 -
431.129 -
431.130 - .. method:: writelines(sequence_of_strings)
431.131 -
431.132 - Write the sequence of strings to the file. Note that newlines are not
431.133 - added. The sequence can be any iterable object producing strings. This is
431.134 - equivalent to calling write() for each string.
431.135 -
431.136 -
431.137 -Sequential (de)compression
431.138 ---------------------------
431.139 -
431.140 -Sequential compression and decompression is done using the classes
431.141 -:class:`BZ2Compressor` and :class:`BZ2Decompressor`.
431.142 -
431.143 -
431.144 -.. class:: BZ2Compressor([compresslevel])
431.145 -
431.146 - Create a new compressor object. This object may be used to compress data
431.147 - sequentially. If you want to compress data in one shot, use the
431.148 - :func:`compress` function instead. The *compresslevel* parameter, if given,
431.149 - must be a number between ``1`` and ``9``; the default is ``9``.
431.150 -
431.151 -
431.152 - .. method:: compress(data)
431.153 -
431.154 - Provide more data to the compressor object. It will return chunks of
431.155 - compressed data whenever possible. When you've finished providing data to
431.156 - compress, call the :meth:`flush` method to finish the compression process,
431.157 - and return what is left in internal buffers.
431.158 -
431.159 -
431.160 - .. method:: flush()
431.161 -
431.162 - Finish the compression process and return what is left in internal
431.163 - buffers. You must not use the compressor object after calling this method.
431.164 -
431.165 -
431.166 -.. class:: BZ2Decompressor()
431.167 -
431.168 - Create a new decompressor object. This object may be used to decompress data
431.169 - sequentially. If you want to decompress data in one shot, use the
431.170 - :func:`decompress` function instead.
431.171 -
431.172 -
431.173 - .. method:: decompress(data)
431.174 -
431.175 - Provide more data to the decompressor object. It will return chunks of
431.176 - decompressed data whenever possible. If you try to decompress data after
431.177 - the end of stream is found, :exc:`EOFError` will be raised. If any data
431.178 - was found after the end of stream, it'll be ignored and saved in
431.179 - :attr:`unused_data` attribute.
431.180 -
431.181 -
431.182 -One-shot (de)compression
431.183 -------------------------
431.184 -
431.185 -One-shot compression and decompression is provided through the :func:`compress`
431.186 -and :func:`decompress` functions.
431.187 -
431.188 -
431.189 -.. function:: compress(data[, compresslevel])
431.190 -
431.191 - Compress *data* in one shot. If you want to compress data sequentially, use
431.192 - an instance of :class:`BZ2Compressor` instead. The *compresslevel* parameter,
431.193 - if given, must be a number between ``1`` and ``9``; the default is ``9``.
431.194 -
431.195 -
431.196 -.. function:: decompress(data)
431.197 -
431.198 - Decompress *data* in one shot. If you want to decompress data sequentially,
431.199 - use an instance of :class:`BZ2Decompressor` instead.
431.200 -
432.1 --- a/python.editor/test/unit/data/testfiles/rst/bz2.rst.indexed Sun Jan 04 13:11:53 2015 -0600
432.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
432.3 @@ -1,58 +0,0 @@
432.4 -
432.5 -
432.6 -Document 0
432.7 -Searchable Keys:
432.8 - class : BZ2Compressor
432.9 - class-ig : bz2compressor
432.10 - in : bz2
432.11 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;compresslevel;
432.12 - member : compress;F;|DOCUMENTED|DOC_ONLY|;data;
432.13 - member : flush;F;|DOCUMENTED|DOC_ONLY|;;
432.14 -
432.15 -Not Searchable Keys:
432.16 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
432.17 -
432.18 -
432.19 -Document 1
432.20 -Searchable Keys:
432.21 - class : BZ2Decompressor
432.22 - class-ig : bz2decompressor
432.23 - in : bz2
432.24 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
432.25 - member : decompress;F;|DOCUMENTED|DOC_ONLY|;data;
432.26 -
432.27 -Not Searchable Keys:
432.28 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
432.29 -
432.30 -
432.31 -Document 2
432.32 -Searchable Keys:
432.33 - class : BZ2File
432.34 - class-ig : bz2file
432.35 - in : bz2
432.36 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;filename,mode,buffering,compresslevel;
432.37 - member : close;F;|DOCUMENTED|DOC_ONLY|;;
432.38 - member : read;F;|DOCUMENTED|DOC_ONLY|;size;
432.39 - member : readline;F;|DOCUMENTED|DOC_ONLY|;size;
432.40 - member : readlines;F;|DOCUMENTED|DOC_ONLY|;size;
432.41 - member : seek;F;|DOCUMENTED|DOC_ONLY|;offset,whence;
432.42 - member : tell;F;|DOCUMENTED|DOC_ONLY|;;
432.43 - member : write;F;|DOCUMENTED|DOC_ONLY|;data;
432.44 - member : writelines;F;|DOCUMENTED|DOC_ONLY|;sequence_of_strings;
432.45 - member : xreadlines;F;|DOCUMENTED|DEPRECATED|DOC_ONLY|;;
432.46 -
432.47 -Not Searchable Keys:
432.48 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
432.49 -
432.50 -
432.51 -Document 3
432.52 -Searchable Keys:
432.53 - item : BZ2Compressor;C;|DOCUMENTED|DOC_ONLY|;
432.54 - item : BZ2Decompressor;C;|DOCUMENTED|DOC_ONLY|;
432.55 - item : BZ2File;C;|DOCUMENTED|DOC_ONLY|;
432.56 - item : compress;F;|DOCUMENTED|DOC_ONLY|;data,compresslevel;
432.57 - item : decompress;F;|DOCUMENTED|DOC_ONLY|;data;
432.58 - module : bz2
432.59 -
432.60 -Not Searchable Keys:
432.61 - modattrs : S
433.1 --- a/python.editor/test/unit/data/testfiles/rst/collections.rst Sun Jan 04 13:11:53 2015 -0600
433.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
433.3 @@ -1,690 +0,0 @@
433.4 -
433.5 -:mod:`collections` --- High-performance container datatypes
433.6 -===========================================================
433.7 -
433.8 -.. module:: collections
433.9 - :synopsis: High-performance datatypes
433.10 -.. moduleauthor:: Raymond Hettinger <python@rcn.com>
433.11 -.. sectionauthor:: Raymond Hettinger <python@rcn.com>
433.12 -
433.13 -.. versionadded:: 2.4
433.14 -
433.15 -.. testsetup:: *
433.16 -
433.17 - from collections import *
433.18 - import itertools
433.19 - __name__ = '<doctest>'
433.20 -
433.21 -This module implements high-performance container datatypes. Currently,
433.22 -there are two datatypes, :class:`deque` and :class:`defaultdict`, and
433.23 -one datatype factory function, :func:`namedtuple`.
433.24 -
433.25 -.. versionchanged:: 2.5
433.26 - Added :class:`defaultdict`.
433.27 -
433.28 -.. versionchanged:: 2.6
433.29 - Added :func:`namedtuple`.
433.30 -
433.31 -The specialized containers provided in this module provide alternatives
433.32 -to Python's general purpose built-in containers, :class:`dict`,
433.33 -:class:`list`, :class:`set`, and :class:`tuple`.
433.34 -
433.35 -Besides the containers provided here, the optional :mod:`bsddb`
433.36 -module offers the ability to create in-memory or file based ordered
433.37 -dictionaries with string keys using the :meth:`bsddb.btopen` method.
433.38 -
433.39 -In addition to containers, the collections module provides some ABCs
433.40 -(abstract base classes) that can be used to test whether a class
433.41 -provides a particular interface, for example, is it hashable or
433.42 -a mapping.
433.43 -
433.44 -.. versionchanged:: 2.6
433.45 - Added abstract base classes.
433.46 -
433.47 -ABCs - abstract base classes
433.48 -----------------------------
433.49 -
433.50 -The collections module offers the following ABCs:
433.51 -
433.52 -========================= ===================== ====================== ====================================================
433.53 -ABC Inherits Abstract Methods Mixin Methods
433.54 -========================= ===================== ====================== ====================================================
433.55 -:class:`Container` ``__contains__``
433.56 -:class:`Hashable` ``__hash__``
433.57 -:class:`Iterable` ``__iter__``
433.58 -:class:`Iterator` :class:`Iterable` ``__next__`` ``__iter__``
433.59 -:class:`Sized` ``__len__``
433.60 -:class:`Callable` ``__call__``
433.61 -
433.62 -:class:`Sequence` :class:`Sized`, ``__getitem__`` ``__contains__``. ``__iter__``, ``__reversed__``.
433.63 - :class:`Iterable`, and ``__len__`` ``index``, and ``count``
433.64 - :class:`Container`
433.65 -
433.66 -:class:`MutableSequnce` :class:`Sequence` ``__getitem__`` Inherited Sequence methods and
433.67 - ``__delitem__``, ``append``, ``reverse``, ``extend``, ``pop``,
433.68 - ``insert``, ``remove``, and ``__iadd__``
433.69 - and ``__len__``
433.70 -
433.71 -:class:`Set` :class:`Sized`, ``__len__``, ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``,
433.72 - :class:`Iterable`, ``__iter__``, and ``__gt__``, ``__ge__``, ``__and__``, ``__or__``
433.73 - :class:`Container` ``__contains__`` ``__sub__``, ``__xor__``, and ``isdisjoint``
433.74 -
433.75 -:class:`MutableSet` :class:`Set` ``add`` and Inherited Set methods and
433.76 - ``discard`` ``clear``, ``pop``, ``remove``, ``__ior__``,
433.77 - ``__iand__``, ``__ixor__``, and ``__isub__``
433.78 -
433.79 -:class:`Mapping` :class:`Sized`, ``__getitem__``, ``__contains__``, ``keys``, ``items``, ``values``,
433.80 - :class:`Iterable`, ``__len__``. and ``get``, ``__eq__``, and ``__ne__``
433.81 - :class:`Container` ``__iter__``
433.82 -
433.83 -:class:`MutableMapping` :class:`Mapping` ``__getitem__`` Inherited Mapping methods and
433.84 - ``__setitem__``, ``pop``, ``popitem``, ``clear``, ``update``,
433.85 - ``__delitem__``, and ``setdefault``
433.86 - ``__iter__``, and
433.87 - ``__len__``
433.88 -
433.89 -:class:`MappingView` :class:`Sized` ``__len__``
433.90 -:class:`KeysView` :class:`MappingView`, ``__contains__``,
433.91 - :class:`Set` ``__iter__``
433.92 -:class:`ItemsView` :class:`MappingView`, ``__contains__``,
433.93 - :class:`Set` ``__iter__``
433.94 -:class:`ValuesView` :class:`MappingView` ``__contains__``, ``__iter__``
433.95 -========================= ===================== ====================== ====================================================
433.96 -
433.97 -These ABCs allow us to ask classes or instances if they provide
433.98 -particular functionality, for example::
433.99 -
433.100 - size = None
433.101 - if isinstance(myvar, collections.Sized):
433.102 - size = len(myvar)
433.103 -
433.104 -Several of the ABCs are also useful as mixins that make it easier to develop
433.105 -classes supporting container APIs. For example, to write a class supporting
433.106 -the full :class:`Set` API, it only necessary to supply the three underlying
433.107 -abstract methods: :meth:`__contains__`, :meth:`__iter__`, and :meth:`__len__`.
433.108 -The ABC supplies the remaining methods such as :meth:`__and__` and
433.109 -:meth:`isdisjoint` ::
433.110 -
433.111 - class ListBasedSet(collections.Set):
433.112 - ''' Alternate set implementation favoring space over speed
433.113 - and not requiring the set elements to be hashable. '''
433.114 - def __init__(self, iterable):
433.115 - self.elements = lst = []
433.116 - for value in iterable:
433.117 - if value not in lst:
433.118 - lst.append(value)
433.119 - def __iter__(self):
433.120 - return iter(self.elements)
433.121 - def __contains__(self, value):
433.122 - return value in self.elements
433.123 - def __len__(self):
433.124 - return len(self.elements)
433.125 -
433.126 - s1 = ListBasedSet('abcdef')
433.127 - s2 = ListBasedSet('defghi')
433.128 - overlap = s1 & s2 # The __and__() method is supported automatically
433.129 -
433.130 -Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
433.131 -
433.132 -(1)
433.133 - Since some set operations create new sets, the default mixin methods need
433.134 - a way to create new instances from an iterable. The class constructor is
433.135 - assumed to have a signature in the form ``ClassName(iterable)``.
433.136 - That assumption is factored-out to an internal classmethod called
433.137 - :meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set.
433.138 - If the :class:`Set` mixin is being used in a class with a different
433.139 - constructor signature, you will need to override :meth:`from_iterable`
433.140 - with a classmethod that can construct new instances from
433.141 - an iterable argument.
433.142 -
433.143 -(2)
433.144 - To override the comparisons (presumably for speed, as the
433.145 - semantics are fixed), redefine :meth:`__le__` and
433.146 - then the other operations will automatically follow suit.
433.147 -
433.148 -(3)
433.149 - The :class:`Set` mixin provides a :meth:`_hash` method to compute a hash value
433.150 - for the set; however, :meth:`__hash__` is not defined because not all sets
433.151 - are hashable or immutable. To add set hashabilty using mixins,
433.152 - inherit from both :meth:`Set` and :meth:`Hashable`, then define
433.153 - ``__hash__ = Set._hash``.
433.154 -
433.155 -(For more about ABCs, see the :mod:`abc` module and :pep:`3119`.)
433.156 -
433.157 -
433.158 -
433.159 -.. _deque-objects:
433.160 -
433.161 -:class:`deque` objects
433.162 -----------------------
433.163 -
433.164 -
433.165 -.. class:: deque([iterable[, maxlen]])
433.166 -
433.167 - Returns a new deque object initialized left-to-right (using :meth:`append`) with
433.168 - data from *iterable*. If *iterable* is not specified, the new deque is empty.
433.169 -
433.170 - Deques are a generalization of stacks and queues (the name is pronounced "deck"
433.171 - and is short for "double-ended queue"). Deques support thread-safe, memory
433.172 - efficient appends and pops from either side of the deque with approximately the
433.173 - same O(1) performance in either direction.
433.174 -
433.175 - Though :class:`list` objects support similar operations, they are optimized for
433.176 - fast fixed-length operations and incur O(n) memory movement costs for
433.177 - ``pop(0)`` and ``insert(0, v)`` operations which change both the size and
433.178 - position of the underlying data representation.
433.179 -
433.180 - .. versionadded:: 2.4
433.181 -
433.182 - If *maxlen* is not specified or is *None*, deques may grow to an
433.183 - arbitrary length. Otherwise, the deque is bounded to the specified maximum
433.184 - length. Once a bounded length deque is full, when new items are added, a
433.185 - corresponding number of items are discarded from the opposite end. Bounded
433.186 - length deques provide functionality similar to the ``tail`` filter in
433.187 - Unix. They are also useful for tracking transactions and other pools of data
433.188 - where only the most recent activity is of interest.
433.189 -
433.190 - .. versionchanged:: 2.6
433.191 - Added *maxlen* parameter.
433.192 -
433.193 - Deque objects support the following methods:
433.194 -
433.195 -
433.196 - .. method:: append(x)
433.197 -
433.198 - Add *x* to the right side of the deque.
433.199 -
433.200 -
433.201 - .. method:: appendleft(x)
433.202 -
433.203 - Add *x* to the left side of the deque.
433.204 -
433.205 -
433.206 - .. method:: clear()
433.207 -
433.208 - Remove all elements from the deque leaving it with length 0.
433.209 -
433.210 -
433.211 - .. method:: extend(iterable)
433.212 -
433.213 - Extend the right side of the deque by appending elements from the iterable
433.214 - argument.
433.215 -
433.216 -
433.217 - .. method:: extendleft(iterable)
433.218 -
433.219 - Extend the left side of the deque by appending elements from *iterable*.
433.220 - Note, the series of left appends results in reversing the order of
433.221 - elements in the iterable argument.
433.222 -
433.223 -
433.224 - .. method:: pop()
433.225 -
433.226 - Remove and return an element from the right side of the deque. If no
433.227 - elements are present, raises an :exc:`IndexError`.
433.228 -
433.229 -
433.230 - .. method:: popleft()
433.231 -
433.232 - Remove and return an element from the left side of the deque. If no
433.233 - elements are present, raises an :exc:`IndexError`.
433.234 -
433.235 -
433.236 - .. method:: remove(value)
433.237 -
433.238 - Removed the first occurrence of *value*. If not found, raises a
433.239 - :exc:`ValueError`.
433.240 -
433.241 - .. versionadded:: 2.5
433.242 -
433.243 -
433.244 - .. method:: rotate(n)
433.245 -
433.246 - Rotate the deque *n* steps to the right. If *n* is negative, rotate to
433.247 - the left. Rotating one step to the right is equivalent to:
433.248 - ``d.appendleft(d.pop())``.
433.249 -
433.250 -
433.251 -In addition to the above, deques support iteration, pickling, ``len(d)``,
433.252 -``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with
433.253 -the :keyword:`in` operator, and subscript references such as ``d[-1]``.
433.254 -
433.255 -Example:
433.256 -
433.257 -.. doctest::
433.258 -
433.259 - >>> from collections import deque
433.260 - >>> d = deque('ghi') # make a new deque with three items
433.261 - >>> for elem in d: # iterate over the deque's elements
433.262 - ... print elem.upper()
433.263 - G
433.264 - H
433.265 - I
433.266 -
433.267 - >>> d.append('j') # add a new entry to the right side
433.268 - >>> d.appendleft('f') # add a new entry to the left side
433.269 - >>> d # show the representation of the deque
433.270 - deque(['f', 'g', 'h', 'i', 'j'])
433.271 -
433.272 - >>> d.pop() # return and remove the rightmost item
433.273 - 'j'
433.274 - >>> d.popleft() # return and remove the leftmost item
433.275 - 'f'
433.276 - >>> list(d) # list the contents of the deque
433.277 - ['g', 'h', 'i']
433.278 - >>> d[0] # peek at leftmost item
433.279 - 'g'
433.280 - >>> d[-1] # peek at rightmost item
433.281 - 'i'
433.282 -
433.283 - >>> list(reversed(d)) # list the contents of a deque in reverse
433.284 - ['i', 'h', 'g']
433.285 - >>> 'h' in d # search the deque
433.286 - True
433.287 - >>> d.extend('jkl') # add multiple elements at once
433.288 - >>> d
433.289 - deque(['g', 'h', 'i', 'j', 'k', 'l'])
433.290 - >>> d.rotate(1) # right rotation
433.291 - >>> d
433.292 - deque(['l', 'g', 'h', 'i', 'j', 'k'])
433.293 - >>> d.rotate(-1) # left rotation
433.294 - >>> d
433.295 - deque(['g', 'h', 'i', 'j', 'k', 'l'])
433.296 -
433.297 - >>> deque(reversed(d)) # make a new deque in reverse order
433.298 - deque(['l', 'k', 'j', 'i', 'h', 'g'])
433.299 - >>> d.clear() # empty the deque
433.300 - >>> d.pop() # cannot pop from an empty deque
433.301 - Traceback (most recent call last):
433.302 - File "<pyshell#6>", line 1, in -toplevel-
433.303 - d.pop()
433.304 - IndexError: pop from an empty deque
433.305 -
433.306 - >>> d.extendleft('abc') # extendleft() reverses the input order
433.307 - >>> d
433.308 - deque(['c', 'b', 'a'])
433.309 -
433.310 -
433.311 -.. _deque-recipes:
433.312 -
433.313 -:class:`deque` Recipes
433.314 -^^^^^^^^^^^^^^^^^^^^^^
433.315 -
433.316 -This section shows various approaches to working with deques.
433.317 -
433.318 -The :meth:`rotate` method provides a way to implement :class:`deque` slicing and
433.319 -deletion. For example, a pure python implementation of ``del d[n]`` relies on
433.320 -the :meth:`rotate` method to position elements to be popped::
433.321 -
433.322 - def delete_nth(d, n):
433.323 - d.rotate(-n)
433.324 - d.popleft()
433.325 - d.rotate(n)
433.326 -
433.327 -To implement :class:`deque` slicing, use a similar approach applying
433.328 -:meth:`rotate` to bring a target element to the left side of the deque. Remove
433.329 -old entries with :meth:`popleft`, add new entries with :meth:`extend`, and then
433.330 -reverse the rotation.
433.331 -With minor variations on that approach, it is easy to implement Forth style
433.332 -stack manipulations such as ``dup``, ``drop``, ``swap``, ``over``, ``pick``,
433.333 -``rot``, and ``roll``.
433.334 -
433.335 -Multi-pass data reduction algorithms can be succinctly expressed and efficiently
433.336 -coded by extracting elements with multiple calls to :meth:`popleft`, applying
433.337 -a reduction function, and calling :meth:`append` to add the result back to the
433.338 -deque.
433.339 -
433.340 -For example, building a balanced binary tree of nested lists entails reducing
433.341 -two adjacent nodes into one by grouping them in a list:
433.342 -
433.343 - >>> def maketree(iterable):
433.344 - ... d = deque(iterable)
433.345 - ... while len(d) > 1:
433.346 - ... pair = [d.popleft(), d.popleft()]
433.347 - ... d.append(pair)
433.348 - ... return list(d)
433.349 - ...
433.350 - >>> print maketree('abcdefgh')
433.351 - [[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]]
433.352 -
433.353 -Bounded length deques provide functionality similar to the ``tail`` filter
433.354 -in Unix::
433.355 -
433.356 - def tail(filename, n=10):
433.357 - 'Return the last n lines of a file'
433.358 - return deque(open(filename), n)
433.359 -
433.360 -.. _defaultdict-objects:
433.361 -
433.362 -:class:`defaultdict` objects
433.363 -----------------------------
433.364 -
433.365 -
433.366 -.. class:: defaultdict([default_factory[, ...]])
433.367 -
433.368 - Returns a new dictionary-like object. :class:`defaultdict` is a subclass of the
433.369 - builtin :class:`dict` class. It overrides one method and adds one writable
433.370 - instance variable. The remaining functionality is the same as for the
433.371 - :class:`dict` class and is not documented here.
433.372 -
433.373 - The first argument provides the initial value for the :attr:`default_factory`
433.374 - attribute; it defaults to ``None``. All remaining arguments are treated the same
433.375 - as if they were passed to the :class:`dict` constructor, including keyword
433.376 - arguments.
433.377 -
433.378 - .. versionadded:: 2.5
433.379 -
433.380 - :class:`defaultdict` objects support the following method in addition to the
433.381 - standard :class:`dict` operations:
433.382 -
433.383 -
433.384 - .. method:: defaultdict.__missing__(key)
433.385 -
433.386 - If the :attr:`default_factory` attribute is ``None``, this raises a
433.387 - :exc:`KeyError` exception with the *key* as argument.
433.388 -
433.389 - If :attr:`default_factory` is not ``None``, it is called without arguments
433.390 - to provide a default value for the given *key*, this value is inserted in
433.391 - the dictionary for the *key*, and returned.
433.392 -
433.393 - If calling :attr:`default_factory` raises an exception this exception is
433.394 - propagated unchanged.
433.395 -
433.396 - This method is called by the :meth:`__getitem__` method of the
433.397 - :class:`dict` class when the requested key is not found; whatever it
433.398 - returns or raises is then returned or raised by :meth:`__getitem__`.
433.399 -
433.400 -
433.401 - :class:`defaultdict` objects support the following instance variable:
433.402 -
433.403 -
433.404 - .. attribute:: defaultdict.default_factory
433.405 -
433.406 - This attribute is used by the :meth:`__missing__` method; it is
433.407 - initialized from the first argument to the constructor, if present, or to
433.408 - ``None``, if absent.
433.409 -
433.410 -
433.411 -.. _defaultdict-examples:
433.412 -
433.413 -:class:`defaultdict` Examples
433.414 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
433.415 -
433.416 -Using :class:`list` as the :attr:`default_factory`, it is easy to group a
433.417 -sequence of key-value pairs into a dictionary of lists:
433.418 -
433.419 - >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
433.420 - >>> d = defaultdict(list)
433.421 - >>> for k, v in s:
433.422 - ... d[k].append(v)
433.423 - ...
433.424 - >>> d.items()
433.425 - [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
433.426 -
433.427 -When each key is encountered for the first time, it is not already in the
433.428 -mapping; so an entry is automatically created using the :attr:`default_factory`
433.429 -function which returns an empty :class:`list`. The :meth:`list.append`
433.430 -operation then attaches the value to the new list. When keys are encountered
433.431 -again, the look-up proceeds normally (returning the list for that key) and the
433.432 -:meth:`list.append` operation adds another value to the list. This technique is
433.433 -simpler and faster than an equivalent technique using :meth:`dict.setdefault`:
433.434 -
433.435 - >>> d = {}
433.436 - >>> for k, v in s:
433.437 - ... d.setdefault(k, []).append(v)
433.438 - ...
433.439 - >>> d.items()
433.440 - [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
433.441 -
433.442 -Setting the :attr:`default_factory` to :class:`int` makes the
433.443 -:class:`defaultdict` useful for counting (like a bag or multiset in other
433.444 -languages):
433.445 -
433.446 - >>> s = 'mississippi'
433.447 - >>> d = defaultdict(int)
433.448 - >>> for k in s:
433.449 - ... d[k] += 1
433.450 - ...
433.451 - >>> d.items()
433.452 - [('i', 4), ('p', 2), ('s', 4), ('m', 1)]
433.453 -
433.454 -When a letter is first encountered, it is missing from the mapping, so the
433.455 -:attr:`default_factory` function calls :func:`int` to supply a default count of
433.456 -zero. The increment operation then builds up the count for each letter.
433.457 -
433.458 -The function :func:`int` which always returns zero is just a special case of
433.459 -constant functions. A faster and more flexible way to create constant functions
433.460 -is to use :func:`itertools.repeat` which can supply any constant value (not just
433.461 -zero):
433.462 -
433.463 - >>> def constant_factory(value):
433.464 - ... return itertools.repeat(value).next
433.465 - >>> d = defaultdict(constant_factory('<missing>'))
433.466 - >>> d.update(name='John', action='ran')
433.467 - >>> '%(name)s %(action)s to %(object)s' % d
433.468 - 'John ran to <missing>'
433.469 -
433.470 -Setting the :attr:`default_factory` to :class:`set` makes the
433.471 -:class:`defaultdict` useful for building a dictionary of sets:
433.472 -
433.473 - >>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
433.474 - >>> d = defaultdict(set)
433.475 - >>> for k, v in s:
433.476 - ... d[k].add(v)
433.477 - ...
433.478 - >>> d.items()
433.479 - [('blue', set([2, 4])), ('red', set([1, 3]))]
433.480 -
433.481 -
433.482 -.. _named-tuple-factory:
433.483 -
433.484 -:func:`namedtuple` Factory Function for Tuples with Named Fields
433.485 -----------------------------------------------------------------
433.486 -
433.487 -Named tuples assign meaning to each position in a tuple and allow for more readable,
433.488 -self-documenting code. They can be used wherever regular tuples are used, and
433.489 -they add the ability to access fields by name instead of position index.
433.490 -
433.491 -.. function:: namedtuple(typename, fieldnames, [verbose])
433.492 -
433.493 - Returns a new tuple subclass named *typename*. The new subclass is used to
433.494 - create tuple-like objects that have fields accessible by attribute lookup as
433.495 - well as being indexable and iterable. Instances of the subclass also have a
433.496 - helpful docstring (with typename and fieldnames) and a helpful :meth:`__repr__`
433.497 - method which lists the tuple contents in a ``name=value`` format.
433.498 -
433.499 - The *fieldnames* are a single string with each fieldname separated by whitespace
433.500 - and/or commas, for example ``'x y'`` or ``'x, y'``. Alternatively, *fieldnames*
433.501 - can be a sequence of strings such as ``['x', 'y']``.
433.502 -
433.503 - Any valid Python identifier may be used for a fieldname except for names
433.504 - starting with an underscore. Valid identifiers consist of letters, digits,
433.505 - and underscores but do not start with a digit or underscore and cannot be
433.506 - a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*, *print*,
433.507 - or *raise*.
433.508 -
433.509 - If *verbose* is true, the class definition is printed just before being built.
433.510 -
433.511 - Named tuple instances do not have per-instance dictionaries, so they are
433.512 - lightweight and require no more memory than regular tuples.
433.513 -
433.514 - .. versionadded:: 2.6
433.515 -
433.516 -Example:
433.517 -
433.518 -.. doctest::
433.519 - :options: +NORMALIZE_WHITESPACE
433.520 -
433.521 - >>> Point = namedtuple('Point', 'x y', verbose=True)
433.522 - class Point(tuple):
433.523 - 'Point(x, y)'
433.524 - <BLANKLINE>
433.525 - __slots__ = ()
433.526 - <BLANKLINE>
433.527 - _fields = ('x', 'y')
433.528 - <BLANKLINE>
433.529 - def __new__(cls, x, y):
433.530 - return tuple.__new__(cls, (x, y))
433.531 - <BLANKLINE>
433.532 - @classmethod
433.533 - def _make(cls, iterable, new=tuple.__new__, len=len):
433.534 - 'Make a new Point object from a sequence or iterable'
433.535 - result = new(cls, iterable)
433.536 - if len(result) != 2:
433.537 - raise TypeError('Expected 2 arguments, got %d' % len(result))
433.538 - return result
433.539 - <BLANKLINE>
433.540 - def __repr__(self):
433.541 - return 'Point(x=%r, y=%r)' % self
433.542 - <BLANKLINE>
433.543 - def _asdict(t):
433.544 - 'Return a new dict which maps field names to their values'
433.545 - return {'x': t[0], 'y': t[1]}
433.546 - <BLANKLINE>
433.547 - def _replace(self, **kwds):
433.548 - 'Return a new Point object replacing specified fields with new values'
433.549 - result = self._make(map(kwds.pop, ('x', 'y'), self))
433.550 - if kwds:
433.551 - raise ValueError('Got unexpected field names: %r' % kwds.keys())
433.552 - return result
433.553 - <BLANKLINE>
433.554 - def __getnewargs__(self):
433.555 - return tuple(self)
433.556 - <BLANKLINE>
433.557 - x = property(itemgetter(0))
433.558 - y = property(itemgetter(1))
433.559 -
433.560 - >>> p = Point(11, y=22) # instantiate with positional or keyword arguments
433.561 - >>> p[0] + p[1] # indexable like the plain tuple (11, 22)
433.562 - 33
433.563 - >>> x, y = p # unpack like a regular tuple
433.564 - >>> x, y
433.565 - (11, 22)
433.566 - >>> p.x + p.y # fields also accessible by name
433.567 - 33
433.568 - >>> p # readable __repr__ with a name=value style
433.569 - Point(x=11, y=22)
433.570 -
433.571 -Named tuples are especially useful for assigning field names to result tuples returned
433.572 -by the :mod:`csv` or :mod:`sqlite3` modules::
433.573 -
433.574 - EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
433.575 -
433.576 - import csv
433.577 - for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
433.578 - print emp.name, emp.title
433.579 -
433.580 - import sqlite3
433.581 - conn = sqlite3.connect('/companydata')
433.582 - cursor = conn.cursor()
433.583 - cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
433.584 - for emp in map(EmployeeRecord._make, cursor.fetchall()):
433.585 - print emp.name, emp.title
433.586 -
433.587 -In addition to the methods inherited from tuples, named tuples support
433.588 -three additional methods and one attribute. To prevent conflicts with
433.589 -field names, the method and attribute names start with an underscore.
433.590 -
433.591 -.. method:: somenamedtuple._make(iterable)
433.592 -
433.593 - Class method that makes a new instance from an existing sequence or iterable.
433.594 -
433.595 -.. doctest::
433.596 -
433.597 - >>> t = [11, 22]
433.598 - >>> Point._make(t)
433.599 - Point(x=11, y=22)
433.600 -
433.601 -.. method:: somenamedtuple._asdict()
433.602 -
433.603 - Return a new dict which maps field names to their corresponding values::
433.604 -
433.605 - >>> p._asdict()
433.606 - {'x': 11, 'y': 22}
433.607 -
433.608 -.. method:: somenamedtuple._replace(kwargs)
433.609 -
433.610 - Return a new instance of the named tuple replacing specified fields with new
433.611 - values:
433.612 -
433.613 -::
433.614 -
433.615 - >>> p = Point(x=11, y=22)
433.616 - >>> p._replace(x=33)
433.617 - Point(x=33, y=22)
433.618 -
433.619 - >>> for partnum, record in inventory.items():
433.620 - ... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())
433.621 -
433.622 -.. attribute:: somenamedtuple._fields
433.623 -
433.624 - Tuple of strings listing the field names. Useful for introspection
433.625 - and for creating new named tuple types from existing named tuples.
433.626 -
433.627 -.. doctest::
433.628 -
433.629 - >>> p._fields # view the field names
433.630 - ('x', 'y')
433.631 -
433.632 - >>> Color = namedtuple('Color', 'red green blue')
433.633 - >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
433.634 - >>> Pixel(11, 22, 128, 255, 0)
433.635 - Pixel(x=11, y=22, red=128, green=255, blue=0)
433.636 -
433.637 -To retrieve a field whose name is stored in a string, use the :func:`getattr`
433.638 -function:
433.639 -
433.640 - >>> getattr(p, 'x')
433.641 - 11
433.642 -
433.643 -To convert a dictionary to a named tuple, use the double-star-operator [#]_:
433.644 -
433.645 - >>> d = {'x': 11, 'y': 22}
433.646 - >>> Point(**d)
433.647 - Point(x=11, y=22)
433.648 -
433.649 -Since a named tuple is a regular Python class, it is easy to add or change
433.650 -functionality with a subclass. Here is how to add a calculated field and
433.651 -a fixed-width print format:
433.652 -
433.653 - >>> class Point(namedtuple('Point', 'x y')):
433.654 - ... __slots__ = ()
433.655 - ... @property
433.656 - ... def hypot(self):
433.657 - ... return (self.x ** 2 + self.y ** 2) ** 0.5
433.658 - ... def __str__(self):
433.659 - ... return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
433.660 -
433.661 - >>> for p in Point(3, 4), Point(14, 5/7.):
433.662 - ... print p
433.663 - Point: x= 3.000 y= 4.000 hypot= 5.000
433.664 - Point: x=14.000 y= 0.714 hypot=14.018
433.665 -
433.666 -The subclass shown above sets ``__slots__`` to an empty tuple. This keeps
433.667 -keep memory requirements low by preventing the creation of instance dictionaries.
433.668 -
433.669 -Subclassing is not useful for adding new, stored fields. Instead, simply
433.670 -create a new named tuple type from the :attr:`_fields` attribute:
433.671 -
433.672 - >>> Point3D = namedtuple('Point3D', Point._fields + ('z',))
433.673 -
433.674 -Default values can be implemented by using :meth:`_replace` to
433.675 -customize a prototype instance:
433.676 -
433.677 - >>> Account = namedtuple('Account', 'owner balance transaction_count')
433.678 - >>> default_account = Account('<owner name>', 0.0, 0)
433.679 - >>> johns_account = default_account._replace(owner='John')
433.680 -
433.681 -Enumerated constants can be implemented with named tuples, but it is simpler
433.682 -and more efficient to use a simple class declaration:
433.683 -
433.684 - >>> Status = namedtuple('Status', 'open pending closed')._make(range(3))
433.685 - >>> Status.open, Status.pending, Status.closed
433.686 - (0, 1, 2)
433.687 - >>> class Status:
433.688 - ... open, pending, closed = range(3)
433.689 -
433.690 -.. rubric:: Footnotes
433.691 -
433.692 -.. [#] For information on the double-star-operator see
433.693 - :ref:`tut-unpacking-arguments` and :ref:`calls`.
434.1 --- a/python.editor/test/unit/data/testfiles/rst/collections.rst.indexed Sun Jan 04 13:11:53 2015 -0600
434.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
434.3 @@ -1,44 +0,0 @@
434.4 -
434.5 -
434.6 -Document 0
434.7 -Searchable Keys:
434.8 - class : defaultdict
434.9 - class-ig : defaultdict
434.10 - in : collections
434.11 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;default_factory;
434.12 - member : __missing__;F;|DOCUMENTED|DOC_ONLY|;key;
434.13 - member : default_factory;A;|DOCUMENTED|DOC_ONLY|;
434.14 -
434.15 -Not Searchable Keys:
434.16 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
434.17 -
434.18 -
434.19 -Document 1
434.20 -Searchable Keys:
434.21 - class : deque
434.22 - class-ig : deque
434.23 - in : collections
434.24 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;iterable,maxlen;
434.25 - member : append;F;|DOCUMENTED|DOC_ONLY|;x;
434.26 - member : appendleft;F;|DOCUMENTED|DOC_ONLY|;x;
434.27 - member : clear;F;|DOCUMENTED|DOC_ONLY|;;
434.28 - member : extend;F;|DOCUMENTED|DOC_ONLY|;iterable;
434.29 - member : extendleft;F;|DOCUMENTED|DOC_ONLY|;iterable;
434.30 - member : pop;F;|DOCUMENTED|DOC_ONLY|;;
434.31 - member : popleft;F;|DOCUMENTED|DOC_ONLY|;;
434.32 - member : remove;F;|DOCUMENTED|DOC_ONLY|;value;
434.33 - member : rotate;F;|DOCUMENTED|DOC_ONLY|;n;
434.34 -
434.35 -Not Searchable Keys:
434.36 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
434.37 -
434.38 -
434.39 -Document 2
434.40 -Searchable Keys:
434.41 - item : defaultdict;C;|DOCUMENTED|DOC_ONLY|;
434.42 - item : deque;C;|DOCUMENTED|DOC_ONLY|;
434.43 - item : namedtuple;F;|DOCUMENTED|DOC_ONLY|;typename,fieldnames,verbose;
434.44 - module : collections
434.45 -
434.46 -Not Searchable Keys:
434.47 - modattrs : S
435.1 --- a/python.editor/test/unit/data/testfiles/rst/constants.rst Sun Jan 04 13:11:53 2015 -0600
435.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
435.3 @@ -1,73 +0,0 @@
435.4 -Built-in Constants
435.5 -==================
435.6 -
435.7 -A small number of constants live in the built-in namespace. They are:
435.8 -
435.9 -
435.10 -.. data:: False
435.11 -
435.12 - The false value of the :class:`bool` type.
435.13 -
435.14 - .. versionadded:: 2.3
435.15 -
435.16 -
435.17 -.. data:: True
435.18 -
435.19 - The true value of the :class:`bool` type.
435.20 -
435.21 - .. versionadded:: 2.3
435.22 -
435.23 -
435.24 -.. data:: None
435.25 -
435.26 - The sole value of :attr:`types.NoneType`. ``None`` is frequently used to
435.27 - represent the absence of a value, as when default arguments are not passed to a
435.28 - function.
435.29 -
435.30 - .. versionchanged:: 2.4
435.31 - Assignments to ``None`` are illegal and raise a :exc:`SyntaxError`.
435.32 -
435.33 -
435.34 -.. data:: NotImplemented
435.35 -
435.36 - Special value which can be returned by the "rich comparison" special methods
435.37 - (:meth:`__eq__`, :meth:`__lt__`, and friends), to indicate that the comparison
435.38 - is not implemented with respect to the other type.
435.39 -
435.40 -
435.41 -.. data:: Ellipsis
435.42 -
435.43 - Special value used in conjunction with extended slicing syntax.
435.44 -
435.45 - .. XXX Someone who understands extended slicing should fill in here.
435.46 -
435.47 -
435.48 -.. data:: __debug__
435.49 -
435.50 - This constant is true if Python was not started with an :option:`-O` option.
435.51 - Assignments to :const:`__debug__` are illegal and raise a :exc:`SyntaxError`.
435.52 - See also the :keyword:`assert` statement.
435.53 -
435.54 -
435.55 -Constants added by the :mod:`site` module
435.56 ------------------------------------------
435.57 -
435.58 -The :mod:`site` module (which is imported automatically during startup, except
435.59 -if the :option:`-S` command-line option is given) adds several constants to the
435.60 -built-in namespace. They are useful for the interactive interpreter shell and
435.61 -should not be used in programs.
435.62 -
435.63 -.. data:: quit([code=None])
435.64 - exit([code=None])
435.65 -
435.66 - Objects that when printed, print a message like "Use quit() or Ctrl-D
435.67 - (i.e. EOF) to exit", and when called, raise :exc:`SystemExit` with the
435.68 - specified exit code, and when .
435.69 -
435.70 -.. data:: copyright
435.71 - license
435.72 - credits
435.73 -
435.74 - Objects that when printed, print a message like "Type license() to see the
435.75 - full license text", and when called, display the corresponding text in a
435.76 - pager-like fashion (one screen at a time).
436.1 --- a/python.editor/test/unit/data/testfiles/rst/constants.rst.indexed Sun Jan 04 13:11:53 2015 -0600
436.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
436.3 @@ -1,17 +0,0 @@
436.4 -
436.5 -
436.6 -Document 0
436.7 -Searchable Keys:
436.8 - item : Ellipsis;D;|DOCUMENTED|DOC_ONLY|;
436.9 - item : False;D;|DOCUMENTED|DOC_ONLY|;
436.10 - item : None;D;|DOCUMENTED|DOC_ONLY|;
436.11 - item : NotImplemented;D;|DOCUMENTED|DOC_ONLY|;
436.12 - item : True;D;|DOCUMENTED|DOC_ONLY|;
436.13 - item : __debug__;D;|DOCUMENTED|DOC_ONLY|;
436.14 - item : copyright;D;|DOCUMENTED|DOC_ONLY|;
436.15 - item : exit;F;|DOCUMENTED|DOC_ONLY|;code;
436.16 - item : quit;F;|DOCUMENTED|DOC_ONLY|;code;
436.17 - module : constants
436.18 -
436.19 -Not Searchable Keys:
436.20 - modattrs : S
437.1 --- a/python.editor/test/unit/data/testfiles/rst/ctypes.rst Sun Jan 04 13:11:53 2015 -0600
437.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
437.3 @@ -1,2483 +0,0 @@
437.4 -
437.5 -:mod:`ctypes` --- A foreign function library for Python.
437.6 -========================================================
437.7 -
437.8 -.. module:: ctypes
437.9 - :synopsis: A foreign function library for Python.
437.10 -.. moduleauthor:: Thomas Heller <theller@python.net>
437.11 -
437.12 -
437.13 -.. versionadded:: 2.5
437.14 -
437.15 -``ctypes`` is a foreign function library for Python. It provides C compatible
437.16 -data types, and allows calling functions in DLLs or shared libraries. It can be
437.17 -used to wrap these libraries in pure Python.
437.18 -
437.19 -
437.20 -.. _ctypes-ctypes-tutorial:
437.21 -
437.22 -ctypes tutorial
437.23 ----------------
437.24 -
437.25 -Note: The code samples in this tutorial use ``doctest`` to make sure that they
437.26 -actually work. Since some code samples behave differently under Linux, Windows,
437.27 -or Mac OS X, they contain doctest directives in comments.
437.28 -
437.29 -Note: Some code samples reference the ctypes :class:`c_int` type. This type is
437.30 -an alias for the :class:`c_long` type on 32-bit systems. So, you should not be
437.31 -confused if :class:`c_long` is printed if you would expect :class:`c_int` ---
437.32 -they are actually the same type.
437.33 -
437.34 -
437.35 -.. _ctypes-loading-dynamic-link-libraries:
437.36 -
437.37 -Loading dynamic link libraries
437.38 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
437.39 -
437.40 -``ctypes`` exports the *cdll*, and on Windows *windll* and *oledll*
437.41 -objects, for loading dynamic link libraries.
437.42 -
437.43 -You load libraries by accessing them as attributes of these objects. *cdll*
437.44 -loads libraries which export functions using the standard ``cdecl`` calling
437.45 -convention, while *windll* libraries call functions using the ``stdcall``
437.46 -calling convention. *oledll* also uses the ``stdcall`` calling convention, and
437.47 -assumes the functions return a Windows :class:`HRESULT` error code. The error
437.48 -code is used to automatically raise a :class:`WindowsError` exception when
437.49 -the function call fails.
437.50 -
437.51 -Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C
437.52 -library containing most standard C functions, and uses the cdecl calling
437.53 -convention::
437.54 -
437.55 - >>> from ctypes import *
437.56 - >>> print windll.kernel32 # doctest: +WINDOWS
437.57 - <WinDLL 'kernel32', handle ... at ...>
437.58 - >>> print cdll.msvcrt # doctest: +WINDOWS
437.59 - <CDLL 'msvcrt', handle ... at ...>
437.60 - >>> libc = cdll.msvcrt # doctest: +WINDOWS
437.61 - >>>
437.62 -
437.63 -Windows appends the usual ``.dll`` file suffix automatically.
437.64 -
437.65 -On Linux, it is required to specify the filename *including* the extension to
437.66 -load a library, so attribute access can not be used to load libraries. Either the
437.67 -:meth:`LoadLibrary` method of the dll loaders should be used, or you should load
437.68 -the library by creating an instance of CDLL by calling the constructor::
437.69 -
437.70 - >>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX
437.71 - <CDLL 'libc.so.6', handle ... at ...>
437.72 - >>> libc = CDLL("libc.so.6") # doctest: +LINUX
437.73 - >>> libc # doctest: +LINUX
437.74 - <CDLL 'libc.so.6', handle ... at ...>
437.75 - >>>
437.76 -
437.77 -.. XXX Add section for Mac OS X.
437.78 -
437.79 -
437.80 -.. _ctypes-accessing-functions-from-loaded-dlls:
437.81 -
437.82 -Accessing functions from loaded dlls
437.83 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
437.84 -
437.85 -Functions are accessed as attributes of dll objects::
437.86 -
437.87 - >>> from ctypes import *
437.88 - >>> libc.printf
437.89 - <_FuncPtr object at 0x...>
437.90 - >>> print windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
437.91 - <_FuncPtr object at 0x...>
437.92 - >>> print windll.kernel32.MyOwnFunction # doctest: +WINDOWS
437.93 - Traceback (most recent call last):
437.94 - File "<stdin>", line 1, in ?
437.95 - File "ctypes.py", line 239, in __getattr__
437.96 - func = _StdcallFuncPtr(name, self)
437.97 - AttributeError: function 'MyOwnFunction' not found
437.98 - >>>
437.99 -
437.100 -Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI
437.101 -as well as UNICODE versions of a function. The UNICODE version is exported with
437.102 -an ``W`` appended to the name, while the ANSI version is exported with an ``A``
437.103 -appended to the name. The win32 ``GetModuleHandle`` function, which returns a
437.104 -*module handle* for a given module name, has the following C prototype, and a
437.105 -macro is used to expose one of them as ``GetModuleHandle`` depending on whether
437.106 -UNICODE is defined or not::
437.107 -
437.108 - /* ANSI version */
437.109 - HMODULE GetModuleHandleA(LPCSTR lpModuleName);
437.110 - /* UNICODE version */
437.111 - HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
437.112 -
437.113 -*windll* does not try to select one of them by magic, you must access the
437.114 -version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW``
437.115 -explicitly, and then call it with strings or unicode strings
437.116 -respectively.
437.117 -
437.118 -Sometimes, dlls export functions with names which aren't valid Python
437.119 -identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use ``getattr``
437.120 -to retrieve the function::
437.121 -
437.122 - >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS
437.123 - <_FuncPtr object at 0x...>
437.124 - >>>
437.125 -
437.126 -On Windows, some dlls export functions not by name but by ordinal. These
437.127 -functions can be accessed by indexing the dll object with the ordinal number::
437.128 -
437.129 - >>> cdll.kernel32[1] # doctest: +WINDOWS
437.130 - <_FuncPtr object at 0x...>
437.131 - >>> cdll.kernel32[0] # doctest: +WINDOWS
437.132 - Traceback (most recent call last):
437.133 - File "<stdin>", line 1, in ?
437.134 - File "ctypes.py", line 310, in __getitem__
437.135 - func = _StdcallFuncPtr(name, self)
437.136 - AttributeError: function ordinal 0 not found
437.137 - >>>
437.138 -
437.139 -
437.140 -.. _ctypes-calling-functions:
437.141 -
437.142 -Calling functions
437.143 -^^^^^^^^^^^^^^^^^
437.144 -
437.145 -You can call these functions like any other Python callable. This example uses
437.146 -the ``time()`` function, which returns system time in seconds since the Unix
437.147 -epoch, and the ``GetModuleHandleA()`` function, which returns a win32 module
437.148 -handle.
437.149 -
437.150 -This example calls both functions with a NULL pointer (``None`` should be used
437.151 -as the NULL pointer)::
437.152 -
437.153 - >>> print libc.time(None) # doctest: +SKIP
437.154 - 1150640792
437.155 - >>> print hex(windll.kernel32.GetModuleHandleA(None)) # doctest: +WINDOWS
437.156 - 0x1d000000
437.157 - >>>
437.158 -
437.159 -``ctypes`` tries to protect you from calling functions with the wrong number of
437.160 -arguments or the wrong calling convention. Unfortunately this only works on
437.161 -Windows. It does this by examining the stack after the function returns, so
437.162 -although an error is raised the function *has* been called::
437.163 -
437.164 - >>> windll.kernel32.GetModuleHandleA() # doctest: +WINDOWS
437.165 - Traceback (most recent call last):
437.166 - File "<stdin>", line 1, in ?
437.167 - ValueError: Procedure probably called with not enough arguments (4 bytes missing)
437.168 - >>> windll.kernel32.GetModuleHandleA(0, 0) # doctest: +WINDOWS
437.169 - Traceback (most recent call last):
437.170 - File "<stdin>", line 1, in ?
437.171 - ValueError: Procedure probably called with too many arguments (4 bytes in excess)
437.172 - >>>
437.173 -
437.174 -The same exception is raised when you call an ``stdcall`` function with the
437.175 -``cdecl`` calling convention, or vice versa::
437.176 -
437.177 - >>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS
437.178 - Traceback (most recent call last):
437.179 - File "<stdin>", line 1, in ?
437.180 - ValueError: Procedure probably called with not enough arguments (4 bytes missing)
437.181 - >>>
437.182 -
437.183 - >>> windll.msvcrt.printf("spam") # doctest: +WINDOWS
437.184 - Traceback (most recent call last):
437.185 - File "<stdin>", line 1, in ?
437.186 - ValueError: Procedure probably called with too many arguments (4 bytes in excess)
437.187 - >>>
437.188 -
437.189 -To find out the correct calling convention you have to look into the C header
437.190 -file or the documentation for the function you want to call.
437.191 -
437.192 -On Windows, ``ctypes`` uses win32 structured exception handling to prevent
437.193 -crashes from general protection faults when functions are called with invalid
437.194 -argument values::
437.195 -
437.196 - >>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS
437.197 - Traceback (most recent call last):
437.198 - File "<stdin>", line 1, in ?
437.199 - WindowsError: exception: access violation reading 0x00000020
437.200 - >>>
437.201 -
437.202 -There are, however, enough ways to crash Python with ``ctypes``, so you should
437.203 -be careful anyway.
437.204 -
437.205 -``None``, integers, longs, byte strings and unicode strings are the only native
437.206 -Python objects that can directly be used as parameters in these function calls.
437.207 -``None`` is passed as a C ``NULL`` pointer, byte strings and unicode strings are
437.208 -passed as pointer to the memory block that contains their data (``char *`` or
437.209 -``wchar_t *``). Python integers and Python longs are passed as the platforms
437.210 -default C ``int`` type, their value is masked to fit into the C type.
437.211 -
437.212 -Before we move on calling functions with other parameter types, we have to learn
437.213 -more about ``ctypes`` data types.
437.214 -
437.215 -
437.216 -.. _ctypes-fundamental-data-types:
437.217 -
437.218 -Fundamental data types
437.219 -^^^^^^^^^^^^^^^^^^^^^^
437.220 -
437.221 -``ctypes`` defines a number of primitive C compatible data types :
437.222 -
437.223 - +----------------------+--------------------------------+----------------------------+
437.224 - | ctypes type | C type | Python type |
437.225 - +======================+================================+============================+
437.226 - | :class:`c_char` | ``char`` | 1-character string |
437.227 - +----------------------+--------------------------------+----------------------------+
437.228 - | :class:`c_wchar` | ``wchar_t`` | 1-character unicode string |
437.229 - +----------------------+--------------------------------+----------------------------+
437.230 - | :class:`c_byte` | ``char`` | int/long |
437.231 - +----------------------+--------------------------------+----------------------------+
437.232 - | :class:`c_ubyte` | ``unsigned char`` | int/long |
437.233 - +----------------------+--------------------------------+----------------------------+
437.234 - | :class:`c_short` | ``short`` | int/long |
437.235 - +----------------------+--------------------------------+----------------------------+
437.236 - | :class:`c_ushort` | ``unsigned short`` | int/long |
437.237 - +----------------------+--------------------------------+----------------------------+
437.238 - | :class:`c_int` | ``int`` | int/long |
437.239 - +----------------------+--------------------------------+----------------------------+
437.240 - | :class:`c_uint` | ``unsigned int`` | int/long |
437.241 - +----------------------+--------------------------------+----------------------------+
437.242 - | :class:`c_long` | ``long`` | int/long |
437.243 - +----------------------+--------------------------------+----------------------------+
437.244 - | :class:`c_ulong` | ``unsigned long`` | int/long |
437.245 - +----------------------+--------------------------------+----------------------------+
437.246 - | :class:`c_longlong` | ``__int64`` or ``long long`` | int/long |
437.247 - +----------------------+--------------------------------+----------------------------+
437.248 - | :class:`c_ulonglong` | ``unsigned __int64`` or | int/long |
437.249 - | | ``unsigned long long`` | |
437.250 - +----------------------+--------------------------------+----------------------------+
437.251 - | :class:`c_float` | ``float`` | float |
437.252 - +----------------------+--------------------------------+----------------------------+
437.253 - | :class:`c_double` | ``double`` | float |
437.254 - +----------------------+--------------------------------+----------------------------+
437.255 - | :class:`c_longdouble`| ``long double`` | float |
437.256 - +----------------------+--------------------------------+----------------------------+
437.257 - | :class:`c_char_p` | ``char *`` (NUL terminated) | string or ``None`` |
437.258 - +----------------------+--------------------------------+----------------------------+
437.259 - | :class:`c_wchar_p` | ``wchar_t *`` (NUL terminated) | unicode or ``None`` |
437.260 - +----------------------+--------------------------------+----------------------------+
437.261 - | :class:`c_void_p` | ``void *`` | int/long or ``None`` |
437.262 - +----------------------+--------------------------------+----------------------------+
437.263 -
437.264 -
437.265 -All these types can be created by calling them with an optional initializer of
437.266 -the correct type and value::
437.267 -
437.268 - >>> c_int()
437.269 - c_long(0)
437.270 - >>> c_char_p("Hello, World")
437.271 - c_char_p('Hello, World')
437.272 - >>> c_ushort(-3)
437.273 - c_ushort(65533)
437.274 - >>>
437.275 -
437.276 -Since these types are mutable, their value can also be changed afterwards::
437.277 -
437.278 - >>> i = c_int(42)
437.279 - >>> print i
437.280 - c_long(42)
437.281 - >>> print i.value
437.282 - 42
437.283 - >>> i.value = -99
437.284 - >>> print i.value
437.285 - -99
437.286 - >>>
437.287 -
437.288 -Assigning a new value to instances of the pointer types :class:`c_char_p`,
437.289 -:class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they
437.290 -point to, *not the contents* of the memory block (of course not, because Python
437.291 -strings are immutable)::
437.292 -
437.293 - >>> s = "Hello, World"
437.294 - >>> c_s = c_char_p(s)
437.295 - >>> print c_s
437.296 - c_char_p('Hello, World')
437.297 - >>> c_s.value = "Hi, there"
437.298 - >>> print c_s
437.299 - c_char_p('Hi, there')
437.300 - >>> print s # first string is unchanged
437.301 - Hello, World
437.302 - >>>
437.303 -
437.304 -You should be careful, however, not to pass them to functions expecting pointers
437.305 -to mutable memory. If you need mutable memory blocks, ctypes has a
437.306 -``create_string_buffer`` function which creates these in various ways. The
437.307 -current memory block contents can be accessed (or changed) with the ``raw``
437.308 -property; if you want to access it as NUL terminated string, use the ``value``
437.309 -property::
437.310 -
437.311 - >>> from ctypes import *
437.312 - >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes
437.313 - >>> print sizeof(p), repr(p.raw)
437.314 - 3 '\x00\x00\x00'
437.315 - >>> p = create_string_buffer("Hello") # create a buffer containing a NUL terminated string
437.316 - >>> print sizeof(p), repr(p.raw)
437.317 - 6 'Hello\x00'
437.318 - >>> print repr(p.value)
437.319 - 'Hello'
437.320 - >>> p = create_string_buffer("Hello", 10) # create a 10 byte buffer
437.321 - >>> print sizeof(p), repr(p.raw)
437.322 - 10 'Hello\x00\x00\x00\x00\x00'
437.323 - >>> p.value = "Hi"
437.324 - >>> print sizeof(p), repr(p.raw)
437.325 - 10 'Hi\x00lo\x00\x00\x00\x00\x00'
437.326 - >>>
437.327 -
437.328 -The ``create_string_buffer`` function replaces the ``c_buffer`` function (which
437.329 -is still available as an alias), as well as the ``c_string`` function from
437.330 -earlier ctypes releases. To create a mutable memory block containing unicode
437.331 -characters of the C type ``wchar_t`` use the ``create_unicode_buffer`` function.
437.332 -
437.333 -
437.334 -.. _ctypes-calling-functions-continued:
437.335 -
437.336 -Calling functions, continued
437.337 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^
437.338 -
437.339 -Note that printf prints to the real standard output channel, *not* to
437.340 -``sys.stdout``, so these examples will only work at the console prompt, not from
437.341 -within *IDLE* or *PythonWin*::
437.342 -
437.343 - >>> printf = libc.printf
437.344 - >>> printf("Hello, %s\n", "World!")
437.345 - Hello, World!
437.346 - 14
437.347 - >>> printf("Hello, %S", u"World!")
437.348 - Hello, World!
437.349 - 13
437.350 - >>> printf("%d bottles of beer\n", 42)
437.351 - 42 bottles of beer
437.352 - 19
437.353 - >>> printf("%f bottles of beer\n", 42.5)
437.354 - Traceback (most recent call last):
437.355 - File "<stdin>", line 1, in ?
437.356 - ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
437.357 - >>>
437.358 -
437.359 -As has been mentioned before, all Python types except integers, strings, and
437.360 -unicode strings have to be wrapped in their corresponding ``ctypes`` type, so
437.361 -that they can be converted to the required C data type::
437.362 -
437.363 - >>> printf("An int %d, a double %f\n", 1234, c_double(3.14))
437.364 - Integer 1234, double 3.1400001049
437.365 - 31
437.366 - >>>
437.367 -
437.368 -
437.369 -.. _ctypes-calling-functions-with-own-custom-data-types:
437.370 -
437.371 -Calling functions with your own custom data types
437.372 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
437.373 -
437.374 -You can also customize ``ctypes`` argument conversion to allow instances of your
437.375 -own classes be used as function arguments. ``ctypes`` looks for an
437.376 -:attr:`_as_parameter_` attribute and uses this as the function argument. Of
437.377 -course, it must be one of integer, string, or unicode::
437.378 -
437.379 - >>> class Bottles(object):
437.380 - ... def __init__(self, number):
437.381 - ... self._as_parameter_ = number
437.382 - ...
437.383 - >>> bottles = Bottles(42)
437.384 - >>> printf("%d bottles of beer\n", bottles)
437.385 - 42 bottles of beer
437.386 - 19
437.387 - >>>
437.388 -
437.389 -If you don't want to store the instance's data in the :attr:`_as_parameter_`
437.390 -instance variable, you could define a ``property`` which makes the data
437.391 -available.
437.392 -
437.393 -
437.394 -.. _ctypes-specifying-required-argument-types:
437.395 -
437.396 -Specifying the required argument types (function prototypes)
437.397 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
437.398 -
437.399 -It is possible to specify the required argument types of functions exported from
437.400 -DLLs by setting the :attr:`argtypes` attribute.
437.401 -
437.402 -:attr:`argtypes` must be a sequence of C data types (the ``printf`` function is
437.403 -probably not a good example here, because it takes a variable number and
437.404 -different types of parameters depending on the format string, on the other hand
437.405 -this is quite handy to experiment with this feature)::
437.406 -
437.407 - >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
437.408 - >>> printf("String '%s', Int %d, Double %f\n", "Hi", 10, 2.2)
437.409 - String 'Hi', Int 10, Double 2.200000
437.410 - 37
437.411 - >>>
437.412 -
437.413 -Specifying a format protects against incompatible argument types (just as a
437.414 -prototype for a C function), and tries to convert the arguments to valid types::
437.415 -
437.416 - >>> printf("%d %d %d", 1, 2, 3)
437.417 - Traceback (most recent call last):
437.418 - File "<stdin>", line 1, in ?
437.419 - ArgumentError: argument 2: exceptions.TypeError: wrong type
437.420 - >>> printf("%s %d %f", "X", 2, 3)
437.421 - X 2 3.00000012
437.422 - 12
437.423 - >>>
437.424 -
437.425 -If you have defined your own classes which you pass to function calls, you have
437.426 -to implement a :meth:`from_param` class method for them to be able to use them
437.427 -in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives
437.428 -the Python object passed to the function call, it should do a typecheck or
437.429 -whatever is needed to make sure this object is acceptable, and then return the
437.430 -object itself, its :attr:`_as_parameter_` attribute, or whatever you want to
437.431 -pass as the C function argument in this case. Again, the result should be an
437.432 -integer, string, unicode, a ``ctypes`` instance, or an object with an
437.433 -:attr:`_as_parameter_` attribute.
437.434 -
437.435 -
437.436 -.. _ctypes-return-types:
437.437 -
437.438 -Return types
437.439 -^^^^^^^^^^^^
437.440 -
437.441 -By default functions are assumed to return the C ``int`` type. Other return
437.442 -types can be specified by setting the :attr:`restype` attribute of the function
437.443 -object.
437.444 -
437.445 -Here is a more advanced example, it uses the ``strchr`` function, which expects
437.446 -a string pointer and a char, and returns a pointer to a string::
437.447 -
437.448 - >>> strchr = libc.strchr
437.449 - >>> strchr("abcdef", ord("d")) # doctest: +SKIP
437.450 - 8059983
437.451 - >>> strchr.restype = c_char_p # c_char_p is a pointer to a string
437.452 - >>> strchr("abcdef", ord("d"))
437.453 - 'def'
437.454 - >>> print strchr("abcdef", ord("x"))
437.455 - None
437.456 - >>>
437.457 -
437.458 -If you want to avoid the ``ord("x")`` calls above, you can set the
437.459 -:attr:`argtypes` attribute, and the second argument will be converted from a
437.460 -single character Python string into a C char::
437.461 -
437.462 - >>> strchr.restype = c_char_p
437.463 - >>> strchr.argtypes = [c_char_p, c_char]
437.464 - >>> strchr("abcdef", "d")
437.465 - 'def'
437.466 - >>> strchr("abcdef", "def")
437.467 - Traceback (most recent call last):
437.468 - File "<stdin>", line 1, in ?
437.469 - ArgumentError: argument 2: exceptions.TypeError: one character string expected
437.470 - >>> print strchr("abcdef", "x")
437.471 - None
437.472 - >>> strchr("abcdef", "d")
437.473 - 'def'
437.474 - >>>
437.475 -
437.476 -You can also use a callable Python object (a function or a class for example) as
437.477 -the :attr:`restype` attribute, if the foreign function returns an integer. The
437.478 -callable will be called with the ``integer`` the C function returns, and the
437.479 -result of this call will be used as the result of your function call. This is
437.480 -useful to check for error return values and automatically raise an exception::
437.481 -
437.482 - >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
437.483 - >>> def ValidHandle(value):
437.484 - ... if value == 0:
437.485 - ... raise WinError()
437.486 - ... return value
437.487 - ...
437.488 - >>>
437.489 - >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS
437.490 - >>> GetModuleHandle(None) # doctest: +WINDOWS
437.491 - 486539264
437.492 - >>> GetModuleHandle("something silly") # doctest: +WINDOWS
437.493 - Traceback (most recent call last):
437.494 - File "<stdin>", line 1, in ?
437.495 - File "<stdin>", line 3, in ValidHandle
437.496 - WindowsError: [Errno 126] The specified module could not be found.
437.497 - >>>
437.498 -
437.499 -``WinError`` is a function which will call Windows ``FormatMessage()`` api to
437.500 -get the string representation of an error code, and *returns* an exception.
437.501 -``WinError`` takes an optional error code parameter, if no one is used, it calls
437.502 -:func:`GetLastError` to retrieve it.
437.503 -
437.504 -Please note that a much more powerful error checking mechanism is available
437.505 -through the :attr:`errcheck` attribute; see the reference manual for details.
437.506 -
437.507 -
437.508 -.. _ctypes-passing-pointers:
437.509 -
437.510 -Passing pointers (or: passing parameters by reference)
437.511 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
437.512 -
437.513 -Sometimes a C api function expects a *pointer* to a data type as parameter,
437.514 -probably to write into the corresponding location, or if the data is too large
437.515 -to be passed by value. This is also known as *passing parameters by reference*.
437.516 -
437.517 -``ctypes`` exports the :func:`byref` function which is used to pass parameters
437.518 -by reference. The same effect can be achieved with the ``pointer`` function,
437.519 -although ``pointer`` does a lot more work since it constructs a real pointer
437.520 -object, so it is faster to use :func:`byref` if you don't need the pointer
437.521 -object in Python itself::
437.522 -
437.523 - >>> i = c_int()
437.524 - >>> f = c_float()
437.525 - >>> s = create_string_buffer('\000' * 32)
437.526 - >>> print i.value, f.value, repr(s.value)
437.527 - 0 0.0 ''
437.528 - >>> libc.sscanf("1 3.14 Hello", "%d %f %s",
437.529 - ... byref(i), byref(f), s)
437.530 - 3
437.531 - >>> print i.value, f.value, repr(s.value)
437.532 - 1 3.1400001049 'Hello'
437.533 - >>>
437.534 -
437.535 -
437.536 -.. _ctypes-structures-unions:
437.537 -
437.538 -Structures and unions
437.539 -^^^^^^^^^^^^^^^^^^^^^
437.540 -
437.541 -Structures and unions must derive from the :class:`Structure` and :class:`Union`
437.542 -base classes which are defined in the ``ctypes`` module. Each subclass must
437.543 -define a :attr:`_fields_` attribute. :attr:`_fields_` must be a list of
437.544 -*2-tuples*, containing a *field name* and a *field type*.
437.545 -
437.546 -The field type must be a ``ctypes`` type like :class:`c_int`, or any other
437.547 -derived ``ctypes`` type: structure, union, array, pointer.
437.548 -
437.549 -Here is a simple example of a POINT structure, which contains two integers named
437.550 -``x`` and ``y``, and also shows how to initialize a structure in the
437.551 -constructor::
437.552 -
437.553 - >>> from ctypes import *
437.554 - >>> class POINT(Structure):
437.555 - ... _fields_ = [("x", c_int),
437.556 - ... ("y", c_int)]
437.557 - ...
437.558 - >>> point = POINT(10, 20)
437.559 - >>> print point.x, point.y
437.560 - 10 20
437.561 - >>> point = POINT(y=5)
437.562 - >>> print point.x, point.y
437.563 - 0 5
437.564 - >>> POINT(1, 2, 3)
437.565 - Traceback (most recent call last):
437.566 - File "<stdin>", line 1, in ?
437.567 - ValueError: too many initializers
437.568 - >>>
437.569 -
437.570 -You can, however, build much more complicated structures. Structures can itself
437.571 -contain other structures by using a structure as a field type.
437.572 -
437.573 -Here is a RECT structure which contains two POINTs named ``upperleft`` and
437.574 -``lowerright`` ::
437.575 -
437.576 - >>> class RECT(Structure):
437.577 - ... _fields_ = [("upperleft", POINT),
437.578 - ... ("lowerright", POINT)]
437.579 - ...
437.580 - >>> rc = RECT(point)
437.581 - >>> print rc.upperleft.x, rc.upperleft.y
437.582 - 0 5
437.583 - >>> print rc.lowerright.x, rc.lowerright.y
437.584 - 0 0
437.585 - >>>
437.586 -
437.587 -Nested structures can also be initialized in the constructor in several ways::
437.588 -
437.589 - >>> r = RECT(POINT(1, 2), POINT(3, 4))
437.590 - >>> r = RECT((1, 2), (3, 4))
437.591 -
437.592 -Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
437.593 -for debugging because they can provide useful information::
437.594 -
437.595 - >>> print POINT.x
437.596 - <Field type=c_long, ofs=0, size=4>
437.597 - >>> print POINT.y
437.598 - <Field type=c_long, ofs=4, size=4>
437.599 - >>>
437.600 -
437.601 -
437.602 -.. _ctypes-structureunion-alignment-byte-order:
437.603 -
437.604 -Structure/union alignment and byte order
437.605 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
437.606 -
437.607 -By default, Structure and Union fields are aligned in the same way the C
437.608 -compiler does it. It is possible to override this behavior be specifying a
437.609 -:attr:`_pack_` class attribute in the subclass definition. This must be set to a
437.610 -positive integer and specifies the maximum alignment for the fields. This is
437.611 -what ``#pragma pack(n)`` also does in MSVC.
437.612 -
437.613 -``ctypes`` uses the native byte order for Structures and Unions. To build
437.614 -structures with non-native byte order, you can use one of the
437.615 -BigEndianStructure, LittleEndianStructure, BigEndianUnion, and LittleEndianUnion
437.616 -base classes. These classes cannot contain pointer fields.
437.617 -
437.618 -
437.619 -.. _ctypes-bit-fields-in-structures-unions:
437.620 -
437.621 -Bit fields in structures and unions
437.622 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
437.623 -
437.624 -It is possible to create structures and unions containing bit fields. Bit fields
437.625 -are only possible for integer fields, the bit width is specified as the third
437.626 -item in the :attr:`_fields_` tuples::
437.627 -
437.628 - >>> class Int(Structure):
437.629 - ... _fields_ = [("first_16", c_int, 16),
437.630 - ... ("second_16", c_int, 16)]
437.631 - ...
437.632 - >>> print Int.first_16
437.633 - <Field type=c_long, ofs=0:0, bits=16>
437.634 - >>> print Int.second_16
437.635 - <Field type=c_long, ofs=0:16, bits=16>
437.636 - >>>
437.637 -
437.638 -
437.639 -.. _ctypes-arrays:
437.640 -
437.641 -Arrays
437.642 -^^^^^^
437.643 -
437.644 -Arrays are sequences, containing a fixed number of instances of the same type.
437.645 -
437.646 -The recommended way to create array types is by multiplying a data type with a
437.647 -positive integer::
437.648 -
437.649 - TenPointsArrayType = POINT * 10
437.650 -
437.651 -Here is an example of an somewhat artificial data type, a structure containing 4
437.652 -POINTs among other stuff::
437.653 -
437.654 - >>> from ctypes import *
437.655 - >>> class POINT(Structure):
437.656 - ... _fields_ = ("x", c_int), ("y", c_int)
437.657 - ...
437.658 - >>> class MyStruct(Structure):
437.659 - ... _fields_ = [("a", c_int),
437.660 - ... ("b", c_float),
437.661 - ... ("point_array", POINT * 4)]
437.662 - >>>
437.663 - >>> print len(MyStruct().point_array)
437.664 - 4
437.665 - >>>
437.666 -
437.667 -Instances are created in the usual way, by calling the class::
437.668 -
437.669 - arr = TenPointsArrayType()
437.670 - for pt in arr:
437.671 - print pt.x, pt.y
437.672 -
437.673 -The above code print a series of ``0 0`` lines, because the array contents is
437.674 -initialized to zeros.
437.675 -
437.676 -Initializers of the correct type can also be specified::
437.677 -
437.678 - >>> from ctypes import *
437.679 - >>> TenIntegers = c_int * 10
437.680 - >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
437.681 - >>> print ii
437.682 - <c_long_Array_10 object at 0x...>
437.683 - >>> for i in ii: print i,
437.684 - ...
437.685 - 1 2 3 4 5 6 7 8 9 10
437.686 - >>>
437.687 -
437.688 -
437.689 -.. _ctypes-pointers:
437.690 -
437.691 -Pointers
437.692 -^^^^^^^^
437.693 -
437.694 -Pointer instances are created by calling the ``pointer`` function on a
437.695 -``ctypes`` type::
437.696 -
437.697 - >>> from ctypes import *
437.698 - >>> i = c_int(42)
437.699 - >>> pi = pointer(i)
437.700 - >>>
437.701 -
437.702 -Pointer instances have a ``contents`` attribute which returns the object to
437.703 -which the pointer points, the ``i`` object above::
437.704 -
437.705 - >>> pi.contents
437.706 - c_long(42)
437.707 - >>>
437.708 -
437.709 -Note that ``ctypes`` does not have OOR (original object return), it constructs a
437.710 -new, equivalent object each time you retrieve an attribute::
437.711 -
437.712 - >>> pi.contents is i
437.713 - False
437.714 - >>> pi.contents is pi.contents
437.715 - False
437.716 - >>>
437.717 -
437.718 -Assigning another :class:`c_int` instance to the pointer's contents attribute
437.719 -would cause the pointer to point to the memory location where this is stored::
437.720 -
437.721 - >>> i = c_int(99)
437.722 - >>> pi.contents = i
437.723 - >>> pi.contents
437.724 - c_long(99)
437.725 - >>>
437.726 -
437.727 -.. XXX Document dereferencing pointers, and that it is preferred over the .contents attribute.
437.728 -
437.729 -Pointer instances can also be indexed with integers::
437.730 -
437.731 - >>> pi[0]
437.732 - 99
437.733 - >>>
437.734 -
437.735 -Assigning to an integer index changes the pointed to value::
437.736 -
437.737 - >>> print i
437.738 - c_long(99)
437.739 - >>> pi[0] = 22
437.740 - >>> print i
437.741 - c_long(22)
437.742 - >>>
437.743 -
437.744 -It is also possible to use indexes different from 0, but you must know what
437.745 -you're doing, just as in C: You can access or change arbitrary memory locations.
437.746 -Generally you only use this feature if you receive a pointer from a C function,
437.747 -and you *know* that the pointer actually points to an array instead of a single
437.748 -item.
437.749 -
437.750 -Behind the scenes, the ``pointer`` function does more than simply create pointer
437.751 -instances, it has to create pointer *types* first. This is done with the
437.752 -``POINTER`` function, which accepts any ``ctypes`` type, and returns a new
437.753 -type::
437.754 -
437.755 - >>> PI = POINTER(c_int)
437.756 - >>> PI
437.757 - <class 'ctypes.LP_c_long'>
437.758 - >>> PI(42)
437.759 - Traceback (most recent call last):
437.760 - File "<stdin>", line 1, in ?
437.761 - TypeError: expected c_long instead of int
437.762 - >>> PI(c_int(42))
437.763 - <ctypes.LP_c_long object at 0x...>
437.764 - >>>
437.765 -
437.766 -Calling the pointer type without an argument creates a ``NULL`` pointer.
437.767 -``NULL`` pointers have a ``False`` boolean value::
437.768 -
437.769 - >>> null_ptr = POINTER(c_int)()
437.770 - >>> print bool(null_ptr)
437.771 - False
437.772 - >>>
437.773 -
437.774 -``ctypes`` checks for ``NULL`` when dereferencing pointers (but dereferencing
437.775 -invalid non-\ ``NULL`` pointers would crash Python)::
437.776 -
437.777 - >>> null_ptr[0]
437.778 - Traceback (most recent call last):
437.779 - ....
437.780 - ValueError: NULL pointer access
437.781 - >>>
437.782 -
437.783 - >>> null_ptr[0] = 1234
437.784 - Traceback (most recent call last):
437.785 - ....
437.786 - ValueError: NULL pointer access
437.787 - >>>
437.788 -
437.789 -
437.790 -.. _ctypes-type-conversions:
437.791 -
437.792 -Type conversions
437.793 -^^^^^^^^^^^^^^^^
437.794 -
437.795 -Usually, ctypes does strict type checking. This means, if you have
437.796 -``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of
437.797 -a member field in a structure definition, only instances of exactly the same
437.798 -type are accepted. There are some exceptions to this rule, where ctypes accepts
437.799 -other objects. For example, you can pass compatible array instances instead of
437.800 -pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
437.801 -
437.802 - >>> class Bar(Structure):
437.803 - ... _fields_ = [("count", c_int), ("values", POINTER(c_int))]
437.804 - ...
437.805 - >>> bar = Bar()
437.806 - >>> bar.values = (c_int * 3)(1, 2, 3)
437.807 - >>> bar.count = 3
437.808 - >>> for i in range(bar.count):
437.809 - ... print bar.values[i]
437.810 - ...
437.811 - 1
437.812 - 2
437.813 - 3
437.814 - >>>
437.815 -
437.816 -To set a POINTER type field to ``NULL``, you can assign ``None``::
437.817 -
437.818 - >>> bar.values = None
437.819 - >>>
437.820 -
437.821 -.. XXX list other conversions...
437.822 -
437.823 -Sometimes you have instances of incompatible types. In C, you can cast one
437.824 -type into another type. ``ctypes`` provides a ``cast`` function which can be
437.825 -used in the same way. The ``Bar`` structure defined above accepts
437.826 -``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
437.827 -but not instances of other types::
437.828 -
437.829 - >>> bar.values = (c_byte * 4)()
437.830 - Traceback (most recent call last):
437.831 - File "<stdin>", line 1, in ?
437.832 - TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
437.833 - >>>
437.834 -
437.835 -For these cases, the ``cast`` function is handy.
437.836 -
437.837 -The ``cast`` function can be used to cast a ctypes instance into a pointer to a
437.838 -different ctypes data type. ``cast`` takes two parameters, a ctypes object that
437.839 -is or can be converted to a pointer of some kind, and a ctypes pointer type. It
437.840 -returns an instance of the second argument, which references the same memory
437.841 -block as the first argument::
437.842 -
437.843 - >>> a = (c_byte * 4)()
437.844 - >>> cast(a, POINTER(c_int))
437.845 - <ctypes.LP_c_long object at ...>
437.846 - >>>
437.847 -
437.848 -So, ``cast`` can be used to assign to the ``values`` field of ``Bar`` the
437.849 -structure::
437.850 -
437.851 - >>> bar = Bar()
437.852 - >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
437.853 - >>> print bar.values[0]
437.854 - 0
437.855 - >>>
437.856 -
437.857 -
437.858 -.. _ctypes-incomplete-types:
437.859 -
437.860 -Incomplete Types
437.861 -^^^^^^^^^^^^^^^^
437.862 -
437.863 -*Incomplete Types* are structures, unions or arrays whose members are not yet
437.864 -specified. In C, they are specified by forward declarations, which are defined
437.865 -later::
437.866 -
437.867 - struct cell; /* forward declaration */
437.868 -
437.869 - struct {
437.870 - char *name;
437.871 - struct cell *next;
437.872 - } cell;
437.873 -
437.874 -The straightforward translation into ctypes code would be this, but it does not
437.875 -work::
437.876 -
437.877 - >>> class cell(Structure):
437.878 - ... _fields_ = [("name", c_char_p),
437.879 - ... ("next", POINTER(cell))]
437.880 - ...
437.881 - Traceback (most recent call last):
437.882 - File "<stdin>", line 1, in ?
437.883 - File "<stdin>", line 2, in cell
437.884 - NameError: name 'cell' is not defined
437.885 - >>>
437.886 -
437.887 -because the new ``class cell`` is not available in the class statement itself.
437.888 -In ``ctypes``, we can define the ``cell`` class and set the :attr:`_fields_`
437.889 -attribute later, after the class statement::
437.890 -
437.891 - >>> from ctypes import *
437.892 - >>> class cell(Structure):
437.893 - ... pass
437.894 - ...
437.895 - >>> cell._fields_ = [("name", c_char_p),
437.896 - ... ("next", POINTER(cell))]
437.897 - >>>
437.898 -
437.899 -Lets try it. We create two instances of ``cell``, and let them point to each
437.900 -other, and finally follow the pointer chain a few times::
437.901 -
437.902 - >>> c1 = cell()
437.903 - >>> c1.name = "foo"
437.904 - >>> c2 = cell()
437.905 - >>> c2.name = "bar"
437.906 - >>> c1.next = pointer(c2)
437.907 - >>> c2.next = pointer(c1)
437.908 - >>> p = c1
437.909 - >>> for i in range(8):
437.910 - ... print p.name,
437.911 - ... p = p.next[0]
437.912 - ...
437.913 - foo bar foo bar foo bar foo bar
437.914 - >>>
437.915 -
437.916 -
437.917 -.. _ctypes-callback-functions:
437.918 -
437.919 -Callback functions
437.920 -^^^^^^^^^^^^^^^^^^
437.921 -
437.922 -``ctypes`` allows to create C callable function pointers from Python callables.
437.923 -These are sometimes called *callback functions*.
437.924 -
437.925 -First, you must create a class for the callback function, the class knows the
437.926 -calling convention, the return type, and the number and types of arguments this
437.927 -function will receive.
437.928 -
437.929 -The CFUNCTYPE factory function creates types for callback functions using the
437.930 -normal cdecl calling convention, and, on Windows, the WINFUNCTYPE factory
437.931 -function creates types for callback functions using the stdcall calling
437.932 -convention.
437.933 -
437.934 -Both of these factory functions are called with the result type as first
437.935 -argument, and the callback functions expected argument types as the remaining
437.936 -arguments.
437.937 -
437.938 -I will present an example here which uses the standard C library's :func:`qsort`
437.939 -function, this is used to sort items with the help of a callback function.
437.940 -:func:`qsort` will be used to sort an array of integers::
437.941 -
437.942 - >>> IntArray5 = c_int * 5
437.943 - >>> ia = IntArray5(5, 1, 7, 33, 99)
437.944 - >>> qsort = libc.qsort
437.945 - >>> qsort.restype = None
437.946 - >>>
437.947 -
437.948 -:func:`qsort` must be called with a pointer to the data to sort, the number of
437.949 -items in the data array, the size of one item, and a pointer to the comparison
437.950 -function, the callback. The callback will then be called with two pointers to
437.951 -items, and it must return a negative integer if the first item is smaller than
437.952 -the second, a zero if they are equal, and a positive integer else.
437.953 -
437.954 -So our callback function receives pointers to integers, and must return an
437.955 -integer. First we create the ``type`` for the callback function::
437.956 -
437.957 - >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
437.958 - >>>
437.959 -
437.960 -For the first implementation of the callback function, we simply print the
437.961 -arguments we get, and return 0 (incremental development ;-)::
437.962 -
437.963 - >>> def py_cmp_func(a, b):
437.964 - ... print "py_cmp_func", a, b
437.965 - ... return 0
437.966 - ...
437.967 - >>>
437.968 -
437.969 -Create the C callable callback::
437.970 -
437.971 - >>> cmp_func = CMPFUNC(py_cmp_func)
437.972 - >>>
437.973 -
437.974 -And we're ready to go::
437.975 -
437.976 - >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
437.977 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
437.978 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
437.979 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
437.980 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
437.981 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
437.982 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
437.983 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
437.984 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
437.985 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
437.986 - py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
437.987 - >>>
437.988 -
437.989 -We know how to access the contents of a pointer, so lets redefine our callback::
437.990 -
437.991 - >>> def py_cmp_func(a, b):
437.992 - ... print "py_cmp_func", a[0], b[0]
437.993 - ... return 0
437.994 - ...
437.995 - >>> cmp_func = CMPFUNC(py_cmp_func)
437.996 - >>>
437.997 -
437.998 -Here is what we get on Windows::
437.999 -
437.1000 - >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
437.1001 - py_cmp_func 7 1
437.1002 - py_cmp_func 33 1
437.1003 - py_cmp_func 99 1
437.1004 - py_cmp_func 5 1
437.1005 - py_cmp_func 7 5
437.1006 - py_cmp_func 33 5
437.1007 - py_cmp_func 99 5
437.1008 - py_cmp_func 7 99
437.1009 - py_cmp_func 33 99
437.1010 - py_cmp_func 7 33
437.1011 - >>>
437.1012 -
437.1013 -It is funny to see that on linux the sort function seems to work much more
437.1014 -efficient, it is doing less comparisons::
437.1015 -
437.1016 - >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
437.1017 - py_cmp_func 5 1
437.1018 - py_cmp_func 33 99
437.1019 - py_cmp_func 7 33
437.1020 - py_cmp_func 5 7
437.1021 - py_cmp_func 1 7
437.1022 - >>>
437.1023 -
437.1024 -Ah, we're nearly done! The last step is to actually compare the two items and
437.1025 -return a useful result::
437.1026 -
437.1027 - >>> def py_cmp_func(a, b):
437.1028 - ... print "py_cmp_func", a[0], b[0]
437.1029 - ... return a[0] - b[0]
437.1030 - ...
437.1031 - >>>
437.1032 -
437.1033 -Final run on Windows::
437.1034 -
437.1035 - >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +WINDOWS
437.1036 - py_cmp_func 33 7
437.1037 - py_cmp_func 99 33
437.1038 - py_cmp_func 5 99
437.1039 - py_cmp_func 1 99
437.1040 - py_cmp_func 33 7
437.1041 - py_cmp_func 1 33
437.1042 - py_cmp_func 5 33
437.1043 - py_cmp_func 5 7
437.1044 - py_cmp_func 1 7
437.1045 - py_cmp_func 5 1
437.1046 - >>>
437.1047 -
437.1048 -and on Linux::
437.1049 -
437.1050 - >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
437.1051 - py_cmp_func 5 1
437.1052 - py_cmp_func 33 99
437.1053 - py_cmp_func 7 33
437.1054 - py_cmp_func 1 7
437.1055 - py_cmp_func 5 7
437.1056 - >>>
437.1057 -
437.1058 -It is quite interesting to see that the Windows :func:`qsort` function needs
437.1059 -more comparisons than the linux version!
437.1060 -
437.1061 -As we can easily check, our array is sorted now::
437.1062 -
437.1063 - >>> for i in ia: print i,
437.1064 - ...
437.1065 - 1 5 7 33 99
437.1066 - >>>
437.1067 -
437.1068 -**Important note for callback functions:**
437.1069 -
437.1070 -Make sure you keep references to CFUNCTYPE objects as long as they are used from
437.1071 -C code. ``ctypes`` doesn't, and if you don't, they may be garbage collected,
437.1072 -crashing your program when a callback is made.
437.1073 -
437.1074 -
437.1075 -.. _ctypes-accessing-values-exported-from-dlls:
437.1076 -
437.1077 -Accessing values exported from dlls
437.1078 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
437.1079 -
437.1080 -Some shared libraries not only export functions, they also export variables. An
437.1081 -example in the Python library itself is the ``Py_OptimizeFlag``, an integer set
437.1082 -to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
437.1083 -startup.
437.1084 -
437.1085 -``ctypes`` can access values like this with the :meth:`in_dll` class methods of
437.1086 -the type. *pythonapi* is a predefined symbol giving access to the Python C
437.1087 -api::
437.1088 -
437.1089 - >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
437.1090 - >>> print opt_flag
437.1091 - c_long(0)
437.1092 - >>>
437.1093 -
437.1094 -If the interpreter would have been started with :option:`-O`, the sample would
437.1095 -have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been
437.1096 -specified.
437.1097 -
437.1098 -An extended example which also demonstrates the use of pointers accesses the
437.1099 -``PyImport_FrozenModules`` pointer exported by Python.
437.1100 -
437.1101 -Quoting the Python docs: *This pointer is initialized to point to an array of
437.1102 -"struct _frozen" records, terminated by one whose members are all NULL or zero.
437.1103 -When a frozen module is imported, it is searched in this table. Third-party code
437.1104 -could play tricks with this to provide a dynamically created collection of
437.1105 -frozen modules.*
437.1106 -
437.1107 -So manipulating this pointer could even prove useful. To restrict the example
437.1108 -size, we show only how this table can be read with ``ctypes``::
437.1109 -
437.1110 - >>> from ctypes import *
437.1111 - >>>
437.1112 - >>> class struct_frozen(Structure):
437.1113 - ... _fields_ = [("name", c_char_p),
437.1114 - ... ("code", POINTER(c_ubyte)),
437.1115 - ... ("size", c_int)]
437.1116 - ...
437.1117 - >>>
437.1118 -
437.1119 -We have defined the ``struct _frozen`` data type, so we can get the pointer to
437.1120 -the table::
437.1121 -
437.1122 - >>> FrozenTable = POINTER(struct_frozen)
437.1123 - >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
437.1124 - >>>
437.1125 -
437.1126 -Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
437.1127 -can iterate over it, but we just have to make sure that our loop terminates,
437.1128 -because pointers have no size. Sooner or later it would probably crash with an
437.1129 -access violation or whatever, so it's better to break out of the loop when we
437.1130 -hit the NULL entry::
437.1131 -
437.1132 - >>> for item in table:
437.1133 - ... print item.name, item.size
437.1134 - ... if item.name is None:
437.1135 - ... break
437.1136 - ...
437.1137 - __hello__ 104
437.1138 - __phello__ -104
437.1139 - __phello__.spam 104
437.1140 - None 0
437.1141 - >>>
437.1142 -
437.1143 -The fact that standard Python has a frozen module and a frozen package
437.1144 -(indicated by the negative size member) is not well known, it is only used for
437.1145 -testing. Try it out with ``import __hello__`` for example.
437.1146 -
437.1147 -
437.1148 -.. _ctypes-surprises:
437.1149 -
437.1150 -Surprises
437.1151 -^^^^^^^^^
437.1152 -
437.1153 -There are some edges in ``ctypes`` where you may be expect something else than
437.1154 -what actually happens.
437.1155 -
437.1156 -Consider the following example::
437.1157 -
437.1158 - >>> from ctypes import *
437.1159 - >>> class POINT(Structure):
437.1160 - ... _fields_ = ("x", c_int), ("y", c_int)
437.1161 - ...
437.1162 - >>> class RECT(Structure):
437.1163 - ... _fields_ = ("a", POINT), ("b", POINT)
437.1164 - ...
437.1165 - >>> p1 = POINT(1, 2)
437.1166 - >>> p2 = POINT(3, 4)
437.1167 - >>> rc = RECT(p1, p2)
437.1168 - >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
437.1169 - 1 2 3 4
437.1170 - >>> # now swap the two points
437.1171 - >>> rc.a, rc.b = rc.b, rc.a
437.1172 - >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
437.1173 - 3 4 3 4
437.1174 - >>>
437.1175 -
437.1176 -Hm. We certainly expected the last statement to print ``3 4 1 2``. What
437.1177 -happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
437.1178 -
437.1179 - >>> temp0, temp1 = rc.b, rc.a
437.1180 - >>> rc.a = temp0
437.1181 - >>> rc.b = temp1
437.1182 - >>>
437.1183 -
437.1184 -Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
437.1185 -the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
437.1186 -contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the
437.1187 -contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
437.1188 -the expected effect.
437.1189 -
437.1190 -Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
437.1191 -doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
437.1192 -the root-object's underlying buffer.
437.1193 -
437.1194 -Another example that may behave different from what one would expect is this::
437.1195 -
437.1196 - >>> s = c_char_p()
437.1197 - >>> s.value = "abc def ghi"
437.1198 - >>> s.value
437.1199 - 'abc def ghi'
437.1200 - >>> s.value is s.value
437.1201 - False
437.1202 - >>>
437.1203 -
437.1204 -Why is it printing ``False``? ctypes instances are objects containing a memory
437.1205 -block plus some :term:`descriptor`\s accessing the contents of the memory.
437.1206 -Storing a Python object in the memory block does not store the object itself,
437.1207 -instead the ``contents`` of the object is stored. Accessing the contents again
437.1208 -constructs a new Python object each time!
437.1209 -
437.1210 -
437.1211 -.. _ctypes-variable-sized-data-types:
437.1212 -
437.1213 -Variable-sized data types
437.1214 -^^^^^^^^^^^^^^^^^^^^^^^^^
437.1215 -
437.1216 -``ctypes`` provides some support for variable-sized arrays and structures (this
437.1217 -was added in version 0.9.9.7).
437.1218 -
437.1219 -The ``resize`` function can be used to resize the memory buffer of an existing
437.1220 -ctypes object. The function takes the object as first argument, and the
437.1221 -requested size in bytes as the second argument. The memory block cannot be made
437.1222 -smaller than the natural memory block specified by the objects type, a
437.1223 -``ValueError`` is raised if this is tried::
437.1224 -
437.1225 - >>> short_array = (c_short * 4)()
437.1226 - >>> print sizeof(short_array)
437.1227 - 8
437.1228 - >>> resize(short_array, 4)
437.1229 - Traceback (most recent call last):
437.1230 - ...
437.1231 - ValueError: minimum size is 8
437.1232 - >>> resize(short_array, 32)
437.1233 - >>> sizeof(short_array)
437.1234 - 32
437.1235 - >>> sizeof(type(short_array))
437.1236 - 8
437.1237 - >>>
437.1238 -
437.1239 -This is nice and fine, but how would one access the additional elements
437.1240 -contained in this array? Since the type still only knows about 4 elements, we
437.1241 -get errors accessing other elements::
437.1242 -
437.1243 - >>> short_array[:]
437.1244 - [0, 0, 0, 0]
437.1245 - >>> short_array[7]
437.1246 - Traceback (most recent call last):
437.1247 - ...
437.1248 - IndexError: invalid index
437.1249 - >>>
437.1250 -
437.1251 -Another way to use variable-sized data types with ``ctypes`` is to use the
437.1252 -dynamic nature of Python, and (re-)define the data type after the required size
437.1253 -is already known, on a case by case basis.
437.1254 -
437.1255 -
437.1256 -.. _ctypes-ctypes-reference:
437.1257 -
437.1258 -ctypes reference
437.1259 -----------------
437.1260 -
437.1261 -
437.1262 -.. _ctypes-finding-shared-libraries:
437.1263 -
437.1264 -Finding shared libraries
437.1265 -^^^^^^^^^^^^^^^^^^^^^^^^
437.1266 -
437.1267 -When programming in a compiled language, shared libraries are accessed when
437.1268 -compiling/linking a program, and when the program is run.
437.1269 -
437.1270 -The purpose of the ``find_library`` function is to locate a library in a way
437.1271 -similar to what the compiler does (on platforms with several versions of a
437.1272 -shared library the most recent should be loaded), while the ctypes library
437.1273 -loaders act like when a program is run, and call the runtime loader directly.
437.1274 -
437.1275 -The ``ctypes.util`` module provides a function which can help to determine the
437.1276 -library to load.
437.1277 -
437.1278 -
437.1279 -.. data:: find_library(name)
437.1280 - :noindex:
437.1281 -
437.1282 - Try to find a library and return a pathname. *name* is the library name without
437.1283 - any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
437.1284 - is the form used for the posix linker option :option:`-l`). If no library can
437.1285 - be found, returns ``None``.
437.1286 -
437.1287 -The exact functionality is system dependent.
437.1288 -
437.1289 -On Linux, ``find_library`` tries to run external programs (/sbin/ldconfig, gcc,
437.1290 -and objdump) to find the library file. It returns the filename of the library
437.1291 -file. Here are some examples::
437.1292 -
437.1293 - >>> from ctypes.util import find_library
437.1294 - >>> find_library("m")
437.1295 - 'libm.so.6'
437.1296 - >>> find_library("c")
437.1297 - 'libc.so.6'
437.1298 - >>> find_library("bz2")
437.1299 - 'libbz2.so.1.0'
437.1300 - >>>
437.1301 -
437.1302 -On OS X, ``find_library`` tries several predefined naming schemes and paths to
437.1303 -locate the library, and returns a full pathname if successful::
437.1304 -
437.1305 - >>> from ctypes.util import find_library
437.1306 - >>> find_library("c")
437.1307 - '/usr/lib/libc.dylib'
437.1308 - >>> find_library("m")
437.1309 - '/usr/lib/libm.dylib'
437.1310 - >>> find_library("bz2")
437.1311 - '/usr/lib/libbz2.dylib'
437.1312 - >>> find_library("AGL")
437.1313 - '/System/Library/Frameworks/AGL.framework/AGL'
437.1314 - >>>
437.1315 -
437.1316 -On Windows, ``find_library`` searches along the system search path, and returns
437.1317 -the full pathname, but since there is no predefined naming scheme a call like
437.1318 -``find_library("c")`` will fail and return ``None``.
437.1319 -
437.1320 -If wrapping a shared library with ``ctypes``, it *may* be better to determine
437.1321 -the shared library name at development type, and hardcode that into the wrapper
437.1322 -module instead of using ``find_library`` to locate the library at runtime.
437.1323 -
437.1324 -
437.1325 -.. _ctypes-loading-shared-libraries:
437.1326 -
437.1327 -Loading shared libraries
437.1328 -^^^^^^^^^^^^^^^^^^^^^^^^
437.1329 -
437.1330 -There are several ways to loaded shared libraries into the Python process. One
437.1331 -way is to instantiate one of the following classes:
437.1332 -
437.1333 -
437.1334 -.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
437.1335 -
437.1336 - Instances of this class represent loaded shared libraries. Functions in these
437.1337 - libraries use the standard C calling convention, and are assumed to return
437.1338 - ``int``.
437.1339 -
437.1340 -
437.1341 -.. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
437.1342 -
437.1343 - Windows only: Instances of this class represent loaded shared libraries,
437.1344 - functions in these libraries use the ``stdcall`` calling convention, and are
437.1345 - assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT`
437.1346 - values contain information specifying whether the function call failed or
437.1347 - succeeded, together with additional error code. If the return value signals a
437.1348 - failure, an :class:`WindowsError` is automatically raised.
437.1349 -
437.1350 -
437.1351 -.. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
437.1352 -
437.1353 - Windows only: Instances of this class represent loaded shared libraries,
437.1354 - functions in these libraries use the ``stdcall`` calling convention, and are
437.1355 - assumed to return ``int`` by default.
437.1356 -
437.1357 - On Windows CE only the standard calling convention is used, for convenience the
437.1358 - :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
437.1359 - platform.
437.1360 -
437.1361 -The Python :term:`global interpreter lock` is released before calling any
437.1362 -function exported by these libraries, and reacquired afterwards.
437.1363 -
437.1364 -
437.1365 -.. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
437.1366 -
437.1367 - Instances of this class behave like :class:`CDLL` instances, except that the
437.1368 - Python GIL is *not* released during the function call, and after the function
437.1369 - execution the Python error flag is checked. If the error flag is set, a Python
437.1370 - exception is raised.
437.1371 -
437.1372 - Thus, this is only useful to call Python C api functions directly.
437.1373 -
437.1374 -All these classes can be instantiated by calling them with at least one
437.1375 -argument, the pathname of the shared library. If you have an existing handle to
437.1376 -an already loaded shard library, it can be passed as the ``handle`` named
437.1377 -parameter, otherwise the underlying platforms ``dlopen`` or :meth:`LoadLibrary`
437.1378 -function is used to load the library into the process, and to get a handle to
437.1379 -it.
437.1380 -
437.1381 -The *mode* parameter can be used to specify how the library is loaded. For
437.1382 -details, consult the ``dlopen(3)`` manpage, on Windows, *mode* is ignored.
437.1383 -
437.1384 -The *use_errno* parameter, when set to True, enables a ctypes
437.1385 -mechanism that allows to access the system `errno` error number in a
437.1386 -safe way. `ctypes` maintains a thread-local copy of the systems
437.1387 -`errno` variable; if you call foreign functions created with
437.1388 -`use_errno=True` then the `errno` value before the function call is
437.1389 -swapped with the ctypes private copy, the same happens immediately
437.1390 -after the function call.
437.1391 -
437.1392 -The function `ctypes.get_errno()` returns the value of the ctypes
437.1393 -private copy, and the function `ctypes.set_errno(value)` changes the
437.1394 -ctypes private copy to `value` and returns the former value.
437.1395 -
437.1396 -The *use_last_error* parameter, when set to True, enables the same
437.1397 -mechanism for the Windows error code which is managed by the
437.1398 -:func:`GetLastError` and :func:`SetLastError` Windows API functions;
437.1399 -`ctypes.get_last_error()` and `ctypes.set_last_error(value)` are used
437.1400 -to request and change the ctypes private copy of the windows error
437.1401 -code.
437.1402 -
437.1403 -.. versionadded:: 2.6
437.1404 - The ``use_last_error`` and ``use_errno`` optional parameters
437.1405 - were added.
437.1406 -
437.1407 -.. data:: RTLD_GLOBAL
437.1408 - :noindex:
437.1409 -
437.1410 - Flag to use as *mode* parameter. On platforms where this flag is not available,
437.1411 - it is defined as the integer zero.
437.1412 -
437.1413 -
437.1414 -.. data:: RTLD_LOCAL
437.1415 - :noindex:
437.1416 -
437.1417 - Flag to use as *mode* parameter. On platforms where this is not available, it
437.1418 - is the same as *RTLD_GLOBAL*.
437.1419 -
437.1420 -
437.1421 -.. data:: DEFAULT_MODE
437.1422 - :noindex:
437.1423 -
437.1424 - The default mode which is used to load shared libraries. On OSX 10.3, this is
437.1425 - *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
437.1426 -
437.1427 -Instances of these classes have no public methods, however :meth:`__getattr__`
437.1428 -and :meth:`__getitem__` have special behavior: functions exported by the shared
437.1429 -library can be accessed as attributes of by index. Please note that both
437.1430 -:meth:`__getattr__` and :meth:`__getitem__` cache their result, so calling them
437.1431 -repeatedly returns the same object each time.
437.1432 -
437.1433 -The following public attributes are available, their name starts with an
437.1434 -underscore to not clash with exported function names:
437.1435 -
437.1436 -
437.1437 -.. attribute:: PyDLL._handle
437.1438 -
437.1439 - The system handle used to access the library.
437.1440 -
437.1441 -
437.1442 -.. attribute:: PyDLL._name
437.1443 -
437.1444 - The name of the library passed in the constructor.
437.1445 -
437.1446 -Shared libraries can also be loaded by using one of the prefabricated objects,
437.1447 -which are instances of the :class:`LibraryLoader` class, either by calling the
437.1448 -:meth:`LoadLibrary` method, or by retrieving the library as attribute of the
437.1449 -loader instance.
437.1450 -
437.1451 -
437.1452 -.. class:: LibraryLoader(dlltype)
437.1453 -
437.1454 - Class which loads shared libraries. ``dlltype`` should be one of the
437.1455 - :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
437.1456 -
437.1457 - :meth:`__getattr__` has special behavior: It allows to load a shared library by
437.1458 - accessing it as attribute of a library loader instance. The result is cached,
437.1459 - so repeated attribute accesses return the same library each time.
437.1460 -
437.1461 -
437.1462 - .. method:: LoadLibrary(name)
437.1463 -
437.1464 - Load a shared library into the process and return it. This method always
437.1465 - returns a new instance of the library.
437.1466 -
437.1467 -These prefabricated library loaders are available:
437.1468 -
437.1469 -
437.1470 -.. data:: cdll
437.1471 - :noindex:
437.1472 -
437.1473 - Creates :class:`CDLL` instances.
437.1474 -
437.1475 -
437.1476 -.. data:: windll
437.1477 - :noindex:
437.1478 -
437.1479 - Windows only: Creates :class:`WinDLL` instances.
437.1480 -
437.1481 -
437.1482 -.. data:: oledll
437.1483 - :noindex:
437.1484 -
437.1485 - Windows only: Creates :class:`OleDLL` instances.
437.1486 -
437.1487 -
437.1488 -.. data:: pydll
437.1489 - :noindex:
437.1490 -
437.1491 - Creates :class:`PyDLL` instances.
437.1492 -
437.1493 -For accessing the C Python api directly, a ready-to-use Python shared library
437.1494 -object is available:
437.1495 -
437.1496 -
437.1497 -.. data:: pythonapi
437.1498 - :noindex:
437.1499 -
437.1500 - An instance of :class:`PyDLL` that exposes Python C api functions as attributes.
437.1501 - Note that all these functions are assumed to return C ``int``, which is of
437.1502 - course not always the truth, so you have to assign the correct :attr:`restype`
437.1503 - attribute to use these functions.
437.1504 -
437.1505 -
437.1506 -.. _ctypes-foreign-functions:
437.1507 -
437.1508 -Foreign functions
437.1509 -^^^^^^^^^^^^^^^^^
437.1510 -
437.1511 -As explained in the previous section, foreign functions can be accessed as
437.1512 -attributes of loaded shared libraries. The function objects created in this way
437.1513 -by default accept any number of arguments, accept any ctypes data instances as
437.1514 -arguments, and return the default result type specified by the library loader.
437.1515 -They are instances of a private class:
437.1516 -
437.1517 -
437.1518 -.. class:: _FuncPtr
437.1519 -
437.1520 - Base class for C callable foreign functions.
437.1521 -
437.1522 - Instances of foreign functions are also C compatible data types; they
437.1523 - represent C function pointers.
437.1524 -
437.1525 - This behavior can be customized by assigning to special attributes of the
437.1526 - foreign function object.
437.1527 -
437.1528 -
437.1529 - .. attribute:: restype
437.1530 -
437.1531 - Assign a ctypes type to specify the result type of the foreign function.
437.1532 - Use ``None`` for ``void`` a function not returning anything.
437.1533 -
437.1534 - It is possible to assign a callable Python object that is not a ctypes
437.1535 - type, in this case the function is assumed to return a C ``int``, and the
437.1536 - callable will be called with this integer, allowing to do further
437.1537 - processing or error checking. Using this is deprecated, for more flexible
437.1538 - post processing or error checking use a ctypes data type as
437.1539 - :attr:`restype` and assign a callable to the :attr:`errcheck` attribute.
437.1540 -
437.1541 -
437.1542 - .. attribute:: argtypes
437.1543 -
437.1544 - Assign a tuple of ctypes types to specify the argument types that the
437.1545 - function accepts. Functions using the ``stdcall`` calling convention can
437.1546 - only be called with the same number of arguments as the length of this
437.1547 - tuple; functions using the C calling convention accept additional,
437.1548 - unspecified arguments as well.
437.1549 -
437.1550 - When a foreign function is called, each actual argument is passed to the
437.1551 - :meth:`from_param` class method of the items in the :attr:`argtypes`
437.1552 - tuple, this method allows to adapt the actual argument to an object that
437.1553 - the foreign function accepts. For example, a :class:`c_char_p` item in
437.1554 - the :attr:`argtypes` tuple will convert a unicode string passed as
437.1555 - argument into an byte string using ctypes conversion rules.
437.1556 -
437.1557 - New: It is now possible to put items in argtypes which are not ctypes
437.1558 - types, but each item must have a :meth:`from_param` method which returns a
437.1559 - value usable as argument (integer, string, ctypes instance). This allows
437.1560 - to define adapters that can adapt custom objects as function parameters.
437.1561 -
437.1562 -
437.1563 - .. attribute:: errcheck
437.1564 -
437.1565 - Assign a Python function or another callable to this attribute. The
437.1566 - callable will be called with three or more arguments:
437.1567 -
437.1568 - .. function:: callable(result, func, arguments)
437.1569 - :noindex:
437.1570 -
437.1571 - ``result`` is what the foreign function returns, as specified
437.1572 - by the :attr:`restype` attribute.
437.1573 -
437.1574 - ``func`` is the foreign function object itself, this allows
437.1575 - to reuse the same callable object to check or post process
437.1576 - the results of several functions.
437.1577 -
437.1578 - ``arguments`` is a tuple containing the parameters originally
437.1579 - passed to the function call, this allows to specialize the
437.1580 - behavior on the arguments used.
437.1581 -
437.1582 - The object that this function returns will be returned from the
437.1583 - foreign function call, but it can also check the result value
437.1584 - and raise an exception if the foreign function call failed.
437.1585 -
437.1586 -
437.1587 -.. exception:: ArgumentError()
437.1588 -
437.1589 - This exception is raised when a foreign function call cannot convert one of the
437.1590 - passed arguments.
437.1591 -
437.1592 -
437.1593 -.. _ctypes-function-prototypes:
437.1594 -
437.1595 -Function prototypes
437.1596 -^^^^^^^^^^^^^^^^^^^
437.1597 -
437.1598 -Foreign functions can also be created by instantiating function prototypes.
437.1599 -Function prototypes are similar to function prototypes in C; they describe a
437.1600 -function (return type, argument types, calling convention) without defining an
437.1601 -implementation. The factory functions must be called with the desired result
437.1602 -type and the argument types of the function.
437.1603 -
437.1604 -
437.1605 -.. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
437.1606 -
437.1607 - The returned function prototype creates functions that use the standard C
437.1608 - calling convention. The function will release the GIL during the call.
437.1609 - If `use_errno` is set to True, the ctypes private copy of the system `errno`
437.1610 - variable is exchanged with the real `errno` value bafore and after the call;
437.1611 - `use_last_error` does the same for the Windows error code.
437.1612 -
437.1613 - .. versionchanged:: 2.6
437.1614 - The optional `use_errno` and `use_last_error` parameters were
437.1615 - added.
437.1616 -
437.1617 -
437.1618 -.. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
437.1619 -
437.1620 - Windows only: The returned function prototype creates functions that use the
437.1621 - ``stdcall`` calling convention, except on Windows CE where :func:`WINFUNCTYPE`
437.1622 - is the same as :func:`CFUNCTYPE`. The function will release the GIL during the
437.1623 - call. `use_errno` and `use_last_error` have the same meaning as above.
437.1624 -
437.1625 -
437.1626 -.. function:: PYFUNCTYPE(restype, *argtypes)
437.1627 -
437.1628 - The returned function prototype creates functions that use the Python calling
437.1629 - convention. The function will *not* release the GIL during the call.
437.1630 -
437.1631 -Function prototypes created by these factory functions can be instantiated in
437.1632 -different ways, depending on the type and number of the parameters in the call:
437.1633 -
437.1634 -
437.1635 - .. function:: prototype(address)
437.1636 - :noindex:
437.1637 - :module:
437.1638 -
437.1639 - Returns a foreign function at the specified address which must be an integer.
437.1640 -
437.1641 -
437.1642 - .. function:: prototype(callable)
437.1643 - :noindex:
437.1644 - :module:
437.1645 -
437.1646 - Create a C callable function (a callback function) from a Python ``callable``.
437.1647 -
437.1648 -
437.1649 - .. function:: prototype(func_spec[, paramflags])
437.1650 - :noindex:
437.1651 - :module:
437.1652 -
437.1653 - Returns a foreign function exported by a shared library. ``func_spec`` must be a
437.1654 - 2-tuple ``(name_or_ordinal, library)``. The first item is the name of the
437.1655 - exported function as string, or the ordinal of the exported function as small
437.1656 - integer. The second item is the shared library instance.
437.1657 -
437.1658 -
437.1659 - .. function:: prototype(vtbl_index, name[, paramflags[, iid]])
437.1660 - :noindex:
437.1661 - :module:
437.1662 -
437.1663 - Returns a foreign function that will call a COM method. ``vtbl_index`` is the
437.1664 - index into the virtual function table, a small non-negative integer. *name* is
437.1665 - name of the COM method. *iid* is an optional pointer to the interface identifier
437.1666 - which is used in extended error reporting.
437.1667 -
437.1668 - COM methods use a special calling convention: They require a pointer to the COM
437.1669 - interface as first argument, in addition to those parameters that are specified
437.1670 - in the :attr:`argtypes` tuple.
437.1671 -
437.1672 - The optional *paramflags* parameter creates foreign function wrappers with much
437.1673 - more functionality than the features described above.
437.1674 -
437.1675 - *paramflags* must be a tuple of the same length as :attr:`argtypes`.
437.1676 -
437.1677 - Each item in this tuple contains further information about a parameter, it must
437.1678 - be a tuple containing one, two, or three items.
437.1679 -
437.1680 - The first item is an integer containing a combination of direction
437.1681 - flags for the parameter:
437.1682 -
437.1683 - 1
437.1684 - Specifies an input parameter to the function.
437.1685 -
437.1686 - 2
437.1687 - Output parameter. The foreign function fills in a value.
437.1688 -
437.1689 - 4
437.1690 - Input parameter which defaults to the integer zero.
437.1691 -
437.1692 - The optional second item is the parameter name as string. If this is specified,
437.1693 - the foreign function can be called with named parameters.
437.1694 -
437.1695 - The optional third item is the default value for this parameter.
437.1696 -
437.1697 -This example demonstrates how to wrap the Windows ``MessageBoxA`` function so
437.1698 -that it supports default parameters and named arguments. The C declaration from
437.1699 -the windows header file is this::
437.1700 -
437.1701 - WINUSERAPI int WINAPI
437.1702 - MessageBoxA(
437.1703 - HWND hWnd ,
437.1704 - LPCSTR lpText,
437.1705 - LPCSTR lpCaption,
437.1706 - UINT uType);
437.1707 -
437.1708 -Here is the wrapping with ``ctypes``::
437.1709 -
437.1710 - >>> from ctypes import c_int, WINFUNCTYPE, windll
437.1711 - >>> from ctypes.wintypes import HWND, LPCSTR, UINT
437.1712 - >>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
437.1713 - >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
437.1714 - >>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
437.1715 - >>>
437.1716 -
437.1717 -The MessageBox foreign function can now be called in these ways::
437.1718 -
437.1719 - >>> MessageBox()
437.1720 - >>> MessageBox(text="Spam, spam, spam")
437.1721 - >>> MessageBox(flags=2, text="foo bar")
437.1722 - >>>
437.1723 -
437.1724 -A second example demonstrates output parameters. The win32 ``GetWindowRect``
437.1725 -function retrieves the dimensions of a specified window by copying them into
437.1726 -``RECT`` structure that the caller has to supply. Here is the C declaration::
437.1727 -
437.1728 - WINUSERAPI BOOL WINAPI
437.1729 - GetWindowRect(
437.1730 - HWND hWnd,
437.1731 - LPRECT lpRect);
437.1732 -
437.1733 -Here is the wrapping with ``ctypes``::
437.1734 -
437.1735 - >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
437.1736 - >>> from ctypes.wintypes import BOOL, HWND, RECT
437.1737 - >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
437.1738 - >>> paramflags = (1, "hwnd"), (2, "lprect")
437.1739 - >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
437.1740 - >>>
437.1741 -
437.1742 -Functions with output parameters will automatically return the output parameter
437.1743 -value if there is a single one, or a tuple containing the output parameter
437.1744 -values when there are more than one, so the GetWindowRect function now returns a
437.1745 -RECT instance, when called.
437.1746 -
437.1747 -Output parameters can be combined with the :attr:`errcheck` protocol to do
437.1748 -further output processing and error checking. The win32 ``GetWindowRect`` api
437.1749 -function returns a ``BOOL`` to signal success or failure, so this function could
437.1750 -do the error checking, and raises an exception when the api call failed::
437.1751 -
437.1752 - >>> def errcheck(result, func, args):
437.1753 - ... if not result:
437.1754 - ... raise WinError()
437.1755 - ... return args
437.1756 - ...
437.1757 - >>> GetWindowRect.errcheck = errcheck
437.1758 - >>>
437.1759 -
437.1760 -If the :attr:`errcheck` function returns the argument tuple it receives
437.1761 -unchanged, ``ctypes`` continues the normal processing it does on the output
437.1762 -parameters. If you want to return a tuple of window coordinates instead of a
437.1763 -``RECT`` instance, you can retrieve the fields in the function and return them
437.1764 -instead, the normal processing will no longer take place::
437.1765 -
437.1766 - >>> def errcheck(result, func, args):
437.1767 - ... if not result:
437.1768 - ... raise WinError()
437.1769 - ... rc = args[1]
437.1770 - ... return rc.left, rc.top, rc.bottom, rc.right
437.1771 - ...
437.1772 - >>> GetWindowRect.errcheck = errcheck
437.1773 - >>>
437.1774 -
437.1775 -
437.1776 -.. _ctypes-utility-functions:
437.1777 -
437.1778 -Utility functions
437.1779 -^^^^^^^^^^^^^^^^^
437.1780 -
437.1781 -
437.1782 -.. function:: addressof(obj)
437.1783 -
437.1784 - Returns the address of the memory buffer as integer. ``obj`` must be an
437.1785 - instance of a ctypes type.
437.1786 -
437.1787 -
437.1788 -.. function:: alignment(obj_or_type)
437.1789 -
437.1790 - Returns the alignment requirements of a ctypes type. ``obj_or_type`` must be a
437.1791 - ctypes type or instance.
437.1792 -
437.1793 -
437.1794 -.. function:: byref(obj[, offset])
437.1795 -
437.1796 - Returns a light-weight pointer to ``obj``, which must be an
437.1797 - instance of a ctypes type. ``offset`` defaults to zero, and must be
437.1798 - an integer that will be added to the internal pointer value.
437.1799 -
437.1800 - ``byref(obj, offset)`` corresponds to this C code::
437.1801 -
437.1802 - (((char *)&obj) + offset)
437.1803 -
437.1804 - The returned object can only be used as a foreign function call
437.1805 - parameter. It behaves similar to ``pointer(obj)``, but the
437.1806 - construction is a lot faster.
437.1807 -
437.1808 - .. versionadded:: 2.6
437.1809 - The ``offset`` optional argument was added.
437.1810 -
437.1811 -.. function:: cast(obj, type)
437.1812 -
437.1813 - This function is similar to the cast operator in C. It returns a new instance of
437.1814 - ``type`` which points to the same memory block as ``obj``. ``type`` must be a
437.1815 - pointer type, and ``obj`` must be an object that can be interpreted as a
437.1816 - pointer.
437.1817 -
437.1818 -
437.1819 -.. function:: create_string_buffer(init_or_size[, size])
437.1820 -
437.1821 - This function creates a mutable character buffer. The returned object is a
437.1822 - ctypes array of :class:`c_char`.
437.1823 -
437.1824 - ``init_or_size`` must be an integer which specifies the size of the array, or a
437.1825 - string which will be used to initialize the array items.
437.1826 -
437.1827 - If a string is specified as first argument, the buffer is made one item larger
437.1828 - than the length of the string so that the last element in the array is a NUL
437.1829 - termination character. An integer can be passed as second argument which allows
437.1830 - to specify the size of the array if the length of the string should not be used.
437.1831 -
437.1832 - If the first parameter is a unicode string, it is converted into an 8-bit string
437.1833 - according to ctypes conversion rules.
437.1834 -
437.1835 -
437.1836 -.. function:: create_unicode_buffer(init_or_size[, size])
437.1837 -
437.1838 - This function creates a mutable unicode character buffer. The returned object is
437.1839 - a ctypes array of :class:`c_wchar`.
437.1840 -
437.1841 - ``init_or_size`` must be an integer which specifies the size of the array, or a
437.1842 - unicode string which will be used to initialize the array items.
437.1843 -
437.1844 - If a unicode string is specified as first argument, the buffer is made one item
437.1845 - larger than the length of the string so that the last element in the array is a
437.1846 - NUL termination character. An integer can be passed as second argument which
437.1847 - allows to specify the size of the array if the length of the string should not
437.1848 - be used.
437.1849 -
437.1850 - If the first parameter is a 8-bit string, it is converted into an unicode string
437.1851 - according to ctypes conversion rules.
437.1852 -
437.1853 -
437.1854 -.. function:: DllCanUnloadNow()
437.1855 -
437.1856 - Windows only: This function is a hook which allows to implement in-process COM
437.1857 - servers with ctypes. It is called from the DllCanUnloadNow function that the
437.1858 - _ctypes extension dll exports.
437.1859 -
437.1860 -
437.1861 -.. function:: DllGetClassObject()
437.1862 -
437.1863 - Windows only: This function is a hook which allows to implement in-process COM
437.1864 - servers with ctypes. It is called from the DllGetClassObject function that the
437.1865 - ``_ctypes`` extension dll exports.
437.1866 -
437.1867 -.. function:: find_library(name)
437.1868 - :module: ctypes.util
437.1869 -
437.1870 - Try to find a library and return a pathname. `name` is the library name without
437.1871 - any prefix like `lib`, suffix like ``.so``, ``.dylib`` or version number (this
437.1872 - is the form used for the posix linker option :option:`-l`). If no library can
437.1873 - be found, returns ``None``.
437.1874 -
437.1875 - The exact functionality is system dependent.
437.1876 -
437.1877 - .. versionchanged:: 2.6
437.1878 - Windows only: ``find_library("m")`` or
437.1879 - ``find_library("c")`` return the result of a call to
437.1880 - ``find_msvcrt()``.
437.1881 -
437.1882 -.. function:: find_msvcrt()
437.1883 - :module: ctypes.util
437.1884 -
437.1885 - Windows only: return the filename of the VC runtype library used
437.1886 - by Python, and by the extension modules. If the name of the
437.1887 - library cannot be determined, ``None`` is returned.
437.1888 -
437.1889 - If you need to free memory, for example, allocated by an extension
437.1890 - module with a call to the ``free(void *)``, it is important that you
437.1891 - use the function in the same library that allocated the memory.
437.1892 -
437.1893 - .. versionadded:: 2.6
437.1894 -
437.1895 -.. function:: FormatError([code])
437.1896 -
437.1897 - Windows only: Returns a textual description of the error code. If no error code
437.1898 - is specified, the last error code is used by calling the Windows api function
437.1899 - GetLastError.
437.1900 -
437.1901 -
437.1902 -.. function:: GetLastError()
437.1903 -
437.1904 - Windows only: Returns the last error code set by Windows in the calling thread.
437.1905 - This function calls the Windows `GetLastError()` function directly,
437.1906 - it does not return the ctypes-private copy of the error code.
437.1907 -
437.1908 -.. function:: get_errno()
437.1909 -
437.1910 - Returns the current value of the ctypes-private copy of the system
437.1911 - `errno` variable in the calling thread.
437.1912 -
437.1913 - .. versionadded:: 2.6
437.1914 -
437.1915 -.. function:: get_last_error()
437.1916 -
437.1917 - Windows only: returns the current value of the ctypes-private copy of the system
437.1918 - `LastError` variable in the calling thread.
437.1919 -
437.1920 - .. versionadded:: 2.6
437.1921 -
437.1922 -.. function:: memmove(dst, src, count)
437.1923 -
437.1924 - Same as the standard C memmove library function: copies *count* bytes from
437.1925 - ``src`` to *dst*. *dst* and ``src`` must be integers or ctypes instances that
437.1926 - can be converted to pointers.
437.1927 -
437.1928 -
437.1929 -.. function:: memset(dst, c, count)
437.1930 -
437.1931 - Same as the standard C memset library function: fills the memory block at
437.1932 - address *dst* with *count* bytes of value *c*. *dst* must be an integer
437.1933 - specifying an address, or a ctypes instance.
437.1934 -
437.1935 -
437.1936 -.. function:: POINTER(type)
437.1937 -
437.1938 - This factory function creates and returns a new ctypes pointer type. Pointer
437.1939 - types are cached an reused internally, so calling this function repeatedly is
437.1940 - cheap. type must be a ctypes type.
437.1941 -
437.1942 -
437.1943 -.. function:: pointer(obj)
437.1944 -
437.1945 - This function creates a new pointer instance, pointing to ``obj``. The returned
437.1946 - object is of the type POINTER(type(obj)).
437.1947 -
437.1948 - Note: If you just want to pass a pointer to an object to a foreign function
437.1949 - call, you should use ``byref(obj)`` which is much faster.
437.1950 -
437.1951 -
437.1952 -.. function:: resize(obj, size)
437.1953 -
437.1954 - This function resizes the internal memory buffer of obj, which must be an
437.1955 - instance of a ctypes type. It is not possible to make the buffer smaller than
437.1956 - the native size of the objects type, as given by sizeof(type(obj)), but it is
437.1957 - possible to enlarge the buffer.
437.1958 -
437.1959 -
437.1960 -.. function:: set_conversion_mode(encoding, errors)
437.1961 -
437.1962 - This function sets the rules that ctypes objects use when converting between
437.1963 - 8-bit strings and unicode strings. encoding must be a string specifying an
437.1964 - encoding, like ``'utf-8'`` or ``'mbcs'``, errors must be a string specifying the
437.1965 - error handling on encoding/decoding errors. Examples of possible values are
437.1966 - ``"strict"``, ``"replace"``, or ``"ignore"``.
437.1967 -
437.1968 - ``set_conversion_mode`` returns a 2-tuple containing the previous conversion
437.1969 - rules. On windows, the initial conversion rules are ``('mbcs', 'ignore')``, on
437.1970 - other systems ``('ascii', 'strict')``.
437.1971 -
437.1972 -
437.1973 -.. function:: set_errno(value)
437.1974 -
437.1975 - Set the current value of the ctypes-private copy of the system
437.1976 - `errno` variable in the calling thread to `value` and return the
437.1977 - previous value.
437.1978 -
437.1979 - .. versionadded:: 2.6
437.1980 -
437.1981 -.. function:: set_last_error(value)
437.1982 -
437.1983 - Windows only: set the current value of the ctypes-private copy of
437.1984 - the system `LastError` variable in the calling thread to `value`
437.1985 - and return the previous value.
437.1986 -
437.1987 - .. versionadded:: 2.6
437.1988 -
437.1989 -.. function:: sizeof(obj_or_type)
437.1990 -
437.1991 - Returns the size in bytes of a ctypes type or instance memory buffer. Does the
437.1992 - same as the C ``sizeof()`` function.
437.1993 -
437.1994 -
437.1995 -.. function:: string_at(address[, size])
437.1996 -
437.1997 - This function returns the string starting at memory address address. If size
437.1998 - is specified, it is used as size, otherwise the string is assumed to be
437.1999 - zero-terminated.
437.2000 -
437.2001 -
437.2002 -.. function:: WinError(code=None, descr=None)
437.2003 -
437.2004 - Windows only: this function is probably the worst-named thing in ctypes. It
437.2005 - creates an instance of WindowsError. If *code* is not specified,
437.2006 - ``GetLastError`` is called to determine the error code. If ``descr`` is not
437.2007 - specified, :func:`FormatError` is called to get a textual description of the
437.2008 - error.
437.2009 -
437.2010 -
437.2011 -.. function:: wstring_at(address)
437.2012 -
437.2013 - This function returns the wide character string starting at memory address
437.2014 - ``address`` as unicode string. If ``size`` is specified, it is used as the
437.2015 - number of characters of the string, otherwise the string is assumed to be
437.2016 - zero-terminated.
437.2017 -
437.2018 -
437.2019 -.. _ctypes-data-types:
437.2020 -
437.2021 -Data types
437.2022 -^^^^^^^^^^
437.2023 -
437.2024 -
437.2025 -.. class:: _CData
437.2026 -
437.2027 - This non-public class is the common base class of all ctypes data types. Among
437.2028 - other things, all ctypes type instances contain a memory block that hold C
437.2029 - compatible data; the address of the memory block is returned by the
437.2030 - ``addressof()`` helper function. Another instance variable is exposed as
437.2031 - :attr:`_objects`; this contains other Python objects that need to be kept alive
437.2032 - in case the memory block contains pointers.
437.2033 -
437.2034 - Common methods of ctypes data types, these are all class methods (to be
437.2035 - exact, they are methods of the :term:`metaclass`):
437.2036 -
437.2037 -
437.2038 - .. method:: _CData.from_buffer(source[, offset])
437.2039 -
437.2040 - This method returns a ctypes instance that shares the buffer of
437.2041 - the ``source`` object. The ``source`` object must support the
437.2042 - writeable buffer interface. The optional ``offset`` parameter
437.2043 - specifies an offset into the source buffer in bytes; the default
437.2044 - is zero. If the source buffer is not large enough a ValueError
437.2045 - is raised.
437.2046 -
437.2047 - .. versionadded:: 2.6
437.2048 -
437.2049 - .. method:: _CData.from_buffer_copy(source[, offset])
437.2050 -
437.2051 - This method creates a ctypes instance, copying the buffer from
437.2052 - the source object buffer which must be readable. The optional
437.2053 - ``offset`` parameter specifies an offset into the source buffer
437.2054 - in bytes; the default is zero. If the source buffer is not
437.2055 - large enough a ValueError is raised.
437.2056 -
437.2057 - .. versionadded:: 2.6
437.2058 -
437.2059 -
437.2060 - .. method:: from_address(address)
437.2061 -
437.2062 - This method returns a ctypes type instance using the memory specified by
437.2063 - address which must be an integer.
437.2064 -
437.2065 -
437.2066 - .. method:: from_param(obj)
437.2067 -
437.2068 - This method adapts *obj* to a ctypes type. It is called with the actual
437.2069 - object used in a foreign function call when the type is present in the
437.2070 - foreign function's :attr:`argtypes` tuple; it must return an object that
437.2071 - can be used as a function call parameter.
437.2072 -
437.2073 - All ctypes data types have a default implementation of this classmethod
437.2074 - that normally returns ``obj`` if that is an instance of the type. Some
437.2075 - types accept other objects as well.
437.2076 -
437.2077 -
437.2078 - .. method:: in_dll(library, name)
437.2079 -
437.2080 - This method returns a ctypes type instance exported by a shared
437.2081 - library. *name* is the name of the symbol that exports the data, *library*
437.2082 - is the loaded shared library.
437.2083 -
437.2084 -
437.2085 - Common instance variables of ctypes data types:
437.2086 -
437.2087 -
437.2088 - .. attribute:: _b_base_
437.2089 -
437.2090 - Sometimes ctypes data instances do not own the memory block they contain,
437.2091 - instead they share part of the memory block of a base object. The
437.2092 - :attr:`_b_base_` read-only member is the root ctypes object that owns the
437.2093 - memory block.
437.2094 -
437.2095 -
437.2096 - .. attribute:: _b_needsfree_
437.2097 -
437.2098 - This read-only variable is true when the ctypes data instance has
437.2099 - allocated the memory block itself, false otherwise.
437.2100 -
437.2101 -
437.2102 - .. attribute:: _objects
437.2103 -
437.2104 - This member is either ``None`` or a dictionary containing Python objects
437.2105 - that need to be kept alive so that the memory block contents is kept
437.2106 - valid. This object is only exposed for debugging; never modify the
437.2107 - contents of this dictionary.
437.2108 -
437.2109 -
437.2110 -.. _ctypes-fundamental-data-types-2:
437.2111 -
437.2112 -Fundamental data types
437.2113 -^^^^^^^^^^^^^^^^^^^^^^
437.2114 -
437.2115 -
437.2116 -.. class:: _SimpleCData
437.2117 -
437.2118 - This non-public class is the base class of all fundamental ctypes data types. It
437.2119 - is mentioned here because it contains the common attributes of the fundamental
437.2120 - ctypes data types. ``_SimpleCData`` is a subclass of ``_CData``, so it inherits
437.2121 - their methods and attributes.
437.2122 -
437.2123 - .. versionchanged:: 2.6
437.2124 - ctypes data types that are not and do not contain pointers can
437.2125 - now be pickled.
437.2126 -
437.2127 - Instances have a single attribute:
437.2128 -
437.2129 -
437.2130 - .. attribute:: value
437.2131 -
437.2132 - This attribute contains the actual value of the instance. For integer and
437.2133 - pointer types, it is an integer, for character types, it is a single
437.2134 - character string, for character pointer types it is a Python string or
437.2135 - unicode string.
437.2136 -
437.2137 - When the ``value`` attribute is retrieved from a ctypes instance, usually
437.2138 - a new object is returned each time. ``ctypes`` does *not* implement
437.2139 - original object return, always a new object is constructed. The same is
437.2140 - true for all other ctypes object instances.
437.2141 -
437.2142 -Fundamental data types, when returned as foreign function call results, or, for
437.2143 -example, by retrieving structure field members or array items, are transparently
437.2144 -converted to native Python types. In other words, if a foreign function has a
437.2145 -:attr:`restype` of :class:`c_char_p`, you will always receive a Python string,
437.2146 -*not* a :class:`c_char_p` instance.
437.2147 -
437.2148 -Subclasses of fundamental data types do *not* inherit this behavior. So, if a
437.2149 -foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will
437.2150 -receive an instance of this subclass from the function call. Of course, you can
437.2151 -get the value of the pointer by accessing the ``value`` attribute.
437.2152 -
437.2153 -These are the fundamental ctypes data types:
437.2154 -
437.2155 -
437.2156 -.. class:: c_byte
437.2157 -
437.2158 - Represents the C signed char datatype, and interprets the value as small
437.2159 - integer. The constructor accepts an optional integer initializer; no overflow
437.2160 - checking is done.
437.2161 -
437.2162 -
437.2163 -.. class:: c_char
437.2164 -
437.2165 - Represents the C char datatype, and interprets the value as a single character.
437.2166 - The constructor accepts an optional string initializer, the length of the string
437.2167 - must be exactly one character.
437.2168 -
437.2169 -
437.2170 -.. class:: c_char_p
437.2171 -
437.2172 - Represents the C char \* datatype, which must be a pointer to a zero-terminated
437.2173 - string. The constructor accepts an integer address, or a string.
437.2174 -
437.2175 -
437.2176 -.. class:: c_double
437.2177 -
437.2178 - Represents the C double datatype. The constructor accepts an optional float
437.2179 - initializer.
437.2180 -
437.2181 -
437.2182 -.. class:: c_longdouble
437.2183 -
437.2184 - Represents the C long double datatype. The constructor accepts an
437.2185 - optional float initializer. On platforms where ``sizeof(long
437.2186 - double) == sizeof(double)`` it is an alias to :class:`c_double`.
437.2187 -
437.2188 - .. versionadded:: 2.6
437.2189 -
437.2190 -.. class:: c_float
437.2191 -
437.2192 - Represents the C float datatype. The constructor accepts an optional float
437.2193 - initializer.
437.2194 -
437.2195 -
437.2196 -.. class:: c_int
437.2197 -
437.2198 - Represents the C signed int datatype. The constructor accepts an optional
437.2199 - integer initializer; no overflow checking is done. On platforms where
437.2200 - ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`.
437.2201 -
437.2202 -
437.2203 -.. class:: c_int8
437.2204 -
437.2205 - Represents the C 8-bit ``signed int`` datatype. Usually an alias for
437.2206 - :class:`c_byte`.
437.2207 -
437.2208 -
437.2209 -.. class:: c_int16
437.2210 -
437.2211 - Represents the C 16-bit signed int datatype. Usually an alias for
437.2212 - :class:`c_short`.
437.2213 -
437.2214 -
437.2215 -.. class:: c_int32
437.2216 -
437.2217 - Represents the C 32-bit signed int datatype. Usually an alias for
437.2218 - :class:`c_int`.
437.2219 -
437.2220 -
437.2221 -.. class:: c_int64
437.2222 -
437.2223 - Represents the C 64-bit ``signed int`` datatype. Usually an alias for
437.2224 - :class:`c_longlong`.
437.2225 -
437.2226 -
437.2227 -.. class:: c_long
437.2228 -
437.2229 - Represents the C ``signed long`` datatype. The constructor accepts an optional
437.2230 - integer initializer; no overflow checking is done.
437.2231 -
437.2232 -
437.2233 -.. class:: c_longlong
437.2234 -
437.2235 - Represents the C ``signed long long`` datatype. The constructor accepts an
437.2236 - optional integer initializer; no overflow checking is done.
437.2237 -
437.2238 -
437.2239 -.. class:: c_short
437.2240 -
437.2241 - Represents the C ``signed short`` datatype. The constructor accepts an optional
437.2242 - integer initializer; no overflow checking is done.
437.2243 -
437.2244 -
437.2245 -.. class:: c_size_t
437.2246 -
437.2247 - Represents the C ``size_t`` datatype.
437.2248 -
437.2249 -
437.2250 -.. class:: c_ubyte
437.2251 -
437.2252 - Represents the C ``unsigned char`` datatype, it interprets the value as small
437.2253 - integer. The constructor accepts an optional integer initializer; no overflow
437.2254 - checking is done.
437.2255 -
437.2256 -
437.2257 -.. class:: c_uint
437.2258 -
437.2259 - Represents the C ``unsigned int`` datatype. The constructor accepts an optional
437.2260 - integer initializer; no overflow checking is done. On platforms where
437.2261 - ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`.
437.2262 -
437.2263 -
437.2264 -.. class:: c_uint8
437.2265 -
437.2266 - Represents the C 8-bit unsigned int datatype. Usually an alias for
437.2267 - :class:`c_ubyte`.
437.2268 -
437.2269 -
437.2270 -.. class:: c_uint16
437.2271 -
437.2272 - Represents the C 16-bit unsigned int datatype. Usually an alias for
437.2273 - :class:`c_ushort`.
437.2274 -
437.2275 -
437.2276 -.. class:: c_uint32
437.2277 -
437.2278 - Represents the C 32-bit unsigned int datatype. Usually an alias for
437.2279 - :class:`c_uint`.
437.2280 -
437.2281 -
437.2282 -.. class:: c_uint64
437.2283 -
437.2284 - Represents the C 64-bit unsigned int datatype. Usually an alias for
437.2285 - :class:`c_ulonglong`.
437.2286 -
437.2287 -
437.2288 -.. class:: c_ulong
437.2289 -
437.2290 - Represents the C ``unsigned long`` datatype. The constructor accepts an optional
437.2291 - integer initializer; no overflow checking is done.
437.2292 -
437.2293 -
437.2294 -.. class:: c_ulonglong
437.2295 -
437.2296 - Represents the C ``unsigned long long`` datatype. The constructor accepts an
437.2297 - optional integer initializer; no overflow checking is done.
437.2298 -
437.2299 -
437.2300 -.. class:: c_ushort
437.2301 -
437.2302 - Represents the C ``unsigned short`` datatype. The constructor accepts an
437.2303 - optional integer initializer; no overflow checking is done.
437.2304 -
437.2305 -
437.2306 -.. class:: c_void_p
437.2307 -
437.2308 - Represents the C ``void *`` type. The value is represented as integer. The
437.2309 - constructor accepts an optional integer initializer.
437.2310 -
437.2311 -
437.2312 -.. class:: c_wchar
437.2313 -
437.2314 - Represents the C ``wchar_t`` datatype, and interprets the value as a single
437.2315 - character unicode string. The constructor accepts an optional string
437.2316 - initializer, the length of the string must be exactly one character.
437.2317 -
437.2318 -
437.2319 -.. class:: c_wchar_p
437.2320 -
437.2321 - Represents the C ``wchar_t *`` datatype, which must be a pointer to a
437.2322 - zero-terminated wide character string. The constructor accepts an integer
437.2323 - address, or a string.
437.2324 -
437.2325 -
437.2326 -.. class:: c_bool
437.2327 -
437.2328 - Represent the C ``bool`` datatype (more accurately, _Bool from C99). Its value
437.2329 - can be True or False, and the constructor accepts any object that has a truth
437.2330 - value.
437.2331 -
437.2332 - .. versionadded:: 2.6
437.2333 -
437.2334 -
437.2335 -.. class:: HRESULT
437.2336 -
437.2337 - Windows only: Represents a :class:`HRESULT` value, which contains success or
437.2338 - error information for a function or method call.
437.2339 -
437.2340 -
437.2341 -.. class:: py_object
437.2342 -
437.2343 - Represents the C ``PyObject *`` datatype. Calling this without an argument
437.2344 - creates a ``NULL`` ``PyObject *`` pointer.
437.2345 -
437.2346 -The ``ctypes.wintypes`` module provides quite some other Windows specific data
437.2347 -types, for example ``HWND``, ``WPARAM``, or ``DWORD``. Some useful structures
437.2348 -like ``MSG`` or ``RECT`` are also defined.
437.2349 -
437.2350 -
437.2351 -.. _ctypes-structured-data-types:
437.2352 -
437.2353 -Structured data types
437.2354 -^^^^^^^^^^^^^^^^^^^^^
437.2355 -
437.2356 -
437.2357 -.. class:: Union(*args, **kw)
437.2358 -
437.2359 - Abstract base class for unions in native byte order.
437.2360 -
437.2361 -
437.2362 -.. class:: BigEndianStructure(*args, **kw)
437.2363 -
437.2364 - Abstract base class for structures in *big endian* byte order.
437.2365 -
437.2366 -
437.2367 -.. class:: LittleEndianStructure(*args, **kw)
437.2368 -
437.2369 - Abstract base class for structures in *little endian* byte order.
437.2370 -
437.2371 -Structures with non-native byte order cannot contain pointer type fields, or any
437.2372 -other data types containing pointer type fields.
437.2373 -
437.2374 -
437.2375 -.. class:: Structure(*args, **kw)
437.2376 -
437.2377 - Abstract base class for structures in *native* byte order.
437.2378 -
437.2379 - Concrete structure and union types must be created by subclassing one of these
437.2380 - types, and at least define a :attr:`_fields_` class variable. ``ctypes`` will
437.2381 - create :term:`descriptor`\s which allow reading and writing the fields by direct
437.2382 - attribute accesses. These are the
437.2383 -
437.2384 -
437.2385 - .. attribute:: _fields_
437.2386 -
437.2387 - A sequence defining the structure fields. The items must be 2-tuples or
437.2388 - 3-tuples. The first item is the name of the field, the second item
437.2389 - specifies the type of the field; it can be any ctypes data type.
437.2390 -
437.2391 - For integer type fields like :class:`c_int`, a third optional item can be
437.2392 - given. It must be a small positive integer defining the bit width of the
437.2393 - field.
437.2394 -
437.2395 - Field names must be unique within one structure or union. This is not
437.2396 - checked, only one field can be accessed when names are repeated.
437.2397 -
437.2398 - It is possible to define the :attr:`_fields_` class variable *after* the
437.2399 - class statement that defines the Structure subclass, this allows to create
437.2400 - data types that directly or indirectly reference themselves::
437.2401 -
437.2402 - class List(Structure):
437.2403 - pass
437.2404 - List._fields_ = [("pnext", POINTER(List)),
437.2405 - ...
437.2406 - ]
437.2407 -
437.2408 - The :attr:`_fields_` class variable must, however, be defined before the
437.2409 - type is first used (an instance is created, ``sizeof()`` is called on it,
437.2410 - and so on). Later assignments to the :attr:`_fields_` class variable will
437.2411 - raise an AttributeError.
437.2412 -
437.2413 - Structure and union subclass constructors accept both positional and named
437.2414 - arguments. Positional arguments are used to initialize the fields in the
437.2415 - same order as they appear in the :attr:`_fields_` definition, named
437.2416 - arguments are used to initialize the fields with the corresponding name.
437.2417 -
437.2418 - It is possible to defined sub-subclasses of structure types, they inherit
437.2419 - the fields of the base class plus the :attr:`_fields_` defined in the
437.2420 - sub-subclass, if any.
437.2421 -
437.2422 -
437.2423 - .. attribute:: _pack_
437.2424 -
437.2425 - An optional small integer that allows to override the alignment of
437.2426 - structure fields in the instance. :attr:`_pack_` must already be defined
437.2427 - when :attr:`_fields_` is assigned, otherwise it will have no effect.
437.2428 -
437.2429 -
437.2430 - .. attribute:: _anonymous_
437.2431 -
437.2432 - An optional sequence that lists the names of unnamed (anonymous) fields.
437.2433 - ``_anonymous_`` must be already defined when :attr:`_fields_` is assigned,
437.2434 - otherwise it will have no effect.
437.2435 -
437.2436 - The fields listed in this variable must be structure or union type fields.
437.2437 - ``ctypes`` will create descriptors in the structure type that allows to
437.2438 - access the nested fields directly, without the need to create the
437.2439 - structure or union field.
437.2440 -
437.2441 - Here is an example type (Windows)::
437.2442 -
437.2443 - class _U(Union):
437.2444 - _fields_ = [("lptdesc", POINTER(TYPEDESC)),
437.2445 - ("lpadesc", POINTER(ARRAYDESC)),
437.2446 - ("hreftype", HREFTYPE)]
437.2447 -
437.2448 - class TYPEDESC(Structure):
437.2449 - _fields_ = [("u", _U),
437.2450 - ("vt", VARTYPE)]
437.2451 -
437.2452 - _anonymous_ = ("u",)
437.2453 -
437.2454 - The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
437.2455 - specifies which one of the union fields is valid. Since the ``u`` field
437.2456 - is defined as anonymous field, it is now possible to access the members
437.2457 - directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
437.2458 - are equivalent, but the former is faster since it does not need to create
437.2459 - a temporary union instance::
437.2460 -
437.2461 - td = TYPEDESC()
437.2462 - td.vt = VT_PTR
437.2463 - td.lptdesc = POINTER(some_type)
437.2464 - td.u.lptdesc = POINTER(some_type)
437.2465 -
437.2466 -It is possible to defined sub-subclasses of structures, they inherit the fields
437.2467 -of the base class. If the subclass definition has a separate :attr:`_fields_`
437.2468 -variable, the fields specified in this are appended to the fields of the base
437.2469 -class.
437.2470 -
437.2471 -Structure and union constructors accept both positional and keyword arguments.
437.2472 -Positional arguments are used to initialize member fields in the same order as
437.2473 -they are appear in :attr:`_fields_`. Keyword arguments in the constructor are
437.2474 -interpreted as attribute assignments, so they will initialize :attr:`_fields_`
437.2475 -with the same name, or create new attributes for names not present in
437.2476 -:attr:`_fields_`.
437.2477 -
437.2478 -
437.2479 -.. _ctypes-arrays-pointers:
437.2480 -
437.2481 -Arrays and pointers
437.2482 -^^^^^^^^^^^^^^^^^^^
437.2483 -
437.2484 -Not yet written - please see the sections :ref:`ctypes-pointers` and
437.2485 -section :ref:`ctypes-arrays` in the tutorial.
437.2486 -
438.1 --- a/python.editor/test/unit/data/testfiles/rst/ctypes.rst.indexed Sun Jan 04 13:11:53 2015 -0600
438.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
438.3 @@ -1,553 +0,0 @@
438.4 -
438.5 -
438.6 -Document 0
438.7 -Searchable Keys:
438.8 - class : ArgumentError
438.9 - class-ig : argumenterror
438.10 - extends : Exception
438.11 - in : ctypes
438.12 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
438.13 -
438.14 -Not Searchable Keys:
438.15 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.16 -
438.17 -
438.18 -Document 1
438.19 -Searchable Keys:
438.20 - class : BigEndianStructure
438.21 - class-ig : bigendianstructure
438.22 - in : ctypes
438.23 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;*args,**kw;
438.24 -
438.25 -Not Searchable Keys:
438.26 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.27 -
438.28 -
438.29 -Document 2
438.30 -Searchable Keys:
438.31 - class : CDLL
438.32 - class-ig : cdll
438.33 - in : ctypes
438.34 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;name,mode,handle,use_errno,use_last_error;
438.35 -
438.36 -Not Searchable Keys:
438.37 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.38 -
438.39 -
438.40 -Document 3
438.41 -Searchable Keys:
438.42 - class : HRESULT
438.43 - class-ig : hresult
438.44 - in : ctypes
438.45 -
438.46 -Not Searchable Keys:
438.47 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.48 -
438.49 -
438.50 -Document 4
438.51 -Searchable Keys:
438.52 - class : LibraryLoader
438.53 - class-ig : libraryloader
438.54 - in : ctypes
438.55 - member : LoadLibrary;F;|DOCUMENTED|DOC_ONLY|;name;
438.56 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;dlltype;
438.57 -
438.58 -Not Searchable Keys:
438.59 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.60 -
438.61 -
438.62 -Document 5
438.63 -Searchable Keys:
438.64 - class : LittleEndianStructure
438.65 - class-ig : littleendianstructure
438.66 - in : ctypes
438.67 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;*args,**kw;
438.68 -
438.69 -Not Searchable Keys:
438.70 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.71 -
438.72 -
438.73 -Document 6
438.74 -Searchable Keys:
438.75 - class : OleDLL
438.76 - class-ig : oledll
438.77 - in : ctypes
438.78 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;name,mode,handle,use_errno,use_last_error;
438.79 -
438.80 -Not Searchable Keys:
438.81 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.82 -
438.83 -
438.84 -Document 7
438.85 -Searchable Keys:
438.86 - class : PyDLL
438.87 - class-ig : pydll
438.88 - in : ctypes
438.89 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;name,mode,handle;
438.90 - member : _handle;A;|DOCUMENTED|PRIVATE|DOC_ONLY|;
438.91 - member : _name;A;|DOCUMENTED|PRIVATE|DOC_ONLY|;
438.92 -
438.93 -Not Searchable Keys:
438.94 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.95 -
438.96 -
438.97 -Document 8
438.98 -Searchable Keys:
438.99 - class : Structure
438.100 - class-ig : structure
438.101 - in : ctypes
438.102 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;*args,**kw;
438.103 - member : _anonymous_;A;|DOCUMENTED|DOC_ONLY|;
438.104 - member : _fields_;A;|DOCUMENTED|DOC_ONLY|;
438.105 - member : _pack_;A;|DOCUMENTED|DOC_ONLY|;
438.106 -
438.107 -Not Searchable Keys:
438.108 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.109 -
438.110 -
438.111 -Document 9
438.112 -Searchable Keys:
438.113 - class : Union
438.114 - class-ig : union
438.115 - in : ctypes
438.116 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;*args,**kw;
438.117 -
438.118 -Not Searchable Keys:
438.119 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.120 -
438.121 -
438.122 -Document 10
438.123 -Searchable Keys:
438.124 - class : WinDLL
438.125 - class-ig : windll
438.126 - in : ctypes
438.127 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;name,mode,handle,use_errno,use_last_error;
438.128 -
438.129 -Not Searchable Keys:
438.130 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.131 -
438.132 -
438.133 -Document 11
438.134 -Searchable Keys:
438.135 - class : _CData
438.136 - class-ig : _cdata
438.137 - in : ctypes
438.138 - member : _b_base_;A;|DOCUMENTED|DOC_ONLY|;
438.139 - member : _b_needsfree_;A;|DOCUMENTED|DOC_ONLY|;
438.140 - member : _objects;A;|DOCUMENTED|PRIVATE|DOC_ONLY|;
438.141 - member : from_address;F;|DOCUMENTED|DOC_ONLY|;address;
438.142 - member : from_buffer;F;|DOCUMENTED|DOC_ONLY|;source,offset;
438.143 - member : from_buffer_copy;F;|DOCUMENTED|DOC_ONLY|;source,offset;
438.144 - member : from_param;F;|DOCUMENTED|DOC_ONLY|;obj;
438.145 - member : in_dll;F;|DOCUMENTED|DOC_ONLY|;library,name;
438.146 -
438.147 -Not Searchable Keys:
438.148 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.149 -
438.150 -
438.151 -Document 12
438.152 -Searchable Keys:
438.153 - class : _FuncPtr
438.154 - class-ig : _funcptr
438.155 - in : ctypes
438.156 - member : argtypes;A;|DOCUMENTED|DOC_ONLY|;
438.157 - member : errcheck;A;|DOCUMENTED|DOC_ONLY|;
438.158 - member : restype;A;|DOCUMENTED|DOC_ONLY|;
438.159 -
438.160 -Not Searchable Keys:
438.161 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.162 -
438.163 -
438.164 -Document 13
438.165 -Searchable Keys:
438.166 - class : _SimpleCData
438.167 - class-ig : _simplecdata
438.168 - in : ctypes
438.169 - member : value;A;|DOCUMENTED|DOC_ONLY|;
438.170 -
438.171 -Not Searchable Keys:
438.172 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.173 -
438.174 -
438.175 -Document 14
438.176 -Searchable Keys:
438.177 - class : c_bool
438.178 - class-ig : c_bool
438.179 - in : ctypes
438.180 -
438.181 -Not Searchable Keys:
438.182 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.183 -
438.184 -
438.185 -Document 15
438.186 -Searchable Keys:
438.187 - class : c_byte
438.188 - class-ig : c_byte
438.189 - in : ctypes
438.190 -
438.191 -Not Searchable Keys:
438.192 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.193 -
438.194 -
438.195 -Document 16
438.196 -Searchable Keys:
438.197 - class : c_char
438.198 - class-ig : c_char
438.199 - in : ctypes
438.200 -
438.201 -Not Searchable Keys:
438.202 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.203 -
438.204 -
438.205 -Document 17
438.206 -Searchable Keys:
438.207 - class : c_char_p
438.208 - class-ig : c_char_p
438.209 - in : ctypes
438.210 -
438.211 -Not Searchable Keys:
438.212 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.213 -
438.214 -
438.215 -Document 18
438.216 -Searchable Keys:
438.217 - class : c_double
438.218 - class-ig : c_double
438.219 - in : ctypes
438.220 -
438.221 -Not Searchable Keys:
438.222 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.223 -
438.224 -
438.225 -Document 19
438.226 -Searchable Keys:
438.227 - class : c_float
438.228 - class-ig : c_float
438.229 - in : ctypes
438.230 -
438.231 -Not Searchable Keys:
438.232 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.233 -
438.234 -
438.235 -Document 20
438.236 -Searchable Keys:
438.237 - class : c_int
438.238 - class-ig : c_int
438.239 - in : ctypes
438.240 -
438.241 -Not Searchable Keys:
438.242 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.243 -
438.244 -
438.245 -Document 21
438.246 -Searchable Keys:
438.247 - class : c_int16
438.248 - class-ig : c_int16
438.249 - in : ctypes
438.250 -
438.251 -Not Searchable Keys:
438.252 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.253 -
438.254 -
438.255 -Document 22
438.256 -Searchable Keys:
438.257 - class : c_int32
438.258 - class-ig : c_int32
438.259 - in : ctypes
438.260 -
438.261 -Not Searchable Keys:
438.262 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.263 -
438.264 -
438.265 -Document 23
438.266 -Searchable Keys:
438.267 - class : c_int64
438.268 - class-ig : c_int64
438.269 - in : ctypes
438.270 -
438.271 -Not Searchable Keys:
438.272 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.273 -
438.274 -
438.275 -Document 24
438.276 -Searchable Keys:
438.277 - class : c_int8
438.278 - class-ig : c_int8
438.279 - in : ctypes
438.280 -
438.281 -Not Searchable Keys:
438.282 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.283 -
438.284 -
438.285 -Document 25
438.286 -Searchable Keys:
438.287 - class : c_long
438.288 - class-ig : c_long
438.289 - in : ctypes
438.290 -
438.291 -Not Searchable Keys:
438.292 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.293 -
438.294 -
438.295 -Document 26
438.296 -Searchable Keys:
438.297 - class : c_longdouble
438.298 - class-ig : c_longdouble
438.299 - in : ctypes
438.300 -
438.301 -Not Searchable Keys:
438.302 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.303 -
438.304 -
438.305 -Document 27
438.306 -Searchable Keys:
438.307 - class : c_longlong
438.308 - class-ig : c_longlong
438.309 - in : ctypes
438.310 -
438.311 -Not Searchable Keys:
438.312 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.313 -
438.314 -
438.315 -Document 28
438.316 -Searchable Keys:
438.317 - class : c_short
438.318 - class-ig : c_short
438.319 - in : ctypes
438.320 -
438.321 -Not Searchable Keys:
438.322 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.323 -
438.324 -
438.325 -Document 29
438.326 -Searchable Keys:
438.327 - class : c_size_t
438.328 - class-ig : c_size_t
438.329 - in : ctypes
438.330 -
438.331 -Not Searchable Keys:
438.332 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.333 -
438.334 -
438.335 -Document 30
438.336 -Searchable Keys:
438.337 - class : c_ubyte
438.338 - class-ig : c_ubyte
438.339 - in : ctypes
438.340 -
438.341 -Not Searchable Keys:
438.342 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.343 -
438.344 -
438.345 -Document 31
438.346 -Searchable Keys:
438.347 - class : c_uint
438.348 - class-ig : c_uint
438.349 - in : ctypes
438.350 -
438.351 -Not Searchable Keys:
438.352 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.353 -
438.354 -
438.355 -Document 32
438.356 -Searchable Keys:
438.357 - class : c_uint16
438.358 - class-ig : c_uint16
438.359 - in : ctypes
438.360 -
438.361 -Not Searchable Keys:
438.362 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.363 -
438.364 -
438.365 -Document 33
438.366 -Searchable Keys:
438.367 - class : c_uint32
438.368 - class-ig : c_uint32
438.369 - in : ctypes
438.370 -
438.371 -Not Searchable Keys:
438.372 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.373 -
438.374 -
438.375 -Document 34
438.376 -Searchable Keys:
438.377 - class : c_uint64
438.378 - class-ig : c_uint64
438.379 - in : ctypes
438.380 -
438.381 -Not Searchable Keys:
438.382 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.383 -
438.384 -
438.385 -Document 35
438.386 -Searchable Keys:
438.387 - class : c_uint8
438.388 - class-ig : c_uint8
438.389 - in : ctypes
438.390 -
438.391 -Not Searchable Keys:
438.392 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.393 -
438.394 -
438.395 -Document 36
438.396 -Searchable Keys:
438.397 - class : c_ulong
438.398 - class-ig : c_ulong
438.399 - in : ctypes
438.400 -
438.401 -Not Searchable Keys:
438.402 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.403 -
438.404 -
438.405 -Document 37
438.406 -Searchable Keys:
438.407 - class : c_ulonglong
438.408 - class-ig : c_ulonglong
438.409 - in : ctypes
438.410 -
438.411 -Not Searchable Keys:
438.412 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.413 -
438.414 -
438.415 -Document 38
438.416 -Searchable Keys:
438.417 - class : c_ushort
438.418 - class-ig : c_ushort
438.419 - in : ctypes
438.420 -
438.421 -Not Searchable Keys:
438.422 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.423 -
438.424 -
438.425 -Document 39
438.426 -Searchable Keys:
438.427 - class : c_void_p
438.428 - class-ig : c_void_p
438.429 - in : ctypes
438.430 -
438.431 -Not Searchable Keys:
438.432 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.433 -
438.434 -
438.435 -Document 40
438.436 -Searchable Keys:
438.437 - class : c_wchar
438.438 - class-ig : c_wchar
438.439 - in : ctypes
438.440 -
438.441 -Not Searchable Keys:
438.442 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.443 -
438.444 -
438.445 -Document 41
438.446 -Searchable Keys:
438.447 - class : c_wchar_p
438.448 - class-ig : c_wchar_p
438.449 - in : ctypes
438.450 -
438.451 -Not Searchable Keys:
438.452 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.453 -
438.454 -
438.455 -Document 42
438.456 -Searchable Keys:
438.457 - class : py_object
438.458 - class-ig : py_object
438.459 - in : ctypes
438.460 -
438.461 -Not Searchable Keys:
438.462 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
438.463 -
438.464 -
438.465 -Document 43
438.466 -Searchable Keys:
438.467 - item : ArgumentError;C;|DOCUMENTED|DOC_ONLY|;
438.468 - item : BigEndianStructure;C;|DOCUMENTED|DOC_ONLY|;
438.469 - item : CDLL;C;|DOCUMENTED|DOC_ONLY|;
438.470 - item : CFUNCTYPE;F;|DOCUMENTED|DOC_ONLY|;restype,*argtypes,use_errno,use_last_error;
438.471 - item : DEFAULT_MODE;D;|DOCUMENTED|DOC_ONLY|;
438.472 - item : DllCanUnloadNow;F;|DOCUMENTED|DOC_ONLY|;;
438.473 - item : DllGetClassObject;F;|DOCUMENTED|DOC_ONLY|;;
438.474 - item : FormatError;F;|DOCUMENTED|DOC_ONLY|;code;
438.475 - item : GetLastError;F;|DOCUMENTED|DOC_ONLY|;;
438.476 - item : HRESULT;C;|DOCUMENTED|DOC_ONLY|;
438.477 - item : LibraryLoader;C;|DOCUMENTED|DOC_ONLY|;
438.478 - item : LittleEndianStructure;C;|DOCUMENTED|DOC_ONLY|;
438.479 - item : OleDLL;C;|DOCUMENTED|DOC_ONLY|;
438.480 - item : POINTER;F;|DOCUMENTED|DOC_ONLY|;type;
438.481 - item : PYFUNCTYPE;F;|DOCUMENTED|DOC_ONLY|;restype,*argtypes;
438.482 - item : PyDLL;C;|DOCUMENTED|DOC_ONLY|;
438.483 - item : RTLD_GLOBAL;D;|DOCUMENTED|DOC_ONLY|;
438.484 - item : RTLD_LOCAL;D;|DOCUMENTED|DOC_ONLY|;
438.485 - item : Structure;C;|DOCUMENTED|DOC_ONLY|;
438.486 - item : Union;C;|DOCUMENTED|DOC_ONLY|;
438.487 - item : WINFUNCTYPE;F;|DOCUMENTED|DOC_ONLY|;restype,*argtypes,use_errno,use_last_error;
438.488 - item : WinDLL;C;|DOCUMENTED|DOC_ONLY|;
438.489 - item : WinError;F;|DOCUMENTED|DOC_ONLY|;code,descr;
438.490 - item : _CData;C;|DOCUMENTED|PRIVATE|DOC_ONLY|;
438.491 - item : _FuncPtr;C;|DOCUMENTED|PRIVATE|DOC_ONLY|;
438.492 - item : _SimpleCData;C;|DOCUMENTED|PRIVATE|DOC_ONLY|;
438.493 - item : addressof;F;|DOCUMENTED|DOC_ONLY|;obj;
438.494 - item : alignment;F;|DOCUMENTED|DOC_ONLY|;obj_or_type;
438.495 - item : byref;F;|DOCUMENTED|DOC_ONLY|;obj,offset;
438.496 - item : c_bool;C;|DOCUMENTED|DOC_ONLY|;
438.497 - item : c_byte;C;|DOCUMENTED|DOC_ONLY|;
438.498 - item : c_char;C;|DOCUMENTED|DOC_ONLY|;
438.499 - item : c_char_p;C;|DOCUMENTED|DOC_ONLY|;
438.500 - item : c_double;C;|DOCUMENTED|DOC_ONLY|;
438.501 - item : c_float;C;|DOCUMENTED|DOC_ONLY|;
438.502 - item : c_int16;C;|DOCUMENTED|DOC_ONLY|;
438.503 - item : c_int32;C;|DOCUMENTED|DOC_ONLY|;
438.504 - item : c_int64;C;|DOCUMENTED|DOC_ONLY|;
438.505 - item : c_int8;C;|DOCUMENTED|DOC_ONLY|;
438.506 - item : c_int;C;|DOCUMENTED|DOC_ONLY|;
438.507 - item : c_long;C;|DOCUMENTED|DOC_ONLY|;
438.508 - item : c_longdouble;C;|DOCUMENTED|DOC_ONLY|;
438.509 - item : c_longlong;C;|DOCUMENTED|DOC_ONLY|;
438.510 - item : c_short;C;|DOCUMENTED|DOC_ONLY|;
438.511 - item : c_size_t;C;|DOCUMENTED|DOC_ONLY|;
438.512 - item : c_ubyte;C;|DOCUMENTED|DOC_ONLY|;
438.513 - item : c_uint16;C;|DOCUMENTED|DOC_ONLY|;
438.514 - item : c_uint32;C;|DOCUMENTED|DOC_ONLY|;
438.515 - item : c_uint64;C;|DOCUMENTED|DOC_ONLY|;
438.516 - item : c_uint8;C;|DOCUMENTED|DOC_ONLY|;
438.517 - item : c_uint;C;|DOCUMENTED|DOC_ONLY|;
438.518 - item : c_ulong;C;|DOCUMENTED|DOC_ONLY|;
438.519 - item : c_ulonglong;C;|DOCUMENTED|DOC_ONLY|;
438.520 - item : c_ushort;C;|DOCUMENTED|DOC_ONLY|;
438.521 - item : c_void_p;C;|DOCUMENTED|DOC_ONLY|;
438.522 - item : c_wchar;C;|DOCUMENTED|DOC_ONLY|;
438.523 - item : c_wchar_p;C;|DOCUMENTED|DOC_ONLY|;
438.524 - item : callable;F;|DOCUMENTED|DOC_ONLY|;result,func,arguments;
438.525 - item : cast;F;|DOCUMENTED|DOC_ONLY|;obj,type;
438.526 - item : cdll;D;|DOCUMENTED|DOC_ONLY|;
438.527 - item : create_string_buffer;F;|DOCUMENTED|DOC_ONLY|;init_or_size,size;
438.528 - item : create_unicode_buffer;F;|DOCUMENTED|DOC_ONLY|;init_or_size,size;
438.529 - item : find_library;F;|DOCUMENTED|DOC_ONLY|;name;
438.530 - item : find_library;F;|DOCUMENTED|DOC_ONLY|;name;
438.531 - item : find_msvcrt;F;|DOCUMENTED|DOC_ONLY|;;
438.532 - item : get_errno;F;|DOCUMENTED|DOC_ONLY|;;
438.533 - item : get_last_error;F;|DOCUMENTED|DOC_ONLY|;;
438.534 - item : memmove;F;|DOCUMENTED|DOC_ONLY|;dst,src,count;
438.535 - item : memset;F;|DOCUMENTED|DOC_ONLY|;dst,c,count;
438.536 - item : oledll;D;|DOCUMENTED|DOC_ONLY|;
438.537 - item : pointer;F;|DOCUMENTED|DOC_ONLY|;obj;
438.538 - item : prototype;F;|DOCUMENTED|DOC_ONLY|;address;
438.539 - item : prototype;F;|DOCUMENTED|DOC_ONLY|;callable;
438.540 - item : prototype;F;|DOCUMENTED|DOC_ONLY|;func_spec,paramflags;
438.541 - item : prototype;F;|DOCUMENTED|DOC_ONLY|;vtbl_index,name,paramflags,iid;
438.542 - item : py_object;C;|DOCUMENTED|DOC_ONLY|;
438.543 - item : pydll;D;|DOCUMENTED|DOC_ONLY|;
438.544 - item : pythonapi;D;|DOCUMENTED|DOC_ONLY|;
438.545 - item : resize;F;|DOCUMENTED|DOC_ONLY|;obj,size;
438.546 - item : set_conversion_mode;F;|DOCUMENTED|DOC_ONLY|;encoding,errors;
438.547 - item : set_errno;F;|DOCUMENTED|DOC_ONLY|;value;
438.548 - item : set_last_error;F;|DOCUMENTED|DOC_ONLY|;value;
438.549 - item : sizeof;F;|DOCUMENTED|DOC_ONLY|;obj_or_type;
438.550 - item : string_at;F;|DOCUMENTED|DOC_ONLY|;address,size;
438.551 - item : windll;D;|DOCUMENTED|DOC_ONLY|;
438.552 - item : wstring_at;F;|DOCUMENTED|DOC_ONLY|;address;
438.553 - module : ctypes
438.554 -
438.555 -Not Searchable Keys:
438.556 - modattrs : S
439.1 --- a/python.editor/test/unit/data/testfiles/rst/exceptions.rst Sun Jan 04 13:11:53 2015 -0600
439.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
439.3 @@ -1,478 +0,0 @@
439.4 -.. _bltin-exceptions:
439.5 -
439.6 -Built-in Exceptions
439.7 -===================
439.8 -
439.9 -.. module:: exceptions
439.10 - :synopsis: Standard exception classes.
439.11 -
439.12 -
439.13 -Exceptions should be class objects. The exceptions are defined in the module
439.14 -:mod:`exceptions`. This module never needs to be imported explicitly: the
439.15 -exceptions are provided in the built-in namespace as well as the
439.16 -:mod:`exceptions` module.
439.17 -
439.18 -.. index::
439.19 - statement: try
439.20 - statement: except
439.21 -
439.22 -For class exceptions, in a :keyword:`try` statement with an :keyword:`except`
439.23 -clause that mentions a particular class, that clause also handles any exception
439.24 -classes derived from that class (but not exception classes from which *it* is
439.25 -derived). Two exception classes that are not related via subclassing are never
439.26 -equivalent, even if they have the same name.
439.27 -
439.28 -.. index:: statement: raise
439.29 -
439.30 -The built-in exceptions listed below can be generated by the interpreter or
439.31 -built-in functions. Except where mentioned, they have an "associated value"
439.32 -indicating the detailed cause of the error. This may be a string or a tuple
439.33 -containing several items of information (e.g., an error code and a string
439.34 -explaining the code). The associated value is the second argument to the
439.35 -:keyword:`raise` statement. If the exception class is derived from the standard
439.36 -root class :exc:`BaseException`, the associated value is present as the
439.37 -exception instance's :attr:`args` attribute.
439.38 -
439.39 -User code can raise built-in exceptions. This can be used to test an exception
439.40 -handler or to report an error condition "just like" the situation in which the
439.41 -interpreter raises the same exception; but beware that there is nothing to
439.42 -prevent user code from raising an inappropriate error.
439.43 -
439.44 -The built-in exception classes can be sub-classed to define new exceptions;
439.45 -programmers are encouraged to at least derive new exceptions from the
439.46 -:exc:`Exception` class and not :exc:`BaseException`. More information on
439.47 -defining exceptions is available in the Python Tutorial under
439.48 -:ref:`tut-userexceptions`.
439.49 -
439.50 -The following exceptions are only used as base classes for other exceptions.
439.51 -
439.52 -
439.53 -.. exception:: BaseException
439.54 -
439.55 - The base class for all built-in exceptions. It is not meant to be directly
439.56 - inherited by user-defined classes (for that use :exc:`Exception`). If
439.57 - :func:`str` or :func:`unicode` is called on an instance of this class, the
439.58 - representation of the argument(s) to the instance are returned or the emptry
439.59 - string when there were no arguments. All arguments are stored in :attr:`args`
439.60 - as a tuple.
439.61 -
439.62 - .. versionadded:: 2.5
439.63 -
439.64 -
439.65 -.. exception:: Exception
439.66 -
439.67 - All built-in, non-system-exiting exceptions are derived from this class. All
439.68 - user-defined exceptions should also be derived from this class.
439.69 -
439.70 - .. versionchanged:: 2.5
439.71 - Changed to inherit from :exc:`BaseException`.
439.72 -
439.73 -
439.74 -.. exception:: StandardError
439.75 -
439.76 - The base class for all built-in exceptions except :exc:`StopIteration`,
439.77 - :exc:`GeneratorExit`, :exc:`KeyboardInterrupt` and :exc:`SystemExit`.
439.78 - :exc:`StandardError` itself is derived from :exc:`Exception`.
439.79 -
439.80 -
439.81 -.. exception:: ArithmeticError
439.82 -
439.83 - The base class for those built-in exceptions that are raised for various
439.84 - arithmetic errors: :exc:`OverflowError`, :exc:`ZeroDivisionError`,
439.85 - :exc:`FloatingPointError`.
439.86 -
439.87 -
439.88 -.. exception:: LookupError
439.89 -
439.90 - The base class for the exceptions that are raised when a key or index used on a
439.91 - mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This can be
439.92 - raised directly by :func:`sys.setdefaultencoding`.
439.93 -
439.94 -
439.95 -.. exception:: EnvironmentError
439.96 -
439.97 - The base class for exceptions that can occur outside the Python system:
439.98 - :exc:`IOError`, :exc:`OSError`. When exceptions of this type are created with a
439.99 - 2-tuple, the first item is available on the instance's :attr:`errno` attribute
439.100 - (it is assumed to be an error number), and the second item is available on the
439.101 - :attr:`strerror` attribute (it is usually the associated error message). The
439.102 - tuple itself is also available on the :attr:`args` attribute.
439.103 -
439.104 - .. versionadded:: 1.5.2
439.105 -
439.106 - When an :exc:`EnvironmentError` exception is instantiated with a 3-tuple, the
439.107 - first two items are available as above, while the third item is available on the
439.108 - :attr:`filename` attribute. However, for backwards compatibility, the
439.109 - :attr:`args` attribute contains only a 2-tuple of the first two constructor
439.110 - arguments.
439.111 -
439.112 - The :attr:`filename` attribute is ``None`` when this exception is created with
439.113 - other than 3 arguments. The :attr:`errno` and :attr:`strerror` attributes are
439.114 - also ``None`` when the instance was created with other than 2 or 3 arguments.
439.115 - In this last case, :attr:`args` contains the verbatim constructor arguments as a
439.116 - tuple.
439.117 -
439.118 -The following exceptions are the exceptions that are actually raised.
439.119 -
439.120 -
439.121 -.. exception:: AssertionError
439.122 -
439.123 - .. index:: statement: assert
439.124 -
439.125 - Raised when an :keyword:`assert` statement fails.
439.126 -
439.127 -
439.128 -.. exception:: AttributeError
439.129 -
439.130 - Raised when an attribute reference (see :ref:`attribute-references`) or
439.131 - assignment fails. (When an object does not support attribute references or
439.132 - attribute assignments at all, :exc:`TypeError` is raised.)
439.133 -
439.134 -
439.135 -.. exception:: EOFError
439.136 -
439.137 - Raised when one of the built-in functions (:func:`input` or :func:`raw_input`)
439.138 - hits an end-of-file condition (EOF) without reading any data. (N.B.: the
439.139 - :meth:`file.read` and :meth:`file.readline` methods return an empty string
439.140 - when they hit EOF.)
439.141 -
439.142 -
439.143 -.. exception:: FloatingPointError
439.144 -
439.145 - Raised when a floating point operation fails. This exception is always defined,
439.146 - but can only be raised when Python is configured with the
439.147 - :option:`--with-fpectl` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
439.148 - defined in the :file:`pyconfig.h` file.
439.149 -
439.150 -
439.151 -.. exception:: GeneratorExit
439.152 -
439.153 - Raise when a :term:`generator`\'s :meth:`close` method is called. It
439.154 - directly inherits from :exc:`BaseException` instead of :exc:`StandardError` since
439.155 - it is technically not an error.
439.156 -
439.157 - .. versionadded:: 2.5
439.158 -
439.159 - .. versionchanged:: 2.6
439.160 - Changed to inherit from :exc:`BaseException`.
439.161 -
439.162 -.. exception:: IOError
439.163 -
439.164 - Raised when an I/O operation (such as a :keyword:`print` statement, the built-in
439.165 - :func:`open` function or a method of a file object) fails for an I/O-related
439.166 - reason, e.g., "file not found" or "disk full".
439.167 -
439.168 - This class is derived from :exc:`EnvironmentError`. See the discussion above
439.169 - for more information on exception instance attributes.
439.170 -
439.171 - .. versionchanged:: 2.6
439.172 - Changed :exc:`socket.error` to use this as a base class.
439.173 -
439.174 -
439.175 -.. exception:: ImportError
439.176 -
439.177 - Raised when an :keyword:`import` statement fails to find the module definition
439.178 - or when a ``from ... import`` fails to find a name that is to be imported.
439.179 -
439.180 -
439.181 -.. exception:: IndexError
439.182 -
439.183 - Raised when a sequence subscript is out of range. (Slice indices are silently
439.184 - truncated to fall in the allowed range; if an index is not a plain integer,
439.185 - :exc:`TypeError` is raised.)
439.186 -
439.187 - .. XXX xref to sequences
439.188 -
439.189 -
439.190 -.. exception:: KeyError
439.191 -
439.192 - Raised when a mapping (dictionary) key is not found in the set of existing keys.
439.193 -
439.194 - .. XXX xref to mapping objects?
439.195 -
439.196 -
439.197 -.. exception:: KeyboardInterrupt
439.198 -
439.199 - Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
439.200 - :kbd:`Delete`). During execution, a check for interrupts is made regularly.
439.201 - Interrupts typed when a built-in function :func:`input` or :func:`raw_input` is
439.202 - waiting for input also raise this exception. The exception inherits from
439.203 - :exc:`BaseException` so as to not be accidentally caught by code that catches
439.204 - :exc:`Exception` and thus prevent the interpreter from exiting.
439.205 -
439.206 - .. versionchanged:: 2.5
439.207 - Changed to inherit from :exc:`BaseException`.
439.208 -
439.209 -
439.210 -.. exception:: MemoryError
439.211 -
439.212 - Raised when an operation runs out of memory but the situation may still be
439.213 - rescued (by deleting some objects). The associated value is a string indicating
439.214 - what kind of (internal) operation ran out of memory. Note that because of the
439.215 - underlying memory management architecture (C's :cfunc:`malloc` function), the
439.216 - interpreter may not always be able to completely recover from this situation; it
439.217 - nevertheless raises an exception so that a stack traceback can be printed, in
439.218 - case a run-away program was the cause.
439.219 -
439.220 -
439.221 -.. exception:: NameError
439.222 -
439.223 - Raised when a local or global name is not found. This applies only to
439.224 - unqualified names. The associated value is an error message that includes the
439.225 - name that could not be found.
439.226 -
439.227 -
439.228 -.. exception:: NotImplementedError
439.229 -
439.230 - This exception is derived from :exc:`RuntimeError`. In user defined base
439.231 - classes, abstract methods should raise this exception when they require derived
439.232 - classes to override the method.
439.233 -
439.234 - .. versionadded:: 1.5.2
439.235 -
439.236 -
439.237 -.. exception:: OSError
439.238 -
439.239 - .. index:: module: errno
439.240 -
439.241 - This exception is derived from :exc:`EnvironmentError`. It is raised when a
439.242 - function returns a system-related error (not for illegal argument types or
439.243 - other incidental errors). The :attr:`errno` attribute is a numeric error
439.244 - code from :cdata:`errno`, and the :attr:`strerror` attribute is the
439.245 - corresponding string, as would be printed by the C function :cfunc:`perror`.
439.246 - See the module :mod:`errno`, which contains names for the error codes defined
439.247 - by the underlying operating system.
439.248 -
439.249 - For exceptions that involve a file system path (such as :func:`chdir` or
439.250 - :func:`unlink`), the exception instance will contain a third attribute,
439.251 - :attr:`filename`, which is the file name passed to the function.
439.252 -
439.253 - .. versionadded:: 1.5.2
439.254 -
439.255 -
439.256 -.. exception:: OverflowError
439.257 -
439.258 - Raised when the result of an arithmetic operation is too large to be
439.259 - represented. This cannot occur for long integers (which would rather raise
439.260 - :exc:`MemoryError` than give up) and for most operations with plain integers,
439.261 - which return a long integer instead. Because of the lack of standardization
439.262 - of floating point exception handling in C, most floating point operations
439.263 - also aren't checked.
439.264 -
439.265 -
439.266 -.. exception:: ReferenceError
439.267 -
439.268 - This exception is raised when a weak reference proxy, created by the
439.269 - :func:`weakref.proxy` function, is used to access an attribute of the referent
439.270 - after it has been garbage collected. For more information on weak references,
439.271 - see the :mod:`weakref` module.
439.272 -
439.273 - .. versionadded:: 2.2
439.274 - Previously known as the :exc:`weakref.ReferenceError` exception.
439.275 -
439.276 -
439.277 -.. exception:: RuntimeError
439.278 -
439.279 - Raised when an error is detected that doesn't fall in any of the other
439.280 - categories. The associated value is a string indicating what precisely went
439.281 - wrong. (This exception is mostly a relic from a previous version of the
439.282 - interpreter; it is not used very much any more.)
439.283 -
439.284 -
439.285 -.. exception:: StopIteration
439.286 -
439.287 - Raised by an :term:`iterator`\'s :meth:`next` method to signal that there are
439.288 - no further values. This is derived from :exc:`Exception` rather than
439.289 - :exc:`StandardError`, since this is not considered an error in its normal
439.290 - application.
439.291 -
439.292 - .. versionadded:: 2.2
439.293 -
439.294 -
439.295 -.. exception:: SyntaxError
439.296 -
439.297 - Raised when the parser encounters a syntax error. This may occur in an
439.298 - :keyword:`import` statement, in an :keyword:`exec` statement, in a call to the
439.299 - built-in function :func:`eval` or :func:`input`, or when reading the initial
439.300 - script or standard input (also interactively).
439.301 -
439.302 - Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
439.303 - :attr:`offset` and :attr:`text` for easier access to the details. :func:`str`
439.304 - of the exception instance returns only the message.
439.305 -
439.306 -
439.307 -.. exception:: SystemError
439.308 -
439.309 - Raised when the interpreter finds an internal error, but the situation does not
439.310 - look so serious to cause it to abandon all hope. The associated value is a
439.311 - string indicating what went wrong (in low-level terms).
439.312 -
439.313 - You should report this to the author or maintainer of your Python interpreter.
439.314 - Be sure to report the version of the Python interpreter (``sys.version``; it is
439.315 - also printed at the start of an interactive Python session), the exact error
439.316 - message (the exception's associated value) and if possible the source of the
439.317 - program that triggered the error.
439.318 -
439.319 -
439.320 -.. exception:: SystemExit
439.321 -
439.322 - This exception is raised by the :func:`sys.exit` function. When it is not
439.323 - handled, the Python interpreter exits; no stack traceback is printed. If the
439.324 - associated value is a plain integer, it specifies the system exit status (passed
439.325 - to C's :cfunc:`exit` function); if it is ``None``, the exit status is zero; if
439.326 - it has another type (such as a string), the object's value is printed and the
439.327 - exit status is one.
439.328 -
439.329 - Instances have an attribute :attr:`code` which is set to the proposed exit
439.330 - status or error message (defaulting to ``None``). Also, this exception derives
439.331 - directly from :exc:`BaseException` and not :exc:`StandardError`, since it is not
439.332 - technically an error.
439.333 -
439.334 - A call to :func:`sys.exit` is translated into an exception so that clean-up
439.335 - handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
439.336 - executed, and so that a debugger can execute a script without running the risk
439.337 - of losing control. The :func:`os._exit` function can be used if it is
439.338 - absolutely positively necessary to exit immediately (for example, in the child
439.339 - process after a call to :func:`fork`).
439.340 -
439.341 - The exception inherits from :exc:`BaseException` instead of :exc:`StandardError`
439.342 - or :exc:`Exception` so that it is not accidentally caught by code that catches
439.343 - :exc:`Exception`. This allows the exception to properly propagate up and cause
439.344 - the interpreter to exit.
439.345 -
439.346 - .. versionchanged:: 2.5
439.347 - Changed to inherit from :exc:`BaseException`.
439.348 -
439.349 -
439.350 -.. exception:: TypeError
439.351 -
439.352 - Raised when an operation or function is applied to an object of inappropriate
439.353 - type. The associated value is a string giving details about the type mismatch.
439.354 -
439.355 -
439.356 -.. exception:: UnboundLocalError
439.357 -
439.358 - Raised when a reference is made to a local variable in a function or method, but
439.359 - no value has been bound to that variable. This is a subclass of
439.360 - :exc:`NameError`.
439.361 -
439.362 - .. versionadded:: 2.0
439.363 -
439.364 -
439.365 -.. exception:: UnicodeError
439.366 -
439.367 - Raised when a Unicode-related encoding or decoding error occurs. It is a
439.368 - subclass of :exc:`ValueError`.
439.369 -
439.370 - .. versionadded:: 2.0
439.371 -
439.372 -
439.373 -.. exception:: UnicodeEncodeError
439.374 -
439.375 - Raised when a Unicode-related error occurs during encoding. It is a subclass of
439.376 - :exc:`UnicodeError`.
439.377 -
439.378 - .. versionadded:: 2.3
439.379 -
439.380 -
439.381 -.. exception:: UnicodeDecodeError
439.382 -
439.383 - Raised when a Unicode-related error occurs during decoding. It is a subclass of
439.384 - :exc:`UnicodeError`.
439.385 -
439.386 - .. versionadded:: 2.3
439.387 -
439.388 -
439.389 -.. exception:: UnicodeTranslateError
439.390 -
439.391 - Raised when a Unicode-related error occurs during translating. It is a subclass
439.392 - of :exc:`UnicodeError`.
439.393 -
439.394 - .. versionadded:: 2.3
439.395 -
439.396 -
439.397 -.. exception:: ValueError
439.398 -
439.399 - Raised when a built-in operation or function receives an argument that has the
439.400 - right type but an inappropriate value, and the situation is not described by a
439.401 - more precise exception such as :exc:`IndexError`.
439.402 -
439.403 -
439.404 -.. exception:: WindowsError
439.405 -
439.406 - Raised when a Windows-specific error occurs or when the error number does not
439.407 - correspond to an :cdata:`errno` value. The :attr:`winerror` and
439.408 - :attr:`strerror` values are created from the return values of the
439.409 - :cfunc:`GetLastError` and :cfunc:`FormatMessage` functions from the Windows
439.410 - Platform API. The :attr:`errno` value maps the :attr:`winerror` value to
439.411 - corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`.
439.412 -
439.413 - .. versionadded:: 2.0
439.414 -
439.415 - .. versionchanged:: 2.5
439.416 - Previous versions put the :cfunc:`GetLastError` codes into :attr:`errno`.
439.417 -
439.418 -
439.419 -.. exception:: ZeroDivisionError
439.420 -
439.421 - Raised when the second argument of a division or modulo operation is zero. The
439.422 - associated value is a string indicating the type of the operands and the
439.423 - operation.
439.424 -
439.425 -The following exceptions are used as warning categories; see the :mod:`warnings`
439.426 -module for more information.
439.427 -
439.428 -
439.429 -.. exception:: Warning
439.430 -
439.431 - Base class for warning categories.
439.432 -
439.433 -
439.434 -.. exception:: UserWarning
439.435 -
439.436 - Base class for warnings generated by user code.
439.437 -
439.438 -
439.439 -.. exception:: DeprecationWarning
439.440 -
439.441 - Base class for warnings about deprecated features.
439.442 -
439.443 -
439.444 -.. exception:: PendingDeprecationWarning
439.445 -
439.446 - Base class for warnings about features which will be deprecated in the future.
439.447 -
439.448 -
439.449 -.. exception:: SyntaxWarning
439.450 -
439.451 - Base class for warnings about dubious syntax
439.452 -
439.453 -
439.454 -.. exception:: RuntimeWarning
439.455 -
439.456 - Base class for warnings about dubious runtime behavior.
439.457 -
439.458 -
439.459 -.. exception:: FutureWarning
439.460 -
439.461 - Base class for warnings about constructs that will change semantically in the
439.462 - future.
439.463 -
439.464 -
439.465 -.. exception:: ImportWarning
439.466 -
439.467 - Base class for warnings about probable mistakes in module imports.
439.468 -
439.469 - .. versionadded:: 2.5
439.470 -
439.471 -
439.472 -.. exception:: UnicodeWarning
439.473 -
439.474 - Base class for warnings related to Unicode.
439.475 -
439.476 - .. versionadded:: 2.5
439.477 -
439.478 -The class hierarchy for built-in exceptions is:
439.479 -
439.480 -
439.481 -.. literalinclude:: ../../Lib/test/exception_hierarchy.txt
440.1 --- a/python.editor/test/unit/data/testfiles/rst/exceptions.rst.indexed Sun Jan 04 13:11:53 2015 -0600
440.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
440.3 @@ -1,547 +0,0 @@
440.4 -
440.5 -
440.6 -Document 0
440.7 -Searchable Keys:
440.8 - class : ArithmeticError
440.9 - class-ig : arithmeticerror
440.10 - extends : Exception
440.11 - in : exceptions
440.12 -
440.13 -Not Searchable Keys:
440.14 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.15 -
440.16 -
440.17 -Document 1
440.18 -Searchable Keys:
440.19 - class : AssertionError
440.20 - class-ig : assertionerror
440.21 - extends : Exception
440.22 - in : exceptions
440.23 -
440.24 -Not Searchable Keys:
440.25 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.26 -
440.27 -
440.28 -Document 2
440.29 -Searchable Keys:
440.30 - class : AttributeError
440.31 - class-ig : attributeerror
440.32 - extends : Exception
440.33 - in : exceptions
440.34 -
440.35 -Not Searchable Keys:
440.36 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.37 -
440.38 -
440.39 -Document 3
440.40 -Searchable Keys:
440.41 - class : BaseException
440.42 - class-ig : baseexception
440.43 - extends : Exception
440.44 - in : exceptions
440.45 -
440.46 -Not Searchable Keys:
440.47 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.48 -
440.49 -
440.50 -Document 4
440.51 -Searchable Keys:
440.52 - class : DeprecationWarning
440.53 - class-ig : deprecationwarning
440.54 - extends : Exception
440.55 - in : exceptions
440.56 -
440.57 -Not Searchable Keys:
440.58 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.59 -
440.60 -
440.61 -Document 5
440.62 -Searchable Keys:
440.63 - class : EOFError
440.64 - class-ig : eoferror
440.65 - extends : Exception
440.66 - in : exceptions
440.67 -
440.68 -Not Searchable Keys:
440.69 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.70 -
440.71 -
440.72 -Document 6
440.73 -Searchable Keys:
440.74 - class : EnvironmentError
440.75 - class-ig : environmenterror
440.76 - extends : Exception
440.77 - in : exceptions
440.78 -
440.79 -Not Searchable Keys:
440.80 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.81 -
440.82 -
440.83 -Document 7
440.84 -Searchable Keys:
440.85 - class : Exception
440.86 - class-ig : exception
440.87 - in : exceptions
440.88 -
440.89 -Not Searchable Keys:
440.90 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.91 -
440.92 -
440.93 -Document 8
440.94 -Searchable Keys:
440.95 - class : FloatingPointError
440.96 - class-ig : floatingpointerror
440.97 - extends : Exception
440.98 - in : exceptions
440.99 -
440.100 -Not Searchable Keys:
440.101 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.102 -
440.103 -
440.104 -Document 9
440.105 -Searchable Keys:
440.106 - class : FutureWarning
440.107 - class-ig : futurewarning
440.108 - extends : Exception
440.109 - in : exceptions
440.110 -
440.111 -Not Searchable Keys:
440.112 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.113 -
440.114 -
440.115 -Document 10
440.116 -Searchable Keys:
440.117 - class : GeneratorExit
440.118 - class-ig : generatorexit
440.119 - extends : Exception
440.120 - in : exceptions
440.121 -
440.122 -Not Searchable Keys:
440.123 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.124 -
440.125 -
440.126 -Document 11
440.127 -Searchable Keys:
440.128 - class : IOError
440.129 - class-ig : ioerror
440.130 - extends : Exception
440.131 - in : exceptions
440.132 -
440.133 -Not Searchable Keys:
440.134 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.135 -
440.136 -
440.137 -Document 12
440.138 -Searchable Keys:
440.139 - class : ImportError
440.140 - class-ig : importerror
440.141 - extends : Exception
440.142 - in : exceptions
440.143 -
440.144 -Not Searchable Keys:
440.145 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.146 -
440.147 -
440.148 -Document 13
440.149 -Searchable Keys:
440.150 - class : ImportWarning
440.151 - class-ig : importwarning
440.152 - extends : Exception
440.153 - in : exceptions
440.154 -
440.155 -Not Searchable Keys:
440.156 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.157 -
440.158 -
440.159 -Document 14
440.160 -Searchable Keys:
440.161 - class : IndexError
440.162 - class-ig : indexerror
440.163 - extends : Exception
440.164 - in : exceptions
440.165 -
440.166 -Not Searchable Keys:
440.167 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.168 -
440.169 -
440.170 -Document 15
440.171 -Searchable Keys:
440.172 - class : KeyError
440.173 - class-ig : keyerror
440.174 - extends : Exception
440.175 - in : exceptions
440.176 -
440.177 -Not Searchable Keys:
440.178 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.179 -
440.180 -
440.181 -Document 16
440.182 -Searchable Keys:
440.183 - class : KeyboardInterrupt
440.184 - class-ig : keyboardinterrupt
440.185 - extends : Exception
440.186 - in : exceptions
440.187 -
440.188 -Not Searchable Keys:
440.189 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.190 -
440.191 -
440.192 -Document 17
440.193 -Searchable Keys:
440.194 - class : LookupError
440.195 - class-ig : lookuperror
440.196 - extends : Exception
440.197 - in : exceptions
440.198 -
440.199 -Not Searchable Keys:
440.200 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.201 -
440.202 -
440.203 -Document 18
440.204 -Searchable Keys:
440.205 - class : MemoryError
440.206 - class-ig : memoryerror
440.207 - extends : Exception
440.208 - in : exceptions
440.209 -
440.210 -Not Searchable Keys:
440.211 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.212 -
440.213 -
440.214 -Document 19
440.215 -Searchable Keys:
440.216 - class : NameError
440.217 - class-ig : nameerror
440.218 - extends : Exception
440.219 - in : exceptions
440.220 -
440.221 -Not Searchable Keys:
440.222 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.223 -
440.224 -
440.225 -Document 20
440.226 -Searchable Keys:
440.227 - class : NotImplementedError
440.228 - class-ig : notimplementederror
440.229 - extends : Exception
440.230 - in : exceptions
440.231 -
440.232 -Not Searchable Keys:
440.233 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.234 -
440.235 -
440.236 -Document 21
440.237 -Searchable Keys:
440.238 - class : OSError
440.239 - class-ig : oserror
440.240 - extends : Exception
440.241 - in : exceptions
440.242 -
440.243 -Not Searchable Keys:
440.244 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.245 -
440.246 -
440.247 -Document 22
440.248 -Searchable Keys:
440.249 - class : OverflowError
440.250 - class-ig : overflowerror
440.251 - extends : Exception
440.252 - in : exceptions
440.253 -
440.254 -Not Searchable Keys:
440.255 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.256 -
440.257 -
440.258 -Document 23
440.259 -Searchable Keys:
440.260 - class : PendingDeprecationWarning
440.261 - class-ig : pendingdeprecationwarning
440.262 - extends : Exception
440.263 - in : exceptions
440.264 -
440.265 -Not Searchable Keys:
440.266 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.267 -
440.268 -
440.269 -Document 24
440.270 -Searchable Keys:
440.271 - class : ReferenceError
440.272 - class-ig : referenceerror
440.273 - extends : Exception
440.274 - in : exceptions
440.275 -
440.276 -Not Searchable Keys:
440.277 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.278 -
440.279 -
440.280 -Document 25
440.281 -Searchable Keys:
440.282 - class : RuntimeError
440.283 - class-ig : runtimeerror
440.284 - extends : Exception
440.285 - in : exceptions
440.286 -
440.287 -Not Searchable Keys:
440.288 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.289 -
440.290 -
440.291 -Document 26
440.292 -Searchable Keys:
440.293 - class : RuntimeWarning
440.294 - class-ig : runtimewarning
440.295 - extends : Exception
440.296 - in : exceptions
440.297 -
440.298 -Not Searchable Keys:
440.299 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.300 -
440.301 -
440.302 -Document 27
440.303 -Searchable Keys:
440.304 - class : StandardError
440.305 - class-ig : standarderror
440.306 - extends : Exception
440.307 - in : exceptions
440.308 -
440.309 -Not Searchable Keys:
440.310 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.311 -
440.312 -
440.313 -Document 28
440.314 -Searchable Keys:
440.315 - class : StopIteration
440.316 - class-ig : stopiteration
440.317 - extends : Exception
440.318 - in : exceptions
440.319 -
440.320 -Not Searchable Keys:
440.321 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.322 -
440.323 -
440.324 -Document 29
440.325 -Searchable Keys:
440.326 - class : SyntaxError
440.327 - class-ig : syntaxerror
440.328 - extends : Exception
440.329 - in : exceptions
440.330 -
440.331 -Not Searchable Keys:
440.332 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.333 -
440.334 -
440.335 -Document 30
440.336 -Searchable Keys:
440.337 - class : SyntaxWarning
440.338 - class-ig : syntaxwarning
440.339 - extends : Exception
440.340 - in : exceptions
440.341 -
440.342 -Not Searchable Keys:
440.343 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.344 -
440.345 -
440.346 -Document 31
440.347 -Searchable Keys:
440.348 - class : SystemError
440.349 - class-ig : systemerror
440.350 - extends : Exception
440.351 - in : exceptions
440.352 -
440.353 -Not Searchable Keys:
440.354 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.355 -
440.356 -
440.357 -Document 32
440.358 -Searchable Keys:
440.359 - class : SystemExit
440.360 - class-ig : systemexit
440.361 - extends : Exception
440.362 - in : exceptions
440.363 -
440.364 -Not Searchable Keys:
440.365 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.366 -
440.367 -
440.368 -Document 33
440.369 -Searchable Keys:
440.370 - class : TypeError
440.371 - class-ig : typeerror
440.372 - extends : Exception
440.373 - in : exceptions
440.374 -
440.375 -Not Searchable Keys:
440.376 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.377 -
440.378 -
440.379 -Document 34
440.380 -Searchable Keys:
440.381 - class : UnboundLocalError
440.382 - class-ig : unboundlocalerror
440.383 - extends : Exception
440.384 - in : exceptions
440.385 -
440.386 -Not Searchable Keys:
440.387 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.388 -
440.389 -
440.390 -Document 35
440.391 -Searchable Keys:
440.392 - class : UnicodeDecodeError
440.393 - class-ig : unicodedecodeerror
440.394 - extends : Exception
440.395 - in : exceptions
440.396 -
440.397 -Not Searchable Keys:
440.398 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.399 -
440.400 -
440.401 -Document 36
440.402 -Searchable Keys:
440.403 - class : UnicodeEncodeError
440.404 - class-ig : unicodeencodeerror
440.405 - extends : Exception
440.406 - in : exceptions
440.407 -
440.408 -Not Searchable Keys:
440.409 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.410 -
440.411 -
440.412 -Document 37
440.413 -Searchable Keys:
440.414 - class : UnicodeError
440.415 - class-ig : unicodeerror
440.416 - extends : Exception
440.417 - in : exceptions
440.418 -
440.419 -Not Searchable Keys:
440.420 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.421 -
440.422 -
440.423 -Document 38
440.424 -Searchable Keys:
440.425 - class : UnicodeTranslateError
440.426 - class-ig : unicodetranslateerror
440.427 - extends : Exception
440.428 - in : exceptions
440.429 -
440.430 -Not Searchable Keys:
440.431 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.432 -
440.433 -
440.434 -Document 39
440.435 -Searchable Keys:
440.436 - class : UnicodeWarning
440.437 - class-ig : unicodewarning
440.438 - extends : Exception
440.439 - in : exceptions
440.440 -
440.441 -Not Searchable Keys:
440.442 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.443 -
440.444 -
440.445 -Document 40
440.446 -Searchable Keys:
440.447 - class : UserWarning
440.448 - class-ig : userwarning
440.449 - extends : Exception
440.450 - in : exceptions
440.451 -
440.452 -Not Searchable Keys:
440.453 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.454 -
440.455 -
440.456 -Document 41
440.457 -Searchable Keys:
440.458 - class : ValueError
440.459 - class-ig : valueerror
440.460 - extends : Exception
440.461 - in : exceptions
440.462 -
440.463 -Not Searchable Keys:
440.464 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.465 -
440.466 -
440.467 -Document 42
440.468 -Searchable Keys:
440.469 - class : Warning
440.470 - class-ig : warning
440.471 - extends : Exception
440.472 - in : exceptions
440.473 -
440.474 -Not Searchable Keys:
440.475 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.476 -
440.477 -
440.478 -Document 43
440.479 -Searchable Keys:
440.480 - class : WindowsError
440.481 - class-ig : windowserror
440.482 - extends : Exception
440.483 - in : exceptions
440.484 -
440.485 -Not Searchable Keys:
440.486 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.487 -
440.488 -
440.489 -Document 44
440.490 -Searchable Keys:
440.491 - class : ZeroDivisionError
440.492 - class-ig : zerodivisionerror
440.493 - extends : Exception
440.494 - in : exceptions
440.495 -
440.496 -Not Searchable Keys:
440.497 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
440.498 -
440.499 -
440.500 -Document 45
440.501 -Searchable Keys:
440.502 - item : ArithmeticError;C;|DOCUMENTED|DOC_ONLY|;
440.503 - item : AssertionError;C;|DOCUMENTED|DOC_ONLY|;
440.504 - item : AttributeError;C;|DOCUMENTED|DOC_ONLY|;
440.505 - item : BaseException;C;|DOCUMENTED|DOC_ONLY|;
440.506 - item : DeprecationWarning;C;|DOCUMENTED|DOC_ONLY|;
440.507 - item : EOFError;C;|DOCUMENTED|DOC_ONLY|;
440.508 - item : EnvironmentError;C;|DOCUMENTED|DOC_ONLY|;
440.509 - item : Exception;C;|DOCUMENTED|DOC_ONLY|;
440.510 - item : FloatingPointError;C;|DOCUMENTED|DOC_ONLY|;
440.511 - item : FutureWarning;C;|DOCUMENTED|DOC_ONLY|;
440.512 - item : GeneratorExit;C;|DOCUMENTED|DOC_ONLY|;
440.513 - item : IOError;C;|DOCUMENTED|DOC_ONLY|;
440.514 - item : ImportError;C;|DOCUMENTED|DOC_ONLY|;
440.515 - item : ImportWarning;C;|DOCUMENTED|DOC_ONLY|;
440.516 - item : IndexError;C;|DOCUMENTED|DOC_ONLY|;
440.517 - item : KeyError;C;|DOCUMENTED|DOC_ONLY|;
440.518 - item : KeyboardInterrupt;C;|DOCUMENTED|DOC_ONLY|;
440.519 - item : LookupError;C;|DOCUMENTED|DOC_ONLY|;
440.520 - item : MemoryError;C;|DOCUMENTED|DOC_ONLY|;
440.521 - item : NameError;C;|DOCUMENTED|DOC_ONLY|;
440.522 - item : NotImplementedError;C;|DOCUMENTED|DOC_ONLY|;
440.523 - item : OSError;C;|DOCUMENTED|DOC_ONLY|;
440.524 - item : OverflowError;C;|DOCUMENTED|DOC_ONLY|;
440.525 - item : PendingDeprecationWarning;C;|DOCUMENTED|DOC_ONLY|;
440.526 - item : ReferenceError;C;|DOCUMENTED|DOC_ONLY|;
440.527 - item : RuntimeError;C;|DOCUMENTED|DOC_ONLY|;
440.528 - item : RuntimeWarning;C;|DOCUMENTED|DOC_ONLY|;
440.529 - item : StandardError;C;|DOCUMENTED|DOC_ONLY|;
440.530 - item : StopIteration;C;|DOCUMENTED|DOC_ONLY|;
440.531 - item : SyntaxError;C;|DOCUMENTED|DOC_ONLY|;
440.532 - item : SyntaxWarning;C;|DOCUMENTED|DOC_ONLY|;
440.533 - item : SystemError;C;|DOCUMENTED|DOC_ONLY|;
440.534 - item : SystemExit;C;|DOCUMENTED|DOC_ONLY|;
440.535 - item : TypeError;C;|DOCUMENTED|DOC_ONLY|;
440.536 - item : UnboundLocalError;C;|DOCUMENTED|DOC_ONLY|;
440.537 - item : UnicodeDecodeError;C;|DOCUMENTED|DOC_ONLY|;
440.538 - item : UnicodeEncodeError;C;|DOCUMENTED|DOC_ONLY|;
440.539 - item : UnicodeError;C;|DOCUMENTED|DOC_ONLY|;
440.540 - item : UnicodeTranslateError;C;|DOCUMENTED|DOC_ONLY|;
440.541 - item : UnicodeWarning;C;|DOCUMENTED|DOC_ONLY|;
440.542 - item : UserWarning;C;|DOCUMENTED|DOC_ONLY|;
440.543 - item : ValueError;C;|DOCUMENTED|DOC_ONLY|;
440.544 - item : Warning;C;|DOCUMENTED|DOC_ONLY|;
440.545 - item : WindowsError;C;|DOCUMENTED|DOC_ONLY|;
440.546 - item : ZeroDivisionError;C;|DOCUMENTED|DOC_ONLY|;
440.547 - module : exceptions
440.548 -
440.549 -Not Searchable Keys:
440.550 - modattrs : S
441.1 --- a/python.editor/test/unit/data/testfiles/rst/logging.rst Sun Jan 04 13:11:53 2015 -0600
441.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
441.3 @@ -1,2668 +0,0 @@
441.4 -:mod:`logging` --- Logging facility for Python
441.5 -==============================================
441.6 -
441.7 -.. module:: logging
441.8 - :synopsis: Flexible error logging system for applications.
441.9 -
441.10 -
441.11 -.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
441.12 -.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
441.13 -
441.14 -
441.15 -.. index:: pair: Errors; logging
441.16 -
441.17 -.. versionadded:: 2.3
441.18 -
441.19 -This module defines functions and classes which implement a flexible error
441.20 -logging system for applications.
441.21 -
441.22 -Logging is performed by calling methods on instances of the :class:`Logger`
441.23 -class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
441.24 -conceptually arranged in a namespace hierarchy using dots (periods) as
441.25 -separators. For example, a logger named "scan" is the parent of loggers
441.26 -"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
441.27 -and indicate the area of an application in which a logged message originates.
441.28 -
441.29 -Logged messages also have levels of importance associated with them. The default
441.30 -levels provided are :const:`DEBUG`, :const:`INFO`, :const:`WARNING`,
441.31 -:const:`ERROR` and :const:`CRITICAL`. As a convenience, you indicate the
441.32 -importance of a logged message by calling an appropriate method of
441.33 -:class:`Logger`. The methods are :meth:`debug`, :meth:`info`, :meth:`warning`,
441.34 -:meth:`error` and :meth:`critical`, which mirror the default levels. You are not
441.35 -constrained to use these levels: you can specify your own and use a more general
441.36 -:class:`Logger` method, :meth:`log`, which takes an explicit level argument.
441.37 -
441.38 -
441.39 -Logging tutorial
441.40 -----------------
441.41 -
441.42 -The key benefit of having the logging API provided by a standard library module
441.43 -is that all Python modules can participate in logging, so your application log
441.44 -can include messages from third-party modules.
441.45 -
441.46 -It is, of course, possible to log messages with different verbosity levels or to
441.47 -different destinations. Support for writing log messages to files, HTTP
441.48 -GET/POST locations, email via SMTP, generic sockets, or OS-specific logging
441.49 -mechanisms are all supported by the standard module. You can also create your
441.50 -own log destination class if you have special requirements not met by any of the
441.51 -built-in classes.
441.52 -
441.53 -Simple examples
441.54 -^^^^^^^^^^^^^^^
441.55 -
441.56 -.. sectionauthor:: Doug Hellmann
441.57 -.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
441.58 -
441.59 -Most applications are probably going to want to log to a file, so let's start
441.60 -with that case. Using the :func:`basicConfig` function, we can set up the
441.61 -default handler so that debug messages are written to a file::
441.62 -
441.63 - import logging
441.64 - LOG_FILENAME = '/tmp/logging_example.out'
441.65 - logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)
441.66 -
441.67 - logging.debug('This message should go to the log file')
441.68 -
441.69 -And now if we open the file and look at what we have, we should find the log
441.70 -message::
441.71 -
441.72 - DEBUG:root:This message should go to the log file
441.73 -
441.74 -If you run the script repeatedly, the additional log messages are appended to
441.75 -the file. To create a new file each time, you can pass a filemode argument to
441.76 -:func:`basicConfig` with a value of ``'w'``. Rather than managing the file size
441.77 -yourself, though, it is simpler to use a :class:`RotatingFileHandler`::
441.78 -
441.79 - import glob
441.80 - import logging
441.81 - import logging.handlers
441.82 -
441.83 - LOG_FILENAME = '/tmp/logging_rotatingfile_example.out'
441.84 -
441.85 - # Set up a specific logger with our desired output level
441.86 - my_logger = logging.getLogger('MyLogger')
441.87 - my_logger.setLevel(logging.DEBUG)
441.88 -
441.89 - # Add the log message handler to the logger
441.90 - handler = logging.handlers.RotatingFileHandler(
441.91 - LOG_FILENAME, maxBytes=20, backupCount=5)
441.92 -
441.93 - my_logger.addHandler(handler)
441.94 -
441.95 - # Log some messages
441.96 - for i in range(20):
441.97 - my_logger.debug('i = %d' % i)
441.98 -
441.99 - # See what files are created
441.100 - logfiles = glob.glob('%s*' % LOG_FILENAME)
441.101 -
441.102 - for filename in logfiles:
441.103 - print filename
441.104 -
441.105 -The result should be 6 separate files, each with part of the log history for the
441.106 -application::
441.107 -
441.108 - /tmp/logging_rotatingfile_example.out
441.109 - /tmp/logging_rotatingfile_example.out.1
441.110 - /tmp/logging_rotatingfile_example.out.2
441.111 - /tmp/logging_rotatingfile_example.out.3
441.112 - /tmp/logging_rotatingfile_example.out.4
441.113 - /tmp/logging_rotatingfile_example.out.5
441.114 -
441.115 -The most current file is always :file:`/tmp/logging_rotatingfile_example.out`,
441.116 -and each time it reaches the size limit it is renamed with the suffix
441.117 -``.1``. Each of the existing backup files is renamed to increment the suffix
441.118 -(``.1`` becomes ``.2``, etc.) and the ``.5`` file is erased.
441.119 -
441.120 -Obviously this example sets the log length much much too small as an extreme
441.121 -example. You would want to set *maxBytes* to an appropriate value.
441.122 -
441.123 -Another useful feature of the logging API is the ability to produce different
441.124 -messages at different log levels. This allows you to instrument your code with
441.125 -debug messages, for example, but turning the log level down so that those debug
441.126 -messages are not written for your production system. The default levels are
441.127 -``CRITICAL``, ``ERROR``, ``WARNING``, ``INFO``, ``DEBUG`` and ``UNSET``.
441.128 -
441.129 -The logger, handler, and log message call each specify a level. The log message
441.130 -is only emitted if the handler and logger are configured to emit messages of
441.131 -that level or lower. For example, if a message is ``CRITICAL``, and the logger
441.132 -is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
441.133 -the logger is set to produce only ``ERROR``\s, the message is not emitted::
441.134 -
441.135 - import logging
441.136 - import sys
441.137 -
441.138 - LEVELS = {'debug': logging.DEBUG,
441.139 - 'info': logging.INFO,
441.140 - 'warning': logging.WARNING,
441.141 - 'error': logging.ERROR,
441.142 - 'critical': logging.CRITICAL}
441.143 -
441.144 - if len(sys.argv) > 1:
441.145 - level_name = sys.argv[1]
441.146 - level = LEVELS.get(level_name, logging.NOTSET)
441.147 - logging.basicConfig(level=level)
441.148 -
441.149 - logging.debug('This is a debug message')
441.150 - logging.info('This is an info message')
441.151 - logging.warning('This is a warning message')
441.152 - logging.error('This is an error message')
441.153 - logging.critical('This is a critical error message')
441.154 -
441.155 -Run the script with an argument like 'debug' or 'warning' to see which messages
441.156 -show up at different levels::
441.157 -
441.158 - $ python logging_level_example.py debug
441.159 - DEBUG:root:This is a debug message
441.160 - INFO:root:This is an info message
441.161 - WARNING:root:This is a warning message
441.162 - ERROR:root:This is an error message
441.163 - CRITICAL:root:This is a critical error message
441.164 -
441.165 - $ python logging_level_example.py info
441.166 - INFO:root:This is an info message
441.167 - WARNING:root:This is a warning message
441.168 - ERROR:root:This is an error message
441.169 - CRITICAL:root:This is a critical error message
441.170 -
441.171 -You will notice that these log messages all have ``root`` embedded in them. The
441.172 -logging module supports a hierarchy of loggers with different names. An easy
441.173 -way to tell where a specific log message comes from is to use a separate logger
441.174 -object for each of your modules. Each new logger "inherits" the configuration
441.175 -of its parent, and log messages sent to a logger include the name of that
441.176 -logger. Optionally, each logger can be configured differently, so that messages
441.177 -from different modules are handled in different ways. Let's look at a simple
441.178 -example of how to log from different modules so it is easy to trace the source
441.179 -of the message::
441.180 -
441.181 - import logging
441.182 -
441.183 - logging.basicConfig(level=logging.WARNING)
441.184 -
441.185 - logger1 = logging.getLogger('package1.module1')
441.186 - logger2 = logging.getLogger('package2.module2')
441.187 -
441.188 - logger1.warning('This message comes from one module')
441.189 - logger2.warning('And this message comes from another module')
441.190 -
441.191 -And the output::
441.192 -
441.193 - $ python logging_modules_example.py
441.194 - WARNING:package1.module1:This message comes from one module
441.195 - WARNING:package2.module2:And this message comes from another module
441.196 -
441.197 -There are many more options for configuring logging, including different log
441.198 -message formatting options, having messages delivered to multiple destinations,
441.199 -and changing the configuration of a long-running application on the fly using a
441.200 -socket interface. All of these options are covered in depth in the library
441.201 -module documentation.
441.202 -
441.203 -Loggers
441.204 -^^^^^^^
441.205 -
441.206 -The logging library takes a modular approach and offers the several categories
441.207 -of components: loggers, handlers, filters, and formatters. Loggers expose the
441.208 -interface that application code directly uses. Handlers send the log records to
441.209 -the appropriate destination. Filters provide a finer grained facility for
441.210 -determining which log records to send on to a handler. Formatters specify the
441.211 -layout of the resultant log record.
441.212 -
441.213 -:class:`Logger` objects have a threefold job. First, they expose several
441.214 -methods to application code so that applications can log messages at runtime.
441.215 -Second, logger objects determine which log messages to act upon based upon
441.216 -severity (the default filtering facility) or filter objects. Third, logger
441.217 -objects pass along relevant log messages to all interested log handlers.
441.218 -
441.219 -The most widely used methods on logger objects fall into two categories:
441.220 -configuration and message sending.
441.221 -
441.222 -* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
441.223 - will handle, where debug is the lowest built-in severity level and critical is
441.224 - the highest built-in severity. For example, if the severity level is info,
441.225 - the logger will handle only info, warning, error, and critical messages and
441.226 - will ignore debug messages.
441.227 -
441.228 -* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
441.229 - objects from the logger object. This tutorial does not address filters.
441.230 -
441.231 -With the logger object configured, the following methods create log messages:
441.232 -
441.233 -* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
441.234 - :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
441.235 - a message and a level that corresponds to their respective method names. The
441.236 - message is actually a format string, which may contain the standard string
441.237 - substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The
441.238 - rest of their arguments is a list of objects that correspond with the
441.239 - substitution fields in the message. With regard to :const:`**kwargs`, the
441.240 - logging methods care only about a keyword of :const:`exc_info` and use it to
441.241 - determine whether to log exception information.
441.242 -
441.243 -* :meth:`Logger.exception` creates a log message similar to
441.244 - :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a
441.245 - stack trace along with it. Call this method only from an exception handler.
441.246 -
441.247 -* :meth:`Logger.log` takes a log level as an explicit argument. This is a
441.248 - little more verbose for logging messages than using the log level convenience
441.249 - methods listed above, but this is how to log at custom log levels.
441.250 -
441.251 -:func:`getLogger` returns a reference to a logger instance with the specified
441.252 -if it it is provided, or ``root`` if not. The names are period-separated
441.253 -hierarchical structures. Multiple calls to :func:`getLogger` with the same name
441.254 -will return a reference to the same logger object. Loggers that are further
441.255 -down in the hierarchical list are children of loggers higher up in the list.
441.256 -For example, given a logger with a name of ``foo``, loggers with names of
441.257 -``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all children of ``foo``.
441.258 -Child loggers propagate messages up to their parent loggers. Because of this,
441.259 -it is unnecessary to define and configure all the loggers an application uses.
441.260 -It is sufficient to configure a top-level logger and create child loggers as
441.261 -needed.
441.262 -
441.263 -
441.264 -Handlers
441.265 -^^^^^^^^
441.266 -
441.267 -:class:`Handler` objects are responsible for dispatching the appropriate log
441.268 -messages (based on the log messages' severity) to the handler's specified
441.269 -destination. Logger objects can add zero or more handler objects to themselves
441.270 -with an :func:`addHandler` method. As an example scenario, an application may
441.271 -want to send all log messages to a log file, all log messages of error or higher
441.272 -to stdout, and all messages of critical to an email address. This scenario
441.273 -requires three individual handlers where each handler is responsible for sending
441.274 -messages of a specific severity to a specific location.
441.275 -
441.276 -The standard library includes quite a few handler types; this tutorial uses only
441.277 -:class:`StreamHandler` and :class:`FileHandler` in its examples.
441.278 -
441.279 -There are very few methods in a handler for application developers to concern
441.280 -themselves with. The only handler methods that seem relevant for application
441.281 -developers who are using the built-in handler objects (that is, not creating
441.282 -custom handlers) are the following configuration methods:
441.283 -
441.284 -* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
441.285 - lowest severity that will be dispatched to the appropriate destination. Why
441.286 - are there two :func:`setLevel` methods? The level set in the logger
441.287 - determines which severity of messages it will pass to its handlers. The level
441.288 - set in each handler determines which messages that handler will send on.
441.289 - :func:`setFormatter` selects a Formatter object for this handler to use.
441.290 -
441.291 -* :func:`addFilter` and :func:`removeFilter` respectively configure and
441.292 - deconfigure filter objects on handlers.
441.293 -
441.294 -Application code should not directly instantiate and use handlers. Instead, the
441.295 -:class:`Handler` class is a base class that defines the interface that all
441.296 -Handlers should have and establishes some default behavior that child classes
441.297 -can use (or override).
441.298 -
441.299 -
441.300 -Formatters
441.301 -^^^^^^^^^^
441.302 -
441.303 -Formatter objects configure the final order, structure, and contents of the log
441.304 -message. Unlike the base :class:`logging.Handler` class, application code may
441.305 -instantiate formatter classes, although you could likely subclass the formatter
441.306 -if your application needs special behavior. The constructor takes two optional
441.307 -arguments: a message format string and a date format string. If there is no
441.308 -message format string, the default is to use the raw message. If there is no
441.309 -date format string, the default date format is::
441.310 -
441.311 - %Y-%m-%d %H:%M:%S
441.312 -
441.313 -with the milliseconds tacked on at the end.
441.314 -
441.315 -The message format string uses ``%(<dictionary key>)s`` styled string
441.316 -substitution; the possible keys are documented in :ref:`formatter-objects`.
441.317 -
441.318 -The following message format string will log the time in a human-readable
441.319 -format, the severity of the message, and the contents of the message, in that
441.320 -order::
441.321 -
441.322 - "%(asctime)s - %(levelname)s - %(message)s"
441.323 -
441.324 -
441.325 -Configuring Logging
441.326 -^^^^^^^^^^^^^^^^^^^
441.327 -
441.328 -Programmers can configure logging either by creating loggers, handlers, and
441.329 -formatters explicitly in a main module with the configuration methods listed
441.330 -above (using Python code), or by creating a logging config file. The following
441.331 -code is an example of configuring a very simple logger, a console handler, and a
441.332 -simple formatter in a Python module::
441.333 -
441.334 - import logging
441.335 -
441.336 - # create logger
441.337 - logger = logging.getLogger("simple_example")
441.338 - logger.setLevel(logging.DEBUG)
441.339 - # create console handler and set level to debug
441.340 - ch = logging.StreamHandler()
441.341 - ch.setLevel(logging.DEBUG)
441.342 - # create formatter
441.343 - formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
441.344 - # add formatter to ch
441.345 - ch.setFormatter(formatter)
441.346 - # add ch to logger
441.347 - logger.addHandler(ch)
441.348 -
441.349 - # "application" code
441.350 - logger.debug("debug message")
441.351 - logger.info("info message")
441.352 - logger.warn("warn message")
441.353 - logger.error("error message")
441.354 - logger.critical("critical message")
441.355 -
441.356 -Running this module from the command line produces the following output::
441.357 -
441.358 - $ python simple_logging_module.py
441.359 - 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
441.360 - 2005-03-19 15:10:26,620 - simple_example - INFO - info message
441.361 - 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
441.362 - 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
441.363 - 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
441.364 -
441.365 -The following Python module creates a logger, handler, and formatter nearly
441.366 -identical to those in the example listed above, with the only difference being
441.367 -the names of the objects::
441.368 -
441.369 - import logging
441.370 - import logging.config
441.371 -
441.372 - logging.config.fileConfig("logging.conf")
441.373 -
441.374 - # create logger
441.375 - logger = logging.getLogger("simpleExample")
441.376 -
441.377 - # "application" code
441.378 - logger.debug("debug message")
441.379 - logger.info("info message")
441.380 - logger.warn("warn message")
441.381 - logger.error("error message")
441.382 - logger.critical("critical message")
441.383 -
441.384 -Here is the logging.conf file::
441.385 -
441.386 - [loggers]
441.387 - keys=root,simpleExample
441.388 -
441.389 - [handlers]
441.390 - keys=consoleHandler
441.391 -
441.392 - [formatters]
441.393 - keys=simpleFormatter
441.394 -
441.395 - [logger_root]
441.396 - level=DEBUG
441.397 - handlers=consoleHandler
441.398 -
441.399 - [logger_simpleExample]
441.400 - level=DEBUG
441.401 - handlers=consoleHandler
441.402 - qualname=simpleExample
441.403 - propagate=0
441.404 -
441.405 - [handler_consoleHandler]
441.406 - class=StreamHandler
441.407 - level=DEBUG
441.408 - formatter=simpleFormatter
441.409 - args=(sys.stdout,)
441.410 -
441.411 - [formatter_simpleFormatter]
441.412 - format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
441.413 - datefmt=
441.414 -
441.415 -The output is nearly identical to that of the non-config-file-based example::
441.416 -
441.417 - $ python simple_logging_config.py
441.418 - 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
441.419 - 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
441.420 - 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
441.421 - 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
441.422 - 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
441.423 -
441.424 -You can see that the config file approach has a few advantages over the Python
441.425 -code approach, mainly separation of configuration and code and the ability of
441.426 -noncoders to easily modify the logging properties.
441.427 -
441.428 -Configuring Logging for a Library
441.429 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
441.430 -
441.431 -When developing a library which uses logging, some consideration needs to be
441.432 -given to its configuration. If the using application does not use logging, and
441.433 -library code makes logging calls, then a one-off message "No handlers could be
441.434 -found for logger X.Y.Z" is printed to the console. This message is intended
441.435 -to catch mistakes in logging configuration, but will confuse an application
441.436 -developer who is not aware of logging by the library.
441.437 -
441.438 -In addition to documenting how a library uses logging, a good way to configure
441.439 -library logging so that it does not cause a spurious message is to add a
441.440 -handler which does nothing. This avoids the message being printed, since a
441.441 -handler will be found: it just doesn't produce any output. If the library user
441.442 -configures logging for application use, presumably that configuration will add
441.443 -some handlers, and if levels are suitably configured then logging calls made
441.444 -in library code will send output to those handlers, as normal.
441.445 -
441.446 -A do-nothing handler can be simply defined as follows::
441.447 -
441.448 - import logging
441.449 -
441.450 - class NullHandler(logging.Handler):
441.451 - def emit(self, record):
441.452 - pass
441.453 -
441.454 -An instance of this handler should be added to the top-level logger of the
441.455 -logging namespace used by the library. If all logging by a library *foo* is
441.456 -done using loggers with names matching "foo.x.y", then the code::
441.457 -
441.458 - import logging
441.459 -
441.460 - h = NullHandler()
441.461 - logging.getLogger("foo").addHandler(h)
441.462 -
441.463 -should have the desired effect. If an organisation produces a number of
441.464 -libraries, then the logger name specified can be "orgname.foo" rather than
441.465 -just "foo".
441.466 -
441.467 -
441.468 -Logging Levels
441.469 ---------------
441.470 -
441.471 -The numeric values of logging levels are given in the following table. These are
441.472 -primarily of interest if you want to define your own levels, and need them to
441.473 -have specific values relative to the predefined levels. If you define a level
441.474 -with the same numeric value, it overwrites the predefined value; the predefined
441.475 -name is lost.
441.476 -
441.477 -+--------------+---------------+
441.478 -| Level | Numeric value |
441.479 -+==============+===============+
441.480 -| ``CRITICAL`` | 50 |
441.481 -+--------------+---------------+
441.482 -| ``ERROR`` | 40 |
441.483 -+--------------+---------------+
441.484 -| ``WARNING`` | 30 |
441.485 -+--------------+---------------+
441.486 -| ``INFO`` | 20 |
441.487 -+--------------+---------------+
441.488 -| ``DEBUG`` | 10 |
441.489 -+--------------+---------------+
441.490 -| ``NOTSET`` | 0 |
441.491 -+--------------+---------------+
441.492 -
441.493 -Levels can also be associated with loggers, being set either by the developer or
441.494 -through loading a saved logging configuration. When a logging method is called
441.495 -on a logger, the logger compares its own level with the level associated with
441.496 -the method call. If the logger's level is higher than the method call's, no
441.497 -logging message is actually generated. This is the basic mechanism controlling
441.498 -the verbosity of logging output.
441.499 -
441.500 -Logging messages are encoded as instances of the :class:`LogRecord` class. When
441.501 -a logger decides to actually log an event, a :class:`LogRecord` instance is
441.502 -created from the logging message.
441.503 -
441.504 -Logging messages are subjected to a dispatch mechanism through the use of
441.505 -:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
441.506 -class. Handlers are responsible for ensuring that a logged message (in the form
441.507 -of a :class:`LogRecord`) ends up in a particular location (or set of locations)
441.508 -which is useful for the target audience for that message (such as end users,
441.509 -support desk staff, system administrators, developers). Handlers are passed
441.510 -:class:`LogRecord` instances intended for particular destinations. Each logger
441.511 -can have zero, one or more handlers associated with it (via the
441.512 -:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
441.513 -directly associated with a logger, *all handlers associated with all ancestors
441.514 -of the logger* are called to dispatch the message.
441.515 -
441.516 -Just as for loggers, handlers can have levels associated with them. A handler's
441.517 -level acts as a filter in the same way as a logger's level does. If a handler
441.518 -decides to actually dispatch an event, the :meth:`emit` method is used to send
441.519 -the message to its destination. Most user-defined subclasses of :class:`Handler`
441.520 -will need to override this :meth:`emit`.
441.521 -
441.522 -In addition to the base :class:`Handler` class, many useful subclasses are
441.523 -provided:
441.524 -
441.525 -#. :class:`StreamHandler` instances send error messages to streams (file-like
441.526 - objects).
441.527 -
441.528 -#. :class:`FileHandler` instances send error messages to disk files.
441.529 -
441.530 -#. :class:`BaseRotatingHandler` is the base class for handlers that rotate log
441.531 - files at a certain point. It is not meant to be instantiated directly. Instead,
441.532 - use :class:`RotatingFileHandler` or :class:`TimedRotatingFileHandler`.
441.533 -
441.534 -#. :class:`RotatingFileHandler` instances send error messages to disk files,
441.535 - with support for maximum log file sizes and log file rotation.
441.536 -
441.537 -#. :class:`TimedRotatingFileHandler` instances send error messages to disk files
441.538 - rotating the log file at certain timed intervals.
441.539 -
441.540 -#. :class:`SocketHandler` instances send error messages to TCP/IP sockets.
441.541 -
441.542 -#. :class:`DatagramHandler` instances send error messages to UDP sockets.
441.543 -
441.544 -#. :class:`SMTPHandler` instances send error messages to a designated email
441.545 - address.
441.546 -
441.547 -#. :class:`SysLogHandler` instances send error messages to a Unix syslog daemon,
441.548 - possibly on a remote machine.
441.549 -
441.550 -#. :class:`NTEventLogHandler` instances send error messages to a Windows
441.551 - NT/2000/XP event log.
441.552 -
441.553 -#. :class:`MemoryHandler` instances send error messages to a buffer in memory,
441.554 - which is flushed whenever specific criteria are met.
441.555 -
441.556 -#. :class:`HTTPHandler` instances send error messages to an HTTP server using
441.557 - either ``GET`` or ``POST`` semantics.
441.558 -
441.559 -The :class:`StreamHandler` and :class:`FileHandler` classes are defined in the
441.560 -core logging package. The other handlers are defined in a sub- module,
441.561 -:mod:`logging.handlers`. (There is also another sub-module,
441.562 -:mod:`logging.config`, for configuration functionality.)
441.563 -
441.564 -Logged messages are formatted for presentation through instances of the
441.565 -:class:`Formatter` class. They are initialized with a format string suitable for
441.566 -use with the % operator and a dictionary.
441.567 -
441.568 -For formatting multiple messages in a batch, instances of
441.569 -:class:`BufferingFormatter` can be used. In addition to the format string (which
441.570 -is applied to each message in the batch), there is provision for header and
441.571 -trailer format strings.
441.572 -
441.573 -When filtering based on logger level and/or handler level is not enough,
441.574 -instances of :class:`Filter` can be added to both :class:`Logger` and
441.575 -:class:`Handler` instances (through their :meth:`addFilter` method). Before
441.576 -deciding to process a message further, both loggers and handlers consult all
441.577 -their filters for permission. If any filter returns a false value, the message
441.578 -is not processed further.
441.579 -
441.580 -The basic :class:`Filter` functionality allows filtering by specific logger
441.581 -name. If this feature is used, messages sent to the named logger and its
441.582 -children are allowed through the filter, and all others dropped.
441.583 -
441.584 -In addition to the classes described above, there are a number of module- level
441.585 -functions.
441.586 -
441.587 -
441.588 -.. function:: getLogger([name])
441.589 -
441.590 - Return a logger with the specified name or, if no name is specified, return a
441.591 - logger which is the root logger of the hierarchy. If specified, the name is
441.592 - typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
441.593 - Choice of these names is entirely up to the developer who is using logging.
441.594 -
441.595 - All calls to this function with a given name return the same logger instance.
441.596 - This means that logger instances never need to be passed between different parts
441.597 - of an application.
441.598 -
441.599 -
441.600 -.. function:: getLoggerClass()
441.601 -
441.602 - Return either the standard :class:`Logger` class, or the last class passed to
441.603 - :func:`setLoggerClass`. This function may be called from within a new class
441.604 - definition, to ensure that installing a customised :class:`Logger` class will
441.605 - not undo customisations already applied by other code. For example::
441.606 -
441.607 - class MyLogger(logging.getLoggerClass()):
441.608 - # ... override behaviour here
441.609 -
441.610 -
441.611 -.. function:: debug(msg[, *args[, **kwargs]])
441.612 -
441.613 - Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
441.614 - message format string, and the *args* are the arguments which are merged into
441.615 - *msg* using the string formatting operator. (Note that this means that you can
441.616 - use keywords in the format string, together with a single dictionary argument.)
441.617 -
441.618 - There are two keyword arguments in *kwargs* which are inspected: *exc_info*
441.619 - which, if it does not evaluate as false, causes exception information to be
441.620 - added to the logging message. If an exception tuple (in the format returned by
441.621 - :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
441.622 - is called to get the exception information.
441.623 -
441.624 - The other optional keyword argument is *extra* which can be used to pass a
441.625 - dictionary which is used to populate the __dict__ of the LogRecord created for
441.626 - the logging event with user-defined attributes. These custom attributes can then
441.627 - be used as you like. For example, they could be incorporated into logged
441.628 - messages. For example::
441.629 -
441.630 - FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
441.631 - logging.basicConfig(format=FORMAT)
441.632 - d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
441.633 - logging.warning("Protocol problem: %s", "connection reset", extra=d)
441.634 -
441.635 - would print something like ::
441.636 -
441.637 - 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
441.638 -
441.639 - The keys in the dictionary passed in *extra* should not clash with the keys used
441.640 - by the logging system. (See the :class:`Formatter` documentation for more
441.641 - information on which keys are used by the logging system.)
441.642 -
441.643 - If you choose to use these attributes in logged messages, you need to exercise
441.644 - some care. In the above example, for instance, the :class:`Formatter` has been
441.645 - set up with a format string which expects 'clientip' and 'user' in the attribute
441.646 - dictionary of the LogRecord. If these are missing, the message will not be
441.647 - logged because a string formatting exception will occur. So in this case, you
441.648 - always need to pass the *extra* dictionary with these keys.
441.649 -
441.650 - While this might be annoying, this feature is intended for use in specialized
441.651 - circumstances, such as multi-threaded servers where the same code executes in
441.652 - many contexts, and interesting conditions which arise are dependent on this
441.653 - context (such as remote client IP address and authenticated user name, in the
441.654 - above example). In such circumstances, it is likely that specialized
441.655 - :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
441.656 -
441.657 - .. versionchanged:: 2.5
441.658 - *extra* was added.
441.659 -
441.660 -
441.661 -.. function:: info(msg[, *args[, **kwargs]])
441.662 -
441.663 - Logs a message with level :const:`INFO` on the root logger. The arguments are
441.664 - interpreted as for :func:`debug`.
441.665 -
441.666 -
441.667 -.. function:: warning(msg[, *args[, **kwargs]])
441.668 -
441.669 - Logs a message with level :const:`WARNING` on the root logger. The arguments are
441.670 - interpreted as for :func:`debug`.
441.671 -
441.672 -
441.673 -.. function:: error(msg[, *args[, **kwargs]])
441.674 -
441.675 - Logs a message with level :const:`ERROR` on the root logger. The arguments are
441.676 - interpreted as for :func:`debug`.
441.677 -
441.678 -
441.679 -.. function:: critical(msg[, *args[, **kwargs]])
441.680 -
441.681 - Logs a message with level :const:`CRITICAL` on the root logger. The arguments
441.682 - are interpreted as for :func:`debug`.
441.683 -
441.684 -
441.685 -.. function:: exception(msg[, *args])
441.686 -
441.687 - Logs a message with level :const:`ERROR` on the root logger. The arguments are
441.688 - interpreted as for :func:`debug`. Exception info is added to the logging
441.689 - message. This function should only be called from an exception handler.
441.690 -
441.691 -
441.692 -.. function:: log(level, msg[, *args[, **kwargs]])
441.693 -
441.694 - Logs a message with level *level* on the root logger. The other arguments are
441.695 - interpreted as for :func:`debug`.
441.696 -
441.697 -
441.698 -.. function:: disable(lvl)
441.699 -
441.700 - Provides an overriding level *lvl* for all loggers which takes precedence over
441.701 - the logger's own level. When the need arises to temporarily throttle logging
441.702 - output down across the whole application, this function can be useful.
441.703 -
441.704 -
441.705 -.. function:: addLevelName(lvl, levelName)
441.706 -
441.707 - Associates level *lvl* with text *levelName* in an internal dictionary, which is
441.708 - used to map numeric levels to a textual representation, for example when a
441.709 - :class:`Formatter` formats a message. This function can also be used to define
441.710 - your own levels. The only constraints are that all levels used must be
441.711 - registered using this function, levels should be positive integers and they
441.712 - should increase in increasing order of severity.
441.713 -
441.714 -
441.715 -.. function:: getLevelName(lvl)
441.716 -
441.717 - Returns the textual representation of logging level *lvl*. If the level is one
441.718 - of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
441.719 - :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
441.720 - have associated levels with names using :func:`addLevelName` then the name you
441.721 - have associated with *lvl* is returned. If a numeric value corresponding to one
441.722 - of the defined levels is passed in, the corresponding string representation is
441.723 - returned. Otherwise, the string "Level %s" % lvl is returned.
441.724 -
441.725 -
441.726 -.. function:: makeLogRecord(attrdict)
441.727 -
441.728 - Creates and returns a new :class:`LogRecord` instance whose attributes are
441.729 - defined by *attrdict*. This function is useful for taking a pickled
441.730 - :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
441.731 - it as a :class:`LogRecord` instance at the receiving end.
441.732 -
441.733 -
441.734 -.. function:: basicConfig([**kwargs])
441.735 -
441.736 - Does basic configuration for the logging system by creating a
441.737 - :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
441.738 - root logger. The function does nothing if any handlers have been defined for
441.739 - the root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
441.740 - :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
441.741 - if no handlers are defined for the root logger.
441.742 -
441.743 - This function does nothing if the root logger already has handlers configured.
441.744 -
441.745 - .. versionchanged:: 2.4
441.746 - Formerly, :func:`basicConfig` did not take any keyword arguments.
441.747 -
441.748 - The following keyword arguments are supported.
441.749 -
441.750 - +--------------+---------------------------------------------+
441.751 - | Format | Description |
441.752 - +==============+=============================================+
441.753 - | ``filename`` | Specifies that a FileHandler be created, |
441.754 - | | using the specified filename, rather than a |
441.755 - | | StreamHandler. |
441.756 - +--------------+---------------------------------------------+
441.757 - | ``filemode`` | Specifies the mode to open the file, if |
441.758 - | | filename is specified (if filemode is |
441.759 - | | unspecified, it defaults to 'a'). |
441.760 - +--------------+---------------------------------------------+
441.761 - | ``format`` | Use the specified format string for the |
441.762 - | | handler. |
441.763 - +--------------+---------------------------------------------+
441.764 - | ``datefmt`` | Use the specified date/time format. |
441.765 - +--------------+---------------------------------------------+
441.766 - | ``level`` | Set the root logger level to the specified |
441.767 - | | level. |
441.768 - +--------------+---------------------------------------------+
441.769 - | ``stream`` | Use the specified stream to initialize the |
441.770 - | | StreamHandler. Note that this argument is |
441.771 - | | incompatible with 'filename' - if both are |
441.772 - | | present, 'stream' is ignored. |
441.773 - +--------------+---------------------------------------------+
441.774 -
441.775 -
441.776 -.. function:: shutdown()
441.777 -
441.778 - Informs the logging system to perform an orderly shutdown by flushing and
441.779 - closing all handlers. This should be called at application exit and no
441.780 - further use of the logging system should be made after this call.
441.781 -
441.782 -
441.783 -.. function:: setLoggerClass(klass)
441.784 -
441.785 - Tells the logging system to use the class *klass* when instantiating a logger.
441.786 - The class should define :meth:`__init__` such that only a name argument is
441.787 - required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
441.788 - function is typically called before any loggers are instantiated by applications
441.789 - which need to use custom logger behavior.
441.790 -
441.791 -
441.792 -.. seealso::
441.793 -
441.794 - :pep:`282` - A Logging System
441.795 - The proposal which described this feature for inclusion in the Python standard
441.796 - library.
441.797 -
441.798 - `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
441.799 - This is the original source for the :mod:`logging` package. The version of the
441.800 - package available from this site is suitable for use with Python 1.5.2, 2.1.x
441.801 - and 2.2.x, which do not include the :mod:`logging` package in the standard
441.802 - library.
441.803 -
441.804 -
441.805 -Logger Objects
441.806 ---------------
441.807 -
441.808 -Loggers have the following attributes and methods. Note that Loggers are never
441.809 -instantiated directly, but always through the module-level function
441.810 -``logging.getLogger(name)``.
441.811 -
441.812 -
441.813 -.. attribute:: Logger.propagate
441.814 -
441.815 - If this evaluates to false, logging messages are not passed by this logger or by
441.816 - child loggers to higher level (ancestor) loggers. The constructor sets this
441.817 - attribute to 1.
441.818 -
441.819 -
441.820 -.. method:: Logger.setLevel(lvl)
441.821 -
441.822 - Sets the threshold for this logger to *lvl*. Logging messages which are less
441.823 - severe than *lvl* will be ignored. When a logger is created, the level is set to
441.824 - :const:`NOTSET` (which causes all messages to be processed when the logger is
441.825 - the root logger, or delegation to the parent when the logger is a non-root
441.826 - logger). Note that the root logger is created with level :const:`WARNING`.
441.827 -
441.828 - The term "delegation to the parent" means that if a logger has a level of
441.829 - NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
441.830 - a level other than NOTSET is found, or the root is reached.
441.831 -
441.832 - If an ancestor is found with a level other than NOTSET, then that ancestor's
441.833 - level is treated as the effective level of the logger where the ancestor search
441.834 - began, and is used to determine how a logging event is handled.
441.835 -
441.836 - If the root is reached, and it has a level of NOTSET, then all messages will be
441.837 - processed. Otherwise, the root's level will be used as the effective level.
441.838 -
441.839 -
441.840 -.. method:: Logger.isEnabledFor(lvl)
441.841 -
441.842 - Indicates if a message of severity *lvl* would be processed by this logger.
441.843 - This method checks first the module-level level set by
441.844 - ``logging.disable(lvl)`` and then the logger's effective level as determined
441.845 - by :meth:`getEffectiveLevel`.
441.846 -
441.847 -
441.848 -.. method:: Logger.getEffectiveLevel()
441.849 -
441.850 - Indicates the effective level for this logger. If a value other than
441.851 - :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
441.852 - the hierarchy is traversed towards the root until a value other than
441.853 - :const:`NOTSET` is found, and that value is returned.
441.854 -
441.855 -
441.856 -.. method:: Logger.debug(msg[, *args[, **kwargs]])
441.857 -
441.858 - Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
441.859 - message format string, and the *args* are the arguments which are merged into
441.860 - *msg* using the string formatting operator. (Note that this means that you can
441.861 - use keywords in the format string, together with a single dictionary argument.)
441.862 -
441.863 - There are two keyword arguments in *kwargs* which are inspected: *exc_info*
441.864 - which, if it does not evaluate as false, causes exception information to be
441.865 - added to the logging message. If an exception tuple (in the format returned by
441.866 - :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
441.867 - is called to get the exception information.
441.868 -
441.869 - The other optional keyword argument is *extra* which can be used to pass a
441.870 - dictionary which is used to populate the __dict__ of the LogRecord created for
441.871 - the logging event with user-defined attributes. These custom attributes can then
441.872 - be used as you like. For example, they could be incorporated into logged
441.873 - messages. For example::
441.874 -
441.875 - FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
441.876 - logging.basicConfig(format=FORMAT)
441.877 - d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
441.878 - logger = logging.getLogger("tcpserver")
441.879 - logger.warning("Protocol problem: %s", "connection reset", extra=d)
441.880 -
441.881 - would print something like ::
441.882 -
441.883 - 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
441.884 -
441.885 - The keys in the dictionary passed in *extra* should not clash with the keys used
441.886 - by the logging system. (See the :class:`Formatter` documentation for more
441.887 - information on which keys are used by the logging system.)
441.888 -
441.889 - If you choose to use these attributes in logged messages, you need to exercise
441.890 - some care. In the above example, for instance, the :class:`Formatter` has been
441.891 - set up with a format string which expects 'clientip' and 'user' in the attribute
441.892 - dictionary of the LogRecord. If these are missing, the message will not be
441.893 - logged because a string formatting exception will occur. So in this case, you
441.894 - always need to pass the *extra* dictionary with these keys.
441.895 -
441.896 - While this might be annoying, this feature is intended for use in specialized
441.897 - circumstances, such as multi-threaded servers where the same code executes in
441.898 - many contexts, and interesting conditions which arise are dependent on this
441.899 - context (such as remote client IP address and authenticated user name, in the
441.900 - above example). In such circumstances, it is likely that specialized
441.901 - :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
441.902 -
441.903 - .. versionchanged:: 2.5
441.904 - *extra* was added.
441.905 -
441.906 -
441.907 -.. method:: Logger.info(msg[, *args[, **kwargs]])
441.908 -
441.909 - Logs a message with level :const:`INFO` on this logger. The arguments are
441.910 - interpreted as for :meth:`debug`.
441.911 -
441.912 -
441.913 -.. method:: Logger.warning(msg[, *args[, **kwargs]])
441.914 -
441.915 - Logs a message with level :const:`WARNING` on this logger. The arguments are
441.916 - interpreted as for :meth:`debug`.
441.917 -
441.918 -
441.919 -.. method:: Logger.error(msg[, *args[, **kwargs]])
441.920 -
441.921 - Logs a message with level :const:`ERROR` on this logger. The arguments are
441.922 - interpreted as for :meth:`debug`.
441.923 -
441.924 -
441.925 -.. method:: Logger.critical(msg[, *args[, **kwargs]])
441.926 -
441.927 - Logs a message with level :const:`CRITICAL` on this logger. The arguments are
441.928 - interpreted as for :meth:`debug`.
441.929 -
441.930 -
441.931 -.. method:: Logger.log(lvl, msg[, *args[, **kwargs]])
441.932 -
441.933 - Logs a message with integer level *lvl* on this logger. The other arguments are
441.934 - interpreted as for :meth:`debug`.
441.935 -
441.936 -
441.937 -.. method:: Logger.exception(msg[, *args])
441.938 -
441.939 - Logs a message with level :const:`ERROR` on this logger. The arguments are
441.940 - interpreted as for :meth:`debug`. Exception info is added to the logging
441.941 - message. This method should only be called from an exception handler.
441.942 -
441.943 -
441.944 -.. method:: Logger.addFilter(filt)
441.945 -
441.946 - Adds the specified filter *filt* to this logger.
441.947 -
441.948 -
441.949 -.. method:: Logger.removeFilter(filt)
441.950 -
441.951 - Removes the specified filter *filt* from this logger.
441.952 -
441.953 -
441.954 -.. method:: Logger.filter(record)
441.955 -
441.956 - Applies this logger's filters to the record and returns a true value if the
441.957 - record is to be processed.
441.958 -
441.959 -
441.960 -.. method:: Logger.addHandler(hdlr)
441.961 -
441.962 - Adds the specified handler *hdlr* to this logger.
441.963 -
441.964 -
441.965 -.. method:: Logger.removeHandler(hdlr)
441.966 -
441.967 - Removes the specified handler *hdlr* from this logger.
441.968 -
441.969 -
441.970 -.. method:: Logger.findCaller()
441.971 -
441.972 - Finds the caller's source filename and line number. Returns the filename, line
441.973 - number and function name as a 3-element tuple.
441.974 -
441.975 - .. versionchanged:: 2.4
441.976 - The function name was added. In earlier versions, the filename and line number
441.977 - were returned as a 2-element tuple..
441.978 -
441.979 -
441.980 -.. method:: Logger.handle(record)
441.981 -
441.982 - Handles a record by passing it to all handlers associated with this logger and
441.983 - its ancestors (until a false value of *propagate* is found). This method is used
441.984 - for unpickled records received from a socket, as well as those created locally.
441.985 - Logger-level filtering is applied using :meth:`filter`.
441.986 -
441.987 -
441.988 -.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info [, func, extra])
441.989 -
441.990 - This is a factory method which can be overridden in subclasses to create
441.991 - specialized :class:`LogRecord` instances.
441.992 -
441.993 - .. versionchanged:: 2.5
441.994 - *func* and *extra* were added.
441.995 -
441.996 -
441.997 -.. _minimal-example:
441.998 -
441.999 -Basic example
441.1000 --------------
441.1001 -
441.1002 -.. versionchanged:: 2.4
441.1003 - formerly :func:`basicConfig` did not take any keyword arguments.
441.1004 -
441.1005 -The :mod:`logging` package provides a lot of flexibility, and its configuration
441.1006 -can appear daunting. This section demonstrates that simple use of the logging
441.1007 -package is possible.
441.1008 -
441.1009 -The simplest example shows logging to the console::
441.1010 -
441.1011 - import logging
441.1012 -
441.1013 - logging.debug('A debug message')
441.1014 - logging.info('Some information')
441.1015 - logging.warning('A shot across the bows')
441.1016 -
441.1017 -If you run the above script, you'll see this::
441.1018 -
441.1019 - WARNING:root:A shot across the bows
441.1020 -
441.1021 -Because no particular logger was specified, the system used the root logger. The
441.1022 -debug and info messages didn't appear because by default, the root logger is
441.1023 -configured to only handle messages with a severity of WARNING or above. The
441.1024 -message format is also a configuration default, as is the output destination of
441.1025 -the messages - ``sys.stderr``. The severity level, the message format and
441.1026 -destination can be easily changed, as shown in the example below::
441.1027 -
441.1028 - import logging
441.1029 -
441.1030 - logging.basicConfig(level=logging.DEBUG,
441.1031 - format='%(asctime)s %(levelname)s %(message)s',
441.1032 - filename='/tmp/myapp.log',
441.1033 - filemode='w')
441.1034 - logging.debug('A debug message')
441.1035 - logging.info('Some information')
441.1036 - logging.warning('A shot across the bows')
441.1037 -
441.1038 -The :meth:`basicConfig` method is used to change the configuration defaults,
441.1039 -which results in output (written to ``/tmp/myapp.log``) which should look
441.1040 -something like the following::
441.1041 -
441.1042 - 2004-07-02 13:00:08,743 DEBUG A debug message
441.1043 - 2004-07-02 13:00:08,743 INFO Some information
441.1044 - 2004-07-02 13:00:08,743 WARNING A shot across the bows
441.1045 -
441.1046 -This time, all messages with a severity of DEBUG or above were handled, and the
441.1047 -format of the messages was also changed, and output went to the specified file
441.1048 -rather than the console.
441.1049 -
441.1050 -Formatting uses standard Python string formatting - see section
441.1051 -:ref:`string-formatting`. The format string takes the following common
441.1052 -specifiers. For a complete list of specifiers, consult the :class:`Formatter`
441.1053 -documentation.
441.1054 -
441.1055 -+-------------------+-----------------------------------------------+
441.1056 -| Format | Description |
441.1057 -+===================+===============================================+
441.1058 -| ``%(name)s`` | Name of the logger (logging channel). |
441.1059 -+-------------------+-----------------------------------------------+
441.1060 -| ``%(levelname)s`` | Text logging level for the message |
441.1061 -| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
441.1062 -| | ``'ERROR'``, ``'CRITICAL'``). |
441.1063 -+-------------------+-----------------------------------------------+
441.1064 -| ``%(asctime)s`` | Human-readable time when the |
441.1065 -| | :class:`LogRecord` was created. By default |
441.1066 -| | this is of the form "2003-07-08 16:49:45,896" |
441.1067 -| | (the numbers after the comma are millisecond |
441.1068 -| | portion of the time). |
441.1069 -+-------------------+-----------------------------------------------+
441.1070 -| ``%(message)s`` | The logged message. |
441.1071 -+-------------------+-----------------------------------------------+
441.1072 -
441.1073 -To change the date/time format, you can pass an additional keyword parameter,
441.1074 -*datefmt*, as in the following::
441.1075 -
441.1076 - import logging
441.1077 -
441.1078 - logging.basicConfig(level=logging.DEBUG,
441.1079 - format='%(asctime)s %(levelname)-8s %(message)s',
441.1080 - datefmt='%a, %d %b %Y %H:%M:%S',
441.1081 - filename='/temp/myapp.log',
441.1082 - filemode='w')
441.1083 - logging.debug('A debug message')
441.1084 - logging.info('Some information')
441.1085 - logging.warning('A shot across the bows')
441.1086 -
441.1087 -which would result in output like ::
441.1088 -
441.1089 - Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
441.1090 - Fri, 02 Jul 2004 13:06:18 INFO Some information
441.1091 - Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
441.1092 -
441.1093 -The date format string follows the requirements of :func:`strftime` - see the
441.1094 -documentation for the :mod:`time` module.
441.1095 -
441.1096 -If, instead of sending logging output to the console or a file, you'd rather use
441.1097 -a file-like object which you have created separately, you can pass it to
441.1098 -:func:`basicConfig` using the *stream* keyword argument. Note that if both
441.1099 -*stream* and *filename* keyword arguments are passed, the *stream* argument is
441.1100 -ignored.
441.1101 -
441.1102 -Of course, you can put variable information in your output. To do this, simply
441.1103 -have the message be a format string and pass in additional arguments containing
441.1104 -the variable information, as in the following example::
441.1105 -
441.1106 - import logging
441.1107 -
441.1108 - logging.basicConfig(level=logging.DEBUG,
441.1109 - format='%(asctime)s %(levelname)-8s %(message)s',
441.1110 - datefmt='%a, %d %b %Y %H:%M:%S',
441.1111 - filename='/temp/myapp.log',
441.1112 - filemode='w')
441.1113 - logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
441.1114 -
441.1115 -which would result in ::
441.1116 -
441.1117 - Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
441.1118 -
441.1119 -
441.1120 -.. _multiple-destinations:
441.1121 -
441.1122 -Logging to multiple destinations
441.1123 ---------------------------------
441.1124 -
441.1125 -Let's say you want to log to console and file with different message formats and
441.1126 -in differing circumstances. Say you want to log messages with levels of DEBUG
441.1127 -and higher to file, and those messages at level INFO and higher to the console.
441.1128 -Let's also assume that the file should contain timestamps, but the console
441.1129 -messages should not. Here's how you can achieve this::
441.1130 -
441.1131 - import logging
441.1132 -
441.1133 - # set up logging to file - see previous section for more details
441.1134 - logging.basicConfig(level=logging.DEBUG,
441.1135 - format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
441.1136 - datefmt='%m-%d %H:%M',
441.1137 - filename='/temp/myapp.log',
441.1138 - filemode='w')
441.1139 - # define a Handler which writes INFO messages or higher to the sys.stderr
441.1140 - console = logging.StreamHandler()
441.1141 - console.setLevel(logging.INFO)
441.1142 - # set a format which is simpler for console use
441.1143 - formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
441.1144 - # tell the handler to use this format
441.1145 - console.setFormatter(formatter)
441.1146 - # add the handler to the root logger
441.1147 - logging.getLogger('').addHandler(console)
441.1148 -
441.1149 - # Now, we can log to the root logger, or any other logger. First the root...
441.1150 - logging.info('Jackdaws love my big sphinx of quartz.')
441.1151 -
441.1152 - # Now, define a couple of other loggers which might represent areas in your
441.1153 - # application:
441.1154 -
441.1155 - logger1 = logging.getLogger('myapp.area1')
441.1156 - logger2 = logging.getLogger('myapp.area2')
441.1157 -
441.1158 - logger1.debug('Quick zephyrs blow, vexing daft Jim.')
441.1159 - logger1.info('How quickly daft jumping zebras vex.')
441.1160 - logger2.warning('Jail zesty vixen who grabbed pay from quack.')
441.1161 - logger2.error('The five boxing wizards jump quickly.')
441.1162 -
441.1163 -When you run this, on the console you will see ::
441.1164 -
441.1165 - root : INFO Jackdaws love my big sphinx of quartz.
441.1166 - myapp.area1 : INFO How quickly daft jumping zebras vex.
441.1167 - myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
441.1168 - myapp.area2 : ERROR The five boxing wizards jump quickly.
441.1169 -
441.1170 -and in the file you will see something like ::
441.1171 -
441.1172 - 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
441.1173 - 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
441.1174 - 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
441.1175 - 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
441.1176 - 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
441.1177 -
441.1178 -As you can see, the DEBUG message only shows up in the file. The other messages
441.1179 -are sent to both destinations.
441.1180 -
441.1181 -This example uses console and file handlers, but you can use any number and
441.1182 -combination of handlers you choose.
441.1183 -
441.1184 -
441.1185 -.. _context-info:
441.1186 -
441.1187 -Adding contextual information to your logging output
441.1188 -----------------------------------------------------
441.1189 -
441.1190 -Sometimes you want logging output to contain contextual information in
441.1191 -addition to the parameters passed to the logging call. For example, in a
441.1192 -networked application, it may be desirable to log client-specific information
441.1193 -in the log (e.g. remote client's username, or IP address). Although you could
441.1194 -use the *extra* parameter to achieve this, it's not always convenient to pass
441.1195 -the information in this way. While it might be tempting to create
441.1196 -:class:`Logger` instances on a per-connection basis, this is not a good idea
441.1197 -because these instances are not garbage collected. While this is not a problem
441.1198 -in practice, when the number of :class:`Logger` instances is dependent on the
441.1199 -level of granularity you want to use in logging an application, it could
441.1200 -be hard to manage if the number of :class:`Logger` instances becomes
441.1201 -effectively unbounded.
441.1202 -
441.1203 -An easy way in which you can pass contextual information to be output along
441.1204 -with logging event information is to use the :class:`LoggerAdapter` class.
441.1205 -This class is designed to look like a :class:`Logger`, so that you can call
441.1206 -:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
441.1207 -:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
441.1208 -same signatures as their counterparts in :class:`Logger`, so you can use the
441.1209 -two types of instances interchangeably.
441.1210 -
441.1211 -When you create an instance of :class:`LoggerAdapter`, you pass it a
441.1212 -:class:`Logger` instance and a dict-like object which contains your contextual
441.1213 -information. When you call one of the logging methods on an instance of
441.1214 -:class:`LoggerAdapter`, it delegates the call to the underlying instance of
441.1215 -:class:`Logger` passed to its constructor, and arranges to pass the contextual
441.1216 -information in the delegated call. Here's a snippet from the code of
441.1217 -:class:`LoggerAdapter`::
441.1218 -
441.1219 - def debug(self, msg, *args, **kwargs):
441.1220 - """
441.1221 - Delegate a debug call to the underlying logger, after adding
441.1222 - contextual information from this adapter instance.
441.1223 - """
441.1224 - msg, kwargs = self.process(msg, kwargs)
441.1225 - self.logger.debug(msg, *args, **kwargs)
441.1226 -
441.1227 -The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
441.1228 -information is added to the logging output. It's passed the message and
441.1229 -keyword arguments of the logging call, and it passes back (potentially)
441.1230 -modified versions of these to use in the call to the underlying logger. The
441.1231 -default implementation of this method leaves the message alone, but inserts
441.1232 -an "extra" key in the keyword argument whose value is the dict-like object
441.1233 -passed to the constructor. Of course, if you had passed an "extra" keyword
441.1234 -argument in the call to the adapter, it will be silently overwritten.
441.1235 -
441.1236 -The advantage of using "extra" is that the values in the dict-like object are
441.1237 -merged into the :class:`LogRecord` instance's __dict__, allowing you to use
441.1238 -customized strings with your :class:`Formatter` instances which know about
441.1239 -the keys of the dict-like object. If you need a different method, e.g. if you
441.1240 -want to prepend or append the contextual information to the message string,
441.1241 -you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
441.1242 -to do what you need. Here's an example script which uses this class, which
441.1243 -also illustrates what dict-like behaviour is needed from an arbitrary
441.1244 -"dict-like" object for use in the constructor::
441.1245 -
441.1246 - import logging
441.1247 -
441.1248 - class ConnInfo:
441.1249 - """
441.1250 - An example class which shows how an arbitrary class can be used as
441.1251 - the 'extra' context information repository passed to a LoggerAdapter.
441.1252 - """
441.1253 -
441.1254 - def __getitem__(self, name):
441.1255 - """
441.1256 - To allow this instance to look like a dict.
441.1257 - """
441.1258 - from random import choice
441.1259 - if name == "ip":
441.1260 - result = choice(["127.0.0.1", "192.168.0.1"])
441.1261 - elif name == "user":
441.1262 - result = choice(["jim", "fred", "sheila"])
441.1263 - else:
441.1264 - result = self.__dict__.get(name, "?")
441.1265 - return result
441.1266 -
441.1267 - def __iter__(self):
441.1268 - """
441.1269 - To allow iteration over keys, which will be merged into
441.1270 - the LogRecord dict before formatting and output.
441.1271 - """
441.1272 - keys = ["ip", "user"]
441.1273 - keys.extend(self.__dict__.keys())
441.1274 - return keys.__iter__()
441.1275 -
441.1276 - if __name__ == "__main__":
441.1277 - from random import choice
441.1278 - levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
441.1279 - a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
441.1280 - { "ip" : "123.231.231.123", "user" : "sheila" })
441.1281 - logging.basicConfig(level=logging.DEBUG,
441.1282 - format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
441.1283 - a1.debug("A debug message")
441.1284 - a1.info("An info message with %s", "some parameters")
441.1285 - a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
441.1286 - for x in range(10):
441.1287 - lvl = choice(levels)
441.1288 - lvlname = logging.getLevelName(lvl)
441.1289 - a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
441.1290 -
441.1291 -When this script is run, the output should look something like this::
441.1292 -
441.1293 - 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
441.1294 - 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
441.1295 - 2008-01-18 14:49:54,023 d.e.f CRITICAL IP: 192.168.0.1 User: jim A message at CRITICAL level with 2 parameters
441.1296 - 2008-01-18 14:49:54,033 d.e.f INFO IP: 192.168.0.1 User: jim A message at INFO level with 2 parameters
441.1297 - 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: sheila A message at WARNING level with 2 parameters
441.1298 - 2008-01-18 14:49:54,033 d.e.f ERROR IP: 127.0.0.1 User: fred A message at ERROR level with 2 parameters
441.1299 - 2008-01-18 14:49:54,033 d.e.f ERROR IP: 127.0.0.1 User: sheila A message at ERROR level with 2 parameters
441.1300 - 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: sheila A message at WARNING level with 2 parameters
441.1301 - 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: jim A message at WARNING level with 2 parameters
441.1302 - 2008-01-18 14:49:54,033 d.e.f INFO IP: 192.168.0.1 User: fred A message at INFO level with 2 parameters
441.1303 - 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: sheila A message at WARNING level with 2 parameters
441.1304 - 2008-01-18 14:49:54,033 d.e.f WARNING IP: 127.0.0.1 User: jim A message at WARNING level with 2 parameters
441.1305 -
441.1306 -.. versionadded:: 2.6
441.1307 -
441.1308 -The :class:`LoggerAdapter` class was not present in previous versions.
441.1309 -
441.1310 -
441.1311 -.. _network-logging:
441.1312 -
441.1313 -Sending and receiving logging events across a network
441.1314 ------------------------------------------------------
441.1315 -
441.1316 -Let's say you want to send logging events across a network, and handle them at
441.1317 -the receiving end. A simple way of doing this is attaching a
441.1318 -:class:`SocketHandler` instance to the root logger at the sending end::
441.1319 -
441.1320 - import logging, logging.handlers
441.1321 -
441.1322 - rootLogger = logging.getLogger('')
441.1323 - rootLogger.setLevel(logging.DEBUG)
441.1324 - socketHandler = logging.handlers.SocketHandler('localhost',
441.1325 - logging.handlers.DEFAULT_TCP_LOGGING_PORT)
441.1326 - # don't bother with a formatter, since a socket handler sends the event as
441.1327 - # an unformatted pickle
441.1328 - rootLogger.addHandler(socketHandler)
441.1329 -
441.1330 - # Now, we can log to the root logger, or any other logger. First the root...
441.1331 - logging.info('Jackdaws love my big sphinx of quartz.')
441.1332 -
441.1333 - # Now, define a couple of other loggers which might represent areas in your
441.1334 - # application:
441.1335 -
441.1336 - logger1 = logging.getLogger('myapp.area1')
441.1337 - logger2 = logging.getLogger('myapp.area2')
441.1338 -
441.1339 - logger1.debug('Quick zephyrs blow, vexing daft Jim.')
441.1340 - logger1.info('How quickly daft jumping zebras vex.')
441.1341 - logger2.warning('Jail zesty vixen who grabbed pay from quack.')
441.1342 - logger2.error('The five boxing wizards jump quickly.')
441.1343 -
441.1344 -At the receiving end, you can set up a receiver using the :mod:`SocketServer`
441.1345 -module. Here is a basic working example::
441.1346 -
441.1347 - import cPickle
441.1348 - import logging
441.1349 - import logging.handlers
441.1350 - import SocketServer
441.1351 - import struct
441.1352 -
441.1353 -
441.1354 - class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
441.1355 - """Handler for a streaming logging request.
441.1356 -
441.1357 - This basically logs the record using whatever logging policy is
441.1358 - configured locally.
441.1359 - """
441.1360 -
441.1361 - def handle(self):
441.1362 - """
441.1363 - Handle multiple requests - each expected to be a 4-byte length,
441.1364 - followed by the LogRecord in pickle format. Logs the record
441.1365 - according to whatever policy is configured locally.
441.1366 - """
441.1367 - while 1:
441.1368 - chunk = self.connection.recv(4)
441.1369 - if len(chunk) < 4:
441.1370 - break
441.1371 - slen = struct.unpack(">L", chunk)[0]
441.1372 - chunk = self.connection.recv(slen)
441.1373 - while len(chunk) < slen:
441.1374 - chunk = chunk + self.connection.recv(slen - len(chunk))
441.1375 - obj = self.unPickle(chunk)
441.1376 - record = logging.makeLogRecord(obj)
441.1377 - self.handleLogRecord(record)
441.1378 -
441.1379 - def unPickle(self, data):
441.1380 - return cPickle.loads(data)
441.1381 -
441.1382 - def handleLogRecord(self, record):
441.1383 - # if a name is specified, we use the named logger rather than the one
441.1384 - # implied by the record.
441.1385 - if self.server.logname is not None:
441.1386 - name = self.server.logname
441.1387 - else:
441.1388 - name = record.name
441.1389 - logger = logging.getLogger(name)
441.1390 - # N.B. EVERY record gets logged. This is because Logger.handle
441.1391 - # is normally called AFTER logger-level filtering. If you want
441.1392 - # to do filtering, do it at the client end to save wasting
441.1393 - # cycles and network bandwidth!
441.1394 - logger.handle(record)
441.1395 -
441.1396 - class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
441.1397 - """simple TCP socket-based logging receiver suitable for testing.
441.1398 - """
441.1399 -
441.1400 - allow_reuse_address = 1
441.1401 -
441.1402 - def __init__(self, host='localhost',
441.1403 - port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
441.1404 - handler=LogRecordStreamHandler):
441.1405 - SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
441.1406 - self.abort = 0
441.1407 - self.timeout = 1
441.1408 - self.logname = None
441.1409 -
441.1410 - def serve_until_stopped(self):
441.1411 - import select
441.1412 - abort = 0
441.1413 - while not abort:
441.1414 - rd, wr, ex = select.select([self.socket.fileno()],
441.1415 - [], [],
441.1416 - self.timeout)
441.1417 - if rd:
441.1418 - self.handle_request()
441.1419 - abort = self.abort
441.1420 -
441.1421 - def main():
441.1422 - logging.basicConfig(
441.1423 - format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
441.1424 - tcpserver = LogRecordSocketReceiver()
441.1425 - print "About to start TCP server..."
441.1426 - tcpserver.serve_until_stopped()
441.1427 -
441.1428 - if __name__ == "__main__":
441.1429 - main()
441.1430 -
441.1431 -First run the server, and then the client. On the client side, nothing is
441.1432 -printed on the console; on the server side, you should see something like::
441.1433 -
441.1434 - About to start TCP server...
441.1435 - 59 root INFO Jackdaws love my big sphinx of quartz.
441.1436 - 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
441.1437 - 69 myapp.area1 INFO How quickly daft jumping zebras vex.
441.1438 - 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
441.1439 - 69 myapp.area2 ERROR The five boxing wizards jump quickly.
441.1440 -
441.1441 -
441.1442 -Handler Objects
441.1443 ----------------
441.1444 -
441.1445 -Handlers have the following attributes and methods. Note that :class:`Handler`
441.1446 -is never instantiated directly; this class acts as a base for more useful
441.1447 -subclasses. However, the :meth:`__init__` method in subclasses needs to call
441.1448 -:meth:`Handler.__init__`.
441.1449 -
441.1450 -
441.1451 -.. method:: Handler.__init__(level=NOTSET)
441.1452 -
441.1453 - Initializes the :class:`Handler` instance by setting its level, setting the list
441.1454 - of filters to the empty list and creating a lock (using :meth:`createLock`) for
441.1455 - serializing access to an I/O mechanism.
441.1456 -
441.1457 -
441.1458 -.. method:: Handler.createLock()
441.1459 -
441.1460 - Initializes a thread lock which can be used to serialize access to underlying
441.1461 - I/O functionality which may not be threadsafe.
441.1462 -
441.1463 -
441.1464 -.. method:: Handler.acquire()
441.1465 -
441.1466 - Acquires the thread lock created with :meth:`createLock`.
441.1467 -
441.1468 -
441.1469 -.. method:: Handler.release()
441.1470 -
441.1471 - Releases the thread lock acquired with :meth:`acquire`.
441.1472 -
441.1473 -
441.1474 -.. method:: Handler.setLevel(lvl)
441.1475 -
441.1476 - Sets the threshold for this handler to *lvl*. Logging messages which are less
441.1477 - severe than *lvl* will be ignored. When a handler is created, the level is set
441.1478 - to :const:`NOTSET` (which causes all messages to be processed).
441.1479 -
441.1480 -
441.1481 -.. method:: Handler.setFormatter(form)
441.1482 -
441.1483 - Sets the :class:`Formatter` for this handler to *form*.
441.1484 -
441.1485 -
441.1486 -.. method:: Handler.addFilter(filt)
441.1487 -
441.1488 - Adds the specified filter *filt* to this handler.
441.1489 -
441.1490 -
441.1491 -.. method:: Handler.removeFilter(filt)
441.1492 -
441.1493 - Removes the specified filter *filt* from this handler.
441.1494 -
441.1495 -
441.1496 -.. method:: Handler.filter(record)
441.1497 -
441.1498 - Applies this handler's filters to the record and returns a true value if the
441.1499 - record is to be processed.
441.1500 -
441.1501 -
441.1502 -.. method:: Handler.flush()
441.1503 -
441.1504 - Ensure all logging output has been flushed. This version does nothing and is
441.1505 - intended to be implemented by subclasses.
441.1506 -
441.1507 -
441.1508 -.. method:: Handler.close()
441.1509 -
441.1510 - Tidy up any resources used by the handler. This version does no output but
441.1511 - removes the handler from an internal list of handlers which is closed when
441.1512 - :func:`shutdown` is called. Subclasses should ensure that this gets called
441.1513 - from overridden :meth:`close` methods.
441.1514 -
441.1515 -
441.1516 -.. method:: Handler.handle(record)
441.1517 -
441.1518 - Conditionally emits the specified logging record, depending on filters which may
441.1519 - have been added to the handler. Wraps the actual emission of the record with
441.1520 - acquisition/release of the I/O thread lock.
441.1521 -
441.1522 -
441.1523 -.. method:: Handler.handleError(record)
441.1524 -
441.1525 - This method should be called from handlers when an exception is encountered
441.1526 - during an :meth:`emit` call. By default it does nothing, which means that
441.1527 - exceptions get silently ignored. This is what is mostly wanted for a logging
441.1528 - system - most users will not care about errors in the logging system, they are
441.1529 - more interested in application errors. You could, however, replace this with a
441.1530 - custom handler if you wish. The specified record is the one which was being
441.1531 - processed when the exception occurred.
441.1532 -
441.1533 -
441.1534 -.. method:: Handler.format(record)
441.1535 -
441.1536 - Do formatting for a record - if a formatter is set, use it. Otherwise, use the
441.1537 - default formatter for the module.
441.1538 -
441.1539 -
441.1540 -.. method:: Handler.emit(record)
441.1541 -
441.1542 - Do whatever it takes to actually log the specified logging record. This version
441.1543 - is intended to be implemented by subclasses and so raises a
441.1544 - :exc:`NotImplementedError`.
441.1545 -
441.1546 -
441.1547 -StreamHandler
441.1548 -^^^^^^^^^^^^^
441.1549 -
441.1550 -The :class:`StreamHandler` class, located in the core :mod:`logging` package,
441.1551 -sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
441.1552 -file-like object (or, more precisely, any object which supports :meth:`write`
441.1553 -and :meth:`flush` methods).
441.1554 -
441.1555 -
441.1556 -.. class:: StreamHandler([strm])
441.1557 -
441.1558 - Returns a new instance of the :class:`StreamHandler` class. If *strm* is
441.1559 - specified, the instance will use it for logging output; otherwise, *sys.stderr*
441.1560 - will be used.
441.1561 -
441.1562 -
441.1563 - .. method:: emit(record)
441.1564 -
441.1565 - If a formatter is specified, it is used to format the record. The record
441.1566 - is then written to the stream with a trailing newline. If exception
441.1567 - information is present, it is formatted using
441.1568 - :func:`traceback.print_exception` and appended to the stream.
441.1569 -
441.1570 -
441.1571 - .. method:: flush()
441.1572 -
441.1573 - Flushes the stream by calling its :meth:`flush` method. Note that the
441.1574 - :meth:`close` method is inherited from :class:`Handler` and so does
441.1575 - no output, so an explicit :meth:`flush` call may be needed at times.
441.1576 -
441.1577 -
441.1578 -FileHandler
441.1579 -^^^^^^^^^^^
441.1580 -
441.1581 -The :class:`FileHandler` class, located in the core :mod:`logging` package,
441.1582 -sends logging output to a disk file. It inherits the output functionality from
441.1583 -:class:`StreamHandler`.
441.1584 -
441.1585 -
441.1586 -.. class:: FileHandler(filename[, mode[, encoding[, delay]]])
441.1587 -
441.1588 - Returns a new instance of the :class:`FileHandler` class. The specified file is
441.1589 - opened and used as the stream for logging. If *mode* is not specified,
441.1590 - :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
441.1591 - with that encoding. If *delay* is true, then file opening is deferred until the
441.1592 - first call to :meth:`emit`. By default, the file grows indefinitely.
441.1593 -
441.1594 -
441.1595 - .. method:: close()
441.1596 -
441.1597 - Closes the file.
441.1598 -
441.1599 -
441.1600 - .. method:: emit(record)
441.1601 -
441.1602 - Outputs the record to the file.
441.1603 -
441.1604 -
441.1605 -WatchedFileHandler
441.1606 -^^^^^^^^^^^^^^^^^^
441.1607 -
441.1608 -.. versionadded:: 2.6
441.1609 -
441.1610 -The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
441.1611 -module, is a :class:`FileHandler` which watches the file it is logging to. If
441.1612 -the file changes, it is closed and reopened using the file name.
441.1613 -
441.1614 -A file change can happen because of usage of programs such as *newsyslog* and
441.1615 -*logrotate* which perform log file rotation. This handler, intended for use
441.1616 -under Unix/Linux, watches the file to see if it has changed since the last emit.
441.1617 -(A file is deemed to have changed if its device or inode have changed.) If the
441.1618 -file has changed, the old file stream is closed, and the file opened to get a
441.1619 -new stream.
441.1620 -
441.1621 -This handler is not appropriate for use under Windows, because under Windows
441.1622 -open log files cannot be moved or renamed - logging opens the files with
441.1623 -exclusive locks - and so there is no need for such a handler. Furthermore,
441.1624 -*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
441.1625 -this value.
441.1626 -
441.1627 -
441.1628 -.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
441.1629 -
441.1630 - Returns a new instance of the :class:`WatchedFileHandler` class. The specified
441.1631 - file is opened and used as the stream for logging. If *mode* is not specified,
441.1632 - :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
441.1633 - with that encoding. If *delay* is true, then file opening is deferred until the
441.1634 - first call to :meth:`emit`. By default, the file grows indefinitely.
441.1635 -
441.1636 -
441.1637 - .. method:: emit(record)
441.1638 -
441.1639 - Outputs the record to the file, but first checks to see if the file has
441.1640 - changed. If it has, the existing stream is flushed and closed and the
441.1641 - file opened again, before outputting the record to the file.
441.1642 -
441.1643 -
441.1644 -RotatingFileHandler
441.1645 -^^^^^^^^^^^^^^^^^^^
441.1646 -
441.1647 -The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
441.1648 -module, supports rotation of disk log files.
441.1649 -
441.1650 -
441.1651 -.. class:: RotatingFileHandler(filename[, mode[, maxBytes[, backupCount[, encoding[, delay]]]]])
441.1652 -
441.1653 - Returns a new instance of the :class:`RotatingFileHandler` class. The specified
441.1654 - file is opened and used as the stream for logging. If *mode* is not specified,
441.1655 - ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
441.1656 - with that encoding. If *delay* is true, then file opening is deferred until the
441.1657 - first call to :meth:`emit`. By default, the file grows indefinitely.
441.1658 -
441.1659 - You can use the *maxBytes* and *backupCount* values to allow the file to
441.1660 - :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
441.1661 - the file is closed and a new file is silently opened for output. Rollover occurs
441.1662 - whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
441.1663 - zero, rollover never occurs. If *backupCount* is non-zero, the system will save
441.1664 - old log files by appending the extensions ".1", ".2" etc., to the filename. For
441.1665 - example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
441.1666 - would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
441.1667 - :file:`app.log.5`. The file being written to is always :file:`app.log`. When
441.1668 - this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
441.1669 - :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
441.1670 - :file:`app.log.2`, :file:`app.log.3` etc. respectively.
441.1671 -
441.1672 -
441.1673 - .. method:: doRollover()
441.1674 -
441.1675 - Does a rollover, as described above.
441.1676 -
441.1677 -
441.1678 - .. method:: emit(record)
441.1679 -
441.1680 - Outputs the record to the file, catering for rollover as described
441.1681 - previously.
441.1682 -
441.1683 -
441.1684 -TimedRotatingFileHandler
441.1685 -^^^^^^^^^^^^^^^^^^^^^^^^
441.1686 -
441.1687 -The :class:`TimedRotatingFileHandler` class, located in the
441.1688 -:mod:`logging.handlers` module, supports rotation of disk log files at certain
441.1689 -timed intervals.
441.1690 -
441.1691 -
441.1692 -.. class:: TimedRotatingFileHandler(filename [,when [,interval [,backupCount[, encoding[, delay[, utc]]]]]])
441.1693 -
441.1694 - Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
441.1695 - specified file is opened and used as the stream for logging. On rotating it also
441.1696 - sets the filename suffix. Rotating happens based on the product of *when* and
441.1697 - *interval*.
441.1698 -
441.1699 - You can use the *when* to specify the type of *interval*. The list of possible
441.1700 - values is below. Note that they are not case sensitive.
441.1701 -
441.1702 - +----------------+-----------------------+
441.1703 - | Value | Type of interval |
441.1704 - +================+=======================+
441.1705 - | ``'S'`` | Seconds |
441.1706 - +----------------+-----------------------+
441.1707 - | ``'M'`` | Minutes |
441.1708 - +----------------+-----------------------+
441.1709 - | ``'H'`` | Hours |
441.1710 - +----------------+-----------------------+
441.1711 - | ``'D'`` | Days |
441.1712 - +----------------+-----------------------+
441.1713 - | ``'W'`` | Week day (0=Monday) |
441.1714 - +----------------+-----------------------+
441.1715 - | ``'midnight'`` | Roll over at midnight |
441.1716 - +----------------+-----------------------+
441.1717 -
441.1718 - The system will save old log files by appending extensions to the filename.
441.1719 - The extensions are date-and-time based, using the strftime format
441.1720 - ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
441.1721 - rollover interval.
441.1722 - If the *utc* argument is true, times in UTC will be used; otherwise
441.1723 - local time is used.
441.1724 -
441.1725 - If *backupCount* is nonzero, at most *backupCount* files
441.1726 - will be kept, and if more would be created when rollover occurs, the oldest
441.1727 - one is deleted. The deletion logic uses the interval to determine which
441.1728 - files to delete, so changing the interval may leave old files lying around.
441.1729 -
441.1730 -
441.1731 - .. method:: doRollover()
441.1732 -
441.1733 - Does a rollover, as described above.
441.1734 -
441.1735 -
441.1736 - .. method:: emit(record)
441.1737 -
441.1738 - Outputs the record to the file, catering for rollover as described above.
441.1739 -
441.1740 -
441.1741 -SocketHandler
441.1742 -^^^^^^^^^^^^^
441.1743 -
441.1744 -The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
441.1745 -sends logging output to a network socket. The base class uses a TCP socket.
441.1746 -
441.1747 -
441.1748 -.. class:: SocketHandler(host, port)
441.1749 -
441.1750 - Returns a new instance of the :class:`SocketHandler` class intended to
441.1751 - communicate with a remote machine whose address is given by *host* and *port*.
441.1752 -
441.1753 -
441.1754 - .. method:: close()
441.1755 -
441.1756 - Closes the socket.
441.1757 -
441.1758 -
441.1759 - .. method:: emit()
441.1760 -
441.1761 - Pickles the record's attribute dictionary and writes it to the socket in
441.1762 - binary format. If there is an error with the socket, silently drops the
441.1763 - packet. If the connection was previously lost, re-establishes the
441.1764 - connection. To unpickle the record at the receiving end into a
441.1765 - :class:`LogRecord`, use the :func:`makeLogRecord` function.
441.1766 -
441.1767 -
441.1768 - .. method:: handleError()
441.1769 -
441.1770 - Handles an error which has occurred during :meth:`emit`. The most likely
441.1771 - cause is a lost connection. Closes the socket so that we can retry on the
441.1772 - next event.
441.1773 -
441.1774 -
441.1775 - .. method:: makeSocket()
441.1776 -
441.1777 - This is a factory method which allows subclasses to define the precise
441.1778 - type of socket they want. The default implementation creates a TCP socket
441.1779 - (:const:`socket.SOCK_STREAM`).
441.1780 -
441.1781 -
441.1782 - .. method:: makePickle(record)
441.1783 -
441.1784 - Pickles the record's attribute dictionary in binary format with a length
441.1785 - prefix, and returns it ready for transmission across the socket.
441.1786 -
441.1787 -
441.1788 - .. method:: send(packet)
441.1789 -
441.1790 - Send a pickled string *packet* to the socket. This function allows for
441.1791 - partial sends which can happen when the network is busy.
441.1792 -
441.1793 -
441.1794 -DatagramHandler
441.1795 -^^^^^^^^^^^^^^^
441.1796 -
441.1797 -The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
441.1798 -module, inherits from :class:`SocketHandler` to support sending logging messages
441.1799 -over UDP sockets.
441.1800 -
441.1801 -
441.1802 -.. class:: DatagramHandler(host, port)
441.1803 -
441.1804 - Returns a new instance of the :class:`DatagramHandler` class intended to
441.1805 - communicate with a remote machine whose address is given by *host* and *port*.
441.1806 -
441.1807 -
441.1808 - .. method:: emit()
441.1809 -
441.1810 - Pickles the record's attribute dictionary and writes it to the socket in
441.1811 - binary format. If there is an error with the socket, silently drops the
441.1812 - packet. To unpickle the record at the receiving end into a
441.1813 - :class:`LogRecord`, use the :func:`makeLogRecord` function.
441.1814 -
441.1815 -
441.1816 - .. method:: makeSocket()
441.1817 -
441.1818 - The factory method of :class:`SocketHandler` is here overridden to create
441.1819 - a UDP socket (:const:`socket.SOCK_DGRAM`).
441.1820 -
441.1821 -
441.1822 - .. method:: send(s)
441.1823 -
441.1824 - Send a pickled string to a socket.
441.1825 -
441.1826 -
441.1827 -SysLogHandler
441.1828 -^^^^^^^^^^^^^
441.1829 -
441.1830 -The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
441.1831 -supports sending logging messages to a remote or local Unix syslog.
441.1832 -
441.1833 -
441.1834 -.. class:: SysLogHandler([address[, facility]])
441.1835 -
441.1836 - Returns a new instance of the :class:`SysLogHandler` class intended to
441.1837 - communicate with a remote Unix machine whose address is given by *address* in
441.1838 - the form of a ``(host, port)`` tuple. If *address* is not specified,
441.1839 - ``('localhost', 514)`` is used. The address is used to open a UDP socket. An
441.1840 - alternative to providing a ``(host, port)`` tuple is providing an address as a
441.1841 - string, for example "/dev/log". In this case, a Unix domain socket is used to
441.1842 - send the message to the syslog. If *facility* is not specified,
441.1843 - :const:`LOG_USER` is used.
441.1844 -
441.1845 -
441.1846 - .. method:: close()
441.1847 -
441.1848 - Closes the socket to the remote host.
441.1849 -
441.1850 -
441.1851 - .. method:: emit(record)
441.1852 -
441.1853 - The record is formatted, and then sent to the syslog server. If exception
441.1854 - information is present, it is *not* sent to the server.
441.1855 -
441.1856 -
441.1857 - .. method:: encodePriority(facility, priority)
441.1858 -
441.1859 - Encodes the facility and priority into an integer. You can pass in strings
441.1860 - or integers - if strings are passed, internal mapping dictionaries are
441.1861 - used to convert them to integers.
441.1862 -
441.1863 -
441.1864 -NTEventLogHandler
441.1865 -^^^^^^^^^^^^^^^^^
441.1866 -
441.1867 -The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
441.1868 -module, supports sending logging messages to a local Windows NT, Windows 2000 or
441.1869 -Windows XP event log. Before you can use it, you need Mark Hammond's Win32
441.1870 -extensions for Python installed.
441.1871 -
441.1872 -
441.1873 -.. class:: NTEventLogHandler(appname[, dllname[, logtype]])
441.1874 -
441.1875 - Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
441.1876 - used to define the application name as it appears in the event log. An
441.1877 - appropriate registry entry is created using this name. The *dllname* should give
441.1878 - the fully qualified pathname of a .dll or .exe which contains message
441.1879 - definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
441.1880 - - this is installed with the Win32 extensions and contains some basic
441.1881 - placeholder message definitions. Note that use of these placeholders will make
441.1882 - your event logs big, as the entire message source is held in the log. If you
441.1883 - want slimmer logs, you have to pass in the name of your own .dll or .exe which
441.1884 - contains the message definitions you want to use in the event log). The
441.1885 - *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
441.1886 - defaults to ``'Application'``.
441.1887 -
441.1888 -
441.1889 - .. method:: close()
441.1890 -
441.1891 - At this point, you can remove the application name from the registry as a
441.1892 - source of event log entries. However, if you do this, you will not be able
441.1893 - to see the events as you intended in the Event Log Viewer - it needs to be
441.1894 - able to access the registry to get the .dll name. The current version does
441.1895 - not do this.
441.1896 -
441.1897 -
441.1898 - .. method:: emit(record)
441.1899 -
441.1900 - Determines the message ID, event category and event type, and then logs
441.1901 - the message in the NT event log.
441.1902 -
441.1903 -
441.1904 - .. method:: getEventCategory(record)
441.1905 -
441.1906 - Returns the event category for the record. Override this if you want to
441.1907 - specify your own categories. This version returns 0.
441.1908 -
441.1909 -
441.1910 - .. method:: getEventType(record)
441.1911 -
441.1912 - Returns the event type for the record. Override this if you want to
441.1913 - specify your own types. This version does a mapping using the handler's
441.1914 - typemap attribute, which is set up in :meth:`__init__` to a dictionary
441.1915 - which contains mappings for :const:`DEBUG`, :const:`INFO`,
441.1916 - :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
441.1917 - your own levels, you will either need to override this method or place a
441.1918 - suitable dictionary in the handler's *typemap* attribute.
441.1919 -
441.1920 -
441.1921 - .. method:: getMessageID(record)
441.1922 -
441.1923 - Returns the message ID for the record. If you are using your own messages,
441.1924 - you could do this by having the *msg* passed to the logger being an ID
441.1925 - rather than a format string. Then, in here, you could use a dictionary
441.1926 - lookup to get the message ID. This version returns 1, which is the base
441.1927 - message ID in :file:`win32service.pyd`.
441.1928 -
441.1929 -
441.1930 -SMTPHandler
441.1931 -^^^^^^^^^^^
441.1932 -
441.1933 -The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
441.1934 -supports sending logging messages to an email address via SMTP.
441.1935 -
441.1936 -
441.1937 -.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject[, credentials])
441.1938 -
441.1939 - Returns a new instance of the :class:`SMTPHandler` class. The instance is
441.1940 - initialized with the from and to addresses and subject line of the email. The
441.1941 - *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
441.1942 - the (host, port) tuple format for the *mailhost* argument. If you use a string,
441.1943 - the standard SMTP port is used. If your SMTP server requires authentication, you
441.1944 - can specify a (username, password) tuple for the *credentials* argument.
441.1945 -
441.1946 - .. versionchanged:: 2.6
441.1947 - *credentials* was added.
441.1948 -
441.1949 -
441.1950 - .. method:: emit(record)
441.1951 -
441.1952 - Formats the record and sends it to the specified addressees.
441.1953 -
441.1954 -
441.1955 - .. method:: getSubject(record)
441.1956 -
441.1957 - If you want to specify a subject line which is record-dependent, override
441.1958 - this method.
441.1959 -
441.1960 -
441.1961 -MemoryHandler
441.1962 -^^^^^^^^^^^^^
441.1963 -
441.1964 -The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
441.1965 -supports buffering of logging records in memory, periodically flushing them to a
441.1966 -:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
441.1967 -event of a certain severity or greater is seen.
441.1968 -
441.1969 -:class:`MemoryHandler` is a subclass of the more general
441.1970 -:class:`BufferingHandler`, which is an abstract class. This buffers logging
441.1971 -records in memory. Whenever each record is added to the buffer, a check is made
441.1972 -by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
441.1973 -should, then :meth:`flush` is expected to do the needful.
441.1974 -
441.1975 -
441.1976 -.. class:: BufferingHandler(capacity)
441.1977 -
441.1978 - Initializes the handler with a buffer of the specified capacity.
441.1979 -
441.1980 -
441.1981 - .. method:: emit(record)
441.1982 -
441.1983 - Appends the record to the buffer. If :meth:`shouldFlush` returns true,
441.1984 - calls :meth:`flush` to process the buffer.
441.1985 -
441.1986 -
441.1987 - .. method:: flush()
441.1988 -
441.1989 - You can override this to implement custom flushing behavior. This version
441.1990 - just zaps the buffer to empty.
441.1991 -
441.1992 -
441.1993 - .. method:: shouldFlush(record)
441.1994 -
441.1995 - Returns true if the buffer is up to capacity. This method can be
441.1996 - overridden to implement custom flushing strategies.
441.1997 -
441.1998 -
441.1999 -.. class:: MemoryHandler(capacity[, flushLevel [, target]])
441.2000 -
441.2001 - Returns a new instance of the :class:`MemoryHandler` class. The instance is
441.2002 - initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
441.2003 - :const:`ERROR` is used. If no *target* is specified, the target will need to be
441.2004 - set using :meth:`setTarget` before this handler does anything useful.
441.2005 -
441.2006 -
441.2007 - .. method:: close()
441.2008 -
441.2009 - Calls :meth:`flush`, sets the target to :const:`None` and clears the
441.2010 - buffer.
441.2011 -
441.2012 -
441.2013 - .. method:: flush()
441.2014 -
441.2015 - For a :class:`MemoryHandler`, flushing means just sending the buffered
441.2016 - records to the target, if there is one. Override if you want different
441.2017 - behavior.
441.2018 -
441.2019 -
441.2020 - .. method:: setTarget(target)
441.2021 -
441.2022 - Sets the target handler for this handler.
441.2023 -
441.2024 -
441.2025 - .. method:: shouldFlush(record)
441.2026 -
441.2027 - Checks for buffer full or a record at the *flushLevel* or higher.
441.2028 -
441.2029 -
441.2030 -HTTPHandler
441.2031 -^^^^^^^^^^^
441.2032 -
441.2033 -The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
441.2034 -supports sending logging messages to a Web server, using either ``GET`` or
441.2035 -``POST`` semantics.
441.2036 -
441.2037 -
441.2038 -.. class:: HTTPHandler(host, url[, method])
441.2039 -
441.2040 - Returns a new instance of the :class:`HTTPHandler` class. The instance is
441.2041 - initialized with a host address, url and HTTP method. The *host* can be of the
441.2042 - form ``host:port``, should you need to use a specific port number. If no
441.2043 - *method* is specified, ``GET`` is used.
441.2044 -
441.2045 -
441.2046 - .. method:: emit(record)
441.2047 -
441.2048 - Sends the record to the Web server as an URL-encoded dictionary.
441.2049 -
441.2050 -
441.2051 -.. _formatter-objects:
441.2052 -
441.2053 -Formatter Objects
441.2054 ------------------
441.2055 -
441.2056 -:class:`Formatter`\ s have the following attributes and methods. They are
441.2057 -responsible for converting a :class:`LogRecord` to (usually) a string which can
441.2058 -be interpreted by either a human or an external system. The base
441.2059 -:class:`Formatter` allows a formatting string to be specified. If none is
441.2060 -supplied, the default value of ``'%(message)s'`` is used.
441.2061 -
441.2062 -A Formatter can be initialized with a format string which makes use of knowledge
441.2063 -of the :class:`LogRecord` attributes - such as the default value mentioned above
441.2064 -making use of the fact that the user's message and arguments are pre-formatted
441.2065 -into a :class:`LogRecord`'s *message* attribute. This format string contains
441.2066 -standard python %-style mapping keys. See section :ref:`string-formatting`
441.2067 -for more information on string formatting.
441.2068 -
441.2069 -Currently, the useful mapping keys in a :class:`LogRecord` are:
441.2070 -
441.2071 -+-------------------------+-----------------------------------------------+
441.2072 -| Format | Description |
441.2073 -+=========================+===============================================+
441.2074 -| ``%(name)s`` | Name of the logger (logging channel). |
441.2075 -+-------------------------+-----------------------------------------------+
441.2076 -| ``%(levelno)s`` | Numeric logging level for the message |
441.2077 -| | (:const:`DEBUG`, :const:`INFO`, |
441.2078 -| | :const:`WARNING`, :const:`ERROR`, |
441.2079 -| | :const:`CRITICAL`). |
441.2080 -+-------------------------+-----------------------------------------------+
441.2081 -| ``%(levelname)s`` | Text logging level for the message |
441.2082 -| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
441.2083 -| | ``'ERROR'``, ``'CRITICAL'``). |
441.2084 -+-------------------------+-----------------------------------------------+
441.2085 -| ``%(pathname)s`` | Full pathname of the source file where the |
441.2086 -| | logging call was issued (if available). |
441.2087 -+-------------------------+-----------------------------------------------+
441.2088 -| ``%(filename)s`` | Filename portion of pathname. |
441.2089 -+-------------------------+-----------------------------------------------+
441.2090 -| ``%(module)s`` | Module (name portion of filename). |
441.2091 -+-------------------------+-----------------------------------------------+
441.2092 -| ``%(funcName)s`` | Name of function containing the logging call. |
441.2093 -+-------------------------+-----------------------------------------------+
441.2094 -| ``%(lineno)d`` | Source line number where the logging call was |
441.2095 -| | issued (if available). |
441.2096 -+-------------------------+-----------------------------------------------+
441.2097 -| ``%(created)f`` | Time when the :class:`LogRecord` was created |
441.2098 -| | (as returned by :func:`time.time`). |
441.2099 -+-------------------------+-----------------------------------------------+
441.2100 -| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
441.2101 -| | created, relative to the time the logging |
441.2102 -| | module was loaded. |
441.2103 -+-------------------------+-----------------------------------------------+
441.2104 -| ``%(asctime)s`` | Human-readable time when the |
441.2105 -| | :class:`LogRecord` was created. By default |
441.2106 -| | this is of the form "2003-07-08 16:49:45,896" |
441.2107 -| | (the numbers after the comma are millisecond |
441.2108 -| | portion of the time). |
441.2109 -+-------------------------+-----------------------------------------------+
441.2110 -| ``%(msecs)d`` | Millisecond portion of the time when the |
441.2111 -| | :class:`LogRecord` was created. |
441.2112 -+-------------------------+-----------------------------------------------+
441.2113 -| ``%(thread)d`` | Thread ID (if available). |
441.2114 -+-------------------------+-----------------------------------------------+
441.2115 -| ``%(threadName)s`` | Thread name (if available). |
441.2116 -+-------------------------+-----------------------------------------------+
441.2117 -| ``%(process)d`` | Process ID (if available). |
441.2118 -+-------------------------+-----------------------------------------------+
441.2119 -| ``%(message)s`` | The logged message, computed as ``msg % |
441.2120 -| | args``. |
441.2121 -+-------------------------+-----------------------------------------------+
441.2122 -
441.2123 -.. versionchanged:: 2.5
441.2124 - *funcName* was added.
441.2125 -
441.2126 -
441.2127 -.. class:: Formatter([fmt[, datefmt]])
441.2128 -
441.2129 - Returns a new instance of the :class:`Formatter` class. The instance is
441.2130 - initialized with a format string for the message as a whole, as well as a format
441.2131 - string for the date/time portion of a message. If no *fmt* is specified,
441.2132 - ``'%(message)s'`` is used. If no *datefmt* is specified, the ISO8601 date format
441.2133 - is used.
441.2134 -
441.2135 -
441.2136 - .. method:: format(record)
441.2137 -
441.2138 - The record's attribute dictionary is used as the operand to a string
441.2139 - formatting operation. Returns the resulting string. Before formatting the
441.2140 - dictionary, a couple of preparatory steps are carried out. The *message*
441.2141 - attribute of the record is computed using *msg* % *args*. If the
441.2142 - formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
441.2143 - to format the event time. If there is exception information, it is
441.2144 - formatted using :meth:`formatException` and appended to the message. Note
441.2145 - that the formatted exception information is cached in attribute
441.2146 - *exc_text*. This is useful because the exception information can be
441.2147 - pickled and sent across the wire, but you should be careful if you have
441.2148 - more than one :class:`Formatter` subclass which customizes the formatting
441.2149 - of exception information. In this case, you will have to clear the cached
441.2150 - value after a formatter has done its formatting, so that the next
441.2151 - formatter to handle the event doesn't use the cached value but
441.2152 - recalculates it afresh.
441.2153 -
441.2154 -
441.2155 - .. method:: formatTime(record[, datefmt])
441.2156 -
441.2157 - This method should be called from :meth:`format` by a formatter which
441.2158 - wants to make use of a formatted time. This method can be overridden in
441.2159 - formatters to provide for any specific requirement, but the basic behavior
441.2160 - is as follows: if *datefmt* (a string) is specified, it is used with
441.2161 - :func:`time.strftime` to format the creation time of the
441.2162 - record. Otherwise, the ISO8601 format is used. The resulting string is
441.2163 - returned.
441.2164 -
441.2165 -
441.2166 - .. method:: formatException(exc_info)
441.2167 -
441.2168 - Formats the specified exception information (a standard exception tuple as
441.2169 - returned by :func:`sys.exc_info`) as a string. This default implementation
441.2170 - just uses :func:`traceback.print_exception`. The resulting string is
441.2171 - returned.
441.2172 -
441.2173 -
441.2174 -Filter Objects
441.2175 ---------------
441.2176 -
441.2177 -:class:`Filter`\ s can be used by :class:`Handler`\ s and :class:`Logger`\ s for
441.2178 -more sophisticated filtering than is provided by levels. The base filter class
441.2179 -only allows events which are below a certain point in the logger hierarchy. For
441.2180 -example, a filter initialized with "A.B" will allow events logged by loggers
441.2181 -"A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
441.2182 -initialized with the empty string, all events are passed.
441.2183 -
441.2184 -
441.2185 -.. class:: Filter([name])
441.2186 -
441.2187 - Returns an instance of the :class:`Filter` class. If *name* is specified, it
441.2188 - names a logger which, together with its children, will have its events allowed
441.2189 - through the filter. If no name is specified, allows every event.
441.2190 -
441.2191 -
441.2192 - .. method:: filter(record)
441.2193 -
441.2194 - Is the specified record to be logged? Returns zero for no, nonzero for
441.2195 - yes. If deemed appropriate, the record may be modified in-place by this
441.2196 - method.
441.2197 -
441.2198 -
441.2199 -LogRecord Objects
441.2200 ------------------
441.2201 -
441.2202 -:class:`LogRecord` instances are created every time something is logged. They
441.2203 -contain all the information pertinent to the event being logged. The main
441.2204 -information passed in is in msg and args, which are combined using msg % args to
441.2205 -create the message field of the record. The record also includes information
441.2206 -such as when the record was created, the source line where the logging call was
441.2207 -made, and any exception information to be logged.
441.2208 -
441.2209 -
441.2210 -.. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info [, func])
441.2211 -
441.2212 - Returns an instance of :class:`LogRecord` initialized with interesting
441.2213 - information. The *name* is the logger name; *lvl* is the numeric level;
441.2214 - *pathname* is the absolute pathname of the source file in which the logging
441.2215 - call was made; *lineno* is the line number in that file where the logging
441.2216 - call is found; *msg* is the user-supplied message (a format string); *args*
441.2217 - is the tuple which, together with *msg*, makes up the user message; and
441.2218 - *exc_info* is the exception tuple obtained by calling :func:`sys.exc_info`
441.2219 - (or :const:`None`, if no exception information is available). The *func* is
441.2220 - the name of the function from which the logging call was made. If not
441.2221 - specified, it defaults to ``None``.
441.2222 -
441.2223 - .. versionchanged:: 2.5
441.2224 - *func* was added.
441.2225 -
441.2226 -
441.2227 - .. method:: getMessage()
441.2228 -
441.2229 - Returns the message for this :class:`LogRecord` instance after merging any
441.2230 - user-supplied arguments with the message.
441.2231 -
441.2232 -
441.2233 -LoggerAdapter Objects
441.2234 ----------------------
441.2235 -
441.2236 -.. versionadded:: 2.6
441.2237 -
441.2238 -:class:`LoggerAdapter` instances are used to conveniently pass contextual
441.2239 -information into logging calls. For a usage example , see the section on
441.2240 -`adding contextual information to your logging output`__.
441.2241 -
441.2242 -__ context-info_
441.2243 -
441.2244 -.. class:: LoggerAdapter(logger, extra)
441.2245 -
441.2246 - Returns an instance of :class:`LoggerAdapter` initialized with an
441.2247 - underlying :class:`Logger` instance and a dict-like object.
441.2248 -
441.2249 - .. method:: process(msg, kwargs)
441.2250 -
441.2251 - Modifies the message and/or keyword arguments passed to a logging call in
441.2252 - order to insert contextual information. This implementation takes the object
441.2253 - passed as *extra* to the constructor and adds it to *kwargs* using key
441.2254 - 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
441.2255 - (possibly modified) versions of the arguments passed in.
441.2256 -
441.2257 -In addition to the above, :class:`LoggerAdapter` supports all the logging
441.2258 -methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
441.2259 -:meth:`error`, :meth:`exception`, :meth:`critical` and :meth:`log`. These
441.2260 -methods have the same signatures as their counterparts in :class:`Logger`, so
441.2261 -you can use the two types of instances interchangeably.
441.2262 -
441.2263 -
441.2264 -Thread Safety
441.2265 --------------
441.2266 -
441.2267 -The logging module is intended to be thread-safe without any special work
441.2268 -needing to be done by its clients. It achieves this though using threading
441.2269 -locks; there is one lock to serialize access to the module's shared data, and
441.2270 -each handler also creates a lock to serialize access to its underlying I/O.
441.2271 -
441.2272 -
441.2273 -Configuration
441.2274 --------------
441.2275 -
441.2276 -
441.2277 -.. _logging-config-api:
441.2278 -
441.2279 -Configuration functions
441.2280 -^^^^^^^^^^^^^^^^^^^^^^^
441.2281 -
441.2282 -The following functions configure the logging module. They are located in the
441.2283 -:mod:`logging.config` module. Their use is optional --- you can configure the
441.2284 -logging module using these functions or by making calls to the main API (defined
441.2285 -in :mod:`logging` itself) and defining handlers which are declared either in
441.2286 -:mod:`logging` or :mod:`logging.handlers`.
441.2287 -
441.2288 -
441.2289 -.. function:: fileConfig(fname[, defaults])
441.2290 -
441.2291 - Reads the logging configuration from a ConfigParser-format file named *fname*.
441.2292 - This function can be called several times from an application, allowing an end
441.2293 - user the ability to select from various pre-canned configurations (if the
441.2294 - developer provides a mechanism to present the choices and load the chosen
441.2295 - configuration). Defaults to be passed to ConfigParser can be specified in the
441.2296 - *defaults* argument.
441.2297 -
441.2298 -
441.2299 -.. function:: listen([port])
441.2300 -
441.2301 - Starts up a socket server on the specified port, and listens for new
441.2302 - configurations. If no port is specified, the module's default
441.2303 - :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
441.2304 - sent as a file suitable for processing by :func:`fileConfig`. Returns a
441.2305 - :class:`Thread` instance on which you can call :meth:`start` to start the
441.2306 - server, and which you can :meth:`join` when appropriate. To stop the server,
441.2307 - call :func:`stopListening`.
441.2308 -
441.2309 - To send a configuration to the socket, read in the configuration file and
441.2310 - send it to the socket as a string of bytes preceded by a four-byte length
441.2311 - string packed in binary using ``struct.pack('>L', n)``.
441.2312 -
441.2313 -
441.2314 -.. function:: stopListening()
441.2315 -
441.2316 - Stops the listening server which was created with a call to :func:`listen`.
441.2317 - This is typically called before calling :meth:`join` on the return value from
441.2318 - :func:`listen`.
441.2319 -
441.2320 -
441.2321 -.. _logging-config-fileformat:
441.2322 -
441.2323 -Configuration file format
441.2324 -^^^^^^^^^^^^^^^^^^^^^^^^^
441.2325 -
441.2326 -The configuration file format understood by :func:`fileConfig` is based on
441.2327 -ConfigParser functionality. The file must contain sections called ``[loggers]``,
441.2328 -``[handlers]`` and ``[formatters]`` which identify by name the entities of each
441.2329 -type which are defined in the file. For each such entity, there is a separate
441.2330 -section which identified how that entity is configured. Thus, for a logger named
441.2331 -``log01`` in the ``[loggers]`` section, the relevant configuration details are
441.2332 -held in a section ``[logger_log01]``. Similarly, a handler called ``hand01`` in
441.2333 -the ``[handlers]`` section will have its configuration held in a section called
441.2334 -``[handler_hand01]``, while a formatter called ``form01`` in the
441.2335 -``[formatters]`` section will have its configuration specified in a section
441.2336 -called ``[formatter_form01]``. The root logger configuration must be specified
441.2337 -in a section called ``[logger_root]``.
441.2338 -
441.2339 -Examples of these sections in the file are given below. ::
441.2340 -
441.2341 - [loggers]
441.2342 - keys=root,log02,log03,log04,log05,log06,log07
441.2343 -
441.2344 - [handlers]
441.2345 - keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
441.2346 -
441.2347 - [formatters]
441.2348 - keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
441.2349 -
441.2350 -The root logger must specify a level and a list of handlers. An example of a
441.2351 -root logger section is given below. ::
441.2352 -
441.2353 - [logger_root]
441.2354 - level=NOTSET
441.2355 - handlers=hand01
441.2356 -
441.2357 -The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
441.2358 -``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
441.2359 -logged. Level values are :func:`eval`\ uated in the context of the ``logging``
441.2360 -package's namespace.
441.2361 -
441.2362 -The ``handlers`` entry is a comma-separated list of handler names, which must
441.2363 -appear in the ``[handlers]`` section. These names must appear in the
441.2364 -``[handlers]`` section and have corresponding sections in the configuration
441.2365 -file.
441.2366 -
441.2367 -For loggers other than the root logger, some additional information is required.
441.2368 -This is illustrated by the following example. ::
441.2369 -
441.2370 - [logger_parser]
441.2371 - level=DEBUG
441.2372 - handlers=hand01
441.2373 - propagate=1
441.2374 - qualname=compiler.parser
441.2375 -
441.2376 -The ``level`` and ``handlers`` entries are interpreted as for the root logger,
441.2377 -except that if a non-root logger's level is specified as ``NOTSET``, the system
441.2378 -consults loggers higher up the hierarchy to determine the effective level of the
441.2379 -logger. The ``propagate`` entry is set to 1 to indicate that messages must
441.2380 -propagate to handlers higher up the logger hierarchy from this logger, or 0 to
441.2381 -indicate that messages are **not** propagated to handlers up the hierarchy. The
441.2382 -``qualname`` entry is the hierarchical channel name of the logger, that is to
441.2383 -say the name used by the application to get the logger.
441.2384 -
441.2385 -Sections which specify handler configuration are exemplified by the following.
441.2386 -::
441.2387 -
441.2388 - [handler_hand01]
441.2389 - class=StreamHandler
441.2390 - level=NOTSET
441.2391 - formatter=form01
441.2392 - args=(sys.stdout,)
441.2393 -
441.2394 -The ``class`` entry indicates the handler's class (as determined by :func:`eval`
441.2395 -in the ``logging`` package's namespace). The ``level`` is interpreted as for
441.2396 -loggers, and ``NOTSET`` is taken to mean "log everything".
441.2397 -
441.2398 -.. versionchanged:: 2.6
441.2399 - Added support for resolving the handler's class as a dotted module and class
441.2400 - name.
441.2401 -
441.2402 -The ``formatter`` entry indicates the key name of the formatter for this
441.2403 -handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
441.2404 -If a name is specified, it must appear in the ``[formatters]`` section and have
441.2405 -a corresponding section in the configuration file.
441.2406 -
441.2407 -The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
441.2408 -package's namespace, is the list of arguments to the constructor for the handler
441.2409 -class. Refer to the constructors for the relevant handlers, or to the examples
441.2410 -below, to see how typical entries are constructed. ::
441.2411 -
441.2412 - [handler_hand02]
441.2413 - class=FileHandler
441.2414 - level=DEBUG
441.2415 - formatter=form02
441.2416 - args=('python.log', 'w')
441.2417 -
441.2418 - [handler_hand03]
441.2419 - class=handlers.SocketHandler
441.2420 - level=INFO
441.2421 - formatter=form03
441.2422 - args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
441.2423 -
441.2424 - [handler_hand04]
441.2425 - class=handlers.DatagramHandler
441.2426 - level=WARN
441.2427 - formatter=form04
441.2428 - args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
441.2429 -
441.2430 - [handler_hand05]
441.2431 - class=handlers.SysLogHandler
441.2432 - level=ERROR
441.2433 - formatter=form05
441.2434 - args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
441.2435 -
441.2436 - [handler_hand06]
441.2437 - class=handlers.NTEventLogHandler
441.2438 - level=CRITICAL
441.2439 - formatter=form06
441.2440 - args=('Python Application', '', 'Application')
441.2441 -
441.2442 - [handler_hand07]
441.2443 - class=handlers.SMTPHandler
441.2444 - level=WARN
441.2445 - formatter=form07
441.2446 - args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
441.2447 -
441.2448 - [handler_hand08]
441.2449 - class=handlers.MemoryHandler
441.2450 - level=NOTSET
441.2451 - formatter=form08
441.2452 - target=
441.2453 - args=(10, ERROR)
441.2454 -
441.2455 - [handler_hand09]
441.2456 - class=handlers.HTTPHandler
441.2457 - level=NOTSET
441.2458 - formatter=form09
441.2459 - args=('localhost:9022', '/log', 'GET')
441.2460 -
441.2461 -Sections which specify formatter configuration are typified by the following. ::
441.2462 -
441.2463 - [formatter_form01]
441.2464 - format=F1 %(asctime)s %(levelname)s %(message)s
441.2465 - datefmt=
441.2466 - class=logging.Formatter
441.2467 -
441.2468 -The ``format`` entry is the overall format string, and the ``datefmt`` entry is
441.2469 -the :func:`strftime`\ -compatible date/time format string. If empty, the
441.2470 -package substitutes ISO8601 format date/times, which is almost equivalent to
441.2471 -specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
441.2472 -also specifies milliseconds, which are appended to the result of using the above
441.2473 -format string, with a comma separator. An example time in ISO8601 format is
441.2474 -``2003-01-23 00:29:50,411``.
441.2475 -
441.2476 -The ``class`` entry is optional. It indicates the name of the formatter's class
441.2477 -(as a dotted module and class name.) This option is useful for instantiating a
441.2478 -:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
441.2479 -exception tracebacks in an expanded or condensed format.
441.2480 -
441.2481 -
441.2482 -Configuration server example
441.2483 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^
441.2484 -
441.2485 -Here is an example of a module using the logging configuration server::
441.2486 -
441.2487 - import logging
441.2488 - import logging.config
441.2489 - import time
441.2490 - import os
441.2491 -
441.2492 - # read initial config file
441.2493 - logging.config.fileConfig("logging.conf")
441.2494 -
441.2495 - # create and start listener on port 9999
441.2496 - t = logging.config.listen(9999)
441.2497 - t.start()
441.2498 -
441.2499 - logger = logging.getLogger("simpleExample")
441.2500 -
441.2501 - try:
441.2502 - # loop through logging calls to see the difference
441.2503 - # new configurations make, until Ctrl+C is pressed
441.2504 - while True:
441.2505 - logger.debug("debug message")
441.2506 - logger.info("info message")
441.2507 - logger.warn("warn message")
441.2508 - logger.error("error message")
441.2509 - logger.critical("critical message")
441.2510 - time.sleep(5)
441.2511 - except KeyboardInterrupt:
441.2512 - # cleanup
441.2513 - logging.config.stopListening()
441.2514 - t.join()
441.2515 -
441.2516 -And here is a script that takes a filename and sends that file to the server,
441.2517 -properly preceded with the binary-encoded length, as the new logging
441.2518 -configuration::
441.2519 -
441.2520 - #!/usr/bin/env python
441.2521 - import socket, sys, struct
441.2522 -
441.2523 - data_to_send = open(sys.argv[1], "r").read()
441.2524 -
441.2525 - HOST = 'localhost'
441.2526 - PORT = 9999
441.2527 - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
441.2528 - print "connecting..."
441.2529 - s.connect((HOST, PORT))
441.2530 - print "sending config..."
441.2531 - s.send(struct.pack(">L", len(data_to_send)))
441.2532 - s.send(data_to_send)
441.2533 - s.close()
441.2534 - print "complete"
441.2535 -
441.2536 -
441.2537 -More examples
441.2538 --------------
441.2539 -
441.2540 -Multiple handlers and formatters
441.2541 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
441.2542 -
441.2543 -Loggers are plain Python objects. The :func:`addHandler` method has no minimum
441.2544 -or maximum quota for the number of handlers you may add. Sometimes it will be
441.2545 -beneficial for an application to log all messages of all severities to a text
441.2546 -file while simultaneously logging errors or above to the console. To set this
441.2547 -up, simply configure the appropriate handlers. The logging calls in the
441.2548 -application code will remain unchanged. Here is a slight modification to the
441.2549 -previous simple module-based configuration example::
441.2550 -
441.2551 - import logging
441.2552 -
441.2553 - logger = logging.getLogger("simple_example")
441.2554 - logger.setLevel(logging.DEBUG)
441.2555 - # create file handler which logs even debug messages
441.2556 - fh = logging.FileHandler("spam.log")
441.2557 - fh.setLevel(logging.DEBUG)
441.2558 - # create console handler with a higher log level
441.2559 - ch = logging.StreamHandler()
441.2560 - ch.setLevel(logging.ERROR)
441.2561 - # create formatter and add it to the handlers
441.2562 - formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
441.2563 - ch.setFormatter(formatter)
441.2564 - fh.setFormatter(formatter)
441.2565 - # add the handlers to logger
441.2566 - logger.addHandler(ch)
441.2567 - logger.addHandler(fh)
441.2568 -
441.2569 - # "application" code
441.2570 - logger.debug("debug message")
441.2571 - logger.info("info message")
441.2572 - logger.warn("warn message")
441.2573 - logger.error("error message")
441.2574 - logger.critical("critical message")
441.2575 -
441.2576 -Notice that the "application" code does not care about multiple handlers. All
441.2577 -that changed was the addition and configuration of a new handler named *fh*.
441.2578 -
441.2579 -The ability to create new handlers with higher- or lower-severity filters can be
441.2580 -very helpful when writing and testing an application. Instead of using many
441.2581 -``print`` statements for debugging, use ``logger.debug``: Unlike the print
441.2582 -statements, which you will have to delete or comment out later, the logger.debug
441.2583 -statements can remain intact in the source code and remain dormant until you
441.2584 -need them again. At that time, the only change that needs to happen is to
441.2585 -modify the severity level of the logger and/or handler to debug.
441.2586 -
441.2587 -
441.2588 -Using logging in multiple modules
441.2589 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
441.2590 -
441.2591 -It was mentioned above that multiple calls to
441.2592 -``logging.getLogger('someLogger')`` return a reference to the same logger
441.2593 -object. This is true not only within the same module, but also across modules
441.2594 -as long as it is in the same Python interpreter process. It is true for
441.2595 -references to the same object; additionally, application code can define and
441.2596 -configure a parent logger in one module and create (but not configure) a child
441.2597 -logger in a separate module, and all logger calls to the child will pass up to
441.2598 -the parent. Here is a main module::
441.2599 -
441.2600 - import logging
441.2601 - import auxiliary_module
441.2602 -
441.2603 - # create logger with "spam_application"
441.2604 - logger = logging.getLogger("spam_application")
441.2605 - logger.setLevel(logging.DEBUG)
441.2606 - # create file handler which logs even debug messages
441.2607 - fh = logging.FileHandler("spam.log")
441.2608 - fh.setLevel(logging.DEBUG)
441.2609 - # create console handler with a higher log level
441.2610 - ch = logging.StreamHandler()
441.2611 - ch.setLevel(logging.ERROR)
441.2612 - # create formatter and add it to the handlers
441.2613 - formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
441.2614 - fh.setFormatter(formatter)
441.2615 - ch.setFormatter(formatter)
441.2616 - # add the handlers to the logger
441.2617 - logger.addHandler(fh)
441.2618 - logger.addHandler(ch)
441.2619 -
441.2620 - logger.info("creating an instance of auxiliary_module.Auxiliary")
441.2621 - a = auxiliary_module.Auxiliary()
441.2622 - logger.info("created an instance of auxiliary_module.Auxiliary")
441.2623 - logger.info("calling auxiliary_module.Auxiliary.do_something")
441.2624 - a.do_something()
441.2625 - logger.info("finished auxiliary_module.Auxiliary.do_something")
441.2626 - logger.info("calling auxiliary_module.some_function()")
441.2627 - auxiliary_module.some_function()
441.2628 - logger.info("done with auxiliary_module.some_function()")
441.2629 -
441.2630 -Here is the auxiliary module::
441.2631 -
441.2632 - import logging
441.2633 -
441.2634 - # create logger
441.2635 - module_logger = logging.getLogger("spam_application.auxiliary")
441.2636 -
441.2637 - class Auxiliary:
441.2638 - def __init__(self):
441.2639 - self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
441.2640 - self.logger.info("creating an instance of Auxiliary")
441.2641 - def do_something(self):
441.2642 - self.logger.info("doing something")
441.2643 - a = 1 + 1
441.2644 - self.logger.info("done doing something")
441.2645 -
441.2646 - def some_function():
441.2647 - module_logger.info("received a call to \"some_function\"")
441.2648 -
441.2649 -The output looks like this::
441.2650 -
441.2651 - 2005-03-23 23:47:11,663 - spam_application - INFO -
441.2652 - creating an instance of auxiliary_module.Auxiliary
441.2653 - 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
441.2654 - creating an instance of Auxiliary
441.2655 - 2005-03-23 23:47:11,665 - spam_application - INFO -
441.2656 - created an instance of auxiliary_module.Auxiliary
441.2657 - 2005-03-23 23:47:11,668 - spam_application - INFO -
441.2658 - calling auxiliary_module.Auxiliary.do_something
441.2659 - 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
441.2660 - doing something
441.2661 - 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
441.2662 - done doing something
441.2663 - 2005-03-23 23:47:11,670 - spam_application - INFO -
441.2664 - finished auxiliary_module.Auxiliary.do_something
441.2665 - 2005-03-23 23:47:11,671 - spam_application - INFO -
441.2666 - calling auxiliary_module.some_function()
441.2667 - 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
441.2668 - received a call to "some_function"
441.2669 - 2005-03-23 23:47:11,673 - spam_application - INFO -
441.2670 - done with auxiliary_module.some_function()
441.2671 -
442.1 --- a/python.editor/test/unit/data/testfiles/rst/logging.rst.indexed Sun Jan 04 13:11:53 2015 -0600
442.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
442.3 @@ -1,327 +0,0 @@
442.4 -
442.5 -
442.6 -Document 0
442.7 -Searchable Keys:
442.8 - class : BufferingHandler
442.9 - class-ig : bufferinghandler
442.10 - in : logging
442.11 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;capacity;
442.12 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
442.13 - member : flush;F;|DOCUMENTED|DOC_ONLY|;;
442.14 - member : shouldFlush;F;|DOCUMENTED|DOC_ONLY|;record;
442.15 -
442.16 -Not Searchable Keys:
442.17 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
442.18 -
442.19 -
442.20 -Document 1
442.21 -Searchable Keys:
442.22 - class : DatagramHandler
442.23 - class-ig : datagramhandler
442.24 - in : logging
442.25 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;host,port;
442.26 - member : emit;F;|DOCUMENTED|DOC_ONLY|;;
442.27 - member : makeSocket;F;|DOCUMENTED|DOC_ONLY|;;
442.28 - member : send;F;|DOCUMENTED|DOC_ONLY|;s;
442.29 -
442.30 -Not Searchable Keys:
442.31 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
442.32 -
442.33 -
442.34 -Document 2
442.35 -Searchable Keys:
442.36 - class : FileHandler
442.37 - class-ig : filehandler
442.38 - in : logging
442.39 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;filename,mode,encoding,delay;
442.40 - member : close;F;|DOCUMENTED|DOC_ONLY|;;
442.41 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
442.42 -
442.43 -Not Searchable Keys:
442.44 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
442.45 -
442.46 -
442.47 -Document 3
442.48 -Searchable Keys:
442.49 - class : Filter
442.50 - class-ig : filter
442.51 - in : logging
442.52 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;name;
442.53 - member : filter;F;|DOCUMENTED|DOC_ONLY|;record;
442.54 -
442.55 -Not Searchable Keys:
442.56 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
442.57 -
442.58 -
442.59 -Document 4
442.60 -Searchable Keys:
442.61 - class : Formatter
442.62 - class-ig : formatter
442.63 - in : logging
442.64 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;fmt,datefmt;
442.65 - member : format;F;|DOCUMENTED|DOC_ONLY|;record;
442.66 - member : formatException;F;|DOCUMENTED|DOC_ONLY|;exc_info;
442.67 - member : formatTime;F;|DOCUMENTED|DOC_ONLY|;record,datefmt;
442.68 -
442.69 -Not Searchable Keys:
442.70 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
442.71 -
442.72 -
442.73 -Document 5
442.74 -Searchable Keys:
442.75 - class : HTTPHandler
442.76 - class-ig : httphandler
442.77 - in : logging
442.78 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;host,url,method;
442.79 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
442.80 -
442.81 -Not Searchable Keys:
442.82 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
442.83 -
442.84 -
442.85 -Document 6
442.86 -Searchable Keys:
442.87 - class : Handler
442.88 - class-ig : handler
442.89 - in : logging
442.90 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;level;
442.91 - member : acquire;F;|DOCUMENTED|DOC_ONLY|;;
442.92 - member : addFilter;F;|DOCUMENTED|DOC_ONLY|;filt;
442.93 - member : close;F;|DOCUMENTED|DOC_ONLY|;;
442.94 - member : createLock;F;|DOCUMENTED|DOC_ONLY|;;
442.95 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
442.96 - member : filter;F;|DOCUMENTED|DOC_ONLY|;record;
442.97 - member : flush;F;|DOCUMENTED|DOC_ONLY|;;
442.98 - member : format;F;|DOCUMENTED|DOC_ONLY|;record;
442.99 - member : handle;F;|DOCUMENTED|DOC_ONLY|;record;
442.100 - member : handleError;F;|DOCUMENTED|DOC_ONLY|;record;
442.101 - member : release;F;|DOCUMENTED|DOC_ONLY|;;
442.102 - member : removeFilter;F;|DOCUMENTED|DOC_ONLY|;filt;
442.103 - member : setFormatter;F;|DOCUMENTED|DOC_ONLY|;form;
442.104 - member : setLevel;F;|DOCUMENTED|DOC_ONLY|;lvl;
442.105 -
442.106 -Not Searchable Keys:
442.107 -
442.108 -
442.109 -Document 7
442.110 -Searchable Keys:
442.111 - class : LogRecord
442.112 - class-ig : logrecord
442.113 - in : logging
442.114 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;name,lvl,pathname,lineno,msg,args,exc_info,func;
442.115 - member : getMessage;F;|DOCUMENTED|DOC_ONLY|;;
442.116 -
442.117 -Not Searchable Keys:
442.118 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
442.119 -
442.120 -
442.121 -Document 8
442.122 -Searchable Keys:
442.123 - class : Logger
442.124 - class-ig : logger
442.125 - in : logging
442.126 - member : addFilter;F;|DOCUMENTED|DOC_ONLY|;filt;
442.127 - member : addHandler;F;|DOCUMENTED|DOC_ONLY|;hdlr;
442.128 - member : critical;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
442.129 - member : debug;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
442.130 - member : error;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
442.131 - member : exception;F;|DOCUMENTED|DOC_ONLY|;msg,*args;
442.132 - member : filter;F;|DOCUMENTED|DOC_ONLY|;record;
442.133 - member : findCaller;F;|DOCUMENTED|DOC_ONLY|;;
442.134 - member : getEffectiveLevel;F;|DOCUMENTED|DOC_ONLY|;;
442.135 - member : handle;F;|DOCUMENTED|DOC_ONLY|;record;
442.136 - member : info;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
442.137 - member : isEnabledFor;F;|DOCUMENTED|DOC_ONLY|;lvl;
442.138 - member : log;F;|DOCUMENTED|DOC_ONLY|;lvl,msg,*args,**kwargs;
442.139 - member : makeRecord;F;|DOCUMENTED|DOC_ONLY|;name,lvl,fn,lno,msg,args,exc_info,func,extra;
442.140 - member : propagate;A;|DOCUMENTED|DOC_ONLY|;
442.141 - member : removeFilter;F;|DOCUMENTED|DOC_ONLY|;filt;
442.142 - member : removeHandler;F;|DOCUMENTED|DOC_ONLY|;hdlr;
442.143 - member : setLevel;F;|DOCUMENTED|DOC_ONLY|;lvl;
442.144 - member : warning;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
442.145 -
442.146 -Not Searchable Keys:
442.147 -
442.148 -
442.149 -Document 9
442.150 -Searchable Keys:
442.151 - class : LoggerAdapter
442.152 - class-ig : loggeradapter
442.153 - in : logging
442.154 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;logger,extra;
442.155 - member : process;F;|DOCUMENTED|DOC_ONLY|;msg,kwargs;
442.156 -
442.157 -Not Searchable Keys:
442.158 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
442.159 -
442.160 -
442.161 -Document 10
442.162 -Searchable Keys:
442.163 - class : MemoryHandler
442.164 - class-ig : memoryhandler
442.165 - in : logging
442.166 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;capacity,flushLevel,target;
442.167 - member : close;F;|DOCUMENTED|DOC_ONLY|;;
442.168 - member : flush;F;|DOCUMENTED|DOC_ONLY|;;
442.169 - member : setTarget;F;|DOCUMENTED|DOC_ONLY|;target;
442.170 - member : shouldFlush;F;|DOCUMENTED|DOC_ONLY|;record;
442.171 -
442.172 -Not Searchable Keys:
442.173 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
442.174 -
442.175 -
442.176 -Document 11
442.177 -Searchable Keys:
442.178 - class : NTEventLogHandler
442.179 - class-ig : nteventloghandler
442.180 - in : logging
442.181 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;appname,dllname,logtype;
442.182 - member : close;F;|DOCUMENTED|DOC_ONLY|;;
442.183 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
442.184 - member : getEventCategory;F;|DOCUMENTED|DOC_ONLY|;record;
442.185 - member : getEventType;F;|DOCUMENTED|DOC_ONLY|;record;
442.186 - member : getMessageID;F;|DOCUMENTED|DOC_ONLY|;record;
442.187 -
442.188 -Not Searchable Keys:
442.189 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
442.190 -
442.191 -
442.192 -Document 12
442.193 -Searchable Keys:
442.194 - class : RotatingFileHandler
442.195 - class-ig : rotatingfilehandler
442.196 - in : logging
442.197 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;filename,mode,maxBytes,backupCount,encoding,delay;
442.198 - member : doRollover;F;|DOCUMENTED|DOC_ONLY|;;
442.199 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
442.200 -
442.201 -Not Searchable Keys:
442.202 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
442.203 -
442.204 -
442.205 -Document 13
442.206 -Searchable Keys:
442.207 - class : SMTPHandler
442.208 - class-ig : smtphandler
442.209 - in : logging
442.210 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;mailhost,fromaddr,toaddrs,subject,credentials;
442.211 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
442.212 - member : getSubject;F;|DOCUMENTED|DOC_ONLY|;record;
442.213 -
442.214 -Not Searchable Keys:
442.215 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
442.216 -
442.217 -
442.218 -Document 14
442.219 -Searchable Keys:
442.220 - class : SocketHandler
442.221 - class-ig : sockethandler
442.222 - in : logging
442.223 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;host,port;
442.224 - member : close;F;|DOCUMENTED|DOC_ONLY|;;
442.225 - member : emit;F;|DOCUMENTED|DOC_ONLY|;;
442.226 - member : handleError;F;|DOCUMENTED|DOC_ONLY|;;
442.227 - member : makePickle;F;|DOCUMENTED|DOC_ONLY|;record;
442.228 - member : makeSocket;F;|DOCUMENTED|DOC_ONLY|;;
442.229 - member : send;F;|DOCUMENTED|DOC_ONLY|;packet;
442.230 -
442.231 -Not Searchable Keys:
442.232 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
442.233 -
442.234 -
442.235 -Document 15
442.236 -Searchable Keys:
442.237 - class : StreamHandler
442.238 - class-ig : streamhandler
442.239 - in : logging
442.240 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;strm;
442.241 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
442.242 - member : flush;F;|DOCUMENTED|DOC_ONLY|;;
442.243 -
442.244 -Not Searchable Keys:
442.245 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
442.246 -
442.247 -
442.248 -Document 16
442.249 -Searchable Keys:
442.250 - class : SysLogHandler
442.251 - class-ig : sysloghandler
442.252 - in : logging
442.253 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;address,facility;
442.254 - member : close;F;|DOCUMENTED|DOC_ONLY|;;
442.255 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
442.256 - member : encodePriority;F;|DOCUMENTED|DOC_ONLY|;facility,priority;
442.257 -
442.258 -Not Searchable Keys:
442.259 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
442.260 -
442.261 -
442.262 -Document 17
442.263 -Searchable Keys:
442.264 - class : TimedRotatingFileHandler
442.265 - class-ig : timedrotatingfilehandler
442.266 - in : logging
442.267 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;filename,when,interval,backupCount,encoding,delay,utc;
442.268 - member : doRollover;F;|DOCUMENTED|DOC_ONLY|;;
442.269 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
442.270 -
442.271 -Not Searchable Keys:
442.272 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
442.273 -
442.274 -
442.275 -Document 18
442.276 -Searchable Keys:
442.277 - class : WatchedFileHandler
442.278 - class-ig : watchedfilehandler
442.279 - in : logging
442.280 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;filename,mode,encoding,delay;
442.281 - member : emit;F;|DOCUMENTED|DOC_ONLY|;record;
442.282 -
442.283 -Not Searchable Keys:
442.284 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
442.285 -
442.286 -
442.287 -Document 19
442.288 -Searchable Keys:
442.289 - item : BufferingHandler;C;|DOCUMENTED|DOC_ONLY|;
442.290 - item : DatagramHandler;C;|DOCUMENTED|DOC_ONLY|;
442.291 - item : FileHandler;C;|DOCUMENTED|DOC_ONLY|;
442.292 - item : Filter;C;|DOCUMENTED|DOC_ONLY|;
442.293 - item : Formatter;C;|DOCUMENTED|DOC_ONLY|;
442.294 - item : HTTPHandler;C;|DOCUMENTED|DOC_ONLY|;
442.295 - item : Handler;C;|DOCUMENTED|DOC_ONLY|;
442.296 - item : LogRecord;C;|DOCUMENTED|DOC_ONLY|;
442.297 - item : Logger;C;|DOCUMENTED|DOC_ONLY|;
442.298 - item : LoggerAdapter;C;|DOCUMENTED|DOC_ONLY|;
442.299 - item : MemoryHandler;C;|DOCUMENTED|DOC_ONLY|;
442.300 - item : NTEventLogHandler;C;|DOCUMENTED|DOC_ONLY|;
442.301 - item : RotatingFileHandler;C;|DOCUMENTED|DOC_ONLY|;
442.302 - item : SMTPHandler;C;|DOCUMENTED|DOC_ONLY|;
442.303 - item : SocketHandler;C;|DOCUMENTED|DOC_ONLY|;
442.304 - item : StreamHandler;C;|DOCUMENTED|DOC_ONLY|;
442.305 - item : SysLogHandler;C;|DOCUMENTED|DOC_ONLY|;
442.306 - item : TimedRotatingFileHandler;C;|DOCUMENTED|DOC_ONLY|;
442.307 - item : WatchedFileHandler;C;|DOCUMENTED|DOC_ONLY|;
442.308 - item : addLevelName;F;|DOCUMENTED|DOC_ONLY|;lvl,levelName;
442.309 - item : basicConfig;F;|DOCUMENTED|DOC_ONLY|;**kwargs;
442.310 - item : critical;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
442.311 - item : debug;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
442.312 - item : disable;F;|DOCUMENTED|DOC_ONLY|;lvl;
442.313 - item : error;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
442.314 - item : exception;F;|DOCUMENTED|DOC_ONLY|;msg,*args;
442.315 - item : fileConfig;F;|DOCUMENTED|DOC_ONLY|;fname,defaults;
442.316 - item : getLevelName;F;|DOCUMENTED|DOC_ONLY|;lvl;
442.317 - item : getLogger;F;|DOCUMENTED|DOC_ONLY|;name;
442.318 - item : getLoggerClass;F;|DOCUMENTED|DOC_ONLY|;;
442.319 - item : info;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
442.320 - item : listen;F;|DOCUMENTED|DOC_ONLY|;port;
442.321 - item : log;F;|DOCUMENTED|DOC_ONLY|;level,msg,*args,**kwargs;
442.322 - item : makeLogRecord;F;|DOCUMENTED|DOC_ONLY|;attrdict;
442.323 - item : setLoggerClass;F;|DOCUMENTED|DOC_ONLY|;klass;
442.324 - item : shutdown;F;|DOCUMENTED|DOC_ONLY|;;
442.325 - item : stopListening;F;|DOCUMENTED|DOC_ONLY|;;
442.326 - item : warning;F;|DOCUMENTED|DOC_ONLY|;msg,*args,**kwargs;
442.327 - module : logging
442.328 -
442.329 -Not Searchable Keys:
442.330 - modattrs : S
443.1 --- a/python.editor/test/unit/data/testfiles/rst/operator.rst Sun Jan 04 13:11:53 2015 -0600
443.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
443.3 @@ -1,659 +0,0 @@
443.4 -:mod:`operator` --- Standard operators as functions
443.5 -===================================================
443.6 -
443.7 -.. module:: operator
443.8 - :synopsis: Functions corresponding to the standard operators.
443.9 -.. sectionauthor:: Skip Montanaro <skip@automatrix.com>
443.10 -
443.11 -
443.12 -.. testsetup::
443.13 -
443.14 - import operator
443.15 - from operator import itemgetter
443.16 -
443.17 -
443.18 -The :mod:`operator` module exports a set of functions implemented in C
443.19 -corresponding to the intrinsic operators of Python. For example,
443.20 -``operator.add(x, y)`` is equivalent to the expression ``x+y``. The function
443.21 -names are those used for special class methods; variants without leading and
443.22 -trailing ``__`` are also provided for convenience.
443.23 -
443.24 -The functions fall into categories that perform object comparisons, logical
443.25 -operations, mathematical operations, sequence operations, and abstract type
443.26 -tests.
443.27 -
443.28 -The object comparison functions are useful for all objects, and are named after
443.29 -the rich comparison operators they support:
443.30 -
443.31 -
443.32 -.. function:: lt(a, b)
443.33 - le(a, b)
443.34 - eq(a, b)
443.35 - ne(a, b)
443.36 - ge(a, b)
443.37 - gt(a, b)
443.38 - __lt__(a, b)
443.39 - __le__(a, b)
443.40 - __eq__(a, b)
443.41 - __ne__(a, b)
443.42 - __ge__(a, b)
443.43 - __gt__(a, b)
443.44 -
443.45 - Perform "rich comparisons" between *a* and *b*. Specifically, ``lt(a, b)`` is
443.46 - equivalent to ``a < b``, ``le(a, b)`` is equivalent to ``a <= b``, ``eq(a,
443.47 - b)`` is equivalent to ``a == b``, ``ne(a, b)`` is equivalent to ``a != b``,
443.48 - ``gt(a, b)`` is equivalent to ``a > b`` and ``ge(a, b)`` is equivalent to ``a
443.49 - >= b``. Note that unlike the built-in :func:`cmp`, these functions can
443.50 - return any value, which may or may not be interpretable as a Boolean value.
443.51 - See :ref:`comparisons` for more information about rich comparisons.
443.52 -
443.53 - .. versionadded:: 2.2
443.54 -
443.55 -The logical operations are also generally applicable to all objects, and support
443.56 -truth tests, identity tests, and boolean operations:
443.57 -
443.58 -
443.59 -.. function:: not_(obj)
443.60 - __not__(obj)
443.61 -
443.62 - Return the outcome of :keyword:`not` *obj*. (Note that there is no
443.63 - :meth:`__not__` method for object instances; only the interpreter core defines
443.64 - this operation. The result is affected by the :meth:`__nonzero__` and
443.65 - :meth:`__len__` methods.)
443.66 -
443.67 -
443.68 -.. function:: truth(obj)
443.69 -
443.70 - Return :const:`True` if *obj* is true, and :const:`False` otherwise. This is
443.71 - equivalent to using the :class:`bool` constructor.
443.72 -
443.73 -
443.74 -.. function:: is_(a, b)
443.75 -
443.76 - Return ``a is b``. Tests object identity.
443.77 -
443.78 - .. versionadded:: 2.3
443.79 -
443.80 -
443.81 -.. function:: is_not(a, b)
443.82 -
443.83 - Return ``a is not b``. Tests object identity.
443.84 -
443.85 - .. versionadded:: 2.3
443.86 -
443.87 -The mathematical and bitwise operations are the most numerous:
443.88 -
443.89 -
443.90 -.. function:: abs(obj)
443.91 - __abs__(obj)
443.92 -
443.93 - Return the absolute value of *obj*.
443.94 -
443.95 -
443.96 -.. function:: add(a, b)
443.97 - __add__(a, b)
443.98 -
443.99 - Return ``a + b``, for *a* and *b* numbers.
443.100 -
443.101 -
443.102 -.. function:: and_(a, b)
443.103 - __and__(a, b)
443.104 -
443.105 - Return the bitwise and of *a* and *b*.
443.106 -
443.107 -
443.108 -.. function:: div(a, b)
443.109 - __div__(a, b)
443.110 -
443.111 - Return ``a / b`` when ``__future__.division`` is not in effect. This is
443.112 - also known as "classic" division.
443.113 -
443.114 -
443.115 -.. function:: floordiv(a, b)
443.116 - __floordiv__(a, b)
443.117 -
443.118 - Return ``a // b``.
443.119 -
443.120 - .. versionadded:: 2.2
443.121 -
443.122 -
443.123 -.. function:: inv(obj)
443.124 - invert(obj)
443.125 - __inv__(obj)
443.126 - __invert__(obj)
443.127 -
443.128 - Return the bitwise inverse of the number *obj*. This is equivalent to ``~obj``.
443.129 -
443.130 - .. versionadded:: 2.0
443.131 - The names :func:`invert` and :func:`__invert__`.
443.132 -
443.133 -
443.134 -.. function:: lshift(a, b)
443.135 - __lshift__(a, b)
443.136 -
443.137 - Return *a* shifted left by *b*.
443.138 -
443.139 -
443.140 -.. function:: mod(a, b)
443.141 - __mod__(a, b)
443.142 -
443.143 - Return ``a % b``.
443.144 -
443.145 -
443.146 -.. function:: mul(a, b)
443.147 - __mul__(a, b)
443.148 -
443.149 - Return ``a * b``, for *a* and *b* numbers.
443.150 -
443.151 -
443.152 -.. function:: neg(obj)
443.153 - __neg__(obj)
443.154 -
443.155 - Return *obj* negated.
443.156 -
443.157 -
443.158 -.. function:: or_(a, b)
443.159 - __or__(a, b)
443.160 -
443.161 - Return the bitwise or of *a* and *b*.
443.162 -
443.163 -
443.164 -.. function:: pos(obj)
443.165 - __pos__(obj)
443.166 -
443.167 - Return *obj* positive.
443.168 -
443.169 -
443.170 -.. function:: pow(a, b)
443.171 - __pow__(a, b)
443.172 -
443.173 - Return ``a ** b``, for *a* and *b* numbers.
443.174 -
443.175 - .. versionadded:: 2.3
443.176 -
443.177 -
443.178 -.. function:: rshift(a, b)
443.179 - __rshift__(a, b)
443.180 -
443.181 - Return *a* shifted right by *b*.
443.182 -
443.183 -
443.184 -.. function:: sub(a, b)
443.185 - __sub__(a, b)
443.186 -
443.187 - Return ``a - b``.
443.188 -
443.189 -
443.190 -.. function:: truediv(a, b)
443.191 - __truediv__(a, b)
443.192 -
443.193 - Return ``a / b`` when ``__future__.division`` is in effect. This is also
443.194 - known as "true" division.
443.195 -
443.196 - .. versionadded:: 2.2
443.197 -
443.198 -
443.199 -.. function:: xor(a, b)
443.200 - __xor__(a, b)
443.201 -
443.202 - Return the bitwise exclusive or of *a* and *b*.
443.203 -
443.204 -
443.205 -.. function:: index(a)
443.206 - __index__(a)
443.207 -
443.208 - Return *a* converted to an integer. Equivalent to ``a.__index__()``.
443.209 -
443.210 - .. versionadded:: 2.5
443.211 -
443.212 -
443.213 -Operations which work with sequences include:
443.214 -
443.215 -.. function:: concat(a, b)
443.216 - __concat__(a, b)
443.217 -
443.218 - Return ``a + b`` for *a* and *b* sequences.
443.219 -
443.220 -
443.221 -.. function:: contains(a, b)
443.222 - __contains__(a, b)
443.223 -
443.224 - Return the outcome of the test ``b in a``. Note the reversed operands.
443.225 -
443.226 - .. versionadded:: 2.0
443.227 - The name :func:`__contains__`.
443.228 -
443.229 -
443.230 -.. function:: countOf(a, b)
443.231 -
443.232 - Return the number of occurrences of *b* in *a*.
443.233 -
443.234 -
443.235 -.. function:: delitem(a, b)
443.236 - __delitem__(a, b)
443.237 -
443.238 - Remove the value of *a* at index *b*.
443.239 -
443.240 -
443.241 -.. function:: delslice(a, b, c)
443.242 - __delslice__(a, b, c)
443.243 -
443.244 - Delete the slice of *a* from index *b* to index *c-1*.
443.245 -
443.246 -
443.247 -.. function:: getitem(a, b)
443.248 - __getitem__(a, b)
443.249 -
443.250 - Return the value of *a* at index *b*.
443.251 -
443.252 -
443.253 -.. function:: getslice(a, b, c)
443.254 - __getslice__(a, b, c)
443.255 -
443.256 - Return the slice of *a* from index *b* to index *c-1*.
443.257 -
443.258 -
443.259 -.. function:: indexOf(a, b)
443.260 -
443.261 - Return the index of the first of occurrence of *b* in *a*.
443.262 -
443.263 -
443.264 -.. function:: repeat(a, b)
443.265 - __repeat__(a, b)
443.266 -
443.267 - Return ``a * b`` where *a* is a sequence and *b* is an integer.
443.268 -
443.269 -
443.270 -.. function:: sequenceIncludes(...)
443.271 -
443.272 - .. deprecated:: 2.0
443.273 - Use :func:`contains` instead.
443.274 -
443.275 - Alias for :func:`contains`.
443.276 -
443.277 -
443.278 -.. function:: setitem(a, b, c)
443.279 - __setitem__(a, b, c)
443.280 -
443.281 - Set the value of *a* at index *b* to *c*.
443.282 -
443.283 -
443.284 -.. function:: setslice(a, b, c, v)
443.285 - __setslice__(a, b, c, v)
443.286 -
443.287 - Set the slice of *a* from index *b* to index *c-1* to the sequence *v*.
443.288 -
443.289 -Many operations have an "in-place" version. The following functions provide a
443.290 -more primitive access to in-place operators than the usual syntax does; for
443.291 -example, the :term:`statement` ``x += y`` is equivalent to
443.292 -``x = operator.iadd(x, y)``. Another way to put it is to say that
443.293 -``z = operator.iadd(x, y)`` is equivalent to the compound statement
443.294 -``z = x; z += y``.
443.295 -
443.296 -.. function:: iadd(a, b)
443.297 - __iadd__(a, b)
443.298 -
443.299 - ``a = iadd(a, b)`` is equivalent to ``a += b``.
443.300 -
443.301 - .. versionadded:: 2.5
443.302 -
443.303 -
443.304 -.. function:: iand(a, b)
443.305 - __iand__(a, b)
443.306 -
443.307 - ``a = iand(a, b)`` is equivalent to ``a &= b``.
443.308 -
443.309 - .. versionadded:: 2.5
443.310 -
443.311 -
443.312 -.. function:: iconcat(a, b)
443.313 - __iconcat__(a, b)
443.314 -
443.315 - ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.
443.316 -
443.317 - .. versionadded:: 2.5
443.318 -
443.319 -
443.320 -.. function:: idiv(a, b)
443.321 - __idiv__(a, b)
443.322 -
443.323 - ``a = idiv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division`` is
443.324 - not in effect.
443.325 -
443.326 - .. versionadded:: 2.5
443.327 -
443.328 -
443.329 -.. function:: ifloordiv(a, b)
443.330 - __ifloordiv__(a, b)
443.331 -
443.332 - ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.
443.333 -
443.334 - .. versionadded:: 2.5
443.335 -
443.336 -
443.337 -.. function:: ilshift(a, b)
443.338 - __ilshift__(a, b)
443.339 -
443.340 - ``a = ilshift(a, b)`` is equivalent to ``a <``\ ``<= b``.
443.341 -
443.342 - .. versionadded:: 2.5
443.343 -
443.344 -
443.345 -.. function:: imod(a, b)
443.346 - __imod__(a, b)
443.347 -
443.348 - ``a = imod(a, b)`` is equivalent to ``a %= b``.
443.349 -
443.350 - .. versionadded:: 2.5
443.351 -
443.352 -
443.353 -.. function:: imul(a, b)
443.354 - __imul__(a, b)
443.355 -
443.356 - ``a = imul(a, b)`` is equivalent to ``a *= b``.
443.357 -
443.358 - .. versionadded:: 2.5
443.359 -
443.360 -
443.361 -.. function:: ior(a, b)
443.362 - __ior__(a, b)
443.363 -
443.364 - ``a = ior(a, b)`` is equivalent to ``a |= b``.
443.365 -
443.366 - .. versionadded:: 2.5
443.367 -
443.368 -
443.369 -.. function:: ipow(a, b)
443.370 - __ipow__(a, b)
443.371 -
443.372 - ``a = ipow(a, b)`` is equivalent to ``a **= b``.
443.373 -
443.374 - .. versionadded:: 2.5
443.375 -
443.376 -
443.377 -.. function:: irepeat(a, b)
443.378 - __irepeat__(a, b)
443.379 -
443.380 - ``a = irepeat(a, b)`` is equivalent to ``a *= b`` where *a* is a sequence and
443.381 - *b* is an integer.
443.382 -
443.383 - .. versionadded:: 2.5
443.384 -
443.385 -
443.386 -.. function:: irshift(a, b)
443.387 - __irshift__(a, b)
443.388 -
443.389 - ``a = irshift(a, b)`` is equivalent to ``a >>= b``.
443.390 -
443.391 - .. versionadded:: 2.5
443.392 -
443.393 -
443.394 -.. function:: isub(a, b)
443.395 - __isub__(a, b)
443.396 -
443.397 - ``a = isub(a, b)`` is equivalent to ``a -= b``.
443.398 -
443.399 - .. versionadded:: 2.5
443.400 -
443.401 -
443.402 -.. function:: itruediv(a, b)
443.403 - __itruediv__(a, b)
443.404 -
443.405 - ``a = itruediv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division``
443.406 - is in effect.
443.407 -
443.408 - .. versionadded:: 2.5
443.409 -
443.410 -
443.411 -.. function:: ixor(a, b)
443.412 - __ixor__(a, b)
443.413 -
443.414 - ``a = ixor(a, b)`` is equivalent to ``a ^= b``.
443.415 -
443.416 - .. versionadded:: 2.5
443.417 -
443.418 -
443.419 -The :mod:`operator` module also defines a few predicates to test the type of
443.420 -objects.
443.421 -
443.422 -.. note::
443.423 -
443.424 - Be careful not to misinterpret the results of these functions; only
443.425 - :func:`isCallable` has any measure of reliability with instance objects.
443.426 - For example:
443.427 -
443.428 - >>> class C:
443.429 - ... pass
443.430 - ...
443.431 - >>> import operator
443.432 - >>> obj = C()
443.433 - >>> operator.isMappingType(obj)
443.434 - True
443.435 -
443.436 -.. note::
443.437 -
443.438 - Python 3 is expected to introduce abstract base classes for
443.439 - collection types, so it should be possible to write, for example,
443.440 - ``isinstance(obj, collections.Mapping)`` and ``isinstance(obj,
443.441 - collections.Sequence)``.
443.442 -
443.443 -.. function:: isCallable(obj)
443.444 -
443.445 - .. deprecated:: 2.0
443.446 - Use the :func:`callable` built-in function instead.
443.447 -
443.448 - Returns true if the object *obj* can be called like a function, otherwise it
443.449 - returns false. True is returned for functions, bound and unbound methods, class
443.450 - objects, and instance objects which support the :meth:`__call__` method.
443.451 -
443.452 -
443.453 -.. function:: isMappingType(obj)
443.454 -
443.455 - Returns true if the object *obj* supports the mapping interface. This is true for
443.456 - dictionaries and all instance objects defining :meth:`__getitem__`.
443.457 -
443.458 - .. warning::
443.459 -
443.460 - There is no reliable way to test if an instance supports the complete mapping
443.461 - protocol since the interface itself is ill-defined. This makes this test less
443.462 - useful than it otherwise might be.
443.463 -
443.464 -
443.465 -.. function:: isNumberType(obj)
443.466 -
443.467 - Returns true if the object *obj* represents a number. This is true for all
443.468 - numeric types implemented in C.
443.469 -
443.470 - .. warning::
443.471 -
443.472 - There is no reliable way to test if an instance supports the complete numeric
443.473 - interface since the interface itself is ill-defined. This makes this test less
443.474 - useful than it otherwise might be.
443.475 -
443.476 -
443.477 -.. function:: isSequenceType(obj)
443.478 -
443.479 - Returns true if the object *obj* supports the sequence protocol. This returns true
443.480 - for all objects which define sequence methods in C, and for all instance objects
443.481 - defining :meth:`__getitem__`.
443.482 -
443.483 - .. warning::
443.484 -
443.485 - There is no reliable way to test if an instance supports the complete sequence
443.486 - interface since the interface itself is ill-defined. This makes this test less
443.487 - useful than it otherwise might be.
443.488 -
443.489 -Example: Build a dictionary that maps the ordinals from ``0`` to ``255`` to
443.490 -their character equivalents.
443.491 -
443.492 - >>> d = {}
443.493 - >>> keys = range(256)
443.494 - >>> vals = map(chr, keys)
443.495 - >>> map(operator.setitem, [d]*len(keys), keys, vals) # doctest: +SKIP
443.496 -
443.497 -.. XXX: find a better, readable, example
443.498 -
443.499 -The :mod:`operator` module also defines tools for generalized attribute and item
443.500 -lookups. These are useful for making fast field extractors as arguments for
443.501 -:func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
443.502 -expect a function argument.
443.503 -
443.504 -
443.505 -.. function:: attrgetter(attr[, args...])
443.506 -
443.507 - Return a callable object that fetches *attr* from its operand. If more than one
443.508 - attribute is requested, returns a tuple of attributes. After,
443.509 - ``f = attrgetter('name')``, the call ``f(b)`` returns ``b.name``. After,
443.510 - ``f = attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name,
443.511 - b.date)``.
443.512 -
443.513 - The attribute names can also contain dots; after ``f = attrgetter('date.month')``,
443.514 - the call ``f(b)`` returns ``b.date.month``.
443.515 -
443.516 - .. versionadded:: 2.4
443.517 -
443.518 - .. versionchanged:: 2.5
443.519 - Added support for multiple attributes.
443.520 -
443.521 - .. versionchanged:: 2.6
443.522 - Added support for dotted attributes.
443.523 -
443.524 -
443.525 -.. function:: itemgetter(item[, args...])
443.526 -
443.527 - Return a callable object that fetches *item* from its operand using the
443.528 - operand's :meth:`__getitem__` method. If multiple items are specified,
443.529 - returns a tuple of lookup values. Equivalent to::
443.530 -
443.531 - def itemgetter(*items):
443.532 - if len(items) == 1:
443.533 - item = items[0]
443.534 - def g(obj):
443.535 - return obj[item]
443.536 - else:
443.537 - def g(obj):
443.538 - return tuple(obj[item] for item in items)
443.539 - return g
443.540 -
443.541 - The items can be any type accepted by the operand's :meth:`__getitem__`
443.542 - method. Dictionaries accept any hashable value. Lists, tuples, and
443.543 - strings accept an index or a slice:
443.544 -
443.545 - >>> itemgetter(1)('ABCDEFG')
443.546 - 'B'
443.547 - >>> itemgetter(1,3,5)('ABCDEFG')
443.548 - ('B', 'D', 'F')
443.549 - >>> itemgetter(slice(2,None))('ABCDEFG')
443.550 - 'CDEFG'
443.551 -
443.552 - .. versionadded:: 2.4
443.553 -
443.554 - .. versionchanged:: 2.5
443.555 - Added support for multiple item extraction.
443.556 -
443.557 - Example of using :func:`itemgetter` to retrieve specific fields from a
443.558 - tuple record:
443.559 -
443.560 - >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
443.561 - >>> getcount = itemgetter(1)
443.562 - >>> map(getcount, inventory)
443.563 - [3, 2, 5, 1]
443.564 - >>> sorted(inventory, key=getcount)
443.565 - [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
443.566 -
443.567 -
443.568 -.. function:: methodcaller(name[, args...])
443.569 -
443.570 - Return a callable object that calls the method *name* on its operand. If
443.571 - additional arguments and/or keyword arguments are given, they will be given
443.572 - to the method as well. After ``f = methodcaller('name')``, the call ``f(b)``
443.573 - returns ``b.name()``. After ``f = methodcaller('name', 'foo', bar=1)``, the
443.574 - call ``f(b)`` returns ``b.name('foo', bar=1)``.
443.575 -
443.576 - .. versionadded:: 2.6
443.577 -
443.578 -
443.579 -.. _operator-map:
443.580 -
443.581 -Mapping Operators to Functions
443.582 -------------------------------
443.583 -
443.584 -This table shows how abstract operations correspond to operator symbols in the
443.585 -Python syntax and the functions in the :mod:`operator` module.
443.586 -
443.587 -+-----------------------+-------------------------+---------------------------------+
443.588 -| Operation | Syntax | Function |
443.589 -+=======================+=========================+=================================+
443.590 -| Addition | ``a + b`` | ``add(a, b)`` |
443.591 -+-----------------------+-------------------------+---------------------------------+
443.592 -| Concatenation | ``seq1 + seq2`` | ``concat(seq1, seq2)`` |
443.593 -+-----------------------+-------------------------+---------------------------------+
443.594 -| Containment Test | ``obj in seq`` | ``contains(seq, obj)`` |
443.595 -+-----------------------+-------------------------+---------------------------------+
443.596 -| Division | ``a / b`` | ``div(a, b)`` (without |
443.597 -| | | ``__future__.division``) |
443.598 -+-----------------------+-------------------------+---------------------------------+
443.599 -| Division | ``a / b`` | ``truediv(a, b)`` (with |
443.600 -| | | ``__future__.division``) |
443.601 -+-----------------------+-------------------------+---------------------------------+
443.602 -| Division | ``a // b`` | ``floordiv(a, b)`` |
443.603 -+-----------------------+-------------------------+---------------------------------+
443.604 -| Bitwise And | ``a & b`` | ``and_(a, b)`` |
443.605 -+-----------------------+-------------------------+---------------------------------+
443.606 -| Bitwise Exclusive Or | ``a ^ b`` | ``xor(a, b)`` |
443.607 -+-----------------------+-------------------------+---------------------------------+
443.608 -| Bitwise Inversion | ``~ a`` | ``invert(a)`` |
443.609 -+-----------------------+-------------------------+---------------------------------+
443.610 -| Bitwise Or | ``a | b`` | ``or_(a, b)`` |
443.611 -+-----------------------+-------------------------+---------------------------------+
443.612 -| Exponentiation | ``a ** b`` | ``pow(a, b)`` |
443.613 -+-----------------------+-------------------------+---------------------------------+
443.614 -| Identity | ``a is b`` | ``is_(a, b)`` |
443.615 -+-----------------------+-------------------------+---------------------------------+
443.616 -| Identity | ``a is not b`` | ``is_not(a, b)`` |
443.617 -+-----------------------+-------------------------+---------------------------------+
443.618 -| Indexed Assignment | ``obj[k] = v`` | ``setitem(obj, k, v)`` |
443.619 -+-----------------------+-------------------------+---------------------------------+
443.620 -| Indexed Deletion | ``del obj[k]`` | ``delitem(obj, k)`` |
443.621 -+-----------------------+-------------------------+---------------------------------+
443.622 -| Indexing | ``obj[k]`` | ``getitem(obj, k)`` |
443.623 -+-----------------------+-------------------------+---------------------------------+
443.624 -| Left Shift | ``a << b`` | ``lshift(a, b)`` |
443.625 -+-----------------------+-------------------------+---------------------------------+
443.626 -| Modulo | ``a % b`` | ``mod(a, b)`` |
443.627 -+-----------------------+-------------------------+---------------------------------+
443.628 -| Multiplication | ``a * b`` | ``mul(a, b)`` |
443.629 -+-----------------------+-------------------------+---------------------------------+
443.630 -| Negation (Arithmetic) | ``- a`` | ``neg(a)`` |
443.631 -+-----------------------+-------------------------+---------------------------------+
443.632 -| Negation (Logical) | ``not a`` | ``not_(a)`` |
443.633 -+-----------------------+-------------------------+---------------------------------+
443.634 -| Right Shift | ``a >> b`` | ``rshift(a, b)`` |
443.635 -+-----------------------+-------------------------+---------------------------------+
443.636 -| Sequence Repetition | ``seq * i`` | ``repeat(seq, i)`` |
443.637 -+-----------------------+-------------------------+---------------------------------+
443.638 -| Slice Assignment | ``seq[i:j] = values`` | ``setslice(seq, i, j, values)`` |
443.639 -+-----------------------+-------------------------+---------------------------------+
443.640 -| Slice Deletion | ``del seq[i:j]`` | ``delslice(seq, i, j)`` |
443.641 -+-----------------------+-------------------------+---------------------------------+
443.642 -| Slicing | ``seq[i:j]`` | ``getslice(seq, i, j)`` |
443.643 -+-----------------------+-------------------------+---------------------------------+
443.644 -| String Formatting | ``s % obj`` | ``mod(s, obj)`` |
443.645 -+-----------------------+-------------------------+---------------------------------+
443.646 -| Subtraction | ``a - b`` | ``sub(a, b)`` |
443.647 -+-----------------------+-------------------------+---------------------------------+
443.648 -| Truth Test | ``obj`` | ``truth(obj)`` |
443.649 -+-----------------------+-------------------------+---------------------------------+
443.650 -| Ordering | ``a < b`` | ``lt(a, b)`` |
443.651 -+-----------------------+-------------------------+---------------------------------+
443.652 -| Ordering | ``a <= b`` | ``le(a, b)`` |
443.653 -+-----------------------+-------------------------+---------------------------------+
443.654 -| Equality | ``a == b`` | ``eq(a, b)`` |
443.655 -+-----------------------+-------------------------+---------------------------------+
443.656 -| Difference | ``a != b`` | ``ne(a, b)`` |
443.657 -+-----------------------+-------------------------+---------------------------------+
443.658 -| Ordering | ``a >= b`` | ``ge(a, b)`` |
443.659 -+-----------------------+-------------------------+---------------------------------+
443.660 -| Ordering | ``a > b`` | ``gt(a, b)`` |
443.661 -+-----------------------+-------------------------+---------------------------------+
443.662 -
444.1 --- a/python.editor/test/unit/data/testfiles/rst/operator.rst.indexed Sun Jan 04 13:11:53 2015 -0600
444.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
444.3 @@ -1,365 +0,0 @@
444.4 -
444.5 -
444.6 -Document 0
444.7 -Searchable Keys:
444.8 - class : bool
444.9 - class-ig : bool
444.10 - in : operator
444.11 - member : __abs__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.12 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.13 - member : __and__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.14 - member : __div__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.15 - member : __floordiv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.16 - member : __index__;F;|DOCUMENTED|DOC_ONLY|;a;
444.17 - member : __invert__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.18 - member : __lshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.19 - member : __mod__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.20 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.21 - member : __neg__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.22 - member : __or__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.23 - member : __pos__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.24 - member : __pow__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.25 - member : __rshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.26 - member : __sub__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.27 - member : __truediv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.28 - member : __xor__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.29 -
444.30 -Not Searchable Keys:
444.31 -
444.32 -
444.33 -Document 1
444.34 -Searchable Keys:
444.35 - class : complex
444.36 - class-ig : complex
444.37 - in : operator
444.38 - member : __abs__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.39 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.40 - member : __div__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.41 - member : __eq__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.42 - member : __floordiv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.43 - member : __ge__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.44 - member : __gt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.45 - member : __le__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.46 - member : __lt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.47 - member : __mod__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.48 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.49 - member : __ne__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.50 - member : __neg__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.51 - member : __pos__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.52 - member : __pow__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.53 - member : __sub__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.54 - member : __truediv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.55 -
444.56 -Not Searchable Keys:
444.57 -
444.58 -
444.59 -Document 2
444.60 -Searchable Keys:
444.61 - class : dict
444.62 - class-ig : dict
444.63 - in : operator
444.64 - member : __contains__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.65 - member : __delitem__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.66 - member : __eq__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.67 - member : __ge__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.68 - member : __getitem__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.69 - member : __gt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.70 - member : __le__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.71 - member : __lt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.72 - member : __ne__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.73 - member : __setitem__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
444.74 -
444.75 -Not Searchable Keys:
444.76 -
444.77 -
444.78 -Document 3
444.79 -Searchable Keys:
444.80 - class : float
444.81 - class-ig : float
444.82 - in : operator
444.83 - member : __abs__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.84 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.85 - member : __div__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.86 - member : __eq__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.87 - member : __floordiv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.88 - member : __ge__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.89 - member : __gt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.90 - member : __le__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.91 - member : __lt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.92 - member : __mod__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.93 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.94 - member : __ne__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.95 - member : __neg__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.96 - member : __pos__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.97 - member : __pow__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.98 - member : __sub__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.99 - member : __truediv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.100 -
444.101 -Not Searchable Keys:
444.102 -
444.103 -
444.104 -Document 4
444.105 -Searchable Keys:
444.106 - class : int
444.107 - class-ig : int
444.108 - in : operator
444.109 - member : __abs__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.110 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.111 - member : __and__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.112 - member : __div__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.113 - member : __floordiv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.114 - member : __index__;F;|DOCUMENTED|DOC_ONLY|;a;
444.115 - member : __invert__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.116 - member : __lshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.117 - member : __mod__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.118 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.119 - member : __neg__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.120 - member : __or__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.121 - member : __pos__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.122 - member : __pow__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.123 - member : __rshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.124 - member : __sub__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.125 - member : __truediv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.126 - member : __xor__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.127 -
444.128 -Not Searchable Keys:
444.129 -
444.130 -
444.131 -Document 5
444.132 -Searchable Keys:
444.133 - class : list
444.134 - class-ig : list
444.135 - in : operator
444.136 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.137 - member : __contains__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.138 - member : __delitem__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.139 - member : __delslice__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
444.140 - member : __eq__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.141 - member : __ge__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.142 - member : __getitem__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.143 - member : __getslice__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
444.144 - member : __gt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.145 - member : __iadd__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.146 - member : __imul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.147 - member : __le__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.148 - member : __lt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.149 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.150 - member : __ne__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.151 - member : __setitem__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
444.152 - member : __setslice__;F;|DOCUMENTED|DOC_ONLY|;a,b,c,v;
444.153 - member : index;F;|DOCUMENTED|DOC_ONLY|;a;
444.154 -
444.155 -Not Searchable Keys:
444.156 -
444.157 -
444.158 -Document 6
444.159 -Searchable Keys:
444.160 - class : long
444.161 - class-ig : long
444.162 - in : operator
444.163 - member : __abs__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.164 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.165 - member : __and__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.166 - member : __div__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.167 - member : __floordiv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.168 - member : __index__;F;|DOCUMENTED|DOC_ONLY|;a;
444.169 - member : __invert__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.170 - member : __lshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.171 - member : __mod__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.172 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.173 - member : __neg__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.174 - member : __or__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.175 - member : __pos__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.176 - member : __pow__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.177 - member : __rshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.178 - member : __sub__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.179 - member : __truediv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.180 - member : __xor__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.181 -
444.182 -Not Searchable Keys:
444.183 -
444.184 -
444.185 -Document 7
444.186 -Searchable Keys:
444.187 - class : str
444.188 - class-ig : str
444.189 - in : operator
444.190 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.191 - member : __contains__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.192 - member : __eq__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.193 - member : __ge__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.194 - member : __getitem__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.195 - member : __getslice__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
444.196 - member : __gt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.197 - member : __le__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.198 - member : __lt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.199 - member : __mod__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.200 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.201 - member : __ne__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.202 - member : index;F;|DOCUMENTED|DOC_ONLY|;a;
444.203 -
444.204 -Not Searchable Keys:
444.205 -
444.206 -
444.207 -Document 8
444.208 -Searchable Keys:
444.209 - class : tuple
444.210 - class-ig : tuple
444.211 - in : operator
444.212 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.213 - member : __contains__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.214 - member : __eq__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.215 - member : __ge__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.216 - member : __getitem__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.217 - member : __getslice__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
444.218 - member : __gt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.219 - member : __le__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.220 - member : __lt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.221 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.222 - member : __ne__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.223 - member : index;F;|DOCUMENTED|DOC_ONLY|;a;
444.224 -
444.225 -Not Searchable Keys:
444.226 -
444.227 -
444.228 -Document 9
444.229 -Searchable Keys:
444.230 - class : unicode
444.231 - class-ig : unicode
444.232 - in : operator
444.233 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.234 - member : __contains__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.235 - member : __eq__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.236 - member : __ge__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.237 - member : __getitem__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.238 - member : __getslice__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
444.239 - member : __gt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.240 - member : __le__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.241 - member : __lt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.242 - member : __mod__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.243 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.244 - member : __ne__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.245 - member : index;F;|DOCUMENTED|DOC_ONLY|;a;
444.246 -
444.247 -Not Searchable Keys:
444.248 -
444.249 -
444.250 -Document 10
444.251 -Searchable Keys:
444.252 - item : __abs__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.253 - item : __add__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.254 - item : __and__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.255 - item : __concat__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.256 - item : __contains__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.257 - item : __delitem__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.258 - item : __delslice__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
444.259 - item : __div__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.260 - item : __eq__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.261 - item : __floordiv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.262 - item : __ge__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.263 - item : __getitem__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.264 - item : __getslice__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
444.265 - item : __gt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.266 - item : __iadd__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.267 - item : __iand__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.268 - item : __iconcat__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.269 - item : __idiv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.270 - item : __ifloordiv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.271 - item : __ilshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.272 - item : __imod__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.273 - item : __imul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.274 - item : __index__;F;|DOCUMENTED|DOC_ONLY|;a;
444.275 - item : __inv__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.276 - item : __invert__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.277 - item : __ior__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.278 - item : __ipow__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.279 - item : __irepeat__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.280 - item : __irshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.281 - item : __isub__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.282 - item : __itruediv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.283 - item : __ixor__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.284 - item : __le__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.285 - item : __lshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.286 - item : __lt__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.287 - item : __mod__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.288 - item : __mul__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.289 - item : __ne__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.290 - item : __neg__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.291 - item : __not__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.292 - item : __or__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.293 - item : __pos__;F;|DOCUMENTED|DOC_ONLY|;obj;
444.294 - item : __pow__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.295 - item : __repeat__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.296 - item : __rshift__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.297 - item : __setitem__;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
444.298 - item : __setslice__;F;|DOCUMENTED|DOC_ONLY|;a,b,c,v;
444.299 - item : __sub__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.300 - item : __truediv__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.301 - item : __xor__;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.302 - item : abs;F;|DOCUMENTED|DOC_ONLY|;obj;
444.303 - item : add;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.304 - item : and_;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.305 - item : attrgetter;F;|DOCUMENTED|DOC_ONLY|;attr,args;
444.306 - item : concat;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.307 - item : contains;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.308 - item : countOf;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.309 - item : delitem;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.310 - item : delslice;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
444.311 - item : div;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.312 - item : eq;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.313 - item : floordiv;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.314 - item : ge;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.315 - item : getitem;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.316 - item : getslice;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
444.317 - item : gt;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.318 - item : iadd;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.319 - item : iand;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.320 - item : iconcat;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.321 - item : idiv;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.322 - item : ifloordiv;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.323 - item : ilshift;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.324 - item : imod;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.325 - item : imul;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.326 - item : index;F;|DOCUMENTED|DOC_ONLY|;a;
444.327 - item : indexOf;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.328 - item : inv;F;|DOCUMENTED|DOC_ONLY|;obj;
444.329 - item : invert;F;|DOCUMENTED|DOC_ONLY|;obj;
444.330 - item : ior;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.331 - item : ipow;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.332 - item : irepeat;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.333 - item : irshift;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.334 - item : isCallable;F;|DOCUMENTED|DEPRECATED|DOC_ONLY|;obj;
444.335 - item : isMappingType;F;|DOCUMENTED|DOC_ONLY|;obj;
444.336 - item : isNumberType;F;|DOCUMENTED|DOC_ONLY|;obj;
444.337 - item : isSequenceType;F;|DOCUMENTED|DOC_ONLY|;obj;
444.338 - item : is_;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.339 - item : is_not;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.340 - item : isub;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.341 - item : itemgetter;F;|DOCUMENTED|DOC_ONLY|;item,args;
444.342 - item : itruediv;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.343 - item : ixor;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.344 - item : le;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.345 - item : lshift;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.346 - item : lt;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.347 - item : methodcaller;F;|DOCUMENTED|DOC_ONLY|;name,args;
444.348 - item : mod;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.349 - item : mul;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.350 - item : ne;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.351 - item : neg;F;|DOCUMENTED|DOC_ONLY|;obj;
444.352 - item : not_;F;|DOCUMENTED|DOC_ONLY|;obj;
444.353 - item : or_;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.354 - item : pos;F;|DOCUMENTED|DOC_ONLY|;obj;
444.355 - item : pow;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.356 - item : repeat;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.357 - item : rshift;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.358 - item : sequenceIncludes;F;|DOCUMENTED|DEPRECATED|DOC_ONLY|;;
444.359 - item : setitem;F;|DOCUMENTED|DOC_ONLY|;a,b,c;
444.360 - item : setslice;F;|DOCUMENTED|DOC_ONLY|;a,b,c,v;
444.361 - item : sub;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.362 - item : truediv;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.363 - item : truth;F;|DOCUMENTED|DOC_ONLY|;obj;
444.364 - item : xor;F;|DOCUMENTED|DOC_ONLY|;a,b;
444.365 - module : operator
444.366 -
444.367 -Not Searchable Keys:
444.368 - modattrs : S
445.1 --- a/python.editor/test/unit/data/testfiles/rst/operator.rst.testGetDoc5.html Sun Jan 04 13:11:53 2015 -0600
445.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
445.3 @@ -1,7 +0,0 @@
445.4 -<html><body><pre><b>delitem</b><font color="#808080">(a, b)</font></pre>
445.5 -<hr>
445.6 - __delitem__(a, b)
445.7 -
445.8 -<br><br>
445.9 - Remove the value of <b>a</b> at index <b>b</b>.
445.10 -</body></html>
446.1 --- a/python.editor/test/unit/data/testfiles/rst/pickle.rst Sun Jan 04 13:11:53 2015 -0600
446.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
446.3 @@ -1,879 +0,0 @@
446.4 -:mod:`pickle` --- Python object serialization
446.5 -=============================================
446.6 -
446.7 -.. index::
446.8 - single: persistence
446.9 - pair: persistent; objects
446.10 - pair: serializing; objects
446.11 - pair: marshalling; objects
446.12 - pair: flattening; objects
446.13 - pair: pickling; objects
446.14 -
446.15 -.. module:: pickle
446.16 - :synopsis: Convert Python objects to streams of bytes and back.
446.17 -.. sectionauthor:: Jim Kerr <jbkerr@sr.hp.com>.
446.18 -.. sectionauthor:: Barry Warsaw <barry@zope.com>
446.19 -
446.20 -The :mod:`pickle` module implements a fundamental, but powerful algorithm for
446.21 -serializing and de-serializing a Python object structure. "Pickling" is the
446.22 -process whereby a Python object hierarchy is converted into a byte stream, and
446.23 -"unpickling" is the inverse operation, whereby a byte stream is converted back
446.24 -into an object hierarchy. Pickling (and unpickling) is alternatively known as
446.25 -"serialization", "marshalling," [#]_ or "flattening", however, to avoid
446.26 -confusion, the terms used here are "pickling" and "unpickling".
446.27 -
446.28 -This documentation describes both the :mod:`pickle` module and the
446.29 -:mod:`cPickle` module.
446.30 -
446.31 -
446.32 -Relationship to other Python modules
446.33 -------------------------------------
446.34 -
446.35 -The :mod:`pickle` module has an optimized cousin called the :mod:`cPickle`
446.36 -module. As its name implies, :mod:`cPickle` is written in C, so it can be up to
446.37 -1000 times faster than :mod:`pickle`. However it does not support subclassing
446.38 -of the :func:`Pickler` and :func:`Unpickler` classes, because in :mod:`cPickle`
446.39 -these are functions, not classes. Most applications have no need for this
446.40 -functionality, and can benefit from the improved performance of :mod:`cPickle`.
446.41 -Other than that, the interfaces of the two modules are nearly identical; the
446.42 -common interface is described in this manual and differences are pointed out
446.43 -where necessary. In the following discussions, we use the term "pickle" to
446.44 -collectively describe the :mod:`pickle` and :mod:`cPickle` modules.
446.45 -
446.46 -The data streams the two modules produce are guaranteed to be interchangeable.
446.47 -
446.48 -Python has a more primitive serialization module called :mod:`marshal`, but in
446.49 -general :mod:`pickle` should always be the preferred way to serialize Python
446.50 -objects. :mod:`marshal` exists primarily to support Python's :file:`.pyc`
446.51 -files.
446.52 -
446.53 -The :mod:`pickle` module differs from :mod:`marshal` several significant ways:
446.54 -
446.55 -* The :mod:`pickle` module keeps track of the objects it has already serialized,
446.56 - so that later references to the same object won't be serialized again.
446.57 - :mod:`marshal` doesn't do this.
446.58 -
446.59 - This has implications both for recursive objects and object sharing. Recursive
446.60 - objects are objects that contain references to themselves. These are not
446.61 - handled by marshal, and in fact, attempting to marshal recursive objects will
446.62 - crash your Python interpreter. Object sharing happens when there are multiple
446.63 - references to the same object in different places in the object hierarchy being
446.64 - serialized. :mod:`pickle` stores such objects only once, and ensures that all
446.65 - other references point to the master copy. Shared objects remain shared, which
446.66 - can be very important for mutable objects.
446.67 -
446.68 -* :mod:`marshal` cannot be used to serialize user-defined classes and their
446.69 - instances. :mod:`pickle` can save and restore class instances transparently,
446.70 - however the class definition must be importable and live in the same module as
446.71 - when the object was stored.
446.72 -
446.73 -* The :mod:`marshal` serialization format is not guaranteed to be portable
446.74 - across Python versions. Because its primary job in life is to support
446.75 - :file:`.pyc` files, the Python implementers reserve the right to change the
446.76 - serialization format in non-backwards compatible ways should the need arise.
446.77 - The :mod:`pickle` serialization format is guaranteed to be backwards compatible
446.78 - across Python releases.
446.79 -
446.80 -.. warning::
446.81 -
446.82 - The :mod:`pickle` module is not intended to be secure against erroneous or
446.83 - maliciously constructed data. Never unpickle data received from an untrusted or
446.84 - unauthenticated source.
446.85 -
446.86 -Note that serialization is a more primitive notion than persistence; although
446.87 -:mod:`pickle` reads and writes file objects, it does not handle the issue of
446.88 -naming persistent objects, nor the (even more complicated) issue of concurrent
446.89 -access to persistent objects. The :mod:`pickle` module can transform a complex
446.90 -object into a byte stream and it can transform the byte stream into an object
446.91 -with the same internal structure. Perhaps the most obvious thing to do with
446.92 -these byte streams is to write them onto a file, but it is also conceivable to
446.93 -send them across a network or store them in a database. The module
446.94 -:mod:`shelve` provides a simple interface to pickle and unpickle objects on
446.95 -DBM-style database files.
446.96 -
446.97 -
446.98 -Data stream format
446.99 -------------------
446.100 -
446.101 -.. index::
446.102 - single: XDR
446.103 - single: External Data Representation
446.104 -
446.105 -The data format used by :mod:`pickle` is Python-specific. This has the
446.106 -advantage that there are no restrictions imposed by external standards such as
446.107 -XDR (which can't represent pointer sharing); however it means that non-Python
446.108 -programs may not be able to reconstruct pickled Python objects.
446.109 -
446.110 -By default, the :mod:`pickle` data format uses a printable ASCII representation.
446.111 -This is slightly more voluminous than a binary representation. The big
446.112 -advantage of using printable ASCII (and of some other characteristics of
446.113 -:mod:`pickle`'s representation) is that for debugging or recovery purposes it is
446.114 -possible for a human to read the pickled file with a standard text editor.
446.115 -
446.116 -There are currently 3 different protocols which can be used for pickling.
446.117 -
446.118 -* Protocol version 0 is the original ASCII protocol and is backwards compatible
446.119 - with earlier versions of Python.
446.120 -
446.121 -* Protocol version 1 is the old binary format which is also compatible with
446.122 - earlier versions of Python.
446.123 -
446.124 -* Protocol version 2 was introduced in Python 2.3. It provides much more
446.125 - efficient pickling of :term:`new-style class`\es.
446.126 -
446.127 -Refer to :pep:`307` for more information.
446.128 -
446.129 -If a *protocol* is not specified, protocol 0 is used. If *protocol* is specified
446.130 -as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol version
446.131 -available will be used.
446.132 -
446.133 -.. versionchanged:: 2.3
446.134 - Introduced the *protocol* parameter.
446.135 -
446.136 -A binary format, which is slightly more efficient, can be chosen by specifying a
446.137 -*protocol* version >= 1.
446.138 -
446.139 -
446.140 -Usage
446.141 ------
446.142 -
446.143 -To serialize an object hierarchy, you first create a pickler, then you call the
446.144 -pickler's :meth:`dump` method. To de-serialize a data stream, you first create
446.145 -an unpickler, then you call the unpickler's :meth:`load` method. The
446.146 -:mod:`pickle` module provides the following constant:
446.147 -
446.148 -
446.149 -.. data:: HIGHEST_PROTOCOL
446.150 -
446.151 - The highest protocol version available. This value can be passed as a
446.152 - *protocol* value.
446.153 -
446.154 - .. versionadded:: 2.3
446.155 -
446.156 -.. note::
446.157 -
446.158 - Be sure to always open pickle files created with protocols >= 1 in binary mode.
446.159 - For the old ASCII-based pickle protocol 0 you can use either text mode or binary
446.160 - mode as long as you stay consistent.
446.161 -
446.162 - A pickle file written with protocol 0 in binary mode will contain lone linefeeds
446.163 - as line terminators and therefore will look "funny" when viewed in Notepad or
446.164 - other editors which do not support this format.
446.165 -
446.166 -The :mod:`pickle` module provides the following functions to make the pickling
446.167 -process more convenient:
446.168 -
446.169 -
446.170 -.. function:: dump(obj, file[, protocol])
446.171 -
446.172 - Write a pickled representation of *obj* to the open file object *file*. This is
446.173 - equivalent to ``Pickler(file, protocol).dump(obj)``.
446.174 -
446.175 - If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is
446.176 - specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol
446.177 - version will be used.
446.178 -
446.179 - .. versionchanged:: 2.3
446.180 - Introduced the *protocol* parameter.
446.181 -
446.182 - *file* must have a :meth:`write` method that accepts a single string argument.
446.183 - It can thus be a file object opened for writing, a :mod:`StringIO` object, or
446.184 - any other custom object that meets this interface.
446.185 -
446.186 -
446.187 -.. function:: load(file)
446.188 -
446.189 - Read a string from the open file object *file* and interpret it as a pickle data
446.190 - stream, reconstructing and returning the original object hierarchy. This is
446.191 - equivalent to ``Unpickler(file).load()``.
446.192 -
446.193 - *file* must have two methods, a :meth:`read` method that takes an integer
446.194 - argument, and a :meth:`readline` method that requires no arguments. Both
446.195 - methods should return a string. Thus *file* can be a file object opened for
446.196 - reading, a :mod:`StringIO` object, or any other custom object that meets this
446.197 - interface.
446.198 -
446.199 - This function automatically determines whether the data stream was written in
446.200 - binary mode or not.
446.201 -
446.202 -
446.203 -.. function:: dumps(obj[, protocol])
446.204 -
446.205 - Return the pickled representation of the object as a string, instead of writing
446.206 - it to a file.
446.207 -
446.208 - If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is
446.209 - specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol
446.210 - version will be used.
446.211 -
446.212 - .. versionchanged:: 2.3
446.213 - The *protocol* parameter was added.
446.214 -
446.215 -
446.216 -.. function:: loads(string)
446.217 -
446.218 - Read a pickled object hierarchy from a string. Characters in the string past
446.219 - the pickled object's representation are ignored.
446.220 -
446.221 -The :mod:`pickle` module also defines three exceptions:
446.222 -
446.223 -
446.224 -.. exception:: PickleError
446.225 -
446.226 - A common base class for the other exceptions defined below. This inherits from
446.227 - :exc:`Exception`.
446.228 -
446.229 -
446.230 -.. exception:: PicklingError
446.231 -
446.232 - This exception is raised when an unpicklable object is passed to the
446.233 - :meth:`dump` method.
446.234 -
446.235 -
446.236 -.. exception:: UnpicklingError
446.237 -
446.238 - This exception is raised when there is a problem unpickling an object. Note that
446.239 - other exceptions may also be raised during unpickling, including (but not
446.240 - necessarily limited to) :exc:`AttributeError`, :exc:`EOFError`,
446.241 - :exc:`ImportError`, and :exc:`IndexError`.
446.242 -
446.243 -The :mod:`pickle` module also exports two callables [#]_, :class:`Pickler` and
446.244 -:class:`Unpickler`:
446.245 -
446.246 -
446.247 -.. class:: Pickler(file[, protocol])
446.248 -
446.249 - This takes a file-like object to which it will write a pickle data stream.
446.250 -
446.251 - If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is
446.252 - specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest
446.253 - protocol version will be used.
446.254 -
446.255 - .. versionchanged:: 2.3
446.256 - Introduced the *protocol* parameter.
446.257 -
446.258 - *file* must have a :meth:`write` method that accepts a single string argument.
446.259 - It can thus be an open file object, a :mod:`StringIO` object, or any other
446.260 - custom object that meets this interface.
446.261 -
446.262 - :class:`Pickler` objects define one (or two) public methods:
446.263 -
446.264 -
446.265 - .. method:: dump(obj)
446.266 -
446.267 - Write a pickled representation of *obj* to the open file object given in the
446.268 - constructor. Either the binary or ASCII format will be used, depending on the
446.269 - value of the *protocol* argument passed to the constructor.
446.270 -
446.271 -
446.272 - .. method:: clear_memo()
446.273 -
446.274 - Clears the pickler's "memo". The memo is the data structure that remembers
446.275 - which objects the pickler has already seen, so that shared or recursive objects
446.276 - pickled by reference and not by value. This method is useful when re-using
446.277 - picklers.
446.278 -
446.279 - .. note::
446.280 -
446.281 - Prior to Python 2.3, :meth:`clear_memo` was only available on the picklers
446.282 - created by :mod:`cPickle`. In the :mod:`pickle` module, picklers have an
446.283 - instance variable called :attr:`memo` which is a Python dictionary. So to clear
446.284 - the memo for a :mod:`pickle` module pickler, you could do the following::
446.285 -
446.286 - mypickler.memo.clear()
446.287 -
446.288 - Code that does not need to support older versions of Python should simply use
446.289 - :meth:`clear_memo`.
446.290 -
446.291 -It is possible to make multiple calls to the :meth:`dump` method of the same
446.292 -:class:`Pickler` instance. These must then be matched to the same number of
446.293 -calls to the :meth:`load` method of the corresponding :class:`Unpickler`
446.294 -instance. If the same object is pickled by multiple :meth:`dump` calls, the
446.295 -:meth:`load` will all yield references to the same object. [#]_
446.296 -
446.297 -:class:`Unpickler` objects are defined as:
446.298 -
446.299 -
446.300 -.. class:: Unpickler(file)
446.301 -
446.302 - This takes a file-like object from which it will read a pickle data stream.
446.303 - This class automatically determines whether the data stream was written in
446.304 - binary mode or not, so it does not need a flag as in the :class:`Pickler`
446.305 - factory.
446.306 -
446.307 - *file* must have two methods, a :meth:`read` method that takes an integer
446.308 - argument, and a :meth:`readline` method that requires no arguments. Both
446.309 - methods should return a string. Thus *file* can be a file object opened for
446.310 - reading, a :mod:`StringIO` object, or any other custom object that meets this
446.311 - interface.
446.312 -
446.313 - :class:`Unpickler` objects have one (or two) public methods:
446.314 -
446.315 -
446.316 - .. method:: load()
446.317 -
446.318 - Read a pickled object representation from the open file object given in
446.319 - the constructor, and return the reconstituted object hierarchy specified
446.320 - therein.
446.321 -
446.322 - This method automatically determines whether the data stream was written
446.323 - in binary mode or not.
446.324 -
446.325 -
446.326 - .. method:: noload()
446.327 -
446.328 - This is just like :meth:`load` except that it doesn't actually create any
446.329 - objects. This is useful primarily for finding what's called "persistent
446.330 - ids" that may be referenced in a pickle data stream. See section
446.331 - :ref:`pickle-protocol` below for more details.
446.332 -
446.333 - **Note:** the :meth:`noload` method is currently only available on
446.334 - :class:`Unpickler` objects created with the :mod:`cPickle` module.
446.335 - :mod:`pickle` module :class:`Unpickler`\ s do not have the :meth:`noload`
446.336 - method.
446.337 -
446.338 -
446.339 -What can be pickled and unpickled?
446.340 -----------------------------------
446.341 -
446.342 -The following types can be pickled:
446.343 -
446.344 -* ``None``, ``True``, and ``False``
446.345 -
446.346 -* integers, long integers, floating point numbers, complex numbers
446.347 -
446.348 -* normal and Unicode strings
446.349 -
446.350 -* tuples, lists, sets, and dictionaries containing only picklable objects
446.351 -
446.352 -* functions defined at the top level of a module
446.353 -
446.354 -* built-in functions defined at the top level of a module
446.355 -
446.356 -* classes that are defined at the top level of a module
446.357 -
446.358 -* instances of such classes whose :attr:`__dict__` or :meth:`__setstate__` is
446.359 - picklable (see section :ref:`pickle-protocol` for details)
446.360 -
446.361 -Attempts to pickle unpicklable objects will raise the :exc:`PicklingError`
446.362 -exception; when this happens, an unspecified number of bytes may have already
446.363 -been written to the underlying file. Trying to pickle a highly recursive data
446.364 -structure may exceed the maximum recursion depth, a :exc:`RuntimeError` will be
446.365 -raised in this case. You can carefully raise this limit with
446.366 -:func:`sys.setrecursionlimit`.
446.367 -
446.368 -Note that functions (built-in and user-defined) are pickled by "fully qualified"
446.369 -name reference, not by value. This means that only the function name is
446.370 -pickled, along with the name of module the function is defined in. Neither the
446.371 -function's code, nor any of its function attributes are pickled. Thus the
446.372 -defining module must be importable in the unpickling environment, and the module
446.373 -must contain the named object, otherwise an exception will be raised. [#]_
446.374 -
446.375 -Similarly, classes are pickled by named reference, so the same restrictions in
446.376 -the unpickling environment apply. Note that none of the class's code or data is
446.377 -pickled, so in the following example the class attribute ``attr`` is not
446.378 -restored in the unpickling environment::
446.379 -
446.380 - class Foo:
446.381 - attr = 'a class attr'
446.382 -
446.383 - picklestring = pickle.dumps(Foo)
446.384 -
446.385 -These restrictions are why picklable functions and classes must be defined in
446.386 -the top level of a module.
446.387 -
446.388 -Similarly, when class instances are pickled, their class's code and data are not
446.389 -pickled along with them. Only the instance data are pickled. This is done on
446.390 -purpose, so you can fix bugs in a class or add methods to the class and still
446.391 -load objects that were created with an earlier version of the class. If you
446.392 -plan to have long-lived objects that will see many versions of a class, it may
446.393 -be worthwhile to put a version number in the objects so that suitable
446.394 -conversions can be made by the class's :meth:`__setstate__` method.
446.395 -
446.396 -
446.397 -.. _pickle-protocol:
446.398 -
446.399 -The pickle protocol
446.400 --------------------
446.401 -
446.402 -.. currentmodule:: None
446.403 -
446.404 -This section describes the "pickling protocol" that defines the interface
446.405 -between the pickler/unpickler and the objects that are being serialized. This
446.406 -protocol provides a standard way for you to define, customize, and control how
446.407 -your objects are serialized and de-serialized. The description in this section
446.408 -doesn't cover specific customizations that you can employ to make the unpickling
446.409 -environment slightly safer from untrusted pickle data streams; see section
446.410 -:ref:`pickle-sub` for more details.
446.411 -
446.412 -
446.413 -.. _pickle-inst:
446.414 -
446.415 -Pickling and unpickling normal class instances
446.416 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
446.417 -
446.418 -.. method:: object.__getinitargs__()
446.419 -
446.420 - When a pickled class instance is unpickled, its :meth:`__init__` method is
446.421 - normally *not* invoked. If it is desirable that the :meth:`__init__` method
446.422 - be called on unpickling, an old-style class can define a method
446.423 - :meth:`__getinitargs__`, which should return a *tuple* containing the
446.424 - arguments to be passed to the class constructor (:meth:`__init__` for
446.425 - example). The :meth:`__getinitargs__` method is called at pickle time; the
446.426 - tuple it returns is incorporated in the pickle for the instance.
446.427 -
446.428 -.. method:: object.__getnewargs__()
446.429 -
446.430 - New-style types can provide a :meth:`__getnewargs__` method that is used for
446.431 - protocol 2. Implementing this method is needed if the type establishes some
446.432 - internal invariants when the instance is created, or if the memory allocation
446.433 - is affected by the values passed to the :meth:`__new__` method for the type
446.434 - (as it is for tuples and strings). Instances of a :term:`new-style class`
446.435 - ``C`` are created using ::
446.436 -
446.437 - obj = C.__new__(C, *args)
446.438 -
446.439 - where *args* is the result of calling :meth:`__getnewargs__` on the original
446.440 - object; if there is no :meth:`__getnewargs__`, an empty tuple is assumed.
446.441 -
446.442 -.. method:: object.__getstate__()
446.443 -
446.444 - Classes can further influence how their instances are pickled; if the class
446.445 - defines the method :meth:`__getstate__`, it is called and the return state is
446.446 - pickled as the contents for the instance, instead of the contents of the
446.447 - instance's dictionary. If there is no :meth:`__getstate__` method, the
446.448 - instance's :attr:`__dict__` is pickled.
446.449 -
446.450 -.. method:: object.__setstate__()
446.451 -
446.452 - Upon unpickling, if the class also defines the method :meth:`__setstate__`,
446.453 - it is called with the unpickled state. [#]_ If there is no
446.454 - :meth:`__setstate__` method, the pickled state must be a dictionary and its
446.455 - items are assigned to the new instance's dictionary. If a class defines both
446.456 - :meth:`__getstate__` and :meth:`__setstate__`, the state object needn't be a
446.457 - dictionary and these methods can do what they want. [#]_
446.458 -
446.459 - .. warning::
446.460 -
446.461 - For :term:`new-style class`\es, if :meth:`__getstate__` returns a false
446.462 - value, the :meth:`__setstate__` method will not be called.
446.463 -
446.464 -
446.465 -Pickling and unpickling extension types
446.466 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
446.467 -
446.468 -.. method:: object.__reduce__()
446.469 -
446.470 - When the :class:`Pickler` encounters an object of a type it knows nothing
446.471 - about --- such as an extension type --- it looks in two places for a hint of
446.472 - how to pickle it. One alternative is for the object to implement a
446.473 - :meth:`__reduce__` method. If provided, at pickling time :meth:`__reduce__`
446.474 - will be called with no arguments, and it must return either a string or a
446.475 - tuple.
446.476 -
446.477 - If a string is returned, it names a global variable whose contents are
446.478 - pickled as normal. The string returned by :meth:`__reduce__` should be the
446.479 - object's local name relative to its module; the pickle module searches the
446.480 - module namespace to determine the object's module.
446.481 -
446.482 - When a tuple is returned, it must be between two and five elements long.
446.483 - Optional elements can either be omitted, or ``None`` can be provided as their
446.484 - value. The contents of this tuple are pickled as normal and used to
446.485 - reconstruct the object at unpickling time. The semantics of each element
446.486 - are:
446.487 -
446.488 - * A callable object that will be called to create the initial version of the
446.489 - object. The next element of the tuple will provide arguments for this
446.490 - callable, and later elements provide additional state information that will
446.491 - subsequently be used to fully reconstruct the pickled data.
446.492 -
446.493 - In the unpickling environment this object must be either a class, a
446.494 - callable registered as a "safe constructor" (see below), or it must have an
446.495 - attribute :attr:`__safe_for_unpickling__` with a true value. Otherwise, an
446.496 - :exc:`UnpicklingError` will be raised in the unpickling environment. Note
446.497 - that as usual, the callable itself is pickled by name.
446.498 -
446.499 - * A tuple of arguments for the callable object.
446.500 -
446.501 - .. versionchanged:: 2.5
446.502 - Formerly, this argument could also be ``None``.
446.503 -
446.504 - * Optionally, the object's state, which will be passed to the object's
446.505 - :meth:`__setstate__` method as described in section :ref:`pickle-inst`. If
446.506 - the object has no :meth:`__setstate__` method, then, as above, the value
446.507 - must be a dictionary and it will be added to the object's :attr:`__dict__`.
446.508 -
446.509 - * Optionally, an iterator (and not a sequence) yielding successive list
446.510 - items. These list items will be pickled, and appended to the object using
446.511 - either ``obj.append(item)`` or ``obj.extend(list_of_items)``. This is
446.512 - primarily used for list subclasses, but may be used by other classes as
446.513 - long as they have :meth:`append` and :meth:`extend` methods with the
446.514 - appropriate signature. (Whether :meth:`append` or :meth:`extend` is used
446.515 - depends on which pickle protocol version is used as well as the number of
446.516 - items to append, so both must be supported.)
446.517 -
446.518 - * Optionally, an iterator (not a sequence) yielding successive dictionary
446.519 - items, which should be tuples of the form ``(key, value)``. These items
446.520 - will be pickled and stored to the object using ``obj[key] = value``. This
446.521 - is primarily used for dictionary subclasses, but may be used by other
446.522 - classes as long as they implement :meth:`__setitem__`.
446.523 -
446.524 -.. method:: object.__reduce_ex__(protocol)
446.525 -
446.526 - It is sometimes useful to know the protocol version when implementing
446.527 - :meth:`__reduce__`. This can be done by implementing a method named
446.528 - :meth:`__reduce_ex__` instead of :meth:`__reduce__`. :meth:`__reduce_ex__`,
446.529 - when it exists, is called in preference over :meth:`__reduce__` (you may
446.530 - still provide :meth:`__reduce__` for backwards compatibility). The
446.531 - :meth:`__reduce_ex__` method will be called with a single integer argument,
446.532 - the protocol version.
446.533 -
446.534 - The :class:`object` class implements both :meth:`__reduce__` and
446.535 - :meth:`__reduce_ex__`; however, if a subclass overrides :meth:`__reduce__`
446.536 - but not :meth:`__reduce_ex__`, the :meth:`__reduce_ex__` implementation
446.537 - detects this and calls :meth:`__reduce__`.
446.538 -
446.539 -An alternative to implementing a :meth:`__reduce__` method on the object to be
446.540 -pickled, is to register the callable with the :mod:`copy_reg` module. This
446.541 -module provides a way for programs to register "reduction functions" and
446.542 -constructors for user-defined types. Reduction functions have the same
446.543 -semantics and interface as the :meth:`__reduce__` method described above, except
446.544 -that they are called with a single argument, the object to be pickled.
446.545 -
446.546 -The registered constructor is deemed a "safe constructor" for purposes of
446.547 -unpickling as described above.
446.548 -
446.549 -
446.550 -Pickling and unpickling external objects
446.551 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
446.552 -
446.553 -.. index::
446.554 - single: persistent_id (pickle protocol)
446.555 - single: persistent_load (pickle protocol)
446.556 -
446.557 -For the benefit of object persistence, the :mod:`pickle` module supports the
446.558 -notion of a reference to an object outside the pickled data stream. Such
446.559 -objects are referenced by a "persistent id", which is just an arbitrary string
446.560 -of printable ASCII characters. The resolution of such names is not defined by
446.561 -the :mod:`pickle` module; it will delegate this resolution to user defined
446.562 -functions on the pickler and unpickler. [#]_
446.563 -
446.564 -To define external persistent id resolution, you need to set the
446.565 -:attr:`persistent_id` attribute of the pickler object and the
446.566 -:attr:`persistent_load` attribute of the unpickler object.
446.567 -
446.568 -To pickle objects that have an external persistent id, the pickler must have a
446.569 -custom :func:`persistent_id` method that takes an object as an argument and
446.570 -returns either ``None`` or the persistent id for that object. When ``None`` is
446.571 -returned, the pickler simply pickles the object as normal. When a persistent id
446.572 -string is returned, the pickler will pickle that string, along with a marker so
446.573 -that the unpickler will recognize the string as a persistent id.
446.574 -
446.575 -To unpickle external objects, the unpickler must have a custom
446.576 -:func:`persistent_load` function that takes a persistent id string and returns
446.577 -the referenced object.
446.578 -
446.579 -Here's a silly example that *might* shed more light::
446.580 -
446.581 - import pickle
446.582 - from cStringIO import StringIO
446.583 -
446.584 - src = StringIO()
446.585 - p = pickle.Pickler(src)
446.586 -
446.587 - def persistent_id(obj):
446.588 - if hasattr(obj, 'x'):
446.589 - return 'the value %d' % obj.x
446.590 - else:
446.591 - return None
446.592 -
446.593 - p.persistent_id = persistent_id
446.594 -
446.595 - class Integer:
446.596 - def __init__(self, x):
446.597 - self.x = x
446.598 - def __str__(self):
446.599 - return 'My name is integer %d' % self.x
446.600 -
446.601 - i = Integer(7)
446.602 - print i
446.603 - p.dump(i)
446.604 -
446.605 - datastream = src.getvalue()
446.606 - print repr(datastream)
446.607 - dst = StringIO(datastream)
446.608 -
446.609 - up = pickle.Unpickler(dst)
446.610 -
446.611 - class FancyInteger(Integer):
446.612 - def __str__(self):
446.613 - return 'I am the integer %d' % self.x
446.614 -
446.615 - def persistent_load(persid):
446.616 - if persid.startswith('the value '):
446.617 - value = int(persid.split()[2])
446.618 - return FancyInteger(value)
446.619 - else:
446.620 - raise pickle.UnpicklingError, 'Invalid persistent id'
446.621 -
446.622 - up.persistent_load = persistent_load
446.623 -
446.624 - j = up.load()
446.625 - print j
446.626 -
446.627 -In the :mod:`cPickle` module, the unpickler's :attr:`persistent_load` attribute
446.628 -can also be set to a Python list, in which case, when the unpickler reaches a
446.629 -persistent id, the persistent id string will simply be appended to this list.
446.630 -This functionality exists so that a pickle data stream can be "sniffed" for
446.631 -object references without actually instantiating all the objects in a pickle.
446.632 -[#]_ Setting :attr:`persistent_load` to a list is usually used in conjunction
446.633 -with the :meth:`noload` method on the Unpickler.
446.634 -
446.635 -.. BAW: Both pickle and cPickle support something called inst_persistent_id()
446.636 - which appears to give unknown types a second shot at producing a persistent
446.637 - id. Since Jim Fulton can't remember why it was added or what it's for, I'm
446.638 - leaving it undocumented.
446.639 -
446.640 -
446.641 -.. _pickle-sub:
446.642 -
446.643 -Subclassing Unpicklers
446.644 -----------------------
446.645 -
446.646 -.. index::
446.647 - single: load_global() (pickle protocol)
446.648 - single: find_global() (pickle protocol)
446.649 -
446.650 -By default, unpickling will import any class that it finds in the pickle data.
446.651 -You can control exactly what gets unpickled and what gets called by customizing
446.652 -your unpickler. Unfortunately, exactly how you do this is different depending
446.653 -on whether you're using :mod:`pickle` or :mod:`cPickle`. [#]_
446.654 -
446.655 -In the :mod:`pickle` module, you need to derive a subclass from
446.656 -:class:`Unpickler`, overriding the :meth:`load_global` method.
446.657 -:meth:`load_global` should read two lines from the pickle data stream where the
446.658 -first line will the name of the module containing the class and the second line
446.659 -will be the name of the instance's class. It then looks up the class, possibly
446.660 -importing the module and digging out the attribute, then it appends what it
446.661 -finds to the unpickler's stack. Later on, this class will be assigned to the
446.662 -:attr:`__class__` attribute of an empty class, as a way of magically creating an
446.663 -instance without calling its class's :meth:`__init__`. Your job (should you
446.664 -choose to accept it), would be to have :meth:`load_global` push onto the
446.665 -unpickler's stack, a known safe version of any class you deem safe to unpickle.
446.666 -It is up to you to produce such a class. Or you could raise an error if you
446.667 -want to disallow all unpickling of instances. If this sounds like a hack,
446.668 -you're right. Refer to the source code to make this work.
446.669 -
446.670 -Things are a little cleaner with :mod:`cPickle`, but not by much. To control
446.671 -what gets unpickled, you can set the unpickler's :attr:`find_global` attribute
446.672 -to a function or ``None``. If it is ``None`` then any attempts to unpickle
446.673 -instances will raise an :exc:`UnpicklingError`. If it is a function, then it
446.674 -should accept a module name and a class name, and return the corresponding class
446.675 -object. It is responsible for looking up the class and performing any necessary
446.676 -imports, and it may raise an error to prevent instances of the class from being
446.677 -unpickled.
446.678 -
446.679 -The moral of the story is that you should be really careful about the source of
446.680 -the strings your application unpickles.
446.681 -
446.682 -
446.683 -.. _pickle-example:
446.684 -
446.685 -Example
446.686 --------
446.687 -
446.688 -For the simplest code, use the :func:`dump` and :func:`load` functions. Note
446.689 -that a self-referencing list is pickled and restored correctly. ::
446.690 -
446.691 - import pickle
446.692 -
446.693 - data1 = {'a': [1, 2.0, 3, 4+6j],
446.694 - 'b': ('string', u'Unicode string'),
446.695 - 'c': None}
446.696 -
446.697 - selfref_list = [1, 2, 3]
446.698 - selfref_list.append(selfref_list)
446.699 -
446.700 - output = open('data.pkl', 'wb')
446.701 -
446.702 - # Pickle dictionary using protocol 0.
446.703 - pickle.dump(data1, output)
446.704 -
446.705 - # Pickle the list using the highest protocol available.
446.706 - pickle.dump(selfref_list, output, -1)
446.707 -
446.708 - output.close()
446.709 -
446.710 -The following example reads the resulting pickled data. When reading a
446.711 -pickle-containing file, you should open the file in binary mode because you
446.712 -can't be sure if the ASCII or binary format was used. ::
446.713 -
446.714 - import pprint, pickle
446.715 -
446.716 - pkl_file = open('data.pkl', 'rb')
446.717 -
446.718 - data1 = pickle.load(pkl_file)
446.719 - pprint.pprint(data1)
446.720 -
446.721 - data2 = pickle.load(pkl_file)
446.722 - pprint.pprint(data2)
446.723 -
446.724 - pkl_file.close()
446.725 -
446.726 -Here's a larger example that shows how to modify pickling behavior for a class.
446.727 -The :class:`TextReader` class opens a text file, and returns the line number and
446.728 -line contents each time its :meth:`readline` method is called. If a
446.729 -:class:`TextReader` instance is pickled, all attributes *except* the file object
446.730 -member are saved. When the instance is unpickled, the file is reopened, and
446.731 -reading resumes from the last location. The :meth:`__setstate__` and
446.732 -:meth:`__getstate__` methods are used to implement this behavior. ::
446.733 -
446.734 - #!/usr/local/bin/python
446.735 -
446.736 - class TextReader:
446.737 - """Print and number lines in a text file."""
446.738 - def __init__(self, file):
446.739 - self.file = file
446.740 - self.fh = open(file)
446.741 - self.lineno = 0
446.742 -
446.743 - def readline(self):
446.744 - self.lineno = self.lineno + 1
446.745 - line = self.fh.readline()
446.746 - if not line:
446.747 - return None
446.748 - if line.endswith("\n"):
446.749 - line = line[:-1]
446.750 - return "%d: %s" % (self.lineno, line)
446.751 -
446.752 - def __getstate__(self):
446.753 - odict = self.__dict__.copy() # copy the dict since we change it
446.754 - del odict['fh'] # remove filehandle entry
446.755 - return odict
446.756 -
446.757 - def __setstate__(self, dict):
446.758 - fh = open(dict['file']) # reopen file
446.759 - count = dict['lineno'] # read from file...
446.760 - while count: # until line count is restored
446.761 - fh.readline()
446.762 - count = count - 1
446.763 - self.__dict__.update(dict) # update attributes
446.764 - self.fh = fh # save the file object
446.765 -
446.766 -A sample usage might be something like this::
446.767 -
446.768 - >>> import TextReader
446.769 - >>> obj = TextReader.TextReader("TextReader.py")
446.770 - >>> obj.readline()
446.771 - '1: #!/usr/local/bin/python'
446.772 - >>> obj.readline()
446.773 - '2: '
446.774 - >>> obj.readline()
446.775 - '3: class TextReader:'
446.776 - >>> import pickle
446.777 - >>> pickle.dump(obj, open('save.p', 'wb'))
446.778 -
446.779 -If you want to see that :mod:`pickle` works across Python processes, start
446.780 -another Python session, before continuing. What follows can happen from either
446.781 -the same process or a new process. ::
446.782 -
446.783 - >>> import pickle
446.784 - >>> reader = pickle.load(open('save.p', 'rb'))
446.785 - >>> reader.readline()
446.786 - '4: """Print and number lines in a text file."""'
446.787 -
446.788 -
446.789 -.. seealso::
446.790 -
446.791 - Module :mod:`copy_reg`
446.792 - Pickle interface constructor registration for extension types.
446.793 -
446.794 - Module :mod:`shelve`
446.795 - Indexed databases of objects; uses :mod:`pickle`.
446.796 -
446.797 - Module :mod:`copy`
446.798 - Shallow and deep object copying.
446.799 -
446.800 - Module :mod:`marshal`
446.801 - High-performance serialization of built-in types.
446.802 -
446.803 -
446.804 -:mod:`cPickle` --- A faster :mod:`pickle`
446.805 -=========================================
446.806 -
446.807 -.. module:: cPickle
446.808 - :synopsis: Faster version of pickle, but not subclassable.
446.809 -.. moduleauthor:: Jim Fulton <jim@zope.com>
446.810 -.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
446.811 -
446.812 -
446.813 -.. index:: module: pickle
446.814 -
446.815 -The :mod:`cPickle` module supports serialization and de-serialization of Python
446.816 -objects, providing an interface and functionality nearly identical to the
446.817 -:mod:`pickle` module. There are several differences, the most important being
446.818 -performance and subclassability.
446.819 -
446.820 -First, :mod:`cPickle` can be up to 1000 times faster than :mod:`pickle` because
446.821 -the former is implemented in C. Second, in the :mod:`cPickle` module the
446.822 -callables :func:`Pickler` and :func:`Unpickler` are functions, not classes.
446.823 -This means that you cannot use them to derive custom pickling and unpickling
446.824 -subclasses. Most applications have no need for this functionality and should
446.825 -benefit from the greatly improved performance of the :mod:`cPickle` module.
446.826 -
446.827 -The pickle data stream produced by :mod:`pickle` and :mod:`cPickle` are
446.828 -identical, so it is possible to use :mod:`pickle` and :mod:`cPickle`
446.829 -interchangeably with existing pickles. [#]_
446.830 -
446.831 -There are additional minor differences in API between :mod:`cPickle` and
446.832 -:mod:`pickle`, however for most applications, they are interchangeable. More
446.833 -documentation is provided in the :mod:`pickle` module documentation, which
446.834 -includes a list of the documented differences.
446.835 -
446.836 -.. rubric:: Footnotes
446.837 -
446.838 -.. [#] Don't confuse this with the :mod:`marshal` module
446.839 -
446.840 -.. [#] In the :mod:`pickle` module these callables are classes, which you could
446.841 - subclass to customize the behavior. However, in the :mod:`cPickle` module these
446.842 - callables are factory functions and so cannot be subclassed. One common reason
446.843 - to subclass is to control what objects can actually be unpickled. See section
446.844 - :ref:`pickle-sub` for more details.
446.845 -
446.846 -.. [#] *Warning*: this is intended for pickling multiple objects without intervening
446.847 - modifications to the objects or their parts. If you modify an object and then
446.848 - pickle it again using the same :class:`Pickler` instance, the object is not
446.849 - pickled again --- a reference to it is pickled and the :class:`Unpickler` will
446.850 - return the old value, not the modified one. There are two problems here: (1)
446.851 - detecting changes, and (2) marshalling a minimal set of changes. Garbage
446.852 - Collection may also become a problem here.
446.853 -
446.854 -.. [#] The exception raised will likely be an :exc:`ImportError` or an
446.855 - :exc:`AttributeError` but it could be something else.
446.856 -
446.857 -.. [#] These methods can also be used to implement copying class instances.
446.858 -
446.859 -.. [#] This protocol is also used by the shallow and deep copying operations defined in
446.860 - the :mod:`copy` module.
446.861 -
446.862 -.. [#] The actual mechanism for associating these user defined functions is slightly
446.863 - different for :mod:`pickle` and :mod:`cPickle`. The description given here
446.864 - works the same for both implementations. Users of the :mod:`pickle` module
446.865 - could also use subclassing to effect the same results, overriding the
446.866 - :meth:`persistent_id` and :meth:`persistent_load` methods in the derived
446.867 - classes.
446.868 -
446.869 -.. [#] We'll leave you with the image of Guido and Jim sitting around sniffing pickles
446.870 - in their living rooms.
446.871 -
446.872 -.. [#] A word of caution: the mechanisms described here use internal attributes and
446.873 - methods, which are subject to change in future versions of Python. We intend to
446.874 - someday provide a common interface for controlling this behavior, which will
446.875 - work in either :mod:`pickle` or :mod:`cPickle`.
446.876 -
446.877 -.. [#] Since the pickle data format is actually a tiny stack-oriented programming
446.878 - language, and some freedom is taken in the encodings of certain objects, it is
446.879 - possible that the two modules produce different data streams for the same input
446.880 - objects. However it is guaranteed that they will always be able to read each
446.881 - other's data streams.
446.882 -
447.1 --- a/python.editor/test/unit/data/testfiles/rst/pickle.rst.indexed Sun Jan 04 13:11:53 2015 -0600
447.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
447.3 @@ -1,109 +0,0 @@
447.4 -
447.5 -
447.6 -Document 0
447.7 -Searchable Keys:
447.8 - class : PickleError
447.9 - class-ig : pickleerror
447.10 - extends : Exception
447.11 - in : pickle
447.12 -
447.13 -Not Searchable Keys:
447.14 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
447.15 -
447.16 -
447.17 -Document 1
447.18 -Searchable Keys:
447.19 - class : Pickler
447.20 - class-ig : pickler
447.21 - in : pickle
447.22 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;file,protocol;
447.23 - member : clear_memo;F;|DOCUMENTED|DOC_ONLY|;;
447.24 - member : dump;F;|DOCUMENTED|DOC_ONLY|;obj;
447.25 -
447.26 -Not Searchable Keys:
447.27 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
447.28 -
447.29 -
447.30 -Document 2
447.31 -Searchable Keys:
447.32 - class : PicklingError
447.33 - class-ig : picklingerror
447.34 - extends : Exception
447.35 - in : pickle
447.36 -
447.37 -Not Searchable Keys:
447.38 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
447.39 -
447.40 -
447.41 -Document 3
447.42 -Searchable Keys:
447.43 - class : Unpickler
447.44 - class-ig : unpickler
447.45 - in : pickle
447.46 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;file;
447.47 - member : load;F;|DOCUMENTED|DOC_ONLY|;;
447.48 - member : noload;F;|DOCUMENTED|DOC_ONLY|;;
447.49 -
447.50 -Not Searchable Keys:
447.51 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
447.52 -
447.53 -
447.54 -Document 4
447.55 -Searchable Keys:
447.56 - class : UnpicklingError
447.57 - class-ig : unpicklingerror
447.58 - extends : Exception
447.59 - in : pickle
447.60 -
447.61 -Not Searchable Keys:
447.62 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
447.63 -
447.64 -
447.65 -Document 5
447.66 -Searchable Keys:
447.67 - class : object
447.68 - class-ig : object
447.69 - in : None
447.70 - member : __getinitargs__;F;|DOCUMENTED|DOC_ONLY|;;
447.71 - member : __getnewargs__;F;|DOCUMENTED|DOC_ONLY|;;
447.72 - member : __getstate__;F;|DOCUMENTED|DOC_ONLY|;;
447.73 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
447.74 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;protocol;
447.75 - member : __setstate__;F;|DOCUMENTED|DOC_ONLY|;;
447.76 -
447.77 -Not Searchable Keys:
447.78 -
447.79 -
447.80 -Document 6
447.81 -Searchable Keys:
447.82 - item : HIGHEST_PROTOCOL;D;|DOCUMENTED|DOC_ONLY|;
447.83 - item : dump;F;|DOCUMENTED|DOC_ONLY|;obj,file,protocol;
447.84 - item : dumps;F;|DOCUMENTED|DOC_ONLY|;obj,protocol;
447.85 - item : load;F;|DOCUMENTED|DOC_ONLY|;file;
447.86 - item : loads;F;|DOCUMENTED|DOC_ONLY|;string;
447.87 - module : pickle
447.88 -
447.89 -Not Searchable Keys:
447.90 - modattrs : S
447.91 -
447.92 -
447.93 -Document 7
447.94 -Searchable Keys:
447.95 - item : PickleError;C;|DOCUMENTED|DOC_ONLY|;
447.96 - item : Pickler;C;|DOCUMENTED|DOC_ONLY|;
447.97 - item : PicklingError;C;|DOCUMENTED|DOC_ONLY|;
447.98 - item : Unpickler;C;|DOCUMENTED|DOC_ONLY|;
447.99 - item : UnpicklingError;C;|DOCUMENTED|DOC_ONLY|;
447.100 - item : object;C;|DOCUMENTED|DOC_ONLY|;
447.101 - module : cPickle
447.102 -
447.103 -Not Searchable Keys:
447.104 - modattrs : S
447.105 -
447.106 -
447.107 -Document 8
447.108 -Searchable Keys:
447.109 - module : None
447.110 -
447.111 -Not Searchable Keys:
447.112 - modattrs : S
448.1 --- a/python.editor/test/unit/data/testfiles/rst/platform.rst Sun Jan 04 13:11:53 2015 -0600
448.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
448.3 @@ -1,266 +0,0 @@
448.4 -
448.5 -:mod:`platform` --- Access to underlying platform's identifying data.
448.6 -======================================================================
448.7 -
448.8 -.. module:: platform
448.9 - :synopsis: Retrieves as much platform identifying data as possible.
448.10 -.. moduleauthor:: Marc-Andre Lemburg <mal@egenix.com>
448.11 -.. sectionauthor:: Bjorn Pettersen <bpettersen@corp.fairisaac.com>
448.12 -
448.13 -
448.14 -.. versionadded:: 2.3
448.15 -
448.16 -.. note::
448.17 -
448.18 - Specific platforms listed alphabetically, with Linux included in the Unix
448.19 - section.
448.20 -
448.21 -
448.22 -Cross Platform
448.23 ---------------
448.24 -
448.25 -
448.26 -.. function:: architecture(executable=sys.executable, bits='', linkage='')
448.27 -
448.28 - Queries the given executable (defaults to the Python interpreter binary) for
448.29 - various architecture information.
448.30 -
448.31 - Returns a tuple ``(bits, linkage)`` which contain information about the bit
448.32 - architecture and the linkage format used for the executable. Both values are
448.33 - returned as strings.
448.34 -
448.35 - Values that cannot be determined are returned as given by the parameter presets.
448.36 - If bits is given as ``''``, the :cfunc:`sizeof(pointer)` (or
448.37 - :cfunc:`sizeof(long)` on Python version < 1.5.2) is used as indicator for the
448.38 - supported pointer size.
448.39 -
448.40 - The function relies on the system's :file:`file` command to do the actual work.
448.41 - This is available on most if not all Unix platforms and some non-Unix platforms
448.42 - and then only if the executable points to the Python interpreter. Reasonable
448.43 - defaults are used when the above needs are not met.
448.44 -
448.45 -
448.46 -.. function:: machine()
448.47 -
448.48 - Returns the machine type, e.g. ``'i386'``. An empty string is returned if the
448.49 - value cannot be determined.
448.50 -
448.51 -
448.52 -.. function:: node()
448.53 -
448.54 - Returns the computer's network name (may not be fully qualified!). An empty
448.55 - string is returned if the value cannot be determined.
448.56 -
448.57 -
448.58 -.. function:: platform(aliased=0, terse=0)
448.59 -
448.60 - Returns a single string identifying the underlying platform with as much useful
448.61 - information as possible.
448.62 -
448.63 - The output is intended to be *human readable* rather than machine parseable. It
448.64 - may look different on different platforms and this is intended.
448.65 -
448.66 - If *aliased* is true, the function will use aliases for various platforms that
448.67 - report system names which differ from their common names, for example SunOS will
448.68 - be reported as Solaris. The :func:`system_alias` function is used to implement
448.69 - this.
448.70 -
448.71 - Setting *terse* to true causes the function to return only the absolute minimum
448.72 - information needed to identify the platform.
448.73 -
448.74 -
448.75 -.. function:: processor()
448.76 -
448.77 - Returns the (real) processor name, e.g. ``'amdk6'``.
448.78 -
448.79 - An empty string is returned if the value cannot be determined. Note that many
448.80 - platforms do not provide this information or simply return the same value as for
448.81 - :func:`machine`. NetBSD does this.
448.82 -
448.83 -
448.84 -.. function:: python_build()
448.85 -
448.86 - Returns a tuple ``(buildno, builddate)`` stating the Python build number and
448.87 - date as strings.
448.88 -
448.89 -
448.90 -.. function:: python_compiler()
448.91 -
448.92 - Returns a string identifying the compiler used for compiling Python.
448.93 -
448.94 -
448.95 -.. function:: python_branch()
448.96 -
448.97 - Returns a string identifying the Python implementation SCM branch.
448.98 -
448.99 - .. versionadded:: 2.6
448.100 -
448.101 -
448.102 -.. function:: python_implementation()
448.103 -
448.104 - Returns a string identifying the Python implementation. Possible return values
448.105 - are: 'CPython', 'IronPython', 'Jython'
448.106 -
448.107 - .. versionadded:: 2.6
448.108 -
448.109 -
448.110 -.. function:: python_revision()
448.111 -
448.112 - Returns a string identifying the Python implementation SCM revision.
448.113 -
448.114 - .. versionadded:: 2.6
448.115 -
448.116 -
448.117 -.. function:: python_version()
448.118 -
448.119 - Returns the Python version as string ``'major.minor.patchlevel'``
448.120 -
448.121 - Note that unlike the Python ``sys.version``, the returned value will always
448.122 - include the patchlevel (it defaults to 0).
448.123 -
448.124 -
448.125 -.. function:: python_version_tuple()
448.126 -
448.127 - Returns the Python version as tuple ``(major, minor, patchlevel)`` of strings.
448.128 -
448.129 - Note that unlike the Python ``sys.version``, the returned value will always
448.130 - include the patchlevel (it defaults to ``'0'``).
448.131 -
448.132 -
448.133 -.. function:: release()
448.134 -
448.135 - Returns the system's release, e.g. ``'2.2.0'`` or ``'NT'`` An empty string is
448.136 - returned if the value cannot be determined.
448.137 -
448.138 -
448.139 -.. function:: system()
448.140 -
448.141 - Returns the system/OS name, e.g. ``'Linux'``, ``'Windows'``, or ``'Java'``. An
448.142 - empty string is returned if the value cannot be determined.
448.143 -
448.144 -
448.145 -.. function:: system_alias(system, release, version)
448.146 -
448.147 - Returns ``(system, release, version)`` aliased to common marketing names used
448.148 - for some systems. It also does some reordering of the information in some cases
448.149 - where it would otherwise cause confusion.
448.150 -
448.151 -
448.152 -.. function:: version()
448.153 -
448.154 - Returns the system's release version, e.g. ``'#3 on degas'``. An empty string is
448.155 - returned if the value cannot be determined.
448.156 -
448.157 -
448.158 -.. function:: uname()
448.159 -
448.160 - Fairly portable uname interface. Returns a tuple of strings ``(system, node,
448.161 - release, version, machine, processor)`` identifying the underlying platform.
448.162 -
448.163 - Note that unlike the :func:`os.uname` function this also returns possible
448.164 - processor information as additional tuple entry.
448.165 -
448.166 - Entries which cannot be determined are set to ``''``.
448.167 -
448.168 -
448.169 -Java Platform
448.170 --------------
448.171 -
448.172 -
448.173 -.. function:: java_ver(release='', vendor='', vminfo=('','',''), osinfo=('','',''))
448.174 -
448.175 - Version interface for JPython.
448.176 -
448.177 - Returns a tuple ``(release, vendor, vminfo, osinfo)`` with *vminfo* being a
448.178 - tuple ``(vm_name, vm_release, vm_vendor)`` and *osinfo* being a tuple
448.179 - ``(os_name, os_version, os_arch)``. Values which cannot be determined are set to
448.180 - the defaults given as parameters (which all default to ``''``).
448.181 -
448.182 -
448.183 -Windows Platform
448.184 -----------------
448.185 -
448.186 -
448.187 -.. function:: win32_ver(release='', version='', csd='', ptype='')
448.188 -
448.189 - Get additional version information from the Windows Registry and return a tuple
448.190 - ``(version, csd, ptype)`` referring to version number, CSD level and OS type
448.191 - (multi/single processor).
448.192 -
448.193 - As a hint: *ptype* is ``'Uniprocessor Free'`` on single processor NT machines
448.194 - and ``'Multiprocessor Free'`` on multi processor machines. The *'Free'* refers
448.195 - to the OS version being free of debugging code. It could also state *'Checked'*
448.196 - which means the OS version uses debugging code, i.e. code that checks arguments,
448.197 - ranges, etc.
448.198 -
448.199 - .. note::
448.200 -
448.201 - Note: this function works best with Mark Hammond's
448.202 - :mod:`win32all` package installed, but also on Python 2.3 and
448.203 - later (support for this was added in Python 2.6). It obviously
448.204 - only runs on Win32 compatible platforms.
448.205 -
448.206 -
448.207 -Win95/98 specific
448.208 -^^^^^^^^^^^^^^^^^
448.209 -
448.210 -.. function:: popen(cmd, mode='r', bufsize=None)
448.211 -
448.212 - Portable :func:`popen` interface. Find a working popen implementation
448.213 - preferring :func:`win32pipe.popen`. On Windows NT, :func:`win32pipe.popen`
448.214 - should work; on Windows 9x it hangs due to bugs in the MS C library.
448.215 -
448.216 -
448.217 -Mac OS Platform
448.218 ----------------
448.219 -
448.220 -
448.221 -.. function:: mac_ver(release='', versioninfo=('','',''), machine='')
448.222 -
448.223 - Get Mac OS version information and return it as tuple ``(release, versioninfo,
448.224 - machine)`` with *versioninfo* being a tuple ``(version, dev_stage,
448.225 - non_release_version)``.
448.226 -
448.227 - Entries which cannot be determined are set to ``''``. All tuple entries are
448.228 - strings.
448.229 -
448.230 - Documentation for the underlying :cfunc:`gestalt` API is available online at
448.231 - http://www.rgaros.nl/gestalt/.
448.232 -
448.233 -
448.234 -Unix Platforms
448.235 ---------------
448.236 -
448.237 -
448.238 -.. function:: dist(distname='', version='', id='', supported_dists=('SuSE','debian','redhat','mandrake',...))
448.239 -
448.240 - This is another name for :func:`linux_distribution`.
448.241 -
448.242 -.. function:: linux_distribution(distname='', version='', id='', supported_dists=('SuSE','debian','redhat','mandrake',...), full_distribution_name=1)
448.243 -
448.244 - Tries to determine the name of the Linux OS distribution name.
448.245 -
448.246 - ``supported_dists`` may be given to define the set of Linux distributions to
448.247 - look for. It defaults to a list of currently supported Linux distributions
448.248 - identified by their release file name.
448.249 -
448.250 - If ``full_distribution_name`` is true (default), the full distribution read
448.251 - from the OS is returned. Otherwise the short name taken from
448.252 - ``supported_dists`` is used.
448.253 -
448.254 - Returns a tuple ``(distname,version,id)`` which defaults to the args given as
448.255 - parameters. ``id`` is the item in parentheses after the version number. It
448.256 - is usually the version codename.
448.257 -
448.258 -.. function:: libc_ver(executable=sys.executable, lib='', version='', chunksize=2048)
448.259 -
448.260 - Tries to determine the libc version against which the file executable (defaults
448.261 - to the Python interpreter) is linked. Returns a tuple of strings ``(lib,
448.262 - version)`` which default to the given parameters in case the lookup fails.
448.263 -
448.264 - Note that this function has intimate knowledge of how different libc versions
448.265 - add symbols to the executable is probably only usable for executables compiled
448.266 - using :program:`gcc`.
448.267 -
448.268 - The file is read and scanned in chunks of *chunksize* bytes.
448.269 -
449.1 --- a/python.editor/test/unit/data/testfiles/rst/platform.rst.html Sun Jan 04 13:11:53 2015 -0600
449.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
449.3 @@ -1,283 +0,0 @@
449.4 -<html><body>
449.5 -<h2><a href="mod:platform">platform</a> --- Access to underlying platform's identifying data.
449.6 -</h2>
449.7 -<a href="module:platform">platform</a><br>
449.8 - Retrieves as much platform identifying data as possible.
449.9 -<br>Module Author:</b> Marc-Andre Lemburg <mal@egenix.com>
449.10 -<br>Section Author:</b> Bjorn Pettersen <bpettersen@corp.fairisaac.com>
449.11 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.3
449.12 -</div>
449.13 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
449.14 - Specific platforms listed alphabetically, with Linux included in the Unix
449.15 - section.
449.16 -</div>
449.17 -<h3>Cross Platform
449.18 -</h3>
449.19 -<a href="func:architecture(executable=sys.executable, bits='', linkage='')">architecture(executable=sys.executable, bits='', linkage='')</a>
449.20 -
449.21 -<br><br>
449.22 - Queries the given executable (defaults to the Python interpreter binary) for
449.23 - various architecture information.
449.24 -
449.25 -<br><br>
449.26 - Returns a tuple <code>(bits, linkage)</code> which contain information about the bit
449.27 - architecture and the linkage format used for the executable. Both values are
449.28 - returned as strings.
449.29 -
449.30 -<br><br>
449.31 - Values that cannot be determined are returned as given by the parameter presets.
449.32 - If bits is given as <code>''</code>, the :cfunc:`sizeof(pointer)` (or
449.33 - :cfunc:`sizeof(long)` on Python version < 1.5.2) is used as indicator for the
449.34 - supported pointer size.
449.35 -
449.36 -<br><br>
449.37 - The function relies on the system's :file:<code>file</code> command to do the actual work.
449.38 - This is available on most if not all Unix platforms and some non-Unix platforms
449.39 - and then only if the executable points to the Python interpreter. Reasonable
449.40 - defaults are used when the above needs are not met.
449.41 -
449.42 -<br><br>
449.43 -<a href="func:machine()">machine()</a>
449.44 -
449.45 -<br><br>
449.46 - Returns the machine type, e.g. <code>'i386'</code>. An empty string is returned if the
449.47 - value cannot be determined.
449.48 -
449.49 -<br><br>
449.50 -<a href="func:node()">node()</a>
449.51 -
449.52 -<br><br>
449.53 - Returns the computer's network name (may not be fully qualified!). An empty
449.54 - string is returned if the value cannot be determined.
449.55 -
449.56 -<br><br>
449.57 -<a href="func:platform(aliased=0, terse=0)">platform(aliased=0, terse=0)</a>
449.58 -
449.59 -<br><br>
449.60 - Returns a single string identifying the underlying platform with as much useful
449.61 - information as possible.
449.62 -
449.63 -<br><br>
449.64 - The output is intended to be *human readable* rather than machine parseable. It
449.65 - may look different on different platforms and this is intended.
449.66 -
449.67 -<br><br>
449.68 - If <b>aliased</b> is true, the function will use aliases for various platforms that
449.69 - report system names which differ from their common names, for example SunOS will
449.70 - be reported as Solaris. The <a href="func:system_alias">system_alias</a> function is used to implement
449.71 - this.
449.72 -
449.73 -<br><br>
449.74 - Setting <b>terse</b> to true causes the function to return only the absolute minimum
449.75 - information needed to identify the platform.
449.76 -
449.77 -<br><br>
449.78 -<a href="func:processor()">processor()</a>
449.79 -
449.80 -<br><br>
449.81 - Returns the (real) processor name, e.g. <code>'amdk6'</code>.
449.82 -
449.83 -<br><br>
449.84 - An empty string is returned if the value cannot be determined. Note that many
449.85 - platforms do not provide this information or simply return the same value as for
449.86 - <a href="func:machine">machine</a>. NetBSD does this.
449.87 -
449.88 -<br><br>
449.89 -<a href="func:python_build()">python_build()</a>
449.90 -
449.91 -<br><br>
449.92 - Returns a tuple <code>(buildno, builddate)</code> stating the Python build number and
449.93 - date as strings.
449.94 -
449.95 -<br><br>
449.96 -<a href="func:python_compiler()">python_compiler()</a>
449.97 -
449.98 -<br><br>
449.99 - Returns a string identifying the compiler used for compiling Python.
449.100 -
449.101 -<br><br>
449.102 -<a href="func:python_branch()">python_branch()</a>
449.103 -
449.104 -<br><br>
449.105 - Returns a string identifying the Python implementation SCM branch.
449.106 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
449.107 -</div>
449.108 -<a href="func:python_implementation()">python_implementation()</a>
449.109 - Returns a string identifying the Python implementation. Possible return values
449.110 - are: 'CPython', 'IronPython', 'Jython'
449.111 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
449.112 -</div>
449.113 -<a href="func:python_revision()">python_revision()</a>
449.114 - Returns a string identifying the Python implementation SCM revision.
449.115 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
449.116 -</div>
449.117 -<a href="func:python_version()">python_version()</a>
449.118 - Returns the Python version as string <code>'major.minor.patchlevel'</code>
449.119 -
449.120 -<br><br>
449.121 - Note that unlike the Python <code>sys.version</code>, the returned value will always
449.122 - include the patchlevel (it defaults to 0).
449.123 -
449.124 -<br><br>
449.125 -<a href="func:python_version_tuple()">python_version_tuple()</a>
449.126 -
449.127 -<br><br>
449.128 - Returns the Python version as tuple <code>(major, minor, patchlevel)</code> of strings.
449.129 -
449.130 -<br><br>
449.131 - Note that unlike the Python <code>sys.version</code>, the returned value will always
449.132 - include the patchlevel (it defaults to <code>'0'</code>).
449.133 -
449.134 -<br><br>
449.135 -<a href="func:release()">release()</a>
449.136 -
449.137 -<br><br>
449.138 - Returns the system's release, e.g. <code>'2.2.0'</code> or <code>'NT'</code> An empty string is
449.139 - returned if the value cannot be determined.
449.140 -
449.141 -<br><br>
449.142 -<a href="func:system()">system()</a>
449.143 -
449.144 -<br><br>
449.145 - Returns the system/OS name, e.g. <code>'Linux'</code>, <code>'Windows'</code>, or <code>'Java'</code>. An
449.146 - empty string is returned if the value cannot be determined.
449.147 -
449.148 -<br><br>
449.149 -<a href="func:system_alias(system, release, version)">system_alias(system, release, version)</a>
449.150 -
449.151 -<br><br>
449.152 - Returns <code>(system, release, version)</code> aliased to common marketing names used
449.153 - for some systems. It also does some reordering of the information in some cases
449.154 - where it would otherwise cause confusion.
449.155 -
449.156 -<br><br>
449.157 -<a href="func:version()">version()</a>
449.158 -
449.159 -<br><br>
449.160 - Returns the system's release version, e.g. <code>'#3 on degas'</code>. An empty string is
449.161 - returned if the value cannot be determined.
449.162 -
449.163 -<br><br>
449.164 -<a href="func:uname()">uname()</a>
449.165 -
449.166 -<br><br>
449.167 - Fairly portable uname interface. Returns a tuple of strings ``(system, node,
449.168 - release, version, machine, processor)`` identifying the underlying platform.
449.169 -
449.170 -<br><br>
449.171 - Note that unlike the <a href="func:os.uname">os.uname</a> function this also returns possible
449.172 - processor information as additional tuple entry.
449.173 -
449.174 -<br><br>
449.175 - Entries which cannot be determined are set to <code>''</code>.
449.176 -
449.177 -<br><br>
449.178 -<h3>Java Platform
449.179 -</h3>
449.180 -<a href="func:java_ver(release='', vendor='', vminfo=('','',''), osinfo=('','',''))">java_ver(release='', vendor='', vminfo=('','',''), osinfo=('','',''))</a>
449.181 -
449.182 -<br><br>
449.183 - Version interface for JPython.
449.184 -
449.185 -<br><br>
449.186 - Returns a tuple <code>(release, vendor, vminfo, osinfo)</code> with <b>vminfo</b> being a
449.187 - tuple <code>(vm_name, vm_release, vm_vendor)</code> and <b>osinfo</b> being a tuple
449.188 - <code>(os_name, os_version, os_arch)</code>. Values which cannot be determined are set to
449.189 - the defaults given as parameters (which all default to <code>''</code>).
449.190 -
449.191 -<br><br>
449.192 -<h3>Windows Platform
449.193 -</h3>
449.194 -<a href="func:win32_ver(release='', version='', csd='', ptype='')">win32_ver(release='', version='', csd='', ptype='')</a>
449.195 -
449.196 -<br><br>
449.197 - Get additional version information from the Windows Registry and return a tuple
449.198 - <code>(version, csd, ptype)</code> referring to version number, CSD level and OS type
449.199 - (multi/single processor).
449.200 -
449.201 -<br><br>
449.202 - As a hint: <b>ptype</b> is <code>'Uniprocessor Free'</code> on single processor NT machines
449.203 - and <code>'Multiprocessor Free'</code> on multi processor machines. The *'Free'* refers
449.204 - to the OS version being free of debugging code. It could also state *'Checked'*
449.205 - which means the OS version uses debugging code, i.e. code that checks arguments,
449.206 - ranges, etc.
449.207 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
449.208 -
449.209 -<br><br>
449.210 - Note: this function works best with Mark Hammond's
449.211 - <a href="mod:win32all">win32all</a> package installed, but also on Python 2.3 and
449.212 - later (support for this was added in Python 2.6). It obviously
449.213 - only runs on Win32 compatible platforms.
449.214 -</div>
449.215 -<h3>Win95/98 specific
449.216 -</h3>
449.217 -<a href="func:popen(cmd, mode='r', bufsize=None)">popen(cmd, mode='r', bufsize=None)</a>
449.218 -
449.219 -<br><br>
449.220 - Portable <a href="func:popen">popen</a> interface. Find a working popen implementation
449.221 - preferring <a href="func:win32pipe.popen">win32pipe.popen</a>. On Windows NT, <a href="func:win32pipe.popen">win32pipe.popen</a>
449.222 - should work; on Windows 9x it hangs due to bugs in the MS C library.
449.223 -
449.224 -<br><br>
449.225 -<h3>Mac OS Platform
449.226 -</h3>
449.227 -<a href="func:mac_ver(release='', versioninfo=('','',''), machine='')">mac_ver(release='', versioninfo=('','',''), machine='')</a>
449.228 -
449.229 -<br><br>
449.230 - Get Mac OS version information and return it as tuple ``(release, versioninfo,
449.231 - machine)<code> with *versioninfo* being a tuple </code>(version, dev_stage,
449.232 - non_release_version)``.
449.233 -
449.234 -<br><br>
449.235 - Entries which cannot be determined are set to <code>''</code>. All tuple entries are
449.236 - strings.
449.237 -
449.238 -<br><br>
449.239 - Documentation for the underlying :cfunc:<code>gestalt</code> API is available online at
449.240 - http://www.rgaros.nl/gestalt/.
449.241 -
449.242 -<br><br>
449.243 -<h3>Unix Platforms
449.244 -</h3>
449.245 -<a href="func:dist(distname='', version='', id='', supported_dists=('SuSE','debian','redhat','mandrake',...))">dist(distname='', version='', id='', supported_dists=('SuSE','debian','redhat','mandrake',...))</a>
449.246 -
449.247 -<br><br>
449.248 - This is another name for <a href="func:linux_distribution">linux_distribution</a>.
449.249 -
449.250 -<br><br>
449.251 -<a href="func:linux_distribution(distname='', version='', id='', supported_dists=('SuSE','debian','redhat','mandrake',...), full_distribution_name=1)">linux_distribution(distname='', version='', id='', supported_dists=('SuSE','debian','redhat','mandrake',...), full_distribution_name=1)</a>
449.252 -
449.253 -<br><br>
449.254 - Tries to determine the name of the Linux OS distribution name.
449.255 -
449.256 -<br><br>
449.257 - <code>supported_dists</code> may be given to define the set of Linux distributions to
449.258 - look for. It defaults to a list of currently supported Linux distributions
449.259 - identified by their release file name.
449.260 -
449.261 -<br><br>
449.262 - If <code>full_distribution_name</code> is true (default), the full distribution read
449.263 - from the OS is returned. Otherwise the short name taken from
449.264 - <code>supported_dists</code> is used.
449.265 -
449.266 -<br><br>
449.267 - Returns a tuple <code>(distname,version,id)</code> which defaults to the args given as
449.268 - parameters. <code>id</code> is the item in parentheses after the version number. It
449.269 - is usually the version codename.
449.270 -
449.271 -<br><br>
449.272 -<a href="func:libc_ver(executable=sys.executable, lib='', version='', chunksize=2048)">libc_ver(executable=sys.executable, lib='', version='', chunksize=2048)</a>
449.273 -
449.274 -<br><br>
449.275 - Tries to determine the libc version against which the file executable (defaults
449.276 - to the Python interpreter) is linked. Returns a tuple of strings ``(lib,
449.277 - version)`` which default to the given parameters in case the lookup fails.
449.278 -
449.279 -<br><br>
449.280 - Note that this function has intimate knowledge of how different libc versions
449.281 - add symbols to the executable is probably only usable for executables compiled
449.282 - using :program:<code>gcc</code>.
449.283 -
449.284 -<br><br>
449.285 - The file is read and scanned in chunks of <b>chunksize</b> bytes.
449.286 -</body></html>
450.1 --- a/python.editor/test/unit/data/testfiles/rst/platform.rst.indexed Sun Jan 04 13:11:53 2015 -0600
450.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
450.3 @@ -1,32 +0,0 @@
450.4 -
450.5 -
450.6 -Document 0
450.7 -Searchable Keys:
450.8 - item : architecture;F;|DOCUMENTED|DOC_ONLY|;executable,bits,linkage;
450.9 - item : dist;F;|DOCUMENTED|DOC_ONLY|;distname,version,id,supported_dists;
450.10 - item : java_ver;F;|DOCUMENTED|DOC_ONLY|;release,vendor,vminfo,osinfo;
450.11 - item : libc_ver;F;|DOCUMENTED|DOC_ONLY|;executable,lib,version,chunksize;
450.12 - item : linux_distribution;F;|DOCUMENTED|DOC_ONLY|;distname,version,id,supported_dists,full_distribution_name;
450.13 - item : mac_ver;F;|DOCUMENTED|DOC_ONLY|;release,versioninfo,machine;
450.14 - item : machine;F;|DOCUMENTED|DOC_ONLY|;;
450.15 - item : node;F;|DOCUMENTED|DOC_ONLY|;;
450.16 - item : platform;F;|DOCUMENTED|DOC_ONLY|;aliased,terse;
450.17 - item : popen;F;|DOCUMENTED|DOC_ONLY|;cmd,mode,bufsize;
450.18 - item : processor;F;|DOCUMENTED|DOC_ONLY|;;
450.19 - item : python_branch;F;|DOCUMENTED|DOC_ONLY|;;
450.20 - item : python_build;F;|DOCUMENTED|DOC_ONLY|;;
450.21 - item : python_compiler;F;|DOCUMENTED|DOC_ONLY|;;
450.22 - item : python_implementation;F;|DOCUMENTED|DOC_ONLY|;;
450.23 - item : python_revision;F;|DOCUMENTED|DOC_ONLY|;;
450.24 - item : python_version;F;|DOCUMENTED|DOC_ONLY|;;
450.25 - item : python_version_tuple;F;|DOCUMENTED|DOC_ONLY|;;
450.26 - item : release;F;|DOCUMENTED|DOC_ONLY|;;
450.27 - item : system;F;|DOCUMENTED|DOC_ONLY|;;
450.28 - item : system_alias;F;|DOCUMENTED|DOC_ONLY|;system,release,version;
450.29 - item : uname;F;|DOCUMENTED|DOC_ONLY|;;
450.30 - item : version;F;|DOCUMENTED|DOC_ONLY|;;
450.31 - item : win32_ver;F;|DOCUMENTED|DOC_ONLY|;release,version,csd,ptype;
450.32 - module : platform
450.33 -
450.34 -Not Searchable Keys:
450.35 - modattrs : S
451.1 --- a/python.editor/test/unit/data/testfiles/rst/smtpd.rst Sun Jan 04 13:11:53 2015 -0600
451.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
451.3 @@ -1,73 +0,0 @@
451.4 -:mod:`smtpd` --- SMTP Server
451.5 -============================
451.6 -
451.7 -.. module:: smtpd
451.8 - :synopsis: A SMTP server implementation in Python.
451.9 -
451.10 -.. moduleauthor:: Barry Warsaw <barry@zope.com>
451.11 -.. sectionauthor:: Moshe Zadka <moshez@moshez.org>
451.12 -
451.13 -
451.14 -
451.15 -
451.16 -This module offers several classes to implement SMTP servers. One is a generic
451.17 -do-nothing implementation, which can be overridden, while the other two offer
451.18 -specific mail-sending strategies.
451.19 -
451.20 -
451.21 -SMTPServer Objects
451.22 -------------------
451.23 -
451.24 -
451.25 -.. class:: SMTPServer(localaddr, remoteaddr)
451.26 -
451.27 - Create a new :class:`SMTPServer` object, which binds to local address
451.28 - *localaddr*. It will treat *remoteaddr* as an upstream SMTP relayer. It
451.29 - inherits from :class:`asyncore.dispatcher`, and so will insert itself into
451.30 - :mod:`asyncore`'s event loop on instantiation.
451.31 -
451.32 -
451.33 - .. method:: process_message(peer, mailfrom, rcpttos, data)
451.34 -
451.35 - Raise :exc:`NotImplementedError` exception. Override this in subclasses to
451.36 - do something useful with this message. Whatever was passed in the
451.37 - constructor as *remoteaddr* will be available as the :attr:`_remoteaddr`
451.38 - attribute. *peer* is the remote host's address, *mailfrom* is the envelope
451.39 - originator, *rcpttos* are the envelope recipients and *data* is a string
451.40 - containing the contents of the e-mail (which should be in :rfc:`2822`
451.41 - format).
451.42 -
451.43 -
451.44 -DebuggingServer Objects
451.45 ------------------------
451.46 -
451.47 -
451.48 -.. class:: DebuggingServer(localaddr, remoteaddr)
451.49 -
451.50 - Create a new debugging server. Arguments are as per :class:`SMTPServer`.
451.51 - Messages will be discarded, and printed on stdout.
451.52 -
451.53 -
451.54 -PureProxy Objects
451.55 ------------------
451.56 -
451.57 -
451.58 -.. class:: PureProxy(localaddr, remoteaddr)
451.59 -
451.60 - Create a new pure proxy server. Arguments are as per :class:`SMTPServer`.
451.61 - Everything will be relayed to *remoteaddr*. Note that running this has a good
451.62 - chance to make you into an open relay, so please be careful.
451.63 -
451.64 -
451.65 -MailmanProxy Objects
451.66 ---------------------
451.67 -
451.68 -
451.69 -.. class:: MailmanProxy(localaddr, remoteaddr)
451.70 -
451.71 - Create a new pure proxy server. Arguments are as per :class:`SMTPServer`.
451.72 - Everything will be relayed to *remoteaddr*, unless local mailman configurations
451.73 - knows about an address, in which case it will be handled via mailman. Note that
451.74 - running this has a good chance to make you into an open relay, so please be
451.75 - careful.
451.76 -
452.1 --- a/python.editor/test/unit/data/testfiles/rst/smtpd.rst.html Sun Jan 04 13:11:53 2015 -0600
452.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
452.3 @@ -1,69 +0,0 @@
452.4 -<html><body>
452.5 -<h2><a href="mod:smtpd">smtpd</a> --- SMTP Server
452.6 -</h2>
452.7 -<a href="module:smtpd">smtpd</a><br>
452.8 - A SMTP server implementation in Python.
452.9 -
452.10 -<br><br>
452.11 -<br>Module Author:</b> Barry Warsaw <barry@zope.com>
452.12 -<br>Section Author:</b> Moshe Zadka <moshez@moshez.org>
452.13 -
452.14 -<br><br>
452.15 -This module offers several classes to implement SMTP servers. One is a generic
452.16 -do-nothing implementation, which can be overridden, while the other two offer
452.17 -specific mail-sending strategies.
452.18 -
452.19 -<br><br>
452.20 -<h3>SMTPServer Objects
452.21 -</h3>
452.22 -<a href="class:SMTPServer(localaddr, remoteaddr)">SMTPServer(localaddr, remoteaddr)</a>
452.23 -
452.24 -<br><br>
452.25 - Create a new <a href="class:SMTPServer">SMTPServer</a> object, which binds to local address
452.26 - <b>localaddr</b>. It will treat <b>remoteaddr</b> as an upstream SMTP relayer. It
452.27 - inherits from <a href="class:asyncore.dispatcher">asyncore.dispatcher</a>, and so will insert itself into
452.28 - <a href="mod:asyncore">asyncore</a>'s event loop on instantiation.
452.29 -
452.30 -<br><br>
452.31 -<a href="meth:process_message(peer, mailfrom, rcpttos, data)">process_message(peer, mailfrom, rcpttos, data)</a>
452.32 -
452.33 -<br><br>
452.34 - Raise <a href="exc:NotImplementedError">NotImplementedError</a> exception. Override this in subclasses to
452.35 - do something useful with this message. Whatever was passed in the
452.36 - constructor as <b>remoteaddr</b> will be available as the <code>_remoteaddr</code>
452.37 - attribute. <b>peer</b> is the remote host's address, <b>mailfrom</b> is the envelope
452.38 - originator, <b>rcpttos</b> are the envelope recipients and <b>data</b> is a string
452.39 - containing the contents of the e-mail (which should be in :rfc:<code>2822</code>
452.40 - format).
452.41 -
452.42 -<br><br>
452.43 -<h3>DebuggingServer Objects
452.44 -</h3>
452.45 -<a href="class:DebuggingServer(localaddr, remoteaddr)">DebuggingServer(localaddr, remoteaddr)</a>
452.46 -
452.47 -<br><br>
452.48 - Create a new debugging server. Arguments are as per <a href="class:SMTPServer">SMTPServer</a>.
452.49 - Messages will be discarded, and printed on stdout.
452.50 -
452.51 -<br><br>
452.52 -<h3>PureProxy Objects
452.53 -</h3>
452.54 -<a href="class:PureProxy(localaddr, remoteaddr)">PureProxy(localaddr, remoteaddr)</a>
452.55 -
452.56 -<br><br>
452.57 - Create a new pure proxy server. Arguments are as per <a href="class:SMTPServer">SMTPServer</a>.
452.58 - Everything will be relayed to <b>remoteaddr</b>. Note that running this has a good
452.59 - chance to make you into an open relay, so please be careful.
452.60 -
452.61 -<br><br>
452.62 -<h3>MailmanProxy Objects
452.63 -</h3>
452.64 -<a href="class:MailmanProxy(localaddr, remoteaddr)">MailmanProxy(localaddr, remoteaddr)</a>
452.65 -
452.66 -<br><br>
452.67 - Create a new pure proxy server. Arguments are as per <a href="class:SMTPServer">SMTPServer</a>.
452.68 - Everything will be relayed to <b>remoteaddr</b>, unless local mailman configurations
452.69 - knows about an address, in which case it will be handled via mailman. Note that
452.70 - running this has a good chance to make you into an open relay, so please be
452.71 - careful.
452.72 -</body></html>
453.1 --- a/python.editor/test/unit/data/testfiles/rst/smtpd.rst.indexed Sun Jan 04 13:11:53 2015 -0600
453.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
453.3 @@ -1,57 +0,0 @@
453.4 -
453.5 -
453.6 -Document 0
453.7 -Searchable Keys:
453.8 - class : DebuggingServer
453.9 - class-ig : debuggingserver
453.10 - in : smtpd
453.11 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;localaddr,remoteaddr;
453.12 -
453.13 -Not Searchable Keys:
453.14 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
453.15 -
453.16 -
453.17 -Document 1
453.18 -Searchable Keys:
453.19 - class : MailmanProxy
453.20 - class-ig : mailmanproxy
453.21 - in : smtpd
453.22 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;localaddr,remoteaddr;
453.23 -
453.24 -Not Searchable Keys:
453.25 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
453.26 -
453.27 -
453.28 -Document 2
453.29 -Searchable Keys:
453.30 - class : PureProxy
453.31 - class-ig : pureproxy
453.32 - in : smtpd
453.33 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;localaddr,remoteaddr;
453.34 -
453.35 -Not Searchable Keys:
453.36 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
453.37 -
453.38 -
453.39 -Document 3
453.40 -Searchable Keys:
453.41 - class : SMTPServer
453.42 - class-ig : smtpserver
453.43 - in : smtpd
453.44 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;localaddr,remoteaddr;
453.45 - member : process_message;F;|DOCUMENTED|DOC_ONLY|;peer,mailfrom,rcpttos,data;
453.46 -
453.47 -Not Searchable Keys:
453.48 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
453.49 -
453.50 -
453.51 -Document 4
453.52 -Searchable Keys:
453.53 - item : DebuggingServer;C;|DOCUMENTED|DOC_ONLY|;
453.54 - item : MailmanProxy;C;|DOCUMENTED|DOC_ONLY|;
453.55 - item : PureProxy;C;|DOCUMENTED|DOC_ONLY|;
453.56 - item : SMTPServer;C;|DOCUMENTED|DOC_ONLY|;
453.57 - module : smtpd
453.58 -
453.59 -Not Searchable Keys:
453.60 - modattrs : S
454.1 --- a/python.editor/test/unit/data/testfiles/rst/stdtypes.rst Sun Jan 04 13:11:53 2015 -0600
454.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
454.3 @@ -1,2662 +0,0 @@
454.4 -.. XXX: reference/datamodel and this have quite a few overlaps!
454.5 -
454.6 -
454.7 -.. _bltin-types:
454.8 -
454.9 -**************
454.10 -Built-in Types
454.11 -**************
454.12 -
454.13 -The following sections describe the standard types that are built into the
454.14 -interpreter.
454.15 -
454.16 -.. note::
454.17 -
454.18 - Historically (until release 2.2), Python's built-in types have differed from
454.19 - user-defined types because it was not possible to use the built-in types as the
454.20 - basis for object-oriented inheritance. This limitation no longer
454.21 - exists.
454.22 -
454.23 -.. index:: pair: built-in; types
454.24 -
454.25 -The principal built-in types are numerics, sequences, mappings, files, classes,
454.26 -instances and exceptions.
454.27 -
454.28 -.. index:: statement: print
454.29 -
454.30 -Some operations are supported by several object types; in particular,
454.31 -practically all objects can be compared, tested for truth value, and converted
454.32 -to a string (with the :func:`repr` function or the slightly different
454.33 -:func:`str` function). The latter function is implicitly used when an object is
454.34 -written by the :func:`print` function.
454.35 -
454.36 -
454.37 -.. _truth:
454.38 -
454.39 -Truth Value Testing
454.40 -===================
454.41 -
454.42 -.. index::
454.43 - statement: if
454.44 - statement: while
454.45 - pair: truth; value
454.46 - pair: Boolean; operations
454.47 - single: false
454.48 -
454.49 -Any object can be tested for truth value, for use in an :keyword:`if` or
454.50 -:keyword:`while` condition or as operand of the Boolean operations below. The
454.51 -following values are considered false:
454.52 -
454.53 - .. index:: single: None (Built-in object)
454.54 -
454.55 -* ``None``
454.56 -
454.57 - .. index:: single: False (Built-in object)
454.58 -
454.59 -* ``False``
454.60 -
454.61 -* zero of any numeric type, for example, ``0``, ``0L``, ``0.0``, ``0j``.
454.62 -
454.63 -* any empty sequence, for example, ``''``, ``()``, ``[]``.
454.64 -
454.65 -* any empty mapping, for example, ``{}``.
454.66 -
454.67 -* instances of user-defined classes, if the class defines a :meth:`__nonzero__`
454.68 - or :meth:`__len__` method, when that method returns the integer zero or
454.69 - :class:`bool` value ``False``. [#]_
454.70 -
454.71 -.. index:: single: true
454.72 -
454.73 -All other values are considered true --- so objects of many types are always
454.74 -true.
454.75 -
454.76 -.. index::
454.77 - operator: or
454.78 - operator: and
454.79 - single: False
454.80 - single: True
454.81 -
454.82 -Operations and built-in functions that have a Boolean result always return ``0``
454.83 -or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated.
454.84 -(Important exception: the Boolean operations ``or`` and ``and`` always return
454.85 -one of their operands.)
454.86 -
454.87 -
454.88 -.. _boolean:
454.89 -
454.90 -Boolean Operations --- :keyword:`and`, :keyword:`or`, :keyword:`not`
454.91 -====================================================================
454.92 -
454.93 -.. index:: pair: Boolean; operations
454.94 -
454.95 -These are the Boolean operations, ordered by ascending priority:
454.96 -
454.97 -+-------------+---------------------------------+-------+
454.98 -| Operation | Result | Notes |
454.99 -+=============+=================================+=======+
454.100 -| ``x or y`` | if *x* is false, then *y*, else | \(1) |
454.101 -| | *x* | |
454.102 -+-------------+---------------------------------+-------+
454.103 -| ``x and y`` | if *x* is false, then *x*, else | \(2) |
454.104 -| | *y* | |
454.105 -+-------------+---------------------------------+-------+
454.106 -| ``not x`` | if *x* is false, then ``True``, | \(3) |
454.107 -| | else ``False`` | |
454.108 -+-------------+---------------------------------+-------+
454.109 -
454.110 -.. index::
454.111 - operator: and
454.112 - operator: or
454.113 - operator: not
454.114 -
454.115 -Notes:
454.116 -
454.117 -(1)
454.118 - This is a short-circuit operator, so it only evaluates the second
454.119 - argument if the first one is :const:`False`.
454.120 -
454.121 -(2)
454.122 - This is a short-circuit operator, so it only evaluates the second
454.123 - argument if the first one is :const:`True`.
454.124 -
454.125 -(3)
454.126 - ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is
454.127 - interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error.
454.128 -
454.129 -
454.130 -.. _stdcomparisons:
454.131 -
454.132 -Comparisons
454.133 -===========
454.134 -
454.135 -.. index:: pair: chaining; comparisons
454.136 -
454.137 -Comparison operations are supported by all objects. They all have the same
454.138 -priority (which is higher than that of the Boolean operations). Comparisons can
454.139 -be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and
454.140 -y <= z``, except that *y* is evaluated only once (but in both cases *z* is not
454.141 -evaluated at all when ``x < y`` is found to be false).
454.142 -
454.143 -This table summarizes the comparison operations:
454.144 -
454.145 -+------------+-------------------------+-------+
454.146 -| Operation | Meaning | Notes |
454.147 -+============+=========================+=======+
454.148 -| ``<`` | strictly less than | |
454.149 -+------------+-------------------------+-------+
454.150 -| ``<=`` | less than or equal | |
454.151 -+------------+-------------------------+-------+
454.152 -| ``>`` | strictly greater than | |
454.153 -+------------+-------------------------+-------+
454.154 -| ``>=`` | greater than or equal | |
454.155 -+------------+-------------------------+-------+
454.156 -| ``==`` | equal | |
454.157 -+------------+-------------------------+-------+
454.158 -| ``!=`` | not equal | \(1) |
454.159 -+------------+-------------------------+-------+
454.160 -| ``is`` | object identity | |
454.161 -+------------+-------------------------+-------+
454.162 -| ``is not`` | negated object identity | |
454.163 -+------------+-------------------------+-------+
454.164 -
454.165 -.. index::
454.166 - pair: operator; comparison
454.167 - operator: ==
454.168 - operator: <
454.169 - operator: <=
454.170 - operator: >
454.171 - operator: >=
454.172 - operator: !=
454.173 - operator: is
454.174 - operator: is not
454.175 -
454.176 -Notes:
454.177 -
454.178 -(1)
454.179 - ``!=`` can also be written ``<>``, but this is an obsolete usage
454.180 - kept for backwards compatibility only. New code should always use
454.181 - ``!=``.
454.182 -
454.183 -.. index::
454.184 - pair: object; numeric
454.185 - pair: objects; comparing
454.186 -
454.187 -Objects of different types, except different numeric types and different string
454.188 -types, never compare equal; such objects are ordered consistently but
454.189 -arbitrarily (so that sorting a heterogeneous array yields a consistent result).
454.190 -Furthermore, some types (for example, file objects) support only a degenerate
454.191 -notion of comparison where any two objects of that type are unequal. Again,
454.192 -such objects are ordered arbitrarily but consistently. The ``<``, ``<=``, ``>``
454.193 -and ``>=`` operators will raise a :exc:`TypeError` exception when any operand is
454.194 -a complex number.
454.195 -
454.196 -.. index:: single: __cmp__() (instance method)
454.197 -
454.198 -Instances of a class normally compare as non-equal unless the class defines the
454.199 -:meth:`__cmp__` method. Refer to :ref:`customization`) for information on the
454.200 -use of this method to effect object comparisons.
454.201 -
454.202 -**Implementation note:** Objects of different types except numbers are ordered
454.203 -by their type names; objects of the same types that don't support proper
454.204 -comparison are ordered by their address.
454.205 -
454.206 -.. index::
454.207 - operator: in
454.208 - operator: not in
454.209 -
454.210 -Two more operations with the same syntactic priority, ``in`` and ``not in``, are
454.211 -supported only by sequence types (below).
454.212 -
454.213 -
454.214 -.. _typesnumeric:
454.215 -
454.216 -Numeric Types --- :class:`int`, :class:`float`, :class:`long`, :class:`complex`
454.217 -===============================================================================
454.218 -
454.219 -.. index::
454.220 - object: numeric
454.221 - object: Boolean
454.222 - object: integer
454.223 - object: long integer
454.224 - object: floating point
454.225 - object: complex number
454.226 - pair: C; language
454.227 -
454.228 -There are four distinct numeric types: :dfn:`plain integers`, :dfn:`long
454.229 -integers`, :dfn:`floating point numbers`, and :dfn:`complex numbers`. In
454.230 -addition, Booleans are a subtype of plain integers. Plain integers (also just
454.231 -called :dfn:`integers`) are implemented using :ctype:`long` in C, which gives
454.232 -them at least 32 bits of precision (``sys.maxint`` is always set to the maximum
454.233 -plain integer value for the current platform, the minimum value is
454.234 -``-sys.maxint - 1``). Long integers have unlimited precision. Floating point
454.235 -numbers are implemented using :ctype:`double` in C. All bets on their precision
454.236 -are off unless you happen to know the machine you are working with.
454.237 -
454.238 -Complex numbers have a real and imaginary part, which are each implemented using
454.239 -:ctype:`double` in C. To extract these parts from a complex number *z*, use
454.240 -``z.real`` and ``z.imag``.
454.241 -
454.242 -.. index::
454.243 - pair: numeric; literals
454.244 - pair: integer; literals
454.245 - triple: long; integer; literals
454.246 - pair: floating point; literals
454.247 - pair: complex number; literals
454.248 - pair: hexadecimal; literals
454.249 - pair: octal; literals
454.250 -
454.251 -Numbers are created by numeric literals or as the result of built-in functions
454.252 -and operators. Unadorned integer literals (including hex and octal numbers)
454.253 -yield plain integers unless the value they denote is too large to be represented
454.254 -as a plain integer, in which case they yield a long integer. Integer literals
454.255 -with an ``'L'`` or ``'l'`` suffix yield long integers (``'L'`` is preferred
454.256 -because ``1l`` looks too much like eleven!). Numeric literals containing a
454.257 -decimal point or an exponent sign yield floating point numbers. Appending
454.258 -``'j'`` or ``'J'`` to a numeric literal yields a complex number with a zero real
454.259 -part. A complex numeric literal is the sum of a real and an imaginary part.
454.260 -
454.261 -.. index::
454.262 - single: arithmetic
454.263 - builtin: int
454.264 - builtin: long
454.265 - builtin: float
454.266 - builtin: complex
454.267 -
454.268 -Python fully supports mixed arithmetic: when a binary arithmetic operator has
454.269 -operands of different numeric types, the operand with the "narrower" type is
454.270 -widened to that of the other, where plain integer is narrower than long integer
454.271 -is narrower than floating point is narrower than complex. Comparisons between
454.272 -numbers of mixed type use the same rule. [#]_ The constructors :func:`int`,
454.273 -:func:`long`, :func:`float`, and :func:`complex` can be used to produce numbers
454.274 -of a specific type.
454.275 -
454.276 -All builtin numeric types support the following operations. See
454.277 -:ref:`power` and later sections for the operators' priorities.
454.278 -
454.279 -+--------------------+---------------------------------+--------+
454.280 -| Operation | Result | Notes |
454.281 -+====================+=================================+========+
454.282 -| ``x + y`` | sum of *x* and *y* | |
454.283 -+--------------------+---------------------------------+--------+
454.284 -| ``x - y`` | difference of *x* and *y* | |
454.285 -+--------------------+---------------------------------+--------+
454.286 -| ``x * y`` | product of *x* and *y* | |
454.287 -+--------------------+---------------------------------+--------+
454.288 -| ``x / y`` | quotient of *x* and *y* | \(1) |
454.289 -+--------------------+---------------------------------+--------+
454.290 -| ``x // y`` | (floored) quotient of *x* and | (4)(5) |
454.291 -| | *y* | |
454.292 -+--------------------+---------------------------------+--------+
454.293 -| ``x % y`` | remainder of ``x / y`` | \(4) |
454.294 -+--------------------+---------------------------------+--------+
454.295 -| ``-x`` | *x* negated | |
454.296 -+--------------------+---------------------------------+--------+
454.297 -| ``+x`` | *x* unchanged | |
454.298 -+--------------------+---------------------------------+--------+
454.299 -| ``abs(x)`` | absolute value or magnitude of | \(3) |
454.300 -| | *x* | |
454.301 -+--------------------+---------------------------------+--------+
454.302 -| ``int(x)`` | *x* converted to integer | \(2) |
454.303 -+--------------------+---------------------------------+--------+
454.304 -| ``long(x)`` | *x* converted to long integer | \(2) |
454.305 -+--------------------+---------------------------------+--------+
454.306 -| ``float(x)`` | *x* converted to floating point | \(6) |
454.307 -+--------------------+---------------------------------+--------+
454.308 -| ``complex(re,im)`` | a complex number with real part | |
454.309 -| | *re*, imaginary part *im*. | |
454.310 -| | *im* defaults to zero. | |
454.311 -+--------------------+---------------------------------+--------+
454.312 -| ``c.conjugate()`` | conjugate of the complex number | |
454.313 -| | *c*. (Identity on real numbers) | |
454.314 -+--------------------+---------------------------------+--------+
454.315 -| ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | (3)(4) |
454.316 -+--------------------+---------------------------------+--------+
454.317 -| ``pow(x, y)`` | *x* to the power *y* | (3)(7) |
454.318 -+--------------------+---------------------------------+--------+
454.319 -| ``x ** y`` | *x* to the power *y* | \(7) |
454.320 -+--------------------+---------------------------------+--------+
454.321 -
454.322 -.. index::
454.323 - triple: operations on; numeric; types
454.324 - single: conjugate() (complex number method)
454.325 -
454.326 -Notes:
454.327 -
454.328 -(1)
454.329 - .. index::
454.330 - pair: integer; division
454.331 - triple: long; integer; division
454.332 -
454.333 - For (plain or long) integer division, the result is an integer. The result is
454.334 - always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and
454.335 - (-1)/(-2) is 0. Note that the result is a long integer if either operand is a
454.336 - long integer, regardless of the numeric value.
454.337 -
454.338 -(2)
454.339 - .. index::
454.340 - module: math
454.341 - single: floor() (in module math)
454.342 - single: ceil() (in module math)
454.343 - pair: numeric; conversions
454.344 - pair: C; language
454.345 -
454.346 - Conversion from floating point to (long or plain) integer may round or
454.347 - truncate as in C; see functions :func:`math.floor` and :func:`math.ceil` for
454.348 - well-defined conversions.
454.349 -
454.350 - .. deprecated:: 2.6
454.351 - Instead, convert floats to long explicitly with :func:`trunc`.
454.352 -
454.353 -(3)
454.354 - See :ref:`built-in-funcs` for a full description.
454.355 -
454.356 -(4)
454.357 - Complex floor division operator, modulo operator, and :func:`divmod`.
454.358 -
454.359 - .. deprecated:: 2.3
454.360 - Instead convert to float using :func:`abs` if appropriate.
454.361 -
454.362 -(5)
454.363 - Also referred to as integer division. The resultant value is a whole integer,
454.364 - though the result's type is not necessarily int.
454.365 -
454.366 -(6)
454.367 - float also accepts the strings "nan" and "inf" with an optional prefix "+"
454.368 - or "-" for Not a Number (NaN) and positive or negative infinity.
454.369 -
454.370 - .. versionadded:: 2.6
454.371 -
454.372 -(7)
454.373 - Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for
454.374 - programming languages.
454.375 -
454.376 -All :class:`numbers.Real` types (:class:`int`, :class:`long`, and
454.377 -:class:`float`) also include the following operations:
454.378 -
454.379 -+--------------------+------------------------------------+--------+
454.380 -| Operation | Result | Notes |
454.381 -+====================+====================================+========+
454.382 -| ``trunc(x)`` | *x* truncated to Integral | |
454.383 -+--------------------+------------------------------------+--------+
454.384 -| ``round(x[, n])`` | *x* rounded to n digits, | |
454.385 -| | rounding half to even. If n is | |
454.386 -| | omitted, it defaults to 0. | |
454.387 -+--------------------+------------------------------------+--------+
454.388 -| ``math.floor(x)`` | the greatest integral float <= *x* | |
454.389 -+--------------------+------------------------------------+--------+
454.390 -| ``math.ceil(x)`` | the least integral float >= *x* | |
454.391 -+--------------------+------------------------------------+--------+
454.392 -
454.393 -.. XXXJH exceptions: overflow (when? what operations?) zerodivision
454.394 -
454.395 -
454.396 -.. _bitstring-ops:
454.397 -
454.398 -Bit-string Operations on Integer Types
454.399 ---------------------------------------
454.400 -
454.401 -.. _bit-string-operations:
454.402 -
454.403 -Plain and long integer types support additional operations that make sense only
454.404 -for bit-strings. Negative numbers are treated as their 2's complement value
454.405 -(for long integers, this assumes a sufficiently large number of bits that no
454.406 -overflow occurs during the operation).
454.407 -
454.408 -The priorities of the binary bitwise operations are all lower than the numeric
454.409 -operations and higher than the comparisons; the unary operation ``~`` has the
454.410 -same priority as the other unary numeric operations (``+`` and ``-``).
454.411 -
454.412 -This table lists the bit-string operations sorted in ascending priority:
454.413 -
454.414 -+------------+--------------------------------+----------+
454.415 -| Operation | Result | Notes |
454.416 -+============+================================+==========+
454.417 -| ``x | y`` | bitwise :dfn:`or` of *x* and | |
454.418 -| | *y* | |
454.419 -+------------+--------------------------------+----------+
454.420 -| ``x ^ y`` | bitwise :dfn:`exclusive or` of | |
454.421 -| | *x* and *y* | |
454.422 -+------------+--------------------------------+----------+
454.423 -| ``x & y`` | bitwise :dfn:`and` of *x* and | |
454.424 -| | *y* | |
454.425 -+------------+--------------------------------+----------+
454.426 -| ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
454.427 -+------------+--------------------------------+----------+
454.428 -| ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
454.429 -+------------+--------------------------------+----------+
454.430 -| ``~x`` | the bits of *x* inverted | |
454.431 -+------------+--------------------------------+----------+
454.432 -
454.433 -.. index::
454.434 - triple: operations on; integer; types
454.435 - pair: bit-string; operations
454.436 - pair: shifting; operations
454.437 - pair: masking; operations
454.438 -
454.439 -Notes:
454.440 -
454.441 -(1)
454.442 - Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.
454.443 -
454.444 -(2)
454.445 - A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``. A
454.446 - long integer is returned if the result exceeds the range of plain integers.
454.447 -
454.448 -(3)
454.449 - A right shift by *n* bits is equivalent to division by ``pow(2, n)``.
454.450 -
454.451 -
454.452 -Additional Methods on Float
454.453 ----------------------------
454.454 -
454.455 -The float type has some additional methods.
454.456 -
454.457 -.. method:: float.as_integer_ratio()
454.458 -
454.459 - Return a pair of integers whose ratio is exactly equal to the
454.460 - original float and with a positive denominator. Raises
454.461 - :exc:`OverflowError` on infinities and a :exc:`ValueError` on
454.462 - NaNs.
454.463 -
454.464 - .. versionadded:: 2.6
454.465 -
454.466 -Two methods support conversion to
454.467 -and from hexadecimal strings. Since Python's floats are stored
454.468 -internally as binary numbers, converting a float to or from a
454.469 -*decimal* string usually involves a small rounding error. In
454.470 -contrast, hexadecimal strings allow exact representation and
454.471 -specification of floating-point numbers. This can be useful when
454.472 -debugging, and in numerical work.
454.473 -
454.474 -
454.475 -.. method:: float.hex()
454.476 -
454.477 - Return a representation of a floating-point number as a hexadecimal
454.478 - string. For finite floating-point numbers, this representation
454.479 - will always include a leading ``0x`` and a trailing ``p`` and
454.480 - exponent.
454.481 -
454.482 - .. versionadded:: 2.6
454.483 -
454.484 -
454.485 -.. method:: float.fromhex(s)
454.486 -
454.487 - Class method to return the float represented by a hexadecimal
454.488 - string *s*. The string *s* may have leading and trailing
454.489 - whitespace.
454.490 -
454.491 - .. versionadded:: 2.6
454.492 -
454.493 -
454.494 -Note that :meth:`float.hex` is an instance method, while
454.495 -:meth:`float.fromhex` is a class method.
454.496 -
454.497 -A hexadecimal string takes the form::
454.498 -
454.499 - [sign] ['0x'] integer ['.' fraction] ['p' exponent]
454.500 -
454.501 -where the optional ``sign`` may by either ``+`` or ``-``, ``integer``
454.502 -and ``fraction`` are strings of hexadecimal digits, and ``exponent``
454.503 -is a decimal integer with an optional leading sign. Case is not
454.504 -significant, and there must be at least one hexadecimal digit in
454.505 -either the integer or the fraction. This syntax is similar to the
454.506 -syntax specified in section 6.4.4.2 of the C99 standard, and also to
454.507 -the syntax used in Java 1.5 onwards. In particular, the output of
454.508 -:meth:`float.hex` is usable as a hexadecimal floating-point literal in
454.509 -C or Java code, and hexadecimal strings produced by C's ``%a`` format
454.510 -character or Java's ``Double.toHexString`` are accepted by
454.511 -:meth:`float.fromhex`.
454.512 -
454.513 -
454.514 -Note that the exponent is written in decimal rather than hexadecimal,
454.515 -and that it gives the power of 2 by which to multiply the coefficient.
454.516 -For example, the hexadecimal string ``0x3.a7p10`` represents the
454.517 -floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or
454.518 -``3740.0``::
454.519 -
454.520 - >>> float.fromhex('0x3.a7p10')
454.521 - 3740.0
454.522 -
454.523 -
454.524 -Applying the reverse conversion to ``3740.0`` gives a different
454.525 -hexadecimal string representing the same number::
454.526 -
454.527 - >>> float.hex(3740.0)
454.528 - '0x1.d380000000000p+11'
454.529 -
454.530 -
454.531 -.. _typeiter:
454.532 -
454.533 -Iterator Types
454.534 -==============
454.535 -
454.536 -.. versionadded:: 2.2
454.537 -
454.538 -.. index::
454.539 - single: iterator protocol
454.540 - single: protocol; iterator
454.541 - single: sequence; iteration
454.542 - single: container; iteration over
454.543 -
454.544 -Python supports a concept of iteration over containers. This is implemented
454.545 -using two distinct methods; these are used to allow user-defined classes to
454.546 -support iteration. Sequences, described below in more detail, always support
454.547 -the iteration methods.
454.548 -
454.549 -One method needs to be defined for container objects to provide iteration
454.550 -support:
454.551 -
454.552 -.. XXX duplicated in reference/datamodel!
454.553 -
454.554 -.. method:: container.__iter__()
454.555 -
454.556 - Return an iterator object. The object is required to support the iterator
454.557 - protocol described below. If a container supports different types of
454.558 - iteration, additional methods can be provided to specifically request
454.559 - iterators for those iteration types. (An example of an object supporting
454.560 - multiple forms of iteration would be a tree structure which supports both
454.561 - breadth-first and depth-first traversal.) This method corresponds to the
454.562 - :attr:`tp_iter` slot of the type structure for Python objects in the Python/C
454.563 - API.
454.564 -
454.565 -The iterator objects themselves are required to support the following two
454.566 -methods, which together form the :dfn:`iterator protocol`:
454.567 -
454.568 -
454.569 -.. method:: iterator.__iter__()
454.570 -
454.571 - Return the iterator object itself. This is required to allow both containers
454.572 - and iterators to be used with the :keyword:`for` and :keyword:`in` statements.
454.573 - This method corresponds to the :attr:`tp_iter` slot of the type structure for
454.574 - Python objects in the Python/C API.
454.575 -
454.576 -
454.577 -.. method:: iterator.next()
454.578 -
454.579 - Return the next item from the container. If there are no further items, raise
454.580 - the :exc:`StopIteration` exception. This method corresponds to the
454.581 - :attr:`tp_iternext` slot of the type structure for Python objects in the
454.582 - Python/C API.
454.583 -
454.584 -Python defines several iterator objects to support iteration over general and
454.585 -specific sequence types, dictionaries, and other more specialized forms. The
454.586 -specific types are not important beyond their implementation of the iterator
454.587 -protocol.
454.588 -
454.589 -The intention of the protocol is that once an iterator's :meth:`next` method
454.590 -raises :exc:`StopIteration`, it will continue to do so on subsequent calls.
454.591 -Implementations that do not obey this property are deemed broken. (This
454.592 -constraint was added in Python 2.3; in Python 2.2, various iterators are broken
454.593 -according to this rule.)
454.594 -
454.595 -Python's :term:`generator`\s provide a convenient way to implement the iterator
454.596 -protocol. If a container object's :meth:`__iter__` method is implemented as a
454.597 -generator, it will automatically return an iterator object (technically, a
454.598 -generator object) supplying the :meth:`__iter__` and :meth:`next` methods.
454.599 -
454.600 -
454.601 -.. _typesseq:
454.602 -
454.603 -Sequence Types --- :class:`str`, :class:`unicode`, :class:`list`, :class:`tuple`, :class:`buffer`, :class:`xrange`
454.604 -==================================================================================================================
454.605 -
454.606 -There are six sequence types: strings, Unicode strings, lists, tuples, buffers,
454.607 -and xrange objects.
454.608 -(For other containers see the built in :class:`dict`, :class:`list`,
454.609 -:class:`set`, and :class:`tuple` classes, and the :mod:`collections`
454.610 -module.)
454.611 -
454.612 -
454.613 -.. index::
454.614 - object: sequence
454.615 - object: string
454.616 - object: Unicode
454.617 - object: tuple
454.618 - object: list
454.619 - object: buffer
454.620 - object: xrange
454.621 -
454.622 -String literals are written in single or double quotes: ``'xyzzy'``,
454.623 -``"frobozz"``. See :ref:`strings` for more about string literals.
454.624 -Unicode strings are much like strings, but are specified in the syntax
454.625 -using a preceding ``'u'`` character: ``u'abc'``, ``u"def"``. In addition
454.626 -to the functionality described here, there are also string-specific
454.627 -methods described in the :ref:`string-methods` section. Lists are
454.628 -constructed with square brackets, separating items with commas: ``[a, b, c]``.
454.629 -Tuples are constructed by the comma operator (not within square
454.630 -brackets), with or without enclosing parentheses, but an empty tuple
454.631 -must have the enclosing parentheses, such as ``a, b, c`` or ``()``. A
454.632 -single item tuple must have a trailing comma, such as ``(d,)``.
454.633 -
454.634 -Buffer objects are not directly supported by Python syntax, but can be created
454.635 -by calling the builtin function :func:`buffer`. They don't support
454.636 -concatenation or repetition.
454.637 -
454.638 -Objects of type xrange are similar to buffers in that there is no specific syntax to
454.639 -create them, but they are created using the :func:`xrange` function. They don't
454.640 -support slicing, concatenation or repetition, and using ``in``, ``not in``,
454.641 -:func:`min` or :func:`max` on them is inefficient.
454.642 -
454.643 -Most sequence types support the following operations. The ``in`` and ``not in``
454.644 -operations have the same priorities as the comparison operations. The ``+`` and
454.645 -``*`` operations have the same priority as the corresponding numeric operations.
454.646 -[#]_ Additional methods are provided for :ref:`typesseq-mutable`.
454.647 -
454.648 -This table lists the sequence operations sorted in ascending priority
454.649 -(operations in the same box have the same priority). In the table, *s* and *t*
454.650 -are sequences of the same type; *n*, *i* and *j* are integers:
454.651 -
454.652 -+------------------+--------------------------------+----------+
454.653 -| Operation | Result | Notes |
454.654 -+==================+================================+==========+
454.655 -| ``x in s`` | ``True`` if an item of *s* is | \(1) |
454.656 -| | equal to *x*, else ``False`` | |
454.657 -+------------------+--------------------------------+----------+
454.658 -| ``x not in s`` | ``False`` if an item of *s* is | \(1) |
454.659 -| | equal to *x*, else ``True`` | |
454.660 -+------------------+--------------------------------+----------+
454.661 -| ``s + t`` | the concatenation of *s* and | \(6) |
454.662 -| | *t* | |
454.663 -+------------------+--------------------------------+----------+
454.664 -| ``s * n, n * s`` | *n* shallow copies of *s* | \(2) |
454.665 -| | concatenated | |
454.666 -+------------------+--------------------------------+----------+
454.667 -| ``s[i]`` | *i*'th item of *s*, origin 0 | \(3) |
454.668 -+------------------+--------------------------------+----------+
454.669 -| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
454.670 -+------------------+--------------------------------+----------+
454.671 -| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |
454.672 -| | with step *k* | |
454.673 -+------------------+--------------------------------+----------+
454.674 -| ``len(s)`` | length of *s* | |
454.675 -+------------------+--------------------------------+----------+
454.676 -| ``min(s)`` | smallest item of *s* | |
454.677 -+------------------+--------------------------------+----------+
454.678 -| ``max(s)`` | largest item of *s* | |
454.679 -+------------------+--------------------------------+----------+
454.680 -
454.681 -Sequence types also support comparisons. In particular, tuples and lists
454.682 -are compared lexicographically by comparing corresponding
454.683 -elements. This means that to compare equal, every element must compare
454.684 -equal and the two sequences must be of the same type and have the same
454.685 -length. (For full details see :ref:`comparisons` in the language
454.686 -reference.)
454.687 -
454.688 -.. index::
454.689 - triple: operations on; sequence; types
454.690 - builtin: len
454.691 - builtin: min
454.692 - builtin: max
454.693 - pair: concatenation; operation
454.694 - pair: repetition; operation
454.695 - pair: subscript; operation
454.696 - pair: slice; operation
454.697 - pair: extended slice; operation
454.698 - operator: in
454.699 - operator: not in
454.700 -
454.701 -Notes:
454.702 -
454.703 -(1)
454.704 - When *s* is a string or Unicode string object the ``in`` and ``not in``
454.705 - operations act like a substring test. In Python versions before 2.3, *x* had to
454.706 - be a string of length 1. In Python 2.3 and beyond, *x* may be a string of any
454.707 - length.
454.708 -
454.709 -(2)
454.710 - Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
454.711 - sequence of the same type as *s*). Note also that the copies are shallow;
454.712 - nested structures are not copied. This often haunts new Python programmers;
454.713 - consider:
454.714 -
454.715 - >>> lists = [[]] * 3
454.716 - >>> lists
454.717 - [[], [], []]
454.718 - >>> lists[0].append(3)
454.719 - >>> lists
454.720 - [[3], [3], [3]]
454.721 -
454.722 - What has happened is that ``[[]]`` is a one-element list containing an empty
454.723 - list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty
454.724 - list. Modifying any of the elements of ``lists`` modifies this single list.
454.725 - You can create a list of different lists this way:
454.726 -
454.727 - >>> lists = [[] for i in range(3)]
454.728 - >>> lists[0].append(3)
454.729 - >>> lists[1].append(5)
454.730 - >>> lists[2].append(7)
454.731 - >>> lists
454.732 - [[3], [5], [7]]
454.733 -
454.734 -(3)
454.735 - If *i* or *j* is negative, the index is relative to the end of the string:
454.736 - ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is still
454.737 - ``0``.
454.738 -
454.739 -(4)
454.740 - The slice of *s* from *i* to *j* is defined as the sequence of items with index
454.741 - *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use
454.742 - ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or
454.743 - ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is
454.744 - empty.
454.745 -
454.746 -(5)
454.747 - The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
454.748 - items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words,
454.749 - the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
454.750 - *j* is reached (but never including *j*). If *i* or *j* is greater than
454.751 - ``len(s)``, use ``len(s)``. If *i* or *j* are omitted or ``None``, they become
454.752 - "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero.
454.753 - If *k* is ``None``, it is treated like ``1``.
454.754 -
454.755 -(6)
454.756 - If *s* and *t* are both strings, some Python implementations such as CPython can
454.757 - usually perform an in-place optimization for assignments of the form ``s=s+t``
454.758 - or ``s+=t``. When applicable, this optimization makes quadratic run-time much
454.759 - less likely. This optimization is both version and implementation dependent.
454.760 - For performance sensitive code, it is preferable to use the :meth:`str.join`
454.761 - method which assures consistent linear concatenation performance across versions
454.762 - and implementations.
454.763 -
454.764 - .. versionchanged:: 2.4
454.765 - Formerly, string concatenation never occurred in-place.
454.766 -
454.767 -
454.768 -.. _string-methods:
454.769 -
454.770 -String Methods
454.771 ---------------
454.772 -
454.773 -.. index:: pair: string; methods
454.774 -
454.775 -Below are listed the string methods which both 8-bit strings and Unicode objects
454.776 -support. Note that none of these methods take keyword arguments.
454.777 -
454.778 -In addition, Python's strings support the sequence type methods
454.779 -described in the :ref:`typesseq` section. To output formatted strings
454.780 -use template strings or the ``%`` operator described in the
454.781 -:ref:`string-formatting` section. Also, see the :mod:`re` module for
454.782 -string functions based on regular expressions.
454.783 -
454.784 -.. method:: str.capitalize()
454.785 -
454.786 - Return a copy of the string with only its first character capitalized.
454.787 -
454.788 - For 8-bit strings, this method is locale-dependent.
454.789 -
454.790 -
454.791 -.. method:: str.center(width[, fillchar])
454.792 -
454.793 - Return centered in a string of length *width*. Padding is done using the
454.794 - specified *fillchar* (default is a space).
454.795 -
454.796 - .. versionchanged:: 2.4
454.797 - Support for the *fillchar* argument.
454.798 -
454.799 -
454.800 -.. method:: str.count(sub[, start[, end]])
454.801 -
454.802 - Return the number of occurrences of substring *sub* in the range [*start*,
454.803 - *end*]. Optional arguments *start* and *end* are interpreted as in slice
454.804 - notation.
454.805 -
454.806 -
454.807 -.. method:: str.decode([encoding[, errors]])
454.808 -
454.809 - Decodes the string using the codec registered for *encoding*. *encoding*
454.810 - defaults to the default string encoding. *errors* may be given to set a
454.811 - different error handling scheme. The default is ``'strict'``, meaning that
454.812 - encoding errors raise :exc:`UnicodeError`. Other possible values are
454.813 - ``'ignore'``, ``'replace'`` and any other name registered via
454.814 - :func:`codecs.register_error`, see section :ref:`codec-base-classes`.
454.815 -
454.816 - .. versionadded:: 2.2
454.817 -
454.818 - .. versionchanged:: 2.3
454.819 - Support for other error handling schemes added.
454.820 -
454.821 -
454.822 -.. method:: str.encode([encoding[,errors]])
454.823 -
454.824 - Return an encoded version of the string. Default encoding is the current
454.825 - default string encoding. *errors* may be given to set a different error
454.826 - handling scheme. The default for *errors* is ``'strict'``, meaning that
454.827 - encoding errors raise a :exc:`UnicodeError`. Other possible values are
454.828 - ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, ``'backslashreplace'`` and
454.829 - any other name registered via :func:`codecs.register_error`, see section
454.830 - :ref:`codec-base-classes`. For a list of possible encodings, see section
454.831 - :ref:`standard-encodings`.
454.832 -
454.833 - .. versionadded:: 2.0
454.834 -
454.835 - .. versionchanged:: 2.3
454.836 - Support for ``'xmlcharrefreplace'`` and ``'backslashreplace'`` and other error
454.837 - handling schemes added.
454.838 -
454.839 -
454.840 -.. method:: str.endswith(suffix[, start[, end]])
454.841 -
454.842 - Return ``True`` if the string ends with the specified *suffix*, otherwise return
454.843 - ``False``. *suffix* can also be a tuple of suffixes to look for. With optional
454.844 - *start*, test beginning at that position. With optional *end*, stop comparing
454.845 - at that position.
454.846 -
454.847 - .. versionchanged:: 2.5
454.848 - Accept tuples as *suffix*.
454.849 -
454.850 -
454.851 -.. method:: str.expandtabs([tabsize])
454.852 -
454.853 - Return a copy of the string where all tab characters are replaced by one or
454.854 - more spaces, depending on the current column and the given tab size. The
454.855 - column number is reset to zero after each newline occurring in the string.
454.856 - If *tabsize* is not given, a tab size of ``8`` characters is assumed. This
454.857 - doesn't understand other non-printing characters or escape sequences.
454.858 -
454.859 -
454.860 -.. method:: str.find(sub[, start[, end]])
454.861 -
454.862 - Return the lowest index in the string where substring *sub* is found, such that
454.863 - *sub* is contained in the range [*start*, *end*]. Optional arguments *start*
454.864 - and *end* are interpreted as in slice notation. Return ``-1`` if *sub* is not
454.865 - found.
454.866 -
454.867 -
454.868 -.. method:: str.format(format_string, *args, **kwargs)
454.869 -
454.870 - Perform a string formatting operation. The *format_string* argument can
454.871 - contain literal text or replacement fields delimited by braces ``{}``. Each
454.872 - replacement field contains either the numeric index of a positional argument,
454.873 - or the name of a keyword argument. Returns a copy of *format_string* where
454.874 - each replacement field is replaced with the string value of the corresponding
454.875 - argument.
454.876 -
454.877 - >>> "The sum of 1 + 2 is {0}".format(1+2)
454.878 - 'The sum of 1 + 2 is 3'
454.879 -
454.880 - See :ref:`formatstrings` for a description of the various formatting options
454.881 - that can be specified in format strings.
454.882 -
454.883 - This method of string formatting is the new standard in Python 3.0, and
454.884 - should be preferred to the ``%`` formatting described in
454.885 - :ref:`string-formatting` in new code.
454.886 -
454.887 - .. versionadded:: 2.6
454.888 -
454.889 -
454.890 -.. method:: str.index(sub[, start[, end]])
454.891 -
454.892 - Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found.
454.893 -
454.894 -
454.895 -.. method:: str.isalnum()
454.896 -
454.897 - Return true if all characters in the string are alphanumeric and there is at
454.898 - least one character, false otherwise.
454.899 -
454.900 - For 8-bit strings, this method is locale-dependent.
454.901 -
454.902 -
454.903 -.. method:: str.isalpha()
454.904 -
454.905 - Return true if all characters in the string are alphabetic and there is at least
454.906 - one character, false otherwise.
454.907 -
454.908 - For 8-bit strings, this method is locale-dependent.
454.909 -
454.910 -
454.911 -.. method:: str.isdigit()
454.912 -
454.913 - Return true if all characters in the string are digits and there is at least one
454.914 - character, false otherwise.
454.915 -
454.916 - For 8-bit strings, this method is locale-dependent.
454.917 -
454.918 -
454.919 -.. method:: str.islower()
454.920 -
454.921 - Return true if all cased characters in the string are lowercase and there is at
454.922 - least one cased character, false otherwise.
454.923 -
454.924 - For 8-bit strings, this method is locale-dependent.
454.925 -
454.926 -
454.927 -.. method:: str.isspace()
454.928 -
454.929 - Return true if there are only whitespace characters in the string and there is
454.930 - at least one character, false otherwise.
454.931 -
454.932 - For 8-bit strings, this method is locale-dependent.
454.933 -
454.934 -
454.935 -.. method:: str.istitle()
454.936 -
454.937 - Return true if the string is a titlecased string and there is at least one
454.938 - character, for example uppercase characters may only follow uncased characters
454.939 - and lowercase characters only cased ones. Return false otherwise.
454.940 -
454.941 - For 8-bit strings, this method is locale-dependent.
454.942 -
454.943 -
454.944 -.. method:: str.isupper()
454.945 -
454.946 - Return true if all cased characters in the string are uppercase and there is at
454.947 - least one cased character, false otherwise.
454.948 -
454.949 - For 8-bit strings, this method is locale-dependent.
454.950 -
454.951 -
454.952 -.. method:: str.join(seq)
454.953 -
454.954 - Return a string which is the concatenation of the strings in the sequence *seq*.
454.955 - The separator between elements is the string providing this method.
454.956 -
454.957 -
454.958 -.. method:: str.ljust(width[, fillchar])
454.959 -
454.960 - Return the string left justified in a string of length *width*. Padding is done
454.961 - using the specified *fillchar* (default is a space). The original string is
454.962 - returned if *width* is less than ``len(s)``.
454.963 -
454.964 - .. versionchanged:: 2.4
454.965 - Support for the *fillchar* argument.
454.966 -
454.967 -
454.968 -.. method:: str.lower()
454.969 -
454.970 - Return a copy of the string converted to lowercase.
454.971 -
454.972 - For 8-bit strings, this method is locale-dependent.
454.973 -
454.974 -
454.975 -.. method:: str.lstrip([chars])
454.976 -
454.977 - Return a copy of the string with leading characters removed. The *chars*
454.978 - argument is a string specifying the set of characters to be removed. If omitted
454.979 - or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
454.980 - argument is not a prefix; rather, all combinations of its values are stripped:
454.981 -
454.982 - >>> ' spacious '.lstrip()
454.983 - 'spacious '
454.984 - >>> 'www.example.com'.lstrip('cmowz.')
454.985 - 'example.com'
454.986 -
454.987 - .. versionchanged:: 2.2.2
454.988 - Support for the *chars* argument.
454.989 -
454.990 -
454.991 -.. method:: str.partition(sep)
454.992 -
454.993 - Split the string at the first occurrence of *sep*, and return a 3-tuple
454.994 - containing the part before the separator, the separator itself, and the part
454.995 - after the separator. If the separator is not found, return a 3-tuple containing
454.996 - the string itself, followed by two empty strings.
454.997 -
454.998 - .. versionadded:: 2.5
454.999 -
454.1000 -
454.1001 -.. method:: str.replace(old, new[, count])
454.1002 -
454.1003 - Return a copy of the string with all occurrences of substring *old* replaced by
454.1004 - *new*. If the optional argument *count* is given, only the first *count*
454.1005 - occurrences are replaced.
454.1006 -
454.1007 -
454.1008 -.. method:: str.rfind(sub [,start [,end]])
454.1009 -
454.1010 - Return the highest index in the string where substring *sub* is found, such that
454.1011 - *sub* is contained within s[start,end]. Optional arguments *start* and *end*
454.1012 - are interpreted as in slice notation. Return ``-1`` on failure.
454.1013 -
454.1014 -
454.1015 -.. method:: str.rindex(sub[, start[, end]])
454.1016 -
454.1017 - Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
454.1018 - found.
454.1019 -
454.1020 -
454.1021 -.. method:: str.rjust(width[, fillchar])
454.1022 -
454.1023 - Return the string right justified in a string of length *width*. Padding is done
454.1024 - using the specified *fillchar* (default is a space). The original string is
454.1025 - returned if *width* is less than ``len(s)``.
454.1026 -
454.1027 - .. versionchanged:: 2.4
454.1028 - Support for the *fillchar* argument.
454.1029 -
454.1030 -
454.1031 -.. method:: str.rpartition(sep)
454.1032 -
454.1033 - Split the string at the last occurrence of *sep*, and return a 3-tuple
454.1034 - containing the part before the separator, the separator itself, and the part
454.1035 - after the separator. If the separator is not found, return a 3-tuple containing
454.1036 - two empty strings, followed by the string itself.
454.1037 -
454.1038 - .. versionadded:: 2.5
454.1039 -
454.1040 -
454.1041 -.. method:: str.rsplit([sep [,maxsplit]])
454.1042 -
454.1043 - Return a list of the words in the string, using *sep* as the delimiter string.
454.1044 - If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
454.1045 - ones. If *sep* is not specified or ``None``, any whitespace string is a
454.1046 - separator. Except for splitting from the right, :meth:`rsplit` behaves like
454.1047 - :meth:`split` which is described in detail below.
454.1048 -
454.1049 - .. versionadded:: 2.4
454.1050 -
454.1051 -
454.1052 -.. method:: str.rstrip([chars])
454.1053 -
454.1054 - Return a copy of the string with trailing characters removed. The *chars*
454.1055 - argument is a string specifying the set of characters to be removed. If omitted
454.1056 - or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
454.1057 - argument is not a suffix; rather, all combinations of its values are stripped:
454.1058 -
454.1059 - >>> ' spacious '.rstrip()
454.1060 - ' spacious'
454.1061 - >>> 'mississippi'.rstrip('ipz')
454.1062 - 'mississ'
454.1063 -
454.1064 - .. versionchanged:: 2.2.2
454.1065 - Support for the *chars* argument.
454.1066 -
454.1067 -
454.1068 -.. method:: str.split([sep[, maxsplit]])
454.1069 -
454.1070 - Return a list of the words in the string, using *sep* as the delimiter
454.1071 - string. If *maxsplit* is given, at most *maxsplit* splits are done (thus,
454.1072 - the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not
454.1073 - specified, then there is no limit on the number of splits (all possible
454.1074 - splits are made).
454.1075 -
454.1076 - If *sep* is given, consecutive delimiters are not grouped together and are
454.1077 - deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns
454.1078 - ``['1', '', '2']``). The *sep* argument may consist of multiple characters
454.1079 - (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``).
454.1080 - Splitting an empty string with a specified separator returns ``['']``.
454.1081 -
454.1082 - If *sep* is not specified or is ``None``, a different splitting algorithm is
454.1083 - applied: runs of consecutive whitespace are regarded as a single separator,
454.1084 - and the result will contain no empty strings at the start or end if the
454.1085 - string has leading or trailing whitespace. Consequently, splitting an empty
454.1086 - string or a string consisting of just whitespace with a ``None`` separator
454.1087 - returns ``[]``.
454.1088 -
454.1089 - For example, ``' 1 2 3 '.split()`` returns ``['1', '2', '3']``, and
454.1090 - ``' 1 2 3 '.split(None, 1)`` returns ``['1', '2 3 ']``.
454.1091 -
454.1092 -
454.1093 -.. method:: str.splitlines([keepends])
454.1094 -
454.1095 - Return a list of the lines in the string, breaking at line boundaries. Line
454.1096 - breaks are not included in the resulting list unless *keepends* is given and
454.1097 - true.
454.1098 -
454.1099 -
454.1100 -.. method:: str.startswith(prefix[, start[, end]])
454.1101 -
454.1102 - Return ``True`` if string starts with the *prefix*, otherwise return ``False``.
454.1103 - *prefix* can also be a tuple of prefixes to look for. With optional *start*,
454.1104 - test string beginning at that position. With optional *end*, stop comparing
454.1105 - string at that position.
454.1106 -
454.1107 - .. versionchanged:: 2.5
454.1108 - Accept tuples as *prefix*.
454.1109 -
454.1110 -
454.1111 -.. method:: str.strip([chars])
454.1112 -
454.1113 - Return a copy of the string with the leading and trailing characters removed.
454.1114 - The *chars* argument is a string specifying the set of characters to be removed.
454.1115 - If omitted or ``None``, the *chars* argument defaults to removing whitespace.
454.1116 - The *chars* argument is not a prefix or suffix; rather, all combinations of its
454.1117 - values are stripped:
454.1118 -
454.1119 - >>> ' spacious '.strip()
454.1120 - 'spacious'
454.1121 - >>> 'www.example.com'.strip('cmowz.')
454.1122 - 'example'
454.1123 -
454.1124 - .. versionchanged:: 2.2.2
454.1125 - Support for the *chars* argument.
454.1126 -
454.1127 -
454.1128 -.. method:: str.swapcase()
454.1129 -
454.1130 - Return a copy of the string with uppercase characters converted to lowercase and
454.1131 - vice versa.
454.1132 -
454.1133 - For 8-bit strings, this method is locale-dependent.
454.1134 -
454.1135 -
454.1136 -.. method:: str.title()
454.1137 -
454.1138 - Return a titlecased version of the string: words start with uppercase
454.1139 - characters, all remaining cased characters are lowercase.
454.1140 -
454.1141 - For 8-bit strings, this method is locale-dependent.
454.1142 -
454.1143 -
454.1144 -.. method:: str.translate(table[, deletechars])
454.1145 -
454.1146 - Return a copy of the string where all characters occurring in the optional
454.1147 - argument *deletechars* are removed, and the remaining characters have been
454.1148 - mapped through the given translation table, which must be a string of length
454.1149 - 256.
454.1150 -
454.1151 - You can use the :func:`maketrans` helper function in the :mod:`string` module to
454.1152 - create a translation table. For string objects, set the *table* argument to
454.1153 - ``None`` for translations that only delete characters:
454.1154 -
454.1155 - >>> 'read this short text'.translate(None, 'aeiou')
454.1156 - 'rd ths shrt txt'
454.1157 -
454.1158 - .. versionadded:: 2.6
454.1159 - Support for a ``None`` *table* argument.
454.1160 -
454.1161 - For Unicode objects, the :meth:`translate` method does not accept the optional
454.1162 - *deletechars* argument. Instead, it returns a copy of the *s* where all
454.1163 - characters have been mapped through the given translation table which must be a
454.1164 - mapping of Unicode ordinals to Unicode ordinals, Unicode strings or ``None``.
454.1165 - Unmapped characters are left untouched. Characters mapped to ``None`` are
454.1166 - deleted. Note, a more flexible approach is to create a custom character mapping
454.1167 - codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an
454.1168 - example).
454.1169 -
454.1170 -
454.1171 -.. method:: str.upper()
454.1172 -
454.1173 - Return a copy of the string converted to uppercase.
454.1174 -
454.1175 - For 8-bit strings, this method is locale-dependent.
454.1176 -
454.1177 -
454.1178 -.. method:: str.zfill(width)
454.1179 -
454.1180 - Return the numeric string left filled with zeros in a string of length
454.1181 - *width*. A sign prefix is handled correctly. The original string is
454.1182 - returned if *width* is less than ``len(s)``.
454.1183 -
454.1184 -
454.1185 - .. versionadded:: 2.2.2
454.1186 -
454.1187 -The following methods are present only on unicode objects:
454.1188 -
454.1189 -.. method:: unicode.isnumeric()
454.1190 -
454.1191 - Return ``True`` if there are only numeric characters in S, ``False``
454.1192 - otherwise. Numeric characters include digit characters, and all characters
454.1193 - that have the Unicode numeric value property, e.g. U+2155,
454.1194 - VULGAR FRACTION ONE FIFTH.
454.1195 -
454.1196 -.. method:: unicode.isdecimal()
454.1197 -
454.1198 - Return ``True`` if there are only decimal characters in S, ``False``
454.1199 - otherwise. Decimal characters include digit characters, and all characters
454.1200 - that that can be used to form decimal-radix numbers, e.g. U+0660,
454.1201 - ARABIC-INDIC DIGIT ZERO.
454.1202 -
454.1203 -
454.1204 -.. _string-formatting:
454.1205 -
454.1206 -String Formatting Operations
454.1207 -----------------------------
454.1208 -
454.1209 -.. index::
454.1210 - single: formatting, string (%)
454.1211 - single: interpolation, string (%)
454.1212 - single: string; formatting
454.1213 - single: string; interpolation
454.1214 - single: printf-style formatting
454.1215 - single: sprintf-style formatting
454.1216 - single: % formatting
454.1217 - single: % interpolation
454.1218 -
454.1219 -String and Unicode objects have one unique built-in operation: the ``%``
454.1220 -operator (modulo). This is also known as the string *formatting* or
454.1221 -*interpolation* operator. Given ``format % values`` (where *format* is a string
454.1222 -or Unicode object), ``%`` conversion specifications in *format* are replaced
454.1223 -with zero or more elements of *values*. The effect is similar to the using
454.1224 -:cfunc:`sprintf` in the C language. If *format* is a Unicode object, or if any
454.1225 -of the objects being converted using the ``%s`` conversion are Unicode objects,
454.1226 -the result will also be a Unicode object.
454.1227 -
454.1228 -If *format* requires a single argument, *values* may be a single non-tuple
454.1229 -object. [#]_ Otherwise, *values* must be a tuple with exactly the number of
454.1230 -items specified by the format string, or a single mapping object (for example, a
454.1231 -dictionary).
454.1232 -
454.1233 -A conversion specifier contains two or more characters and has the following
454.1234 -components, which must occur in this order:
454.1235 -
454.1236 -#. The ``'%'`` character, which marks the start of the specifier.
454.1237 -
454.1238 -#. Mapping key (optional), consisting of a parenthesised sequence of characters
454.1239 - (for example, ``(somename)``).
454.1240 -
454.1241 -#. Conversion flags (optional), which affect the result of some conversion
454.1242 - types.
454.1243 -
454.1244 -#. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the
454.1245 - actual width is read from the next element of the tuple in *values*, and the
454.1246 - object to convert comes after the minimum field width and optional precision.
454.1247 -
454.1248 -#. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If
454.1249 - specified as ``'*'`` (an asterisk), the actual width is read from the next
454.1250 - element of the tuple in *values*, and the value to convert comes after the
454.1251 - precision.
454.1252 -
454.1253 -#. Length modifier (optional).
454.1254 -
454.1255 -#. Conversion type.
454.1256 -
454.1257 -When the right argument is a dictionary (or other mapping type), then the
454.1258 -formats in the string *must* include a parenthesised mapping key into that
454.1259 -dictionary inserted immediately after the ``'%'`` character. The mapping key
454.1260 -selects the value to be formatted from the mapping. For example:
454.1261 -
454.1262 - >>> print '%(language)s has %(#)03d quote types.' % \
454.1263 - ... {'language': "Python", "#": 2}
454.1264 - Python has 002 quote types.
454.1265 -
454.1266 -In this case no ``*`` specifiers may occur in a format (since they require a
454.1267 -sequential parameter list).
454.1268 -
454.1269 -The conversion flag characters are:
454.1270 -
454.1271 -+---------+---------------------------------------------------------------------+
454.1272 -| Flag | Meaning |
454.1273 -+=========+=====================================================================+
454.1274 -| ``'#'`` | The value conversion will use the "alternate form" (where defined |
454.1275 -| | below). |
454.1276 -+---------+---------------------------------------------------------------------+
454.1277 -| ``'0'`` | The conversion will be zero padded for numeric values. |
454.1278 -+---------+---------------------------------------------------------------------+
454.1279 -| ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
454.1280 -| | conversion if both are given). |
454.1281 -+---------+---------------------------------------------------------------------+
454.1282 -| ``' '`` | (a space) A blank should be left before a positive number (or empty |
454.1283 -| | string) produced by a signed conversion. |
454.1284 -+---------+---------------------------------------------------------------------+
454.1285 -| ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
454.1286 -| | (overrides a "space" flag). |
454.1287 -+---------+---------------------------------------------------------------------+
454.1288 -
454.1289 -A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
454.1290 -is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.
454.1291 -
454.1292 -The conversion types are:
454.1293 -
454.1294 -+------------+-----------------------------------------------------+-------+
454.1295 -| Conversion | Meaning | Notes |
454.1296 -+============+=====================================================+=======+
454.1297 -| ``'d'`` | Signed integer decimal. | |
454.1298 -+------------+-----------------------------------------------------+-------+
454.1299 -| ``'i'`` | Signed integer decimal. | |
454.1300 -+------------+-----------------------------------------------------+-------+
454.1301 -| ``'o'`` | Signed octal value. | \(1) |
454.1302 -+------------+-----------------------------------------------------+-------+
454.1303 -| ``'u'`` | Obselete type -- it is identical to ``'d'``. | \(7) |
454.1304 -+------------+-----------------------------------------------------+-------+
454.1305 -| ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
454.1306 -+------------+-----------------------------------------------------+-------+
454.1307 -| ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
454.1308 -+------------+-----------------------------------------------------+-------+
454.1309 -| ``'e'`` | Floating point exponential format (lowercase). | \(3) |
454.1310 -+------------+-----------------------------------------------------+-------+
454.1311 -| ``'E'`` | Floating point exponential format (uppercase). | \(3) |
454.1312 -+------------+-----------------------------------------------------+-------+
454.1313 -| ``'f'`` | Floating point decimal format. | \(3) |
454.1314 -+------------+-----------------------------------------------------+-------+
454.1315 -| ``'F'`` | Floating point decimal format. | \(3) |
454.1316 -+------------+-----------------------------------------------------+-------+
454.1317 -| ``'g'`` | Floating point format. Uses lowercase exponential | \(4) |
454.1318 -| | format if exponent is less than -4 or not less than | |
454.1319 -| | precision, decimal format otherwise. | |
454.1320 -+------------+-----------------------------------------------------+-------+
454.1321 -| ``'G'`` | Floating point format. Uses uppercase exponential | \(4) |
454.1322 -| | format if exponent is less than -4 or not less than | |
454.1323 -| | precision, decimal format otherwise. | |
454.1324 -+------------+-----------------------------------------------------+-------+
454.1325 -| ``'c'`` | Single character (accepts integer or single | |
454.1326 -| | character string). | |
454.1327 -+------------+-----------------------------------------------------+-------+
454.1328 -| ``'r'`` | String (converts any python object using | \(5) |
454.1329 -| | :func:`repr`). | |
454.1330 -+------------+-----------------------------------------------------+-------+
454.1331 -| ``'s'`` | String (converts any python object using | \(6) |
454.1332 -| | :func:`str`). | |
454.1333 -+------------+-----------------------------------------------------+-------+
454.1334 -| ``'%'`` | No argument is converted, results in a ``'%'`` | |
454.1335 -| | character in the result. | |
454.1336 -+------------+-----------------------------------------------------+-------+
454.1337 -
454.1338 -Notes:
454.1339 -
454.1340 -(1)
454.1341 - The alternate form causes a leading zero (``'0'``) to be inserted between
454.1342 - left-hand padding and the formatting of the number if the leading character
454.1343 - of the result is not already a zero.
454.1344 -
454.1345 -(2)
454.1346 - The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
454.1347 - the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding
454.1348 - and the formatting of the number if the leading character of the result is not
454.1349 - already a zero.
454.1350 -
454.1351 -(3)
454.1352 - The alternate form causes the result to always contain a decimal point, even if
454.1353 - no digits follow it.
454.1354 -
454.1355 - The precision determines the number of digits after the decimal point and
454.1356 - defaults to 6.
454.1357 -
454.1358 -(4)
454.1359 - The alternate form causes the result to always contain a decimal point, and
454.1360 - trailing zeroes are not removed as they would otherwise be.
454.1361 -
454.1362 - The precision determines the number of significant digits before and after the
454.1363 - decimal point and defaults to 6.
454.1364 -
454.1365 -(5)
454.1366 - The ``%r`` conversion was added in Python 2.0.
454.1367 -
454.1368 - The precision determines the maximal number of characters used.
454.1369 -
454.1370 -(6)
454.1371 - If the object or format provided is a :class:`unicode` string, the resulting
454.1372 - string will also be :class:`unicode`.
454.1373 -
454.1374 - The precision determines the maximal number of characters used.
454.1375 -
454.1376 -(7)
454.1377 - See :pep:`237`.
454.1378 -
454.1379 -Since Python strings have an explicit length, ``%s`` conversions do not assume
454.1380 -that ``'\0'`` is the end of the string.
454.1381 -
454.1382 -.. XXX Examples?
454.1383 -
454.1384 -For safety reasons, floating point precisions are clipped to 50; ``%f``
454.1385 -conversions for numbers whose absolute value is over 1e25 are replaced by ``%g``
454.1386 -conversions. [#]_ All other errors raise exceptions.
454.1387 -
454.1388 -.. index::
454.1389 - module: string
454.1390 - module: re
454.1391 -
454.1392 -Additional string operations are defined in standard modules :mod:`string` and
454.1393 -:mod:`re`.
454.1394 -
454.1395 -
454.1396 -.. _typesseq-xrange:
454.1397 -
454.1398 -XRange Type
454.1399 ------------
454.1400 -
454.1401 -.. index:: object: xrange
454.1402 -
454.1403 -The :class:`xrange` type is an immutable sequence which is commonly used for
454.1404 -looping. The advantage of the :class:`xrange` type is that an :class:`xrange`
454.1405 -object will always take the same amount of memory, no matter the size of the
454.1406 -range it represents. There are no consistent performance advantages.
454.1407 -
454.1408 -XRange objects have very little behavior: they only support indexing, iteration,
454.1409 -and the :func:`len` function.
454.1410 -
454.1411 -
454.1412 -.. _typesseq-mutable:
454.1413 -
454.1414 -Mutable Sequence Types
454.1415 -----------------------
454.1416 -
454.1417 -.. index::
454.1418 - triple: mutable; sequence; types
454.1419 - object: list
454.1420 -
454.1421 -List objects support additional operations that allow in-place modification of
454.1422 -the object. Other mutable sequence types (when added to the language) should
454.1423 -also support these operations. Strings and tuples are immutable sequence types:
454.1424 -such objects cannot be modified once created. The following operations are
454.1425 -defined on mutable sequence types (where *x* is an arbitrary object):
454.1426 -
454.1427 -+------------------------------+--------------------------------+---------------------+
454.1428 -| Operation | Result | Notes |
454.1429 -+==============================+================================+=====================+
454.1430 -| ``s[i] = x`` | item *i* of *s* is replaced by | |
454.1431 -| | *x* | |
454.1432 -+------------------------------+--------------------------------+---------------------+
454.1433 -| ``s[i:j] = t`` | slice of *s* from *i* to *j* | |
454.1434 -| | is replaced by the contents of | |
454.1435 -| | the iterable *t* | |
454.1436 -+------------------------------+--------------------------------+---------------------+
454.1437 -| ``del s[i:j]`` | same as ``s[i:j] = []`` | |
454.1438 -+------------------------------+--------------------------------+---------------------+
454.1439 -| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) |
454.1440 -| | are replaced by those of *t* | |
454.1441 -+------------------------------+--------------------------------+---------------------+
454.1442 -| ``del s[i:j:k]`` | removes the elements of | |
454.1443 -| | ``s[i:j:k]`` from the list | |
454.1444 -+------------------------------+--------------------------------+---------------------+
454.1445 -| ``s.append(x)`` | same as ``s[len(s):len(s)] = | \(2) |
454.1446 -| | [x]`` | |
454.1447 -+------------------------------+--------------------------------+---------------------+
454.1448 -| ``s.extend(x)`` | same as ``s[len(s):len(s)] = | \(3) |
454.1449 -| | x`` | |
454.1450 -+------------------------------+--------------------------------+---------------------+
454.1451 -| ``s.count(x)`` | return number of *i*'s for | |
454.1452 -| | which ``s[i] == x`` | |
454.1453 -+------------------------------+--------------------------------+---------------------+
454.1454 -| ``s.index(x[, i[, j]])`` | return smallest *k* such that | \(4) |
454.1455 -| | ``s[k] == x`` and ``i <= k < | |
454.1456 -| | j`` | |
454.1457 -+------------------------------+--------------------------------+---------------------+
454.1458 -| ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | \(5) |
454.1459 -+------------------------------+--------------------------------+---------------------+
454.1460 -| ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(6) |
454.1461 -| | return x`` | |
454.1462 -+------------------------------+--------------------------------+---------------------+
454.1463 -| ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(4) |
454.1464 -+------------------------------+--------------------------------+---------------------+
454.1465 -| ``s.reverse()`` | reverses the items of *s* in | \(7) |
454.1466 -| | place | |
454.1467 -+------------------------------+--------------------------------+---------------------+
454.1468 -| ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |
454.1469 -| reverse]]])`` | | |
454.1470 -+------------------------------+--------------------------------+---------------------+
454.1471 -
454.1472 -.. index::
454.1473 - triple: operations on; sequence; types
454.1474 - triple: operations on; list; type
454.1475 - pair: subscript; assignment
454.1476 - pair: slice; assignment
454.1477 - pair: extended slice; assignment
454.1478 - statement: del
454.1479 - single: append() (list method)
454.1480 - single: extend() (list method)
454.1481 - single: count() (list method)
454.1482 - single: index() (list method)
454.1483 - single: insert() (list method)
454.1484 - single: pop() (list method)
454.1485 - single: remove() (list method)
454.1486 - single: reverse() (list method)
454.1487 - single: sort() (list method)
454.1488 -
454.1489 -Notes:
454.1490 -
454.1491 -(1)
454.1492 - *t* must have the same length as the slice it is replacing.
454.1493 -
454.1494 -(2)
454.1495 - The C implementation of Python has historically accepted multiple parameters and
454.1496 - implicitly joined them into a tuple; this no longer works in Python 2.0. Use of
454.1497 - this misfeature has been deprecated since Python 1.4.
454.1498 -
454.1499 -(3)
454.1500 - *x* can be any iterable object.
454.1501 -
454.1502 -(4)
454.1503 - Raises :exc:`ValueError` when *x* is not found in *s*. When a negative index is
454.1504 - passed as the second or third parameter to the :meth:`index` method, the list
454.1505 - length is added, as for slice indices. If it is still negative, it is truncated
454.1506 - to zero, as for slice indices.
454.1507 -
454.1508 - .. versionchanged:: 2.3
454.1509 - Previously, :meth:`index` didn't have arguments for specifying start and stop
454.1510 - positions.
454.1511 -
454.1512 -(5)
454.1513 - When a negative index is passed as the first parameter to the :meth:`insert`
454.1514 - method, the list length is added, as for slice indices. If it is still
454.1515 - negative, it is truncated to zero, as for slice indices.
454.1516 -
454.1517 - .. versionchanged:: 2.3
454.1518 - Previously, all negative indices were truncated to zero.
454.1519 -
454.1520 -(6)
454.1521 - The :meth:`pop` method is only supported by the list and array types. The
454.1522 - optional argument *i* defaults to ``-1``, so that by default the last item is
454.1523 - removed and returned.
454.1524 -
454.1525 -(7)
454.1526 - The :meth:`sort` and :meth:`reverse` methods modify the list in place for
454.1527 - economy of space when sorting or reversing a large list. To remind you that
454.1528 - they operate by side effect, they don't return the sorted or reversed list.
454.1529 -
454.1530 -(8)
454.1531 - The :meth:`sort` method takes optional arguments for controlling the
454.1532 - comparisons.
454.1533 -
454.1534 - *cmp* specifies a custom comparison function of two arguments (list items) which
454.1535 - should return a negative, zero or positive number depending on whether the first
454.1536 - argument is considered smaller than, equal to, or larger than the second
454.1537 - argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``. The default value
454.1538 - is ``None``.
454.1539 -
454.1540 - *key* specifies a function of one argument that is used to extract a comparison
454.1541 - key from each list element: ``key=str.lower``. The default value is ``None``.
454.1542 -
454.1543 - *reverse* is a boolean value. If set to ``True``, then the list elements are
454.1544 - sorted as if each comparison were reversed.
454.1545 -
454.1546 - In general, the *key* and *reverse* conversion processes are much faster than
454.1547 - specifying an equivalent *cmp* function. This is because *cmp* is called
454.1548 - multiple times for each list element while *key* and *reverse* touch each
454.1549 - element only once.
454.1550 -
454.1551 - .. versionchanged:: 2.3
454.1552 - Support for ``None`` as an equivalent to omitting *cmp* was added.
454.1553 -
454.1554 - .. versionchanged:: 2.4
454.1555 - Support for *key* and *reverse* was added.
454.1556 -
454.1557 -(9)
454.1558 - Starting with Python 2.3, the :meth:`sort` method is guaranteed to be stable. A
454.1559 - sort is stable if it guarantees not to change the relative order of elements
454.1560 - that compare equal --- this is helpful for sorting in multiple passes (for
454.1561 - example, sort by department, then by salary grade).
454.1562 -
454.1563 -(10)
454.1564 - While a list is being sorted, the effect of attempting to mutate, or even
454.1565 - inspect, the list is undefined. The C implementation of Python 2.3 and newer
454.1566 - makes the list appear empty for the duration, and raises :exc:`ValueError` if it
454.1567 - can detect that the list has been mutated during a sort.
454.1568 -
454.1569 -
454.1570 -.. _types-set:
454.1571 -
454.1572 -Set Types --- :class:`set`, :class:`frozenset`
454.1573 -==============================================
454.1574 -
454.1575 -.. index:: object: set
454.1576 -
454.1577 -A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects.
454.1578 -Common uses include membership testing, removing duplicates from a sequence, and
454.1579 -computing mathematical operations such as intersection, union, difference, and
454.1580 -symmetric difference.
454.1581 -(For other containers see the built in :class:`dict`, :class:`list`,
454.1582 -and :class:`tuple` classes, and the :mod:`collections` module.)
454.1583 -
454.1584 -
454.1585 -.. versionadded:: 2.4
454.1586 -
454.1587 -Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
454.1588 -set``. Being an unordered collection, sets do not record element position or
454.1589 -order of insertion. Accordingly, sets do not support indexing, slicing, or
454.1590 -other sequence-like behavior.
454.1591 -
454.1592 -There are currently two builtin set types, :class:`set` and :class:`frozenset`.
454.1593 -The :class:`set` type is mutable --- the contents can be changed using methods
454.1594 -like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value
454.1595 -and cannot be used as either a dictionary key or as an element of another set.
454.1596 -The :class:`frozenset` type is immutable and :term:`hashable` --- its contents cannot be
454.1597 -altered after it is created; it can therefore be used as a dictionary key or as
454.1598 -an element of another set.
454.1599 -
454.1600 -The constructors for both classes work the same:
454.1601 -
454.1602 -.. class:: set([iterable])
454.1603 - frozenset([iterable])
454.1604 -
454.1605 - Return a new set or frozenset object whose elements are taken from
454.1606 - *iterable*. The elements of a set must be hashable. To represent sets of
454.1607 - sets, the inner sets must be :class:`frozenset` objects. If *iterable* is
454.1608 - not specified, a new empty set is returned.
454.1609 -
454.1610 - Instances of :class:`set` and :class:`frozenset` provide the following
454.1611 - operations:
454.1612 -
454.1613 - .. describe:: len(s)
454.1614 -
454.1615 - Return the cardinality of set *s*.
454.1616 -
454.1617 - .. describe:: x in s
454.1618 -
454.1619 - Test *x* for membership in *s*.
454.1620 -
454.1621 - .. describe:: x not in s
454.1622 -
454.1623 - Test *x* for non-membership in *s*.
454.1624 -
454.1625 - .. method:: isdisjoint(other)
454.1626 -
454.1627 - Return True if the set has no elements in common with *other*. Sets are
454.1628 - disjoint if and only if their intersection is the empty set.
454.1629 -
454.1630 - .. versionadded:: 2.6
454.1631 -
454.1632 - .. method:: issubset(other)
454.1633 - set <= other
454.1634 -
454.1635 - Test whether every element in the set is in *other*.
454.1636 -
454.1637 - .. method:: set < other
454.1638 -
454.1639 - Test whether the set is a true subset of *other*, that is,
454.1640 - ``set <= other and set != other``.
454.1641 -
454.1642 - .. method:: issuperset(other)
454.1643 - set >= other
454.1644 -
454.1645 - Test whether every element in *other* is in the set.
454.1646 -
454.1647 - .. method:: set > other
454.1648 -
454.1649 - Test whether the set is a true superset of *other*, that is, ``set >=
454.1650 - other and set != other``.
454.1651 -
454.1652 - .. method:: union(other, ...)
454.1653 - set | other | ...
454.1654 -
454.1655 - Return a new set with elements from both sets.
454.1656 -
454.1657 - .. versionchanged:: 2.6
454.1658 - Accepts multiple input iterables.
454.1659 -
454.1660 - .. method:: intersection(other, ...)
454.1661 - set & other & ...
454.1662 -
454.1663 - Return a new set with elements common to both sets.
454.1664 -
454.1665 - .. versionchanged:: 2.6
454.1666 - Accepts multiple input iterables.
454.1667 -
454.1668 - .. method:: difference(other, ...)
454.1669 - set - other - ...
454.1670 -
454.1671 - Return a new set with elements in the set that are not in the others.
454.1672 -
454.1673 - .. versionchanged:: 2.6
454.1674 - Accepts multiple input iterables.
454.1675 -
454.1676 - .. method:: symmetric_difference(other)
454.1677 - set ^ other
454.1678 -
454.1679 - Return a new set with elements in either the set or *other* but not both.
454.1680 -
454.1681 - .. method:: copy()
454.1682 -
454.1683 - Return a new set with a shallow copy of *s*.
454.1684 -
454.1685 -
454.1686 - Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
454.1687 - :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and
454.1688 - :meth:`issuperset` methods will accept any iterable as an argument. In
454.1689 - contrast, their operator based counterparts require their arguments to be
454.1690 - sets. This precludes error-prone constructions like ``set('abc') & 'cbs'``
454.1691 - in favor of the more readable ``set('abc').intersection('cbs')``.
454.1692 -
454.1693 - Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
454.1694 - sets are equal if and only if every element of each set is contained in the
454.1695 - other (each is a subset of the other). A set is less than another set if and
454.1696 - only if the first set is a proper subset of the second set (is a subset, but
454.1697 - is not equal). A set is greater than another set if and only if the first set
454.1698 - is a proper superset of the second set (is a superset, but is not equal).
454.1699 -
454.1700 - Instances of :class:`set` are compared to instances of :class:`frozenset`
454.1701 - based on their members. For example, ``set('abc') == frozenset('abc')``
454.1702 - returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
454.1703 -
454.1704 - The subset and equality comparisons do not generalize to a complete ordering
454.1705 - function. For example, any two disjoint sets are not equal and are not
454.1706 - subsets of each other, so *all* of the following return ``False``: ``a<b``,
454.1707 - ``a==b``, or ``a>b``. Accordingly, sets do not implement the :meth:`__cmp__`
454.1708 - method.
454.1709 -
454.1710 - Since sets only define partial ordering (subset relationships), the output of
454.1711 - the :meth:`list.sort` method is undefined for lists of sets.
454.1712 -
454.1713 - Set elements, like dictionary keys, must be :term:`hashable`.
454.1714 -
454.1715 - Binary operations that mix :class:`set` instances with :class:`frozenset`
454.1716 - return the type of the first operand. For example: ``frozenset('ab') |
454.1717 - set('bc')`` returns an instance of :class:`frozenset`.
454.1718 -
454.1719 - The following table lists operations available for :class:`set` that do not
454.1720 - apply to immutable instances of :class:`frozenset`:
454.1721 -
454.1722 - .. method:: update(other, ...)
454.1723 - set |= other | ...
454.1724 -
454.1725 - Update the set, adding elements from *other*.
454.1726 -
454.1727 - .. versionchanged:: 2.6
454.1728 - Accepts multiple input iterables.
454.1729 -
454.1730 - .. method:: intersection_update(other, ...)
454.1731 - set &= other & ...
454.1732 -
454.1733 - Update the set, keeping only elements found in it and *other*.
454.1734 -
454.1735 - .. versionchanged:: 2.6
454.1736 - Accepts multiple input iterables.
454.1737 -
454.1738 - .. method:: difference_update(other, ...)
454.1739 - set -= other | ...
454.1740 -
454.1741 - Update the set, removing elements found in others.
454.1742 -
454.1743 - .. versionchanged:: 2.6
454.1744 - Accepts multiple input iterables.
454.1745 -
454.1746 - .. method:: symmetric_difference_update(other)
454.1747 - set ^= other
454.1748 -
454.1749 - Update the set, keeping only elements found in either set, but not in both.
454.1750 -
454.1751 - .. method:: add(elem)
454.1752 -
454.1753 - Add element *elem* to the set.
454.1754 -
454.1755 - .. method:: remove(elem)
454.1756 -
454.1757 - Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is
454.1758 - not contained in the set.
454.1759 -
454.1760 - .. method:: discard(elem)
454.1761 -
454.1762 - Remove element *elem* from the set if it is present.
454.1763 -
454.1764 - .. method:: pop()
454.1765 -
454.1766 - Remove and return an arbitrary element from the set. Raises
454.1767 - :exc:`KeyError` if the set is empty.
454.1768 -
454.1769 - .. method:: clear()
454.1770 -
454.1771 - Remove all elements from the set.
454.1772 -
454.1773 -
454.1774 - Note, the non-operator versions of the :meth:`update`,
454.1775 - :meth:`intersection_update`, :meth:`difference_update`, and
454.1776 - :meth:`symmetric_difference_update` methods will accept any iterable as an
454.1777 - argument.
454.1778 -
454.1779 - Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and
454.1780 - :meth:`discard` methods may be a set. To support searching for an equivalent
454.1781 - frozenset, the *elem* set is temporarily mutated during the search and then
454.1782 - restored. During the search, the *elem* set should not be read or mutated
454.1783 - since it does not have a meaningful value.
454.1784 -
454.1785 -
454.1786 -.. seealso::
454.1787 -
454.1788 - :ref:`comparison-to-builtin-set`
454.1789 - Differences between the :mod:`sets` module and the built-in set types.
454.1790 -
454.1791 -
454.1792 -.. _typesmapping:
454.1793 -
454.1794 -Mapping Types --- :class:`dict`
454.1795 -===============================
454.1796 -
454.1797 -.. index::
454.1798 - object: mapping
454.1799 - object: dictionary
454.1800 - triple: operations on; mapping; types
454.1801 - triple: operations on; dictionary; type
454.1802 - statement: del
454.1803 - builtin: len
454.1804 -
454.1805 -A :dfn:`mapping` object maps :term:`hashable` values to arbitrary objects.
454.1806 -Mappings are mutable objects. There is currently only one standard mapping
454.1807 -type, the :dfn:`dictionary`. (For other containers see the built in
454.1808 -:class:`list`, :class:`set`, and :class:`tuple` classes, and the
454.1809 -:mod:`collections` module.)
454.1810 -
454.1811 -A dictionary's keys are *almost* arbitrary values. Values that are not
454.1812 -:term:`hashable`, that is, values containing lists, dictionaries or other
454.1813 -mutable types (that are compared by value rather than by object identity) may
454.1814 -not be used as keys. Numeric types used for keys obey the normal rules for
454.1815 -numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``)
454.1816 -then they can be used interchangeably to index the same dictionary entry. (Note
454.1817 -however, that since computers store floating-point numbers as approximations it
454.1818 -is usually unwise to use them as dictionary keys.)
454.1819 -
454.1820 -Dictionaries can be created by placing a comma-separated list of ``key: value``
454.1821 -pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
454.1822 -'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor.
454.1823 -
454.1824 -.. class:: dict([arg])
454.1825 -
454.1826 - Return a new dictionary initialized from an optional positional argument or from
454.1827 - a set of keyword arguments. If no arguments are given, return a new empty
454.1828 - dictionary. If the positional argument *arg* is a mapping object, return a
454.1829 - dictionary mapping the same keys to the same values as does the mapping object.
454.1830 - Otherwise the positional argument must be a sequence, a container that supports
454.1831 - iteration, or an iterator object. The elements of the argument must each also
454.1832 - be of one of those kinds, and each must in turn contain exactly two objects.
454.1833 - The first is used as a key in the new dictionary, and the second as the key's
454.1834 - value. If a given key is seen more than once, the last value associated with it
454.1835 - is retained in the new dictionary.
454.1836 -
454.1837 - If keyword arguments are given, the keywords themselves with their associated
454.1838 - values are added as items to the dictionary. If a key is specified both in the
454.1839 - positional argument and as a keyword argument, the value associated with the
454.1840 - keyword is retained in the dictionary. For example, these all return a
454.1841 - dictionary equal to ``{"one": 2, "two": 3}``:
454.1842 -
454.1843 - * ``dict(one=2, two=3)``
454.1844 -
454.1845 - * ``dict({'one': 2, 'two': 3})``
454.1846 -
454.1847 - * ``dict(zip(('one', 'two'), (2, 3)))``
454.1848 -
454.1849 - * ``dict([['two', 3], ['one', 2]])``
454.1850 -
454.1851 - The first example only works for keys that are valid Python
454.1852 - identifiers; the others work with any valid keys.
454.1853 -
454.1854 - .. versionadded:: 2.2
454.1855 -
454.1856 - .. versionchanged:: 2.3
454.1857 - Support for building a dictionary from keyword arguments added.
454.1858 -
454.1859 -
454.1860 - These are the operations that dictionaries support (and therefore, custom
454.1861 - mapping types should support too):
454.1862 -
454.1863 - .. describe:: len(d)
454.1864 -
454.1865 - Return the number of items in the dictionary *d*.
454.1866 -
454.1867 - .. describe:: d[key]
454.1868 -
454.1869 - Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key*
454.1870 - is not in the map.
454.1871 -
454.1872 - .. versionadded:: 2.5
454.1873 - If a subclass of dict defines a method :meth:`__missing__`, if the key
454.1874 - *key* is not present, the ``d[key]`` operation calls that method with
454.1875 - the key *key* as argument. The ``d[key]`` operation then returns or
454.1876 - raises whatever is returned or raised by the ``__missing__(key)`` call
454.1877 - if the key is not present. No other operations or methods invoke
454.1878 - :meth:`__missing__`. If :meth:`__missing__` is not defined,
454.1879 - :exc:`KeyError` is raised. :meth:`__missing__` must be a method; it
454.1880 - cannot be an instance variable. For an example, see
454.1881 - :class:`collections.defaultdict`.
454.1882 -
454.1883 - .. describe:: d[key] = value
454.1884 -
454.1885 - Set ``d[key]`` to *value*.
454.1886 -
454.1887 - .. describe:: del d[key]
454.1888 -
454.1889 - Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the
454.1890 - map.
454.1891 -
454.1892 - .. describe:: key in d
454.1893 -
454.1894 - Return ``True`` if *d* has a key *key*, else ``False``.
454.1895 -
454.1896 - .. versionadded:: 2.2
454.1897 -
454.1898 - .. describe:: key not in d
454.1899 -
454.1900 - Equivalent to ``not key in d``.
454.1901 -
454.1902 - .. versionadded:: 2.2
454.1903 -
454.1904 - .. method:: clear()
454.1905 -
454.1906 - Remove all items from the dictionary.
454.1907 -
454.1908 - .. method:: copy()
454.1909 -
454.1910 - Return a shallow copy of the dictionary.
454.1911 -
454.1912 - .. method:: fromkeys(seq[, value])
454.1913 -
454.1914 - Create a new dictionary with keys from *seq* and values set to *value*.
454.1915 -
454.1916 - :func:`fromkeys` is a class method that returns a new dictionary. *value*
454.1917 - defaults to ``None``.
454.1918 -
454.1919 - .. versionadded:: 2.3
454.1920 -
454.1921 - .. method:: get(key[, default])
454.1922 -
454.1923 - Return the value for *key* if *key* is in the dictionary, else *default*.
454.1924 - If *default* is not given, it defaults to ``None``, so that this method
454.1925 - never raises a :exc:`KeyError`.
454.1926 -
454.1927 - .. method:: has_key(key)
454.1928 -
454.1929 - ``dict.has_key(key)`` is equivalent to ``key in d``, but deprecated.
454.1930 -
454.1931 - .. method:: items()
454.1932 -
454.1933 - Return a copy of the dictionary's list of ``(key, value)`` pairs.
454.1934 -
454.1935 - .. note::
454.1936 -
454.1937 - Keys and values are listed in an arbitrary order which is non-random,
454.1938 - varies across Python implementations, and depends on the dictionary's
454.1939 - history of insertions and deletions. If :meth:`items`, :meth:`keys`,
454.1940 - :meth:`values`, :meth:`iteritems`, :meth:`iterkeys`, and
454.1941 - :meth:`itervalues` are called with no intervening modifications to the
454.1942 - dictionary, the lists will directly correspond. This allows the
454.1943 - creation of ``(value, key)`` pairs using :func:`zip`: ``pairs =
454.1944 - zip(d.values(), d.keys())``. The same relationship holds for the
454.1945 - :meth:`iterkeys` and :meth:`itervalues` methods: ``pairs =
454.1946 - zip(d.itervalues(), d.iterkeys())`` provides the same value for
454.1947 - ``pairs``. Another way to create the same list is ``pairs = [(v, k) for
454.1948 - (k, v) in d.iteritems()]``.
454.1949 -
454.1950 - .. method:: iteritems()
454.1951 -
454.1952 - Return an iterator over the dictionary's ``(key, value)`` pairs. See the
454.1953 - note for :meth:`dict.items`.
454.1954 -
454.1955 - .. versionadded:: 2.2
454.1956 -
454.1957 - .. method:: iterkeys()
454.1958 -
454.1959 - Return an iterator over the dictionary's keys. See the note for
454.1960 - :meth:`dict.items`.
454.1961 -
454.1962 - .. versionadded:: 2.2
454.1963 -
454.1964 - .. method:: itervalues()
454.1965 -
454.1966 - Return an iterator over the dictionary's values. See the note for
454.1967 - :meth:`dict.items`.
454.1968 -
454.1969 - .. versionadded:: 2.2
454.1970 -
454.1971 - .. method:: keys()
454.1972 -
454.1973 - Return a copy of the dictionary's list of keys. See the note for
454.1974 - :meth:`dict.items`.
454.1975 -
454.1976 - .. method:: pop(key[, default])
454.1977 -
454.1978 - If *key* is in the dictionary, remove it and return its value, else return
454.1979 - *default*. If *default* is not given and *key* is not in the dictionary,
454.1980 - a :exc:`KeyError` is raised.
454.1981 -
454.1982 - .. versionadded:: 2.3
454.1983 -
454.1984 - .. method:: popitem()
454.1985 -
454.1986 - Remove and return an arbitrary ``(key, value)`` pair from the dictionary.
454.1987 -
454.1988 - :func:`popitem` is useful to destructively iterate over a dictionary, as
454.1989 - often used in set algorithms. If the dictionary is empty, calling
454.1990 - :func:`popitem` raises a :exc:`KeyError`.
454.1991 -
454.1992 - .. method:: setdefault(key[, default])
454.1993 -
454.1994 - If *key* is in the dictionary, return its value. If not, insert *key*
454.1995 - with a value of *default* and return *default*. *default* defaults to
454.1996 - ``None``.
454.1997 -
454.1998 - .. method:: update([other])
454.1999 -
454.2000 - Update the dictionary with the key/value pairs from *other*, overwriting
454.2001 - existing keys. Return ``None``.
454.2002 -
454.2003 - :func:`update` accepts either another dictionary object or an iterable of
454.2004 - key/value pairs (as a tuple or other iterable of length two). If keyword
454.2005 - arguments are specified, the dictionary is then is updated with those
454.2006 - key/value pairs: ``d.update(red=1, blue=2)``.
454.2007 -
454.2008 - .. versionchanged:: 2.4
454.2009 - Allowed the argument to be an iterable of key/value pairs and allowed
454.2010 - keyword arguments.
454.2011 -
454.2012 - .. method:: values()
454.2013 -
454.2014 - Return a copy of the dictionary's list of values. See the note for
454.2015 - :meth:`dict.items`.
454.2016 -
454.2017 -
454.2018 -.. _bltin-file-objects:
454.2019 -
454.2020 -File Objects
454.2021 -============
454.2022 -
454.2023 -.. index::
454.2024 - object: file
454.2025 - builtin: file
454.2026 - module: os
454.2027 - module: socket
454.2028 -
454.2029 -File objects are implemented using C's ``stdio`` package and can be
454.2030 -created with the built-in :func:`open` function. File
454.2031 -objects are also returned by some other built-in functions and methods,
454.2032 -such as :func:`os.popen` and :func:`os.fdopen` and the :meth:`makefile`
454.2033 -method of socket objects. Temporary files can be created using the
454.2034 -:mod:`tempfile` module, and high-level file operations such as copying,
454.2035 -moving, and deleting files and directories can be achieved with the
454.2036 -:mod:`shutil` module.
454.2037 -
454.2038 -When a file operation fails for an I/O-related reason, the exception
454.2039 -:exc:`IOError` is raised. This includes situations where the operation is not
454.2040 -defined for some reason, like :meth:`seek` on a tty device or writing a file
454.2041 -opened for reading.
454.2042 -
454.2043 -Files have the following methods:
454.2044 -
454.2045 -
454.2046 -.. method:: file.close()
454.2047 -
454.2048 - Close the file. A closed file cannot be read or written any more. Any operation
454.2049 - which requires that the file be open will raise a :exc:`ValueError` after the
454.2050 - file has been closed. Calling :meth:`close` more than once is allowed.
454.2051 -
454.2052 - As of Python 2.5, you can avoid having to call this method explicitly if you use
454.2053 - the :keyword:`with` statement. For example, the following code will
454.2054 - automatically close *f* when the :keyword:`with` block is exited::
454.2055 -
454.2056 - from __future__ import with_statement # This isn't required in Python 2.6
454.2057 -
454.2058 - with open("hello.txt") as f:
454.2059 - for line in f:
454.2060 - print line
454.2061 -
454.2062 - In older versions of Python, you would have needed to do this to get the same
454.2063 - effect::
454.2064 -
454.2065 - f = open("hello.txt")
454.2066 - try:
454.2067 - for line in f:
454.2068 - print line
454.2069 - finally:
454.2070 - f.close()
454.2071 -
454.2072 - .. note::
454.2073 -
454.2074 - Not all "file-like" types in Python support use as a context manager for the
454.2075 - :keyword:`with` statement. If your code is intended to work with any file-like
454.2076 - object, you can use the function :func:`contextlib.closing` instead of using
454.2077 - the object directly.
454.2078 -
454.2079 -
454.2080 -.. method:: file.flush()
454.2081 -
454.2082 - Flush the internal buffer, like ``stdio``'s :cfunc:`fflush`. This may be a
454.2083 - no-op on some file-like objects.
454.2084 -
454.2085 -
454.2086 -.. method:: file.fileno()
454.2087 -
454.2088 - .. index::
454.2089 - pair: file; descriptor
454.2090 - module: fcntl
454.2091 -
454.2092 - Return the integer "file descriptor" that is used by the underlying
454.2093 - implementation to request I/O operations from the operating system. This can be
454.2094 - useful for other, lower level interfaces that use file descriptors, such as the
454.2095 - :mod:`fcntl` module or :func:`os.read` and friends.
454.2096 -
454.2097 - .. note::
454.2098 -
454.2099 - File-like objects which do not have a real file descriptor should *not* provide
454.2100 - this method!
454.2101 -
454.2102 -
454.2103 -.. method:: file.isatty()
454.2104 -
454.2105 - Return ``True`` if the file is connected to a tty(-like) device, else ``False``.
454.2106 -
454.2107 - .. note::
454.2108 -
454.2109 - If a file-like object is not associated with a real file, this method should
454.2110 - *not* be implemented.
454.2111 -
454.2112 -
454.2113 -.. method:: file.next()
454.2114 -
454.2115 - A file object is its own iterator, for example ``iter(f)`` returns *f* (unless
454.2116 - *f* is closed). When a file is used as an iterator, typically in a
454.2117 - :keyword:`for` loop (for example, ``for line in f: print line``), the
454.2118 - :meth:`next` method is called repeatedly. This method returns the next input
454.2119 - line, or raises :exc:`StopIteration` when EOF is hit when the file is open for
454.2120 - reading (behavior is undefined when the file is open for writing). In order to
454.2121 - make a :keyword:`for` loop the most efficient way of looping over the lines of a
454.2122 - file (a very common operation), the :meth:`next` method uses a hidden read-ahead
454.2123 - buffer. As a consequence of using a read-ahead buffer, combining :meth:`next`
454.2124 - with other file methods (like :meth:`readline`) does not work right. However,
454.2125 - using :meth:`seek` to reposition the file to an absolute position will flush the
454.2126 - read-ahead buffer.
454.2127 -
454.2128 - .. versionadded:: 2.3
454.2129 -
454.2130 -
454.2131 -.. method:: file.read([size])
454.2132 -
454.2133 - Read at most *size* bytes from the file (less if the read hits EOF before
454.2134 - obtaining *size* bytes). If the *size* argument is negative or omitted, read
454.2135 - all data until EOF is reached. The bytes are returned as a string object. An
454.2136 - empty string is returned when EOF is encountered immediately. (For certain
454.2137 - files, like ttys, it makes sense to continue reading after an EOF is hit.) Note
454.2138 - that this method may call the underlying C function :cfunc:`fread` more than
454.2139 - once in an effort to acquire as close to *size* bytes as possible. Also note
454.2140 - that when in non-blocking mode, less data than was requested may be
454.2141 - returned, even if no *size* parameter was given.
454.2142 -
454.2143 - .. note::
454.2144 - This function is simply a wrapper for the underlying
454.2145 - :cfunc:`fread` C function, and will behave the same in corner cases,
454.2146 - such as whether the EOF value is cached.
454.2147 -
454.2148 -
454.2149 -.. method:: file.readline([size])
454.2150 -
454.2151 - Read one entire line from the file. A trailing newline character is kept in the
454.2152 - string (but may be absent when a file ends with an incomplete line). [#]_ If
454.2153 - the *size* argument is present and non-negative, it is a maximum byte count
454.2154 - (including the trailing newline) and an incomplete line may be returned. An
454.2155 - empty string is returned *only* when EOF is encountered immediately.
454.2156 -
454.2157 - .. note::
454.2158 -
454.2159 - Unlike ``stdio``'s :cfunc:`fgets`, the returned string contains null characters
454.2160 - (``'\0'``) if they occurred in the input.
454.2161 -
454.2162 -
454.2163 -.. method:: file.readlines([sizehint])
454.2164 -
454.2165 - Read until EOF using :meth:`readline` and return a list containing the lines
454.2166 - thus read. If the optional *sizehint* argument is present, instead of
454.2167 - reading up to EOF, whole lines totalling approximately *sizehint* bytes
454.2168 - (possibly after rounding up to an internal buffer size) are read. Objects
454.2169 - implementing a file-like interface may choose to ignore *sizehint* if it
454.2170 - cannot be implemented, or cannot be implemented efficiently.
454.2171 -
454.2172 -
454.2173 -.. method:: file.xreadlines()
454.2174 -
454.2175 - This method returns the same thing as ``iter(f)``.
454.2176 -
454.2177 - .. versionadded:: 2.1
454.2178 -
454.2179 - .. deprecated:: 2.3
454.2180 - Use ``for line in file`` instead.
454.2181 -
454.2182 -
454.2183 -.. method:: file.seek(offset[, whence])
454.2184 -
454.2185 - Set the file's current position, like ``stdio``'s :cfunc:`fseek`. The *whence*
454.2186 - argument is optional and defaults to ``os.SEEK_SET`` or ``0`` (absolute file
454.2187 - positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the
454.2188 - current position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's
454.2189 - end). There is no return value.
454.2190 -
454.2191 - For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by two and
454.2192 - ``f.seek(-3, os.SEEK_END)`` sets the position to the third to last.
454.2193 -
454.2194 - Note that if the file is opened for appending
454.2195 - (mode ``'a'`` or ``'a+'``), any :meth:`seek` operations will be undone at the
454.2196 - next write. If the file is only opened for writing in append mode (mode
454.2197 - ``'a'``), this method is essentially a no-op, but it remains useful for files
454.2198 - opened in append mode with reading enabled (mode ``'a+'``). If the file is
454.2199 - opened in text mode (without ``'b'``), only offsets returned by :meth:`tell` are
454.2200 - legal. Use of other offsets causes undefined behavior.
454.2201 -
454.2202 - Note that not all file objects are seekable.
454.2203 -
454.2204 - .. versionchanged:: 2.6
454.2205 - Passing float values as offset has been deprecated.
454.2206 -
454.2207 -
454.2208 -.. method:: file.tell()
454.2209 -
454.2210 - Return the file's current position, like ``stdio``'s :cfunc:`ftell`.
454.2211 -
454.2212 - .. note::
454.2213 -
454.2214 - On Windows, :meth:`tell` can return illegal values (after an :cfunc:`fgets`)
454.2215 - when reading files with Unix-style line-endings. Use binary mode (``'rb'``) to
454.2216 - circumvent this problem.
454.2217 -
454.2218 -
454.2219 -.. method:: file.truncate([size])
454.2220 -
454.2221 - Truncate the file's size. If the optional *size* argument is present, the file
454.2222 - is truncated to (at most) that size. The size defaults to the current position.
454.2223 - The current file position is not changed. Note that if a specified size exceeds
454.2224 - the file's current size, the result is platform-dependent: possibilities
454.2225 - include that the file may remain unchanged, increase to the specified size as if
454.2226 - zero-filled, or increase to the specified size with undefined new content.
454.2227 - Availability: Windows, many Unix variants.
454.2228 -
454.2229 -
454.2230 -.. method:: file.write(str)
454.2231 -
454.2232 - Write a string to the file. There is no return value. Due to buffering, the
454.2233 - string may not actually show up in the file until the :meth:`flush` or
454.2234 - :meth:`close` method is called.
454.2235 -
454.2236 -
454.2237 -.. method:: file.writelines(sequence)
454.2238 -
454.2239 - Write a sequence of strings to the file. The sequence can be any iterable
454.2240 - object producing strings, typically a list of strings. There is no return value.
454.2241 - (The name is intended to match :meth:`readlines`; :meth:`writelines` does not
454.2242 - add line separators.)
454.2243 -
454.2244 -Files support the iterator protocol. Each iteration returns the same result as
454.2245 -``file.readline()``, and iteration ends when the :meth:`readline` method returns
454.2246 -an empty string.
454.2247 -
454.2248 -File objects also offer a number of other interesting attributes. These are not
454.2249 -required for file-like objects, but should be implemented if they make sense for
454.2250 -the particular object.
454.2251 -
454.2252 -
454.2253 -.. attribute:: file.closed
454.2254 -
454.2255 - bool indicating the current state of the file object. This is a read-only
454.2256 - attribute; the :meth:`close` method changes the value. It may not be available
454.2257 - on all file-like objects.
454.2258 -
454.2259 -
454.2260 -.. attribute:: file.encoding
454.2261 -
454.2262 - The encoding that this file uses. When Unicode strings are written to a file,
454.2263 - they will be converted to byte strings using this encoding. In addition, when
454.2264 - the file is connected to a terminal, the attribute gives the encoding that the
454.2265 - terminal is likely to use (that information might be incorrect if the user has
454.2266 - misconfigured the terminal). The attribute is read-only and may not be present
454.2267 - on all file-like objects. It may also be ``None``, in which case the file uses
454.2268 - the system default encoding for converting Unicode strings.
454.2269 -
454.2270 - .. versionadded:: 2.3
454.2271 -
454.2272 -
454.2273 -.. attribute:: file.errors
454.2274 -
454.2275 - The Unicode error handler used along with the encoding.
454.2276 -
454.2277 - .. versionadded:: 2.6
454.2278 -
454.2279 -
454.2280 -.. attribute:: file.mode
454.2281 -
454.2282 - The I/O mode for the file. If the file was created using the :func:`open`
454.2283 - built-in function, this will be the value of the *mode* parameter. This is a
454.2284 - read-only attribute and may not be present on all file-like objects.
454.2285 -
454.2286 -
454.2287 -.. attribute:: file.name
454.2288 -
454.2289 - If the file object was created using :func:`open`, the name of the file.
454.2290 - Otherwise, some string that indicates the source of the file object, of the
454.2291 - form ``<...>``. This is a read-only attribute and may not be present on all
454.2292 - file-like objects.
454.2293 -
454.2294 -
454.2295 -.. attribute:: file.newlines
454.2296 -
454.2297 - If Python was built with the :option:`--with-universal-newlines` option to
454.2298 - :program:`configure` (the default) this read-only attribute exists, and for
454.2299 - files opened in universal newline read mode it keeps track of the types of
454.2300 - newlines encountered while reading the file. The values it can take are
454.2301 - ``'\r'``, ``'\n'``, ``'\r\n'``, ``None`` (unknown, no newlines read yet) or a
454.2302 - tuple containing all the newline types seen, to indicate that multiple newline
454.2303 - conventions were encountered. For files not opened in universal newline read
454.2304 - mode the value of this attribute will be ``None``.
454.2305 -
454.2306 -
454.2307 -.. attribute:: file.softspace
454.2308 -
454.2309 - Boolean that indicates whether a space character needs to be printed before
454.2310 - another value when using the :keyword:`print` statement. Classes that are trying
454.2311 - to simulate a file object should also have a writable :attr:`softspace`
454.2312 - attribute, which should be initialized to zero. This will be automatic for most
454.2313 - classes implemented in Python (care may be needed for objects that override
454.2314 - attribute access); types implemented in C will have to provide a writable
454.2315 - :attr:`softspace` attribute.
454.2316 -
454.2317 - .. note::
454.2318 -
454.2319 - This attribute is not used to control the :keyword:`print` statement, but to
454.2320 - allow the implementation of :keyword:`print` to keep track of its internal
454.2321 - state.
454.2322 -
454.2323 -
454.2324 -.. _typecontextmanager:
454.2325 -
454.2326 -Context Manager Types
454.2327 -=====================
454.2328 -
454.2329 -.. versionadded:: 2.5
454.2330 -
454.2331 -.. index::
454.2332 - single: context manager
454.2333 - single: context management protocol
454.2334 - single: protocol; context management
454.2335 -
454.2336 -Python's :keyword:`with` statement supports the concept of a runtime context
454.2337 -defined by a context manager. This is implemented using two separate methods
454.2338 -that allow user-defined classes to define a runtime context that is entered
454.2339 -before the statement body is executed and exited when the statement ends.
454.2340 -
454.2341 -The :dfn:`context management protocol` consists of a pair of methods that need
454.2342 -to be provided for a context manager object to define a runtime context:
454.2343 -
454.2344 -
454.2345 -.. method:: contextmanager.__enter__()
454.2346 -
454.2347 - Enter the runtime context and return either this object or another object
454.2348 - related to the runtime context. The value returned by this method is bound to
454.2349 - the identifier in the :keyword:`as` clause of :keyword:`with` statements using
454.2350 - this context manager.
454.2351 -
454.2352 - An example of a context manager that returns itself is a file object. File
454.2353 - objects return themselves from __enter__() to allow :func:`open` to be used as
454.2354 - the context expression in a :keyword:`with` statement.
454.2355 -
454.2356 - An example of a context manager that returns a related object is the one
454.2357 - returned by :func:`decimal.localcontext`. These managers set the active
454.2358 - decimal context to a copy of the original decimal context and then return the
454.2359 - copy. This allows changes to be made to the current decimal context in the body
454.2360 - of the :keyword:`with` statement without affecting code outside the
454.2361 - :keyword:`with` statement.
454.2362 -
454.2363 -
454.2364 -.. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)
454.2365 -
454.2366 - Exit the runtime context and return a Boolean flag indicating if any exception
454.2367 - that occurred should be suppressed. If an exception occurred while executing the
454.2368 - body of the :keyword:`with` statement, the arguments contain the exception type,
454.2369 - value and traceback information. Otherwise, all three arguments are ``None``.
454.2370 -
454.2371 - Returning a true value from this method will cause the :keyword:`with` statement
454.2372 - to suppress the exception and continue execution with the statement immediately
454.2373 - following the :keyword:`with` statement. Otherwise the exception continues
454.2374 - propagating after this method has finished executing. Exceptions that occur
454.2375 - during execution of this method will replace any exception that occurred in the
454.2376 - body of the :keyword:`with` statement.
454.2377 -
454.2378 - The exception passed in should never be reraised explicitly - instead, this
454.2379 - method should return a false value to indicate that the method completed
454.2380 - successfully and does not want to suppress the raised exception. This allows
454.2381 - context management code (such as ``contextlib.nested``) to easily detect whether
454.2382 - or not an :meth:`__exit__` method has actually failed.
454.2383 -
454.2384 -Python defines several context managers to support easy thread synchronisation,
454.2385 -prompt closure of files or other objects, and simpler manipulation of the active
454.2386 -decimal arithmetic context. The specific types are not treated specially beyond
454.2387 -their implementation of the context management protocol. See the
454.2388 -:mod:`contextlib` module for some examples.
454.2389 -
454.2390 -Python's :term:`generator`\s and the ``contextlib.contextfactory`` :term:`decorator`
454.2391 -provide a convenient way to implement these protocols. If a generator function is
454.2392 -decorated with the ``contextlib.contextfactory`` decorator, it will return a
454.2393 -context manager implementing the necessary :meth:`__enter__` and
454.2394 -:meth:`__exit__` methods, rather than the iterator produced by an undecorated
454.2395 -generator function.
454.2396 -
454.2397 -Note that there is no specific slot for any of these methods in the type
454.2398 -structure for Python objects in the Python/C API. Extension types wanting to
454.2399 -define these methods must provide them as a normal Python accessible method.
454.2400 -Compared to the overhead of setting up the runtime context, the overhead of a
454.2401 -single class dictionary lookup is negligible.
454.2402 -
454.2403 -
454.2404 -.. _typesother:
454.2405 -
454.2406 -Other Built-in Types
454.2407 -====================
454.2408 -
454.2409 -The interpreter supports several other kinds of objects. Most of these support
454.2410 -only one or two operations.
454.2411 -
454.2412 -
454.2413 -.. _typesmodules:
454.2414 -
454.2415 -Modules
454.2416 --------
454.2417 -
454.2418 -The only special operation on a module is attribute access: ``m.name``, where
454.2419 -*m* is a module and *name* accesses a name defined in *m*'s symbol table.
454.2420 -Module attributes can be assigned to. (Note that the :keyword:`import`
454.2421 -statement is not, strictly speaking, an operation on a module object; ``import
454.2422 -foo`` does not require a module object named *foo* to exist, rather it requires
454.2423 -an (external) *definition* for a module named *foo* somewhere.)
454.2424 -
454.2425 -A special member of every module is :attr:`__dict__`. This is the dictionary
454.2426 -containing the module's symbol table. Modifying this dictionary will actually
454.2427 -change the module's symbol table, but direct assignment to the :attr:`__dict__`
454.2428 -attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines
454.2429 -``m.a`` to be ``1``, but you can't write ``m.__dict__ = {}``). Modifying
454.2430 -:attr:`__dict__` directly is not recommended.
454.2431 -
454.2432 -Modules built into the interpreter are written like this: ``<module 'sys'
454.2433 -(built-in)>``. If loaded from a file, they are written as ``<module 'os' from
454.2434 -'/usr/local/lib/pythonX.Y/os.pyc'>``.
454.2435 -
454.2436 -
454.2437 -.. _typesobjects:
454.2438 -
454.2439 -Classes and Class Instances
454.2440 ----------------------------
454.2441 -
454.2442 -See :ref:`objects` and :ref:`class` for these.
454.2443 -
454.2444 -
454.2445 -.. _typesfunctions:
454.2446 -
454.2447 -Functions
454.2448 ----------
454.2449 -
454.2450 -Function objects are created by function definitions. The only operation on a
454.2451 -function object is to call it: ``func(argument-list)``.
454.2452 -
454.2453 -There are really two flavors of function objects: built-in functions and
454.2454 -user-defined functions. Both support the same operation (to call the function),
454.2455 -but the implementation is different, hence the different object types.
454.2456 -
454.2457 -See :ref:`function` for more information.
454.2458 -
454.2459 -
454.2460 -.. _typesmethods:
454.2461 -
454.2462 -Methods
454.2463 --------
454.2464 -
454.2465 -.. index:: object: method
454.2466 -
454.2467 -Methods are functions that are called using the attribute notation. There are
454.2468 -two flavors: built-in methods (such as :meth:`append` on lists) and class
454.2469 -instance methods. Built-in methods are described with the types that support
454.2470 -them.
454.2471 -
454.2472 -The implementation adds two special read-only attributes to class instance
454.2473 -methods: ``m.im_self`` is the object on which the method operates, and
454.2474 -``m.im_func`` is the function implementing the method. Calling ``m(arg-1,
454.2475 -arg-2, ..., arg-n)`` is completely equivalent to calling ``m.im_func(m.im_self,
454.2476 -arg-1, arg-2, ..., arg-n)``.
454.2477 -
454.2478 -Class instance methods are either *bound* or *unbound*, referring to whether the
454.2479 -method was accessed through an instance or a class, respectively. When a method
454.2480 -is unbound, its ``im_self`` attribute will be ``None`` and if called, an
454.2481 -explicit ``self`` object must be passed as the first argument. In this case,
454.2482 -``self`` must be an instance of the unbound method's class (or a subclass of
454.2483 -that class), otherwise a :exc:`TypeError` is raised.
454.2484 -
454.2485 -Like function objects, methods objects support getting arbitrary attributes.
454.2486 -However, since method attributes are actually stored on the underlying function
454.2487 -object (``meth.im_func``), setting method attributes on either bound or unbound
454.2488 -methods is disallowed. Attempting to set a method attribute results in a
454.2489 -:exc:`TypeError` being raised. In order to set a method attribute, you need to
454.2490 -explicitly set it on the underlying function object::
454.2491 -
454.2492 - class C:
454.2493 - def method(self):
454.2494 - pass
454.2495 -
454.2496 - c = C()
454.2497 - c.method.im_func.whoami = 'my name is c'
454.2498 -
454.2499 -See :ref:`types` for more information.
454.2500 -
454.2501 -
454.2502 -.. _bltin-code-objects:
454.2503 -
454.2504 -Code Objects
454.2505 -------------
454.2506 -
454.2507 -.. index:: object: code
454.2508 -
454.2509 -.. index::
454.2510 - builtin: compile
454.2511 - single: func_code (function object attribute)
454.2512 -
454.2513 -Code objects are used by the implementation to represent "pseudo-compiled"
454.2514 -executable Python code such as a function body. They differ from function
454.2515 -objects because they don't contain a reference to their global execution
454.2516 -environment. Code objects are returned by the built-in :func:`compile` function
454.2517 -and can be extracted from function objects through their :attr:`func_code`
454.2518 -attribute. See also the :mod:`code` module.
454.2519 -
454.2520 -.. index::
454.2521 - statement: exec
454.2522 - builtin: eval
454.2523 -
454.2524 -A code object can be executed or evaluated by passing it (instead of a source
454.2525 -string) to the :keyword:`exec` statement or the built-in :func:`eval` function.
454.2526 -
454.2527 -See :ref:`types` for more information.
454.2528 -
454.2529 -
454.2530 -.. _bltin-type-objects:
454.2531 -
454.2532 -Type Objects
454.2533 -------------
454.2534 -
454.2535 -.. index::
454.2536 - builtin: type
454.2537 - module: types
454.2538 -
454.2539 -Type objects represent the various object types. An object's type is accessed
454.2540 -by the built-in function :func:`type`. There are no special operations on
454.2541 -types. The standard module :mod:`types` defines names for all standard built-in
454.2542 -types.
454.2543 -
454.2544 -Types are written like this: ``<type 'int'>``.
454.2545 -
454.2546 -
454.2547 -.. _bltin-null-object:
454.2548 -
454.2549 -The Null Object
454.2550 ----------------
454.2551 -
454.2552 -This object is returned by functions that don't explicitly return a value. It
454.2553 -supports no special operations. There is exactly one null object, named
454.2554 -``None`` (a built-in name).
454.2555 -
454.2556 -It is written as ``None``.
454.2557 -
454.2558 -
454.2559 -.. _bltin-ellipsis-object:
454.2560 -
454.2561 -The Ellipsis Object
454.2562 --------------------
454.2563 -
454.2564 -This object is used by extended slice notation (see :ref:`slicings`). It
454.2565 -supports no special operations. There is exactly one ellipsis object, named
454.2566 -:const:`Ellipsis` (a built-in name).
454.2567 -
454.2568 -It is written as ``Ellipsis``.
454.2569 -
454.2570 -
454.2571 -Boolean Values
454.2572 ---------------
454.2573 -
454.2574 -Boolean values are the two constant objects ``False`` and ``True``. They are
454.2575 -used to represent truth values (although other values can also be considered
454.2576 -false or true). In numeric contexts (for example when used as the argument to
454.2577 -an arithmetic operator), they behave like the integers 0 and 1, respectively.
454.2578 -The built-in function :func:`bool` can be used to cast any value to a Boolean,
454.2579 -if the value can be interpreted as a truth value (see section Truth Value
454.2580 -Testing above).
454.2581 -
454.2582 -.. index::
454.2583 - single: False
454.2584 - single: True
454.2585 - pair: Boolean; values
454.2586 -
454.2587 -They are written as ``False`` and ``True``, respectively.
454.2588 -
454.2589 -
454.2590 -.. _typesinternal:
454.2591 -
454.2592 -Internal Objects
454.2593 -----------------
454.2594 -
454.2595 -See :ref:`types` for this information. It describes stack frame objects,
454.2596 -traceback objects, and slice objects.
454.2597 -
454.2598 -
454.2599 -.. _specialattrs:
454.2600 -
454.2601 -Special Attributes
454.2602 -==================
454.2603 -
454.2604 -The implementation adds a few special read-only attributes to several object
454.2605 -types, where they are relevant. Some of these are not reported by the
454.2606 -:func:`dir` built-in function.
454.2607 -
454.2608 -
454.2609 -.. attribute:: object.__dict__
454.2610 -
454.2611 - A dictionary or other mapping object used to store an object's (writable)
454.2612 - attributes.
454.2613 -
454.2614 -
454.2615 -.. attribute:: object.__methods__
454.2616 -
454.2617 - .. deprecated:: 2.2
454.2618 - Use the built-in function :func:`dir` to get a list of an object's attributes.
454.2619 - This attribute is no longer available.
454.2620 -
454.2621 -
454.2622 -.. attribute:: object.__members__
454.2623 -
454.2624 - .. deprecated:: 2.2
454.2625 - Use the built-in function :func:`dir` to get a list of an object's attributes.
454.2626 - This attribute is no longer available.
454.2627 -
454.2628 -
454.2629 -.. attribute:: instance.__class__
454.2630 -
454.2631 - The class to which a class instance belongs.
454.2632 -
454.2633 -
454.2634 -.. attribute:: class.__bases__
454.2635 -
454.2636 - The tuple of base classes of a class object. If there are no base classes, this
454.2637 - will be an empty tuple.
454.2638 -
454.2639 -
454.2640 -.. attribute:: class.__name__
454.2641 -
454.2642 - The name of the class or type.
454.2643 -
454.2644 -.. rubric:: Footnotes
454.2645 -
454.2646 -.. [#] Additional information on these special methods may be found in the Python
454.2647 - Reference Manual (:ref:`customization`).
454.2648 -
454.2649 -.. [#] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
454.2650 - similarly for tuples.
454.2651 -
454.2652 -.. [#] They must have since the parser can't tell the type of the operands.
454.2653 -
454.2654 -.. [#] To format only a tuple you should therefore provide a singleton tuple whose only
454.2655 - element is the tuple to be formatted.
454.2656 -
454.2657 -.. [#] These numbers are fairly arbitrary. They are intended to avoid printing endless
454.2658 - strings of meaningless digits without hampering correct use and without having
454.2659 - to know the exact precision of floating point values on a particular machine.
454.2660 -
454.2661 -.. [#] The advantage of leaving the newline on is that returning an empty string is
454.2662 - then an unambiguous EOF indication. It is also possible (in cases where it
454.2663 - might matter, for example, if you want to make an exact copy of a file while
454.2664 - scanning its lines) to tell whether the last line of a file ended in a newline
454.2665 - or not (yes this happens!).
455.1 --- a/python.editor/test/unit/data/testfiles/rst/stdtypes.rst.html Sun Jan 04 13:11:53 2015 -0600
455.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
455.3 @@ -1,2519 +0,0 @@
455.4 -<html><body>
455.5 -.. XXX: reference/datamodel and this have quite a few overlaps!
455.6 -
455.7 -<br><br>
455.8 -
455.9 -<h2><br><br>
455.10 -</h2>
455.11 -<h2>Built-in Types
455.12 -</h2>
455.13 -The following sections describe the standard types that are built into the
455.14 -interpreter.
455.15 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
455.16 -
455.17 -<br><br>
455.18 - Historically (until release 2.2), Python's built-in types have differed from
455.19 - user-defined types because it was not possible to use the built-in types as the
455.20 - basis for object-oriented inheritance. This limitation no longer
455.21 - exists.
455.22 -</div>
455.23 -The principal built-in types are numerics, sequences, mappings, files, classes,
455.24 -instances and exceptions.
455.25 -
455.26 -<br><br>
455.27 -Some operations are supported by several object types; in particular,
455.28 -practically all objects can be compared, tested for truth value, and converted
455.29 -to a string (with the <a href="func:repr">repr</a> function or the slightly different
455.30 -<a href="func:str">str</a> function). The latter function is implicitly used when an object is
455.31 -written by the <a href="func:print">print</a> function.
455.32 -
455.33 -<br><br>
455.34 -
455.35 -<br><br>
455.36 -<h2>Truth Value Testing
455.37 -</h2>
455.38 -Any object can be tested for truth value, for use in an <code style="color:#0000e6;">if</code> or
455.39 -<code style="color:#0000e6;">while</code> condition or as operand of the Boolean operations below. The
455.40 -following values are considered false:
455.41 -
455.42 -<br><br>
455.43 -* <code>None</code>
455.44 -* <code>False</code>
455.45 -* zero of any numeric type, for example, <code>0</code>, <code>0L</code>, <code>0.0</code>, <code>0j</code>.
455.46 -
455.47 -<br><br>
455.48 -* any empty sequence, for example, <code>''</code>, <code>()</code>, <code>[]</code>.
455.49 -
455.50 -<br><br>
455.51 -* any empty mapping, for example, <code>{}</code>.
455.52 -
455.53 -<br><br>
455.54 -* instances of user-defined classes, if the class defines a <a href="meth:__nonzero__">__nonzero__</a>
455.55 - or <a href="meth:__len__">__len__</a> method, when that method returns the integer zero or
455.56 - <a href="class:bool">bool</a> value <code>False</code>. [#]_
455.57 -
455.58 -<br><br>
455.59 -All other values are considered true --- so objects of many types are always
455.60 -true.
455.61 -
455.62 -<br><br>
455.63 -Operations and built-in functions that have a Boolean result always return <code>0</code>
455.64 -or <code>False</code> for false and <code>1</code> or <code>True</code> for true, unless otherwise stated.
455.65 -(Important exception: the Boolean operations <code>or</code> and <code>and</code> always return
455.66 -one of their operands.)
455.67 -
455.68 -<br><br>
455.69 -
455.70 -<br><br>
455.71 -<h2>Boolean Operations --- <code style="color:#0000e6;">and</code>, <code style="color:#0000e6;">or</code>, <code style="color:#0000e6;">not</code>
455.72 -</h2>
455.73 -These are the Boolean operations, ordered by ascending priority:
455.74 -<pre>+-------------+---------------------------------+-------+
455.75 -| Operation | Result | Notes |
455.76 -+=============+=================================+=======+
455.77 -| ``x or y`` | if *x* is false, then *y*, else | \(1) |
455.78 -| | *x* | |
455.79 -+-------------+---------------------------------+-------+
455.80 -| ``x and y`` | if *x* is false, then *x*, else | \(2) |
455.81 -| | *y* | |
455.82 -+-------------+---------------------------------+-------+
455.83 -| ``not x`` | if *x* is false, then ``True``, | \(3) |
455.84 -| | else ``False`` | |
455.85 -+-------------+---------------------------------+-------+
455.86 -</pre>
455.87 -Notes:
455.88 -(1)
455.89 - This is a short-circuit operator, so it only evaluates the second
455.90 - argument if the first one is :const:<code>False</code>.
455.91 -
455.92 -<br><br>
455.93 -(2)
455.94 - This is a short-circuit operator, so it only evaluates the second
455.95 - argument if the first one is :const:<code>True</code>.
455.96 -
455.97 -<br><br>
455.98 -(3)
455.99 - <code>not</code> has a lower priority than non-Boolean operators, so <code>not a == b</code> is
455.100 - interpreted as <code>not (a == b)</code>, and <code>a == not b</code> is a syntax error.
455.101 -
455.102 -<br><br>
455.103 -
455.104 -<br><br>
455.105 -<h2>Comparisons
455.106 -</h2>
455.107 -Comparison operations are supported by all objects. They all have the same
455.108 -priority (which is higher than that of the Boolean operations). Comparisons can
455.109 -be chained arbitrarily; for example, <code>x < y <= z</code> is equivalent to ``x < y and
455.110 -y <= z``, except that <b>y</b> is evaluated only once (but in both cases <b>z</b> is not
455.111 -evaluated at all when <code>x < y</code> is found to be false).
455.112 -
455.113 -<br><br>
455.114 -This table summarizes the comparison operations:
455.115 -
455.116 -<br><br>
455.117 -<pre>+------------+-------------------------+-------+
455.118 -| Operation | Meaning | Notes |
455.119 -+============+=========================+=======+
455.120 -| ``<`` | strictly less than | |
455.121 -+------------+-------------------------+-------+
455.122 -| ``<=`` | less than or equal | |
455.123 -+------------+-------------------------+-------+
455.124 -| ``>`` | strictly greater than | |
455.125 -+------------+-------------------------+-------+
455.126 -| ``>=`` | greater than or equal | |
455.127 -+------------+-------------------------+-------+
455.128 -| ``==`` | equal | |
455.129 -+------------+-------------------------+-------+
455.130 -| ``!=`` | not equal | \(1) |
455.131 -+------------+-------------------------+-------+
455.132 -| ``is`` | object identity | |
455.133 -+------------+-------------------------+-------+
455.134 -| ``is not`` | negated object identity | |
455.135 -+------------+-------------------------+-------+
455.136 -</pre>
455.137 -Notes:
455.138 -(1)
455.139 - <code>!=</code> can also be written <code><></code>, but this is an obsolete usage
455.140 - kept for backwards compatibility only. New code should always use
455.141 - <code>!=</code>.
455.142 -
455.143 -<br><br>
455.144 -Objects of different types, except different numeric types and different string
455.145 -types, never compare equal; such objects are ordered consistently but
455.146 -arbitrarily (so that sorting a heterogeneous array yields a consistent result).
455.147 -Furthermore, some types (for example, file objects) support only a degenerate
455.148 -notion of comparison where any two objects of that type are unequal. Again,
455.149 -such objects are ordered arbitrarily but consistently. The <code><</code>, <code><=</code>, <code>></code>
455.150 -and <code>>=</code> operators will raise a <a href="exc:TypeError">TypeError</a> exception when any operand is
455.151 -a complex number.
455.152 -
455.153 -<br><br>
455.154 -Instances of a class normally compare as non-equal unless the class defines the
455.155 -<a href="meth:__cmp__">__cmp__</a> method. Refer to <code>customization</code>) for information on the
455.156 -use of this method to effect object comparisons.
455.157 -
455.158 -<br><br>
455.159 -**Implementation note:** Objects of different types except numbers are ordered
455.160 -by their type names; objects of the same types that don't support proper
455.161 -comparison are ordered by their address.
455.162 -
455.163 -<br><br>
455.164 -Two more operations with the same syntactic priority, <code>in</code> and <code>not in</code>, are
455.165 -supported only by sequence types (below).
455.166 -
455.167 -<br><br>
455.168 -
455.169 -<br><br>
455.170 -<h2>Numeric Types --- <a href="class:int">int</a>, <a href="class:float">float</a>, <a href="class:long">long</a>, <a href="class:complex">complex</a>
455.171 -</h2>
455.172 -There are four distinct numeric types: :dfn:`plain integers`, :dfn:`long
455.173 -integers`, :dfn:`floating point numbers`, and :dfn:`complex numbers`. In
455.174 -addition, Booleans are a subtype of plain integers. Plain integers (also just
455.175 -called :dfn:<code>integers</code>) are implemented using :ctype:<code>long</code> in C, which gives
455.176 -them at least 32 bits of precision (<code>sys.maxint</code> is always set to the maximum
455.177 -plain integer value for the current platform, the minimum value is
455.178 -<code>-sys.maxint - 1</code>). Long integers have unlimited precision. Floating point
455.179 -numbers are implemented using :ctype:<code>double</code> in C. All bets on their precision
455.180 -are off unless you happen to know the machine you are working with.
455.181 -
455.182 -<br><br>
455.183 -Complex numbers have a real and imaginary part, which are each implemented using
455.184 -:ctype:<code>double</code> in C. To extract these parts from a complex number <b>z</b>, use
455.185 -<code>z.real</code> and <code>z.imag</code>.
455.186 -
455.187 -<br><br>
455.188 -Numbers are created by numeric literals or as the result of built-in functions
455.189 -and operators. Unadorned integer literals (including hex and octal numbers)
455.190 -yield plain integers unless the value they denote is too large to be represented
455.191 -as a plain integer, in which case they yield a long integer. Integer literals
455.192 -with an <code>'L'</code> or <code>'l'</code> suffix yield long integers (<code>'L'</code> is preferred
455.193 -because <code>1l</code> looks too much like eleven!). Numeric literals containing a
455.194 -decimal point or an exponent sign yield floating point numbers. Appending
455.195 -<code>'j'</code> or <code>'J'</code> to a numeric literal yields a complex number with a zero real
455.196 -part. A complex numeric literal is the sum of a real and an imaginary part.
455.197 -
455.198 -<br><br>
455.199 -Python fully supports mixed arithmetic: when a binary arithmetic operator has
455.200 -operands of different numeric types, the operand with the "narrower" type is
455.201 -widened to that of the other, where plain integer is narrower than long integer
455.202 -is narrower than floating point is narrower than complex. Comparisons between
455.203 -numbers of mixed type use the same rule. [#]_ The constructors <a href="func:int">int</a>,
455.204 -<a href="func:long">long</a>, <a href="func:float">float</a>, and <a href="func:complex">complex</a> can be used to produce numbers
455.205 -of a specific type.
455.206 -
455.207 -<br><br>
455.208 -All builtin numeric types support the following operations. See
455.209 -<code>power</code> and later sections for the operators' priorities.
455.210 -
455.211 -<br><br>
455.212 -<pre>+--------------------+---------------------------------+--------+
455.213 -| Operation | Result | Notes |
455.214 -+====================+=================================+========+
455.215 -| ``x + y`` | sum of *x* and *y* | |
455.216 -+--------------------+---------------------------------+--------+
455.217 -| ``x - y`` | difference of *x* and *y* | |
455.218 -+--------------------+---------------------------------+--------+
455.219 -| ``x * y`` | product of *x* and *y* | |
455.220 -+--------------------+---------------------------------+--------+
455.221 -| ``x / y`` | quotient of *x* and *y* | \(1) |
455.222 -+--------------------+---------------------------------+--------+
455.223 -| ``x // y`` | (floored) quotient of *x* and | (4)(5) |
455.224 -| | *y* | |
455.225 -+--------------------+---------------------------------+--------+
455.226 -| ``x % y`` | remainder of ``x / y`` | \(4) |
455.227 -+--------------------+---------------------------------+--------+
455.228 -| ``-x`` | *x* negated | |
455.229 -+--------------------+---------------------------------+--------+
455.230 -| ``+x`` | *x* unchanged | |
455.231 -+--------------------+---------------------------------+--------+
455.232 -| ``abs(x)`` | absolute value or magnitude of | \(3) |
455.233 -| | *x* | |
455.234 -+--------------------+---------------------------------+--------+
455.235 -| ``int(x)`` | *x* converted to integer | \(2) |
455.236 -+--------------------+---------------------------------+--------+
455.237 -| ``long(x)`` | *x* converted to long integer | \(2) |
455.238 -+--------------------+---------------------------------+--------+
455.239 -| ``float(x)`` | *x* converted to floating point | \(6) |
455.240 -+--------------------+---------------------------------+--------+
455.241 -| ``complex(re,im)`` | a complex number with real part | |
455.242 -| | *re*, imaginary part *im*. | |
455.243 -| | *im* defaults to zero. | |
455.244 -+--------------------+---------------------------------+--------+
455.245 -| ``c.conjugate()`` | conjugate of the complex number | |
455.246 -| | *c*. (Identity on real numbers) | |
455.247 -+--------------------+---------------------------------+--------+
455.248 -| ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | (3)(4) |
455.249 -+--------------------+---------------------------------+--------+
455.250 -| ``pow(x, y)`` | *x* to the power *y* | (3)(7) |
455.251 -+--------------------+---------------------------------+--------+
455.252 -| ``x ** y`` | *x* to the power *y* | \(7) |
455.253 -+--------------------+---------------------------------+--------+
455.254 -</pre>
455.255 -Notes:
455.256 -(1)
455.257 - For (plain or long) integer division, the result is an integer. The result is
455.258 - always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and
455.259 - (-1)/(-2) is 0. Note that the result is a long integer if either operand is a
455.260 - long integer, regardless of the numeric value.
455.261 -
455.262 -<br><br>
455.263 -(2)
455.264 - Conversion from floating point to (long or plain) integer may round or
455.265 - truncate as in C; see functions <a href="func:math.floor">math.floor</a> and <a href="func:math.ceil">math.ceil</a> for
455.266 - well-defined conversions.
455.267 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Deprecated</b>: 2.6
455.268 - Instead, convert floats to long explicitly with <a href="func:trunc">trunc</a>.
455.269 -</div>
455.270 -(3)
455.271 - See <code>built-in-funcs</code> for a full description.
455.272 -
455.273 -<br><br>
455.274 -(4)
455.275 - Complex floor division operator, modulo operator, and <a href="func:divmod">divmod</a>.
455.276 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Deprecated</b>: 2.3
455.277 - Instead convert to float using <a href="func:abs">abs</a> if appropriate.
455.278 -</div>
455.279 -(5)
455.280 - Also referred to as integer division. The resultant value is a whole integer,
455.281 - though the result's type is not necessarily int.
455.282 -
455.283 -<br><br>
455.284 -(6)
455.285 - float also accepts the strings "nan" and "inf" with an optional prefix "+"
455.286 - or "-" for Not a Number (NaN) and positive or negative infinity.
455.287 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
455.288 -</div>
455.289 -(7)
455.290 - Python defines <code>pow(0, 0)</code> and <code>0 ** 0</code> to be <code>1</code>, as is common for
455.291 - programming languages.
455.292 -
455.293 -<br><br>
455.294 -All <a href="class:numbers.Real">numbers.Real</a> types (<a href="class:int">int</a>, <a href="class:long">long</a>, and
455.295 -<a href="class:float">float</a>) also include the following operations:
455.296 -
455.297 -<br><br>
455.298 -<pre>+--------------------+------------------------------------+--------+
455.299 -| Operation | Result | Notes |
455.300 -+====================+====================================+========+
455.301 -| ``trunc(x)`` | *x* truncated to Integral | |
455.302 -+--------------------+------------------------------------+--------+
455.303 -| ``round(x[, n])`` | *x* rounded to n digits, | |
455.304 -| | rounding half to even. If n is | |
455.305 -| | omitted, it defaults to 0. | |
455.306 -+--------------------+------------------------------------+--------+
455.307 -| ``math.floor(x)`` | the greatest integral float <= *x* | |
455.308 -+--------------------+------------------------------------+--------+
455.309 -| ``math.ceil(x)`` | the least integral float >= *x* | |
455.310 -+--------------------+------------------------------------+--------+
455.311 -</pre>
455.312 -.. XXXJH exceptions: overflow (when? what operations?) zerodivision
455.313 -
455.314 -<br><br>
455.315 -
455.316 -<br><br>
455.317 -<h3>Bit-string Operations on Integer Types
455.318 -</h3>
455.319 -
455.320 -<br><br>
455.321 -Plain and long integer types support additional operations that make sense only
455.322 -for bit-strings. Negative numbers are treated as their 2's complement value
455.323 -(for long integers, this assumes a sufficiently large number of bits that no
455.324 -overflow occurs during the operation).
455.325 -
455.326 -<br><br>
455.327 -The priorities of the binary bitwise operations are all lower than the numeric
455.328 -operations and higher than the comparisons; the unary operation <code>~</code> has the
455.329 -same priority as the other unary numeric operations (<code>+</code> and <code>-</code>).
455.330 -
455.331 -<br><br>
455.332 -This table lists the bit-string operations sorted in ascending priority:
455.333 -
455.334 -<br><br>
455.335 -<pre>+------------+--------------------------------+----------+
455.336 -| Operation | Result | Notes |
455.337 -+============+================================+==========+
455.338 -| ``x | y`` | bitwise :dfn:`or` of *x* and | |
455.339 -| | *y* | |
455.340 -+------------+--------------------------------+----------+
455.341 -| ``x ^ y`` | bitwise :dfn:`exclusive or` of | |
455.342 -| | *x* and *y* | |
455.343 -+------------+--------------------------------+----------+
455.344 -| ``x & y`` | bitwise :dfn:`and` of *x* and | |
455.345 -| | *y* | |
455.346 -+------------+--------------------------------+----------+
455.347 -| ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
455.348 -+------------+--------------------------------+----------+
455.349 -| ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
455.350 -+------------+--------------------------------+----------+
455.351 -| ``~x`` | the bits of *x* inverted | |
455.352 -+------------+--------------------------------+----------+
455.353 -</pre>
455.354 -Notes:
455.355 -(1)
455.356 - Negative shift counts are illegal and cause a <a href="exc:ValueError">ValueError</a> to be raised.
455.357 -
455.358 -<br><br>
455.359 -(2)
455.360 - A left shift by <b>n</b> bits is equivalent to multiplication by <code>pow(2, n)</code>. A
455.361 - long integer is returned if the result exceeds the range of plain integers.
455.362 -
455.363 -<br><br>
455.364 -(3)
455.365 - A right shift by <b>n</b> bits is equivalent to division by <code>pow(2, n)</code>.
455.366 -
455.367 -<br><br>
455.368 -<h3>Additional Methods on Float
455.369 -</h3>
455.370 -The float type has some additional methods.
455.371 -
455.372 -<br><br>
455.373 -<a href="meth:float.as_integer_ratio()">float.as_integer_ratio()</a>
455.374 -
455.375 -<br><br>
455.376 - Return a pair of integers whose ratio is exactly equal to the
455.377 - original float and with a positive denominator. Raises
455.378 - <a href="exc:OverflowError">OverflowError</a> on infinities and a <a href="exc:ValueError">ValueError</a> on
455.379 - NaNs.
455.380 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
455.381 -</div>
455.382 -Two methods support conversion to
455.383 -and from hexadecimal strings. Since Python's floats are stored
455.384 -internally as binary numbers, converting a float to or from a
455.385 -*decimal* string usually involves a small rounding error. In
455.386 -contrast, hexadecimal strings allow exact representation and
455.387 -specification of floating-point numbers. This can be useful when
455.388 -debugging, and in numerical work.
455.389 -
455.390 -<br><br>
455.391 -<a href="meth:float.hex()">float.hex()</a>
455.392 -
455.393 -<br><br>
455.394 - Return a representation of a floating-point number as a hexadecimal
455.395 - string. For finite floating-point numbers, this representation
455.396 - will always include a leading <code>0x</code> and a trailing <code>p</code> and
455.397 - exponent.
455.398 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
455.399 -</div>
455.400 -<a href="meth:float.fromhex(s)">float.fromhex(s)</a>
455.401 - Class method to return the float represented by a hexadecimal
455.402 - string <b>s</b>. The string <b>s</b> may have leading and trailing
455.403 - whitespace.
455.404 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
455.405 -</div>
455.406 -Note that <a href="meth:float.hex">float.hex</a> is an instance method, while
455.407 -<a href="meth:float.fromhex">float.fromhex</a> is a class method.
455.408 -
455.409 -<br><br>
455.410 -A hexadecimal string takes the form::
455.411 -
455.412 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
455.413 - <span style="">[</span><span style="">sign</span><span style="">]</span> <span style="">[</span><span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">0x</span></span><span style="color:#ce7b00;">'</span><span style="">]</span> <span style="">integer</span> <span style="">[</span><span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">.</span></span><span style="color:#ce7b00;">'</span> <span style="">fraction</span><span style="">]</span> <span style="">[</span><span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">p</span></span><span style="color:#ce7b00;">'</span> <span style="">exponent</span><span style="">]</span><span style="color:#000000;"><br></span></pre>
455.414 -where the optional <code>sign</code> may by either <code>+</code> or <code>-</code>, <code>integer</code>
455.415 -and <code>fraction</code> are strings of hexadecimal digits, and <code>exponent</code>
455.416 -is a decimal integer with an optional leading sign. Case is not
455.417 -significant, and there must be at least one hexadecimal digit in
455.418 -either the integer or the fraction. This syntax is similar to the
455.419 -syntax specified in section 6.4.4.2 of the C99 standard, and also to
455.420 -the syntax used in Java 1.5 onwards. In particular, the output of
455.421 -<a href="meth:float.hex">float.hex</a> is usable as a hexadecimal floating-point literal in
455.422 -C or Java code, and hexadecimal strings produced by C's <code>%a</code> format
455.423 -character or Java's <code>Double.toHexString</code> are accepted by
455.424 -<a href="meth:float.fromhex">float.fromhex</a>.
455.425 -
455.426 -<br><br>
455.427 -Note that the exponent is written in decimal rather than hexadecimal,
455.428 -and that it gives the power of 2 by which to multiply the coefficient.
455.429 -For example, the hexadecimal string <code>0x3.a7p10</code> represents the
455.430 -floating-point number <code>(3 + 10./16 + 7./16**2) * 2.0**10</code>, or
455.431 -<code>3740.0</code>::
455.432 -
455.433 -
455.434 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
455.435 - <span style="">>></span><span style="">></span> <span style="">float</span><span style="">.</span><span style="">fromhex</span><span style="">(</span><span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">0x3.a7p10</span></span><span style="color:#ce7b00;">'</span><span style="">)</span><span style="color:#000000;"><br></span> <span style="color:#000000;">3740.0</span><span style="color:#000000;"><br></span></pre>
455.436 -Applying the reverse conversion to <code>3740.0</code> gives a different
455.437 -hexadecimal string representing the same number::
455.438 -
455.439 -
455.440 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
455.441 - <span style="">>></span><span style="">></span> <span style="">float</span><span style="">.</span><span style="">hex</span><span style="">(</span><span style="color:#000000;">3740.0</span><span style="">)</span><span style="color:#000000;"><br></span> <span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">0x1.d380000000000p+11</span></span><span style="color:#ce7b00;">'</span><span style="color:#000000;"><br></span></pre>
455.442 -<h2>Iterator Types
455.443 -</h2>
455.444 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
455.445 -</div>
455.446 -Python supports a concept of iteration over containers. This is implemented
455.447 -using two distinct methods; these are used to allow user-defined classes to
455.448 -support iteration. Sequences, described below in more detail, always support
455.449 -the iteration methods.
455.450 -
455.451 -<br><br>
455.452 -One method needs to be defined for container objects to provide iteration
455.453 -support:
455.454 -
455.455 -<br><br>
455.456 -.. XXX duplicated in reference/datamodel!
455.457 -
455.458 -<br><br>
455.459 -<a href="meth:container.__iter__()">container.__iter__()</a>
455.460 -
455.461 -<br><br>
455.462 - Return an iterator object. The object is required to support the iterator
455.463 - protocol described below. If a container supports different types of
455.464 - iteration, additional methods can be provided to specifically request
455.465 - iterators for those iteration types. (An example of an object supporting
455.466 - multiple forms of iteration would be a tree structure which supports both
455.467 - breadth-first and depth-first traversal.) This method corresponds to the
455.468 - <code>tp_iter</code> slot of the type structure for Python objects in the Python/C
455.469 - API.
455.470 -
455.471 -<br><br>
455.472 -The iterator objects themselves are required to support the following two
455.473 -methods, which together form the :dfn:`iterator protocol`:
455.474 -
455.475 -<br><br>
455.476 -<a href="meth:iterator.__iter__()">iterator.__iter__()</a>
455.477 -
455.478 -<br><br>
455.479 - Return the iterator object itself. This is required to allow both containers
455.480 - and iterators to be used with the <code style="color:#0000e6;">for</code> and <code style="color:#0000e6;">in</code> statements.
455.481 - This method corresponds to the <code>tp_iter</code> slot of the type structure for
455.482 - Python objects in the Python/C API.
455.483 -
455.484 -<br><br>
455.485 -<a href="meth:iterator.next()">iterator.next()</a>
455.486 -
455.487 -<br><br>
455.488 - Return the next item from the container. If there are no further items, raise
455.489 - the <a href="exc:StopIteration">StopIteration</a> exception. This method corresponds to the
455.490 - <code>tp_iternext</code> slot of the type structure for Python objects in the
455.491 - Python/C API.
455.492 -
455.493 -<br><br>
455.494 -Python defines several iterator objects to support iteration over general and
455.495 -specific sequence types, dictionaries, and other more specialized forms. The
455.496 -specific types are not important beyond their implementation of the iterator
455.497 -protocol.
455.498 -
455.499 -<br><br>
455.500 -The intention of the protocol is that once an iterator's <a href="meth:next">next</a> method
455.501 -raises <a href="exc:StopIteration">StopIteration</a>, it will continue to do so on subsequent calls.
455.502 -Implementations that do not obey this property are deemed broken. (This
455.503 -constraint was added in Python 2.3; in Python 2.2, various iterators are broken
455.504 -according to this rule.)
455.505 -
455.506 -<br><br>
455.507 -Python's :term:<code>generator</code>\s provide a convenient way to implement the iterator
455.508 -protocol. If a container object's <a href="meth:__iter__">__iter__</a> method is implemented as a
455.509 -generator, it will automatically return an iterator object (technically, a
455.510 -generator object) supplying the <a href="meth:__iter__">__iter__</a> and <a href="meth:next">next</a> methods.
455.511 -
455.512 -<br><br>
455.513 -
455.514 -<br><br>
455.515 -<h2>Sequence Types --- <a href="class:str">str</a>, <a href="class:unicode">unicode</a>, <a href="class:list">list</a>, <a href="class:tuple">tuple</a>, <a href="class:buffer">buffer</a>, <a href="class:xrange">xrange</a>
455.516 -</h2>
455.517 -There are six sequence types: strings, Unicode strings, lists, tuples, buffers,
455.518 -and xrange objects.
455.519 -(For other containers see the built in <a href="class:dict">dict</a>, <a href="class:list">list</a>,
455.520 -<a href="class:set">set</a>, and <a href="class:tuple">tuple</a> classes, and the <a href="mod:collections">collections</a>
455.521 -module.)
455.522 -
455.523 -<br><br>
455.524 -String literals are written in single or double quotes: <code>'xyzzy'</code>,
455.525 -<code>"frobozz"</code>. See <code>strings</code> for more about string literals.
455.526 -Unicode strings are much like strings, but are specified in the syntax
455.527 -using a preceding <code>'u'</code> character: <code>u'abc'</code>, <code>u"def"</code>. In addition
455.528 -to the functionality described here, there are also string-specific
455.529 -methods described in the <code>string-methods</code> section. Lists are
455.530 -constructed with square brackets, separating items with commas: <code>[a, b, c]</code>.
455.531 -Tuples are constructed by the comma operator (not within square
455.532 -brackets), with or without enclosing parentheses, but an empty tuple
455.533 -must have the enclosing parentheses, such as <code>a, b, c</code> or <code>()</code>. A
455.534 -single item tuple must have a trailing comma, such as <code>(d,)</code>.
455.535 -
455.536 -<br><br>
455.537 -Buffer objects are not directly supported by Python syntax, but can be created
455.538 -by calling the builtin function <a href="func:buffer">buffer</a>. They don't support
455.539 -concatenation or repetition.
455.540 -
455.541 -<br><br>
455.542 -Objects of type xrange are similar to buffers in that there is no specific syntax to
455.543 -create them, but they are created using the <a href="func:xrange">xrange</a> function. They don't
455.544 -support slicing, concatenation or repetition, and using <code>in</code>, <code>not in</code>,
455.545 -<a href="func:min">min</a> or <a href="func:max">max</a> on them is inefficient.
455.546 -
455.547 -<br><br>
455.548 -Most sequence types support the following operations. The <code>in</code> and <code>not in</code>
455.549 -operations have the same priorities as the comparison operations. The <code>+</code> and
455.550 -<code>*</code> operations have the same priority as the corresponding numeric operations.
455.551 -[#]_ Additional methods are provided for <code>typesseq-mutable</code>.
455.552 -
455.553 -<br><br>
455.554 -This table lists the sequence operations sorted in ascending priority
455.555 -(operations in the same box have the same priority). In the table, <b>s</b> and <b>t</b>
455.556 -are sequences of the same type; <b>n</b>, <b>i</b> and <b>j</b> are integers:
455.557 -
455.558 -<br><br>
455.559 -<pre>+------------------+--------------------------------+----------+
455.560 -| Operation | Result | Notes |
455.561 -+==================+================================+==========+
455.562 -| ``x in s`` | ``True`` if an item of *s* is | \(1) |
455.563 -| | equal to *x*, else ``False`` | |
455.564 -+------------------+--------------------------------+----------+
455.565 -| ``x not in s`` | ``False`` if an item of *s* is | \(1) |
455.566 -| | equal to *x*, else ``True`` | |
455.567 -+------------------+--------------------------------+----------+
455.568 -| ``s + t`` | the concatenation of *s* and | \(6) |
455.569 -| | *t* | |
455.570 -+------------------+--------------------------------+----------+
455.571 -| ``s * n, n * s`` | *n* shallow copies of *s* | \(2) |
455.572 -| | concatenated | |
455.573 -+------------------+--------------------------------+----------+
455.574 -| ``s[i]`` | *i*'th item of *s*, origin 0 | \(3) |
455.575 -+------------------+--------------------------------+----------+
455.576 -| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
455.577 -+------------------+--------------------------------+----------+
455.578 -| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |
455.579 -| | with step *k* | |
455.580 -+------------------+--------------------------------+----------+
455.581 -| ``len(s)`` | length of *s* | |
455.582 -+------------------+--------------------------------+----------+
455.583 -| ``min(s)`` | smallest item of *s* | |
455.584 -+------------------+--------------------------------+----------+
455.585 -| ``max(s)`` | largest item of *s* | |
455.586 -+------------------+--------------------------------+----------+
455.587 -</pre>
455.588 -Sequence types also support comparisons. In particular, tuples and lists
455.589 -are compared lexicographically by comparing corresponding
455.590 -elements. This means that to compare equal, every element must compare
455.591 -equal and the two sequences must be of the same type and have the same
455.592 -length. (For full details see <code>comparisons</code> in the language
455.593 -reference.)
455.594 -
455.595 -<br><br>
455.596 -Notes:
455.597 -(1)
455.598 - When <b>s</b> is a string or Unicode string object the <code>in</code> and <code>not in</code>
455.599 - operations act like a substring test. In Python versions before 2.3, <b>x</b> had to
455.600 - be a string of length 1. In Python 2.3 and beyond, <b>x</b> may be a string of any
455.601 - length.
455.602 -
455.603 -<br><br>
455.604 -(2)
455.605 - Values of <b>n</b> less than <code>0</code> are treated as <code>0</code> (which yields an empty
455.606 - sequence of the same type as <b>s</b>). Note also that the copies are shallow;
455.607 - nested structures are not copied. This often haunts new Python programmers;
455.608 - consider:
455.609 -
455.610 -<br><br>
455.611 -<code>>>> <span style="">lists</span> <span style="">=</span> <span style="">[</span><span style="">[</span><span style="">]</span><span style="">]</span> <span style="">*</span> <span style="color:#000000;">3</span><span style="color:#000000;"><br></span></code><code>>>> <span style="">lists</span><span style="color:#000000;"><br></span></code><code> [[], [], []]</code><br><code>>>> <span style="">lists</span><span style="">[</span><span style="color:#000000;">0</span><span style="">]</span><span style="">.</span><span style="">append</span><span style="">(</span><span style="color:#000000;">3</span><span style="">)</span><span style="color:#000000;"><br></span></code><code>>>> <span style="">lists</span><span style="color:#000000;"><br></span></code><code> [[3], [3], [3]]</code><br>
455.612 -<br><br>
455.613 - What has happened is that <code>[[]]</code> is a one-element list containing an empty
455.614 - list, so all three elements of <code>[[]] * 3</code> are (pointers to) this single empty
455.615 - list. Modifying any of the elements of <code>lists</code> modifies this single list.
455.616 - You can create a list of different lists this way:
455.617 -
455.618 -<br><br>
455.619 -<code>>>> <span style="">lists</span> <span style="">=</span> <span style="">[</span><span style="">[</span><span style="">]</span> <span style="color:#0000e6;">for</span> <span style="">i</span> <span style="color:#0000e6;">in</span> <span style="">range</span><span style="">(</span><span style="color:#000000;">3</span><span style="">)</span><span style="">]</span><span style="color:#000000;"><br></span></code><code>>>> <span style="">lists</span><span style="">[</span><span style="color:#000000;">0</span><span style="">]</span><span style="">.</span><span style="">append</span><span style="">(</span><span style="color:#000000;">3</span><span style="">)</span><span style="color:#000000;"><br></span></code><code>>>> <span style="">lists</span><span style="">[</span><span style="color:#000000;">1</span><span style="">]</span><span style="">.</span><span style="">append</span><span style="">(</span><span style="color:#000000;">5</span><span style="">)</span><span style="color:#000000;"><br></span></code><code>>>> <span style="">lists</span><span style="">[</span><span style="color:#000000;">2</span><span style="">]</span><span style="">.</span><span style="">append</span><span style="">(</span><span style="color:#000000;">7</span><span style="">)</span><span style="color:#000000;"><br></span></code><code>>>> <span style="">lists</span><span style="color:#000000;"><br></span></code><code> [[3], [5], [7]]</code><br>
455.620 -<br><br>
455.621 -(3)
455.622 - If <b>i</b> or <b>j</b> is negative, the index is relative to the end of the string:
455.623 - <code>len(s) + i</code> or <code>len(s) + j</code> is substituted. But note that <code>-0</code> is still
455.624 - <code>0</code>.
455.625 -
455.626 -<br><br>
455.627 -(4)
455.628 - The slice of <b>s</b> from <b>i</b> to <b>j</b> is defined as the sequence of items with index
455.629 - <b>k</b> such that <code>i <= k < j</code>. If <b>i</b> or <b>j</b> is greater than <code>len(s)</code>, use
455.630 - <code>len(s)</code>. If <b>i</b> is omitted or <code>None</code>, use <code>0</code>. If <b>j</b> is omitted or
455.631 - <code>None</code>, use <code>len(s)</code>. If <b>i</b> is greater than or equal to <b>j</b>, the slice is
455.632 - empty.
455.633 -
455.634 -<br><br>
455.635 -(5)
455.636 - The slice of <b>s</b> from <b>i</b> to <b>j</b> with step <b>k</b> is defined as the sequence of
455.637 - items with index <code>x = i + n*k</code> such that <code>0 <= n < (j-i)/k</code>. In other words,
455.638 - the indices are <code>i</code>, <code>i+k</code>, <code>i+2*k</code>, <code>i+3*k</code> and so on, stopping when
455.639 - <b>j</b> is reached (but never including <b>j</b>). If <b>i</b> or <b>j</b> is greater than
455.640 - <code>len(s)</code>, use <code>len(s)</code>. If <b>i</b> or <b>j</b> are omitted or <code>None</code>, they become
455.641 - "end" values (which end depends on the sign of <b>k</b>). Note, <b>k</b> cannot be zero.
455.642 - If <b>k</b> is <code>None</code>, it is treated like <code>1</code>.
455.643 -
455.644 -<br><br>
455.645 -(6)
455.646 - If <b>s</b> and <b>t</b> are both strings, some Python implementations such as CPython can
455.647 - usually perform an in-place optimization for assignments of the form <code>s=s+t</code>
455.648 - or <code>s+=t</code>. When applicable, this optimization makes quadratic run-time much
455.649 - less likely. This optimization is both version and implementation dependent.
455.650 - For performance sensitive code, it is preferable to use the <a href="meth:str.join">str.join</a>
455.651 - method which assures consistent linear concatenation performance across versions
455.652 - and implementations.
455.653 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.4
455.654 - Formerly, string concatenation never occurred in-place.
455.655 -</div>
455.656 -<h3>String Methods
455.657 -</h3>
455.658 -Below are listed the string methods which both 8-bit strings and Unicode objects
455.659 -support. Note that none of these methods take keyword arguments.
455.660 -
455.661 -<br><br>
455.662 -In addition, Python's strings support the sequence type methods
455.663 -described in the <code>typesseq</code> section. To output formatted strings
455.664 -use template strings or the <code>%</code> operator described in the
455.665 -<code>string-formatting</code> section. Also, see the <a href="mod:re">re</a> module for
455.666 -string functions based on regular expressions.
455.667 -
455.668 -<br><br>
455.669 -<a href="meth:str.capitalize()">str.capitalize()</a>
455.670 -
455.671 -<br><br>
455.672 - Return a copy of the string with only its first character capitalized.
455.673 -
455.674 -<br><br>
455.675 - For 8-bit strings, this method is locale-dependent.
455.676 -
455.677 -<br><br>
455.678 -<a href="meth:str.center(width[, fillchar])">str.center(width[, fillchar])</a>
455.679 -
455.680 -<br><br>
455.681 - Return centered in a string of length <b>width</b>. Padding is done using the
455.682 - specified <b>fillchar</b> (default is a space).
455.683 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.4
455.684 - Support for the <b>fillchar</b> argument.
455.685 -</div>
455.686 -<a href="meth:str.count(sub[, start[, end]])">str.count(sub[, start[, end]])</a>
455.687 - Return the number of occurrences of substring <b>sub</b> in the range [<b>start</b>,
455.688 - <b>end</b>]. Optional arguments <b>start</b> and <b>end</b> are interpreted as in slice
455.689 - notation.
455.690 -
455.691 -<br><br>
455.692 -<a href="meth:str.decode([encoding[, errors]])">str.decode([encoding[, errors]])</a>
455.693 -
455.694 -<br><br>
455.695 - Decodes the string using the codec registered for <b>encoding</b>. <b>encoding</b>
455.696 - defaults to the default string encoding. <b>errors</b> may be given to set a
455.697 - different error handling scheme. The default is <code>'strict'</code>, meaning that
455.698 - encoding errors raise <a href="exc:UnicodeError">UnicodeError</a>. Other possible values are
455.699 - <code>'ignore'</code>, <code>'replace'</code> and any other name registered via
455.700 - <a href="func:codecs.register_error">codecs.register_error</a>, see section <code>codec-base-classes</code>.
455.701 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
455.702 -</div>
455.703 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.3
455.704 - Support for other error handling schemes added.
455.705 -</div>
455.706 -<a href="meth:str.encode([encoding[,errors]])">str.encode([encoding[,errors]])</a>
455.707 - Return an encoded version of the string. Default encoding is the current
455.708 - default string encoding. <b>errors</b> may be given to set a different error
455.709 - handling scheme. The default for <b>errors</b> is <code>'strict'</code>, meaning that
455.710 - encoding errors raise a <a href="exc:UnicodeError">UnicodeError</a>. Other possible values are
455.711 - <code>'ignore'</code>, <code>'replace'</code>, <code>'xmlcharrefreplace'</code>, <code>'backslashreplace'</code> and
455.712 - any other name registered via <a href="func:codecs.register_error">codecs.register_error</a>, see section
455.713 - <code>codec-base-classes</code>. For a list of possible encodings, see section
455.714 - <code>standard-encodings</code>.
455.715 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.0
455.716 -</div>
455.717 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.3
455.718 - Support for <code>'xmlcharrefreplace'</code> and <code>'backslashreplace'</code> and other error
455.719 - handling schemes added.
455.720 -</div>
455.721 -<a href="meth:str.endswith(suffix[, start[, end]])">str.endswith(suffix[, start[, end]])</a>
455.722 - Return <code>True</code> if the string ends with the specified <b>suffix</b>, otherwise return
455.723 - <code>False</code>. <b>suffix</b> can also be a tuple of suffixes to look for. With optional
455.724 - <b>start</b>, test beginning at that position. With optional <b>end</b>, stop comparing
455.725 - at that position.
455.726 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.5
455.727 - Accept tuples as <b>suffix</b>.
455.728 -</div>
455.729 -<a href="meth:str.expandtabs([tabsize])">str.expandtabs([tabsize])</a>
455.730 - Return a copy of the string where all tab characters are replaced by one or
455.731 - more spaces, depending on the current column and the given tab size. The
455.732 - column number is reset to zero after each newline occurring in the string.
455.733 - If <b>tabsize</b> is not given, a tab size of <code>8</code> characters is assumed. This
455.734 - doesn't understand other non-printing characters or escape sequences.
455.735 -
455.736 -<br><br>
455.737 -<a href="meth:str.find(sub[, start[, end]])">str.find(sub[, start[, end]])</a>
455.738 -
455.739 -<br><br>
455.740 - Return the lowest index in the string where substring <b>sub</b> is found, such that
455.741 - <b>sub</b> is contained in the range [<b>start</b>, <b>end</b>]. Optional arguments <b>start</b>
455.742 - and <b>end</b> are interpreted as in slice notation. Return <code>-1</code> if <b>sub</b> is not
455.743 - found.
455.744 -
455.745 -<br><br>
455.746 -<a href="meth:str.format(format_string, *args, **kwargs)">str.format(format_string, *args, **kwargs)</a>
455.747 -
455.748 -<br><br>
455.749 - Perform a string formatting operation. The <b>format_string</b> argument can
455.750 - contain literal text or replacement fields delimited by braces <code>{}</code>. Each
455.751 - replacement field contains either the numeric index of a positional argument,
455.752 - or the name of a keyword argument. Returns a copy of <b>format_string</b> where
455.753 - each replacement field is replaced with the string value of the corresponding
455.754 - argument.
455.755 -
455.756 -<br><br>
455.757 -<code>>>> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">The sum of 1 + 2 is {0}</span></span><span style="color:#ce7b00;">"</span><span style="">.</span><span style="">format</span><span style="">(</span><span style="color:#000000;">1</span><span style="">+</span><span style="color:#000000;">2</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> 'The sum of 1 + 2 is 3'</code><br>
455.758 -<br><br>
455.759 - See <code>formatstrings</code> for a description of the various formatting options
455.760 - that can be specified in format strings.
455.761 -
455.762 -<br><br>
455.763 - This method of string formatting is the new standard in Python 3.0, and
455.764 - should be preferred to the <code>%</code> formatting described in
455.765 - <code>string-formatting</code> in new code.
455.766 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
455.767 -</div>
455.768 -<a href="meth:str.index(sub[, start[, end]])">str.index(sub[, start[, end]])</a>
455.769 - Like <a href="meth:find">find</a>, but raise <a href="exc:ValueError">ValueError</a> when the substring is not found.
455.770 -
455.771 -<br><br>
455.772 -<a href="meth:str.isalnum()">str.isalnum()</a>
455.773 -
455.774 -<br><br>
455.775 - Return true if all characters in the string are alphanumeric and there is at
455.776 - least one character, false otherwise.
455.777 -
455.778 -<br><br>
455.779 - For 8-bit strings, this method is locale-dependent.
455.780 -
455.781 -<br><br>
455.782 -<a href="meth:str.isalpha()">str.isalpha()</a>
455.783 -
455.784 -<br><br>
455.785 - Return true if all characters in the string are alphabetic and there is at least
455.786 - one character, false otherwise.
455.787 -
455.788 -<br><br>
455.789 - For 8-bit strings, this method is locale-dependent.
455.790 -
455.791 -<br><br>
455.792 -<a href="meth:str.isdigit()">str.isdigit()</a>
455.793 -
455.794 -<br><br>
455.795 - Return true if all characters in the string are digits and there is at least one
455.796 - character, false otherwise.
455.797 -
455.798 -<br><br>
455.799 - For 8-bit strings, this method is locale-dependent.
455.800 -
455.801 -<br><br>
455.802 -<a href="meth:str.islower()">str.islower()</a>
455.803 -
455.804 -<br><br>
455.805 - Return true if all cased characters in the string are lowercase and there is at
455.806 - least one cased character, false otherwise.
455.807 -
455.808 -<br><br>
455.809 - For 8-bit strings, this method is locale-dependent.
455.810 -
455.811 -<br><br>
455.812 -<a href="meth:str.isspace()">str.isspace()</a>
455.813 -
455.814 -<br><br>
455.815 - Return true if there are only whitespace characters in the string and there is
455.816 - at least one character, false otherwise.
455.817 -
455.818 -<br><br>
455.819 - For 8-bit strings, this method is locale-dependent.
455.820 -
455.821 -<br><br>
455.822 -<a href="meth:str.istitle()">str.istitle()</a>
455.823 -
455.824 -<br><br>
455.825 - Return true if the string is a titlecased string and there is at least one
455.826 - character, for example uppercase characters may only follow uncased characters
455.827 - and lowercase characters only cased ones. Return false otherwise.
455.828 -
455.829 -<br><br>
455.830 - For 8-bit strings, this method is locale-dependent.
455.831 -
455.832 -<br><br>
455.833 -<a href="meth:str.isupper()">str.isupper()</a>
455.834 -
455.835 -<br><br>
455.836 - Return true if all cased characters in the string are uppercase and there is at
455.837 - least one cased character, false otherwise.
455.838 -
455.839 -<br><br>
455.840 - For 8-bit strings, this method is locale-dependent.
455.841 -
455.842 -<br><br>
455.843 -<a href="meth:str.join(seq)">str.join(seq)</a>
455.844 -
455.845 -<br><br>
455.846 - Return a string which is the concatenation of the strings in the sequence <b>seq</b>.
455.847 - The separator between elements is the string providing this method.
455.848 -
455.849 -<br><br>
455.850 -<a href="meth:str.ljust(width[, fillchar])">str.ljust(width[, fillchar])</a>
455.851 -
455.852 -<br><br>
455.853 - Return the string left justified in a string of length <b>width</b>. Padding is done
455.854 - using the specified <b>fillchar</b> (default is a space). The original string is
455.855 - returned if <b>width</b> is less than <code>len(s)</code>.
455.856 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.4
455.857 - Support for the <b>fillchar</b> argument.
455.858 -</div>
455.859 -<a href="meth:str.lower()">str.lower()</a>
455.860 - Return a copy of the string converted to lowercase.
455.861 -
455.862 -<br><br>
455.863 - For 8-bit strings, this method is locale-dependent.
455.864 -
455.865 -<br><br>
455.866 -<a href="meth:str.lstrip([chars])">str.lstrip([chars])</a>
455.867 -
455.868 -<br><br>
455.869 - Return a copy of the string with leading characters removed. The <b>chars</b>
455.870 - argument is a string specifying the set of characters to be removed. If omitted
455.871 - or <code>None</code>, the <b>chars</b> argument defaults to removing whitespace. The <b>chars</b>
455.872 - argument is not a prefix; rather, all combinations of its values are stripped:
455.873 -
455.874 -<br><br>
455.875 -<code>>>> <span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;"> spacious </span></span><span style="color:#ce7b00;">'</span><span style="">.</span><span style="">lstrip</span><span style="">(</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> 'spacious '</code><br><code>>>> <span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#0000ff;">www.example.com</span></span><span style="color:#ce7b00;">'</span><span style="">.</span><span style="">lstrip</span><span style="">(</span><span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">cmowz.</span></span><span style="color:#ce7b00;">'</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> 'example.com'</code><br><div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.2.2
455.876 - Support for the <b>chars</b> argument.
455.877 -</div>
455.878 -<a href="meth:str.partition(sep)">str.partition(sep)</a>
455.879 - Split the string at the first occurrence of <b>sep</b>, and return a 3-tuple
455.880 - containing the part before the separator, the separator itself, and the part
455.881 - after the separator. If the separator is not found, return a 3-tuple containing
455.882 - the string itself, followed by two empty strings.
455.883 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.5
455.884 -</div>
455.885 -<a href="meth:str.replace(old, new[, count])">str.replace(old, new[, count])</a>
455.886 - Return a copy of the string with all occurrences of substring <b>old</b> replaced by
455.887 - <b>new</b>. If the optional argument <b>count</b> is given, only the first <b>count</b>
455.888 - occurrences are replaced.
455.889 -
455.890 -<br><br>
455.891 -<a href="meth:str.rfind(sub [,start [,end]])">str.rfind(sub [,start [,end]])</a>
455.892 -
455.893 -<br><br>
455.894 - Return the highest index in the string where substring <b>sub</b> is found, such that
455.895 - <b>sub</b> is contained within s[start,end]. Optional arguments <b>start</b> and <b>end</b>
455.896 - are interpreted as in slice notation. Return <code>-1</code> on failure.
455.897 -
455.898 -<br><br>
455.899 -<a href="meth:str.rindex(sub[, start[, end]])">str.rindex(sub[, start[, end]])</a>
455.900 -
455.901 -<br><br>
455.902 - Like <a href="meth:rfind">rfind</a> but raises <a href="exc:ValueError">ValueError</a> when the substring <b>sub</b> is not
455.903 - found.
455.904 -
455.905 -<br><br>
455.906 -<a href="meth:str.rjust(width[, fillchar])">str.rjust(width[, fillchar])</a>
455.907 -
455.908 -<br><br>
455.909 - Return the string right justified in a string of length <b>width</b>. Padding is done
455.910 - using the specified <b>fillchar</b> (default is a space). The original string is
455.911 - returned if <b>width</b> is less than <code>len(s)</code>.
455.912 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.4
455.913 - Support for the <b>fillchar</b> argument.
455.914 -</div>
455.915 -<a href="meth:str.rpartition(sep)">str.rpartition(sep)</a>
455.916 - Split the string at the last occurrence of <b>sep</b>, and return a 3-tuple
455.917 - containing the part before the separator, the separator itself, and the part
455.918 - after the separator. If the separator is not found, return a 3-tuple containing
455.919 - two empty strings, followed by the string itself.
455.920 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.5
455.921 -</div>
455.922 -<a href="meth:str.rsplit([sep [,maxsplit]])">str.rsplit([sep [,maxsplit]])</a>
455.923 - Return a list of the words in the string, using <b>sep</b> as the delimiter string.
455.924 - If <b>maxsplit</b> is given, at most <b>maxsplit</b> splits are done, the <b>rightmost</b>
455.925 - ones. If <b>sep</b> is not specified or <code>None</code>, any whitespace string is a
455.926 - separator. Except for splitting from the right, <a href="meth:rsplit">rsplit</a> behaves like
455.927 - <a href="meth:split">split</a> which is described in detail below.
455.928 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.4
455.929 -</div>
455.930 -<a href="meth:str.rstrip([chars])">str.rstrip([chars])</a>
455.931 - Return a copy of the string with trailing characters removed. The <b>chars</b>
455.932 - argument is a string specifying the set of characters to be removed. If omitted
455.933 - or <code>None</code>, the <b>chars</b> argument defaults to removing whitespace. The <b>chars</b>
455.934 - argument is not a suffix; rather, all combinations of its values are stripped:
455.935 -
455.936 -<br><br>
455.937 -<code>>>> <span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;"> spacious </span></span><span style="color:#ce7b00;">'</span><span style="">.</span><span style="">rstrip</span><span style="">(</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> ' spacious'</code><br><code>>>> <span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">mississippi</span></span><span style="color:#ce7b00;">'</span><span style="">.</span><span style="">rstrip</span><span style="">(</span><span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">ipz</span></span><span style="color:#ce7b00;">'</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> 'mississ'</code><br><div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.2.2
455.938 - Support for the <b>chars</b> argument.
455.939 -</div>
455.940 -<a href="meth:str.split([sep[, maxsplit]])">str.split([sep[, maxsplit]])</a>
455.941 - Return a list of the words in the string, using <b>sep</b> as the delimiter
455.942 - string. If <b>maxsplit</b> is given, at most <b>maxsplit</b> splits are done (thus,
455.943 - the list will have at most <code>maxsplit+1</code> elements). If <b>maxsplit</b> is not
455.944 - specified, then there is no limit on the number of splits (all possible
455.945 - splits are made).
455.946 -
455.947 -<br><br>
455.948 - If <b>sep</b> is given, consecutive delimiters are not grouped together and are
455.949 - deemed to delimit empty strings (for example, <code>'1,,2'.split(',')</code> returns
455.950 - <code>['1', '', '2']</code>). The <b>sep</b> argument may consist of multiple characters
455.951 - (for example, <code>'1<>2<>3'.split('<>')</code> returns <code>['1', '2', '3']</code>).
455.952 - Splitting an empty string with a specified separator returns <code>['']</code>.
455.953 -
455.954 -<br><br>
455.955 - If <b>sep</b> is not specified or is <code>None</code>, a different splitting algorithm is
455.956 - applied: runs of consecutive whitespace are regarded as a single separator,
455.957 - and the result will contain no empty strings at the start or end if the
455.958 - string has leading or trailing whitespace. Consequently, splitting an empty
455.959 - string or a string consisting of just whitespace with a <code>None</code> separator
455.960 - returns <code>[]</code>.
455.961 -
455.962 -<br><br>
455.963 - For example, <code>' 1 2 3 '.split()</code> returns <code>['1', '2', '3']</code>, and
455.964 - <code>' 1 2 3 '.split(None, 1)</code> returns <code>['1', '2 3 ']</code>.
455.965 -
455.966 -<br><br>
455.967 -<a href="meth:str.splitlines([keepends])">str.splitlines([keepends])</a>
455.968 -
455.969 -<br><br>
455.970 - Return a list of the lines in the string, breaking at line boundaries. Line
455.971 - breaks are not included in the resulting list unless <b>keepends</b> is given and
455.972 - true.
455.973 -
455.974 -<br><br>
455.975 -<a href="meth:str.startswith(prefix[, start[, end]])">str.startswith(prefix[, start[, end]])</a>
455.976 -
455.977 -<br><br>
455.978 - Return <code>True</code> if string starts with the <b>prefix</b>, otherwise return <code>False</code>.
455.979 - <b>prefix</b> can also be a tuple of prefixes to look for. With optional <b>start</b>,
455.980 - test string beginning at that position. With optional <b>end</b>, stop comparing
455.981 - string at that position.
455.982 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.5
455.983 - Accept tuples as <b>prefix</b>.
455.984 -</div>
455.985 -<a href="meth:str.strip([chars])">str.strip([chars])</a>
455.986 - Return a copy of the string with the leading and trailing characters removed.
455.987 - The <b>chars</b> argument is a string specifying the set of characters to be removed.
455.988 - If omitted or <code>None</code>, the <b>chars</b> argument defaults to removing whitespace.
455.989 - The <b>chars</b> argument is not a prefix or suffix; rather, all combinations of its
455.990 - values are stripped:
455.991 -
455.992 -<br><br>
455.993 -<code>>>> <span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;"> spacious </span></span><span style="color:#ce7b00;">'</span><span style="">.</span><span style="">strip</span><span style="">(</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> 'spacious'</code><br><code>>>> <span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#0000ff;">www.example.com</span></span><span style="color:#ce7b00;">'</span><span style="">.</span><span style="">strip</span><span style="">(</span><span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">cmowz.</span></span><span style="color:#ce7b00;">'</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> 'example'</code><br><div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.2.2
455.994 - Support for the <b>chars</b> argument.
455.995 -</div>
455.996 -<a href="meth:str.swapcase()">str.swapcase()</a>
455.997 - Return a copy of the string with uppercase characters converted to lowercase and
455.998 - vice versa.
455.999 -
455.1000 -<br><br>
455.1001 - For 8-bit strings, this method is locale-dependent.
455.1002 -
455.1003 -<br><br>
455.1004 -<a href="meth:str.title()">str.title()</a>
455.1005 -
455.1006 -<br><br>
455.1007 - Return a titlecased version of the string: words start with uppercase
455.1008 - characters, all remaining cased characters are lowercase.
455.1009 -
455.1010 -<br><br>
455.1011 - For 8-bit strings, this method is locale-dependent.
455.1012 -
455.1013 -<br><br>
455.1014 -<a href="meth:str.translate(table[, deletechars])">str.translate(table[, deletechars])</a>
455.1015 -
455.1016 -<br><br>
455.1017 - Return a copy of the string where all characters occurring in the optional
455.1018 - argument <b>deletechars</b> are removed, and the remaining characters have been
455.1019 - mapped through the given translation table, which must be a string of length
455.1020 - 256.
455.1021 -
455.1022 -<br><br>
455.1023 - You can use the <a href="func:maketrans">maketrans</a> helper function in the <a href="mod:string">string</a> module to
455.1024 - create a translation table. For string objects, set the <b>table</b> argument to
455.1025 - <code>None</code> for translations that only delete characters:
455.1026 -
455.1027 -<br><br>
455.1028 -<code>>>> <span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">read this short text</span></span><span style="color:#ce7b00;">'</span><span style="">.</span><span style="">translate</span><span style="">(</span><span style="">None</span><span style="">,</span> <span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">aeiou</span></span><span style="color:#ce7b00;">'</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> 'rd ths shrt txt'</code><br><div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
455.1029 - Support for a <code>None</code> <b>table</b> argument.
455.1030 -</div>
455.1031 - For Unicode objects, the <a href="meth:translate">translate</a> method does not accept the optional
455.1032 - <b>deletechars</b> argument. Instead, it returns a copy of the <b>s</b> where all
455.1033 - characters have been mapped through the given translation table which must be a
455.1034 - mapping of Unicode ordinals to Unicode ordinals, Unicode strings or <code>None</code>.
455.1035 - Unmapped characters are left untouched. Characters mapped to <code>None</code> are
455.1036 - deleted. Note, a more flexible approach is to create a custom character mapping
455.1037 - codec using the <a href="mod:codecs">codecs</a> module (see <a href="mod:encodings.cp1251">encodings.cp1251</a> for an
455.1038 - example).
455.1039 -
455.1040 -<br><br>
455.1041 -<a href="meth:str.upper()">str.upper()</a>
455.1042 -
455.1043 -<br><br>
455.1044 - Return a copy of the string converted to uppercase.
455.1045 -
455.1046 -<br><br>
455.1047 - For 8-bit strings, this method is locale-dependent.
455.1048 -
455.1049 -<br><br>
455.1050 -<a href="meth:str.zfill(width)">str.zfill(width)</a>
455.1051 -
455.1052 -<br><br>
455.1053 - Return the numeric string left filled with zeros in a string of length
455.1054 - <b>width</b>. A sign prefix is handled correctly. The original string is
455.1055 - returned if <b>width</b> is less than <code>len(s)</code>.
455.1056 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2.2
455.1057 -</div>
455.1058 -The following methods are present only on unicode objects:
455.1059 -<a href="meth:unicode.isnumeric()">unicode.isnumeric()</a>
455.1060 -
455.1061 -<br><br>
455.1062 - Return <code>True</code> if there are only numeric characters in S, <code>False</code>
455.1063 - otherwise. Numeric characters include digit characters, and all characters
455.1064 - that have the Unicode numeric value property, e.g. U+2155,
455.1065 - VULGAR FRACTION ONE FIFTH.
455.1066 -
455.1067 -<br><br>
455.1068 -<a href="meth:unicode.isdecimal()">unicode.isdecimal()</a>
455.1069 -
455.1070 -<br><br>
455.1071 - Return <code>True</code> if there are only decimal characters in S, <code>False</code>
455.1072 - otherwise. Decimal characters include digit characters, and all characters
455.1073 - that that can be used to form decimal-radix numbers, e.g. U+0660,
455.1074 - ARABIC-INDIC DIGIT ZERO.
455.1075 -
455.1076 -<br><br>
455.1077 -
455.1078 -<br><br>
455.1079 -<h3>String Formatting Operations
455.1080 -</h3>
455.1081 -String and Unicode objects have one unique built-in operation: the <code>%</code>
455.1082 -operator (modulo). This is also known as the string <b>formatting</b> or
455.1083 -*interpolation* operator. Given <code>format % values</code> (where <b>format</b> is a string
455.1084 -or Unicode object), <code>%</code> conversion specifications in <b>format</b> are replaced
455.1085 -with zero or more elements of <b>values</b>. The effect is similar to the using
455.1086 -:cfunc:<code>sprintf</code> in the C language. If <b>format</b> is a Unicode object, or if any
455.1087 -of the objects being converted using the <code>%s</code> conversion are Unicode objects,
455.1088 -the result will also be a Unicode object.
455.1089 -
455.1090 -<br><br>
455.1091 -If <b>format</b> requires a single argument, <b>values</b> may be a single non-tuple
455.1092 -object. [#]_ Otherwise, <b>values</b> must be a tuple with exactly the number of
455.1093 -items specified by the format string, or a single mapping object (for example, a
455.1094 -dictionary).
455.1095 -
455.1096 -<br><br>
455.1097 -A conversion specifier contains two or more characters and has the following
455.1098 -components, which must occur in this order:
455.1099 -
455.1100 -<br><br>
455.1101 -#. The <code>'%'</code> character, which marks the start of the specifier.
455.1102 -
455.1103 -<br><br>
455.1104 -#. Mapping key (optional), consisting of a parenthesised sequence of characters
455.1105 - (for example, <code>(somename)</code>).
455.1106 -
455.1107 -<br><br>
455.1108 -#. Conversion flags (optional), which affect the result of some conversion
455.1109 - types.
455.1110 -
455.1111 -<br><br>
455.1112 -#. Minimum field width (optional). If specified as an <code>'*'</code> (asterisk), the
455.1113 - actual width is read from the next element of the tuple in <b>values</b>, and the
455.1114 - object to convert comes after the minimum field width and optional precision.
455.1115 -
455.1116 -<br><br>
455.1117 -#. Precision (optional), given as a <code>'.'</code> (dot) followed by the precision. If
455.1118 - specified as <code>'*'</code> (an asterisk), the actual width is read from the next
455.1119 - element of the tuple in <b>values</b>, and the value to convert comes after the
455.1120 - precision.
455.1121 -
455.1122 -<br><br>
455.1123 -#. Length modifier (optional).
455.1124 -
455.1125 -<br><br>
455.1126 -#. Conversion type.
455.1127 -
455.1128 -<br><br>
455.1129 -When the right argument is a dictionary (or other mapping type), then the
455.1130 -formats in the string <b>must</b> include a parenthesised mapping key into that
455.1131 -dictionary inserted immediately after the <code>'%'</code> character. The mapping key
455.1132 -selects the value to be formatted from the mapping. For example:
455.1133 -
455.1134 -<br><br>
455.1135 -<code>>>> <span style="color:#0000e6;">print</span> <span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">%(language)s has %(#)03d quote types.</span></span><span style="color:#ce7b00;">'</span> <span style="">%</span> <span style="">\</span><span style="color:#000000;"><br></span></code><code> ... {'language': "Python", "#": 2}</code><br><code> Python has 002 quote types.</code><br>
455.1136 -<br><br>
455.1137 -In this case no <code>*</code> specifiers may occur in a format (since they require a
455.1138 -sequential parameter list).
455.1139 -
455.1140 -<br><br>
455.1141 -The conversion flag characters are:
455.1142 -
455.1143 -<br><br>
455.1144 -<pre>+---------+---------------------------------------------------------------------+
455.1145 -| Flag | Meaning |
455.1146 -+=========+=====================================================================+
455.1147 -| ``'#'`` | The value conversion will use the "alternate form" (where defined |
455.1148 -| | below). |
455.1149 -+---------+---------------------------------------------------------------------+
455.1150 -| ``'0'`` | The conversion will be zero padded for numeric values. |
455.1151 -+---------+---------------------------------------------------------------------+
455.1152 -| ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
455.1153 -| | conversion if both are given). |
455.1154 -+---------+---------------------------------------------------------------------+
455.1155 -| ``' '`` | (a space) A blank should be left before a positive number (or empty |
455.1156 -| | string) produced by a signed conversion. |
455.1157 -+---------+---------------------------------------------------------------------+
455.1158 -| ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
455.1159 -| | (overrides a "space" flag). |
455.1160 -+---------+---------------------------------------------------------------------+
455.1161 -</pre>
455.1162 -A length modifier (<code>h</code>, <code>l</code>, or <code>L</code>) may be present, but is ignored as it
455.1163 -is not necessary for Python -- so e.g. <code>%ld</code> is identical to <code>%d</code>.
455.1164 -
455.1165 -<br><br>
455.1166 -The conversion types are:
455.1167 -
455.1168 -<br><br>
455.1169 -<pre>+------------+-----------------------------------------------------+-------+
455.1170 -| Conversion | Meaning | Notes |
455.1171 -+============+=====================================================+=======+
455.1172 -| ``'d'`` | Signed integer decimal. | |
455.1173 -+------------+-----------------------------------------------------+-------+
455.1174 -| ``'i'`` | Signed integer decimal. | |
455.1175 -+------------+-----------------------------------------------------+-------+
455.1176 -| ``'o'`` | Signed octal value. | \(1) |
455.1177 -+------------+-----------------------------------------------------+-------+
455.1178 -| ``'u'`` | Obselete type -- it is identical to ``'d'``. | \(7) |
455.1179 -+------------+-----------------------------------------------------+-------+
455.1180 -| ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
455.1181 -+------------+-----------------------------------------------------+-------+
455.1182 -| ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
455.1183 -+------------+-----------------------------------------------------+-------+
455.1184 -| ``'e'`` | Floating point exponential format (lowercase). | \(3) |
455.1185 -+------------+-----------------------------------------------------+-------+
455.1186 -| ``'E'`` | Floating point exponential format (uppercase). | \(3) |
455.1187 -+------------+-----------------------------------------------------+-------+
455.1188 -| ``'f'`` | Floating point decimal format. | \(3) |
455.1189 -+------------+-----------------------------------------------------+-------+
455.1190 -| ``'F'`` | Floating point decimal format. | \(3) |
455.1191 -+------------+-----------------------------------------------------+-------+
455.1192 -| ``'g'`` | Floating point format. Uses lowercase exponential | \(4) |
455.1193 -| | format if exponent is less than -4 or not less than | |
455.1194 -| | precision, decimal format otherwise. | |
455.1195 -+------------+-----------------------------------------------------+-------+
455.1196 -| ``'G'`` | Floating point format. Uses uppercase exponential | \(4) |
455.1197 -| | format if exponent is less than -4 or not less than | |
455.1198 -| | precision, decimal format otherwise. | |
455.1199 -+------------+-----------------------------------------------------+-------+
455.1200 -| ``'c'`` | Single character (accepts integer or single | |
455.1201 -| | character string). | |
455.1202 -+------------+-----------------------------------------------------+-------+
455.1203 -| ``'r'`` | String (converts any python object using | \(5) |
455.1204 -| | :func:`repr`). | |
455.1205 -+------------+-----------------------------------------------------+-------+
455.1206 -| ``'s'`` | String (converts any python object using | \(6) |
455.1207 -| | :func:`str`). | |
455.1208 -+------------+-----------------------------------------------------+-------+
455.1209 -| ``'%'`` | No argument is converted, results in a ``'%'`` | |
455.1210 -| | character in the result. | |
455.1211 -+------------+-----------------------------------------------------+-------+
455.1212 -</pre>
455.1213 -Notes:
455.1214 -
455.1215 -<br><br>
455.1216 -(1)
455.1217 - The alternate form causes a leading zero (<code>'0'</code>) to be inserted between
455.1218 - left-hand padding and the formatting of the number if the leading character
455.1219 - of the result is not already a zero.
455.1220 -
455.1221 -<br><br>
455.1222 -(2)
455.1223 - The alternate form causes a leading <code>'0x'</code> or <code>'0X'</code> (depending on whether
455.1224 - the <code>'x'</code> or <code>'X'</code> format was used) to be inserted between left-hand padding
455.1225 - and the formatting of the number if the leading character of the result is not
455.1226 - already a zero.
455.1227 -
455.1228 -<br><br>
455.1229 -(3)
455.1230 - The alternate form causes the result to always contain a decimal point, even if
455.1231 - no digits follow it.
455.1232 -
455.1233 -<br><br>
455.1234 - The precision determines the number of digits after the decimal point and
455.1235 - defaults to 6.
455.1236 -
455.1237 -<br><br>
455.1238 -(4)
455.1239 - The alternate form causes the result to always contain a decimal point, and
455.1240 - trailing zeroes are not removed as they would otherwise be.
455.1241 -
455.1242 -<br><br>
455.1243 - The precision determines the number of significant digits before and after the
455.1244 - decimal point and defaults to 6.
455.1245 -
455.1246 -<br><br>
455.1247 -(5)
455.1248 - The <code>%r</code> conversion was added in Python 2.0.
455.1249 -
455.1250 -<br><br>
455.1251 - The precision determines the maximal number of characters used.
455.1252 -
455.1253 -<br><br>
455.1254 -(6)
455.1255 - If the object or format provided is a <a href="class:unicode">unicode</a> string, the resulting
455.1256 - string will also be <a href="class:unicode">unicode</a>.
455.1257 -
455.1258 -<br><br>
455.1259 - The precision determines the maximal number of characters used.
455.1260 -
455.1261 -<br><br>
455.1262 -(7)
455.1263 - See <a href="http://www.python.org/dev/peps/pep-0237/">PEP 237</a>.
455.1264 -
455.1265 -<br><br>
455.1266 -Since Python strings have an explicit length, <code>%s</code> conversions do not assume
455.1267 -that <code>'\0'</code> is the end of the string.
455.1268 -
455.1269 -<br><br>
455.1270 -.. XXX Examples?
455.1271 -
455.1272 -<br><br>
455.1273 -For safety reasons, floating point precisions are clipped to 50; <code>%f</code>
455.1274 -conversions for numbers whose absolute value is over 1e25 are replaced by <code>%g</code>
455.1275 -conversions. [#]_ All other errors raise exceptions.
455.1276 -
455.1277 -<br><br>
455.1278 -Additional string operations are defined in standard modules <a href="mod:string">string</a> and
455.1279 -<a href="mod:re">re</a>.
455.1280 -
455.1281 -<br><br>
455.1282 -
455.1283 -<br><br>
455.1284 -<h3>XRange Type
455.1285 -</h3>
455.1286 -The <a href="class:xrange">xrange</a> type is an immutable sequence which is commonly used for
455.1287 -looping. The advantage of the <a href="class:xrange">xrange</a> type is that an <a href="class:xrange">xrange</a>
455.1288 -object will always take the same amount of memory, no matter the size of the
455.1289 -range it represents. There are no consistent performance advantages.
455.1290 -
455.1291 -<br><br>
455.1292 -XRange objects have very little behavior: they only support indexing, iteration,
455.1293 -and the <a href="func:len">len</a> function.
455.1294 -
455.1295 -<br><br>
455.1296 -
455.1297 -<br><br>
455.1298 -<h3>Mutable Sequence Types
455.1299 -</h3>
455.1300 -List objects support additional operations that allow in-place modification of
455.1301 -the object. Other mutable sequence types (when added to the language) should
455.1302 -also support these operations. Strings and tuples are immutable sequence types:
455.1303 -such objects cannot be modified once created. The following operations are
455.1304 -defined on mutable sequence types (where <b>x</b> is an arbitrary object):
455.1305 -
455.1306 -<br><br>
455.1307 -<pre>+------------------------------+--------------------------------+---------------------+
455.1308 -| Operation | Result | Notes |
455.1309 -+==============================+================================+=====================+
455.1310 -| ``s[i] = x`` | item *i* of *s* is replaced by | |
455.1311 -| | *x* | |
455.1312 -+------------------------------+--------------------------------+---------------------+
455.1313 -| ``s[i:j] = t`` | slice of *s* from *i* to *j* | |
455.1314 -| | is replaced by the contents of | |
455.1315 -| | the iterable *t* | |
455.1316 -+------------------------------+--------------------------------+---------------------+
455.1317 -| ``del s[i:j]`` | same as ``s[i:j] = []`` | |
455.1318 -+------------------------------+--------------------------------+---------------------+
455.1319 -| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) |
455.1320 -| | are replaced by those of *t* | |
455.1321 -+------------------------------+--------------------------------+---------------------+
455.1322 -| ``del s[i:j:k]`` | removes the elements of | |
455.1323 -| | ``s[i:j:k]`` from the list | |
455.1324 -+------------------------------+--------------------------------+---------------------+
455.1325 -| ``s.append(x)`` | same as ``s[len(s):len(s)] = | \(2) |
455.1326 -| | [x]`` | |
455.1327 -+------------------------------+--------------------------------+---------------------+
455.1328 -| ``s.extend(x)`` | same as ``s[len(s):len(s)] = | \(3) |
455.1329 -| | x`` | |
455.1330 -+------------------------------+--------------------------------+---------------------+
455.1331 -| ``s.count(x)`` | return number of *i*'s for | |
455.1332 -| | which ``s[i] == x`` | |
455.1333 -+------------------------------+--------------------------------+---------------------+
455.1334 -| ``s.index(x[, i[, j]])`` | return smallest *k* such that | \(4) |
455.1335 -| | ``s[k] == x`` and ``i <= k < | |
455.1336 -| | j`` | |
455.1337 -+------------------------------+--------------------------------+---------------------+
455.1338 -| ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | \(5) |
455.1339 -+------------------------------+--------------------------------+---------------------+
455.1340 -| ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(6) |
455.1341 -| | return x`` | |
455.1342 -+------------------------------+--------------------------------+---------------------+
455.1343 -| ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(4) |
455.1344 -+------------------------------+--------------------------------+---------------------+
455.1345 -| ``s.reverse()`` | reverses the items of *s* in | \(7) |
455.1346 -| | place | |
455.1347 -+------------------------------+--------------------------------+---------------------+
455.1348 -| ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |
455.1349 -| reverse]]])`` | | |
455.1350 -+------------------------------+--------------------------------+---------------------+
455.1351 -</pre>
455.1352 -Notes:
455.1353 -(1)
455.1354 - <b>t</b> must have the same length as the slice it is replacing.
455.1355 -
455.1356 -<br><br>
455.1357 -(2)
455.1358 - The C implementation of Python has historically accepted multiple parameters and
455.1359 - implicitly joined them into a tuple; this no longer works in Python 2.0. Use of
455.1360 - this misfeature has been deprecated since Python 1.4.
455.1361 -
455.1362 -<br><br>
455.1363 -(3)
455.1364 - <b>x</b> can be any iterable object.
455.1365 -
455.1366 -<br><br>
455.1367 -(4)
455.1368 - Raises <a href="exc:ValueError">ValueError</a> when <b>x</b> is not found in <b>s</b>. When a negative index is
455.1369 - passed as the second or third parameter to the <a href="meth:index">index</a> method, the list
455.1370 - length is added, as for slice indices. If it is still negative, it is truncated
455.1371 - to zero, as for slice indices.
455.1372 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.3
455.1373 - Previously, <a href="meth:index">index</a> didn't have arguments for specifying start and stop
455.1374 - positions.
455.1375 -</div>
455.1376 -(5)
455.1377 - When a negative index is passed as the first parameter to the <a href="meth:insert">insert</a>
455.1378 - method, the list length is added, as for slice indices. If it is still
455.1379 - negative, it is truncated to zero, as for slice indices.
455.1380 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.3
455.1381 - Previously, all negative indices were truncated to zero.
455.1382 -</div>
455.1383 -(6)
455.1384 - The <a href="meth:pop">pop</a> method is only supported by the list and array types. The
455.1385 - optional argument <b>i</b> defaults to <code>-1</code>, so that by default the last item is
455.1386 - removed and returned.
455.1387 -
455.1388 -<br><br>
455.1389 -(7)
455.1390 - The <a href="meth:sort">sort</a> and <a href="meth:reverse">reverse</a> methods modify the list in place for
455.1391 - economy of space when sorting or reversing a large list. To remind you that
455.1392 - they operate by side effect, they don't return the sorted or reversed list.
455.1393 -
455.1394 -<br><br>
455.1395 -(8)
455.1396 - The <a href="meth:sort">sort</a> method takes optional arguments for controlling the
455.1397 - comparisons.
455.1398 -
455.1399 -<br><br>
455.1400 - <b>cmp</b> specifies a custom comparison function of two arguments (list items) which
455.1401 - should return a negative, zero or positive number depending on whether the first
455.1402 - argument is considered smaller than, equal to, or larger than the second
455.1403 - argument: <code>cmp=lambda x,y: cmp(x.lower(), y.lower())</code>. The default value
455.1404 - is <code>None</code>.
455.1405 -
455.1406 -<br><br>
455.1407 - <b>key</b> specifies a function of one argument that is used to extract a comparison
455.1408 - key from each list element: <code>key=str.lower</code>. The default value is <code>None</code>.
455.1409 -
455.1410 -<br><br>
455.1411 - <b>reverse</b> is a boolean value. If set to <code>True</code>, then the list elements are
455.1412 - sorted as if each comparison were reversed.
455.1413 -
455.1414 -<br><br>
455.1415 - In general, the <b>key</b> and <b>reverse</b> conversion processes are much faster than
455.1416 - specifying an equivalent <b>cmp</b> function. This is because <b>cmp</b> is called
455.1417 - multiple times for each list element while <b>key</b> and <b>reverse</b> touch each
455.1418 - element only once.
455.1419 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.3
455.1420 - Support for <code>None</code> as an equivalent to omitting <b>cmp</b> was added.
455.1421 -</div>
455.1422 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.4
455.1423 - Support for <b>key</b> and <b>reverse</b> was added.
455.1424 -</div>
455.1425 -(9)
455.1426 - Starting with Python 2.3, the <a href="meth:sort">sort</a> method is guaranteed to be stable. A
455.1427 - sort is stable if it guarantees not to change the relative order of elements
455.1428 - that compare equal --- this is helpful for sorting in multiple passes (for
455.1429 - example, sort by department, then by salary grade).
455.1430 -
455.1431 -<br><br>
455.1432 -(10)
455.1433 - While a list is being sorted, the effect of attempting to mutate, or even
455.1434 - inspect, the list is undefined. The C implementation of Python 2.3 and newer
455.1435 - makes the list appear empty for the duration, and raises <a href="exc:ValueError">ValueError</a> if it
455.1436 - can detect that the list has been mutated during a sort.
455.1437 -
455.1438 -<br><br>
455.1439 -
455.1440 -<br><br>
455.1441 -<h2>Set Types --- <a href="class:set">set</a>, <a href="class:frozenset">frozenset</a>
455.1442 -</h2>
455.1443 -A :dfn:<code>set</code> object is an unordered collection of distinct :term:<code>hashable</code> objects.
455.1444 -Common uses include membership testing, removing duplicates from a sequence, and
455.1445 -computing mathematical operations such as intersection, union, difference, and
455.1446 -symmetric difference.
455.1447 -(For other containers see the built in <a href="class:dict">dict</a>, <a href="class:list">list</a>,
455.1448 -and <a href="class:tuple">tuple</a> classes, and the <a href="mod:collections">collections</a> module.)
455.1449 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.4
455.1450 -</div>
455.1451 -Like other collections, sets support <code>x in set</code>, <code>len(set)</code>, and ``for x in
455.1452 -set``. Being an unordered collection, sets do not record element position or
455.1453 -order of insertion. Accordingly, sets do not support indexing, slicing, or
455.1454 -other sequence-like behavior.
455.1455 -
455.1456 -<br><br>
455.1457 -There are currently two builtin set types, <a href="class:set">set</a> and <a href="class:frozenset">frozenset</a>.
455.1458 -The <a href="class:set">set</a> type is mutable --- the contents can be changed using methods
455.1459 -like <a href="meth:add">add</a> and <a href="meth:remove">remove</a>. Since it is mutable, it has no hash value
455.1460 -and cannot be used as either a dictionary key or as an element of another set.
455.1461 -The <a href="class:frozenset">frozenset</a> type is immutable and :term:<code>hashable</code> --- its contents cannot be
455.1462 -altered after it is created; it can therefore be used as a dictionary key or as
455.1463 -an element of another set.
455.1464 -
455.1465 -<br><br>
455.1466 -The constructors for both classes work the same:
455.1467 -
455.1468 -<br><br>
455.1469 -<a href="class:set([iterable])">set([iterable])</a>
455.1470 - frozenset([iterable])
455.1471 -
455.1472 -<br><br>
455.1473 - Return a new set or frozenset object whose elements are taken from
455.1474 - <b>iterable</b>. The elements of a set must be hashable. To represent sets of
455.1475 - sets, the inner sets must be <a href="class:frozenset">frozenset</a> objects. If <b>iterable</b> is
455.1476 - not specified, a new empty set is returned.
455.1477 -
455.1478 -<br><br>
455.1479 - Instances of <a href="class:set">set</a> and <a href="class:frozenset">frozenset</a> provide the following
455.1480 - operations:
455.1481 -
455.1482 -<br><br>
455.1483 - .. describe:: len(s)
455.1484 -
455.1485 -<br><br>
455.1486 - Return the cardinality of set <b>s</b>.
455.1487 -
455.1488 -<br><br>
455.1489 - .. describe:: x in s
455.1490 -
455.1491 -<br><br>
455.1492 - Test <b>x</b> for membership in <b>s</b>.
455.1493 -
455.1494 -<br><br>
455.1495 - .. describe:: x not in s
455.1496 -
455.1497 -<br><br>
455.1498 - Test <b>x</b> for non-membership in <b>s</b>.
455.1499 -
455.1500 -<br><br>
455.1501 -<a href="meth:isdisjoint(other)">isdisjoint(other)</a>
455.1502 -
455.1503 -<br><br>
455.1504 - Return True if the set has no elements in common with <b>other</b>. Sets are
455.1505 - disjoint if and only if their intersection is the empty set.
455.1506 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
455.1507 -</div>
455.1508 -<a href="meth:issubset(other)">issubset(other)</a>
455.1509 - set <= other
455.1510 -
455.1511 -<br><br>
455.1512 - Test whether every element in the set is in <b>other</b>.
455.1513 -
455.1514 -<br><br>
455.1515 -<a href="meth:set < other">set < other</a>
455.1516 -
455.1517 -<br><br>
455.1518 - Test whether the set is a true subset of <b>other</b>, that is,
455.1519 - <code>set <= other and set != other</code>.
455.1520 -
455.1521 -<br><br>
455.1522 -<a href="meth:issuperset(other)">issuperset(other)</a>
455.1523 - set >= other
455.1524 -
455.1525 -<br><br>
455.1526 - Test whether every element in <b>other</b> is in the set.
455.1527 -
455.1528 -<br><br>
455.1529 -<a href="meth:set > other">set > other</a>
455.1530 -
455.1531 -<br><br>
455.1532 - Test whether the set is a true superset of <b>other</b>, that is, ``set >=
455.1533 - other and set != other``.
455.1534 -
455.1535 -<br><br>
455.1536 -<a href="meth:union(other, ...)">union(other, ...)</a>
455.1537 - set | other | ...
455.1538 -
455.1539 -<br><br>
455.1540 - Return a new set with elements from both sets.
455.1541 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.6
455.1542 - Accepts multiple input iterables.
455.1543 -</div>
455.1544 -<a href="meth:intersection(other, ...)">intersection(other, ...)</a>
455.1545 - set & other & ...
455.1546 -
455.1547 -<br><br>
455.1548 - Return a new set with elements common to both sets.
455.1549 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.6
455.1550 - Accepts multiple input iterables.
455.1551 -</div>
455.1552 -<a href="meth:difference(other, ...)">difference(other, ...)</a>
455.1553 - set - other - ...
455.1554 -
455.1555 -<br><br>
455.1556 - Return a new set with elements in the set that are not in the others.
455.1557 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.6
455.1558 - Accepts multiple input iterables.
455.1559 -</div>
455.1560 -<a href="meth:symmetric_difference(other)">symmetric_difference(other)</a>
455.1561 - set ^ other
455.1562 -
455.1563 -<br><br>
455.1564 - Return a new set with elements in either the set or <b>other</b> but not both.
455.1565 -
455.1566 -<br><br>
455.1567 -<a href="meth:copy()">copy()</a>
455.1568 -
455.1569 -<br><br>
455.1570 - Return a new set with a shallow copy of <b>s</b>.
455.1571 -
455.1572 -<br><br>
455.1573 - Note, the non-operator versions of <a href="meth:union">union</a>, <a href="meth:intersection">intersection</a>,
455.1574 - <a href="meth:difference">difference</a>, and <a href="meth:symmetric_difference">symmetric_difference</a>, <a href="meth:issubset">issubset</a>, and
455.1575 - <a href="meth:issuperset">issuperset</a> methods will accept any iterable as an argument. In
455.1576 - contrast, their operator based counterparts require their arguments to be
455.1577 - sets. This precludes error-prone constructions like <code>set('abc') & 'cbs'</code>
455.1578 - in favor of the more readable <code>set('abc').intersection('cbs')</code>.
455.1579 -
455.1580 -<br><br>
455.1581 - Both <a href="class:set">set</a> and <a href="class:frozenset">frozenset</a> support set to set comparisons. Two
455.1582 - sets are equal if and only if every element of each set is contained in the
455.1583 - other (each is a subset of the other). A set is less than another set if and
455.1584 - only if the first set is a proper subset of the second set (is a subset, but
455.1585 - is not equal). A set is greater than another set if and only if the first set
455.1586 - is a proper superset of the second set (is a superset, but is not equal).
455.1587 -
455.1588 -<br><br>
455.1589 - Instances of <a href="class:set">set</a> are compared to instances of <a href="class:frozenset">frozenset</a>
455.1590 - based on their members. For example, <code>set('abc') == frozenset('abc')</code>
455.1591 - returns <code>True</code> and so does <code>set('abc') in set([frozenset('abc')])</code>.
455.1592 -
455.1593 -<br><br>
455.1594 - The subset and equality comparisons do not generalize to a complete ordering
455.1595 - function. For example, any two disjoint sets are not equal and are not
455.1596 - subsets of each other, so <b>all</b> of the following return <code>False</code>: <code>a<b</code>,
455.1597 - <code>a==b</code>, or <code>a>b</code>. Accordingly, sets do not implement the <a href="meth:__cmp__">__cmp__</a>
455.1598 - method.
455.1599 -
455.1600 -<br><br>
455.1601 - Since sets only define partial ordering (subset relationships), the output of
455.1602 - the <a href="meth:list.sort">list.sort</a> method is undefined for lists of sets.
455.1603 -
455.1604 -<br><br>
455.1605 - Set elements, like dictionary keys, must be :term:<code>hashable</code>.
455.1606 -
455.1607 -<br><br>
455.1608 - Binary operations that mix <a href="class:set">set</a> instances with <a href="class:frozenset">frozenset</a>
455.1609 - return the type of the first operand. For example: ``frozenset('ab') |
455.1610 - set('bc')`` returns an instance of <a href="class:frozenset">frozenset</a>.
455.1611 -
455.1612 -<br><br>
455.1613 - The following table lists operations available for <a href="class:set">set</a> that do not
455.1614 - apply to immutable instances of <a href="class:frozenset">frozenset</a>:
455.1615 -
455.1616 -<br><br>
455.1617 -<a href="meth:update(other, ...)">update(other, ...)</a>
455.1618 - set |= other | ...
455.1619 -
455.1620 -<br><br>
455.1621 - Update the set, adding elements from <b>other</b>.
455.1622 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.6
455.1623 - Accepts multiple input iterables.
455.1624 -</div>
455.1625 -<a href="meth:intersection_update(other, ...)">intersection_update(other, ...)</a>
455.1626 - set &= other & ...
455.1627 -
455.1628 -<br><br>
455.1629 - Update the set, keeping only elements found in it and <b>other</b>.
455.1630 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.6
455.1631 - Accepts multiple input iterables.
455.1632 -</div>
455.1633 -<a href="meth:difference_update(other, ...)">difference_update(other, ...)</a>
455.1634 - set -= other | ...
455.1635 -
455.1636 -<br><br>
455.1637 - Update the set, removing elements found in others.
455.1638 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.6
455.1639 - Accepts multiple input iterables.
455.1640 -</div>
455.1641 -<a href="meth:symmetric_difference_update(other)">symmetric_difference_update(other)</a>
455.1642 - set ^= other
455.1643 -
455.1644 -<br><br>
455.1645 - Update the set, keeping only elements found in either set, but not in both.
455.1646 -
455.1647 -<br><br>
455.1648 -<a href="meth:add(elem)">add(elem)</a>
455.1649 -
455.1650 -<br><br>
455.1651 - Add element <b>elem</b> to the set.
455.1652 -
455.1653 -<br><br>
455.1654 -<a href="meth:remove(elem)">remove(elem)</a>
455.1655 -
455.1656 -<br><br>
455.1657 - Remove element <b>elem</b> from the set. Raises <a href="exc:KeyError">KeyError</a> if <b>elem</b> is
455.1658 - not contained in the set.
455.1659 -
455.1660 -<br><br>
455.1661 -<a href="meth:discard(elem)">discard(elem)</a>
455.1662 -
455.1663 -<br><br>
455.1664 - Remove element <b>elem</b> from the set if it is present.
455.1665 -
455.1666 -<br><br>
455.1667 -<a href="meth:pop()">pop()</a>
455.1668 -
455.1669 -<br><br>
455.1670 - Remove and return an arbitrary element from the set. Raises
455.1671 - <a href="exc:KeyError">KeyError</a> if the set is empty.
455.1672 -
455.1673 -<br><br>
455.1674 -<a href="meth:clear()">clear()</a>
455.1675 -
455.1676 -<br><br>
455.1677 - Remove all elements from the set.
455.1678 -
455.1679 -<br><br>
455.1680 - Note, the non-operator versions of the <a href="meth:update">update</a>,
455.1681 - <a href="meth:intersection_update">intersection_update</a>, <a href="meth:difference_update">difference_update</a>, and
455.1682 - <a href="meth:symmetric_difference_update">symmetric_difference_update</a> methods will accept any iterable as an
455.1683 - argument.
455.1684 -
455.1685 -<br><br>
455.1686 - Note, the <b>elem</b> argument to the <a href="meth:__contains__">__contains__</a>, <a href="meth:remove">remove</a>, and
455.1687 - <a href="meth:discard">discard</a> methods may be a set. To support searching for an equivalent
455.1688 - frozenset, the <b>elem</b> set is temporarily mutated during the search and then
455.1689 - restored. During the search, the <b>elem</b> set should not be read or mutated
455.1690 - since it does not have a meaningful value.
455.1691 -<div style="margin: 5px 5px; background: #ddffdd; border-size: 1px; padding: 5px"><b>See Also</b>:
455.1692 -
455.1693 -<br><br>
455.1694 - <code>comparison-to-builtin-set</code>
455.1695 - Differences between the <a href="mod:sets">sets</a> module and the built-in set types.
455.1696 -</div>
455.1697 -<h2>Mapping Types --- <a href="class:dict">dict</a>
455.1698 -</h2>
455.1699 -A :dfn:<code>mapping</code> object maps :term:<code>hashable</code> values to arbitrary objects.
455.1700 -Mappings are mutable objects. There is currently only one standard mapping
455.1701 -type, the :dfn:<code>dictionary</code>. (For other containers see the built in
455.1702 -<a href="class:list">list</a>, <a href="class:set">set</a>, and <a href="class:tuple">tuple</a> classes, and the
455.1703 -<a href="mod:collections">collections</a> module.)
455.1704 -
455.1705 -<br><br>
455.1706 -A dictionary's keys are <b>almost</b> arbitrary values. Values that are not
455.1707 -:term:<code>hashable</code>, that is, values containing lists, dictionaries or other
455.1708 -mutable types (that are compared by value rather than by object identity) may
455.1709 -not be used as keys. Numeric types used for keys obey the normal rules for
455.1710 -numeric comparison: if two numbers compare equal (such as <code>1</code> and <code>1.0</code>)
455.1711 -then they can be used interchangeably to index the same dictionary entry. (Note
455.1712 -however, that since computers store floating-point numbers as approximations it
455.1713 -is usually unwise to use them as dictionary keys.)
455.1714 -
455.1715 -<br><br>
455.1716 -Dictionaries can be created by placing a comma-separated list of <code>key: value</code>
455.1717 -pairs within braces, for example: <code>{'jack': 4098, 'sjoerd': 4127}</code> or ``{4098:
455.1718 -'jack', 4127: 'sjoerd'}``, or by the <a href="class:dict">dict</a> constructor.
455.1719 -
455.1720 -<br><br>
455.1721 -<a href="class:dict([arg])">dict([arg])</a>
455.1722 -
455.1723 -<br><br>
455.1724 - Return a new dictionary initialized from an optional positional argument or from
455.1725 - a set of keyword arguments. If no arguments are given, return a new empty
455.1726 - dictionary. If the positional argument <b>arg</b> is a mapping object, return a
455.1727 - dictionary mapping the same keys to the same values as does the mapping object.
455.1728 - Otherwise the positional argument must be a sequence, a container that supports
455.1729 - iteration, or an iterator object. The elements of the argument must each also
455.1730 - be of one of those kinds, and each must in turn contain exactly two objects.
455.1731 - The first is used as a key in the new dictionary, and the second as the key's
455.1732 - value. If a given key is seen more than once, the last value associated with it
455.1733 - is retained in the new dictionary.
455.1734 -
455.1735 -<br><br>
455.1736 - If keyword arguments are given, the keywords themselves with their associated
455.1737 - values are added as items to the dictionary. If a key is specified both in the
455.1738 - positional argument and as a keyword argument, the value associated with the
455.1739 - keyword is retained in the dictionary. For example, these all return a
455.1740 - dictionary equal to <code>{"one": 2, "two": 3}</code>:
455.1741 -
455.1742 -<br><br>
455.1743 - * <code>dict(one=2, two=3)</code>
455.1744 -
455.1745 -<br><br>
455.1746 - * <code>dict({'one': 2, 'two': 3})</code>
455.1747 -
455.1748 -<br><br>
455.1749 - * <code>dict(zip(('one', 'two'), (2, 3)))</code>
455.1750 -
455.1751 -<br><br>
455.1752 - * <code>dict([['two', 3], ['one', 2]])</code>
455.1753 -
455.1754 -<br><br>
455.1755 - The first example only works for keys that are valid Python
455.1756 - identifiers; the others work with any valid keys.
455.1757 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
455.1758 -</div>
455.1759 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.3
455.1760 - Support for building a dictionary from keyword arguments added.
455.1761 -</div>
455.1762 - These are the operations that dictionaries support (and therefore, custom
455.1763 - mapping types should support too):
455.1764 -
455.1765 -<br><br>
455.1766 - .. describe:: len(d)
455.1767 -
455.1768 -<br><br>
455.1769 - Return the number of items in the dictionary <b>d</b>.
455.1770 -
455.1771 -<br><br>
455.1772 - .. describe:: d[key]
455.1773 -
455.1774 -<br><br>
455.1775 - Return the item of <b>d</b> with key <b>key</b>. Raises a <a href="exc:KeyError">KeyError</a> if <b>key</b>
455.1776 - is not in the map.
455.1777 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.5
455.1778 - If a subclass of dict defines a method <a href="meth:__missing__">__missing__</a>, if the key
455.1779 - <b>key</b> is not present, the <code>d[key]</code> operation calls that method with
455.1780 - the key <b>key</b> as argument. The <code>d[key]</code> operation then returns or
455.1781 - raises whatever is returned or raised by the <code>__missing__(key)</code> call
455.1782 - if the key is not present. No other operations or methods invoke
455.1783 - <a href="meth:__missing__">__missing__</a>. If <a href="meth:__missing__">__missing__</a> is not defined,
455.1784 - <a href="exc:KeyError">KeyError</a> is raised. <a href="meth:__missing__">__missing__</a> must be a method; it
455.1785 - cannot be an instance variable. For an example, see
455.1786 - <a href="class:collections.defaultdict">collections.defaultdict</a>.
455.1787 -</div>
455.1788 - .. describe:: d[key] = value
455.1789 - Set <code>d[key]</code> to <b>value</b>.
455.1790 -
455.1791 -<br><br>
455.1792 - .. describe:: del d[key]
455.1793 -
455.1794 -<br><br>
455.1795 - Remove <code>d[key]</code> from <b>d</b>. Raises a <a href="exc:KeyError">KeyError</a> if <b>key</b> is not in the
455.1796 - map.
455.1797 -
455.1798 -<br><br>
455.1799 - .. describe:: key in d
455.1800 -
455.1801 -<br><br>
455.1802 - Return <code>True</code> if <b>d</b> has a key <b>key</b>, else <code>False</code>.
455.1803 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
455.1804 -</div>
455.1805 - .. describe:: key not in d
455.1806 - Equivalent to <code>not key in d</code>.
455.1807 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
455.1808 -</div>
455.1809 -<a href="meth:clear()">clear()</a>
455.1810 - Remove all items from the dictionary.
455.1811 -
455.1812 -<br><br>
455.1813 -<a href="meth:copy()">copy()</a>
455.1814 -
455.1815 -<br><br>
455.1816 - Return a shallow copy of the dictionary.
455.1817 -
455.1818 -<br><br>
455.1819 -<a href="meth:fromkeys(seq[, value])">fromkeys(seq[, value])</a>
455.1820 -
455.1821 -<br><br>
455.1822 - Create a new dictionary with keys from <b>seq</b> and values set to <b>value</b>.
455.1823 -
455.1824 -<br><br>
455.1825 - <a href="func:fromkeys">fromkeys</a> is a class method that returns a new dictionary. <b>value</b>
455.1826 - defaults to <code>None</code>.
455.1827 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.3
455.1828 -</div>
455.1829 -<a href="meth:get(key[, default])">get(key[, default])</a>
455.1830 - Return the value for <b>key</b> if <b>key</b> is in the dictionary, else <b>default</b>.
455.1831 - If <b>default</b> is not given, it defaults to <code>None</code>, so that this method
455.1832 - never raises a <a href="exc:KeyError">KeyError</a>.
455.1833 -
455.1834 -<br><br>
455.1835 -<a href="meth:has_key(key)">has_key(key)</a>
455.1836 -
455.1837 -<br><br>
455.1838 - <code>dict.has_key(key)</code> is equivalent to <code>key in d</code>, but deprecated.
455.1839 -
455.1840 -<br><br>
455.1841 -<a href="meth:items()">items()</a>
455.1842 -
455.1843 -<br><br>
455.1844 - Return a copy of the dictionary's list of <code>(key, value)</code> pairs.
455.1845 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
455.1846 -
455.1847 -<br><br>
455.1848 - Keys and values are listed in an arbitrary order which is non-random,
455.1849 - varies across Python implementations, and depends on the dictionary's
455.1850 - history of insertions and deletions. If <a href="meth:items">items</a>, <a href="meth:keys">keys</a>,
455.1851 - <a href="meth:values">values</a>, <a href="meth:iteritems">iteritems</a>, <a href="meth:iterkeys">iterkeys</a>, and
455.1852 - <a href="meth:itervalues">itervalues</a> are called with no intervening modifications to the
455.1853 - dictionary, the lists will directly correspond. This allows the
455.1854 - creation of <code>(value, key)</code> pairs using <a href="func:zip">zip</a>: ``pairs =
455.1855 - zip(d.values(), d.keys())``. The same relationship holds for the
455.1856 - <a href="meth:iterkeys">iterkeys</a> and <a href="meth:itervalues">itervalues</a> methods: ``pairs =
455.1857 - zip(d.itervalues(), d.iterkeys())`` provides the same value for
455.1858 - <code>pairs</code>. Another way to create the same list is ``pairs = [(v, k) for
455.1859 - (k, v) in d.iteritems()]``.
455.1860 -</div>
455.1861 -<a href="meth:iteritems()">iteritems()</a>
455.1862 - Return an iterator over the dictionary's <code>(key, value)</code> pairs. See the
455.1863 - note for <a href="meth:dict.items">dict.items</a>.
455.1864 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
455.1865 -</div>
455.1866 -<a href="meth:iterkeys()">iterkeys()</a>
455.1867 - Return an iterator over the dictionary's keys. See the note for
455.1868 - <a href="meth:dict.items">dict.items</a>.
455.1869 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
455.1870 -</div>
455.1871 -<a href="meth:itervalues()">itervalues()</a>
455.1872 - Return an iterator over the dictionary's values. See the note for
455.1873 - <a href="meth:dict.items">dict.items</a>.
455.1874 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
455.1875 -</div>
455.1876 -<a href="meth:keys()">keys()</a>
455.1877 - Return a copy of the dictionary's list of keys. See the note for
455.1878 - <a href="meth:dict.items">dict.items</a>.
455.1879 -
455.1880 -<br><br>
455.1881 -<a href="meth:pop(key[, default])">pop(key[, default])</a>
455.1882 -
455.1883 -<br><br>
455.1884 - If <b>key</b> is in the dictionary, remove it and return its value, else return
455.1885 - <b>default</b>. If <b>default</b> is not given and <b>key</b> is not in the dictionary,
455.1886 - a <a href="exc:KeyError">KeyError</a> is raised.
455.1887 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.3
455.1888 -</div>
455.1889 -<a href="meth:popitem()">popitem()</a>
455.1890 - Remove and return an arbitrary <code>(key, value)</code> pair from the dictionary.
455.1891 -
455.1892 -<br><br>
455.1893 - <a href="func:popitem">popitem</a> is useful to destructively iterate over a dictionary, as
455.1894 - often used in set algorithms. If the dictionary is empty, calling
455.1895 - <a href="func:popitem">popitem</a> raises a <a href="exc:KeyError">KeyError</a>.
455.1896 -
455.1897 -<br><br>
455.1898 -<a href="meth:setdefault(key[, default])">setdefault(key[, default])</a>
455.1899 -
455.1900 -<br><br>
455.1901 - If <b>key</b> is in the dictionary, return its value. If not, insert <b>key</b>
455.1902 - with a value of <b>default</b> and return <b>default</b>. <b>default</b> defaults to
455.1903 - <code>None</code>.
455.1904 -
455.1905 -<br><br>
455.1906 -<a href="meth:update([other])">update([other])</a>
455.1907 -
455.1908 -<br><br>
455.1909 - Update the dictionary with the key/value pairs from <b>other</b>, overwriting
455.1910 - existing keys. Return <code>None</code>.
455.1911 -
455.1912 -<br><br>
455.1913 - <a href="func:update">update</a> accepts either another dictionary object or an iterable of
455.1914 - key/value pairs (as a tuple or other iterable of length two). If keyword
455.1915 - arguments are specified, the dictionary is then is updated with those
455.1916 - key/value pairs: <code>d.update(red=1, blue=2)</code>.
455.1917 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.4
455.1918 - Allowed the argument to be an iterable of key/value pairs and allowed
455.1919 - keyword arguments.
455.1920 -</div>
455.1921 -<a href="meth:values()">values()</a>
455.1922 - Return a copy of the dictionary's list of values. See the note for
455.1923 - <a href="meth:dict.items">dict.items</a>.
455.1924 -
455.1925 -<br><br>
455.1926 -
455.1927 -<br><br>
455.1928 -<h2>File Objects
455.1929 -</h2>
455.1930 -File objects are implemented using C's <code>stdio</code> package and can be
455.1931 -created with the built-in <a href="func:open">open</a> function. File
455.1932 -objects are also returned by some other built-in functions and methods,
455.1933 -such as <a href="func:os.popen">os.popen</a> and <a href="func:os.fdopen">os.fdopen</a> and the <a href="meth:makefile">makefile</a>
455.1934 -method of socket objects. Temporary files can be created using the
455.1935 -<a href="mod:tempfile">tempfile</a> module, and high-level file operations such as copying,
455.1936 -moving, and deleting files and directories can be achieved with the
455.1937 -<a href="mod:shutil">shutil</a> module.
455.1938 -
455.1939 -<br><br>
455.1940 -When a file operation fails for an I/O-related reason, the exception
455.1941 -<a href="exc:IOError">IOError</a> is raised. This includes situations where the operation is not
455.1942 -defined for some reason, like <a href="meth:seek">seek</a> on a tty device or writing a file
455.1943 -opened for reading.
455.1944 -
455.1945 -<br><br>
455.1946 -Files have the following methods:
455.1947 -
455.1948 -<br><br>
455.1949 -<a href="meth:file.close()">file.close()</a>
455.1950 -
455.1951 -<br><br>
455.1952 - Close the file. A closed file cannot be read or written any more. Any operation
455.1953 - which requires that the file be open will raise a <a href="exc:ValueError">ValueError</a> after the
455.1954 - file has been closed. Calling <a href="meth:close">close</a> more than once is allowed.
455.1955 -
455.1956 -<br><br>
455.1957 - As of Python 2.5, you can avoid having to call this method explicitly if you use
455.1958 - the <code style="color:#0000e6;">with</code> statement. For example, the following code will
455.1959 - automatically close <b>f</b> when the <code style="color:#0000e6;">with</code> block is exited::
455.1960 -
455.1961 -
455.1962 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
455.1963 - <span style="color:#0000e6;">from</span> <span style="">__future__</span> <span style="color:#0000e6;">import</span> <span style="">with_statement</span> <span style="color:#969696"><span style="color:#969696;"># This isn't required in Python 2.6</span></span><span style="color:#000000;"><br></span> <span style="color:#0000e6;">with</span> <span style="">open</span><span style="">(</span><span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">hello.txt</span></span><span style="color:#ce7b00;">"</span><span style="">)</span> <span style="color:#0000e6;">as</span> <span style="">f</span><span style="">:</span><span style="color:#000000;"><br></span> <span style="color:#0000e6;">for</span> <span style="">line</span> <span style="color:#0000e6;">in</span> <span style="">f</span><span style="">:</span><span style="color:#000000;"><br></span> <span style="color:#0000e6;">print</span> <span style="">line</span><span style="color:#000000;"><br></span></pre>
455.1964 - In older versions of Python, you would have needed to do this to get the same
455.1965 - effect::
455.1966 -
455.1967 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
455.1968 - <span style="">f</span> <span style="">=</span> <span style="">open</span><span style="">(</span><span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">hello.txt</span></span><span style="color:#ce7b00;">"</span><span style="">)</span><span style="color:#000000;"><br></span> <span style="color:#0000e6;">try</span><span style="">:</span><span style="color:#000000;"><br></span> <span style="color:#0000e6;">for</span> <span style="">line</span> <span style="color:#0000e6;">in</span> <span style="">f</span><span style="">:</span><span style="color:#000000;"><br></span> <span style="color:#0000e6;">print</span> <span style="">line</span><span style="color:#000000;"><br></span> <span style="color:#0000e6;">finally</span><span style="">:</span><span style="color:#000000;"><br></span> <span style="">f</span><span style="">.</span><span style="">close</span><span style="">(</span><span style="">)</span><span style="color:#000000;"><br></span></pre>
455.1969 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
455.1970 - Not all "file-like" types in Python support use as a context manager for the
455.1971 - <code style="color:#0000e6;">with</code> statement. If your code is intended to work with any file-like
455.1972 - object, you can use the function <a href="func:contextlib.closing">contextlib.closing</a> instead of using
455.1973 - the object directly.
455.1974 -</div>
455.1975 -<a href="meth:file.flush()">file.flush()</a>
455.1976 - Flush the internal buffer, like <code>stdio</code>'s :cfunc:<code>fflush</code>. This may be a
455.1977 - no-op on some file-like objects.
455.1978 -
455.1979 -<br><br>
455.1980 -<a href="meth:file.fileno()">file.fileno()</a>
455.1981 -
455.1982 -<br><br>
455.1983 - Return the integer "file descriptor" that is used by the underlying
455.1984 - implementation to request I/O operations from the operating system. This can be
455.1985 - useful for other, lower level interfaces that use file descriptors, such as the
455.1986 - <a href="mod:fcntl">fcntl</a> module or <a href="func:os.read">os.read</a> and friends.
455.1987 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
455.1988 -
455.1989 -<br><br>
455.1990 - File-like objects which do not have a real file descriptor should <b>not</b> provide
455.1991 - this method!
455.1992 -</div>
455.1993 -<a href="meth:file.isatty()">file.isatty()</a>
455.1994 - Return <code>True</code> if the file is connected to a tty(-like) device, else <code>False</code>.
455.1995 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
455.1996 -
455.1997 -<br><br>
455.1998 - If a file-like object is not associated with a real file, this method should
455.1999 - <b>not</b> be implemented.
455.2000 -</div>
455.2001 -<a href="meth:file.next()">file.next()</a>
455.2002 - A file object is its own iterator, for example <code>iter(f)</code> returns <b>f</b> (unless
455.2003 - <b>f</b> is closed). When a file is used as an iterator, typically in a
455.2004 - <code style="color:#0000e6;">for</code> loop (for example, <code>for line in f: print line</code>), the
455.2005 - <a href="meth:next">next</a> method is called repeatedly. This method returns the next input
455.2006 - line, or raises <a href="exc:StopIteration">StopIteration</a> when EOF is hit when the file is open for
455.2007 - reading (behavior is undefined when the file is open for writing). In order to
455.2008 - make a <code style="color:#0000e6;">for</code> loop the most efficient way of looping over the lines of a
455.2009 - file (a very common operation), the <a href="meth:next">next</a> method uses a hidden read-ahead
455.2010 - buffer. As a consequence of using a read-ahead buffer, combining <a href="meth:next">next</a>
455.2011 - with other file methods (like <a href="meth:readline">readline</a>) does not work right. However,
455.2012 - using <a href="meth:seek">seek</a> to reposition the file to an absolute position will flush the
455.2013 - read-ahead buffer.
455.2014 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.3
455.2015 -</div>
455.2016 -<a href="meth:file.read([size])">file.read([size])</a>
455.2017 - Read at most <b>size</b> bytes from the file (less if the read hits EOF before
455.2018 - obtaining <b>size</b> bytes). If the <b>size</b> argument is negative or omitted, read
455.2019 - all data until EOF is reached. The bytes are returned as a string object. An
455.2020 - empty string is returned when EOF is encountered immediately. (For certain
455.2021 - files, like ttys, it makes sense to continue reading after an EOF is hit.) Note
455.2022 - that this method may call the underlying C function :cfunc:<code>fread</code> more than
455.2023 - once in an effort to acquire as close to <b>size</b> bytes as possible. Also note
455.2024 - that when in non-blocking mode, less data than was requested may be
455.2025 - returned, even if no <b>size</b> parameter was given.
455.2026 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
455.2027 - This function is simply a wrapper for the underlying
455.2028 - :cfunc:<code>fread</code> C function, and will behave the same in corner cases,
455.2029 - such as whether the EOF value is cached.
455.2030 -</div>
455.2031 -<a href="meth:file.readline([size])">file.readline([size])</a>
455.2032 - Read one entire line from the file. A trailing newline character is kept in the
455.2033 - string (but may be absent when a file ends with an incomplete line). [#]_ If
455.2034 - the <b>size</b> argument is present and non-negative, it is a maximum byte count
455.2035 - (including the trailing newline) and an incomplete line may be returned. An
455.2036 - empty string is returned <b>only</b> when EOF is encountered immediately.
455.2037 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
455.2038 -
455.2039 -<br><br>
455.2040 - Unlike <code>stdio</code>'s :cfunc:<code>fgets</code>, the returned string contains null characters
455.2041 - (<code>'\0'</code>) if they occurred in the input.
455.2042 -</div>
455.2043 -<a href="meth:file.readlines([sizehint])">file.readlines([sizehint])</a>
455.2044 - Read until EOF using <a href="meth:readline">readline</a> and return a list containing the lines
455.2045 - thus read. If the optional <b>sizehint</b> argument is present, instead of
455.2046 - reading up to EOF, whole lines totalling approximately <b>sizehint</b> bytes
455.2047 - (possibly after rounding up to an internal buffer size) are read. Objects
455.2048 - implementing a file-like interface may choose to ignore <b>sizehint</b> if it
455.2049 - cannot be implemented, or cannot be implemented efficiently.
455.2050 -
455.2051 -<br><br>
455.2052 -<a href="meth:file.xreadlines()">file.xreadlines()</a>
455.2053 -
455.2054 -<br><br>
455.2055 - This method returns the same thing as <code>iter(f)</code>.
455.2056 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.1
455.2057 -</div>
455.2058 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Deprecated</b>: 2.3
455.2059 - Use <code>for line in file</code> instead.
455.2060 -</div>
455.2061 -<a href="meth:file.seek(offset[, whence])">file.seek(offset[, whence])</a>
455.2062 - Set the file's current position, like <code>stdio</code>'s :cfunc:<code>fseek</code>. The <b>whence</b>
455.2063 - argument is optional and defaults to <code>os.SEEK_SET</code> or <code>0</code> (absolute file
455.2064 - positioning); other values are <code>os.SEEK_CUR</code> or <code>1</code> (seek relative to the
455.2065 - current position) and <code>os.SEEK_END</code> or <code>2</code> (seek relative to the file's
455.2066 - end). There is no return value.
455.2067 -
455.2068 -<br><br>
455.2069 - For example, <code>f.seek(2, os.SEEK_CUR)</code> advances the position by two and
455.2070 - <code>f.seek(-3, os.SEEK_END)</code> sets the position to the third to last.
455.2071 -
455.2072 -<br><br>
455.2073 - Note that if the file is opened for appending
455.2074 - (mode <code>'a'</code> or <code>'a+'</code>), any <a href="meth:seek">seek</a> operations will be undone at the
455.2075 - next write. If the file is only opened for writing in append mode (mode
455.2076 - <code>'a'</code>), this method is essentially a no-op, but it remains useful for files
455.2077 - opened in append mode with reading enabled (mode <code>'a+'</code>). If the file is
455.2078 - opened in text mode (without <code>'b'</code>), only offsets returned by <a href="meth:tell">tell</a> are
455.2079 - legal. Use of other offsets causes undefined behavior.
455.2080 -
455.2081 -<br><br>
455.2082 - Note that not all file objects are seekable.
455.2083 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.6
455.2084 - Passing float values as offset has been deprecated.
455.2085 -</div>
455.2086 -<a href="meth:file.tell()">file.tell()</a>
455.2087 - Return the file's current position, like <code>stdio</code>'s :cfunc:<code>ftell</code>.
455.2088 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
455.2089 -
455.2090 -<br><br>
455.2091 - On Windows, <a href="meth:tell">tell</a> can return illegal values (after an :cfunc:<code>fgets</code>)
455.2092 - when reading files with Unix-style line-endings. Use binary mode (<code>'rb'</code>) to
455.2093 - circumvent this problem.
455.2094 -</div>
455.2095 -<a href="meth:file.truncate([size])">file.truncate([size])</a>
455.2096 - Truncate the file's size. If the optional <b>size</b> argument is present, the file
455.2097 - is truncated to (at most) that size. The size defaults to the current position.
455.2098 - The current file position is not changed. Note that if a specified size exceeds
455.2099 - the file's current size, the result is platform-dependent: possibilities
455.2100 - include that the file may remain unchanged, increase to the specified size as if
455.2101 - zero-filled, or increase to the specified size with undefined new content.
455.2102 - Availability: Windows, many Unix variants.
455.2103 -
455.2104 -<br><br>
455.2105 -<a href="meth:file.write(str)">file.write(str)</a>
455.2106 -
455.2107 -<br><br>
455.2108 - Write a string to the file. There is no return value. Due to buffering, the
455.2109 - string may not actually show up in the file until the <a href="meth:flush">flush</a> or
455.2110 - <a href="meth:close">close</a> method is called.
455.2111 -
455.2112 -<br><br>
455.2113 -<a href="meth:file.writelines(sequence)">file.writelines(sequence)</a>
455.2114 -
455.2115 -<br><br>
455.2116 - Write a sequence of strings to the file. The sequence can be any iterable
455.2117 - object producing strings, typically a list of strings. There is no return value.
455.2118 - (The name is intended to match <a href="meth:readlines">readlines</a>; <a href="meth:writelines">writelines</a> does not
455.2119 - add line separators.)
455.2120 -
455.2121 -<br><br>
455.2122 -Files support the iterator protocol. Each iteration returns the same result as
455.2123 -<code>file.readline()</code>, and iteration ends when the <a href="meth:readline">readline</a> method returns
455.2124 -an empty string.
455.2125 -
455.2126 -<br><br>
455.2127 -File objects also offer a number of other interesting attributes. These are not
455.2128 -required for file-like objects, but should be implemented if they make sense for
455.2129 -the particular object.
455.2130 -
455.2131 -<br><br>
455.2132 -<a href="attr:file.closed">file.closed</a>
455.2133 -
455.2134 -<br><br>
455.2135 - bool indicating the current state of the file object. This is a read-only
455.2136 - attribute; the <a href="meth:close">close</a> method changes the value. It may not be available
455.2137 - on all file-like objects.
455.2138 -
455.2139 -<br><br>
455.2140 -<a href="attr:file.encoding">file.encoding</a>
455.2141 -
455.2142 -<br><br>
455.2143 - The encoding that this file uses. When Unicode strings are written to a file,
455.2144 - they will be converted to byte strings using this encoding. In addition, when
455.2145 - the file is connected to a terminal, the attribute gives the encoding that the
455.2146 - terminal is likely to use (that information might be incorrect if the user has
455.2147 - misconfigured the terminal). The attribute is read-only and may not be present
455.2148 - on all file-like objects. It may also be <code>None</code>, in which case the file uses
455.2149 - the system default encoding for converting Unicode strings.
455.2150 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.3
455.2151 -</div>
455.2152 -<a href="attr:file.errors">file.errors</a>
455.2153 - The Unicode error handler used along with the encoding.
455.2154 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
455.2155 -</div>
455.2156 -<a href="attr:file.mode">file.mode</a>
455.2157 - The I/O mode for the file. If the file was created using the <a href="func:open">open</a>
455.2158 - built-in function, this will be the value of the <b>mode</b> parameter. This is a
455.2159 - read-only attribute and may not be present on all file-like objects.
455.2160 -
455.2161 -<br><br>
455.2162 -<a href="attr:file.name">file.name</a>
455.2163 -
455.2164 -<br><br>
455.2165 - If the file object was created using <a href="func:open">open</a>, the name of the file.
455.2166 - Otherwise, some string that indicates the source of the file object, of the
455.2167 - form <code><...></code>. This is a read-only attribute and may not be present on all
455.2168 - file-like objects.
455.2169 -
455.2170 -<br><br>
455.2171 -<a href="attr:file.newlines">file.newlines</a>
455.2172 -
455.2173 -<br><br>
455.2174 - If Python was built with the :option:`--with-universal-newlines` option to
455.2175 - :program:<code>configure</code> (the default) this read-only attribute exists, and for
455.2176 - files opened in universal newline read mode it keeps track of the types of
455.2177 - newlines encountered while reading the file. The values it can take are
455.2178 - <code>'\r'</code>, <code>'\n'</code>, <code>'\r\n'</code>, <code>None</code> (unknown, no newlines read yet) or a
455.2179 - tuple containing all the newline types seen, to indicate that multiple newline
455.2180 - conventions were encountered. For files not opened in universal newline read
455.2181 - mode the value of this attribute will be <code>None</code>.
455.2182 -
455.2183 -<br><br>
455.2184 -<a href="attr:file.softspace">file.softspace</a>
455.2185 -
455.2186 -<br><br>
455.2187 - Boolean that indicates whether a space character needs to be printed before
455.2188 - another value when using the <code style="color:#0000e6;">print</code> statement. Classes that are trying
455.2189 - to simulate a file object should also have a writable <code>softspace</code>
455.2190 - attribute, which should be initialized to zero. This will be automatic for most
455.2191 - classes implemented in Python (care may be needed for objects that override
455.2192 - attribute access); types implemented in C will have to provide a writable
455.2193 - <code>softspace</code> attribute.
455.2194 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
455.2195 -
455.2196 -<br><br>
455.2197 - This attribute is not used to control the <code style="color:#0000e6;">print</code> statement, but to
455.2198 - allow the implementation of <code style="color:#0000e6;">print</code> to keep track of its internal
455.2199 - state.
455.2200 -</div>
455.2201 -<h2>Context Manager Types
455.2202 -</h2>
455.2203 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.5
455.2204 -</div>
455.2205 -Python's <code style="color:#0000e6;">with</code> statement supports the concept of a runtime context
455.2206 -defined by a context manager. This is implemented using two separate methods
455.2207 -that allow user-defined classes to define a runtime context that is entered
455.2208 -before the statement body is executed and exited when the statement ends.
455.2209 -
455.2210 -<br><br>
455.2211 -The :dfn:`context management protocol` consists of a pair of methods that need
455.2212 -to be provided for a context manager object to define a runtime context:
455.2213 -
455.2214 -<br><br>
455.2215 -<a href="meth:contextmanager.__enter__()">contextmanager.__enter__()</a>
455.2216 -
455.2217 -<br><br>
455.2218 - Enter the runtime context and return either this object or another object
455.2219 - related to the runtime context. The value returned by this method is bound to
455.2220 - the identifier in the <code style="color:#0000e6;">as</code> clause of <code style="color:#0000e6;">with</code> statements using
455.2221 - this context manager.
455.2222 -
455.2223 -<br><br>
455.2224 - An example of a context manager that returns itself is a file object. File
455.2225 - objects return themselves from __enter__() to allow <a href="func:open">open</a> to be used as
455.2226 - the context expression in a <code style="color:#0000e6;">with</code> statement.
455.2227 -
455.2228 -<br><br>
455.2229 - An example of a context manager that returns a related object is the one
455.2230 - returned by <a href="func:decimal.localcontext">decimal.localcontext</a>. These managers set the active
455.2231 - decimal context to a copy of the original decimal context and then return the
455.2232 - copy. This allows changes to be made to the current decimal context in the body
455.2233 - of the <code style="color:#0000e6;">with</code> statement without affecting code outside the
455.2234 - <code style="color:#0000e6;">with</code> statement.
455.2235 -
455.2236 -<br><br>
455.2237 -<a href="meth:contextmanager.__exit__(exc_type, exc_val, exc_tb)">contextmanager.__exit__(exc_type, exc_val, exc_tb)</a>
455.2238 -
455.2239 -<br><br>
455.2240 - Exit the runtime context and return a Boolean flag indicating if any exception
455.2241 - that occurred should be suppressed. If an exception occurred while executing the
455.2242 - body of the <code style="color:#0000e6;">with</code> statement, the arguments contain the exception type,
455.2243 - value and traceback information. Otherwise, all three arguments are <code>None</code>.
455.2244 -
455.2245 -<br><br>
455.2246 - Returning a true value from this method will cause the <code style="color:#0000e6;">with</code> statement
455.2247 - to suppress the exception and continue execution with the statement immediately
455.2248 - following the <code style="color:#0000e6;">with</code> statement. Otherwise the exception continues
455.2249 - propagating after this method has finished executing. Exceptions that occur
455.2250 - during execution of this method will replace any exception that occurred in the
455.2251 - body of the <code style="color:#0000e6;">with</code> statement.
455.2252 -
455.2253 -<br><br>
455.2254 - The exception passed in should never be reraised explicitly - instead, this
455.2255 - method should return a false value to indicate that the method completed
455.2256 - successfully and does not want to suppress the raised exception. This allows
455.2257 - context management code (such as <code>contextlib.nested</code>) to easily detect whether
455.2258 - or not an <a href="meth:__exit__">__exit__</a> method has actually failed.
455.2259 -
455.2260 -<br><br>
455.2261 -Python defines several context managers to support easy thread synchronisation,
455.2262 -prompt closure of files or other objects, and simpler manipulation of the active
455.2263 -decimal arithmetic context. The specific types are not treated specially beyond
455.2264 -their implementation of the context management protocol. See the
455.2265 -<a href="mod:contextlib">contextlib</a> module for some examples.
455.2266 -
455.2267 -<br><br>
455.2268 -Python's :term:<code>generator</code>\s and the <code>contextlib.contextfactory</code> :term:<code>decorator</code>
455.2269 -provide a convenient way to implement these protocols. If a generator function is
455.2270 -decorated with the <code>contextlib.contextfactory</code> decorator, it will return a
455.2271 -context manager implementing the necessary <a href="meth:__enter__">__enter__</a> and
455.2272 -<a href="meth:__exit__">__exit__</a> methods, rather than the iterator produced by an undecorated
455.2273 -generator function.
455.2274 -
455.2275 -<br><br>
455.2276 -Note that there is no specific slot for any of these methods in the type
455.2277 -structure for Python objects in the Python/C API. Extension types wanting to
455.2278 -define these methods must provide them as a normal Python accessible method.
455.2279 -Compared to the overhead of setting up the runtime context, the overhead of a
455.2280 -single class dictionary lookup is negligible.
455.2281 -
455.2282 -<br><br>
455.2283 -
455.2284 -<br><br>
455.2285 -<h2>Other Built-in Types
455.2286 -</h2>
455.2287 -The interpreter supports several other kinds of objects. Most of these support
455.2288 -only one or two operations.
455.2289 -
455.2290 -<br><br>
455.2291 -
455.2292 -<br><br>
455.2293 -<h3>Modules
455.2294 -</h3>
455.2295 -The only special operation on a module is attribute access: <code>m.name</code>, where
455.2296 -*m* is a module and <b>name</b> accesses a name defined in <b>m</b>'s symbol table.
455.2297 -Module attributes can be assigned to. (Note that the <code style="color:#0000e6;">import</code>
455.2298 -statement is not, strictly speaking, an operation on a module object; ``import
455.2299 -foo`` does not require a module object named <b>foo</b> to exist, rather it requires
455.2300 -an (external) <b>definition</b> for a module named <b>foo</b> somewhere.)
455.2301 -
455.2302 -<br><br>
455.2303 -A special member of every module is <code>__dict__</code>. This is the dictionary
455.2304 -containing the module's symbol table. Modifying this dictionary will actually
455.2305 -change the module's symbol table, but direct assignment to the <code>__dict__</code>
455.2306 -attribute is not possible (you can write <code>m.__dict__['a'] = 1</code>, which defines
455.2307 -<code>m.a</code> to be <code>1</code>, but you can't write <code>m.__dict__ = {}</code>). Modifying
455.2308 -<code>__dict__</code> directly is not recommended.
455.2309 -
455.2310 -<br><br>
455.2311 -Modules built into the interpreter are written like this: ``<module 'sys'
455.2312 -(built-in)><code>. If loaded from a file, they are written as </code><module 'os' from
455.2313 -'/usr/local/lib/pythonX.Y/os.pyc'>``.
455.2314 -
455.2315 -<br><br>
455.2316 -
455.2317 -<br><br>
455.2318 -<h3>Classes and Class Instances
455.2319 -</h3>
455.2320 -See <code>objects</code> and <code>class</code> for these.
455.2321 -
455.2322 -<br><br>
455.2323 -
455.2324 -<br><br>
455.2325 -<h3>Functions
455.2326 -</h3>
455.2327 -Function objects are created by function definitions. The only operation on a
455.2328 -function object is to call it: <code>func(argument-list)</code>.
455.2329 -
455.2330 -<br><br>
455.2331 -There are really two flavors of function objects: built-in functions and
455.2332 -user-defined functions. Both support the same operation (to call the function),
455.2333 -but the implementation is different, hence the different object types.
455.2334 -
455.2335 -<br><br>
455.2336 -See <code>function</code> for more information.
455.2337 -
455.2338 -<br><br>
455.2339 -
455.2340 -<br><br>
455.2341 -<h3>Methods
455.2342 -</h3>
455.2343 -Methods are functions that are called using the attribute notation. There are
455.2344 -two flavors: built-in methods (such as <a href="meth:append">append</a> on lists) and class
455.2345 -instance methods. Built-in methods are described with the types that support
455.2346 -them.
455.2347 -
455.2348 -<br><br>
455.2349 -The implementation adds two special read-only attributes to class instance
455.2350 -methods: <code>m.im_self</code> is the object on which the method operates, and
455.2351 -<code>m.im_func</code> is the function implementing the method. Calling ``m(arg-1,
455.2352 -arg-2, ..., arg-n)<code> is completely equivalent to calling </code>m.im_func(m.im_self,
455.2353 -arg-1, arg-2, ..., arg-n)``.
455.2354 -
455.2355 -<br><br>
455.2356 -Class instance methods are either <b>bound</b> or <b>unbound</b>, referring to whether the
455.2357 -method was accessed through an instance or a class, respectively. When a method
455.2358 -is unbound, its <code>im_self</code> attribute will be <code>None</code> and if called, an
455.2359 -explicit <code>self</code> object must be passed as the first argument. In this case,
455.2360 -<code>self</code> must be an instance of the unbound method's class (or a subclass of
455.2361 -that class), otherwise a <a href="exc:TypeError">TypeError</a> is raised.
455.2362 -
455.2363 -<br><br>
455.2364 -Like function objects, methods objects support getting arbitrary attributes.
455.2365 -However, since method attributes are actually stored on the underlying function
455.2366 -object (<code>meth.im_func</code>), setting method attributes on either bound or unbound
455.2367 -methods is disallowed. Attempting to set a method attribute results in a
455.2368 -<a href="exc:TypeError">TypeError</a> being raised. In order to set a method attribute, you need to
455.2369 -explicitly set it on the underlying function object::
455.2370 -
455.2371 -
455.2372 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
455.2373 - <span style="color:#0000e6;">class</span> <span style="">C</span><span style="">:</span><span style="color:#000000;"><br></span> <span style="color:#0000e6;">def</span> <span style="">method</span><span style="">(</span><span style="">self</span><span style="">)</span><span style="">:</span><span style="color:#000000;"><br></span> <span style="color:#0000e6;">pass</span><span style="color:#000000;"><br></span> <span style="">c</span> <span style="">=</span> <span style="">C</span><span style="">(</span><span style="">)</span><span style="color:#000000;"><br></span> <span style="">c</span><span style="">.</span><span style="">method</span><span style="">.</span><span style="">im_func</span><span style="">.</span><span style="">whoami</span> <span style="">=</span> <span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">my name is c</span></span><span style="color:#ce7b00;">'</span><span style="color:#000000;"><br></span></pre>
455.2374 -See <code>types</code> for more information.
455.2375 -
455.2376 -<br><br>
455.2377 -<h3>Code Objects
455.2378 -</h3>
455.2379 -Code objects are used by the implementation to represent "pseudo-compiled"
455.2380 -executable Python code such as a function body. They differ from function
455.2381 -objects because they don't contain a reference to their global execution
455.2382 -environment. Code objects are returned by the built-in <a href="func:compile">compile</a> function
455.2383 -and can be extracted from function objects through their <code>func_code</code>
455.2384 -attribute. See also the <a href="mod:code">code</a> module.
455.2385 -
455.2386 -<br><br>
455.2387 -A code object can be executed or evaluated by passing it (instead of a source
455.2388 -string) to the <code style="color:#0000e6;">exec</code> statement or the built-in <a href="func:eval">eval</a> function.
455.2389 -
455.2390 -<br><br>
455.2391 -See <code>types</code> for more information.
455.2392 -
455.2393 -<br><br>
455.2394 -
455.2395 -<br><br>
455.2396 -<h3>Type Objects
455.2397 -</h3>
455.2398 -Type objects represent the various object types. An object's type is accessed
455.2399 -by the built-in function <a href="func:type">type</a>. There are no special operations on
455.2400 -types. The standard module <a href="mod:types">types</a> defines names for all standard built-in
455.2401 -types.
455.2402 -
455.2403 -<br><br>
455.2404 -Types are written like this: <code><type 'int'></code>.
455.2405 -
455.2406 -<br><br>
455.2407 -
455.2408 -<br><br>
455.2409 -<h3>The Null Object
455.2410 -</h3>
455.2411 -This object is returned by functions that don't explicitly return a value. It
455.2412 -supports no special operations. There is exactly one null object, named
455.2413 -<code>None</code> (a built-in name).
455.2414 -
455.2415 -<br><br>
455.2416 -It is written as <code>None</code>.
455.2417 -
455.2418 -<br><br>
455.2419 -
455.2420 -<br><br>
455.2421 -<h3>The Ellipsis Object
455.2422 -</h3>
455.2423 -This object is used by extended slice notation (see <code>slicings</code>). It
455.2424 -supports no special operations. There is exactly one ellipsis object, named
455.2425 -:const:<code>Ellipsis</code> (a built-in name).
455.2426 -
455.2427 -<br><br>
455.2428 -It is written as <code>Ellipsis</code>.
455.2429 -
455.2430 -<br><br>
455.2431 -<h3>Boolean Values
455.2432 -</h3>
455.2433 -Boolean values are the two constant objects <code>False</code> and <code>True</code>. They are
455.2434 -used to represent truth values (although other values can also be considered
455.2435 -false or true). In numeric contexts (for example when used as the argument to
455.2436 -an arithmetic operator), they behave like the integers 0 and 1, respectively.
455.2437 -The built-in function <a href="func:bool">bool</a> can be used to cast any value to a Boolean,
455.2438 -if the value can be interpreted as a truth value (see section Truth Value
455.2439 -Testing above).
455.2440 -
455.2441 -<br><br>
455.2442 -They are written as <code>False</code> and <code>True</code>, respectively.
455.2443 -
455.2444 -<br><br>
455.2445 -<h3>Internal Objects
455.2446 -</h3>
455.2447 -See <code>types</code> for this information. It describes stack frame objects,
455.2448 -traceback objects, and slice objects.
455.2449 -
455.2450 -<br><br>
455.2451 -
455.2452 -<br><br>
455.2453 -<h2>Special Attributes
455.2454 -</h2>
455.2455 -The implementation adds a few special read-only attributes to several object
455.2456 -types, where they are relevant. Some of these are not reported by the
455.2457 -<a href="func:dir">dir</a> built-in function.
455.2458 -
455.2459 -<br><br>
455.2460 -<a href="attr:object.__dict__">object.__dict__</a>
455.2461 -
455.2462 -<br><br>
455.2463 - A dictionary or other mapping object used to store an object's (writable)
455.2464 - attributes.
455.2465 -
455.2466 -<br><br>
455.2467 -<a href="attr:object.__methods__">object.__methods__</a>
455.2468 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Deprecated</b>: 2.2
455.2469 - Use the built-in function <a href="func:dir">dir</a> to get a list of an object's attributes.
455.2470 - This attribute is no longer available.
455.2471 -</div>
455.2472 -<a href="attr:object.__members__">object.__members__</a>
455.2473 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Deprecated</b>: 2.2
455.2474 - Use the built-in function <a href="func:dir">dir</a> to get a list of an object's attributes.
455.2475 - This attribute is no longer available.
455.2476 -</div>
455.2477 -<a href="attr:instance.__class__">instance.__class__</a>
455.2478 - The class to which a class instance belongs.
455.2479 -
455.2480 -<br><br>
455.2481 -<a href="attr:class.__bases__">class.__bases__</a>
455.2482 -
455.2483 -<br><br>
455.2484 - The tuple of base classes of a class object. If there are no base classes, this
455.2485 - will be an empty tuple.
455.2486 -
455.2487 -<br><br>
455.2488 -<a href="attr:class.__name__">class.__name__</a>
455.2489 -
455.2490 -<br><br>
455.2491 - The name of the class or type.
455.2492 -
455.2493 -<br><br>
455.2494 -.. rubric:: Footnotes
455.2495 -
455.2496 -<br><br>
455.2497 -.. [#] Additional information on these special methods may be found in the Python
455.2498 - Reference Manual (<code>customization</code>).
455.2499 -
455.2500 -<br><br>
455.2501 -.. [#] As a consequence, the list <code>[1, 2]</code> is considered equal to <code>[1.0, 2.0]</code>, and
455.2502 - similarly for tuples.
455.2503 -
455.2504 -<br><br>
455.2505 -.. [#] They must have since the parser can't tell the type of the operands.
455.2506 -
455.2507 -<br><br>
455.2508 -.. [#] To format only a tuple you should therefore provide a singleton tuple whose only
455.2509 - element is the tuple to be formatted.
455.2510 -
455.2511 -<br><br>
455.2512 -.. [#] These numbers are fairly arbitrary. They are intended to avoid printing endless
455.2513 - strings of meaningless digits without hampering correct use and without having
455.2514 - to know the exact precision of floating point values on a particular machine.
455.2515 -
455.2516 -<br><br>
455.2517 -.. [#] The advantage of leaving the newline on is that returning an empty string is
455.2518 - then an unambiguous EOF indication. It is also possible (in cases where it
455.2519 - might matter, for example, if you want to make an exact copy of a file while
455.2520 - scanning its lines) to tell whether the last line of a file ended in a newline
455.2521 - or not (yes this happens!).
455.2522 -</body></html>
456.1 --- a/python.editor/test/unit/data/testfiles/rst/stdtypes.rst.indexed Sun Jan 04 13:11:53 2015 -0600
456.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
456.3 @@ -1,241 +0,0 @@
456.4 -
456.5 -
456.6 -Document 0
456.7 -Searchable Keys:
456.8 - class : class
456.9 - class-ig : class
456.10 - in : stdtypes
456.11 - member : __bases__;A;|DOCUMENTED|DOC_ONLY|;
456.12 - member : __name__;A;|DOCUMENTED|DOC_ONLY|;
456.13 -
456.14 -Not Searchable Keys:
456.15 -
456.16 -
456.17 -Document 1
456.18 -Searchable Keys:
456.19 - class : container
456.20 - class-ig : container
456.21 - in : stdtypes
456.22 - member : __iter__;F;|DOCUMENTED|DOC_ONLY|;;
456.23 -
456.24 -Not Searchable Keys:
456.25 -
456.26 -
456.27 -Document 2
456.28 -Searchable Keys:
456.29 - class : contextmanager
456.30 - class-ig : contextmanager
456.31 - in : stdtypes
456.32 - member : __enter__;F;|DOCUMENTED|DOC_ONLY|;;
456.33 - member : __exit__;F;|DOCUMENTED|DOC_ONLY|;exc_type,exc_val,exc_tb;
456.34 -
456.35 -Not Searchable Keys:
456.36 -
456.37 -
456.38 -Document 3
456.39 -Searchable Keys:
456.40 - class : dict
456.41 - class-ig : dict
456.42 - in : stdtypes
456.43 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;arg;
456.44 - member : clear;F;|DOCUMENTED|DOC_ONLY|;;
456.45 - member : copy;F;|DOCUMENTED|DOC_ONLY|;;
456.46 - member : fromkeys;F;|DOCUMENTED|DOC_ONLY|;seq,value;
456.47 - member : get;F;|DOCUMENTED|DOC_ONLY|;key,default;
456.48 - member : has_key;F;|DOCUMENTED|DOC_ONLY|;key;
456.49 - member : items;F;|DOCUMENTED|DOC_ONLY|;;
456.50 - member : iteritems;F;|DOCUMENTED|DOC_ONLY|;;
456.51 - member : iterkeys;F;|DOCUMENTED|DOC_ONLY|;;
456.52 - member : itervalues;F;|DOCUMENTED|DOC_ONLY|;;
456.53 - member : keys;F;|DOCUMENTED|DOC_ONLY|;;
456.54 - member : pop;F;|DOCUMENTED|DOC_ONLY|;key,default;
456.55 - member : popitem;F;|DOCUMENTED|DOC_ONLY|;;
456.56 - member : setdefault;F;|DOCUMENTED|DOC_ONLY|;key,default;
456.57 - member : update;F;|DOCUMENTED|DOC_ONLY|;other;
456.58 - member : values;F;|DOCUMENTED|DOC_ONLY|;;
456.59 -
456.60 -Not Searchable Keys:
456.61 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
456.62 -
456.63 -
456.64 -Document 4
456.65 -Searchable Keys:
456.66 - class : file
456.67 - class-ig : file
456.68 - in : stdtypes
456.69 - member : close;F;|DOCUMENTED|DOC_ONLY|;;
456.70 - member : closed;A;|DOCUMENTED|DOC_ONLY|;
456.71 - member : encoding;A;|DOCUMENTED|DOC_ONLY|;
456.72 - member : errors;A;|DOCUMENTED|DOC_ONLY|;
456.73 - member : fileno;F;|DOCUMENTED|DOC_ONLY|;;
456.74 - member : flush;F;|DOCUMENTED|DOC_ONLY|;;
456.75 - member : isatty;F;|DOCUMENTED|DOC_ONLY|;;
456.76 - member : mode;A;|DOCUMENTED|DOC_ONLY|;
456.77 - member : name;A;|DOCUMENTED|DOC_ONLY|;
456.78 - member : newlines;A;|DOCUMENTED|DOC_ONLY|;
456.79 - member : next;F;|DOCUMENTED|DOC_ONLY|;;
456.80 - member : read;F;|DOCUMENTED|DOC_ONLY|;size;
456.81 - member : readline;F;|DOCUMENTED|DOC_ONLY|;size;
456.82 - member : readlines;F;|DOCUMENTED|DOC_ONLY|;sizehint;
456.83 - member : seek;F;|DOCUMENTED|DOC_ONLY|;offset,whence;
456.84 - member : softspace;A;|DOCUMENTED|DOC_ONLY|;
456.85 - member : tell;F;|DOCUMENTED|DOC_ONLY|;;
456.86 - member : truncate;F;|DOCUMENTED|DOC_ONLY|;size;
456.87 - member : write;F;|DOCUMENTED|DOC_ONLY|;str;
456.88 - member : writelines;F;|DOCUMENTED|DOC_ONLY|;sequence;
456.89 - member : xreadlines;F;|DOCUMENTED|DEPRECATED|DOC_ONLY|;;
456.90 -
456.91 -Not Searchable Keys:
456.92 -
456.93 -
456.94 -Document 5
456.95 -Searchable Keys:
456.96 - class : float
456.97 - class-ig : float
456.98 - in : stdtypes
456.99 - member : as_integer_ratio;F;|DOCUMENTED|DOC_ONLY|;;
456.100 - member : fromhex;F;|DOCUMENTED|DOC_ONLY|;s;
456.101 - member : hex;F;|DOCUMENTED|DOC_ONLY|;;
456.102 -
456.103 -Not Searchable Keys:
456.104 -
456.105 -
456.106 -Document 6
456.107 -Searchable Keys:
456.108 - class : instance
456.109 - class-ig : instance
456.110 - in : stdtypes
456.111 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
456.112 -
456.113 -Not Searchable Keys:
456.114 -
456.115 -
456.116 -Document 7
456.117 -Searchable Keys:
456.118 - class : iterator
456.119 - class-ig : iterator
456.120 - in : stdtypes
456.121 - member : __iter__;F;|DOCUMENTED|DOC_ONLY|;;
456.122 - member : next;F;|DOCUMENTED|DOC_ONLY|;;
456.123 -
456.124 -Not Searchable Keys:
456.125 -
456.126 -
456.127 -Document 8
456.128 -Searchable Keys:
456.129 - class : object
456.130 - class-ig : object
456.131 - in : stdtypes
456.132 - member : __dict__;A;|DOCUMENTED|DOC_ONLY|;
456.133 - member : __members__;A;|DOCUMENTED|DEPRECATED|DOC_ONLY|;
456.134 - member : __methods__;A;|DOCUMENTED|DEPRECATED|DOC_ONLY|;
456.135 -
456.136 -Not Searchable Keys:
456.137 -
456.138 -
456.139 -Document 9
456.140 -Searchable Keys:
456.141 - class : set
456.142 - class-ig : set
456.143 - in : stdtypes
456.144 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;iterable;
456.145 - member : add;F;|DOCUMENTED|DOC_ONLY|;elem;
456.146 - member : clear;F;|DOCUMENTED|DOC_ONLY|;;
456.147 - member : copy;F;|DOCUMENTED|DOC_ONLY|;;
456.148 - member : difference;F;|DOCUMENTED|DOC_ONLY|;other;
456.149 - member : difference_update;F;|DOCUMENTED|DOC_ONLY|;other;
456.150 - member : discard;F;|DOCUMENTED|DOC_ONLY|;elem;
456.151 - member : intersection;F;|DOCUMENTED|DOC_ONLY|;other;
456.152 - member : intersection_update;F;|DOCUMENTED|DOC_ONLY|;other;
456.153 - member : isdisjoint;F;|DOCUMENTED|DOC_ONLY|;other;
456.154 - member : issubset;F;|DOCUMENTED|DOC_ONLY|;other;
456.155 - member : issuperset;F;|DOCUMENTED|DOC_ONLY|;other;
456.156 - member : pop;F;|DOCUMENTED|DOC_ONLY|;;
456.157 - member : remove;F;|DOCUMENTED|DOC_ONLY|;elem;
456.158 - member : set<other;F;|DOCUMENTED|DOC_ONLY|;;
456.159 - member : set>other;F;|DOCUMENTED|DOC_ONLY|;;
456.160 - member : symmetric_difference;F;|DOCUMENTED|DOC_ONLY|;other;
456.161 - member : symmetric_difference_update;F;|DOCUMENTED|DOC_ONLY|;other;
456.162 - member : union;F;|DOCUMENTED|DOC_ONLY|;other;
456.163 - member : update;F;|DOCUMENTED|DOC_ONLY|;other;
456.164 -
456.165 -Not Searchable Keys:
456.166 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
456.167 -
456.168 -
456.169 -Document 10
456.170 -Searchable Keys:
456.171 - class : str
456.172 - class-ig : str
456.173 - in : stdtypes
456.174 - member : capitalize;F;|DOCUMENTED|DOC_ONLY|;;
456.175 - member : center;F;|DOCUMENTED|DOC_ONLY|;width,fillchar;
456.176 - member : count;F;|DOCUMENTED|DOC_ONLY|;sub,start,end;
456.177 - member : decode;F;|DOCUMENTED|DOC_ONLY|;encoding,errors;
456.178 - member : encode;F;|DOCUMENTED|DOC_ONLY|;encoding,errors;
456.179 - member : endswith;F;|DOCUMENTED|DOC_ONLY|;suffix,start,end;
456.180 - member : expandtabs;F;|DOCUMENTED|DOC_ONLY|;tabsize;
456.181 - member : find;F;|DOCUMENTED|DOC_ONLY|;sub,start,end;
456.182 - member : format;F;|DOCUMENTED|DOC_ONLY|;format_string,*args,**kwargs;
456.183 - member : index;F;|DOCUMENTED|DOC_ONLY|;sub,start,end;
456.184 - member : isalnum;F;|DOCUMENTED|DOC_ONLY|;;
456.185 - member : isalpha;F;|DOCUMENTED|DOC_ONLY|;;
456.186 - member : isdigit;F;|DOCUMENTED|DOC_ONLY|;;
456.187 - member : islower;F;|DOCUMENTED|DOC_ONLY|;;
456.188 - member : isspace;F;|DOCUMENTED|DOC_ONLY|;;
456.189 - member : istitle;F;|DOCUMENTED|DOC_ONLY|;;
456.190 - member : isupper;F;|DOCUMENTED|DOC_ONLY|;;
456.191 - member : join;F;|DOCUMENTED|DOC_ONLY|;seq;
456.192 - member : ljust;F;|DOCUMENTED|DOC_ONLY|;width,fillchar;
456.193 - member : lower;F;|DOCUMENTED|DOC_ONLY|;;
456.194 - member : lstrip;F;|DOCUMENTED|DOC_ONLY|;chars;
456.195 - member : partition;F;|DOCUMENTED|DOC_ONLY|;sep;
456.196 - member : replace;F;|DOCUMENTED|DOC_ONLY|;old,new,count;
456.197 - member : rfind;F;|DOCUMENTED|DOC_ONLY|;sub,start,end;
456.198 - member : rindex;F;|DOCUMENTED|DOC_ONLY|;sub,start,end;
456.199 - member : rjust;F;|DOCUMENTED|DOC_ONLY|;width,fillchar;
456.200 - member : rpartition;F;|DOCUMENTED|DOC_ONLY|;sep;
456.201 - member : rsplit;F;|DOCUMENTED|DOC_ONLY|;sep,maxsplit;
456.202 - member : rstrip;F;|DOCUMENTED|DOC_ONLY|;chars;
456.203 - member : split;F;|DOCUMENTED|DOC_ONLY|;sep,maxsplit;
456.204 - member : splitlines;F;|DOCUMENTED|DOC_ONLY|;keepends;
456.205 - member : startswith;F;|DOCUMENTED|DOC_ONLY|;prefix,start,end;
456.206 - member : strip;F;|DOCUMENTED|DOC_ONLY|;chars;
456.207 - member : swapcase;F;|DOCUMENTED|DOC_ONLY|;;
456.208 - member : title;F;|DOCUMENTED|DOC_ONLY|;;
456.209 - member : translate;F;|DOCUMENTED|DOC_ONLY|;table,deletechars;
456.210 - member : upper;F;|DOCUMENTED|DOC_ONLY|;;
456.211 - member : zfill;F;|DOCUMENTED|DOC_ONLY|;width;
456.212 -
456.213 -Not Searchable Keys:
456.214 -
456.215 -
456.216 -Document 11
456.217 -Searchable Keys:
456.218 - class : unicode
456.219 - class-ig : unicode
456.220 - in : stdtypes
456.221 - member : isdecimal;F;|DOCUMENTED|DOC_ONLY|;;
456.222 - member : isnumeric;F;|DOCUMENTED|DOC_ONLY|;;
456.223 -
456.224 -Not Searchable Keys:
456.225 -
456.226 -
456.227 -Document 12
456.228 -Searchable Keys:
456.229 - item : class;C;|DOCUMENTED|DOC_ONLY|;
456.230 - item : container;C;|DOCUMENTED|DOC_ONLY|;
456.231 - item : contextmanager;C;|DOCUMENTED|DOC_ONLY|;
456.232 - item : dict;C;|DOCUMENTED|DOC_ONLY|;
456.233 - item : file;C;|DOCUMENTED|DOC_ONLY|;
456.234 - item : float;C;|DOCUMENTED|DOC_ONLY|;
456.235 - item : instance;C;|DOCUMENTED|DOC_ONLY|;
456.236 - item : iterator;C;|DOCUMENTED|DOC_ONLY|;
456.237 - item : object;C;|DOCUMENTED|DOC_ONLY|;
456.238 - item : set;C;|DOCUMENTED|DOC_ONLY|;
456.239 - item : str;C;|DOCUMENTED|DOC_ONLY|;
456.240 - item : unicode;C;|DOCUMENTED|DOC_ONLY|;
456.241 - module : stdtypes
456.242 -
456.243 -Not Searchable Keys:
456.244 - modattrs : S
457.1 --- a/python.editor/test/unit/data/testfiles/rst/stdtypes.rst.testGetDoc2.html Sun Jan 04 13:11:53 2015 -0600
457.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
457.3 @@ -1,204 +0,0 @@
457.4 -<html><body><pre><b>dict</b></pre>
457.5 -
457.6 -<hr>
457.7 - Return a new dictionary initialized from an optional positional argument or from
457.8 - a set of keyword arguments. If no arguments are given, return a new empty
457.9 - dictionary. If the positional argument <b>arg</b> is a mapping object, return a
457.10 - dictionary mapping the same keys to the same values as does the mapping object.
457.11 - Otherwise the positional argument must be a sequence, a container that supports
457.12 - iteration, or an iterator object. The elements of the argument must each also
457.13 - be of one of those kinds, and each must in turn contain exactly two objects.
457.14 - The first is used as a key in the new dictionary, and the second as the key's
457.15 - value. If a given key is seen more than once, the last value associated with it
457.16 - is retained in the new dictionary.
457.17 -
457.18 -<br><br>
457.19 - If keyword arguments are given, the keywords themselves with their associated
457.20 - values are added as items to the dictionary. If a key is specified both in the
457.21 - positional argument and as a keyword argument, the value associated with the
457.22 - keyword is retained in the dictionary. For example, these all return a
457.23 - dictionary equal to <code>{"one": 2, "two": 3}</code>:
457.24 -
457.25 -<br><br>
457.26 - * <code>dict(one=2, two=3)</code>
457.27 -
457.28 -<br><br>
457.29 - * <code>dict({'one': 2, 'two': 3})</code>
457.30 -
457.31 -<br><br>
457.32 - * <code>dict(zip(('one', 'two'), (2, 3)))</code>
457.33 -
457.34 -<br><br>
457.35 - * <code>dict([['two', 3], ['one', 2]])</code>
457.36 -
457.37 -<br><br>
457.38 - The first example only works for keys that are valid Python
457.39 - identifiers; the others work with any valid keys.
457.40 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
457.41 -</div>
457.42 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.3
457.43 - Support for building a dictionary from keyword arguments added.
457.44 -</div>
457.45 - These are the operations that dictionaries support (and therefore, custom
457.46 - mapping types should support too):
457.47 -
457.48 -<br><br>
457.49 - .. describe:: len(d)
457.50 -
457.51 -<br><br>
457.52 - Return the number of items in the dictionary <b>d</b>.
457.53 -
457.54 -<br><br>
457.55 - .. describe:: d[key]
457.56 -
457.57 -<br><br>
457.58 - Return the item of <b>d</b> with key <b>key</b>. Raises a <a href="exc:KeyError">KeyError</a> if <b>key</b>
457.59 - is not in the map.
457.60 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.5
457.61 - If a subclass of dict defines a method <a href="meth:__missing__">__missing__</a>, if the key
457.62 - <b>key</b> is not present, the <code>d[key]</code> operation calls that method with
457.63 - the key <b>key</b> as argument. The <code>d[key]</code> operation then returns or
457.64 - raises whatever is returned or raised by the <code>__missing__(key)</code> call
457.65 - if the key is not present. No other operations or methods invoke
457.66 - <a href="meth:__missing__">__missing__</a>. If <a href="meth:__missing__">__missing__</a> is not defined,
457.67 - <a href="exc:KeyError">KeyError</a> is raised. <a href="meth:__missing__">__missing__</a> must be a method; it
457.68 - cannot be an instance variable. For an example, see
457.69 - <a href="class:collections.defaultdict">collections.defaultdict</a>.
457.70 -</div>
457.71 - .. describe:: d[key] = value
457.72 - Set <code>d[key]</code> to <b>value</b>.
457.73 -
457.74 -<br><br>
457.75 - .. describe:: del d[key]
457.76 -
457.77 -<br><br>
457.78 - Remove <code>d[key]</code> from <b>d</b>. Raises a <a href="exc:KeyError">KeyError</a> if <b>key</b> is not in the
457.79 - map.
457.80 -
457.81 -<br><br>
457.82 - .. describe:: key in d
457.83 -
457.84 -<br><br>
457.85 - Return <code>True</code> if <b>d</b> has a key <b>key</b>, else <code>False</code>.
457.86 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
457.87 -</div>
457.88 - .. describe:: key not in d
457.89 - Equivalent to <code>not key in d</code>.
457.90 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
457.91 -</div>
457.92 -<a href="meth:clear()">clear()</a>
457.93 - Remove all items from the dictionary.
457.94 -
457.95 -<br><br>
457.96 -<a href="meth:copy()">copy()</a>
457.97 -
457.98 -<br><br>
457.99 - Return a shallow copy of the dictionary.
457.100 -
457.101 -<br><br>
457.102 -<a href="meth:fromkeys(seq[, value])">fromkeys(seq[, value])</a>
457.103 -
457.104 -<br><br>
457.105 - Create a new dictionary with keys from <b>seq</b> and values set to <b>value</b>.
457.106 -
457.107 -<br><br>
457.108 - <a href="func:fromkeys">fromkeys</a> is a class method that returns a new dictionary. <b>value</b>
457.109 - defaults to <code>None</code>.
457.110 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.3
457.111 -</div>
457.112 -<a href="meth:get(key[, default])">get(key[, default])</a>
457.113 - Return the value for <b>key</b> if <b>key</b> is in the dictionary, else <b>default</b>.
457.114 - If <b>default</b> is not given, it defaults to <code>None</code>, so that this method
457.115 - never raises a <a href="exc:KeyError">KeyError</a>.
457.116 -
457.117 -<br><br>
457.118 -<a href="meth:has_key(key)">has_key(key)</a>
457.119 -
457.120 -<br><br>
457.121 - <code>dict.has_key(key)</code> is equivalent to <code>key in d</code>, but deprecated.
457.122 -
457.123 -<br><br>
457.124 -<a href="meth:items()">items()</a>
457.125 -
457.126 -<br><br>
457.127 - Return a copy of the dictionary's list of <code>(key, value)</code> pairs.
457.128 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
457.129 -
457.130 -<br><br>
457.131 - Keys and values are listed in an arbitrary order which is non-random,
457.132 - varies across Python implementations, and depends on the dictionary's
457.133 - history of insertions and deletions. If <a href="meth:items">items</a>, <a href="meth:keys">keys</a>,
457.134 - <a href="meth:values">values</a>, <a href="meth:iteritems">iteritems</a>, <a href="meth:iterkeys">iterkeys</a>, and
457.135 - <a href="meth:itervalues">itervalues</a> are called with no intervening modifications to the
457.136 - dictionary, the lists will directly correspond. This allows the
457.137 - creation of <code>(value, key)</code> pairs using <a href="func:zip">zip</a>: ``pairs =
457.138 - zip(d.values(), d.keys())``. The same relationship holds for the
457.139 - <a href="meth:iterkeys">iterkeys</a> and <a href="meth:itervalues">itervalues</a> methods: ``pairs =
457.140 - zip(d.itervalues(), d.iterkeys())`` provides the same value for
457.141 - <code>pairs</code>. Another way to create the same list is ``pairs = [(v, k) for
457.142 - (k, v) in d.iteritems()]``.
457.143 -</div>
457.144 -<a href="meth:iteritems()">iteritems()</a>
457.145 - Return an iterator over the dictionary's <code>(key, value)</code> pairs. See the
457.146 - note for <a href="meth:dict.items">dict.items</a>.
457.147 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
457.148 -</div>
457.149 -<a href="meth:iterkeys()">iterkeys()</a>
457.150 - Return an iterator over the dictionary's keys. See the note for
457.151 - <a href="meth:dict.items">dict.items</a>.
457.152 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
457.153 -</div>
457.154 -<a href="meth:itervalues()">itervalues()</a>
457.155 - Return an iterator over the dictionary's values. See the note for
457.156 - <a href="meth:dict.items">dict.items</a>.
457.157 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.2
457.158 -</div>
457.159 -<a href="meth:keys()">keys()</a>
457.160 - Return a copy of the dictionary's list of keys. See the note for
457.161 - <a href="meth:dict.items">dict.items</a>.
457.162 -
457.163 -<br><br>
457.164 -<a href="meth:pop(key[, default])">pop(key[, default])</a>
457.165 -
457.166 -<br><br>
457.167 - If <b>key</b> is in the dictionary, remove it and return its value, else return
457.168 - <b>default</b>. If <b>default</b> is not given and <b>key</b> is not in the dictionary,
457.169 - a <a href="exc:KeyError">KeyError</a> is raised.
457.170 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.3
457.171 -</div>
457.172 -<a href="meth:popitem()">popitem()</a>
457.173 - Remove and return an arbitrary <code>(key, value)</code> pair from the dictionary.
457.174 -
457.175 -<br><br>
457.176 - <a href="func:popitem">popitem</a> is useful to destructively iterate over a dictionary, as
457.177 - often used in set algorithms. If the dictionary is empty, calling
457.178 - <a href="func:popitem">popitem</a> raises a <a href="exc:KeyError">KeyError</a>.
457.179 -
457.180 -<br><br>
457.181 -<a href="meth:setdefault(key[, default])">setdefault(key[, default])</a>
457.182 -
457.183 -<br><br>
457.184 - If <b>key</b> is in the dictionary, return its value. If not, insert <b>key</b>
457.185 - with a value of <b>default</b> and return <b>default</b>. <b>default</b> defaults to
457.186 - <code>None</code>.
457.187 -
457.188 -<br><br>
457.189 -<a href="meth:update([other])">update([other])</a>
457.190 -
457.191 -<br><br>
457.192 - Update the dictionary with the key/value pairs from <b>other</b>, overwriting
457.193 - existing keys. Return <code>None</code>.
457.194 -
457.195 -<br><br>
457.196 - <a href="func:update">update</a> accepts either another dictionary object or an iterable of
457.197 - key/value pairs (as a tuple or other iterable of length two). If keyword
457.198 - arguments are specified, the dictionary is then is updated with those
457.199 - key/value pairs: <code>d.update(red=1, blue=2)</code>.
457.200 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.4
457.201 - Allowed the argument to be an iterable of key/value pairs and allowed
457.202 - keyword arguments.
457.203 -</div>
457.204 -<a href="meth:values()">values()</a>
457.205 - Return a copy of the dictionary's list of values. See the note for
457.206 - <a href="meth:dict.items">dict.items</a>.
457.207 -</body></html>
458.1 --- a/python.editor/test/unit/data/testfiles/rst/stdtypes.rst.testGetDoc4.html Sun Jan 04 13:11:53 2015 -0600
458.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
458.3 @@ -1,26 +0,0 @@
458.4 -<html><body><pre><b>file.close</b><font color="#808080">()</font></pre>
458.5 -<hr>
458.6 - Close the file. A closed file cannot be read or written any more. Any operation
458.7 - which requires that the file be open will raise a <a href="exc:ValueError">ValueError</a> after the
458.8 - file has been closed. Calling <a href="meth:close">close</a> more than once is allowed.
458.9 -
458.10 -<br><br>
458.11 - As of Python 2.5, you can avoid having to call this method explicitly if you use
458.12 - the <code style="color:#0000e6;">with</code> statement. For example, the following code will
458.13 - automatically close <b>f</b> when the <code style="color:#0000e6;">with</code> block is exited::
458.14 -
458.15 -
458.16 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
458.17 - <span style="color:#0000e6;">from</span> <span style="">__future__</span> <span style="color:#0000e6;">import</span> <span style="">with_statement</span> <span style="color:#969696"><span style="color:#969696;"># This isn't required in Python 2.6</span></span><span style="color:#000000;"><br></span> <span style="color:#0000e6;">with</span> <span style="">open</span><span style="">(</span><span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">hello.txt</span></span><span style="color:#ce7b00;">"</span><span style="">)</span> <span style="color:#0000e6;">as</span> <span style="">f</span><span style="">:</span><span style="color:#000000;"><br></span> <span style="color:#0000e6;">for</span> <span style="">line</span> <span style="color:#0000e6;">in</span> <span style="">f</span><span style="">:</span><span style="color:#000000;"><br></span> <span style="color:#0000e6;">print</span> <span style="">line</span><span style="color:#000000;"><br></span></pre>
458.18 - In older versions of Python, you would have needed to do this to get the same
458.19 - effect::
458.20 -
458.21 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
458.22 - <span style="">f</span> <span style="">=</span> <span style="">open</span><span style="">(</span><span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">hello.txt</span></span><span style="color:#ce7b00;">"</span><span style="">)</span><span style="color:#000000;"><br></span> <span style="color:#0000e6;">try</span><span style="">:</span><span style="color:#000000;"><br></span> <span style="color:#0000e6;">for</span> <span style="">line</span> <span style="color:#0000e6;">in</span> <span style="">f</span><span style="">:</span><span style="color:#000000;"><br></span> <span style="color:#0000e6;">print</span> <span style="">line</span><span style="color:#000000;"><br></span> <span style="color:#0000e6;">finally</span><span style="">:</span><span style="color:#000000;"><br></span> <span style="">f</span><span style="">.</span><span style="">close</span><span style="">(</span><span style="">)</span><span style="color:#000000;"><br></span></pre>
458.23 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
458.24 - Not all "file-like" types in Python support use as a context manager for the
458.25 - <code style="color:#0000e6;">with</code> statement. If your code is intended to work with any file-like
458.26 - object, you can use the function <a href="func:contextlib.closing">contextlib.closing</a> instead of using
458.27 - the object directly.
458.28 -</div>
458.29 -</body></html>
459.1 --- a/python.editor/test/unit/data/testfiles/rst/string.rst Sun Jan 04 13:11:53 2015 -0600
459.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
459.3 @@ -1,849 +0,0 @@
459.4 -:mod:`string` --- Common string operations
459.5 -==========================================
459.6 -
459.7 -.. module:: string
459.8 - :synopsis: Common string operations.
459.9 -
459.10 -
459.11 -.. index:: module: re
459.12 -
459.13 -The :mod:`string` module contains a number of useful constants and
459.14 -classes, as well as some deprecated legacy functions that are also
459.15 -available as methods on strings. In addition, Python's built-in string
459.16 -classes support the sequence type methods described in the
459.17 -:ref:`typesseq` section, and also the string-specific methods described
459.18 -in the :ref:`string-methods` section. To output formatted strings use
459.19 -template strings or the ``%`` operator described in the
459.20 -:ref:`string-formatting` section. Also, see the :mod:`re` module for
459.21 -string functions based on regular expressions.
459.22 -
459.23 -
459.24 -String constants
459.25 -----------------
459.26 -
459.27 -The constants defined in this module are:
459.28 -
459.29 -
459.30 -.. data:: ascii_letters
459.31 -
459.32 - The concatenation of the :const:`ascii_lowercase` and :const:`ascii_uppercase`
459.33 - constants described below. This value is not locale-dependent.
459.34 -
459.35 -
459.36 -.. data:: ascii_lowercase
459.37 -
459.38 - The lowercase letters ``'abcdefghijklmnopqrstuvwxyz'``. This value is not
459.39 - locale-dependent and will not change.
459.40 -
459.41 -
459.42 -.. data:: ascii_uppercase
459.43 -
459.44 - The uppercase letters ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. This value is not
459.45 - locale-dependent and will not change.
459.46 -
459.47 -
459.48 -.. data:: digits
459.49 -
459.50 - The string ``'0123456789'``.
459.51 -
459.52 -
459.53 -.. data:: hexdigits
459.54 -
459.55 - The string ``'0123456789abcdefABCDEF'``.
459.56 -
459.57 -
459.58 -.. data:: letters
459.59 -
459.60 - The concatenation of the strings :const:`lowercase` and :const:`uppercase`
459.61 - described below. The specific value is locale-dependent, and will be updated
459.62 - when :func:`locale.setlocale` is called.
459.63 -
459.64 -
459.65 -.. data:: lowercase
459.66 -
459.67 - A string containing all the characters that are considered lowercase letters.
459.68 - On most systems this is the string ``'abcdefghijklmnopqrstuvwxyz'``. Do not
459.69 - change its definition --- the effect on the routines :func:`upper` and
459.70 - :func:`swapcase` is undefined. The specific value is locale-dependent, and will
459.71 - be updated when :func:`locale.setlocale` is called.
459.72 -
459.73 -
459.74 -.. data:: octdigits
459.75 -
459.76 - The string ``'01234567'``.
459.77 -
459.78 -
459.79 -.. data:: punctuation
459.80 -
459.81 - String of ASCII characters which are considered punctuation characters in the
459.82 - ``C`` locale.
459.83 -
459.84 -
459.85 -.. data:: printable
459.86 -
459.87 - String of characters which are considered printable. This is a combination of
459.88 - :const:`digits`, :const:`letters`, :const:`punctuation`, and
459.89 - :const:`whitespace`.
459.90 -
459.91 -
459.92 -.. data:: uppercase
459.93 -
459.94 - A string containing all the characters that are considered uppercase letters.
459.95 - On most systems this is the string ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. Do not
459.96 - change its definition --- the effect on the routines :func:`lower` and
459.97 - :func:`swapcase` is undefined. The specific value is locale-dependent, and will
459.98 - be updated when :func:`locale.setlocale` is called.
459.99 -
459.100 -
459.101 -.. data:: whitespace
459.102 -
459.103 - A string containing all characters that are considered whitespace. On most
459.104 - systems this includes the characters space, tab, linefeed, return, formfeed, and
459.105 - vertical tab. Do not change its definition --- the effect on the routines
459.106 - :func:`strip` and :func:`split` is undefined.
459.107 -
459.108 -
459.109 -.. _new-string-formatting:
459.110 -
459.111 -String Formatting
459.112 ------------------
459.113 -
459.114 -Starting in Python 2.6, the built-in str and unicode classes provide the ability
459.115 -to do complex variable substitutions and value formatting via the
459.116 -:meth:`str.format` method described in :pep:`3101`. The :class:`Formatter`
459.117 -class in the :mod:`string` module allows you to create and customize your own
459.118 -string formatting behaviors using the same implementation as the built-in
459.119 -:meth:`format` method.
459.120 -
459.121 -.. class:: Formatter
459.122 -
459.123 - The :class:`Formatter` class has the following public methods:
459.124 -
459.125 - .. method:: format(format_string, *args, *kwargs)
459.126 -
459.127 - :meth:`format` is the primary API method. It takes a format template
459.128 - string, and an arbitrary set of positional and keyword argument.
459.129 - :meth:`format` is just a wrapper that calls :meth:`vformat`.
459.130 -
459.131 - .. method:: vformat(format_string, args, kwargs)
459.132 -
459.133 - This function does the actual work of formatting. It is exposed as a
459.134 - separate function for cases where you want to pass in a predefined
459.135 - dictionary of arguments, rather than unpacking and repacking the
459.136 - dictionary as individual arguments using the ``*args`` and ``**kwds``
459.137 - syntax. :meth:`vformat` does the work of breaking up the format template
459.138 - string into character data and replacement fields. It calls the various
459.139 - methods described below.
459.140 -
459.141 - In addition, the :class:`Formatter` defines a number of methods that are
459.142 - intended to be replaced by subclasses:
459.143 -
459.144 - .. method:: parse(format_string)
459.145 -
459.146 - Loop over the format_string and return an iterable of tuples
459.147 - (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used
459.148 - by :meth:`vformat` to break the string in to either literal text, or
459.149 - replacement fields.
459.150 -
459.151 - The values in the tuple conceptually represent a span of literal text
459.152 - followed by a single replacement field. If there is no literal text
459.153 - (which can happen if two replacement fields occur consecutively), then
459.154 - *literal_text* will be a zero-length string. If there is no replacement
459.155 - field, then the values of *field_name*, *format_spec* and *conversion*
459.156 - will be ``None``.
459.157 -
459.158 - .. method:: get_field(field_name, args, kwargs)
459.159 -
459.160 - Given *field_name* as returned by :meth:`parse` (see above), convert it to
459.161 - an object to be formatted. Returns a tuple (obj, used_key). The default
459.162 - version takes strings of the form defined in :pep:`3101`, such as
459.163 - "0[name]" or "label.title". *args* and *kwargs* are as passed in to
459.164 - :meth:`vformat`. The return value *used_key* has the same meaning as the
459.165 - *key* parameter to :meth:`get_value`.
459.166 -
459.167 - .. method:: get_value(key, args, kwargs)
459.168 -
459.169 - Retrieve a given field value. The *key* argument will be either an
459.170 - integer or a string. If it is an integer, it represents the index of the
459.171 - positional argument in *args*; if it is a string, then it represents a
459.172 - named argument in *kwargs*.
459.173 -
459.174 - The *args* parameter is set to the list of positional arguments to
459.175 - :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of
459.176 - keyword arguments.
459.177 -
459.178 - For compound field names, these functions are only called for the first
459.179 - component of the field name; Subsequent components are handled through
459.180 - normal attribute and indexing operations.
459.181 -
459.182 - So for example, the field expression '0.name' would cause
459.183 - :meth:`get_value` to be called with a *key* argument of 0. The ``name``
459.184 - attribute will be looked up after :meth:`get_value` returns by calling the
459.185 - built-in :func:`getattr` function.
459.186 -
459.187 - If the index or keyword refers to an item that does not exist, then an
459.188 - :exc:`IndexError` or :exc:`KeyError` should be raised.
459.189 -
459.190 - .. method:: check_unused_args(used_args, args, kwargs)
459.191 -
459.192 - Implement checking for unused arguments if desired. The arguments to this
459.193 - function is the set of all argument keys that were actually referred to in
459.194 - the format string (integers for positional arguments, and strings for
459.195 - named arguments), and a reference to the *args* and *kwargs* that was
459.196 - passed to vformat. The set of unused args can be calculated from these
459.197 - parameters. :meth:`check_unused_args` is assumed to throw an exception if
459.198 - the check fails.
459.199 -
459.200 - .. method:: format_field(value, format_spec)
459.201 -
459.202 - :meth:`format_field` simply calls the global :func:`format` built-in. The
459.203 - method is provided so that subclasses can override it.
459.204 -
459.205 - .. method:: convert_field(value, conversion)
459.206 -
459.207 - Converts the value (returned by :meth:`get_field`) given a conversion type
459.208 - (as in the tuple returned by the :meth:`parse` method.) The default
459.209 - version understands 'r' (repr) and 's' (str) conversion types.
459.210 -
459.211 -
459.212 -.. _formatstrings:
459.213 -
459.214 -Format String Syntax
459.215 ---------------------
459.216 -
459.217 -The :meth:`str.format` method and the :class:`Formatter` class share the same
459.218 -syntax for format strings (although in the case of :class:`Formatter`,
459.219 -subclasses can define their own format string syntax.)
459.220 -
459.221 -Format strings contain "replacement fields" surrounded by curly braces ``{}``.
459.222 -Anything that is not contained in braces is considered literal text, which is
459.223 -copied unchanged to the output. If you need to include a brace character in the
459.224 -literal text, it can be escaped by doubling: ``{{`` and ``}}``.
459.225 -
459.226 -The grammar for a replacement field is as follows:
459.227 -
459.228 - .. productionlist:: sf
459.229 - replacement_field: "{" `field_name` ["!" `conversion`] [":" `format_spec`] "}"
459.230 - field_name: (`identifier` | `integer`) ("." `attribute_name` | "[" element_index "]")*
459.231 - attribute_name: `identifier`
459.232 - element_index: `integer`
459.233 - conversion: "r" | "s"
459.234 - format_spec: <described in the next section>
459.235 -
459.236 -In less formal terms, the replacement field starts with a *field_name*, which
459.237 -can either be a number (for a positional argument), or an identifier (for
459.238 -keyword arguments). Following this is an optional *conversion* field, which is
459.239 -preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
459.240 -by a colon ``':'``.
459.241 -
459.242 -The *field_name* itself begins with either a number or a keyword. If it's a
459.243 -number, it refers to a positional argument, and if it's a keyword it refers to a
459.244 -named keyword argument. This can be followed by any number of index or
459.245 -attribute expressions. An expression of the form ``'.name'`` selects the named
459.246 -attribute using :func:`getattr`, while an expression of the form ``'[index]'``
459.247 -does an index lookup using :func:`__getitem__`.
459.248 -
459.249 -Some simple format string examples::
459.250 -
459.251 - "First, thou shalt count to {0}" # References first positional argument
459.252 - "My quest is {name}" # References keyword argument 'name'
459.253 - "Weight in tons {0.weight}" # 'weight' attribute of first positional arg
459.254 - "Units destroyed: {players[0]}" # First element of keyword argument 'players'.
459.255 -
459.256 -The *conversion* field causes a type coercion before formatting. Normally, the
459.257 -job of formatting a value is done by the :meth:`__format__` method of the value
459.258 -itself. However, in some cases it is desirable to force a type to be formatted
459.259 -as a string, overriding its own definition of formatting. By converting the
459.260 -value to a string before calling :meth:`__format__`, the normal formatting logic
459.261 -is bypassed.
459.262 -
459.263 -Two conversion flags are currently supported: ``'!s'`` which calls :func:`str`
459.264 -on the value, and ``'!r'`` which calls :func:`repr`.
459.265 -
459.266 -Some examples::
459.267 -
459.268 - "Harold's a clever {0!s}" # Calls str() on the argument first
459.269 - "Bring out the holy {name!r}" # Calls repr() on the argument first
459.270 -
459.271 -The *format_spec* field contains a specification of how the value should be
459.272 -presented, including such details as field width, alignment, padding, decimal
459.273 -precision and so on. Each value type can define it's own "formatting
459.274 -mini-language" or interpretation of the *format_spec*.
459.275 -
459.276 -Most built-in types support a common formatting mini-language, which is
459.277 -described in the next section.
459.278 -
459.279 -A *format_spec* field can also include nested replacement fields within it.
459.280 -These nested replacement fields can contain only a field name; conversion flags
459.281 -and format specifications are not allowed. The replacement fields within the
459.282 -format_spec are substituted before the *format_spec* string is interpreted.
459.283 -This allows the formatting of a value to be dynamically specified.
459.284 -
459.285 -For example, suppose you wanted to have a replacement field whose field width is
459.286 -determined by another variable::
459.287 -
459.288 - "A man with two {0:{1}}".format("noses", 10)
459.289 -
459.290 -This would first evaluate the inner replacement field, making the format string
459.291 -effectively::
459.292 -
459.293 - "A man with two {0:10}"
459.294 -
459.295 -Then the outer replacement field would be evaluated, producing::
459.296 -
459.297 - "noses "
459.298 -
459.299 -Which is substituted into the string, yielding::
459.300 -
459.301 - "A man with two noses "
459.302 -
459.303 -(The extra space is because we specified a field width of 10, and because left
459.304 -alignment is the default for strings.)
459.305 -
459.306 -
459.307 -.. _formatspec:
459.308 -
459.309 -Format Specification Mini-Language
459.310 -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
459.311 -
459.312 -"Format specifications" are used within replacement fields contained within a
459.313 -format string to define how individual values are presented (see
459.314 -:ref:`formatstrings`.) They can also be passed directly to the builtin
459.315 -:func:`format` function. Each formattable type may define how the format
459.316 -specification is to be interpreted.
459.317 -
459.318 -Most built-in types implement the following options for format specifications,
459.319 -although some of the formatting options are only supported by the numeric types.
459.320 -
459.321 -A general convention is that an empty format string (``""``) produces the same
459.322 -result as if you had called :func:`str` on the value.
459.323 -
459.324 -The general form of a *standard format specifier* is:
459.325 -
459.326 -.. productionlist:: sf
459.327 - format_spec: [[`fill`]`align`][`sign`][#][0][`width`][.`precision`][`type`]
459.328 - fill: <a character other than '}'>
459.329 - align: "<" | ">" | "=" | "^"
459.330 - sign: "+" | "-" | " "
459.331 - width: `integer`
459.332 - precision: `integer`
459.333 - type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%"
459.334 -
459.335 -The *fill* character can be any character other than '}' (which signifies the
459.336 -end of the field). The presence of a fill character is signaled by the *next*
459.337 -character, which must be one of the alignment options. If the second character
459.338 -of *format_spec* is not a valid alignment option, then it is assumed that both
459.339 -the fill character and the alignment option are absent.
459.340 -
459.341 -The meaning of the various alignment options is as follows:
459.342 -
459.343 - +---------+----------------------------------------------------------+
459.344 - | Option | Meaning |
459.345 - +=========+==========================================================+
459.346 - | ``'<'`` | Forces the field to be left-aligned within the available |
459.347 - | | space (This is the default.) |
459.348 - +---------+----------------------------------------------------------+
459.349 - | ``'>'`` | Forces the field to be right-aligned within the |
459.350 - | | available space. |
459.351 - +---------+----------------------------------------------------------+
459.352 - | ``'='`` | Forces the padding to be placed after the sign (if any) |
459.353 - | | but before the digits. This is used for printing fields |
459.354 - | | in the form '+000000120'. This alignment option is only |
459.355 - | | valid for numeric types. |
459.356 - +---------+----------------------------------------------------------+
459.357 - | ``'^'`` | Forces the field to be centered within the available |
459.358 - | | space. |
459.359 - +---------+----------------------------------------------------------+
459.360 -
459.361 -Note that unless a minimum field width is defined, the field width will always
459.362 -be the same size as the data to fill it, so that the alignment option has no
459.363 -meaning in this case.
459.364 -
459.365 -The *sign* option is only valid for number types, and can be one of the
459.366 -following:
459.367 -
459.368 - +---------+----------------------------------------------------------+
459.369 - | Option | Meaning |
459.370 - +=========+==========================================================+
459.371 - | ``'+'`` | indicates that a sign should be used for both |
459.372 - | | positive as well as negative numbers. |
459.373 - +---------+----------------------------------------------------------+
459.374 - | ``'-'`` | indicates that a sign should be used only for negative |
459.375 - | | numbers (this is the default behavior). |
459.376 - +---------+----------------------------------------------------------+
459.377 - | space | indicates that a leading space should be used on |
459.378 - | | positive numbers, and a minus sign on negative numbers. |
459.379 - +---------+----------------------------------------------------------+
459.380 -
459.381 -The ``'#'`` option is only valid for integers, and only for binary, octal, or
459.382 -hexadecimal output. If present, it specifies that the output will be prefixed
459.383 -by ``'0b'``, ``'0o'``, or ``'0x'``, respectively.
459.384 -
459.385 -*width* is a decimal integer defining the minimum field width. If not
459.386 -specified, then the field width will be determined by the content.
459.387 -
459.388 -If the *width* field is preceded by a zero (``'0'``) character, this enables
459.389 -zero-padding. This is equivalent to an *alignment* type of ``'='`` and a *fill*
459.390 -character of ``'0'``.
459.391 -
459.392 -The *precision* is a decimal number indicating how many digits should be
459.393 -displayed after the decimal point for a floating point value formatted with
459.394 -``'f'`` and ``'F'``, or before and after the decimal point for a floating point
459.395 -value formatted with ``'g'`` or ``'G'``. For non-number types the field
459.396 -indicates the maximum field size - in other words, how many characters will be
459.397 -used from the field content. The *precision* is ignored for integer values.
459.398 -
459.399 -Finally, the *type* determines how the data should be presented.
459.400 -
459.401 -The available integer presentation types are:
459.402 -
459.403 - +---------+----------------------------------------------------------+
459.404 - | Type | Meaning |
459.405 - +=========+==========================================================+
459.406 - | ``'b'`` | Binary format. Outputs the number in base 2. |
459.407 - +---------+----------------------------------------------------------+
459.408 - | ``'c'`` | Character. Converts the integer to the corresponding |
459.409 - | | unicode character before printing. |
459.410 - +---------+----------------------------------------------------------+
459.411 - | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
459.412 - +---------+----------------------------------------------------------+
459.413 - | ``'o'`` | Octal format. Outputs the number in base 8. |
459.414 - +---------+----------------------------------------------------------+
459.415 - | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
459.416 - | | case letters for the digits above 9. |
459.417 - +---------+----------------------------------------------------------+
459.418 - | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
459.419 - | | case letters for the digits above 9. |
459.420 - +---------+----------------------------------------------------------+
459.421 - | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
459.422 - | | the current locale setting to insert the appropriate |
459.423 - | | number separator characters. |
459.424 - +---------+----------------------------------------------------------+
459.425 - | None | The same as ``'d'``. |
459.426 - +---------+----------------------------------------------------------+
459.427 -
459.428 -The available presentation types for floating point and decimal values are:
459.429 -
459.430 - +---------+----------------------------------------------------------+
459.431 - | Type | Meaning |
459.432 - +=========+==========================================================+
459.433 - | ``'e'`` | Exponent notation. Prints the number in scientific |
459.434 - | | notation using the letter 'e' to indicate the exponent. |
459.435 - +---------+----------------------------------------------------------+
459.436 - | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
459.437 - | | upper case 'E' as the separator character. |
459.438 - +---------+----------------------------------------------------------+
459.439 - | ``'f'`` | Fixed point. Displays the number as a fixed-point |
459.440 - | | number. |
459.441 - +---------+----------------------------------------------------------+
459.442 - | ``'F'`` | Fixed point. Same as ``'f'``. |
459.443 - +---------+----------------------------------------------------------+
459.444 - | ``'g'`` | General format. This prints the number as a fixed-point |
459.445 - | | number, unless the number is too large, in which case |
459.446 - | | it switches to ``'e'`` exponent notation. Infinity and |
459.447 - | | NaN values are formatted as ``inf``, ``-inf`` and |
459.448 - | | ``nan``, respectively. |
459.449 - +---------+----------------------------------------------------------+
459.450 - | ``'G'`` | General format. Same as ``'g'`` except switches to |
459.451 - | | ``'E'`` if the number gets to large. The representations |
459.452 - | | of infinity and NaN are uppercased, too. |
459.453 - +---------+----------------------------------------------------------+
459.454 - | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
459.455 - | | the current locale setting to insert the appropriate |
459.456 - | | number separator characters. |
459.457 - +---------+----------------------------------------------------------+
459.458 - | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
459.459 - | | in fixed (``'f'``) format, followed by a percent sign. |
459.460 - +---------+----------------------------------------------------------+
459.461 - | None | The same as ``'g'``. |
459.462 - +---------+----------------------------------------------------------+
459.463 -
459.464 -
459.465 -Template strings
459.466 -----------------
459.467 -
459.468 -Templates provide simpler string substitutions as described in :pep:`292`.
459.469 -Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
459.470 --based substitutions, using the following rules:
459.471 -
459.472 -* ``$$`` is an escape; it is replaced with a single ``$``.
459.473 -
459.474 -* ``$identifier`` names a substitution placeholder matching a mapping key of
459.475 - ``"identifier"``. By default, ``"identifier"`` must spell a Python
459.476 - identifier. The first non-identifier character after the ``$`` character
459.477 - terminates this placeholder specification.
459.478 -
459.479 -* ``${identifier}`` is equivalent to ``$identifier``. It is required when valid
459.480 - identifier characters follow the placeholder but are not part of the
459.481 - placeholder, such as ``"${noun}ification"``.
459.482 -
459.483 -Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
459.484 -being raised.
459.485 -
459.486 -.. versionadded:: 2.4
459.487 -
459.488 -The :mod:`string` module provides a :class:`Template` class that implements
459.489 -these rules. The methods of :class:`Template` are:
459.490 -
459.491 -
459.492 -.. class:: Template(template)
459.493 -
459.494 - The constructor takes a single argument which is the template string.
459.495 -
459.496 -
459.497 - .. method:: substitute(mapping[, **kws])
459.498 -
459.499 - Performs the template substitution, returning a new string. *mapping* is
459.500 - any dictionary-like object with keys that match the placeholders in the
459.501 - template. Alternatively, you can provide keyword arguments, where the
459.502 - keywords are the placeholders. When both *mapping* and *kws* are given
459.503 - and there are duplicates, the placeholders from *kws* take precedence.
459.504 -
459.505 -
459.506 - .. method:: safe_substitute(mapping[, **kws])
459.507 -
459.508 - Like :meth:`substitute`, except that if placeholders are missing from
459.509 - *mapping* and *kws*, instead of raising a :exc:`KeyError` exception, the
459.510 - original placeholder will appear in the resulting string intact. Also,
459.511 - unlike with :meth:`substitute`, any other appearances of the ``$`` will
459.512 - simply return ``$`` instead of raising :exc:`ValueError`.
459.513 -
459.514 - While other exceptions may still occur, this method is called "safe"
459.515 - because substitutions always tries to return a usable string instead of
459.516 - raising an exception. In another sense, :meth:`safe_substitute` may be
459.517 - anything other than safe, since it will silently ignore malformed
459.518 - templates containing dangling delimiters, unmatched braces, or
459.519 - placeholders that are not valid Python identifiers.
459.520 -
459.521 -:class:`Template` instances also provide one public data attribute:
459.522 -
459.523 -
459.524 -.. attribute:: string.template
459.525 -
459.526 - This is the object passed to the constructor's *template* argument. In general,
459.527 - you shouldn't change it, but read-only access is not enforced.
459.528 -
459.529 -Here is an example of how to use a Template:
459.530 -
459.531 - >>> from string import Template
459.532 - >>> s = Template('$who likes $what')
459.533 - >>> s.substitute(who='tim', what='kung pao')
459.534 - 'tim likes kung pao'
459.535 - >>> d = dict(who='tim')
459.536 - >>> Template('Give $who $100').substitute(d)
459.537 - Traceback (most recent call last):
459.538 - [...]
459.539 - ValueError: Invalid placeholder in string: line 1, col 10
459.540 - >>> Template('$who likes $what').substitute(d)
459.541 - Traceback (most recent call last):
459.542 - [...]
459.543 - KeyError: 'what'
459.544 - >>> Template('$who likes $what').safe_substitute(d)
459.545 - 'tim likes $what'
459.546 -
459.547 -Advanced usage: you can derive subclasses of :class:`Template` to customize the
459.548 -placeholder syntax, delimiter character, or the entire regular expression used
459.549 -to parse template strings. To do this, you can override these class attributes:
459.550 -
459.551 -* *delimiter* -- This is the literal string describing a placeholder introducing
459.552 - delimiter. The default value ``$``. Note that this should *not* be a regular
459.553 - expression, as the implementation will call :meth:`re.escape` on this string as
459.554 - needed.
459.555 -
459.556 -* *idpattern* -- This is the regular expression describing the pattern for
459.557 - non-braced placeholders (the braces will be added automatically as
459.558 - appropriate). The default value is the regular expression
459.559 - ``[_a-z][_a-z0-9]*``.
459.560 -
459.561 -Alternatively, you can provide the entire regular expression pattern by
459.562 -overriding the class attribute *pattern*. If you do this, the value must be a
459.563 -regular expression object with four named capturing groups. The capturing
459.564 -groups correspond to the rules given above, along with the invalid placeholder
459.565 -rule:
459.566 -
459.567 -* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
459.568 - default pattern.
459.569 -
459.570 -* *named* -- This group matches the unbraced placeholder name; it should not
459.571 - include the delimiter in capturing group.
459.572 -
459.573 -* *braced* -- This group matches the brace enclosed placeholder name; it should
459.574 - not include either the delimiter or braces in the capturing group.
459.575 -
459.576 -* *invalid* -- This group matches any other delimiter pattern (usually a single
459.577 - delimiter), and it should appear last in the regular expression.
459.578 -
459.579 -
459.580 -String functions
459.581 -----------------
459.582 -
459.583 -The following functions are available to operate on string and Unicode objects.
459.584 -They are not available as string methods.
459.585 -
459.586 -
459.587 -.. function:: capwords(s)
459.588 -
459.589 - Split the argument into words using :func:`split`, capitalize each word using
459.590 - :func:`capitalize`, and join the capitalized words using :func:`join`. Note
459.591 - that this replaces runs of whitespace characters by a single space, and removes
459.592 - leading and trailing whitespace.
459.593 -
459.594 -
459.595 -.. function:: maketrans(from, to)
459.596 -
459.597 - Return a translation table suitable for passing to :func:`translate`, that will
459.598 - map each character in *from* into the character at the same position in *to*;
459.599 - *from* and *to* must have the same length.
459.600 -
459.601 - .. warning::
459.602 -
459.603 - Don't use strings derived from :const:`lowercase` and :const:`uppercase` as
459.604 - arguments; in some locales, these don't have the same length. For case
459.605 - conversions, always use :func:`lower` and :func:`upper`.
459.606 -
459.607 -
459.608 -Deprecated string functions
459.609 ----------------------------
459.610 -
459.611 -The following list of functions are also defined as methods of string and
459.612 -Unicode objects; see section :ref:`string-methods` for more information on
459.613 -those. You should consider these functions as deprecated, although they will
459.614 -not be removed until Python 3.0. The functions defined in this module are:
459.615 -
459.616 -
459.617 -.. function:: atof(s)
459.618 -
459.619 - .. deprecated:: 2.0
459.620 - Use the :func:`float` built-in function.
459.621 -
459.622 - .. index:: builtin: float
459.623 -
459.624 - Convert a string to a floating point number. The string must have the standard
459.625 - syntax for a floating point literal in Python, optionally preceded by a sign
459.626 - (``+`` or ``-``). Note that this behaves identical to the built-in function
459.627 - :func:`float` when passed a string.
459.628 -
459.629 - .. note::
459.630 -
459.631 - .. index::
459.632 - single: NaN
459.633 - single: Infinity
459.634 -
459.635 - When passing in a string, values for NaN and Infinity may be returned, depending
459.636 - on the underlying C library. The specific set of strings accepted which cause
459.637 - these values to be returned depends entirely on the C library and is known to
459.638 - vary.
459.639 -
459.640 -
459.641 -.. function:: atoi(s[, base])
459.642 -
459.643 - .. deprecated:: 2.0
459.644 - Use the :func:`int` built-in function.
459.645 -
459.646 - .. index:: builtin: eval
459.647 -
459.648 - Convert string *s* to an integer in the given *base*. The string must consist
459.649 - of one or more digits, optionally preceded by a sign (``+`` or ``-``). The
459.650 - *base* defaults to 10. If it is 0, a default base is chosen depending on the
459.651 - leading characters of the string (after stripping the sign): ``0x`` or ``0X``
459.652 - means 16, ``0`` means 8, anything else means 10. If *base* is 16, a leading
459.653 - ``0x`` or ``0X`` is always accepted, though not required. This behaves
459.654 - identically to the built-in function :func:`int` when passed a string. (Also
459.655 - note: for a more flexible interpretation of numeric literals, use the built-in
459.656 - function :func:`eval`.)
459.657 -
459.658 -
459.659 -.. function:: atol(s[, base])
459.660 -
459.661 - .. deprecated:: 2.0
459.662 - Use the :func:`long` built-in function.
459.663 -
459.664 - .. index:: builtin: long
459.665 -
459.666 - Convert string *s* to a long integer in the given *base*. The string must
459.667 - consist of one or more digits, optionally preceded by a sign (``+`` or ``-``).
459.668 - The *base* argument has the same meaning as for :func:`atoi`. A trailing ``l``
459.669 - or ``L`` is not allowed, except if the base is 0. Note that when invoked
459.670 - without *base* or with *base* set to 10, this behaves identical to the built-in
459.671 - function :func:`long` when passed a string.
459.672 -
459.673 -
459.674 -.. function:: capitalize(word)
459.675 -
459.676 - Return a copy of *word* with only its first character capitalized.
459.677 -
459.678 -
459.679 -.. function:: expandtabs(s[, tabsize])
459.680 -
459.681 - Expand tabs in a string replacing them by one or more spaces, depending on the
459.682 - current column and the given tab size. The column number is reset to zero after
459.683 - each newline occurring in the string. This doesn't understand other non-printing
459.684 - characters or escape sequences. The tab size defaults to 8.
459.685 -
459.686 -
459.687 -.. function:: find(s, sub[, start[,end]])
459.688 -
459.689 - Return the lowest index in *s* where the substring *sub* is found such that
459.690 - *sub* is wholly contained in ``s[start:end]``. Return ``-1`` on failure.
459.691 - Defaults for *start* and *end* and interpretation of negative values is the same
459.692 - as for slices.
459.693 -
459.694 -
459.695 -.. function:: rfind(s, sub[, start[, end]])
459.696 -
459.697 - Like :func:`find` but find the highest index.
459.698 -
459.699 -
459.700 -.. function:: index(s, sub[, start[, end]])
459.701 -
459.702 - Like :func:`find` but raise :exc:`ValueError` when the substring is not found.
459.703 -
459.704 -
459.705 -.. function:: rindex(s, sub[, start[, end]])
459.706 -
459.707 - Like :func:`rfind` but raise :exc:`ValueError` when the substring is not found.
459.708 -
459.709 -
459.710 -.. function:: count(s, sub[, start[, end]])
459.711 -
459.712 - Return the number of (non-overlapping) occurrences of substring *sub* in string
459.713 - ``s[start:end]``. Defaults for *start* and *end* and interpretation of negative
459.714 - values are the same as for slices.
459.715 -
459.716 -
459.717 -.. function:: lower(s)
459.718 -
459.719 - Return a copy of *s*, but with upper case letters converted to lower case.
459.720 -
459.721 -
459.722 -.. function:: split(s[, sep[, maxsplit]])
459.723 -
459.724 - Return a list of the words of the string *s*. If the optional second argument
459.725 - *sep* is absent or ``None``, the words are separated by arbitrary strings of
459.726 - whitespace characters (space, tab, newline, return, formfeed). If the second
459.727 - argument *sep* is present and not ``None``, it specifies a string to be used as
459.728 - the word separator. The returned list will then have one more item than the
459.729 - number of non-overlapping occurrences of the separator in the string. The
459.730 - optional third argument *maxsplit* defaults to 0. If it is nonzero, at most
459.731 - *maxsplit* number of splits occur, and the remainder of the string is returned
459.732 - as the final element of the list (thus, the list will have at most
459.733 - ``maxsplit+1`` elements).
459.734 -
459.735 - The behavior of split on an empty string depends on the value of *sep*. If *sep*
459.736 - is not specified, or specified as ``None``, the result will be an empty list.
459.737 - If *sep* is specified as any string, the result will be a list containing one
459.738 - element which is an empty string.
459.739 -
459.740 -
459.741 -.. function:: rsplit(s[, sep[, maxsplit]])
459.742 -
459.743 - Return a list of the words of the string *s*, scanning *s* from the end. To all
459.744 - intents and purposes, the resulting list of words is the same as returned by
459.745 - :func:`split`, except when the optional third argument *maxsplit* is explicitly
459.746 - specified and nonzero. When *maxsplit* is nonzero, at most *maxsplit* number of
459.747 - splits -- the *rightmost* ones -- occur, and the remainder of the string is
459.748 - returned as the first element of the list (thus, the list will have at most
459.749 - ``maxsplit+1`` elements).
459.750 -
459.751 - .. versionadded:: 2.4
459.752 -
459.753 -
459.754 -.. function:: splitfields(s[, sep[, maxsplit]])
459.755 -
459.756 - This function behaves identically to :func:`split`. (In the past, :func:`split`
459.757 - was only used with one argument, while :func:`splitfields` was only used with
459.758 - two arguments.)
459.759 -
459.760 -
459.761 -.. function:: join(words[, sep])
459.762 -
459.763 - Concatenate a list or tuple of words with intervening occurrences of *sep*.
459.764 - The default value for *sep* is a single space character. It is always true that
459.765 - ``string.join(string.split(s, sep), sep)`` equals *s*.
459.766 -
459.767 -
459.768 -.. function:: joinfields(words[, sep])
459.769 -
459.770 - This function behaves identically to :func:`join`. (In the past, :func:`join`
459.771 - was only used with one argument, while :func:`joinfields` was only used with two
459.772 - arguments.) Note that there is no :meth:`joinfields` method on string objects;
459.773 - use the :meth:`join` method instead.
459.774 -
459.775 -
459.776 -.. function:: lstrip(s[, chars])
459.777 -
459.778 - Return a copy of the string with leading characters removed. If *chars* is
459.779 - omitted or ``None``, whitespace characters are removed. If given and not
459.780 - ``None``, *chars* must be a string; the characters in the string will be
459.781 - stripped from the beginning of the string this method is called on.
459.782 -
459.783 - .. versionchanged:: 2.2.3
459.784 - The *chars* parameter was added. The *chars* parameter cannot be passed in
459.785 - earlier 2.2 versions.
459.786 -
459.787 -
459.788 -.. function:: rstrip(s[, chars])
459.789 -
459.790 - Return a copy of the string with trailing characters removed. If *chars* is
459.791 - omitted or ``None``, whitespace characters are removed. If given and not
459.792 - ``None``, *chars* must be a string; the characters in the string will be
459.793 - stripped from the end of the string this method is called on.
459.794 -
459.795 - .. versionchanged:: 2.2.3
459.796 - The *chars* parameter was added. The *chars* parameter cannot be passed in
459.797 - earlier 2.2 versions.
459.798 -
459.799 -
459.800 -.. function:: strip(s[, chars])
459.801 -
459.802 - Return a copy of the string with leading and trailing characters removed. If
459.803 - *chars* is omitted or ``None``, whitespace characters are removed. If given and
459.804 - not ``None``, *chars* must be a string; the characters in the string will be
459.805 - stripped from the both ends of the string this method is called on.
459.806 -
459.807 - .. versionchanged:: 2.2.3
459.808 - The *chars* parameter was added. The *chars* parameter cannot be passed in
459.809 - earlier 2.2 versions.
459.810 -
459.811 -
459.812 -.. function:: swapcase(s)
459.813 -
459.814 - Return a copy of *s*, but with lower case letters converted to upper case and
459.815 - vice versa.
459.816 -
459.817 -
459.818 -.. function:: translate(s, table[, deletechars])
459.819 -
459.820 - Delete all characters from *s* that are in *deletechars* (if present), and then
459.821 - translate the characters using *table*, which must be a 256-character string
459.822 - giving the translation for each character value, indexed by its ordinal. If
459.823 - *table* is ``None``, then only the character deletion step is performed.
459.824 -
459.825 -
459.826 -.. function:: upper(s)
459.827 -
459.828 - Return a copy of *s*, but with lower case letters converted to upper case.
459.829 -
459.830 -
459.831 -.. function:: ljust(s, width)
459.832 - rjust(s, width)
459.833 - center(s, width)
459.834 -
459.835 - These functions respectively left-justify, right-justify and center a string in
459.836 - a field of given width. They return a string that is at least *width*
459.837 - characters wide, created by padding the string *s* with spaces until the given
459.838 - width on the right, left or both sides. The string is never truncated.
459.839 -
459.840 -
459.841 -.. function:: zfill(s, width)
459.842 -
459.843 - Pad a numeric string on the left with zero digits until the given width is
459.844 - reached. Strings starting with a sign are handled correctly.
459.845 -
459.846 -
459.847 -.. function:: replace(str, old, new[, maxreplace])
459.848 -
459.849 - Return a copy of string *str* with all occurrences of substring *old* replaced
459.850 - by *new*. If the optional argument *maxreplace* is given, the first
459.851 - *maxreplace* occurrences are replaced.
459.852 -
460.1 --- a/python.editor/test/unit/data/testfiles/rst/string.rst.html Sun Jan 04 13:11:53 2015 -0600
460.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
460.3 @@ -1,888 +0,0 @@
460.4 -<html><body>
460.5 -<h2><a href="mod:string">string</a> --- Common string operations
460.6 -</h2>
460.7 -<a href="module:string">string</a><br>
460.8 - Common string operations.
460.9 -
460.10 -<br><br>
460.11 -The <a href="mod:string">string</a> module contains a number of useful constants and
460.12 -classes, as well as some deprecated legacy functions that are also
460.13 -available as methods on strings. In addition, Python's built-in string
460.14 -classes support the sequence type methods described in the
460.15 -<code>typesseq</code> section, and also the string-specific methods described
460.16 -in the <code>string-methods</code> section. To output formatted strings use
460.17 -template strings or the <code>%</code> operator described in the
460.18 -<code>string-formatting</code> section. Also, see the <a href="mod:re">re</a> module for
460.19 -string functions based on regular expressions.
460.20 -
460.21 -<br><br>
460.22 -<h3>String constants
460.23 -</h3>
460.24 -The constants defined in this module are:
460.25 -
460.26 -<br><br>
460.27 -<a href="data:ascii_letters">ascii_letters</a>
460.28 -
460.29 -<br><br>
460.30 - The concatenation of the :const:<code>ascii_lowercase</code> and :const:<code>ascii_uppercase</code>
460.31 - constants described below. This value is not locale-dependent.
460.32 -
460.33 -<br><br>
460.34 -<a href="data:ascii_lowercase">ascii_lowercase</a>
460.35 -
460.36 -<br><br>
460.37 - The lowercase letters <code>'abcdefghijklmnopqrstuvwxyz'</code>. This value is not
460.38 - locale-dependent and will not change.
460.39 -
460.40 -<br><br>
460.41 -<a href="data:ascii_uppercase">ascii_uppercase</a>
460.42 -
460.43 -<br><br>
460.44 - The uppercase letters <code>'ABCDEFGHIJKLMNOPQRSTUVWXYZ'</code>. This value is not
460.45 - locale-dependent and will not change.
460.46 -
460.47 -<br><br>
460.48 -<a href="data:digits">digits</a>
460.49 -
460.50 -<br><br>
460.51 - The string <code>'0123456789'</code>.
460.52 -
460.53 -<br><br>
460.54 -<a href="data:hexdigits">hexdigits</a>
460.55 -
460.56 -<br><br>
460.57 - The string <code>'0123456789abcdefABCDEF'</code>.
460.58 -
460.59 -<br><br>
460.60 -<a href="data:letters">letters</a>
460.61 -
460.62 -<br><br>
460.63 - The concatenation of the strings :const:<code>lowercase</code> and :const:<code>uppercase</code>
460.64 - described below. The specific value is locale-dependent, and will be updated
460.65 - when <a href="func:locale.setlocale">locale.setlocale</a> is called.
460.66 -
460.67 -<br><br>
460.68 -<a href="data:lowercase">lowercase</a>
460.69 -
460.70 -<br><br>
460.71 - A string containing all the characters that are considered lowercase letters.
460.72 - On most systems this is the string <code>'abcdefghijklmnopqrstuvwxyz'</code>. Do not
460.73 - change its definition --- the effect on the routines <a href="func:upper">upper</a> and
460.74 - <a href="func:swapcase">swapcase</a> is undefined. The specific value is locale-dependent, and will
460.75 - be updated when <a href="func:locale.setlocale">locale.setlocale</a> is called.
460.76 -
460.77 -<br><br>
460.78 -<a href="data:octdigits">octdigits</a>
460.79 -
460.80 -<br><br>
460.81 - The string <code>'01234567'</code>.
460.82 -
460.83 -<br><br>
460.84 -<a href="data:punctuation">punctuation</a>
460.85 -
460.86 -<br><br>
460.87 - String of ASCII characters which are considered punctuation characters in the
460.88 - <code>C</code> locale.
460.89 -
460.90 -<br><br>
460.91 -<a href="data:printable">printable</a>
460.92 -
460.93 -<br><br>
460.94 - String of characters which are considered printable. This is a combination of
460.95 - :const:<code>digits</code>, :const:<code>letters</code>, :const:<code>punctuation</code>, and
460.96 - :const:<code>whitespace</code>.
460.97 -
460.98 -<br><br>
460.99 -<a href="data:uppercase">uppercase</a>
460.100 -
460.101 -<br><br>
460.102 - A string containing all the characters that are considered uppercase letters.
460.103 - On most systems this is the string <code>'ABCDEFGHIJKLMNOPQRSTUVWXYZ'</code>. Do not
460.104 - change its definition --- the effect on the routines <a href="func:lower">lower</a> and
460.105 - <a href="func:swapcase">swapcase</a> is undefined. The specific value is locale-dependent, and will
460.106 - be updated when <a href="func:locale.setlocale">locale.setlocale</a> is called.
460.107 -
460.108 -<br><br>
460.109 -<a href="data:whitespace">whitespace</a>
460.110 -
460.111 -<br><br>
460.112 - A string containing all characters that are considered whitespace. On most
460.113 - systems this includes the characters space, tab, linefeed, return, formfeed, and
460.114 - vertical tab. Do not change its definition --- the effect on the routines
460.115 - <a href="func:strip">strip</a> and <a href="func:split">split</a> is undefined.
460.116 -
460.117 -<br><br>
460.118 -
460.119 -<br><br>
460.120 -<h3>String Formatting
460.121 -</h3>
460.122 -Starting in Python 2.6, the built-in str and unicode classes provide the ability
460.123 -to do complex variable substitutions and value formatting via the
460.124 -<a href="meth:str.format">str.format</a> method described in <a href="http://www.python.org/dev/peps/pep-3101/">PEP 3101</a>. The <a href="class:Formatter">Formatter</a>
460.125 -class in the <a href="mod:string">string</a> module allows you to create and customize your own
460.126 -string formatting behaviors using the same implementation as the built-in
460.127 -<a href="meth:format">format</a> method.
460.128 -
460.129 -<br><br>
460.130 -<a href="class:Formatter">Formatter</a>
460.131 -
460.132 -<br><br>
460.133 - The <a href="class:Formatter">Formatter</a> class has the following public methods:
460.134 -
460.135 -<br><br>
460.136 -<a href="meth:format(format_string, *args, *kwargs)">format(format_string, *args, *kwargs)</a>
460.137 -
460.138 -<br><br>
460.139 - <a href="meth:format">format</a> is the primary API method. It takes a format template
460.140 - string, and an arbitrary set of positional and keyword argument.
460.141 - <a href="meth:format">format</a> is just a wrapper that calls <a href="meth:vformat">vformat</a>.
460.142 -
460.143 -<br><br>
460.144 -<a href="meth:vformat(format_string, args, kwargs)">vformat(format_string, args, kwargs)</a>
460.145 -
460.146 -<br><br>
460.147 - This function does the actual work of formatting. It is exposed as a
460.148 - separate function for cases where you want to pass in a predefined
460.149 - dictionary of arguments, rather than unpacking and repacking the
460.150 - dictionary as individual arguments using the <code>*args</code> and <code>**kwds</code>
460.151 - syntax. <a href="meth:vformat">vformat</a> does the work of breaking up the format template
460.152 - string into character data and replacement fields. It calls the various
460.153 - methods described below.
460.154 -
460.155 -<br><br>
460.156 - In addition, the <a href="class:Formatter">Formatter</a> defines a number of methods that are
460.157 - intended to be replaced by subclasses:
460.158 -
460.159 -<br><br>
460.160 -<a href="meth:parse(format_string)">parse(format_string)</a>
460.161 -
460.162 -<br><br>
460.163 - Loop over the format_string and return an iterable of tuples
460.164 - (<b>literal_text</b>, <b>field_name</b>, <b>format_spec</b>, <b>conversion</b>). This is used
460.165 - by <a href="meth:vformat">vformat</a> to break the string in to either literal text, or
460.166 - replacement fields.
460.167 -
460.168 -<br><br>
460.169 - The values in the tuple conceptually represent a span of literal text
460.170 - followed by a single replacement field. If there is no literal text
460.171 - (which can happen if two replacement fields occur consecutively), then
460.172 - <b>literal_text</b> will be a zero-length string. If there is no replacement
460.173 - field, then the values of <b>field_name</b>, <b>format_spec</b> and <b>conversion</b>
460.174 - will be <code>None</code>.
460.175 -
460.176 -<br><br>
460.177 -<a href="meth:get_field(field_name, args, kwargs)">get_field(field_name, args, kwargs)</a>
460.178 -
460.179 -<br><br>
460.180 - Given <b>field_name</b> as returned by <a href="meth:parse">parse</a> (see above), convert it to
460.181 - an object to be formatted. Returns a tuple (obj, used_key). The default
460.182 - version takes strings of the form defined in <a href="http://www.python.org/dev/peps/pep-3101/">PEP 3101</a>, such as
460.183 - "0[name]" or "label.title". <b>args</b> and <b>kwargs</b> are as passed in to
460.184 - <a href="meth:vformat">vformat</a>. The return value <b>used_key</b> has the same meaning as the
460.185 - <b>key</b> parameter to <a href="meth:get_value">get_value</a>.
460.186 -
460.187 -<br><br>
460.188 -<a href="meth:get_value(key, args, kwargs)">get_value(key, args, kwargs)</a>
460.189 -
460.190 -<br><br>
460.191 - Retrieve a given field value. The <b>key</b> argument will be either an
460.192 - integer or a string. If it is an integer, it represents the index of the
460.193 - positional argument in <b>args</b>; if it is a string, then it represents a
460.194 - named argument in <b>kwargs</b>.
460.195 -
460.196 -<br><br>
460.197 - The <b>args</b> parameter is set to the list of positional arguments to
460.198 - <a href="meth:vformat">vformat</a>, and the <b>kwargs</b> parameter is set to the dictionary of
460.199 - keyword arguments.
460.200 -
460.201 -<br><br>
460.202 - For compound field names, these functions are only called for the first
460.203 - component of the field name; Subsequent components are handled through
460.204 - normal attribute and indexing operations.
460.205 -
460.206 -<br><br>
460.207 - So for example, the field expression '0.name' would cause
460.208 - <a href="meth:get_value">get_value</a> to be called with a <b>key</b> argument of 0. The <code>name</code>
460.209 - attribute will be looked up after <a href="meth:get_value">get_value</a> returns by calling the
460.210 - built-in <a href="func:getattr">getattr</a> function.
460.211 -
460.212 -<br><br>
460.213 - If the index or keyword refers to an item that does not exist, then an
460.214 - <a href="exc:IndexError">IndexError</a> or <a href="exc:KeyError">KeyError</a> should be raised.
460.215 -
460.216 -<br><br>
460.217 -<a href="meth:check_unused_args(used_args, args, kwargs)">check_unused_args(used_args, args, kwargs)</a>
460.218 -
460.219 -<br><br>
460.220 - Implement checking for unused arguments if desired. The arguments to this
460.221 - function is the set of all argument keys that were actually referred to in
460.222 - the format string (integers for positional arguments, and strings for
460.223 - named arguments), and a reference to the <b>args</b> and <b>kwargs</b> that was
460.224 - passed to vformat. The set of unused args can be calculated from these
460.225 - parameters. <a href="meth:check_unused_args">check_unused_args</a> is assumed to throw an exception if
460.226 - the check fails.
460.227 -
460.228 -<br><br>
460.229 -<a href="meth:format_field(value, format_spec)">format_field(value, format_spec)</a>
460.230 -
460.231 -<br><br>
460.232 - <a href="meth:format_field">format_field</a> simply calls the global <a href="func:format">format</a> built-in. The
460.233 - method is provided so that subclasses can override it.
460.234 -
460.235 -<br><br>
460.236 -<a href="meth:convert_field(value, conversion)">convert_field(value, conversion)</a>
460.237 -
460.238 -<br><br>
460.239 - Converts the value (returned by <a href="meth:get_field">get_field</a>) given a conversion type
460.240 - (as in the tuple returned by the <a href="meth:parse">parse</a> method.) The default
460.241 - version understands 'r' (repr) and 's' (str) conversion types.
460.242 -
460.243 -<br><br>
460.244 -
460.245 -<br><br>
460.246 -<h3>Format String Syntax
460.247 -</h3>
460.248 -The <a href="meth:str.format">str.format</a> method and the <a href="class:Formatter">Formatter</a> class share the same
460.249 -syntax for format strings (although in the case of <a href="class:Formatter">Formatter</a>,
460.250 -subclasses can define their own format string syntax.)
460.251 -
460.252 -<br><br>
460.253 -Format strings contain "replacement fields" surrounded by curly braces <code>{}</code>.
460.254 -Anything that is not contained in braces is considered literal text, which is
460.255 -copied unchanged to the output. If you need to include a brace character in the
460.256 -literal text, it can be escaped by doubling: <code>{{</code> and <code>}}</code>.
460.257 -
460.258 -<br><br>
460.259 -The grammar for a replacement field is as follows:
460.260 -
460.261 -<br><br>
460.262 -
460.263 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
460.264 - <span style="">.</span><span style="">.</span> <span style="">productionlist</span><span style="">:</span><span style="">:</span> <span style="">sf</span><span style="color:#000000;"><br></span> <span style="">replacement_field</span><span style="">:</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">{</span></span><span style="color:#ce7b00;">"</span> <span style="">`</span><span style="">field_name</span><span style="">`</span> <span style="">[</span><span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">!</span></span><span style="color:#ce7b00;">"</span> <span style="">`</span><span style="">conversion</span><span style="">`</span><span style="">]</span> <span style="">[</span><span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">:</span></span><span style="color:#ce7b00;">"</span> <span style="">`</span><span style="">format_spec</span><span style="">`</span><span style="">]</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">}</span></span><span style="color:#ce7b00;">"</span><span style="color:#000000;"><br></span> <span style="">field_name</span><span style="">:</span> <span style="">(</span><span style="">`</span><span style="">identifier</span><span style="">`</span> <span style="">|</span> <span style="">`</span><span style="">integer</span><span style="">`</span><span style="">)</span> <span style="">(</span><span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">.</span></span><span style="color:#ce7b00;">"</span> <span style="">`</span><span style="">attribute_name</span><span style="">`</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">[</span></span><span style="color:#ce7b00;">"</span> <span style="">element_index</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">]</span></span><span style="color:#ce7b00;">"</span><span style="">)</span><span style="">*</span><span style="color:#000000;"><br></span> <span style="">attribute_name</span><span style="">:</span> <span style="">`</span><span style="">identifier</span><span style="">`</span><span style="color:#000000;"><br></span> <span style="">element_index</span><span style="">:</span> <span style="">`</span><span style="">integer</span><span style="">`</span><span style="color:#000000;"><br></span> <span style="">conversion</span><span style="">:</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">r</span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">s</span></span><span style="color:#ce7b00;">"</span><span style="color:#000000;"><br></span> <span style="">format_spec</span><span style="">:</span> <span style=""><</span><span style="">described</span> <span style="color:#0000e6;">in</span> <span style="">the</span> <span style="">next</span> <span style="">section</span><span style="">></span><span style="color:#000000;"><br></span></pre>
460.265 -In less formal terms, the replacement field starts with a <b>field_name</b>, which
460.266 -can either be a number (for a positional argument), or an identifier (for
460.267 -keyword arguments). Following this is an optional <b>conversion</b> field, which is
460.268 -preceded by an exclamation point <code>'!'</code>, and a <b>format_spec</b>, which is preceded
460.269 -by a colon <code>':'</code>.
460.270 -
460.271 -<br><br>
460.272 -The <b>field_name</b> itself begins with either a number or a keyword. If it's a
460.273 -number, it refers to a positional argument, and if it's a keyword it refers to a
460.274 -named keyword argument. This can be followed by any number of index or
460.275 -attribute expressions. An expression of the form <code>'.name'</code> selects the named
460.276 -attribute using <a href="func:getattr">getattr</a>, while an expression of the form <code>'[index]'</code>
460.277 -does an index lookup using <a href="func:__getitem__">__getitem__</a>.
460.278 -
460.279 -<br><br>
460.280 -Some simple format string examples::
460.281 -
460.282 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
460.283 - <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">First, thou shalt count to {0}</span></span><span style="color:#ce7b00;">"</span> <span style="color:#969696"><span style="color:#969696;"># References first positional argument</span></span><span style="color:#000000;"><br></span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">My quest is {name}</span></span><span style="color:#ce7b00;">"</span> <span style="color:#969696"><span style="color:#969696;"># References keyword argument 'name'</span></span><span style="color:#000000;"><br></span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">Weight in tons {0.weight}</span></span><span style="color:#ce7b00;">"</span> <span style="color:#969696"><span style="color:#969696;"># 'weight' attribute of first positional arg</span></span><span style="color:#000000;"><br></span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">Units destroyed: {players[0]}</span></span><span style="color:#ce7b00;">"</span> <span style="color:#969696"><span style="color:#969696;"># First element of keyword argument 'players'.</span></span><span style="color:#000000;"><br></span></pre>
460.284 -The <b>conversion</b> field causes a type coercion before formatting. Normally, the
460.285 -job of formatting a value is done by the <a href="meth:__format__">__format__</a> method of the value
460.286 -itself. However, in some cases it is desirable to force a type to be formatted
460.287 -as a string, overriding its own definition of formatting. By converting the
460.288 -value to a string before calling <a href="meth:__format__">__format__</a>, the normal formatting logic
460.289 -is bypassed.
460.290 -
460.291 -<br><br>
460.292 -Two conversion flags are currently supported: <code>'!s'</code> which calls <a href="func:str">str</a>
460.293 -on the value, and <code>'!r'</code> which calls <a href="func:repr">repr</a>.
460.294 -
460.295 -<br><br>
460.296 -Some examples::
460.297 -
460.298 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
460.299 - <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">Harold's a clever {0!s}</span></span><span style="color:#ce7b00;">"</span> <span style="color:#969696"><span style="color:#969696;"># Calls str() on the argument first</span></span><span style="color:#000000;"><br></span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">Bring out the holy {name!r}</span></span><span style="color:#ce7b00;">"</span> <span style="color:#969696"><span style="color:#969696;"># Calls repr() on the argument first</span></span><span style="color:#000000;"><br></span></pre>
460.300 -The <b>format_spec</b> field contains a specification of how the value should be
460.301 -presented, including such details as field width, alignment, padding, decimal
460.302 -precision and so on. Each value type can define it's own "formatting
460.303 -mini-language" or interpretation of the <b>format_spec</b>.
460.304 -
460.305 -<br><br>
460.306 -Most built-in types support a common formatting mini-language, which is
460.307 -described in the next section.
460.308 -
460.309 -<br><br>
460.310 -A <b>format_spec</b> field can also include nested replacement fields within it.
460.311 -These nested replacement fields can contain only a field name; conversion flags
460.312 -and format specifications are not allowed. The replacement fields within the
460.313 -format_spec are substituted before the <b>format_spec</b> string is interpreted.
460.314 -This allows the formatting of a value to be dynamically specified.
460.315 -
460.316 -<br><br>
460.317 -For example, suppose you wanted to have a replacement field whose field width is
460.318 -determined by another variable::
460.319 -
460.320 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
460.321 - <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">A man with two {0:{1}}</span></span><span style="color:#ce7b00;">"</span><span style="">.</span><span style="">format</span><span style="">(</span><span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">noses</span></span><span style="color:#ce7b00;">"</span><span style="">,</span> <span style="color:#000000;">10</span><span style="">)</span><span style="color:#000000;"><br></span></pre>
460.322 -This would first evaluate the inner replacement field, making the format string
460.323 -effectively::
460.324 -
460.325 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
460.326 - <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">A man with two {0:10}</span></span><span style="color:#ce7b00;">"</span><span style="color:#000000;"><br></span></pre>
460.327 -Then the outer replacement field would be evaluated, producing::
460.328 -
460.329 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
460.330 - <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">noses </span></span><span style="color:#ce7b00;">"</span><span style="color:#000000;"><br></span></pre>
460.331 -Which is substituted into the string, yielding::
460.332 -
460.333 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
460.334 - <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">A man with two noses </span></span><span style="color:#ce7b00;">"</span><span style="color:#000000;"><br></span></pre>
460.335 -(The extra space is because we specified a field width of 10, and because left
460.336 -alignment is the default for strings.)
460.337 -
460.338 -<br><br>
460.339 -
460.340 -<br><br>
460.341 -<h3>Format Specification Mini-Language
460.342 -</h3>
460.343 -"Format specifications" are used within replacement fields contained within a
460.344 -format string to define how individual values are presented (see
460.345 -<code>formatstrings</code>.) They can also be passed directly to the builtin
460.346 -<a href="func:format">format</a> function. Each formattable type may define how the format
460.347 -specification is to be interpreted.
460.348 -
460.349 -<br><br>
460.350 -Most built-in types implement the following options for format specifications,
460.351 -although some of the formatting options are only supported by the numeric types.
460.352 -
460.353 -<br><br>
460.354 -A general convention is that an empty format string (<code>""</code>) produces the same
460.355 -result as if you had called <a href="func:str">str</a> on the value.
460.356 -
460.357 -<br><br>
460.358 -The general form of a *standard format specifier* is:
460.359 -
460.360 -<br><br>
460.361 -
460.362 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
460.363 -<span style="">.</span><span style="">.</span> <span style="">productionlist</span><span style="">:</span><span style="">:</span> <span style="">sf</span><span style="color:#000000;"><br></span> <span style="">format_spec</span><span style="">:</span> <span style="">[</span><span style="">[</span><span style="">`</span><span style="">fill</span><span style="">`</span><span style="">]</span><span style="">`</span><span style="">align</span><span style="">`</span><span style="">]</span><span style="">[</span><span style="">`</span><span style="">sign</span><span style="">`</span><span style="">]</span><span style="">[</span><span style="color:#969696"><span style="color:#969696;">#][0][`width`][.`precision`][`type`]</span></span><span style="color:#000000;"><br></span> <span style="">fill</span><span style="">:</span> <span style=""><</span><span style="">a</span> <span style="">character</span> <span style="">other</span> <span style="">than</span> <span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">}</span></span><span style="color:#ce7b00;">'</span><span style="">></span><span style="color:#000000;"><br></span> <span style="">align</span><span style="">:</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;"><</span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">></span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">=</span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">^</span></span><span style="color:#ce7b00;">"</span><span style="color:#000000;"><br></span> <span style="">sign</span><span style="">:</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">+</span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">-</span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;"> </span></span><span style="color:#ce7b00;">"</span><span style="color:#000000;"><br></span> <span style="">width</span><span style="">:</span> <span style="">`</span><span style="">integer</span><span style="">`</span><span style="color:#000000;"><br></span> <span style="">precision</span><span style="">:</span> <span style="">`</span><span style="">integer</span><span style="">`</span><span style="color:#000000;"><br></span> <span style="">type</span><span style="">:</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">b</span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">c</span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">d</span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">e</span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">E</span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">f</span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">F</span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">g</span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">G</span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">n</span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">o</span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">x</span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">X</span></span><span style="color:#ce7b00;">"</span> <span style="">|</span> <span style="color:#ce7b00;">"</span><span style="color:#ce7b00"><span style="color:#ce7b00;">%</span></span><span style="color:#ce7b00;">"</span><span style="color:#000000;"><br></span></pre>
460.364 -The <b>fill</b> character can be any character other than '}' (which signifies the
460.365 -end of the field). The presence of a fill character is signaled by the <b>next</b>
460.366 -character, which must be one of the alignment options. If the second character
460.367 -of <b>format_spec</b> is not a valid alignment option, then it is assumed that both
460.368 -the fill character and the alignment option are absent.
460.369 -
460.370 -<br><br>
460.371 -The meaning of the various alignment options is as follows:
460.372 -
460.373 -<br><br>
460.374 -<pre> +---------+----------------------------------------------------------+
460.375 - | Option | Meaning |
460.376 - +=========+==========================================================+
460.377 - | ``'<'`` | Forces the field to be left-aligned within the available |
460.378 - | | space (This is the default.) |
460.379 - +---------+----------------------------------------------------------+
460.380 - | ``'>'`` | Forces the field to be right-aligned within the |
460.381 - | | available space. |
460.382 - +---------+----------------------------------------------------------+
460.383 - | ``'='`` | Forces the padding to be placed after the sign (if any) |
460.384 - | | but before the digits. This is used for printing fields |
460.385 - | | in the form '+000000120'. This alignment option is only |
460.386 - | | valid for numeric types. |
460.387 - +---------+----------------------------------------------------------+
460.388 - | ``'^'`` | Forces the field to be centered within the available |
460.389 - | | space. |
460.390 - +---------+----------------------------------------------------------+
460.391 -</pre>
460.392 -Note that unless a minimum field width is defined, the field width will always
460.393 -be the same size as the data to fill it, so that the alignment option has no
460.394 -meaning in this case.
460.395 -
460.396 -<br><br>
460.397 -The <b>sign</b> option is only valid for number types, and can be one of the
460.398 -following:
460.399 -
460.400 -<br><br>
460.401 -<pre> +---------+----------------------------------------------------------+
460.402 - | Option | Meaning |
460.403 - +=========+==========================================================+
460.404 - | ``'+'`` | indicates that a sign should be used for both |
460.405 - | | positive as well as negative numbers. |
460.406 - +---------+----------------------------------------------------------+
460.407 - | ``'-'`` | indicates that a sign should be used only for negative |
460.408 - | | numbers (this is the default behavior). |
460.409 - +---------+----------------------------------------------------------+
460.410 - | space | indicates that a leading space should be used on |
460.411 - | | positive numbers, and a minus sign on negative numbers. |
460.412 - +---------+----------------------------------------------------------+
460.413 -</pre>
460.414 -The <code>'#'</code> option is only valid for integers, and only for binary, octal, or
460.415 -hexadecimal output. If present, it specifies that the output will be prefixed
460.416 -by <code>'0b'</code>, <code>'0o'</code>, or <code>'0x'</code>, respectively.
460.417 -
460.418 -<br><br>
460.419 -*width* is a decimal integer defining the minimum field width. If not
460.420 -specified, then the field width will be determined by the content.
460.421 -
460.422 -<br><br>
460.423 -If the <b>width</b> field is preceded by a zero (<code>'0'</code>) character, this enables
460.424 -zero-padding. This is equivalent to an <b>alignment</b> type of <code>'='</code> and a <b>fill</b>
460.425 -character of <code>'0'</code>.
460.426 -
460.427 -<br><br>
460.428 -The <b>precision</b> is a decimal number indicating how many digits should be
460.429 -displayed after the decimal point for a floating point value formatted with
460.430 -<code>'f'</code> and <code>'F'</code>, or before and after the decimal point for a floating point
460.431 -value formatted with <code>'g'</code> or <code>'G'</code>. For non-number types the field
460.432 -indicates the maximum field size - in other words, how many characters will be
460.433 -used from the field content. The <b>precision</b> is ignored for integer values.
460.434 -
460.435 -<br><br>
460.436 -Finally, the <b>type</b> determines how the data should be presented.
460.437 -
460.438 -<br><br>
460.439 -The available integer presentation types are:
460.440 -
460.441 -<br><br>
460.442 -<pre> +---------+----------------------------------------------------------+
460.443 - | Type | Meaning |
460.444 - +=========+==========================================================+
460.445 - | ``'b'`` | Binary format. Outputs the number in base 2. |
460.446 - +---------+----------------------------------------------------------+
460.447 - | ``'c'`` | Character. Converts the integer to the corresponding |
460.448 - | | unicode character before printing. |
460.449 - +---------+----------------------------------------------------------+
460.450 - | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
460.451 - +---------+----------------------------------------------------------+
460.452 - | ``'o'`` | Octal format. Outputs the number in base 8. |
460.453 - +---------+----------------------------------------------------------+
460.454 - | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
460.455 - | | case letters for the digits above 9. |
460.456 - +---------+----------------------------------------------------------+
460.457 - | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
460.458 - | | case letters for the digits above 9. |
460.459 - +---------+----------------------------------------------------------+
460.460 - | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
460.461 - | | the current locale setting to insert the appropriate |
460.462 - | | number separator characters. |
460.463 - +---------+----------------------------------------------------------+
460.464 - | None | The same as ``'d'``. |
460.465 - +---------+----------------------------------------------------------+
460.466 -</pre>
460.467 -The available presentation types for floating point and decimal values are:
460.468 -
460.469 -<br><br>
460.470 -<pre> +---------+----------------------------------------------------------+
460.471 - | Type | Meaning |
460.472 - +=========+==========================================================+
460.473 - | ``'e'`` | Exponent notation. Prints the number in scientific |
460.474 - | | notation using the letter 'e' to indicate the exponent. |
460.475 - +---------+----------------------------------------------------------+
460.476 - | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
460.477 - | | upper case 'E' as the separator character. |
460.478 - +---------+----------------------------------------------------------+
460.479 - | ``'f'`` | Fixed point. Displays the number as a fixed-point |
460.480 - | | number. |
460.481 - +---------+----------------------------------------------------------+
460.482 - | ``'F'`` | Fixed point. Same as ``'f'``. |
460.483 - +---------+----------------------------------------------------------+
460.484 - | ``'g'`` | General format. This prints the number as a fixed-point |
460.485 - | | number, unless the number is too large, in which case |
460.486 - | | it switches to ``'e'`` exponent notation. Infinity and |
460.487 - | | NaN values are formatted as ``inf``, ``-inf`` and |
460.488 - | | ``nan``, respectively. |
460.489 - +---------+----------------------------------------------------------+
460.490 - | ``'G'`` | General format. Same as ``'g'`` except switches to |
460.491 - | | ``'E'`` if the number gets to large. The representations |
460.492 - | | of infinity and NaN are uppercased, too. |
460.493 - +---------+----------------------------------------------------------+
460.494 - | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
460.495 - | | the current locale setting to insert the appropriate |
460.496 - | | number separator characters. |
460.497 - +---------+----------------------------------------------------------+
460.498 - | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
460.499 - | | in fixed (``'f'``) format, followed by a percent sign. |
460.500 - +---------+----------------------------------------------------------+
460.501 - | None | The same as ``'g'``. |
460.502 - +---------+----------------------------------------------------------+
460.503 -</pre>
460.504 -<h3>Template strings
460.505 -</h3>
460.506 -Templates provide simpler string substitutions as described in <a href="http://www.python.org/dev/peps/pep-0292/">PEP 292</a>.
460.507 -Instead of the normal <code>%</code>\ -based substitutions, Templates support <code>$</code>\
460.508 --based substitutions, using the following rules:
460.509 -
460.510 -<br><br>
460.511 -* <code>$$</code> is an escape; it is replaced with a single <code>$</code>.
460.512 -
460.513 -<br><br>
460.514 -* <code>$identifier</code> names a substitution placeholder matching a mapping key of
460.515 - <code>"identifier"</code>. By default, <code>"identifier"</code> must spell a Python
460.516 - identifier. The first non-identifier character after the <code>$</code> character
460.517 - terminates this placeholder specification.
460.518 -
460.519 -<br><br>
460.520 -* <code>${identifier}</code> is equivalent to <code>$identifier</code>. It is required when valid
460.521 - identifier characters follow the placeholder but are not part of the
460.522 - placeholder, such as <code>"${noun}ification"</code>.
460.523 -
460.524 -<br><br>
460.525 -Any other appearance of <code>$</code> in the string will result in a <a href="exc:ValueError">ValueError</a>
460.526 -being raised.
460.527 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.4
460.528 -</div>
460.529 -The <a href="mod:string">string</a> module provides a <a href="class:Template">Template</a> class that implements
460.530 -these rules. The methods of <a href="class:Template">Template</a> are:
460.531 -
460.532 -<br><br>
460.533 -<a href="class:Template(template)">Template(template)</a>
460.534 -
460.535 -<br><br>
460.536 - The constructor takes a single argument which is the template string.
460.537 -
460.538 -<br><br>
460.539 -<a href="meth:substitute(mapping[, **kws])">substitute(mapping[, **kws])</a>
460.540 -
460.541 -<br><br>
460.542 - Performs the template substitution, returning a new string. <b>mapping</b> is
460.543 - any dictionary-like object with keys that match the placeholders in the
460.544 - template. Alternatively, you can provide keyword arguments, where the
460.545 - keywords are the placeholders. When both <b>mapping</b> and <b>kws</b> are given
460.546 - and there are duplicates, the placeholders from <b>kws</b> take precedence.
460.547 -
460.548 -<br><br>
460.549 -<a href="meth:safe_substitute(mapping[, **kws])">safe_substitute(mapping[, **kws])</a>
460.550 -
460.551 -<br><br>
460.552 - Like <a href="meth:substitute">substitute</a>, except that if placeholders are missing from
460.553 - <b>mapping</b> and <b>kws</b>, instead of raising a <a href="exc:KeyError">KeyError</a> exception, the
460.554 - original placeholder will appear in the resulting string intact. Also,
460.555 - unlike with <a href="meth:substitute">substitute</a>, any other appearances of the <code>$</code> will
460.556 - simply return <code>$</code> instead of raising <a href="exc:ValueError">ValueError</a>.
460.557 -
460.558 -<br><br>
460.559 - While other exceptions may still occur, this method is called "safe"
460.560 - because substitutions always tries to return a usable string instead of
460.561 - raising an exception. In another sense, <a href="meth:safe_substitute">safe_substitute</a> may be
460.562 - anything other than safe, since it will silently ignore malformed
460.563 - templates containing dangling delimiters, unmatched braces, or
460.564 - placeholders that are not valid Python identifiers.
460.565 -
460.566 -<br><br>
460.567 -<a href="class:Template">Template</a> instances also provide one public data attribute:
460.568 -
460.569 -<br><br>
460.570 -<a href="attr:string.template">string.template</a>
460.571 -
460.572 -<br><br>
460.573 - This is the object passed to the constructor's <b>template</b> argument. In general,
460.574 - you shouldn't change it, but read-only access is not enforced.
460.575 -
460.576 -<br><br>
460.577 -Here is an example of how to use a Template:
460.578 -
460.579 -<br><br>
460.580 -<code>>>> <span style="color:#0000e6;">from</span> <span style="">string</span> <span style="color:#0000e6;">import</span> <span style="">Template</span><span style="color:#000000;"><br></span></code><code>>>> <span style="">s</span> <span style="">=</span> <span style="">Template</span><span style="">(</span><span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">$who likes $what</span></span><span style="color:#ce7b00;">'</span><span style="">)</span><span style="color:#000000;"><br></span></code><code>>>> <span style="">s</span><span style="">.</span><span style="">substitute</span><span style="">(</span><span style="">who</span><span style="">=</span><span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">tim</span></span><span style="color:#ce7b00;">'</span><span style="">,</span> <span style="">what</span><span style="">=</span><span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">kung pao</span></span><span style="color:#ce7b00;">'</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> 'tim likes kung pao'</code><br><code>>>> <span style="">d</span> <span style="">=</span> <span style="">dict</span><span style="">(</span><span style="">who</span><span style="">=</span><span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">tim</span></span><span style="color:#ce7b00;">'</span><span style="">)</span><span style="color:#000000;"><br></span></code><code>>>> <span style="">Template</span><span style="">(</span><span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">Give $who $100</span></span><span style="color:#ce7b00;">'</span><span style="">)</span><span style="">.</span><span style="">substitute</span><span style="">(</span><span style="">d</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> Traceback (most recent call last):</code><br><code> [...]</code><br><code> ValueError: Invalid placeholder in string: line 1, col 10</code><br><code>>>> <span style="">Template</span><span style="">(</span><span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">$who likes $what</span></span><span style="color:#ce7b00;">'</span><span style="">)</span><span style="">.</span><span style="">substitute</span><span style="">(</span><span style="">d</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> Traceback (most recent call last):</code><br><code> [...]</code><br><code> KeyError: 'what'</code><br><code>>>> <span style="">Template</span><span style="">(</span><span style="color:#ce7b00;">'</span><span style="color:#ce7b00"><span style="color:#ce7b00;">$who likes $what</span></span><span style="color:#ce7b00;">'</span><span style="">)</span><span style="">.</span><span style="">safe_substitute</span><span style="">(</span><span style="">d</span><span style="">)</span><span style="color:#000000;"><br></span></code><code> 'tim likes $what'</code><br>
460.581 -<br><br>
460.582 -Advanced usage: you can derive subclasses of <a href="class:Template">Template</a> to customize the
460.583 -placeholder syntax, delimiter character, or the entire regular expression used
460.584 -to parse template strings. To do this, you can override these class attributes:
460.585 -
460.586 -<br><br>
460.587 -* <b>delimiter</b> -- This is the literal string describing a placeholder introducing
460.588 - delimiter. The default value <code>$</code>. Note that this should <b>not</b> be a regular
460.589 - expression, as the implementation will call <a href="meth:re.escape">re.escape</a> on this string as
460.590 - needed.
460.591 -
460.592 -<br><br>
460.593 -* <b>idpattern</b> -- This is the regular expression describing the pattern for
460.594 - non-braced placeholders (the braces will be added automatically as
460.595 - appropriate). The default value is the regular expression
460.596 - <code>[_a-z][_a-z0-9]*</code>.
460.597 -
460.598 -<br><br>
460.599 -Alternatively, you can provide the entire regular expression pattern by
460.600 -overriding the class attribute <b>pattern</b>. If you do this, the value must be a
460.601 -regular expression object with four named capturing groups. The capturing
460.602 -groups correspond to the rules given above, along with the invalid placeholder
460.603 -rule:
460.604 -
460.605 -<br><br>
460.606 -* <b>escaped</b> -- This group matches the escape sequence, e.g. <code>$$</code>, in the
460.607 - default pattern.
460.608 -
460.609 -<br><br>
460.610 -* <b>named</b> -- This group matches the unbraced placeholder name; it should not
460.611 - include the delimiter in capturing group.
460.612 -
460.613 -<br><br>
460.614 -* <b>braced</b> -- This group matches the brace enclosed placeholder name; it should
460.615 - not include either the delimiter or braces in the capturing group.
460.616 -
460.617 -<br><br>
460.618 -* <b>invalid</b> -- This group matches any other delimiter pattern (usually a single
460.619 - delimiter), and it should appear last in the regular expression.
460.620 -
460.621 -<br><br>
460.622 -<h3>String functions
460.623 -</h3>
460.624 -The following functions are available to operate on string and Unicode objects.
460.625 -They are not available as string methods.
460.626 -
460.627 -<br><br>
460.628 -<a href="func:capwords(s)">capwords(s)</a>
460.629 -
460.630 -<br><br>
460.631 - Split the argument into words using <a href="func:split">split</a>, capitalize each word using
460.632 - <a href="func:capitalize">capitalize</a>, and join the capitalized words using <a href="func:join">join</a>. Note
460.633 - that this replaces runs of whitespace characters by a single space, and removes
460.634 - leading and trailing whitespace.
460.635 -
460.636 -<br><br>
460.637 -<a href="func:maketrans(from, to)">maketrans(from, to)</a>
460.638 -
460.639 -<br><br>
460.640 - Return a translation table suitable for passing to <a href="func:translate">translate</a>, that will
460.641 - map each character in <b>from</b> into the character at the same position in <b>to</b>;
460.642 - <b>from</b> and <b>to</b> must have the same length.
460.643 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>WARNING</b>:
460.644 -
460.645 -<br><br>
460.646 - Don't use strings derived from :const:<code>lowercase</code> and :const:<code>uppercase</code> as
460.647 - arguments; in some locales, these don't have the same length. For case
460.648 - conversions, always use <a href="func:lower">lower</a> and <a href="func:upper">upper</a>.
460.649 -</div>
460.650 -<h3>Deprecated string functions
460.651 -</h3>
460.652 -The following list of functions are also defined as methods of string and
460.653 -Unicode objects; see section <code>string-methods</code> for more information on
460.654 -those. You should consider these functions as deprecated, although they will
460.655 -not be removed until Python 3.0. The functions defined in this module are:
460.656 -
460.657 -<br><br>
460.658 -<a href="func:atof(s)">atof(s)</a>
460.659 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Deprecated</b>: 2.0
460.660 - Use the <a href="func:float">float</a> built-in function.
460.661 -</div>
460.662 - Convert a string to a floating point number. The string must have the standard
460.663 - syntax for a floating point literal in Python, optionally preceded by a sign
460.664 - (<code>+</code> or <code>-</code>). Note that this behaves identical to the built-in function
460.665 - <a href="func:float">float</a> when passed a string.
460.666 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
460.667 -
460.668 -<br><br>
460.669 - .. index::
460.670 - single: NaN
460.671 - single: Infinity
460.672 -
460.673 -<br><br>
460.674 - When passing in a string, values for NaN and Infinity may be returned, depending
460.675 - on the underlying C library. The specific set of strings accepted which cause
460.676 - these values to be returned depends entirely on the C library and is known to
460.677 - vary.
460.678 -</div>
460.679 -<a href="func:atoi(s[, base])">atoi(s[, base])</a>
460.680 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Deprecated</b>: 2.0
460.681 - Use the <a href="func:int">int</a> built-in function.
460.682 -</div>
460.683 - Convert string <b>s</b> to an integer in the given <b>base</b>. The string must consist
460.684 - of one or more digits, optionally preceded by a sign (<code>+</code> or <code>-</code>). The
460.685 - <b>base</b> defaults to 10. If it is 0, a default base is chosen depending on the
460.686 - leading characters of the string (after stripping the sign): <code>0x</code> or <code>0X</code>
460.687 - means 16, <code>0</code> means 8, anything else means 10. If <b>base</b> is 16, a leading
460.688 - <code>0x</code> or <code>0X</code> is always accepted, though not required. This behaves
460.689 - identically to the built-in function <a href="func:int">int</a> when passed a string. (Also
460.690 - note: for a more flexible interpretation of numeric literals, use the built-in
460.691 - function <a href="func:eval">eval</a>.)
460.692 -
460.693 -<br><br>
460.694 -<a href="func:atol(s[, base])">atol(s[, base])</a>
460.695 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Deprecated</b>: 2.0
460.696 - Use the <a href="func:long">long</a> built-in function.
460.697 -</div>
460.698 - Convert string <b>s</b> to a long integer in the given <b>base</b>. The string must
460.699 - consist of one or more digits, optionally preceded by a sign (<code>+</code> or <code>-</code>).
460.700 - The <b>base</b> argument has the same meaning as for <a href="func:atoi">atoi</a>. A trailing <code>l</code>
460.701 - or <code>L</code> is not allowed, except if the base is 0. Note that when invoked
460.702 - without <b>base</b> or with <b>base</b> set to 10, this behaves identical to the built-in
460.703 - function <a href="func:long">long</a> when passed a string.
460.704 -
460.705 -<br><br>
460.706 -<a href="func:capitalize(word)">capitalize(word)</a>
460.707 -
460.708 -<br><br>
460.709 - Return a copy of <b>word</b> with only its first character capitalized.
460.710 -
460.711 -<br><br>
460.712 -<a href="func:expandtabs(s[, tabsize])">expandtabs(s[, tabsize])</a>
460.713 -
460.714 -<br><br>
460.715 - Expand tabs in a string replacing them by one or more spaces, depending on the
460.716 - current column and the given tab size. The column number is reset to zero after
460.717 - each newline occurring in the string. This doesn't understand other non-printing
460.718 - characters or escape sequences. The tab size defaults to 8.
460.719 -
460.720 -<br><br>
460.721 -<a href="func:find(s, sub[, start[,end]])">find(s, sub[, start[,end]])</a>
460.722 -
460.723 -<br><br>
460.724 - Return the lowest index in <b>s</b> where the substring <b>sub</b> is found such that
460.725 - <b>sub</b> is wholly contained in <code>s[start:end]</code>. Return <code>-1</code> on failure.
460.726 - Defaults for <b>start</b> and <b>end</b> and interpretation of negative values is the same
460.727 - as for slices.
460.728 -
460.729 -<br><br>
460.730 -<a href="func:rfind(s, sub[, start[, end]])">rfind(s, sub[, start[, end]])</a>
460.731 -
460.732 -<br><br>
460.733 - Like <a href="func:find">find</a> but find the highest index.
460.734 -
460.735 -<br><br>
460.736 -<a href="func:index(s, sub[, start[, end]])">index(s, sub[, start[, end]])</a>
460.737 -
460.738 -<br><br>
460.739 - Like <a href="func:find">find</a> but raise <a href="exc:ValueError">ValueError</a> when the substring is not found.
460.740 -
460.741 -<br><br>
460.742 -<a href="func:rindex(s, sub[, start[, end]])">rindex(s, sub[, start[, end]])</a>
460.743 -
460.744 -<br><br>
460.745 - Like <a href="func:rfind">rfind</a> but raise <a href="exc:ValueError">ValueError</a> when the substring is not found.
460.746 -
460.747 -<br><br>
460.748 -<a href="func:count(s, sub[, start[, end]])">count(s, sub[, start[, end]])</a>
460.749 -
460.750 -<br><br>
460.751 - Return the number of (non-overlapping) occurrences of substring <b>sub</b> in string
460.752 - <code>s[start:end]</code>. Defaults for <b>start</b> and <b>end</b> and interpretation of negative
460.753 - values are the same as for slices.
460.754 -
460.755 -<br><br>
460.756 -<a href="func:lower(s)">lower(s)</a>
460.757 -
460.758 -<br><br>
460.759 - Return a copy of <b>s</b>, but with upper case letters converted to lower case.
460.760 -
460.761 -<br><br>
460.762 -<a href="func:split(s[, sep[, maxsplit]])">split(s[, sep[, maxsplit]])</a>
460.763 -
460.764 -<br><br>
460.765 - Return a list of the words of the string <b>s</b>. If the optional second argument
460.766 - <b>sep</b> is absent or <code>None</code>, the words are separated by arbitrary strings of
460.767 - whitespace characters (space, tab, newline, return, formfeed). If the second
460.768 - argument <b>sep</b> is present and not <code>None</code>, it specifies a string to be used as
460.769 - the word separator. The returned list will then have one more item than the
460.770 - number of non-overlapping occurrences of the separator in the string. The
460.771 - optional third argument <b>maxsplit</b> defaults to 0. If it is nonzero, at most
460.772 - <b>maxsplit</b> number of splits occur, and the remainder of the string is returned
460.773 - as the final element of the list (thus, the list will have at most
460.774 - <code>maxsplit+1</code> elements).
460.775 -
460.776 -<br><br>
460.777 - The behavior of split on an empty string depends on the value of <b>sep</b>. If <b>sep</b>
460.778 - is not specified, or specified as <code>None</code>, the result will be an empty list.
460.779 - If <b>sep</b> is specified as any string, the result will be a list containing one
460.780 - element which is an empty string.
460.781 -
460.782 -<br><br>
460.783 -<a href="func:rsplit(s[, sep[, maxsplit]])">rsplit(s[, sep[, maxsplit]])</a>
460.784 -
460.785 -<br><br>
460.786 - Return a list of the words of the string <b>s</b>, scanning <b>s</b> from the end. To all
460.787 - intents and purposes, the resulting list of words is the same as returned by
460.788 - <a href="func:split">split</a>, except when the optional third argument <b>maxsplit</b> is explicitly
460.789 - specified and nonzero. When <b>maxsplit</b> is nonzero, at most <b>maxsplit</b> number of
460.790 - splits -- the <b>rightmost</b> ones -- occur, and the remainder of the string is
460.791 - returned as the first element of the list (thus, the list will have at most
460.792 - <code>maxsplit+1</code> elements).
460.793 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.4
460.794 -</div>
460.795 -<a href="func:splitfields(s[, sep[, maxsplit]])">splitfields(s[, sep[, maxsplit]])</a>
460.796 - This function behaves identically to <a href="func:split">split</a>. (In the past, <a href="func:split">split</a>
460.797 - was only used with one argument, while <a href="func:splitfields">splitfields</a> was only used with
460.798 - two arguments.)
460.799 -
460.800 -<br><br>
460.801 -<a href="func:join(words[, sep])">join(words[, sep])</a>
460.802 -
460.803 -<br><br>
460.804 - Concatenate a list or tuple of words with intervening occurrences of <b>sep</b>.
460.805 - The default value for <b>sep</b> is a single space character. It is always true that
460.806 - <code>string.join(string.split(s, sep), sep)</code> equals <b>s</b>.
460.807 -
460.808 -<br><br>
460.809 -<a href="func:joinfields(words[, sep])">joinfields(words[, sep])</a>
460.810 -
460.811 -<br><br>
460.812 - This function behaves identically to <a href="func:join">join</a>. (In the past, <a href="func:join">join</a>
460.813 - was only used with one argument, while <a href="func:joinfields">joinfields</a> was only used with two
460.814 - arguments.) Note that there is no <a href="meth:joinfields">joinfields</a> method on string objects;
460.815 - use the <a href="meth:join">join</a> method instead.
460.816 -
460.817 -<br><br>
460.818 -<a href="func:lstrip(s[, chars])">lstrip(s[, chars])</a>
460.819 -
460.820 -<br><br>
460.821 - Return a copy of the string with leading characters removed. If <b>chars</b> is
460.822 - omitted or <code>None</code>, whitespace characters are removed. If given and not
460.823 - <code>None</code>, <b>chars</b> must be a string; the characters in the string will be
460.824 - stripped from the beginning of the string this method is called on.
460.825 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.2.3
460.826 - The <b>chars</b> parameter was added. The <b>chars</b> parameter cannot be passed in
460.827 - earlier 2.2 versions.
460.828 -</div>
460.829 -<a href="func:rstrip(s[, chars])">rstrip(s[, chars])</a>
460.830 - Return a copy of the string with trailing characters removed. If <b>chars</b> is
460.831 - omitted or <code>None</code>, whitespace characters are removed. If given and not
460.832 - <code>None</code>, <b>chars</b> must be a string; the characters in the string will be
460.833 - stripped from the end of the string this method is called on.
460.834 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.2.3
460.835 - The <b>chars</b> parameter was added. The <b>chars</b> parameter cannot be passed in
460.836 - earlier 2.2 versions.
460.837 -</div>
460.838 -<a href="func:strip(s[, chars])">strip(s[, chars])</a>
460.839 - Return a copy of the string with leading and trailing characters removed. If
460.840 - <b>chars</b> is omitted or <code>None</code>, whitespace characters are removed. If given and
460.841 - not <code>None</code>, <b>chars</b> must be a string; the characters in the string will be
460.842 - stripped from the both ends of the string this method is called on.
460.843 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.2.3
460.844 - The <b>chars</b> parameter was added. The <b>chars</b> parameter cannot be passed in
460.845 - earlier 2.2 versions.
460.846 -</div>
460.847 -<a href="func:swapcase(s)">swapcase(s)</a>
460.848 - Return a copy of <b>s</b>, but with lower case letters converted to upper case and
460.849 - vice versa.
460.850 -
460.851 -<br><br>
460.852 -<a href="func:translate(s, table[, deletechars])">translate(s, table[, deletechars])</a>
460.853 -
460.854 -<br><br>
460.855 - Delete all characters from <b>s</b> that are in <b>deletechars</b> (if present), and then
460.856 - translate the characters using <b>table</b>, which must be a 256-character string
460.857 - giving the translation for each character value, indexed by its ordinal. If
460.858 - <b>table</b> is <code>None</code>, then only the character deletion step is performed.
460.859 -
460.860 -<br><br>
460.861 -<a href="func:upper(s)">upper(s)</a>
460.862 -
460.863 -<br><br>
460.864 - Return a copy of <b>s</b>, but with lower case letters converted to upper case.
460.865 -
460.866 -<br><br>
460.867 -<a href="func:ljust(s, width)">ljust(s, width)</a>
460.868 - rjust(s, width)
460.869 - center(s, width)
460.870 -
460.871 -<br><br>
460.872 - These functions respectively left-justify, right-justify and center a string in
460.873 - a field of given width. They return a string that is at least <b>width</b>
460.874 - characters wide, created by padding the string <b>s</b> with spaces until the given
460.875 - width on the right, left or both sides. The string is never truncated.
460.876 -
460.877 -<br><br>
460.878 -<a href="func:zfill(s, width)">zfill(s, width)</a>
460.879 -
460.880 -<br><br>
460.881 - Pad a numeric string on the left with zero digits until the given width is
460.882 - reached. Strings starting with a sign are handled correctly.
460.883 -
460.884 -<br><br>
460.885 -<a href="func:replace(str, old, new[, maxreplace])">replace(str, old, new[, maxreplace])</a>
460.886 -
460.887 -<br><br>
460.888 - Return a copy of string <b>str</b> with all occurrences of substring <b>old</b> replaced
460.889 - by <b>new</b>. If the optional argument <b>maxreplace</b> is given, the first
460.890 - <b>maxreplace</b> occurrences are replaced.
460.891 -</body></html>
461.1 --- a/python.editor/test/unit/data/testfiles/rst/string.rst.indexed Sun Jan 04 13:11:53 2015 -0600
461.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
461.3 @@ -1,82 +0,0 @@
461.4 -
461.5 -
461.6 -Document 0
461.7 -Searchable Keys:
461.8 - class : Formatter
461.9 - class-ig : formatter
461.10 - in : string
461.11 - member : check_unused_args;F;|DOCUMENTED|DOC_ONLY|;used_args,args,kwargs;
461.12 - member : convert_field;F;|DOCUMENTED|DOC_ONLY|;value,conversion;
461.13 - member : format;F;|DOCUMENTED|DOC_ONLY|;format_string,*args,*kwargs;
461.14 - member : format_field;F;|DOCUMENTED|DOC_ONLY|;value,format_spec;
461.15 - member : get_field;F;|DOCUMENTED|DOC_ONLY|;field_name,args,kwargs;
461.16 - member : get_value;F;|DOCUMENTED|DOC_ONLY|;key,args,kwargs;
461.17 - member : parse;F;|DOCUMENTED|DOC_ONLY|;format_string;
461.18 - member : vformat;F;|DOCUMENTED|DOC_ONLY|;format_string,args,kwargs;
461.19 -
461.20 -Not Searchable Keys:
461.21 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
461.22 -
461.23 -
461.24 -Document 1
461.25 -Searchable Keys:
461.26 - class : Template
461.27 - class-ig : template
461.28 - in : string
461.29 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;template;
461.30 - member : safe_substitute;F;|DOCUMENTED|DOC_ONLY|;mapping,**kws;
461.31 - member : substitute;F;|DOCUMENTED|DOC_ONLY|;mapping,**kws;
461.32 -
461.33 -Not Searchable Keys:
461.34 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
461.35 -
461.36 -
461.37 -Document 2
461.38 -Searchable Keys:
461.39 - item : Formatter;C;|DOCUMENTED|DOC_ONLY|;
461.40 - item : Template;C;|DOCUMENTED|DOC_ONLY|;
461.41 - item : ascii_letters;D;|DOCUMENTED|DOC_ONLY|;
461.42 - item : ascii_lowercase;D;|DOCUMENTED|DOC_ONLY|;
461.43 - item : ascii_uppercase;D;|DOCUMENTED|DOC_ONLY|;
461.44 - item : atof;F;|DOCUMENTED|DEPRECATED|DOC_ONLY|;s;
461.45 - item : atoi;F;|DOCUMENTED|DEPRECATED|DOC_ONLY|;s,base;
461.46 - item : atol;F;|DOCUMENTED|DEPRECATED|DOC_ONLY|;s,base;
461.47 - item : capitalize;F;|DOCUMENTED|DOC_ONLY|;word;
461.48 - item : capwords;F;|DOCUMENTED|DOC_ONLY|;s;
461.49 - item : center;F;|DOCUMENTED|DOC_ONLY|;s,width;
461.50 - item : count;F;|DOCUMENTED|DOC_ONLY|;s,sub,start,end;
461.51 - item : digits;D;|DOCUMENTED|DOC_ONLY|;
461.52 - item : expandtabs;F;|DOCUMENTED|DOC_ONLY|;s,tabsize;
461.53 - item : find;F;|DOCUMENTED|DOC_ONLY|;s,sub,start,end;
461.54 - item : hexdigits;D;|DOCUMENTED|DOC_ONLY|;
461.55 - item : index;F;|DOCUMENTED|DOC_ONLY|;s,sub,start,end;
461.56 - item : join;F;|DOCUMENTED|DOC_ONLY|;words,sep;
461.57 - item : joinfields;F;|DOCUMENTED|DOC_ONLY|;words,sep;
461.58 - item : letters;D;|DOCUMENTED|DOC_ONLY|;
461.59 - item : ljust;F;|DOCUMENTED|DOC_ONLY|;s,width;
461.60 - item : lower;F;|DOCUMENTED|DOC_ONLY|;s;
461.61 - item : lowercase;D;|DOCUMENTED|DOC_ONLY|;
461.62 - item : lstrip;F;|DOCUMENTED|DOC_ONLY|;s,chars;
461.63 - item : maketrans;F;|DOCUMENTED|DOC_ONLY|;from,to;
461.64 - item : octdigits;D;|DOCUMENTED|DOC_ONLY|;
461.65 - item : printable;D;|DOCUMENTED|DOC_ONLY|;
461.66 - item : punctuation;D;|DOCUMENTED|DOC_ONLY|;
461.67 - item : replace;F;|DOCUMENTED|DOC_ONLY|;str,old,new,maxreplace;
461.68 - item : rfind;F;|DOCUMENTED|DOC_ONLY|;s,sub,start,end;
461.69 - item : rindex;F;|DOCUMENTED|DOC_ONLY|;s,sub,start,end;
461.70 - item : rjust;F;|DOCUMENTED|DOC_ONLY|;s,width;
461.71 - item : rsplit;F;|DOCUMENTED|DOC_ONLY|;s,sep,maxsplit;
461.72 - item : rstrip;F;|DOCUMENTED|DOC_ONLY|;s,chars;
461.73 - item : split;F;|DOCUMENTED|DOC_ONLY|;s,sep,maxsplit;
461.74 - item : splitfields;F;|DOCUMENTED|DOC_ONLY|;s,sep,maxsplit;
461.75 - item : strip;F;|DOCUMENTED|DOC_ONLY|;s,chars;
461.76 - item : swapcase;F;|DOCUMENTED|DOC_ONLY|;s;
461.77 - item : translate;F;|DOCUMENTED|DOC_ONLY|;s,table,deletechars;
461.78 - item : upper;F;|DOCUMENTED|DOC_ONLY|;s;
461.79 - item : uppercase;D;|DOCUMENTED|DOC_ONLY|;
461.80 - item : whitespace;D;|DOCUMENTED|DOC_ONLY|;
461.81 - item : zfill;F;|DOCUMENTED|DOC_ONLY|;s,width;
461.82 - module : string
461.83 -
461.84 -Not Searchable Keys:
461.85 - modattrs : S
462.1 --- a/python.editor/test/unit/data/testfiles/rst/stub_missing.rst Sun Jan 04 13:11:53 2015 -0600
462.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
462.3 @@ -1,2367 +0,0 @@
462.4 -NetBeans extra documentation:
462.5 -Documentation for APIs missing from the RST documentation shipping with Python.
462.6 -This is generated from introspecting python code using extract_rst.py.
462.7 -Python version stats:
462.8 -2.6 (trunk:66714:66715M, Oct 1 2008, 18:36:04)
462.9 -[GCC 4.0.1 (Apple Computer, Inc. build 5370)]
462.10 -
462.11 -
462.12 -.. class:: int
462.13 -
462.14 - int(x[, base]) -> integer
462.15 -
462.16 - Convert a string or number to an integer, if possible. A floating point
462.17 - argument will be truncated towards zero (this does not include a string
462.18 - representation of a floating point number!) When converting a string, use
462.19 - the optional base. It is an error to supply a base when converting a
462.20 - non-string. If base is zero, the proper base is guessed based on the
462.21 - string content. If the argument is outside the integer range a
462.22 - long object will be returned instead.
462.23 -
462.24 -
462.25 -.. attribute:: __class__
462.26 -
462.27 - int(x[, base]) -> integer
462.28 -
462.29 - Convert a string or number to an integer, if possible. A floating point
462.30 - argument will be truncated towards zero (this does not include a string
462.31 - representation of a floating point number!) When converting a string, use
462.32 - the optional base. It is an error to supply a base when converting a
462.33 - non-string. If base is zero, the proper base is guessed based on the
462.34 - string content. If the argument is outside the integer range a
462.35 - long object will be returned instead.
462.36 -
462.37 -
462.38 -.. method:: __cmp__(y)
462.39 -
462.40 - x.__cmp__(y) <==> cmp(x,y)
462.41 -
462.42 -
462.43 -.. method:: __coerce__(y)
462.44 -
462.45 - x.__coerce__(y) <==> coerce(x, y)
462.46 -
462.47 -
462.48 -.. method:: __delattr__(name)
462.49 -
462.50 - x.__delattr__('name') <==> del x.name
462.51 -
462.52 -
462.53 -.. method:: __divmod__(y)
462.54 -
462.55 - x.__divmod__(y) <==> divmod(x, y)
462.56 -
462.57 -
462.58 -.. attribute:: __doc__
462.59 -
462.60 - str(object) -> string
462.61 -
462.62 - Return a nice string representation of the object.
462.63 - If the argument is a string, the return value is the same object.
462.64 -
462.65 -
462.66 -.. method:: __float__()
462.67 -
462.68 - x.__float__() <==> float(x)
462.69 -
462.70 -
462.71 -.. method:: __format__()
462.72 -
462.73 - .. versionadded:: 2.6
462.74 -
462.75 -.. method:: __getattribute__(name)
462.76 -
462.77 - x.__getattribute__('name') <==> x.name
462.78 -
462.79 -
462.80 -.. method:: __getnewargs__()
462.81 -
462.82 -
462.83 -.. method:: __hash__()
462.84 -
462.85 - x.__hash__() <==> hash(x)
462.86 -
462.87 -
462.88 -.. method:: __hex__()
462.89 -
462.90 - x.__hex__() <==> hex(x)
462.91 -
462.92 -
462.93 -.. method:: __init__()
462.94 -
462.95 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
462.96 -
462.97 -
462.98 -.. method:: __int__()
462.99 -
462.100 - x.__int__() <==> int(x)
462.101 -
462.102 -
462.103 -.. method:: __long__()
462.104 -
462.105 - x.__long__() <==> long(x)
462.106 -
462.107 -
462.108 -.. method:: __new__(S, ___)
462.109 -
462.110 - T.__new__(S, ...) -> a new object with type S, a subtype of T
462.111 -
462.112 -
462.113 -.. method:: __nonzero__()
462.114 -
462.115 - x.__nonzero__() <==> x != 0
462.116 -
462.117 -
462.118 -.. method:: __oct__()
462.119 -
462.120 - x.__oct__() <==> oct(x)
462.121 -
462.122 -
462.123 -.. method:: __radd__(y)
462.124 -
462.125 - x.__radd__(y) <==> y+x
462.126 -
462.127 -
462.128 -.. method:: __rand__(y)
462.129 -
462.130 - x.__rand__(y) <==> y&x
462.131 -
462.132 -
462.133 -.. method:: __rdiv__(y)
462.134 -
462.135 - x.__rdiv__(y) <==> y/x
462.136 -
462.137 -
462.138 -.. method:: __rdivmod__(y)
462.139 -
462.140 - x.__rdivmod__(y) <==> divmod(y, x)
462.141 -
462.142 -
462.143 -.. method:: __reduce__()
462.144 -
462.145 - helper for pickle
462.146 -
462.147 -
462.148 -.. method:: __reduce_ex__()
462.149 -
462.150 - helper for pickle
462.151 -
462.152 -
462.153 -.. method:: __repr__()
462.154 -
462.155 - x.__repr__() <==> repr(x)
462.156 -
462.157 -
462.158 -.. method:: __rfloordiv__(y)
462.159 -
462.160 - x.__rfloordiv__(y) <==> y//x
462.161 -
462.162 -
462.163 -.. method:: __rlshift__(y)
462.164 -
462.165 - x.__rlshift__(y) <==> y<<x
462.166 -
462.167 -
462.168 -.. method:: __rmod__(y)
462.169 -
462.170 - x.__rmod__(y) <==> y%x
462.171 -
462.172 -
462.173 -.. method:: __rmul__(y)
462.174 -
462.175 - x.__rmul__(y) <==> y*x
462.176 -
462.177 -
462.178 -.. method:: __ror__(y)
462.179 -
462.180 - x.__ror__(y) <==> y|x
462.181 -
462.182 -
462.183 -.. method:: __rpow__(x)
462.184 -
462.185 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
462.186 -
462.187 -
462.188 -.. method:: __rrshift__(y)
462.189 -
462.190 - x.__rrshift__(y) <==> y>>x
462.191 -
462.192 -
462.193 -.. method:: __rsub__(y)
462.194 -
462.195 - x.__rsub__(y) <==> y-x
462.196 -
462.197 -
462.198 -.. method:: __rtruediv__(y)
462.199 -
462.200 - x.__rtruediv__(y) <==> y/x
462.201 -
462.202 -
462.203 -.. method:: __rxor__(y)
462.204 -
462.205 - x.__rxor__(y) <==> y^x
462.206 -
462.207 -
462.208 -.. method:: __setattr__(name, value)
462.209 -
462.210 - x.__setattr__('name', value) <==> x.name = value
462.211 -
462.212 -
462.213 -.. method:: __sizeof__()
462.214 -
462.215 - __sizeof__() -> size of object in memory, in bytes
462.216 -
462.217 - .. versionadded:: 2.6
462.218 -
462.219 -.. method:: __str__()
462.220 -
462.221 - x.__str__() <==> str(x)
462.222 -
462.223 -
462.224 -.. method:: __subclasshook__()
462.225 -
462.226 - Abstract classes can override this to customize issubclass().
462.227 -
462.228 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
462.229 - It should return True, False or NotImplemented. If it returns
462.230 - NotImplemented, the normal algorithm is used. Otherwise, it
462.231 - overrides the normal algorithm (and the outcome is cached).
462.232 -
462.233 -
462.234 - .. versionadded:: 2.6
462.235 -
462.236 -.. method:: __trunc__()
462.237 -
462.238 - Truncating an Integral returns itself.
462.239 -
462.240 - .. versionadded:: 2.6
462.241 -
462.242 -.. method:: conjugate()
462.243 -
462.244 - Returns self, the complex conjugate of any int.
462.245 -
462.246 - .. versionadded:: 2.6
462.247 -
462.248 -.. attribute:: denominator
462.249 -
462.250 - int(x[, base]) -> integer
462.251 -
462.252 - Convert a string or number to an integer, if possible. A floating point
462.253 - argument will be truncated towards zero (this does not include a string
462.254 - representation of a floating point number!) When converting a string, use
462.255 - the optional base. It is an error to supply a base when converting a
462.256 - non-string. If base is zero, the proper base is guessed based on the
462.257 - string content. If the argument is outside the integer range a
462.258 - long object will be returned instead.
462.259 -
462.260 - .. versionadded:: 2.6
462.261 -
462.262 -.. attribute:: imag
462.263 -
462.264 - int(x[, base]) -> integer
462.265 -
462.266 - Convert a string or number to an integer, if possible. A floating point
462.267 - argument will be truncated towards zero (this does not include a string
462.268 - representation of a floating point number!) When converting a string, use
462.269 - the optional base. It is an error to supply a base when converting a
462.270 - non-string. If base is zero, the proper base is guessed based on the
462.271 - string content. If the argument is outside the integer range a
462.272 - long object will be returned instead.
462.273 -
462.274 - .. versionadded:: 2.6
462.275 -
462.276 -.. attribute:: numerator
462.277 -
462.278 - int(x[, base]) -> integer
462.279 -
462.280 - Convert a string or number to an integer, if possible. A floating point
462.281 - argument will be truncated towards zero (this does not include a string
462.282 - representation of a floating point number!) When converting a string, use
462.283 - the optional base. It is an error to supply a base when converting a
462.284 - non-string. If base is zero, the proper base is guessed based on the
462.285 - string content. If the argument is outside the integer range a
462.286 - long object will be returned instead.
462.287 -
462.288 - .. versionadded:: 2.6
462.289 -
462.290 -.. attribute:: real
462.291 -
462.292 - int(x[, base]) -> integer
462.293 -
462.294 - Convert a string or number to an integer, if possible. A floating point
462.295 - argument will be truncated towards zero (this does not include a string
462.296 - representation of a floating point number!) When converting a string, use
462.297 - the optional base. It is an error to supply a base when converting a
462.298 - non-string. If base is zero, the proper base is guessed based on the
462.299 - string content. If the argument is outside the integer range a
462.300 - long object will be returned instead.
462.301 -
462.302 - .. versionadded:: 2.6
462.303 -
462.304 -.. class:: float
462.305 -
462.306 - float(x) -> floating point number
462.307 -
462.308 - Convert a string or number to a floating point number, if possible.
462.309 -
462.310 -
462.311 -.. attribute:: __class__
462.312 -
462.313 - float(x) -> floating point number
462.314 -
462.315 - Convert a string or number to a floating point number, if possible.
462.316 -
462.317 -
462.318 -.. method:: __coerce__(y)
462.319 -
462.320 - x.__coerce__(y) <==> coerce(x, y)
462.321 -
462.322 -
462.323 -.. method:: __delattr__(name)
462.324 -
462.325 - x.__delattr__('name') <==> del x.name
462.326 -
462.327 -
462.328 -.. method:: __divmod__(y)
462.329 -
462.330 - x.__divmod__(y) <==> divmod(x, y)
462.331 -
462.332 -
462.333 -.. attribute:: __doc__
462.334 -
462.335 - str(object) -> string
462.336 -
462.337 - Return a nice string representation of the object.
462.338 - If the argument is a string, the return value is the same object.
462.339 -
462.340 -
462.341 -.. method:: __float__()
462.342 -
462.343 - x.__float__() <==> float(x)
462.344 -
462.345 -
462.346 -.. method:: __format__(format_spec)
462.347 -
462.348 - float.__format__(format_spec) -> string
462.349 -
462.350 - Formats the float according to format_spec.
462.351 -
462.352 - .. versionadded:: 2.6
462.353 -
462.354 -.. method:: __getattribute__(name)
462.355 -
462.356 - x.__getattribute__('name') <==> x.name
462.357 -
462.358 -
462.359 -.. method:: __getformat__(typestr)
462.360 -
462.361 - float.__getformat__(typestr) -> string
462.362 -
462.363 - You probably don't want to use this function. It exists mainly to be
462.364 - used in Python's test suite.
462.365 -
462.366 - typestr must be 'double' or 'float'. This function returns whichever of
462.367 - 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the
462.368 - format of floating point numbers used by the C type named by typestr.
462.369 -
462.370 -
462.371 -.. method:: __getnewargs__()
462.372 -
462.373 -
462.374 -.. method:: __hash__()
462.375 -
462.376 - x.__hash__() <==> hash(x)
462.377 -
462.378 -
462.379 -.. method:: __init__()
462.380 -
462.381 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
462.382 -
462.383 -
462.384 -.. method:: __int__()
462.385 -
462.386 - x.__int__() <==> int(x)
462.387 -
462.388 -
462.389 -.. method:: __long__()
462.390 -
462.391 - x.__long__() <==> long(x)
462.392 -
462.393 -
462.394 -.. method:: __new__(S, ___)
462.395 -
462.396 - T.__new__(S, ...) -> a new object with type S, a subtype of T
462.397 -
462.398 -
462.399 -.. method:: __nonzero__()
462.400 -
462.401 - x.__nonzero__() <==> x != 0
462.402 -
462.403 -
462.404 -.. method:: __radd__(y)
462.405 -
462.406 - x.__radd__(y) <==> y+x
462.407 -
462.408 -
462.409 -.. method:: __rdiv__(y)
462.410 -
462.411 - x.__rdiv__(y) <==> y/x
462.412 -
462.413 -
462.414 -.. method:: __rdivmod__(y)
462.415 -
462.416 - x.__rdivmod__(y) <==> divmod(y, x)
462.417 -
462.418 -
462.419 -.. method:: __reduce__()
462.420 -
462.421 - helper for pickle
462.422 -
462.423 -
462.424 -.. method:: __reduce_ex__()
462.425 -
462.426 - helper for pickle
462.427 -
462.428 -
462.429 -.. method:: __repr__()
462.430 -
462.431 - x.__repr__() <==> repr(x)
462.432 -
462.433 -
462.434 -.. method:: __rfloordiv__(y)
462.435 -
462.436 - x.__rfloordiv__(y) <==> y//x
462.437 -
462.438 -
462.439 -.. method:: __rmod__(y)
462.440 -
462.441 - x.__rmod__(y) <==> y%x
462.442 -
462.443 -
462.444 -.. method:: __rmul__(y)
462.445 -
462.446 - x.__rmul__(y) <==> y*x
462.447 -
462.448 -
462.449 -.. method:: __rpow__(x)
462.450 -
462.451 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
462.452 -
462.453 -
462.454 -.. method:: __rsub__(y)
462.455 -
462.456 - x.__rsub__(y) <==> y-x
462.457 -
462.458 -
462.459 -.. method:: __rtruediv__(y)
462.460 -
462.461 - x.__rtruediv__(y) <==> y/x
462.462 -
462.463 -
462.464 -.. method:: __setattr__(name, value)
462.465 -
462.466 - x.__setattr__('name', value) <==> x.name = value
462.467 -
462.468 -
462.469 -.. method:: __setformat__(typestr, fmt)
462.470 -
462.471 - float.__setformat__(typestr, fmt) -> None
462.472 -
462.473 - You probably don't want to use this function. It exists mainly to be
462.474 - used in Python's test suite.
462.475 -
462.476 - typestr must be 'double' or 'float'. fmt must be one of 'unknown',
462.477 - 'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be
462.478 - one of the latter two if it appears to match the underlying C reality.
462.479 -
462.480 - Overrides the automatic determination of C-level floating point type.
462.481 - This affects how floats are converted to and from binary strings.
462.482 -
462.483 -
462.484 -.. method:: __sizeof__()
462.485 -
462.486 - __sizeof__() -> size of object in memory, in bytes
462.487 -
462.488 - .. versionadded:: 2.6
462.489 -
462.490 -.. method:: __str__()
462.491 -
462.492 - x.__str__() <==> str(x)
462.493 -
462.494 -
462.495 -.. method:: __subclasshook__()
462.496 -
462.497 - Abstract classes can override this to customize issubclass().
462.498 -
462.499 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
462.500 - It should return True, False or NotImplemented. If it returns
462.501 - NotImplemented, the normal algorithm is used. Otherwise, it
462.502 - overrides the normal algorithm (and the outcome is cached).
462.503 -
462.504 -
462.505 - .. versionadded:: 2.6
462.506 -
462.507 -.. method:: __trunc__()
462.508 -
462.509 - Returns the Integral closest to x between 0 and x.
462.510 -
462.511 - .. versionadded:: 2.6
462.512 -
462.513 -.. method:: conjugate()
462.514 -
462.515 - Returns self, the complex conjugate of any float.
462.516 -
462.517 - .. versionadded:: 2.6
462.518 -
462.519 -.. attribute:: imag
462.520 -
462.521 - float(x) -> floating point number
462.522 -
462.523 - Convert a string or number to a floating point number, if possible.
462.524 -
462.525 - .. versionadded:: 2.6
462.526 -
462.527 -.. method:: is_integer()
462.528 -
462.529 - Returns True if the float is an integer.
462.530 -
462.531 - .. versionadded:: 2.6
462.532 -
462.533 -.. attribute:: real
462.534 -
462.535 - float(x) -> floating point number
462.536 -
462.537 - Convert a string or number to a floating point number, if possible.
462.538 -
462.539 - .. versionadded:: 2.6
462.540 -
462.541 -.. class:: long
462.542 -
462.543 - long(x[, base]) -> integer
462.544 -
462.545 - Convert a string or number to a long integer, if possible. A floating
462.546 - point argument will be truncated towards zero (this does not include a
462.547 - string representation of a floating point number!) When converting a
462.548 - string, use the optional base. It is an error to supply a base when
462.549 - converting a non-string.
462.550 -
462.551 -
462.552 -.. attribute:: __class__
462.553 -
462.554 - long(x[, base]) -> integer
462.555 -
462.556 - Convert a string or number to a long integer, if possible. A floating
462.557 - point argument will be truncated towards zero (this does not include a
462.558 - string representation of a floating point number!) When converting a
462.559 - string, use the optional base. It is an error to supply a base when
462.560 - converting a non-string.
462.561 -
462.562 -
462.563 -.. method:: __cmp__(y)
462.564 -
462.565 - x.__cmp__(y) <==> cmp(x,y)
462.566 -
462.567 -
462.568 -.. method:: __coerce__(y)
462.569 -
462.570 - x.__coerce__(y) <==> coerce(x, y)
462.571 -
462.572 -
462.573 -.. method:: __delattr__(name)
462.574 -
462.575 - x.__delattr__('name') <==> del x.name
462.576 -
462.577 -
462.578 -.. method:: __divmod__(y)
462.579 -
462.580 - x.__divmod__(y) <==> divmod(x, y)
462.581 -
462.582 -
462.583 -.. attribute:: __doc__
462.584 -
462.585 - str(object) -> string
462.586 -
462.587 - Return a nice string representation of the object.
462.588 - If the argument is a string, the return value is the same object.
462.589 -
462.590 -
462.591 -.. method:: __float__()
462.592 -
462.593 - x.__float__() <==> float(x)
462.594 -
462.595 -
462.596 -.. method:: __format__()
462.597 -
462.598 - .. versionadded:: 2.6
462.599 -
462.600 -.. method:: __getattribute__(name)
462.601 -
462.602 - x.__getattribute__('name') <==> x.name
462.603 -
462.604 -
462.605 -.. method:: __getnewargs__()
462.606 -
462.607 -
462.608 -.. method:: __hash__()
462.609 -
462.610 - x.__hash__() <==> hash(x)
462.611 -
462.612 -
462.613 -.. method:: __hex__()
462.614 -
462.615 - x.__hex__() <==> hex(x)
462.616 -
462.617 -
462.618 -.. method:: __init__()
462.619 -
462.620 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
462.621 -
462.622 -
462.623 -.. method:: __int__()
462.624 -
462.625 - x.__int__() <==> int(x)
462.626 -
462.627 -
462.628 -.. method:: __long__()
462.629 -
462.630 - x.__long__() <==> long(x)
462.631 -
462.632 -
462.633 -.. method:: __new__(S, ___)
462.634 -
462.635 - T.__new__(S, ...) -> a new object with type S, a subtype of T
462.636 -
462.637 -
462.638 -.. method:: __nonzero__()
462.639 -
462.640 - x.__nonzero__() <==> x != 0
462.641 -
462.642 -
462.643 -.. method:: __oct__()
462.644 -
462.645 - x.__oct__() <==> oct(x)
462.646 -
462.647 -
462.648 -.. method:: __radd__(y)
462.649 -
462.650 - x.__radd__(y) <==> y+x
462.651 -
462.652 -
462.653 -.. method:: __rand__(y)
462.654 -
462.655 - x.__rand__(y) <==> y&x
462.656 -
462.657 -
462.658 -.. method:: __rdiv__(y)
462.659 -
462.660 - x.__rdiv__(y) <==> y/x
462.661 -
462.662 -
462.663 -.. method:: __rdivmod__(y)
462.664 -
462.665 - x.__rdivmod__(y) <==> divmod(y, x)
462.666 -
462.667 -
462.668 -.. method:: __reduce__()
462.669 -
462.670 - helper for pickle
462.671 -
462.672 -
462.673 -.. method:: __reduce_ex__()
462.674 -
462.675 - helper for pickle
462.676 -
462.677 -
462.678 -.. method:: __repr__()
462.679 -
462.680 - x.__repr__() <==> repr(x)
462.681 -
462.682 -
462.683 -.. method:: __rfloordiv__(y)
462.684 -
462.685 - x.__rfloordiv__(y) <==> y//x
462.686 -
462.687 -
462.688 -.. method:: __rlshift__(y)
462.689 -
462.690 - x.__rlshift__(y) <==> y<<x
462.691 -
462.692 -
462.693 -.. method:: __rmod__(y)
462.694 -
462.695 - x.__rmod__(y) <==> y%x
462.696 -
462.697 -
462.698 -.. method:: __rmul__(y)
462.699 -
462.700 - x.__rmul__(y) <==> y*x
462.701 -
462.702 -
462.703 -.. method:: __ror__(y)
462.704 -
462.705 - x.__ror__(y) <==> y|x
462.706 -
462.707 -
462.708 -.. method:: __rpow__(x)
462.709 -
462.710 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
462.711 -
462.712 -
462.713 -.. method:: __rrshift__(y)
462.714 -
462.715 - x.__rrshift__(y) <==> y>>x
462.716 -
462.717 -
462.718 -.. method:: __rsub__(y)
462.719 -
462.720 - x.__rsub__(y) <==> y-x
462.721 -
462.722 -
462.723 -.. method:: __rtruediv__(y)
462.724 -
462.725 - x.__rtruediv__(y) <==> y/x
462.726 -
462.727 -
462.728 -.. method:: __rxor__(y)
462.729 -
462.730 - x.__rxor__(y) <==> y^x
462.731 -
462.732 -
462.733 -.. method:: __setattr__(name, value)
462.734 -
462.735 - x.__setattr__('name', value) <==> x.name = value
462.736 -
462.737 -
462.738 -.. method:: __sizeof__()
462.739 -
462.740 - Returns size in memory, in bytes
462.741 -
462.742 - .. versionadded:: 2.6
462.743 -
462.744 -.. method:: __str__()
462.745 -
462.746 - x.__str__() <==> str(x)
462.747 -
462.748 -
462.749 -.. method:: __subclasshook__()
462.750 -
462.751 - Abstract classes can override this to customize issubclass().
462.752 -
462.753 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
462.754 - It should return True, False or NotImplemented. If it returns
462.755 - NotImplemented, the normal algorithm is used. Otherwise, it
462.756 - overrides the normal algorithm (and the outcome is cached).
462.757 -
462.758 -
462.759 - .. versionadded:: 2.6
462.760 -
462.761 -.. method:: __trunc__()
462.762 -
462.763 - Truncating an Integral returns itself.
462.764 -
462.765 - .. versionadded:: 2.6
462.766 -
462.767 -.. method:: conjugate()
462.768 -
462.769 - Returns self, the complex conjugate of any long.
462.770 -
462.771 - .. versionadded:: 2.6
462.772 -
462.773 -.. attribute:: denominator
462.774 -
462.775 - long(x[, base]) -> integer
462.776 -
462.777 - Convert a string or number to a long integer, if possible. A floating
462.778 - point argument will be truncated towards zero (this does not include a
462.779 - string representation of a floating point number!) When converting a
462.780 - string, use the optional base. It is an error to supply a base when
462.781 - converting a non-string.
462.782 -
462.783 - .. versionadded:: 2.6
462.784 -
462.785 -.. attribute:: imag
462.786 -
462.787 - long(x[, base]) -> integer
462.788 -
462.789 - Convert a string or number to a long integer, if possible. A floating
462.790 - point argument will be truncated towards zero (this does not include a
462.791 - string representation of a floating point number!) When converting a
462.792 - string, use the optional base. It is an error to supply a base when
462.793 - converting a non-string.
462.794 -
462.795 - .. versionadded:: 2.6
462.796 -
462.797 -.. attribute:: numerator
462.798 -
462.799 - long(x[, base]) -> integer
462.800 -
462.801 - Convert a string or number to a long integer, if possible. A floating
462.802 - point argument will be truncated towards zero (this does not include a
462.803 - string representation of a floating point number!) When converting a
462.804 - string, use the optional base. It is an error to supply a base when
462.805 - converting a non-string.
462.806 -
462.807 - .. versionadded:: 2.6
462.808 -
462.809 -.. attribute:: real
462.810 -
462.811 - long(x[, base]) -> integer
462.812 -
462.813 - Convert a string or number to a long integer, if possible. A floating
462.814 - point argument will be truncated towards zero (this does not include a
462.815 - string representation of a floating point number!) When converting a
462.816 - string, use the optional base. It is an error to supply a base when
462.817 - converting a non-string.
462.818 -
462.819 - .. versionadded:: 2.6
462.820 -
462.821 -.. class:: bool
462.822 -
462.823 - bool(x) -> bool
462.824 -
462.825 - Returns True when the argument x is true, False otherwise.
462.826 - The builtins True and False are the only two instances of the class bool.
462.827 - The class bool is a subclass of the class int, and cannot be subclassed.
462.828 -
462.829 -
462.830 -.. method:: __abs__()
462.831 -
462.832 - x.__abs__() <==> abs(x)
462.833 -
462.834 -
462.835 -.. method:: __add__(y)
462.836 -
462.837 - x.__add__(y) <==> x+y
462.838 -
462.839 -
462.840 -.. method:: __and__(y)
462.841 -
462.842 - x.__and__(y) <==> x&y
462.843 -
462.844 -
462.845 -.. attribute:: __class__
462.846 -
462.847 - bool(x) -> bool
462.848 -
462.849 - Returns True when the argument x is true, False otherwise.
462.850 - The builtins True and False are the only two instances of the class bool.
462.851 - The class bool is a subclass of the class int, and cannot be subclassed.
462.852 -
462.853 -
462.854 -.. method:: __cmp__(y)
462.855 -
462.856 - x.__cmp__(y) <==> cmp(x,y)
462.857 -
462.858 -
462.859 -.. method:: __coerce__(y)
462.860 -
462.861 - x.__coerce__(y) <==> coerce(x, y)
462.862 -
462.863 -
462.864 -.. method:: __delattr__(name)
462.865 -
462.866 - x.__delattr__('name') <==> del x.name
462.867 -
462.868 -
462.869 -.. method:: __div__(y)
462.870 -
462.871 - x.__div__(y) <==> x/y
462.872 -
462.873 -
462.874 -.. method:: __divmod__(y)
462.875 -
462.876 - x.__divmod__(y) <==> divmod(x, y)
462.877 -
462.878 -
462.879 -.. attribute:: __doc__
462.880 -
462.881 - str(object) -> string
462.882 -
462.883 - Return a nice string representation of the object.
462.884 - If the argument is a string, the return value is the same object.
462.885 -
462.886 -
462.887 -.. method:: __float__()
462.888 -
462.889 - x.__float__() <==> float(x)
462.890 -
462.891 -
462.892 -.. method:: __floordiv__(y)
462.893 -
462.894 - x.__floordiv__(y) <==> x//y
462.895 -
462.896 -
462.897 -.. method:: __format__()
462.898 -
462.899 - .. versionadded:: 2.6
462.900 -
462.901 -.. method:: __getattribute__(name)
462.902 -
462.903 - x.__getattribute__('name') <==> x.name
462.904 -
462.905 -
462.906 -.. method:: __getnewargs__()
462.907 -
462.908 -
462.909 -.. method:: __hash__()
462.910 -
462.911 - x.__hash__() <==> hash(x)
462.912 -
462.913 -
462.914 -.. method:: __hex__()
462.915 -
462.916 - x.__hex__() <==> hex(x)
462.917 -
462.918 -
462.919 -.. method:: __index__()
462.920 -
462.921 - x[y:z] <==> x[y.__index__():z.__index__()]
462.922 -
462.923 -
462.924 -.. method:: __init__()
462.925 -
462.926 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
462.927 -
462.928 -
462.929 -.. method:: __int__()
462.930 -
462.931 - x.__int__() <==> int(x)
462.932 -
462.933 -
462.934 -.. method:: __invert__()
462.935 -
462.936 - x.__invert__() <==> ~x
462.937 -
462.938 -
462.939 -.. method:: __long__()
462.940 -
462.941 - x.__long__() <==> long(x)
462.942 -
462.943 -
462.944 -.. method:: __lshift__(y)
462.945 -
462.946 - x.__lshift__(y) <==> x<<y
462.947 -
462.948 -
462.949 -.. method:: __mod__(y)
462.950 -
462.951 - x.__mod__(y) <==> x%y
462.952 -
462.953 -
462.954 -.. method:: __mul__(y)
462.955 -
462.956 - x.__mul__(y) <==> x*y
462.957 -
462.958 -
462.959 -.. method:: __neg__()
462.960 -
462.961 - x.__neg__() <==> -x
462.962 -
462.963 -
462.964 -.. method:: __new__(S, ___)
462.965 -
462.966 - T.__new__(S, ...) -> a new object with type S, a subtype of T
462.967 -
462.968 -
462.969 -.. method:: __nonzero__()
462.970 -
462.971 - x.__nonzero__() <==> x != 0
462.972 -
462.973 -
462.974 -.. method:: __oct__()
462.975 -
462.976 - x.__oct__() <==> oct(x)
462.977 -
462.978 -
462.979 -.. method:: __or__(y)
462.980 -
462.981 - x.__or__(y) <==> x|y
462.982 -
462.983 -
462.984 -.. method:: __pos__()
462.985 -
462.986 - x.__pos__() <==> +x
462.987 -
462.988 -
462.989 -.. method:: __pow__(y)
462.990 -
462.991 - x.__pow__(y[, z]) <==> pow(x, y[, z])
462.992 -
462.993 -
462.994 -.. method:: __radd__(y)
462.995 -
462.996 - x.__radd__(y) <==> y+x
462.997 -
462.998 -
462.999 -.. method:: __rand__(y)
462.1000 -
462.1001 - x.__rand__(y) <==> y&x
462.1002 -
462.1003 -
462.1004 -.. method:: __rdiv__(y)
462.1005 -
462.1006 - x.__rdiv__(y) <==> y/x
462.1007 -
462.1008 -
462.1009 -.. method:: __rdivmod__(y)
462.1010 -
462.1011 - x.__rdivmod__(y) <==> divmod(y, x)
462.1012 -
462.1013 -
462.1014 -.. method:: __reduce__()
462.1015 -
462.1016 - helper for pickle
462.1017 -
462.1018 -
462.1019 -.. method:: __reduce_ex__()
462.1020 -
462.1021 - helper for pickle
462.1022 -
462.1023 -
462.1024 -.. method:: __repr__()
462.1025 -
462.1026 - x.__repr__() <==> repr(x)
462.1027 -
462.1028 -
462.1029 -.. method:: __rfloordiv__(y)
462.1030 -
462.1031 - x.__rfloordiv__(y) <==> y//x
462.1032 -
462.1033 -
462.1034 -.. method:: __rlshift__(y)
462.1035 -
462.1036 - x.__rlshift__(y) <==> y<<x
462.1037 -
462.1038 -
462.1039 -.. method:: __rmod__(y)
462.1040 -
462.1041 - x.__rmod__(y) <==> y%x
462.1042 -
462.1043 -
462.1044 -.. method:: __rmul__(y)
462.1045 -
462.1046 - x.__rmul__(y) <==> y*x
462.1047 -
462.1048 -
462.1049 -.. method:: __ror__(y)
462.1050 -
462.1051 - x.__ror__(y) <==> y|x
462.1052 -
462.1053 -
462.1054 -.. method:: __rpow__(x)
462.1055 -
462.1056 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
462.1057 -
462.1058 -
462.1059 -.. method:: __rrshift__(y)
462.1060 -
462.1061 - x.__rrshift__(y) <==> y>>x
462.1062 -
462.1063 -
462.1064 -.. method:: __rshift__(y)
462.1065 -
462.1066 - x.__rshift__(y) <==> x>>y
462.1067 -
462.1068 -
462.1069 -.. method:: __rsub__(y)
462.1070 -
462.1071 - x.__rsub__(y) <==> y-x
462.1072 -
462.1073 -
462.1074 -.. method:: __rtruediv__(y)
462.1075 -
462.1076 - x.__rtruediv__(y) <==> y/x
462.1077 -
462.1078 -
462.1079 -.. method:: __rxor__(y)
462.1080 -
462.1081 - x.__rxor__(y) <==> y^x
462.1082 -
462.1083 -
462.1084 -.. method:: __setattr__(name, value)
462.1085 -
462.1086 - x.__setattr__('name', value) <==> x.name = value
462.1087 -
462.1088 -
462.1089 -.. method:: __sizeof__()
462.1090 -
462.1091 - __sizeof__() -> size of object in memory, in bytes
462.1092 -
462.1093 - .. versionadded:: 2.6
462.1094 -
462.1095 -.. method:: __str__()
462.1096 -
462.1097 - x.__str__() <==> str(x)
462.1098 -
462.1099 -
462.1100 -.. method:: __sub__(y)
462.1101 -
462.1102 - x.__sub__(y) <==> x-y
462.1103 -
462.1104 -
462.1105 -.. method:: __subclasshook__()
462.1106 -
462.1107 - Abstract classes can override this to customize issubclass().
462.1108 -
462.1109 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
462.1110 - It should return True, False or NotImplemented. If it returns
462.1111 - NotImplemented, the normal algorithm is used. Otherwise, it
462.1112 - overrides the normal algorithm (and the outcome is cached).
462.1113 -
462.1114 -
462.1115 - .. versionadded:: 2.6
462.1116 -
462.1117 -.. method:: __truediv__(y)
462.1118 -
462.1119 - x.__truediv__(y) <==> x/y
462.1120 -
462.1121 -
462.1122 -.. method:: __trunc__()
462.1123 -
462.1124 - Truncating an Integral returns itself.
462.1125 -
462.1126 - .. versionadded:: 2.6
462.1127 -
462.1128 -.. method:: __xor__(y)
462.1129 -
462.1130 - x.__xor__(y) <==> x^y
462.1131 -
462.1132 -
462.1133 -.. method:: conjugate()
462.1134 -
462.1135 - Returns self, the complex conjugate of any int.
462.1136 -
462.1137 - .. versionadded:: 2.6
462.1138 -
462.1139 -.. attribute:: denominator
462.1140 -
462.1141 - int(x[, base]) -> integer
462.1142 -
462.1143 - Convert a string or number to an integer, if possible. A floating point
462.1144 - argument will be truncated towards zero (this does not include a string
462.1145 - representation of a floating point number!) When converting a string, use
462.1146 - the optional base. It is an error to supply a base when converting a
462.1147 - non-string. If base is zero, the proper base is guessed based on the
462.1148 - string content. If the argument is outside the integer range a
462.1149 - long object will be returned instead.
462.1150 -
462.1151 - .. versionadded:: 2.6
462.1152 -
462.1153 -.. attribute:: imag
462.1154 -
462.1155 - int(x[, base]) -> integer
462.1156 -
462.1157 - Convert a string or number to an integer, if possible. A floating point
462.1158 - argument will be truncated towards zero (this does not include a string
462.1159 - representation of a floating point number!) When converting a string, use
462.1160 - the optional base. It is an error to supply a base when converting a
462.1161 - non-string. If base is zero, the proper base is guessed based on the
462.1162 - string content. If the argument is outside the integer range a
462.1163 - long object will be returned instead.
462.1164 -
462.1165 - .. versionadded:: 2.6
462.1166 -
462.1167 -.. attribute:: numerator
462.1168 -
462.1169 - int(x[, base]) -> integer
462.1170 -
462.1171 - Convert a string or number to an integer, if possible. A floating point
462.1172 - argument will be truncated towards zero (this does not include a string
462.1173 - representation of a floating point number!) When converting a string, use
462.1174 - the optional base. It is an error to supply a base when converting a
462.1175 - non-string. If base is zero, the proper base is guessed based on the
462.1176 - string content. If the argument is outside the integer range a
462.1177 - long object will be returned instead.
462.1178 -
462.1179 - .. versionadded:: 2.6
462.1180 -
462.1181 -.. attribute:: real
462.1182 -
462.1183 - int(x[, base]) -> integer
462.1184 -
462.1185 - Convert a string or number to an integer, if possible. A floating point
462.1186 - argument will be truncated towards zero (this does not include a string
462.1187 - representation of a floating point number!) When converting a string, use
462.1188 - the optional base. It is an error to supply a base when converting a
462.1189 - non-string. If base is zero, the proper base is guessed based on the
462.1190 - string content. If the argument is outside the integer range a
462.1191 - long object will be returned instead.
462.1192 -
462.1193 - .. versionadded:: 2.6
462.1194 -
462.1195 -.. class:: complex
462.1196 -
462.1197 - complex(real[, imag]) -> complex number
462.1198 -
462.1199 - Create a complex number from a real part and an optional imaginary part.
462.1200 - This is equivalent to (real + imag*1j) where imag defaults to 0.
462.1201 -
462.1202 -
462.1203 -.. attribute:: __class__
462.1204 -
462.1205 - complex(real[, imag]) -> complex number
462.1206 -
462.1207 - Create a complex number from a real part and an optional imaginary part.
462.1208 - This is equivalent to (real + imag*1j) where imag defaults to 0.
462.1209 -
462.1210 -
462.1211 -.. method:: __coerce__(y)
462.1212 -
462.1213 - x.__coerce__(y) <==> coerce(x, y)
462.1214 -
462.1215 -
462.1216 -.. method:: __delattr__(name)
462.1217 -
462.1218 - x.__delattr__('name') <==> del x.name
462.1219 -
462.1220 -
462.1221 -.. method:: __divmod__(y)
462.1222 -
462.1223 - x.__divmod__(y) <==> divmod(x, y)
462.1224 -
462.1225 -
462.1226 -.. attribute:: __doc__
462.1227 -
462.1228 - str(object) -> string
462.1229 -
462.1230 - Return a nice string representation of the object.
462.1231 - If the argument is a string, the return value is the same object.
462.1232 -
462.1233 -
462.1234 -.. method:: __float__()
462.1235 -
462.1236 - x.__float__() <==> float(x)
462.1237 -
462.1238 -
462.1239 -.. method:: __format__()
462.1240 -
462.1241 - default object formatter
462.1242 -
462.1243 - .. versionadded:: 2.6
462.1244 -
462.1245 -.. method:: __getattribute__(name)
462.1246 -
462.1247 - x.__getattribute__('name') <==> x.name
462.1248 -
462.1249 -
462.1250 -.. method:: __getnewargs__()
462.1251 -
462.1252 -
462.1253 -.. method:: __hash__()
462.1254 -
462.1255 - x.__hash__() <==> hash(x)
462.1256 -
462.1257 -
462.1258 -.. method:: __init__()
462.1259 -
462.1260 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
462.1261 -
462.1262 -
462.1263 -.. method:: __int__()
462.1264 -
462.1265 - x.__int__() <==> int(x)
462.1266 -
462.1267 -
462.1268 -.. method:: __long__()
462.1269 -
462.1270 - x.__long__() <==> long(x)
462.1271 -
462.1272 -
462.1273 -.. method:: __new__(S, ___)
462.1274 -
462.1275 - T.__new__(S, ...) -> a new object with type S, a subtype of T
462.1276 -
462.1277 -
462.1278 -.. method:: __nonzero__()
462.1279 -
462.1280 - x.__nonzero__() <==> x != 0
462.1281 -
462.1282 -
462.1283 -.. method:: __radd__(y)
462.1284 -
462.1285 - x.__radd__(y) <==> y+x
462.1286 -
462.1287 -
462.1288 -.. method:: __rdiv__(y)
462.1289 -
462.1290 - x.__rdiv__(y) <==> y/x
462.1291 -
462.1292 -
462.1293 -.. method:: __rdivmod__(y)
462.1294 -
462.1295 - x.__rdivmod__(y) <==> divmod(y, x)
462.1296 -
462.1297 -
462.1298 -.. method:: __reduce__()
462.1299 -
462.1300 - helper for pickle
462.1301 -
462.1302 -
462.1303 -.. method:: __reduce_ex__()
462.1304 -
462.1305 - helper for pickle
462.1306 -
462.1307 -
462.1308 -.. method:: __repr__()
462.1309 -
462.1310 - x.__repr__() <==> repr(x)
462.1311 -
462.1312 -
462.1313 -.. method:: __rfloordiv__(y)
462.1314 -
462.1315 - x.__rfloordiv__(y) <==> y//x
462.1316 -
462.1317 -
462.1318 -.. method:: __rmod__(y)
462.1319 -
462.1320 - x.__rmod__(y) <==> y%x
462.1321 -
462.1322 -
462.1323 -.. method:: __rmul__(y)
462.1324 -
462.1325 - x.__rmul__(y) <==> y*x
462.1326 -
462.1327 -
462.1328 -.. method:: __rpow__(x)
462.1329 -
462.1330 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
462.1331 -
462.1332 -
462.1333 -.. method:: __rsub__(y)
462.1334 -
462.1335 - x.__rsub__(y) <==> y-x
462.1336 -
462.1337 -
462.1338 -.. method:: __rtruediv__(y)
462.1339 -
462.1340 - x.__rtruediv__(y) <==> y/x
462.1341 -
462.1342 -
462.1343 -.. method:: __setattr__(name, value)
462.1344 -
462.1345 - x.__setattr__('name', value) <==> x.name = value
462.1346 -
462.1347 -
462.1348 -.. method:: __sizeof__()
462.1349 -
462.1350 - __sizeof__() -> size of object in memory, in bytes
462.1351 -
462.1352 - .. versionadded:: 2.6
462.1353 -
462.1354 -.. method:: __str__()
462.1355 -
462.1356 - x.__str__() <==> str(x)
462.1357 -
462.1358 -
462.1359 -.. method:: __subclasshook__()
462.1360 -
462.1361 - Abstract classes can override this to customize issubclass().
462.1362 -
462.1363 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
462.1364 - It should return True, False or NotImplemented. If it returns
462.1365 - NotImplemented, the normal algorithm is used. Otherwise, it
462.1366 - overrides the normal algorithm (and the outcome is cached).
462.1367 -
462.1368 -
462.1369 - .. versionadded:: 2.6
462.1370 -
462.1371 -.. method:: conjugate()
462.1372 -
462.1373 - complex.conjugate() -> complex
462.1374 -
462.1375 - Returns the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.
462.1376 -
462.1377 -
462.1378 -.. attribute:: imag
462.1379 -
462.1380 - float(x) -> floating point number
462.1381 -
462.1382 - Convert a string or number to a floating point number, if possible.
462.1383 -
462.1384 -
462.1385 -.. attribute:: real
462.1386 -
462.1387 - float(x) -> floating point number
462.1388 -
462.1389 - Convert a string or number to a floating point number, if possible.
462.1390 -
462.1391 -
462.1392 -.. class:: list
462.1393 -
462.1394 - list() -> new list
462.1395 - list(sequence) -> new list initialized from sequence's items
462.1396 -
462.1397 -
462.1398 -.. attribute:: __class__
462.1399 -
462.1400 - list() -> new list
462.1401 - list(sequence) -> new list initialized from sequence's items
462.1402 -
462.1403 -
462.1404 -.. method:: __delattr__(name)
462.1405 -
462.1406 - x.__delattr__('name') <==> del x.name
462.1407 -
462.1408 -
462.1409 -.. attribute:: __doc__
462.1410 -
462.1411 - str(object) -> string
462.1412 -
462.1413 - Return a nice string representation of the object.
462.1414 - If the argument is a string, the return value is the same object.
462.1415 -
462.1416 -
462.1417 -.. method:: __format__()
462.1418 -
462.1419 - default object formatter
462.1420 -
462.1421 - .. versionadded:: 2.6
462.1422 -
462.1423 -.. method:: __getattribute__(name)
462.1424 -
462.1425 - x.__getattribute__('name') <==> x.name
462.1426 -
462.1427 -
462.1428 -.. attribute:: __hash__
462.1429 -
462.1430 -
462.1431 -.. method:: __init__()
462.1432 -
462.1433 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
462.1434 -
462.1435 -
462.1436 -.. method:: __iter__()
462.1437 -
462.1438 - x.__iter__() <==> iter(x)
462.1439 -
462.1440 -
462.1441 -.. method:: __len__()
462.1442 -
462.1443 - x.__len__() <==> len(x)
462.1444 -
462.1445 -
462.1446 -.. method:: __new__(S, ___)
462.1447 -
462.1448 - T.__new__(S, ...) -> a new object with type S, a subtype of T
462.1449 -
462.1450 -
462.1451 -.. method:: __reduce__()
462.1452 -
462.1453 - helper for pickle
462.1454 -
462.1455 -
462.1456 -.. method:: __reduce_ex__()
462.1457 -
462.1458 - helper for pickle
462.1459 -
462.1460 -
462.1461 -.. method:: __repr__()
462.1462 -
462.1463 - x.__repr__() <==> repr(x)
462.1464 -
462.1465 -
462.1466 -.. method:: __reversed__()
462.1467 -
462.1468 - L.__reversed__() -- return a reverse iterator over the list
462.1469 -
462.1470 -
462.1471 -.. method:: __rmul__(n)
462.1472 -
462.1473 - x.__rmul__(n) <==> n*x
462.1474 -
462.1475 -
462.1476 -.. method:: __setattr__(name, value)
462.1477 -
462.1478 - x.__setattr__('name', value) <==> x.name = value
462.1479 -
462.1480 -
462.1481 -.. method:: __sizeof__()
462.1482 -
462.1483 - L.__sizeof__() -- size of L in memory, in bytes
462.1484 -
462.1485 - .. versionadded:: 2.6
462.1486 -
462.1487 -.. method:: __str__()
462.1488 -
462.1489 - x.__str__() <==> str(x)
462.1490 -
462.1491 -
462.1492 -.. method:: __subclasshook__()
462.1493 -
462.1494 - Abstract classes can override this to customize issubclass().
462.1495 -
462.1496 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
462.1497 - It should return True, False or NotImplemented. If it returns
462.1498 - NotImplemented, the normal algorithm is used. Otherwise, it
462.1499 - overrides the normal algorithm (and the outcome is cached).
462.1500 -
462.1501 -
462.1502 - .. versionadded:: 2.6
462.1503 -
462.1504 -.. method:: append()
462.1505 -
462.1506 - L.append(object) -- append object to end
462.1507 -
462.1508 -
462.1509 -.. method:: count(value)
462.1510 -
462.1511 - L.count(value) -> integer -- return number of occurrences of value
462.1512 -
462.1513 -
462.1514 -.. method:: extend()
462.1515 -
462.1516 - L.extend(iterable) -- extend list by appending elements from the iterable
462.1517 -
462.1518 -
462.1519 -.. method:: insert()
462.1520 -
462.1521 - L.insert(index, object) -- insert object before index
462.1522 -
462.1523 -
462.1524 -.. method:: pop()
462.1525 -
462.1526 - L.pop([index]) -> item -- remove and return item at index (default last)
462.1527 -
462.1528 -
462.1529 -.. method:: remove()
462.1530 -
462.1531 - L.remove(value) -- remove first occurrence of value
462.1532 -
462.1533 -
462.1534 -.. method:: reverse()
462.1535 -
462.1536 - L.reverse() -- reverse *IN PLACE*
462.1537 -
462.1538 -
462.1539 -.. method:: sort(cmp=None, key=None, reverse=False) __ stable sort *IN PLACE*;
462.1540 -cmp(x, y)
462.1541 -
462.1542 - L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
462.1543 - cmp(x, y) -> -1, 0, 1
462.1544 -
462.1545 -
462.1546 -.. class:: dict
462.1547 -
462.1548 - dict() -> new empty dictionary.
462.1549 - dict(mapping) -> new dictionary initialized from a mapping object's
462.1550 - (key, value) pairs.
462.1551 - dict(seq) -> new dictionary initialized as if via:
462.1552 - d = {}
462.1553 - for k, v in seq:
462.1554 - d[k] = v
462.1555 - dict(**kwargs) -> new dictionary initialized with the name=value pairs
462.1556 - in the keyword argument list. For example: dict(one=1, two=2)
462.1557 -
462.1558 -
462.1559 -.. attribute:: __class__
462.1560 -
462.1561 - dict() -> new empty dictionary.
462.1562 - dict(mapping) -> new dictionary initialized from a mapping object's
462.1563 - (key, value) pairs.
462.1564 - dict(seq) -> new dictionary initialized as if via:
462.1565 - d = {}
462.1566 - for k, v in seq:
462.1567 - d[k] = v
462.1568 - dict(**kwargs) -> new dictionary initialized with the name=value pairs
462.1569 - in the keyword argument list. For example: dict(one=1, two=2)
462.1570 -
462.1571 -
462.1572 -.. method:: __cmp__(y)
462.1573 -
462.1574 - x.__cmp__(y) <==> cmp(x,y)
462.1575 -
462.1576 -
462.1577 -.. method:: __delattr__(name)
462.1578 -
462.1579 - x.__delattr__('name') <==> del x.name
462.1580 -
462.1581 -
462.1582 -.. attribute:: __doc__
462.1583 -
462.1584 - str(object) -> string
462.1585 -
462.1586 - Return a nice string representation of the object.
462.1587 - If the argument is a string, the return value is the same object.
462.1588 -
462.1589 -
462.1590 -.. method:: __format__()
462.1591 -
462.1592 - default object formatter
462.1593 -
462.1594 - .. versionadded:: 2.6
462.1595 -
462.1596 -.. method:: __getattribute__(name)
462.1597 -
462.1598 - x.__getattribute__('name') <==> x.name
462.1599 -
462.1600 -
462.1601 -.. attribute:: __hash__
462.1602 -
462.1603 -
462.1604 -.. method:: __iter__()
462.1605 -
462.1606 - x.__iter__() <==> iter(x)
462.1607 -
462.1608 -
462.1609 -.. method:: __len__()
462.1610 -
462.1611 - x.__len__() <==> len(x)
462.1612 -
462.1613 -
462.1614 -.. method:: __new__(S, ___)
462.1615 -
462.1616 - T.__new__(S, ...) -> a new object with type S, a subtype of T
462.1617 -
462.1618 -
462.1619 -.. method:: __reduce__()
462.1620 -
462.1621 - helper for pickle
462.1622 -
462.1623 -
462.1624 -.. method:: __reduce_ex__()
462.1625 -
462.1626 - helper for pickle
462.1627 -
462.1628 -
462.1629 -.. method:: __repr__()
462.1630 -
462.1631 - x.__repr__() <==> repr(x)
462.1632 -
462.1633 -
462.1634 -.. method:: __setattr__(name, value)
462.1635 -
462.1636 - x.__setattr__('name', value) <==> x.name = value
462.1637 -
462.1638 -
462.1639 -.. method:: __sizeof__()
462.1640 -
462.1641 - D.__sizeof__() -> size of D in memory, in bytes
462.1642 -
462.1643 - .. versionadded:: 2.6
462.1644 -
462.1645 -.. method:: __str__()
462.1646 -
462.1647 - x.__str__() <==> str(x)
462.1648 -
462.1649 -
462.1650 -.. method:: __subclasshook__()
462.1651 -
462.1652 - Abstract classes can override this to customize issubclass().
462.1653 -
462.1654 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
462.1655 - It should return True, False or NotImplemented. If it returns
462.1656 - NotImplemented, the normal algorithm is used. Otherwise, it
462.1657 - overrides the normal algorithm (and the outcome is cached).
462.1658 -
462.1659 -
462.1660 - .. versionadded:: 2.6
462.1661 -
462.1662 -.. class:: tuple
462.1663 -
462.1664 - tuple() -> an empty tuple
462.1665 - tuple(sequence) -> tuple initialized from sequence's items
462.1666 -
462.1667 - If the argument is a tuple, the return value is the same object.
462.1668 -
462.1669 -
462.1670 -.. attribute:: __class__
462.1671 -
462.1672 - tuple() -> an empty tuple
462.1673 - tuple(sequence) -> tuple initialized from sequence's items
462.1674 -
462.1675 - If the argument is a tuple, the return value is the same object.
462.1676 -
462.1677 -
462.1678 -.. method:: __delattr__(name)
462.1679 -
462.1680 - x.__delattr__('name') <==> del x.name
462.1681 -
462.1682 -
462.1683 -.. attribute:: __doc__
462.1684 -
462.1685 - str(object) -> string
462.1686 -
462.1687 - Return a nice string representation of the object.
462.1688 - If the argument is a string, the return value is the same object.
462.1689 -
462.1690 -
462.1691 -.. method:: __format__()
462.1692 -
462.1693 - default object formatter
462.1694 -
462.1695 - .. versionadded:: 2.6
462.1696 -
462.1697 -.. method:: __getattribute__(name)
462.1698 -
462.1699 - x.__getattribute__('name') <==> x.name
462.1700 -
462.1701 -
462.1702 -.. method:: __getnewargs__()
462.1703 -
462.1704 -
462.1705 -.. method:: __hash__()
462.1706 -
462.1707 - x.__hash__() <==> hash(x)
462.1708 -
462.1709 -
462.1710 -.. method:: __init__()
462.1711 -
462.1712 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
462.1713 -
462.1714 -
462.1715 -.. method:: __iter__()
462.1716 -
462.1717 - x.__iter__() <==> iter(x)
462.1718 -
462.1719 -
462.1720 -.. method:: __len__()
462.1721 -
462.1722 - x.__len__() <==> len(x)
462.1723 -
462.1724 -
462.1725 -.. method:: __new__(S, ___)
462.1726 -
462.1727 - T.__new__(S, ...) -> a new object with type S, a subtype of T
462.1728 -
462.1729 -
462.1730 -.. method:: __reduce__()
462.1731 -
462.1732 - helper for pickle
462.1733 -
462.1734 -
462.1735 -.. method:: __reduce_ex__()
462.1736 -
462.1737 - helper for pickle
462.1738 -
462.1739 -
462.1740 -.. method:: __repr__()
462.1741 -
462.1742 - x.__repr__() <==> repr(x)
462.1743 -
462.1744 -
462.1745 -.. method:: __rmul__(n)
462.1746 -
462.1747 - x.__rmul__(n) <==> n*x
462.1748 -
462.1749 -
462.1750 -.. method:: __setattr__(name, value)
462.1751 -
462.1752 - x.__setattr__('name', value) <==> x.name = value
462.1753 -
462.1754 -
462.1755 -.. method:: __sizeof__()
462.1756 -
462.1757 - T.__sizeof__() -- size of T in memory, in bytes
462.1758 -
462.1759 - .. versionadded:: 2.6
462.1760 -
462.1761 -.. method:: __str__()
462.1762 -
462.1763 - x.__str__() <==> str(x)
462.1764 -
462.1765 -
462.1766 -.. method:: __subclasshook__()
462.1767 -
462.1768 - Abstract classes can override this to customize issubclass().
462.1769 -
462.1770 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
462.1771 - It should return True, False or NotImplemented. If it returns
462.1772 - NotImplemented, the normal algorithm is used. Otherwise, it
462.1773 - overrides the normal algorithm (and the outcome is cached).
462.1774 -
462.1775 -
462.1776 - .. versionadded:: 2.6
462.1777 -
462.1778 -.. method:: count(value)
462.1779 -
462.1780 - T.count(value) -> integer -- return number of occurrences of value
462.1781 -
462.1782 - .. versionadded:: 2.6
462.1783 -
462.1784 -.. class:: str
462.1785 -
462.1786 - str(object) -> string
462.1787 -
462.1788 - Return a nice string representation of the object.
462.1789 - If the argument is a string, the return value is the same object.
462.1790 -
462.1791 -
462.1792 -.. attribute:: __class__
462.1793 -
462.1794 - str(object) -> string
462.1795 -
462.1796 - Return a nice string representation of the object.
462.1797 - If the argument is a string, the return value is the same object.
462.1798 -
462.1799 -
462.1800 -.. method:: __delattr__(name)
462.1801 -
462.1802 - x.__delattr__('name') <==> del x.name
462.1803 -
462.1804 -
462.1805 -.. attribute:: __doc__
462.1806 -
462.1807 - str(object) -> string
462.1808 -
462.1809 - Return a nice string representation of the object.
462.1810 - If the argument is a string, the return value is the same object.
462.1811 -
462.1812 -
462.1813 -.. method:: __format__(format_spec)
462.1814 -
462.1815 - S.__format__(format_spec) -> unicode
462.1816 -
462.1817 -
462.1818 -
462.1819 - .. versionadded:: 2.6
462.1820 -
462.1821 -.. method:: __getattribute__(name)
462.1822 -
462.1823 - x.__getattribute__('name') <==> x.name
462.1824 -
462.1825 -
462.1826 -.. method:: __getnewargs__()
462.1827 -
462.1828 -
462.1829 -.. method:: __hash__()
462.1830 -
462.1831 - x.__hash__() <==> hash(x)
462.1832 -
462.1833 -
462.1834 -.. method:: __init__()
462.1835 -
462.1836 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
462.1837 -
462.1838 -
462.1839 -.. method:: __len__()
462.1840 -
462.1841 - x.__len__() <==> len(x)
462.1842 -
462.1843 -
462.1844 -.. method:: __new__(S, ___)
462.1845 -
462.1846 - T.__new__(S, ...) -> a new object with type S, a subtype of T
462.1847 -
462.1848 -
462.1849 -.. method:: __reduce__()
462.1850 -
462.1851 - helper for pickle
462.1852 -
462.1853 -
462.1854 -.. method:: __reduce_ex__()
462.1855 -
462.1856 - helper for pickle
462.1857 -
462.1858 -
462.1859 -.. method:: __repr__()
462.1860 -
462.1861 - x.__repr__() <==> repr(x)
462.1862 -
462.1863 -
462.1864 -.. method:: __rmod__(y)
462.1865 -
462.1866 - x.__rmod__(y) <==> y%x
462.1867 -
462.1868 -
462.1869 -.. method:: __rmul__(n)
462.1870 -
462.1871 - x.__rmul__(n) <==> n*x
462.1872 -
462.1873 -
462.1874 -.. method:: __setattr__(name, value)
462.1875 -
462.1876 - x.__setattr__('name', value) <==> x.name = value
462.1877 -
462.1878 -
462.1879 -.. method:: __sizeof__()
462.1880 -
462.1881 - S.__sizeof__() -> size of S in memory, in bytes
462.1882 -
462.1883 - .. versionadded:: 2.6
462.1884 -
462.1885 -.. method:: __str__()
462.1886 -
462.1887 - x.__str__() <==> str(x)
462.1888 -
462.1889 -
462.1890 -.. method:: __subclasshook__()
462.1891 -
462.1892 - Abstract classes can override this to customize issubclass().
462.1893 -
462.1894 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
462.1895 - It should return True, False or NotImplemented. If it returns
462.1896 - NotImplemented, the normal algorithm is used. Otherwise, it
462.1897 - overrides the normal algorithm (and the outcome is cached).
462.1898 -
462.1899 -
462.1900 - .. versionadded:: 2.6
462.1901 -
462.1902 -.. method:: _formatter_field_name_split()
462.1903 -
462.1904 - .. versionadded:: 2.6
462.1905 -
462.1906 -.. method:: _formatter_parser()
462.1907 -
462.1908 - .. versionadded:: 2.6
462.1909 -
462.1910 -.. class:: unicode
462.1911 -
462.1912 - unicode(string [, encoding[, errors]]) -> object
462.1913 -
462.1914 - Create a new Unicode object from the given encoded string.
462.1915 - encoding defaults to the current default string encoding.
462.1916 - errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.
462.1917 -
462.1918 -
462.1919 -.. attribute:: __class__
462.1920 -
462.1921 - unicode(string [, encoding[, errors]]) -> object
462.1922 -
462.1923 - Create a new Unicode object from the given encoded string.
462.1924 - encoding defaults to the current default string encoding.
462.1925 - errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.
462.1926 -
462.1927 -
462.1928 -.. method:: __delattr__(name)
462.1929 -
462.1930 - x.__delattr__('name') <==> del x.name
462.1931 -
462.1932 -
462.1933 -.. attribute:: __doc__
462.1934 -
462.1935 - str(object) -> string
462.1936 -
462.1937 - Return a nice string representation of the object.
462.1938 - If the argument is a string, the return value is the same object.
462.1939 -
462.1940 -
462.1941 -.. method:: __format__(format_spec)
462.1942 -
462.1943 - S.__format__(format_spec) -> unicode
462.1944 -
462.1945 -
462.1946 -
462.1947 - .. versionadded:: 2.6
462.1948 -
462.1949 -.. method:: __getattribute__(name)
462.1950 -
462.1951 - x.__getattribute__('name') <==> x.name
462.1952 -
462.1953 -
462.1954 -.. method:: __getnewargs__()
462.1955 -
462.1956 -
462.1957 -.. method:: __hash__()
462.1958 -
462.1959 - x.__hash__() <==> hash(x)
462.1960 -
462.1961 -
462.1962 -.. method:: __init__()
462.1963 -
462.1964 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
462.1965 -
462.1966 -
462.1967 -.. method:: __len__()
462.1968 -
462.1969 - x.__len__() <==> len(x)
462.1970 -
462.1971 -
462.1972 -.. method:: __new__(S, ___)
462.1973 -
462.1974 - T.__new__(S, ...) -> a new object with type S, a subtype of T
462.1975 -
462.1976 -
462.1977 -.. method:: __reduce__()
462.1978 -
462.1979 - helper for pickle
462.1980 -
462.1981 -
462.1982 -.. method:: __reduce_ex__()
462.1983 -
462.1984 - helper for pickle
462.1985 -
462.1986 -
462.1987 -.. method:: __repr__()
462.1988 -
462.1989 - x.__repr__() <==> repr(x)
462.1990 -
462.1991 -
462.1992 -.. method:: __rmod__(y)
462.1993 -
462.1994 - x.__rmod__(y) <==> y%x
462.1995 -
462.1996 -
462.1997 -.. method:: __rmul__(n)
462.1998 -
462.1999 - x.__rmul__(n) <==> n*x
462.2000 -
462.2001 -
462.2002 -.. method:: __setattr__(name, value)
462.2003 -
462.2004 - x.__setattr__('name', value) <==> x.name = value
462.2005 -
462.2006 -
462.2007 -.. method:: __sizeof__()
462.2008 -
462.2009 - S.__sizeof__() -> size of S in memory, in bytes
462.2010 -
462.2011 -
462.2012 -
462.2013 - .. versionadded:: 2.6
462.2014 -
462.2015 -.. method:: __str__()
462.2016 -
462.2017 - x.__str__() <==> str(x)
462.2018 -
462.2019 -
462.2020 -.. method:: __subclasshook__()
462.2021 -
462.2022 - Abstract classes can override this to customize issubclass().
462.2023 -
462.2024 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
462.2025 - It should return True, False or NotImplemented. If it returns
462.2026 - NotImplemented, the normal algorithm is used. Otherwise, it
462.2027 - overrides the normal algorithm (and the outcome is cached).
462.2028 -
462.2029 -
462.2030 - .. versionadded:: 2.6
462.2031 -
462.2032 -.. method:: _formatter_field_name_split()
462.2033 -
462.2034 - .. versionadded:: 2.6
462.2035 -
462.2036 -.. method:: _formatter_parser()
462.2037 -
462.2038 - .. versionadded:: 2.6
462.2039 -
462.2040 -.. method:: capitalize()
462.2041 -
462.2042 - S.capitalize() -> unicode
462.2043 -
462.2044 - Return a capitalized version of S, i.e. make the first character
462.2045 - have upper case.
462.2046 -
462.2047 -
462.2048 -.. method:: center(width)
462.2049 -
462.2050 - S.center(width[, fillchar]) -> unicode
462.2051 -
462.2052 - Return S centered in a Unicode string of length width. Padding is
462.2053 - done using the specified fill character (default is a space)
462.2054 -
462.2055 -
462.2056 -.. method:: count(sub)
462.2057 -
462.2058 - S.count(sub[, start[, end]]) -> int
462.2059 -
462.2060 - Return the number of non-overlapping occurrences of substring sub in
462.2061 - Unicode string S[start:end]. Optional arguments start and end are
462.2062 - interpreted as in slice notation.
462.2063 -
462.2064 -
462.2065 -.. method:: decode()
462.2066 -
462.2067 - S.decode([encoding[,errors]]) -> string or unicode
462.2068 -
462.2069 - Decodes S using the codec registered for encoding. encoding defaults
462.2070 - to the default encoding. errors may be given to set a different error
462.2071 - handling scheme. Default is 'strict' meaning that encoding errors raise
462.2072 - a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
462.2073 - as well as any other name registerd with codecs.register_error that is
462.2074 - able to handle UnicodeDecodeErrors.
462.2075 -
462.2076 -
462.2077 -.. method:: encode()
462.2078 -
462.2079 - S.encode([encoding[,errors]]) -> string or unicode
462.2080 -
462.2081 - Encodes S using the codec registered for encoding. encoding defaults
462.2082 - to the default encoding. errors may be given to set a different error
462.2083 - handling scheme. Default is 'strict' meaning that encoding errors raise
462.2084 - a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
462.2085 - 'xmlcharrefreplace' as well as any other name registered with
462.2086 - codecs.register_error that can handle UnicodeEncodeErrors.
462.2087 -
462.2088 -
462.2089 -.. method:: endswith(suffix)
462.2090 -
462.2091 - S.endswith(suffix[, start[, end]]) -> bool
462.2092 -
462.2093 - Return True if S ends with the specified suffix, False otherwise.
462.2094 - With optional start, test S beginning at that position.
462.2095 - With optional end, stop comparing S at that position.
462.2096 - suffix can also be a tuple of strings to try.
462.2097 -
462.2098 -
462.2099 -.. method:: expandtabs()
462.2100 -
462.2101 - S.expandtabs([tabsize]) -> unicode
462.2102 -
462.2103 - Return a copy of S where all tab characters are expanded using spaces.
462.2104 - If tabsize is not given, a tab size of 8 characters is assumed.
462.2105 -
462.2106 -
462.2107 -.. method:: find(sub )
462.2108 -
462.2109 - S.find(sub [,start [,end]]) -> int
462.2110 -
462.2111 - Return the lowest index in S where substring sub is found,
462.2112 - such that sub is contained within s[start:end]. Optional
462.2113 - arguments start and end are interpreted as in slice notation.
462.2114 -
462.2115 - Return -1 on failure.
462.2116 -
462.2117 -
462.2118 -.. method:: format(*args, **kwargs)
462.2119 -
462.2120 - S.format(*args, **kwargs) -> unicode
462.2121 -
462.2122 -
462.2123 -
462.2124 - .. versionadded:: 2.6
462.2125 -
462.2126 -.. method:: isalnum()
462.2127 -
462.2128 - S.isalnum() -> bool
462.2129 -
462.2130 - Return True if all characters in S are alphanumeric
462.2131 - and there is at least one character in S, False otherwise.
462.2132 -
462.2133 -
462.2134 -.. method:: isalpha()
462.2135 -
462.2136 - S.isalpha() -> bool
462.2137 -
462.2138 - Return True if all characters in S are alphabetic
462.2139 - and there is at least one character in S, False otherwise.
462.2140 -
462.2141 -
462.2142 -.. method:: isdigit()
462.2143 -
462.2144 - S.isdigit() -> bool
462.2145 -
462.2146 - Return True if all characters in S are digits
462.2147 - and there is at least one character in S, False otherwise.
462.2148 -
462.2149 -
462.2150 -.. method:: islower()
462.2151 -
462.2152 - S.islower() -> bool
462.2153 -
462.2154 - Return True if all cased characters in S are lowercase and there is
462.2155 - at least one cased character in S, False otherwise.
462.2156 -
462.2157 -
462.2158 -.. method:: isspace()
462.2159 -
462.2160 - S.isspace() -> bool
462.2161 -
462.2162 - Return True if all characters in S are whitespace
462.2163 - and there is at least one character in S, False otherwise.
462.2164 -
462.2165 -
462.2166 -.. method:: istitle()
462.2167 -
462.2168 - S.istitle() -> bool
462.2169 -
462.2170 - Return True if S is a titlecased string and there is at least one
462.2171 - character in S, i.e. upper- and titlecase characters may only
462.2172 - follow uncased characters and lowercase characters only cased ones.
462.2173 - Return False otherwise.
462.2174 -
462.2175 -
462.2176 -.. method:: isupper()
462.2177 -
462.2178 - S.isupper() -> bool
462.2179 -
462.2180 - Return True if all cased characters in S are uppercase and there is
462.2181 - at least one cased character in S, False otherwise.
462.2182 -
462.2183 -
462.2184 -.. method:: join(sequence)
462.2185 -
462.2186 - S.join(sequence) -> unicode
462.2187 -
462.2188 - Return a string which is the concatenation of the strings in the
462.2189 - sequence. The separator between elements is S.
462.2190 -
462.2191 -
462.2192 -.. method:: ljust(width)
462.2193 -
462.2194 - S.ljust(width[, fillchar]) -> int
462.2195 -
462.2196 - Return S left justified in a Unicode string of length width. Padding is
462.2197 - done using the specified fill character (default is a space).
462.2198 -
462.2199 -
462.2200 -.. method:: lower()
462.2201 -
462.2202 - S.lower() -> unicode
462.2203 -
462.2204 - Return a copy of the string S converted to lowercase.
462.2205 -
462.2206 -
462.2207 -.. method:: lstrip()
462.2208 -
462.2209 - S.lstrip([chars]) -> unicode
462.2210 -
462.2211 - Return a copy of the string S with leading whitespace removed.
462.2212 - If chars is given and not None, remove characters in chars instead.
462.2213 - If chars is a str, it will be converted to unicode before stripping
462.2214 -
462.2215 -
462.2216 -.. method:: partition(sep)
462.2217 -
462.2218 - S.partition(sep) -> (head, sep, tail)
462.2219 -
462.2220 - Searches for the separator sep in S, and returns the part before it,
462.2221 - the separator itself, and the part after it. If the separator is not
462.2222 - found, returns S and two empty strings.
462.2223 -
462.2224 -
462.2225 -.. method:: replace(old, new)
462.2226 -
462.2227 - S.replace (old, new[, count]) -> unicode
462.2228 -
462.2229 - Return a copy of S with all occurrences of substring
462.2230 - old replaced by new. If the optional argument count is
462.2231 - given, only the first count occurrences are replaced.
462.2232 -
462.2233 -
462.2234 -.. method:: rfind(sub )
462.2235 -
462.2236 - S.rfind(sub [,start [,end]]) -> int
462.2237 -
462.2238 - Return the highest index in S where substring sub is found,
462.2239 - such that sub is contained within s[start:end]. Optional
462.2240 - arguments start and end are interpreted as in slice notation.
462.2241 -
462.2242 - Return -1 on failure.
462.2243 -
462.2244 -
462.2245 -.. method:: rindex(sub )
462.2246 -
462.2247 - S.rindex(sub [,start [,end]]) -> int
462.2248 -
462.2249 - Like S.rfind() but raise ValueError when the substring is not found.
462.2250 -
462.2251 -
462.2252 -.. method:: rjust(width)
462.2253 -
462.2254 - S.rjust(width[, fillchar]) -> unicode
462.2255 -
462.2256 - Return S right justified in a Unicode string of length width. Padding is
462.2257 - done using the specified fill character (default is a space).
462.2258 -
462.2259 -
462.2260 -.. method:: rpartition(sep)
462.2261 -
462.2262 - S.rpartition(sep) -> (tail, sep, head)
462.2263 -
462.2264 - Searches for the separator sep in S, starting at the end of S, and returns
462.2265 - the part before it, the separator itself, and the part after it. If the
462.2266 - separator is not found, returns two empty strings and S.
462.2267 -
462.2268 -
462.2269 -.. method:: rsplit()
462.2270 -
462.2271 - S.rsplit([sep [,maxsplit]]) -> list of strings
462.2272 -
462.2273 - Return a list of the words in S, using sep as the
462.2274 - delimiter string, starting at the end of the string and
462.2275 - working to the front. If maxsplit is given, at most maxsplit
462.2276 - splits are done. If sep is not specified, any whitespace string
462.2277 - is a separator.
462.2278 -
462.2279 -
462.2280 -.. method:: rstrip()
462.2281 -
462.2282 - S.rstrip([chars]) -> unicode
462.2283 -
462.2284 - Return a copy of the string S with trailing whitespace removed.
462.2285 - If chars is given and not None, remove characters in chars instead.
462.2286 - If chars is a str, it will be converted to unicode before stripping
462.2287 -
462.2288 -
462.2289 -.. method:: split()
462.2290 -
462.2291 - S.split([sep [,maxsplit]]) -> list of strings
462.2292 -
462.2293 - Return a list of the words in S, using sep as the
462.2294 - delimiter string. If maxsplit is given, at most maxsplit
462.2295 - splits are done. If sep is not specified or is None, any
462.2296 - whitespace string is a separator and empty strings are
462.2297 - removed from the result.
462.2298 -
462.2299 -
462.2300 -.. method:: splitlines()
462.2301 -
462.2302 - S.splitlines([keepends]]) -> list of strings
462.2303 -
462.2304 - Return a list of the lines in S, breaking at line boundaries.
462.2305 - Line breaks are not included in the resulting list unless keepends
462.2306 - is given and true.
462.2307 -
462.2308 -
462.2309 -.. method:: startswith(prefix)
462.2310 -
462.2311 - S.startswith(prefix[, start[, end]]) -> bool
462.2312 -
462.2313 - Return True if S starts with the specified prefix, False otherwise.
462.2314 - With optional start, test S beginning at that position.
462.2315 - With optional end, stop comparing S at that position.
462.2316 - prefix can also be a tuple of strings to try.
462.2317 -
462.2318 -
462.2319 -.. method:: strip()
462.2320 -
462.2321 - S.strip([chars]) -> unicode
462.2322 -
462.2323 - Return a copy of the string S with leading and trailing
462.2324 - whitespace removed.
462.2325 - If chars is given and not None, remove characters in chars instead.
462.2326 - If chars is a str, it will be converted to unicode before stripping
462.2327 -
462.2328 -
462.2329 -.. method:: swapcase()
462.2330 -
462.2331 - S.swapcase() -> unicode
462.2332 -
462.2333 - Return a copy of S with uppercase characters converted to lowercase
462.2334 - and vice versa.
462.2335 -
462.2336 -
462.2337 -.. method:: title()
462.2338 -
462.2339 - S.title() -> unicode
462.2340 -
462.2341 - Return a titlecased version of S, i.e. words start with title case
462.2342 - characters, all remaining cased characters have lower case.
462.2343 -
462.2344 -
462.2345 -.. method:: translate(table)
462.2346 -
462.2347 - S.translate(table) -> unicode
462.2348 -
462.2349 - Return a copy of the string S, where all characters have been mapped
462.2350 - through the given translation table, which must be a mapping of
462.2351 - Unicode ordinals to Unicode ordinals, Unicode strings or None.
462.2352 - Unmapped characters are left untouched. Characters mapped to None
462.2353 - are deleted.
462.2354 -
462.2355 -
462.2356 -.. method:: upper()
462.2357 -
462.2358 - S.upper() -> unicode
462.2359 -
462.2360 - Return a copy of S converted to uppercase.
462.2361 -
462.2362 -
462.2363 -.. method:: zfill(width)
462.2364 -
462.2365 - S.zfill(width) -> unicode
462.2366 -
462.2367 - Pad a numeric string S with zeros on the left, to fill a field
462.2368 - of the specified width. The string S is never truncated.
462.2369 -
462.2370 -
463.1 --- a/python.editor/test/unit/data/testfiles/rst/stub_missing.rst.html Sun Jan 04 13:11:53 2015 -0600
463.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
463.3 @@ -1,2638 +0,0 @@
463.4 -<html><body>
463.5 -NetBeans extra documentation:
463.6 -Documentation for APIs missing from the RST documentation shipping with Python.
463.7 -This is generated from introspecting python code using extract_rst.py.
463.8 -Python version stats:
463.9 -2.6 (trunk:66714:66715M, Oct 1 2008, 18:36:04)
463.10 -[GCC 4.0.1 (Apple Computer, Inc. build 5370)]
463.11 -
463.12 -<br><br>
463.13 -<a href="class:int">int</a>
463.14 -
463.15 -<br><br>
463.16 - int(x[, base]) -> integer
463.17 -
463.18 -<br><br>
463.19 - Convert a string or number to an integer, if possible. A floating point
463.20 - argument will be truncated towards zero (this does not include a string
463.21 - representation of a floating point number!) When converting a string, use
463.22 - the optional base. It is an error to supply a base when converting a
463.23 - non-string. If base is zero, the proper base is guessed based on the
463.24 - string content. If the argument is outside the integer range a
463.25 - long object will be returned instead.
463.26 -
463.27 -<br><br>
463.28 -<a href="attr:__class__">__class__</a>
463.29 -
463.30 -<br><br>
463.31 - int(x[, base]) -> integer
463.32 -
463.33 -<br><br>
463.34 - Convert a string or number to an integer, if possible. A floating point
463.35 - argument will be truncated towards zero (this does not include a string
463.36 - representation of a floating point number!) When converting a string, use
463.37 - the optional base. It is an error to supply a base when converting a
463.38 - non-string. If base is zero, the proper base is guessed based on the
463.39 - string content. If the argument is outside the integer range a
463.40 - long object will be returned instead.
463.41 -
463.42 -<br><br>
463.43 -<a href="meth:__cmp__(y)">__cmp__(y)</a>
463.44 -
463.45 -<br><br>
463.46 - x.__cmp__(y) <==> cmp(x,y)
463.47 -
463.48 -<br><br>
463.49 -<a href="meth:__coerce__(y)">__coerce__(y)</a>
463.50 -
463.51 -<br><br>
463.52 - x.__coerce__(y) <==> coerce(x, y)
463.53 -
463.54 -<br><br>
463.55 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
463.56 -
463.57 -<br><br>
463.58 - x.__delattr__('name') <==> del x.name
463.59 -
463.60 -<br><br>
463.61 -<a href="meth:__divmod__(y)">__divmod__(y)</a>
463.62 -
463.63 -<br><br>
463.64 - x.__divmod__(y) <==> divmod(x, y)
463.65 -
463.66 -<br><br>
463.67 -<a href="attr:__doc__">__doc__</a>
463.68 -
463.69 -<br><br>
463.70 - str(object) -> string
463.71 -
463.72 -<br><br>
463.73 - Return a nice string representation of the object.
463.74 - If the argument is a string, the return value is the same object.
463.75 -
463.76 -<br><br>
463.77 -<a href="meth:__float__()">__float__()</a>
463.78 -
463.79 -<br><br>
463.80 - x.__float__() <==> float(x)
463.81 -
463.82 -<br><br>
463.83 -<a href="meth:__format__()">__format__()</a>
463.84 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.85 -</div>
463.86 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
463.87 - x.__getattribute__('name') <==> x.name
463.88 -
463.89 -<br><br>
463.90 -<a href="meth:__getnewargs__()">__getnewargs__()</a>
463.91 -
463.92 -<br><br>
463.93 -<a href="meth:__hash__()">__hash__()</a>
463.94 -
463.95 -<br><br>
463.96 - x.__hash__() <==> hash(x)
463.97 -
463.98 -<br><br>
463.99 -<a href="meth:__hex__()">__hex__()</a>
463.100 -
463.101 -<br><br>
463.102 - x.__hex__() <==> hex(x)
463.103 -
463.104 -<br><br>
463.105 -<a href="meth:__init__()">__init__()</a>
463.106 -
463.107 -<br><br>
463.108 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
463.109 -
463.110 -<br><br>
463.111 -<a href="meth:__int__()">__int__()</a>
463.112 -
463.113 -<br><br>
463.114 - x.__int__() <==> int(x)
463.115 -
463.116 -<br><br>
463.117 -<a href="meth:__long__()">__long__()</a>
463.118 -
463.119 -<br><br>
463.120 - x.__long__() <==> long(x)
463.121 -
463.122 -<br><br>
463.123 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
463.124 -
463.125 -<br><br>
463.126 - T.__new__(S, ...) -> a new object with type S, a subtype of T
463.127 -
463.128 -<br><br>
463.129 -<a href="meth:__nonzero__()">__nonzero__()</a>
463.130 -
463.131 -<br><br>
463.132 - x.__nonzero__() <==> x != 0
463.133 -
463.134 -<br><br>
463.135 -<a href="meth:__oct__()">__oct__()</a>
463.136 -
463.137 -<br><br>
463.138 - x.__oct__() <==> oct(x)
463.139 -
463.140 -<br><br>
463.141 -<a href="meth:__radd__(y)">__radd__(y)</a>
463.142 -
463.143 -<br><br>
463.144 - x.__radd__(y) <==> y+x
463.145 -
463.146 -<br><br>
463.147 -<a href="meth:__rand__(y)">__rand__(y)</a>
463.148 -
463.149 -<br><br>
463.150 - x.__rand__(y) <==> y&x
463.151 -
463.152 -<br><br>
463.153 -<a href="meth:__rdiv__(y)">__rdiv__(y)</a>
463.154 -
463.155 -<br><br>
463.156 - x.__rdiv__(y) <==> y/x
463.157 -
463.158 -<br><br>
463.159 -<a href="meth:__rdivmod__(y)">__rdivmod__(y)</a>
463.160 -
463.161 -<br><br>
463.162 - x.__rdivmod__(y) <==> divmod(y, x)
463.163 -
463.164 -<br><br>
463.165 -<a href="meth:__reduce__()">__reduce__()</a>
463.166 -
463.167 -<br><br>
463.168 - helper for pickle
463.169 -
463.170 -<br><br>
463.171 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
463.172 -
463.173 -<br><br>
463.174 - helper for pickle
463.175 -
463.176 -<br><br>
463.177 -<a href="meth:__repr__()">__repr__()</a>
463.178 -
463.179 -<br><br>
463.180 - x.__repr__() <==> repr(x)
463.181 -
463.182 -<br><br>
463.183 -<a href="meth:__rfloordiv__(y)">__rfloordiv__(y)</a>
463.184 -
463.185 -<br><br>
463.186 - x.__rfloordiv__(y) <==> y//x
463.187 -
463.188 -<br><br>
463.189 -<a href="meth:__rlshift__(y)">__rlshift__(y)</a>
463.190 -
463.191 -<br><br>
463.192 - x.__rlshift__(y) <==> y<<x
463.193 -
463.194 -<br><br>
463.195 -<a href="meth:__rmod__(y)">__rmod__(y)</a>
463.196 -
463.197 -<br><br>
463.198 - x.__rmod__(y) <==> y%x
463.199 -
463.200 -<br><br>
463.201 -<a href="meth:__rmul__(y)">__rmul__(y)</a>
463.202 -
463.203 -<br><br>
463.204 - x.__rmul__(y) <==> y*x
463.205 -
463.206 -<br><br>
463.207 -<a href="meth:__ror__(y)">__ror__(y)</a>
463.208 -
463.209 -<br><br>
463.210 - x.__ror__(y) <==> y|x
463.211 -
463.212 -<br><br>
463.213 -<a href="meth:__rpow__(x)">__rpow__(x)</a>
463.214 -
463.215 -<br><br>
463.216 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
463.217 -
463.218 -<br><br>
463.219 -<a href="meth:__rrshift__(y)">__rrshift__(y)</a>
463.220 -
463.221 -<br><br>
463.222 - x.__rrshift__(y) <==> y>>x
463.223 -
463.224 -<br><br>
463.225 -<a href="meth:__rsub__(y)">__rsub__(y)</a>
463.226 -
463.227 -<br><br>
463.228 - x.__rsub__(y) <==> y-x
463.229 -
463.230 -<br><br>
463.231 -<a href="meth:__rtruediv__(y)">__rtruediv__(y)</a>
463.232 -
463.233 -<br><br>
463.234 - x.__rtruediv__(y) <==> y/x
463.235 -
463.236 -<br><br>
463.237 -<a href="meth:__rxor__(y)">__rxor__(y)</a>
463.238 -
463.239 -<br><br>
463.240 - x.__rxor__(y) <==> y^x
463.241 -
463.242 -<br><br>
463.243 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
463.244 -
463.245 -<br><br>
463.246 - x.__setattr__('name', value) <==> x.name = value
463.247 -
463.248 -<br><br>
463.249 -<a href="meth:__sizeof__()">__sizeof__()</a>
463.250 -
463.251 -<br><br>
463.252 - __sizeof__() -> size of object in memory, in bytes
463.253 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.254 -</div>
463.255 -<a href="meth:__str__()">__str__()</a>
463.256 - x.__str__() <==> str(x)
463.257 -
463.258 -<br><br>
463.259 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
463.260 -
463.261 -<br><br>
463.262 - Abstract classes can override this to customize issubclass().
463.263 -
463.264 -<br><br>
463.265 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
463.266 - It should return True, False or NotImplemented. If it returns
463.267 - NotImplemented, the normal algorithm is used. Otherwise, it
463.268 - overrides the normal algorithm (and the outcome is cached).
463.269 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.270 -</div>
463.271 -<a href="meth:__trunc__()">__trunc__()</a>
463.272 - Truncating an Integral returns itself.
463.273 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.274 -</div>
463.275 -<a href="meth:conjugate()">conjugate()</a>
463.276 - Returns self, the complex conjugate of any int.
463.277 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.278 -</div>
463.279 -<a href="attr:denominator">denominator</a>
463.280 - int(x[, base]) -> integer
463.281 -
463.282 -<br><br>
463.283 - Convert a string or number to an integer, if possible. A floating point
463.284 - argument will be truncated towards zero (this does not include a string
463.285 - representation of a floating point number!) When converting a string, use
463.286 - the optional base. It is an error to supply a base when converting a
463.287 - non-string. If base is zero, the proper base is guessed based on the
463.288 - string content. If the argument is outside the integer range a
463.289 - long object will be returned instead.
463.290 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.291 -</div>
463.292 -<a href="attr:imag">imag</a>
463.293 - int(x[, base]) -> integer
463.294 -
463.295 -<br><br>
463.296 - Convert a string or number to an integer, if possible. A floating point
463.297 - argument will be truncated towards zero (this does not include a string
463.298 - representation of a floating point number!) When converting a string, use
463.299 - the optional base. It is an error to supply a base when converting a
463.300 - non-string. If base is zero, the proper base is guessed based on the
463.301 - string content. If the argument is outside the integer range a
463.302 - long object will be returned instead.
463.303 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.304 -</div>
463.305 -<a href="attr:numerator">numerator</a>
463.306 - int(x[, base]) -> integer
463.307 -
463.308 -<br><br>
463.309 - Convert a string or number to an integer, if possible. A floating point
463.310 - argument will be truncated towards zero (this does not include a string
463.311 - representation of a floating point number!) When converting a string, use
463.312 - the optional base. It is an error to supply a base when converting a
463.313 - non-string. If base is zero, the proper base is guessed based on the
463.314 - string content. If the argument is outside the integer range a
463.315 - long object will be returned instead.
463.316 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.317 -</div>
463.318 -<a href="attr:real">real</a>
463.319 - int(x[, base]) -> integer
463.320 -
463.321 -<br><br>
463.322 - Convert a string or number to an integer, if possible. A floating point
463.323 - argument will be truncated towards zero (this does not include a string
463.324 - representation of a floating point number!) When converting a string, use
463.325 - the optional base. It is an error to supply a base when converting a
463.326 - non-string. If base is zero, the proper base is guessed based on the
463.327 - string content. If the argument is outside the integer range a
463.328 - long object will be returned instead.
463.329 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.330 -</div>
463.331 -<a href="class:float">float</a>
463.332 - float(x) -> floating point number
463.333 -
463.334 -<br><br>
463.335 - Convert a string or number to a floating point number, if possible.
463.336 -
463.337 -<br><br>
463.338 -<a href="attr:__class__">__class__</a>
463.339 -
463.340 -<br><br>
463.341 - float(x) -> floating point number
463.342 -
463.343 -<br><br>
463.344 - Convert a string or number to a floating point number, if possible.
463.345 -
463.346 -<br><br>
463.347 -<a href="meth:__coerce__(y)">__coerce__(y)</a>
463.348 -
463.349 -<br><br>
463.350 - x.__coerce__(y) <==> coerce(x, y)
463.351 -
463.352 -<br><br>
463.353 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
463.354 -
463.355 -<br><br>
463.356 - x.__delattr__('name') <==> del x.name
463.357 -
463.358 -<br><br>
463.359 -<a href="meth:__divmod__(y)">__divmod__(y)</a>
463.360 -
463.361 -<br><br>
463.362 - x.__divmod__(y) <==> divmod(x, y)
463.363 -
463.364 -<br><br>
463.365 -<a href="attr:__doc__">__doc__</a>
463.366 -
463.367 -<br><br>
463.368 - str(object) -> string
463.369 -
463.370 -<br><br>
463.371 - Return a nice string representation of the object.
463.372 - If the argument is a string, the return value is the same object.
463.373 -
463.374 -<br><br>
463.375 -<a href="meth:__float__()">__float__()</a>
463.376 -
463.377 -<br><br>
463.378 - x.__float__() <==> float(x)
463.379 -
463.380 -<br><br>
463.381 -<a href="meth:__format__(format_spec)">__format__(format_spec)</a>
463.382 -
463.383 -<br><br>
463.384 - float.__format__(format_spec) -> string
463.385 -
463.386 -<br><br>
463.387 - Formats the float according to format_spec.
463.388 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.389 -</div>
463.390 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
463.391 - x.__getattribute__('name') <==> x.name
463.392 -
463.393 -<br><br>
463.394 -<a href="meth:__getformat__(typestr)">__getformat__(typestr)</a>
463.395 -
463.396 -<br><br>
463.397 - float.__getformat__(typestr) -> string
463.398 -
463.399 -<br><br>
463.400 - You probably don't want to use this function. It exists mainly to be
463.401 - used in Python's test suite.
463.402 -
463.403 -<br><br>
463.404 - typestr must be 'double' or 'float'. This function returns whichever of
463.405 - 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the
463.406 - format of floating point numbers used by the C type named by typestr.
463.407 -
463.408 -<br><br>
463.409 -<a href="meth:__getnewargs__()">__getnewargs__()</a>
463.410 -
463.411 -<br><br>
463.412 -<a href="meth:__hash__()">__hash__()</a>
463.413 -
463.414 -<br><br>
463.415 - x.__hash__() <==> hash(x)
463.416 -
463.417 -<br><br>
463.418 -<a href="meth:__init__()">__init__()</a>
463.419 -
463.420 -<br><br>
463.421 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
463.422 -
463.423 -<br><br>
463.424 -<a href="meth:__int__()">__int__()</a>
463.425 -
463.426 -<br><br>
463.427 - x.__int__() <==> int(x)
463.428 -
463.429 -<br><br>
463.430 -<a href="meth:__long__()">__long__()</a>
463.431 -
463.432 -<br><br>
463.433 - x.__long__() <==> long(x)
463.434 -
463.435 -<br><br>
463.436 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
463.437 -
463.438 -<br><br>
463.439 - T.__new__(S, ...) -> a new object with type S, a subtype of T
463.440 -
463.441 -<br><br>
463.442 -<a href="meth:__nonzero__()">__nonzero__()</a>
463.443 -
463.444 -<br><br>
463.445 - x.__nonzero__() <==> x != 0
463.446 -
463.447 -<br><br>
463.448 -<a href="meth:__radd__(y)">__radd__(y)</a>
463.449 -
463.450 -<br><br>
463.451 - x.__radd__(y) <==> y+x
463.452 -
463.453 -<br><br>
463.454 -<a href="meth:__rdiv__(y)">__rdiv__(y)</a>
463.455 -
463.456 -<br><br>
463.457 - x.__rdiv__(y) <==> y/x
463.458 -
463.459 -<br><br>
463.460 -<a href="meth:__rdivmod__(y)">__rdivmod__(y)</a>
463.461 -
463.462 -<br><br>
463.463 - x.__rdivmod__(y) <==> divmod(y, x)
463.464 -
463.465 -<br><br>
463.466 -<a href="meth:__reduce__()">__reduce__()</a>
463.467 -
463.468 -<br><br>
463.469 - helper for pickle
463.470 -
463.471 -<br><br>
463.472 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
463.473 -
463.474 -<br><br>
463.475 - helper for pickle
463.476 -
463.477 -<br><br>
463.478 -<a href="meth:__repr__()">__repr__()</a>
463.479 -
463.480 -<br><br>
463.481 - x.__repr__() <==> repr(x)
463.482 -
463.483 -<br><br>
463.484 -<a href="meth:__rfloordiv__(y)">__rfloordiv__(y)</a>
463.485 -
463.486 -<br><br>
463.487 - x.__rfloordiv__(y) <==> y//x
463.488 -
463.489 -<br><br>
463.490 -<a href="meth:__rmod__(y)">__rmod__(y)</a>
463.491 -
463.492 -<br><br>
463.493 - x.__rmod__(y) <==> y%x
463.494 -
463.495 -<br><br>
463.496 -<a href="meth:__rmul__(y)">__rmul__(y)</a>
463.497 -
463.498 -<br><br>
463.499 - x.__rmul__(y) <==> y*x
463.500 -
463.501 -<br><br>
463.502 -<a href="meth:__rpow__(x)">__rpow__(x)</a>
463.503 -
463.504 -<br><br>
463.505 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
463.506 -
463.507 -<br><br>
463.508 -<a href="meth:__rsub__(y)">__rsub__(y)</a>
463.509 -
463.510 -<br><br>
463.511 - x.__rsub__(y) <==> y-x
463.512 -
463.513 -<br><br>
463.514 -<a href="meth:__rtruediv__(y)">__rtruediv__(y)</a>
463.515 -
463.516 -<br><br>
463.517 - x.__rtruediv__(y) <==> y/x
463.518 -
463.519 -<br><br>
463.520 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
463.521 -
463.522 -<br><br>
463.523 - x.__setattr__('name', value) <==> x.name = value
463.524 -
463.525 -<br><br>
463.526 -<a href="meth:__setformat__(typestr, fmt)">__setformat__(typestr, fmt)</a>
463.527 -
463.528 -<br><br>
463.529 - float.__setformat__(typestr, fmt) -> None
463.530 -
463.531 -<br><br>
463.532 - You probably don't want to use this function. It exists mainly to be
463.533 - used in Python's test suite.
463.534 -
463.535 -<br><br>
463.536 - typestr must be 'double' or 'float'. fmt must be one of 'unknown',
463.537 - 'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be
463.538 - one of the latter two if it appears to match the underlying C reality.
463.539 -
463.540 -<br><br>
463.541 - Overrides the automatic determination of C-level floating point type.
463.542 - This affects how floats are converted to and from binary strings.
463.543 -
463.544 -<br><br>
463.545 -<a href="meth:__sizeof__()">__sizeof__()</a>
463.546 -
463.547 -<br><br>
463.548 - __sizeof__() -> size of object in memory, in bytes
463.549 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.550 -</div>
463.551 -<a href="meth:__str__()">__str__()</a>
463.552 - x.__str__() <==> str(x)
463.553 -
463.554 -<br><br>
463.555 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
463.556 -
463.557 -<br><br>
463.558 - Abstract classes can override this to customize issubclass().
463.559 -
463.560 -<br><br>
463.561 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
463.562 - It should return True, False or NotImplemented. If it returns
463.563 - NotImplemented, the normal algorithm is used. Otherwise, it
463.564 - overrides the normal algorithm (and the outcome is cached).
463.565 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.566 -</div>
463.567 -<a href="meth:__trunc__()">__trunc__()</a>
463.568 - Returns the Integral closest to x between 0 and x.
463.569 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.570 -</div>
463.571 -<a href="meth:conjugate()">conjugate()</a>
463.572 - Returns self, the complex conjugate of any float.
463.573 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.574 -</div>
463.575 -<a href="attr:imag">imag</a>
463.576 - float(x) -> floating point number
463.577 -
463.578 -<br><br>
463.579 - Convert a string or number to a floating point number, if possible.
463.580 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.581 -</div>
463.582 -<a href="meth:is_integer()">is_integer()</a>
463.583 - Returns True if the float is an integer.
463.584 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.585 -</div>
463.586 -<a href="attr:real">real</a>
463.587 - float(x) -> floating point number
463.588 -
463.589 -<br><br>
463.590 - Convert a string or number to a floating point number, if possible.
463.591 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.592 -</div>
463.593 -<a href="class:long">long</a>
463.594 - long(x[, base]) -> integer
463.595 -
463.596 -<br><br>
463.597 - Convert a string or number to a long integer, if possible. A floating
463.598 - point argument will be truncated towards zero (this does not include a
463.599 - string representation of a floating point number!) When converting a
463.600 - string, use the optional base. It is an error to supply a base when
463.601 - converting a non-string.
463.602 -
463.603 -<br><br>
463.604 -<a href="attr:__class__">__class__</a>
463.605 -
463.606 -<br><br>
463.607 - long(x[, base]) -> integer
463.608 -
463.609 -<br><br>
463.610 - Convert a string or number to a long integer, if possible. A floating
463.611 - point argument will be truncated towards zero (this does not include a
463.612 - string representation of a floating point number!) When converting a
463.613 - string, use the optional base. It is an error to supply a base when
463.614 - converting a non-string.
463.615 -
463.616 -<br><br>
463.617 -<a href="meth:__cmp__(y)">__cmp__(y)</a>
463.618 -
463.619 -<br><br>
463.620 - x.__cmp__(y) <==> cmp(x,y)
463.621 -
463.622 -<br><br>
463.623 -<a href="meth:__coerce__(y)">__coerce__(y)</a>
463.624 -
463.625 -<br><br>
463.626 - x.__coerce__(y) <==> coerce(x, y)
463.627 -
463.628 -<br><br>
463.629 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
463.630 -
463.631 -<br><br>
463.632 - x.__delattr__('name') <==> del x.name
463.633 -
463.634 -<br><br>
463.635 -<a href="meth:__divmod__(y)">__divmod__(y)</a>
463.636 -
463.637 -<br><br>
463.638 - x.__divmod__(y) <==> divmod(x, y)
463.639 -
463.640 -<br><br>
463.641 -<a href="attr:__doc__">__doc__</a>
463.642 -
463.643 -<br><br>
463.644 - str(object) -> string
463.645 -
463.646 -<br><br>
463.647 - Return a nice string representation of the object.
463.648 - If the argument is a string, the return value is the same object.
463.649 -
463.650 -<br><br>
463.651 -<a href="meth:__float__()">__float__()</a>
463.652 -
463.653 -<br><br>
463.654 - x.__float__() <==> float(x)
463.655 -
463.656 -<br><br>
463.657 -<a href="meth:__format__()">__format__()</a>
463.658 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.659 -</div>
463.660 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
463.661 - x.__getattribute__('name') <==> x.name
463.662 -
463.663 -<br><br>
463.664 -<a href="meth:__getnewargs__()">__getnewargs__()</a>
463.665 -
463.666 -<br><br>
463.667 -<a href="meth:__hash__()">__hash__()</a>
463.668 -
463.669 -<br><br>
463.670 - x.__hash__() <==> hash(x)
463.671 -
463.672 -<br><br>
463.673 -<a href="meth:__hex__()">__hex__()</a>
463.674 -
463.675 -<br><br>
463.676 - x.__hex__() <==> hex(x)
463.677 -
463.678 -<br><br>
463.679 -<a href="meth:__init__()">__init__()</a>
463.680 -
463.681 -<br><br>
463.682 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
463.683 -
463.684 -<br><br>
463.685 -<a href="meth:__int__()">__int__()</a>
463.686 -
463.687 -<br><br>
463.688 - x.__int__() <==> int(x)
463.689 -
463.690 -<br><br>
463.691 -<a href="meth:__long__()">__long__()</a>
463.692 -
463.693 -<br><br>
463.694 - x.__long__() <==> long(x)
463.695 -
463.696 -<br><br>
463.697 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
463.698 -
463.699 -<br><br>
463.700 - T.__new__(S, ...) -> a new object with type S, a subtype of T
463.701 -
463.702 -<br><br>
463.703 -<a href="meth:__nonzero__()">__nonzero__()</a>
463.704 -
463.705 -<br><br>
463.706 - x.__nonzero__() <==> x != 0
463.707 -
463.708 -<br><br>
463.709 -<a href="meth:__oct__()">__oct__()</a>
463.710 -
463.711 -<br><br>
463.712 - x.__oct__() <==> oct(x)
463.713 -
463.714 -<br><br>
463.715 -<a href="meth:__radd__(y)">__radd__(y)</a>
463.716 -
463.717 -<br><br>
463.718 - x.__radd__(y) <==> y+x
463.719 -
463.720 -<br><br>
463.721 -<a href="meth:__rand__(y)">__rand__(y)</a>
463.722 -
463.723 -<br><br>
463.724 - x.__rand__(y) <==> y&x
463.725 -
463.726 -<br><br>
463.727 -<a href="meth:__rdiv__(y)">__rdiv__(y)</a>
463.728 -
463.729 -<br><br>
463.730 - x.__rdiv__(y) <==> y/x
463.731 -
463.732 -<br><br>
463.733 -<a href="meth:__rdivmod__(y)">__rdivmod__(y)</a>
463.734 -
463.735 -<br><br>
463.736 - x.__rdivmod__(y) <==> divmod(y, x)
463.737 -
463.738 -<br><br>
463.739 -<a href="meth:__reduce__()">__reduce__()</a>
463.740 -
463.741 -<br><br>
463.742 - helper for pickle
463.743 -
463.744 -<br><br>
463.745 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
463.746 -
463.747 -<br><br>
463.748 - helper for pickle
463.749 -
463.750 -<br><br>
463.751 -<a href="meth:__repr__()">__repr__()</a>
463.752 -
463.753 -<br><br>
463.754 - x.__repr__() <==> repr(x)
463.755 -
463.756 -<br><br>
463.757 -<a href="meth:__rfloordiv__(y)">__rfloordiv__(y)</a>
463.758 -
463.759 -<br><br>
463.760 - x.__rfloordiv__(y) <==> y//x
463.761 -
463.762 -<br><br>
463.763 -<a href="meth:__rlshift__(y)">__rlshift__(y)</a>
463.764 -
463.765 -<br><br>
463.766 - x.__rlshift__(y) <==> y<<x
463.767 -
463.768 -<br><br>
463.769 -<a href="meth:__rmod__(y)">__rmod__(y)</a>
463.770 -
463.771 -<br><br>
463.772 - x.__rmod__(y) <==> y%x
463.773 -
463.774 -<br><br>
463.775 -<a href="meth:__rmul__(y)">__rmul__(y)</a>
463.776 -
463.777 -<br><br>
463.778 - x.__rmul__(y) <==> y*x
463.779 -
463.780 -<br><br>
463.781 -<a href="meth:__ror__(y)">__ror__(y)</a>
463.782 -
463.783 -<br><br>
463.784 - x.__ror__(y) <==> y|x
463.785 -
463.786 -<br><br>
463.787 -<a href="meth:__rpow__(x)">__rpow__(x)</a>
463.788 -
463.789 -<br><br>
463.790 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
463.791 -
463.792 -<br><br>
463.793 -<a href="meth:__rrshift__(y)">__rrshift__(y)</a>
463.794 -
463.795 -<br><br>
463.796 - x.__rrshift__(y) <==> y>>x
463.797 -
463.798 -<br><br>
463.799 -<a href="meth:__rsub__(y)">__rsub__(y)</a>
463.800 -
463.801 -<br><br>
463.802 - x.__rsub__(y) <==> y-x
463.803 -
463.804 -<br><br>
463.805 -<a href="meth:__rtruediv__(y)">__rtruediv__(y)</a>
463.806 -
463.807 -<br><br>
463.808 - x.__rtruediv__(y) <==> y/x
463.809 -
463.810 -<br><br>
463.811 -<a href="meth:__rxor__(y)">__rxor__(y)</a>
463.812 -
463.813 -<br><br>
463.814 - x.__rxor__(y) <==> y^x
463.815 -
463.816 -<br><br>
463.817 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
463.818 -
463.819 -<br><br>
463.820 - x.__setattr__('name', value) <==> x.name = value
463.821 -
463.822 -<br><br>
463.823 -<a href="meth:__sizeof__()">__sizeof__()</a>
463.824 -
463.825 -<br><br>
463.826 - Returns size in memory, in bytes
463.827 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.828 -</div>
463.829 -<a href="meth:__str__()">__str__()</a>
463.830 - x.__str__() <==> str(x)
463.831 -
463.832 -<br><br>
463.833 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
463.834 -
463.835 -<br><br>
463.836 - Abstract classes can override this to customize issubclass().
463.837 -
463.838 -<br><br>
463.839 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
463.840 - It should return True, False or NotImplemented. If it returns
463.841 - NotImplemented, the normal algorithm is used. Otherwise, it
463.842 - overrides the normal algorithm (and the outcome is cached).
463.843 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.844 -</div>
463.845 -<a href="meth:__trunc__()">__trunc__()</a>
463.846 - Truncating an Integral returns itself.
463.847 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.848 -</div>
463.849 -<a href="meth:conjugate()">conjugate()</a>
463.850 - Returns self, the complex conjugate of any long.
463.851 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.852 -</div>
463.853 -<a href="attr:denominator">denominator</a>
463.854 - long(x[, base]) -> integer
463.855 -
463.856 -<br><br>
463.857 - Convert a string or number to a long integer, if possible. A floating
463.858 - point argument will be truncated towards zero (this does not include a
463.859 - string representation of a floating point number!) When converting a
463.860 - string, use the optional base. It is an error to supply a base when
463.861 - converting a non-string.
463.862 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.863 -</div>
463.864 -<a href="attr:imag">imag</a>
463.865 - long(x[, base]) -> integer
463.866 -
463.867 -<br><br>
463.868 - Convert a string or number to a long integer, if possible. A floating
463.869 - point argument will be truncated towards zero (this does not include a
463.870 - string representation of a floating point number!) When converting a
463.871 - string, use the optional base. It is an error to supply a base when
463.872 - converting a non-string.
463.873 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.874 -</div>
463.875 -<a href="attr:numerator">numerator</a>
463.876 - long(x[, base]) -> integer
463.877 -
463.878 -<br><br>
463.879 - Convert a string or number to a long integer, if possible. A floating
463.880 - point argument will be truncated towards zero (this does not include a
463.881 - string representation of a floating point number!) When converting a
463.882 - string, use the optional base. It is an error to supply a base when
463.883 - converting a non-string.
463.884 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.885 -</div>
463.886 -<a href="attr:real">real</a>
463.887 - long(x[, base]) -> integer
463.888 -
463.889 -<br><br>
463.890 - Convert a string or number to a long integer, if possible. A floating
463.891 - point argument will be truncated towards zero (this does not include a
463.892 - string representation of a floating point number!) When converting a
463.893 - string, use the optional base. It is an error to supply a base when
463.894 - converting a non-string.
463.895 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.896 -</div>
463.897 -<a href="class:bool">bool</a>
463.898 - bool(x) -> bool
463.899 -
463.900 -<br><br>
463.901 - Returns True when the argument x is true, False otherwise.
463.902 - The builtins True and False are the only two instances of the class bool.
463.903 - The class bool is a subclass of the class int, and cannot be subclassed.
463.904 -
463.905 -<br><br>
463.906 -<a href="meth:__abs__()">__abs__()</a>
463.907 -
463.908 -<br><br>
463.909 - x.__abs__() <==> abs(x)
463.910 -
463.911 -<br><br>
463.912 -<a href="meth:__add__(y)">__add__(y)</a>
463.913 -
463.914 -<br><br>
463.915 - x.__add__(y) <==> x+y
463.916 -
463.917 -<br><br>
463.918 -<a href="meth:__and__(y)">__and__(y)</a>
463.919 -
463.920 -<br><br>
463.921 - x.__and__(y) <==> x&y
463.922 -
463.923 -<br><br>
463.924 -<a href="attr:__class__">__class__</a>
463.925 -
463.926 -<br><br>
463.927 - bool(x) -> bool
463.928 -
463.929 -<br><br>
463.930 - Returns True when the argument x is true, False otherwise.
463.931 - The builtins True and False are the only two instances of the class bool.
463.932 - The class bool is a subclass of the class int, and cannot be subclassed.
463.933 -
463.934 -<br><br>
463.935 -<a href="meth:__cmp__(y)">__cmp__(y)</a>
463.936 -
463.937 -<br><br>
463.938 - x.__cmp__(y) <==> cmp(x,y)
463.939 -
463.940 -<br><br>
463.941 -<a href="meth:__coerce__(y)">__coerce__(y)</a>
463.942 -
463.943 -<br><br>
463.944 - x.__coerce__(y) <==> coerce(x, y)
463.945 -
463.946 -<br><br>
463.947 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
463.948 -
463.949 -<br><br>
463.950 - x.__delattr__('name') <==> del x.name
463.951 -
463.952 -<br><br>
463.953 -<a href="meth:__div__(y)">__div__(y)</a>
463.954 -
463.955 -<br><br>
463.956 - x.__div__(y) <==> x/y
463.957 -
463.958 -<br><br>
463.959 -<a href="meth:__divmod__(y)">__divmod__(y)</a>
463.960 -
463.961 -<br><br>
463.962 - x.__divmod__(y) <==> divmod(x, y)
463.963 -
463.964 -<br><br>
463.965 -<a href="attr:__doc__">__doc__</a>
463.966 -
463.967 -<br><br>
463.968 - str(object) -> string
463.969 -
463.970 -<br><br>
463.971 - Return a nice string representation of the object.
463.972 - If the argument is a string, the return value is the same object.
463.973 -
463.974 -<br><br>
463.975 -<a href="meth:__float__()">__float__()</a>
463.976 -
463.977 -<br><br>
463.978 - x.__float__() <==> float(x)
463.979 -
463.980 -<br><br>
463.981 -<a href="meth:__floordiv__(y)">__floordiv__(y)</a>
463.982 -
463.983 -<br><br>
463.984 - x.__floordiv__(y) <==> x//y
463.985 -
463.986 -<br><br>
463.987 -<a href="meth:__format__()">__format__()</a>
463.988 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.989 -</div>
463.990 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
463.991 - x.__getattribute__('name') <==> x.name
463.992 -
463.993 -<br><br>
463.994 -<a href="meth:__getnewargs__()">__getnewargs__()</a>
463.995 -
463.996 -<br><br>
463.997 -<a href="meth:__hash__()">__hash__()</a>
463.998 -
463.999 -<br><br>
463.1000 - x.__hash__() <==> hash(x)
463.1001 -
463.1002 -<br><br>
463.1003 -<a href="meth:__hex__()">__hex__()</a>
463.1004 -
463.1005 -<br><br>
463.1006 - x.__hex__() <==> hex(x)
463.1007 -
463.1008 -<br><br>
463.1009 -<a href="meth:__index__()">__index__()</a>
463.1010 -
463.1011 -<br><br>
463.1012 - x[y:z] <==> x[y.__index__():z.__index__()]
463.1013 -
463.1014 -<br><br>
463.1015 -<a href="meth:__init__()">__init__()</a>
463.1016 -
463.1017 -<br><br>
463.1018 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
463.1019 -
463.1020 -<br><br>
463.1021 -<a href="meth:__int__()">__int__()</a>
463.1022 -
463.1023 -<br><br>
463.1024 - x.__int__() <==> int(x)
463.1025 -
463.1026 -<br><br>
463.1027 -<a href="meth:__invert__()">__invert__()</a>
463.1028 -
463.1029 -<br><br>
463.1030 - x.__invert__() <==> ~x
463.1031 -
463.1032 -<br><br>
463.1033 -<a href="meth:__long__()">__long__()</a>
463.1034 -
463.1035 -<br><br>
463.1036 - x.__long__() <==> long(x)
463.1037 -
463.1038 -<br><br>
463.1039 -<a href="meth:__lshift__(y)">__lshift__(y)</a>
463.1040 -
463.1041 -<br><br>
463.1042 - x.__lshift__(y) <==> x<<y
463.1043 -
463.1044 -<br><br>
463.1045 -<a href="meth:__mod__(y)">__mod__(y)</a>
463.1046 -
463.1047 -<br><br>
463.1048 - x.__mod__(y) <==> x%y
463.1049 -
463.1050 -<br><br>
463.1051 -<a href="meth:__mul__(y)">__mul__(y)</a>
463.1052 -
463.1053 -<br><br>
463.1054 - x.__mul__(y) <==> x*y
463.1055 -
463.1056 -<br><br>
463.1057 -<a href="meth:__neg__()">__neg__()</a>
463.1058 -
463.1059 -<br><br>
463.1060 - x.__neg__() <==> -x
463.1061 -
463.1062 -<br><br>
463.1063 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
463.1064 -
463.1065 -<br><br>
463.1066 - T.__new__(S, ...) -> a new object with type S, a subtype of T
463.1067 -
463.1068 -<br><br>
463.1069 -<a href="meth:__nonzero__()">__nonzero__()</a>
463.1070 -
463.1071 -<br><br>
463.1072 - x.__nonzero__() <==> x != 0
463.1073 -
463.1074 -<br><br>
463.1075 -<a href="meth:__oct__()">__oct__()</a>
463.1076 -
463.1077 -<br><br>
463.1078 - x.__oct__() <==> oct(x)
463.1079 -
463.1080 -<br><br>
463.1081 -<a href="meth:__or__(y)">__or__(y)</a>
463.1082 -
463.1083 -<br><br>
463.1084 - x.__or__(y) <==> x|y
463.1085 -
463.1086 -<br><br>
463.1087 -<a href="meth:__pos__()">__pos__()</a>
463.1088 -
463.1089 -<br><br>
463.1090 - x.__pos__() <==> +x
463.1091 -
463.1092 -<br><br>
463.1093 -<a href="meth:__pow__(y)">__pow__(y)</a>
463.1094 -
463.1095 -<br><br>
463.1096 - x.__pow__(y[, z]) <==> pow(x, y[, z])
463.1097 -
463.1098 -<br><br>
463.1099 -<a href="meth:__radd__(y)">__radd__(y)</a>
463.1100 -
463.1101 -<br><br>
463.1102 - x.__radd__(y) <==> y+x
463.1103 -
463.1104 -<br><br>
463.1105 -<a href="meth:__rand__(y)">__rand__(y)</a>
463.1106 -
463.1107 -<br><br>
463.1108 - x.__rand__(y) <==> y&x
463.1109 -
463.1110 -<br><br>
463.1111 -<a href="meth:__rdiv__(y)">__rdiv__(y)</a>
463.1112 -
463.1113 -<br><br>
463.1114 - x.__rdiv__(y) <==> y/x
463.1115 -
463.1116 -<br><br>
463.1117 -<a href="meth:__rdivmod__(y)">__rdivmod__(y)</a>
463.1118 -
463.1119 -<br><br>
463.1120 - x.__rdivmod__(y) <==> divmod(y, x)
463.1121 -
463.1122 -<br><br>
463.1123 -<a href="meth:__reduce__()">__reduce__()</a>
463.1124 -
463.1125 -<br><br>
463.1126 - helper for pickle
463.1127 -
463.1128 -<br><br>
463.1129 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
463.1130 -
463.1131 -<br><br>
463.1132 - helper for pickle
463.1133 -
463.1134 -<br><br>
463.1135 -<a href="meth:__repr__()">__repr__()</a>
463.1136 -
463.1137 -<br><br>
463.1138 - x.__repr__() <==> repr(x)
463.1139 -
463.1140 -<br><br>
463.1141 -<a href="meth:__rfloordiv__(y)">__rfloordiv__(y)</a>
463.1142 -
463.1143 -<br><br>
463.1144 - x.__rfloordiv__(y) <==> y//x
463.1145 -
463.1146 -<br><br>
463.1147 -<a href="meth:__rlshift__(y)">__rlshift__(y)</a>
463.1148 -
463.1149 -<br><br>
463.1150 - x.__rlshift__(y) <==> y<<x
463.1151 -
463.1152 -<br><br>
463.1153 -<a href="meth:__rmod__(y)">__rmod__(y)</a>
463.1154 -
463.1155 -<br><br>
463.1156 - x.__rmod__(y) <==> y%x
463.1157 -
463.1158 -<br><br>
463.1159 -<a href="meth:__rmul__(y)">__rmul__(y)</a>
463.1160 -
463.1161 -<br><br>
463.1162 - x.__rmul__(y) <==> y*x
463.1163 -
463.1164 -<br><br>
463.1165 -<a href="meth:__ror__(y)">__ror__(y)</a>
463.1166 -
463.1167 -<br><br>
463.1168 - x.__ror__(y) <==> y|x
463.1169 -
463.1170 -<br><br>
463.1171 -<a href="meth:__rpow__(x)">__rpow__(x)</a>
463.1172 -
463.1173 -<br><br>
463.1174 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
463.1175 -
463.1176 -<br><br>
463.1177 -<a href="meth:__rrshift__(y)">__rrshift__(y)</a>
463.1178 -
463.1179 -<br><br>
463.1180 - x.__rrshift__(y) <==> y>>x
463.1181 -
463.1182 -<br><br>
463.1183 -<a href="meth:__rshift__(y)">__rshift__(y)</a>
463.1184 -
463.1185 -<br><br>
463.1186 - x.__rshift__(y) <==> x>>y
463.1187 -
463.1188 -<br><br>
463.1189 -<a href="meth:__rsub__(y)">__rsub__(y)</a>
463.1190 -
463.1191 -<br><br>
463.1192 - x.__rsub__(y) <==> y-x
463.1193 -
463.1194 -<br><br>
463.1195 -<a href="meth:__rtruediv__(y)">__rtruediv__(y)</a>
463.1196 -
463.1197 -<br><br>
463.1198 - x.__rtruediv__(y) <==> y/x
463.1199 -
463.1200 -<br><br>
463.1201 -<a href="meth:__rxor__(y)">__rxor__(y)</a>
463.1202 -
463.1203 -<br><br>
463.1204 - x.__rxor__(y) <==> y^x
463.1205 -
463.1206 -<br><br>
463.1207 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
463.1208 -
463.1209 -<br><br>
463.1210 - x.__setattr__('name', value) <==> x.name = value
463.1211 -
463.1212 -<br><br>
463.1213 -<a href="meth:__sizeof__()">__sizeof__()</a>
463.1214 -
463.1215 -<br><br>
463.1216 - __sizeof__() -> size of object in memory, in bytes
463.1217 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1218 -</div>
463.1219 -<a href="meth:__str__()">__str__()</a>
463.1220 - x.__str__() <==> str(x)
463.1221 -
463.1222 -<br><br>
463.1223 -<a href="meth:__sub__(y)">__sub__(y)</a>
463.1224 -
463.1225 -<br><br>
463.1226 - x.__sub__(y) <==> x-y
463.1227 -
463.1228 -<br><br>
463.1229 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
463.1230 -
463.1231 -<br><br>
463.1232 - Abstract classes can override this to customize issubclass().
463.1233 -
463.1234 -<br><br>
463.1235 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
463.1236 - It should return True, False or NotImplemented. If it returns
463.1237 - NotImplemented, the normal algorithm is used. Otherwise, it
463.1238 - overrides the normal algorithm (and the outcome is cached).
463.1239 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1240 -</div>
463.1241 -<a href="meth:__truediv__(y)">__truediv__(y)</a>
463.1242 - x.__truediv__(y) <==> x/y
463.1243 -
463.1244 -<br><br>
463.1245 -<a href="meth:__trunc__()">__trunc__()</a>
463.1246 -
463.1247 -<br><br>
463.1248 - Truncating an Integral returns itself.
463.1249 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1250 -</div>
463.1251 -<a href="meth:__xor__(y)">__xor__(y)</a>
463.1252 - x.__xor__(y) <==> x^y
463.1253 -
463.1254 -<br><br>
463.1255 -<a href="meth:conjugate()">conjugate()</a>
463.1256 -
463.1257 -<br><br>
463.1258 - Returns self, the complex conjugate of any int.
463.1259 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1260 -</div>
463.1261 -<a href="attr:denominator">denominator</a>
463.1262 - int(x[, base]) -> integer
463.1263 -
463.1264 -<br><br>
463.1265 - Convert a string or number to an integer, if possible. A floating point
463.1266 - argument will be truncated towards zero (this does not include a string
463.1267 - representation of a floating point number!) When converting a string, use
463.1268 - the optional base. It is an error to supply a base when converting a
463.1269 - non-string. If base is zero, the proper base is guessed based on the
463.1270 - string content. If the argument is outside the integer range a
463.1271 - long object will be returned instead.
463.1272 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1273 -</div>
463.1274 -<a href="attr:imag">imag</a>
463.1275 - int(x[, base]) -> integer
463.1276 -
463.1277 -<br><br>
463.1278 - Convert a string or number to an integer, if possible. A floating point
463.1279 - argument will be truncated towards zero (this does not include a string
463.1280 - representation of a floating point number!) When converting a string, use
463.1281 - the optional base. It is an error to supply a base when converting a
463.1282 - non-string. If base is zero, the proper base is guessed based on the
463.1283 - string content. If the argument is outside the integer range a
463.1284 - long object will be returned instead.
463.1285 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1286 -</div>
463.1287 -<a href="attr:numerator">numerator</a>
463.1288 - int(x[, base]) -> integer
463.1289 -
463.1290 -<br><br>
463.1291 - Convert a string or number to an integer, if possible. A floating point
463.1292 - argument will be truncated towards zero (this does not include a string
463.1293 - representation of a floating point number!) When converting a string, use
463.1294 - the optional base. It is an error to supply a base when converting a
463.1295 - non-string. If base is zero, the proper base is guessed based on the
463.1296 - string content. If the argument is outside the integer range a
463.1297 - long object will be returned instead.
463.1298 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1299 -</div>
463.1300 -<a href="attr:real">real</a>
463.1301 - int(x[, base]) -> integer
463.1302 -
463.1303 -<br><br>
463.1304 - Convert a string or number to an integer, if possible. A floating point
463.1305 - argument will be truncated towards zero (this does not include a string
463.1306 - representation of a floating point number!) When converting a string, use
463.1307 - the optional base. It is an error to supply a base when converting a
463.1308 - non-string. If base is zero, the proper base is guessed based on the
463.1309 - string content. If the argument is outside the integer range a
463.1310 - long object will be returned instead.
463.1311 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1312 -</div>
463.1313 -<a href="class:complex">complex</a>
463.1314 - complex(real[, imag]) -> complex number
463.1315 -
463.1316 -<br><br>
463.1317 - Create a complex number from a real part and an optional imaginary part.
463.1318 - This is equivalent to (real + imag*1j) where imag defaults to 0.
463.1319 -
463.1320 -<br><br>
463.1321 -<a href="attr:__class__">__class__</a>
463.1322 -
463.1323 -<br><br>
463.1324 - complex(real[, imag]) -> complex number
463.1325 -
463.1326 -<br><br>
463.1327 - Create a complex number from a real part and an optional imaginary part.
463.1328 - This is equivalent to (real + imag*1j) where imag defaults to 0.
463.1329 -
463.1330 -<br><br>
463.1331 -<a href="meth:__coerce__(y)">__coerce__(y)</a>
463.1332 -
463.1333 -<br><br>
463.1334 - x.__coerce__(y) <==> coerce(x, y)
463.1335 -
463.1336 -<br><br>
463.1337 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
463.1338 -
463.1339 -<br><br>
463.1340 - x.__delattr__('name') <==> del x.name
463.1341 -
463.1342 -<br><br>
463.1343 -<a href="meth:__divmod__(y)">__divmod__(y)</a>
463.1344 -
463.1345 -<br><br>
463.1346 - x.__divmod__(y) <==> divmod(x, y)
463.1347 -
463.1348 -<br><br>
463.1349 -<a href="attr:__doc__">__doc__</a>
463.1350 -
463.1351 -<br><br>
463.1352 - str(object) -> string
463.1353 -
463.1354 -<br><br>
463.1355 - Return a nice string representation of the object.
463.1356 - If the argument is a string, the return value is the same object.
463.1357 -
463.1358 -<br><br>
463.1359 -<a href="meth:__float__()">__float__()</a>
463.1360 -
463.1361 -<br><br>
463.1362 - x.__float__() <==> float(x)
463.1363 -
463.1364 -<br><br>
463.1365 -<a href="meth:__format__()">__format__()</a>
463.1366 -
463.1367 -<br><br>
463.1368 - default object formatter
463.1369 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1370 -</div>
463.1371 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
463.1372 - x.__getattribute__('name') <==> x.name
463.1373 -
463.1374 -<br><br>
463.1375 -<a href="meth:__getnewargs__()">__getnewargs__()</a>
463.1376 -
463.1377 -<br><br>
463.1378 -<a href="meth:__hash__()">__hash__()</a>
463.1379 -
463.1380 -<br><br>
463.1381 - x.__hash__() <==> hash(x)
463.1382 -
463.1383 -<br><br>
463.1384 -<a href="meth:__init__()">__init__()</a>
463.1385 -
463.1386 -<br><br>
463.1387 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
463.1388 -
463.1389 -<br><br>
463.1390 -<a href="meth:__int__()">__int__()</a>
463.1391 -
463.1392 -<br><br>
463.1393 - x.__int__() <==> int(x)
463.1394 -
463.1395 -<br><br>
463.1396 -<a href="meth:__long__()">__long__()</a>
463.1397 -
463.1398 -<br><br>
463.1399 - x.__long__() <==> long(x)
463.1400 -
463.1401 -<br><br>
463.1402 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
463.1403 -
463.1404 -<br><br>
463.1405 - T.__new__(S, ...) -> a new object with type S, a subtype of T
463.1406 -
463.1407 -<br><br>
463.1408 -<a href="meth:__nonzero__()">__nonzero__()</a>
463.1409 -
463.1410 -<br><br>
463.1411 - x.__nonzero__() <==> x != 0
463.1412 -
463.1413 -<br><br>
463.1414 -<a href="meth:__radd__(y)">__radd__(y)</a>
463.1415 -
463.1416 -<br><br>
463.1417 - x.__radd__(y) <==> y+x
463.1418 -
463.1419 -<br><br>
463.1420 -<a href="meth:__rdiv__(y)">__rdiv__(y)</a>
463.1421 -
463.1422 -<br><br>
463.1423 - x.__rdiv__(y) <==> y/x
463.1424 -
463.1425 -<br><br>
463.1426 -<a href="meth:__rdivmod__(y)">__rdivmod__(y)</a>
463.1427 -
463.1428 -<br><br>
463.1429 - x.__rdivmod__(y) <==> divmod(y, x)
463.1430 -
463.1431 -<br><br>
463.1432 -<a href="meth:__reduce__()">__reduce__()</a>
463.1433 -
463.1434 -<br><br>
463.1435 - helper for pickle
463.1436 -
463.1437 -<br><br>
463.1438 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
463.1439 -
463.1440 -<br><br>
463.1441 - helper for pickle
463.1442 -
463.1443 -<br><br>
463.1444 -<a href="meth:__repr__()">__repr__()</a>
463.1445 -
463.1446 -<br><br>
463.1447 - x.__repr__() <==> repr(x)
463.1448 -
463.1449 -<br><br>
463.1450 -<a href="meth:__rfloordiv__(y)">__rfloordiv__(y)</a>
463.1451 -
463.1452 -<br><br>
463.1453 - x.__rfloordiv__(y) <==> y//x
463.1454 -
463.1455 -<br><br>
463.1456 -<a href="meth:__rmod__(y)">__rmod__(y)</a>
463.1457 -
463.1458 -<br><br>
463.1459 - x.__rmod__(y) <==> y%x
463.1460 -
463.1461 -<br><br>
463.1462 -<a href="meth:__rmul__(y)">__rmul__(y)</a>
463.1463 -
463.1464 -<br><br>
463.1465 - x.__rmul__(y) <==> y*x
463.1466 -
463.1467 -<br><br>
463.1468 -<a href="meth:__rpow__(x)">__rpow__(x)</a>
463.1469 -
463.1470 -<br><br>
463.1471 - y.__rpow__(x[, z]) <==> pow(x, y[, z])
463.1472 -
463.1473 -<br><br>
463.1474 -<a href="meth:__rsub__(y)">__rsub__(y)</a>
463.1475 -
463.1476 -<br><br>
463.1477 - x.__rsub__(y) <==> y-x
463.1478 -
463.1479 -<br><br>
463.1480 -<a href="meth:__rtruediv__(y)">__rtruediv__(y)</a>
463.1481 -
463.1482 -<br><br>
463.1483 - x.__rtruediv__(y) <==> y/x
463.1484 -
463.1485 -<br><br>
463.1486 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
463.1487 -
463.1488 -<br><br>
463.1489 - x.__setattr__('name', value) <==> x.name = value
463.1490 -
463.1491 -<br><br>
463.1492 -<a href="meth:__sizeof__()">__sizeof__()</a>
463.1493 -
463.1494 -<br><br>
463.1495 - __sizeof__() -> size of object in memory, in bytes
463.1496 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1497 -</div>
463.1498 -<a href="meth:__str__()">__str__()</a>
463.1499 - x.__str__() <==> str(x)
463.1500 -
463.1501 -<br><br>
463.1502 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
463.1503 -
463.1504 -<br><br>
463.1505 - Abstract classes can override this to customize issubclass().
463.1506 -
463.1507 -<br><br>
463.1508 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
463.1509 - It should return True, False or NotImplemented. If it returns
463.1510 - NotImplemented, the normal algorithm is used. Otherwise, it
463.1511 - overrides the normal algorithm (and the outcome is cached).
463.1512 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1513 -</div>
463.1514 -<a href="meth:conjugate()">conjugate()</a>
463.1515 - complex.conjugate() -> complex
463.1516 -
463.1517 -<br><br>
463.1518 - Returns the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.
463.1519 -
463.1520 -<br><br>
463.1521 -<a href="attr:imag">imag</a>
463.1522 -
463.1523 -<br><br>
463.1524 - float(x) -> floating point number
463.1525 -
463.1526 -<br><br>
463.1527 - Convert a string or number to a floating point number, if possible.
463.1528 -
463.1529 -<br><br>
463.1530 -<a href="attr:real">real</a>
463.1531 -
463.1532 -<br><br>
463.1533 - float(x) -> floating point number
463.1534 -
463.1535 -<br><br>
463.1536 - Convert a string or number to a floating point number, if possible.
463.1537 -
463.1538 -<br><br>
463.1539 -<a href="class:list">list</a>
463.1540 -
463.1541 -<br><br>
463.1542 - list() -> new list
463.1543 - list(sequence) -> new list initialized from sequence's items
463.1544 -
463.1545 -<br><br>
463.1546 -<a href="attr:__class__">__class__</a>
463.1547 -
463.1548 -<br><br>
463.1549 - list() -> new list
463.1550 - list(sequence) -> new list initialized from sequence's items
463.1551 -
463.1552 -<br><br>
463.1553 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
463.1554 -
463.1555 -<br><br>
463.1556 - x.__delattr__('name') <==> del x.name
463.1557 -
463.1558 -<br><br>
463.1559 -<a href="attr:__doc__">__doc__</a>
463.1560 -
463.1561 -<br><br>
463.1562 - str(object) -> string
463.1563 -
463.1564 -<br><br>
463.1565 - Return a nice string representation of the object.
463.1566 - If the argument is a string, the return value is the same object.
463.1567 -
463.1568 -<br><br>
463.1569 -<a href="meth:__format__()">__format__()</a>
463.1570 -
463.1571 -<br><br>
463.1572 - default object formatter
463.1573 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1574 -</div>
463.1575 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
463.1576 - x.__getattribute__('name') <==> x.name
463.1577 -
463.1578 -<br><br>
463.1579 -<a href="attr:__hash__">__hash__</a>
463.1580 -
463.1581 -<br><br>
463.1582 -<a href="meth:__init__()">__init__()</a>
463.1583 -
463.1584 -<br><br>
463.1585 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
463.1586 -
463.1587 -<br><br>
463.1588 -<a href="meth:__iter__()">__iter__()</a>
463.1589 -
463.1590 -<br><br>
463.1591 - x.__iter__() <==> iter(x)
463.1592 -
463.1593 -<br><br>
463.1594 -<a href="meth:__len__()">__len__()</a>
463.1595 -
463.1596 -<br><br>
463.1597 - x.__len__() <==> len(x)
463.1598 -
463.1599 -<br><br>
463.1600 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
463.1601 -
463.1602 -<br><br>
463.1603 - T.__new__(S, ...) -> a new object with type S, a subtype of T
463.1604 -
463.1605 -<br><br>
463.1606 -<a href="meth:__reduce__()">__reduce__()</a>
463.1607 -
463.1608 -<br><br>
463.1609 - helper for pickle
463.1610 -
463.1611 -<br><br>
463.1612 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
463.1613 -
463.1614 -<br><br>
463.1615 - helper for pickle
463.1616 -
463.1617 -<br><br>
463.1618 -<a href="meth:__repr__()">__repr__()</a>
463.1619 -
463.1620 -<br><br>
463.1621 - x.__repr__() <==> repr(x)
463.1622 -
463.1623 -<br><br>
463.1624 -<a href="meth:__reversed__()">__reversed__()</a>
463.1625 -
463.1626 -<br><br>
463.1627 - L.__reversed__() -- return a reverse iterator over the list
463.1628 -
463.1629 -<br><br>
463.1630 -<a href="meth:__rmul__(n)">__rmul__(n)</a>
463.1631 -
463.1632 -<br><br>
463.1633 - x.__rmul__(n) <==> n*x
463.1634 -
463.1635 -<br><br>
463.1636 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
463.1637 -
463.1638 -<br><br>
463.1639 - x.__setattr__('name', value) <==> x.name = value
463.1640 -
463.1641 -<br><br>
463.1642 -<a href="meth:__sizeof__()">__sizeof__()</a>
463.1643 -
463.1644 -<br><br>
463.1645 - L.__sizeof__() -- size of L in memory, in bytes
463.1646 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1647 -</div>
463.1648 -<a href="meth:__str__()">__str__()</a>
463.1649 - x.__str__() <==> str(x)
463.1650 -
463.1651 -<br><br>
463.1652 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
463.1653 -
463.1654 -<br><br>
463.1655 - Abstract classes can override this to customize issubclass().
463.1656 -
463.1657 -<br><br>
463.1658 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
463.1659 - It should return True, False or NotImplemented. If it returns
463.1660 - NotImplemented, the normal algorithm is used. Otherwise, it
463.1661 - overrides the normal algorithm (and the outcome is cached).
463.1662 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1663 -</div>
463.1664 -<a href="meth:append()">append()</a>
463.1665 - L.append(object) -- append object to end
463.1666 -
463.1667 -<br><br>
463.1668 -<a href="meth:count(value)">count(value)</a>
463.1669 -
463.1670 -<br><br>
463.1671 - L.count(value) -> integer -- return number of occurrences of value
463.1672 -
463.1673 -<br><br>
463.1674 -<a href="meth:extend()">extend()</a>
463.1675 -
463.1676 -<br><br>
463.1677 - L.extend(iterable) -- extend list by appending elements from the iterable
463.1678 -
463.1679 -<br><br>
463.1680 -<a href="meth:insert()">insert()</a>
463.1681 -
463.1682 -<br><br>
463.1683 - L.insert(index, object) -- insert object before index
463.1684 -
463.1685 -<br><br>
463.1686 -<a href="meth:pop()">pop()</a>
463.1687 -
463.1688 -<br><br>
463.1689 - L.pop([index]) -> item -- remove and return item at index (default last)
463.1690 -
463.1691 -<br><br>
463.1692 -<a href="meth:remove()">remove()</a>
463.1693 -
463.1694 -<br><br>
463.1695 - L.remove(value) -- remove first occurrence of value
463.1696 -
463.1697 -<br><br>
463.1698 -<a href="meth:reverse()">reverse()</a>
463.1699 -
463.1700 -<br><br>
463.1701 - L.reverse() -- reverse *IN PLACE*
463.1702 -
463.1703 -<br><br>
463.1704 -<a href="meth:sort(cmp=None, key=None, reverse=False) __ stable sort *IN PLACE*;">sort(cmp=None, key=None, reverse=False) __ stable sort *IN PLACE*;</a>
463.1705 -cmp(x, y)
463.1706 -
463.1707 -<br><br>
463.1708 - L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
463.1709 - cmp(x, y) -> -1, 0, 1
463.1710 -
463.1711 -<br><br>
463.1712 -<a href="class:dict">dict</a>
463.1713 -
463.1714 -<br><br>
463.1715 - dict() -> new empty dictionary.
463.1716 - dict(mapping) -> new dictionary initialized from a mapping object's
463.1717 - (key, value) pairs.
463.1718 - dict(seq) -> new dictionary initialized as if via:
463.1719 - d = {}
463.1720 - for k, v in seq:
463.1721 - d[k] = v
463.1722 - dict(**kwargs) -> new dictionary initialized with the name=value pairs
463.1723 - in the keyword argument list. For example: dict(one=1, two=2)
463.1724 -
463.1725 -<br><br>
463.1726 -<a href="attr:__class__">__class__</a>
463.1727 -
463.1728 -<br><br>
463.1729 - dict() -> new empty dictionary.
463.1730 - dict(mapping) -> new dictionary initialized from a mapping object's
463.1731 - (key, value) pairs.
463.1732 - dict(seq) -> new dictionary initialized as if via:
463.1733 - d = {}
463.1734 - for k, v in seq:
463.1735 - d[k] = v
463.1736 - dict(**kwargs) -> new dictionary initialized with the name=value pairs
463.1737 - in the keyword argument list. For example: dict(one=1, two=2)
463.1738 -
463.1739 -<br><br>
463.1740 -<a href="meth:__cmp__(y)">__cmp__(y)</a>
463.1741 -
463.1742 -<br><br>
463.1743 - x.__cmp__(y) <==> cmp(x,y)
463.1744 -
463.1745 -<br><br>
463.1746 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
463.1747 -
463.1748 -<br><br>
463.1749 - x.__delattr__('name') <==> del x.name
463.1750 -
463.1751 -<br><br>
463.1752 -<a href="attr:__doc__">__doc__</a>
463.1753 -
463.1754 -<br><br>
463.1755 - str(object) -> string
463.1756 -
463.1757 -<br><br>
463.1758 - Return a nice string representation of the object.
463.1759 - If the argument is a string, the return value is the same object.
463.1760 -
463.1761 -<br><br>
463.1762 -<a href="meth:__format__()">__format__()</a>
463.1763 -
463.1764 -<br><br>
463.1765 - default object formatter
463.1766 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1767 -</div>
463.1768 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
463.1769 - x.__getattribute__('name') <==> x.name
463.1770 -
463.1771 -<br><br>
463.1772 -<a href="attr:__hash__">__hash__</a>
463.1773 -
463.1774 -<br><br>
463.1775 -<a href="meth:__iter__()">__iter__()</a>
463.1776 -
463.1777 -<br><br>
463.1778 - x.__iter__() <==> iter(x)
463.1779 -
463.1780 -<br><br>
463.1781 -<a href="meth:__len__()">__len__()</a>
463.1782 -
463.1783 -<br><br>
463.1784 - x.__len__() <==> len(x)
463.1785 -
463.1786 -<br><br>
463.1787 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
463.1788 -
463.1789 -<br><br>
463.1790 - T.__new__(S, ...) -> a new object with type S, a subtype of T
463.1791 -
463.1792 -<br><br>
463.1793 -<a href="meth:__reduce__()">__reduce__()</a>
463.1794 -
463.1795 -<br><br>
463.1796 - helper for pickle
463.1797 -
463.1798 -<br><br>
463.1799 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
463.1800 -
463.1801 -<br><br>
463.1802 - helper for pickle
463.1803 -
463.1804 -<br><br>
463.1805 -<a href="meth:__repr__()">__repr__()</a>
463.1806 -
463.1807 -<br><br>
463.1808 - x.__repr__() <==> repr(x)
463.1809 -
463.1810 -<br><br>
463.1811 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
463.1812 -
463.1813 -<br><br>
463.1814 - x.__setattr__('name', value) <==> x.name = value
463.1815 -
463.1816 -<br><br>
463.1817 -<a href="meth:__sizeof__()">__sizeof__()</a>
463.1818 -
463.1819 -<br><br>
463.1820 - D.__sizeof__() -> size of D in memory, in bytes
463.1821 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1822 -</div>
463.1823 -<a href="meth:__str__()">__str__()</a>
463.1824 - x.__str__() <==> str(x)
463.1825 -
463.1826 -<br><br>
463.1827 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
463.1828 -
463.1829 -<br><br>
463.1830 - Abstract classes can override this to customize issubclass().
463.1831 -
463.1832 -<br><br>
463.1833 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
463.1834 - It should return True, False or NotImplemented. If it returns
463.1835 - NotImplemented, the normal algorithm is used. Otherwise, it
463.1836 - overrides the normal algorithm (and the outcome is cached).
463.1837 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1838 -</div>
463.1839 -<a href="class:tuple">tuple</a>
463.1840 - tuple() -> an empty tuple
463.1841 - tuple(sequence) -> tuple initialized from sequence's items
463.1842 -
463.1843 -<br><br>
463.1844 - If the argument is a tuple, the return value is the same object.
463.1845 -
463.1846 -<br><br>
463.1847 -<a href="attr:__class__">__class__</a>
463.1848 -
463.1849 -<br><br>
463.1850 - tuple() -> an empty tuple
463.1851 - tuple(sequence) -> tuple initialized from sequence's items
463.1852 -
463.1853 -<br><br>
463.1854 - If the argument is a tuple, the return value is the same object.
463.1855 -
463.1856 -<br><br>
463.1857 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
463.1858 -
463.1859 -<br><br>
463.1860 - x.__delattr__('name') <==> del x.name
463.1861 -
463.1862 -<br><br>
463.1863 -<a href="attr:__doc__">__doc__</a>
463.1864 -
463.1865 -<br><br>
463.1866 - str(object) -> string
463.1867 -
463.1868 -<br><br>
463.1869 - Return a nice string representation of the object.
463.1870 - If the argument is a string, the return value is the same object.
463.1871 -
463.1872 -<br><br>
463.1873 -<a href="meth:__format__()">__format__()</a>
463.1874 -
463.1875 -<br><br>
463.1876 - default object formatter
463.1877 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1878 -</div>
463.1879 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
463.1880 - x.__getattribute__('name') <==> x.name
463.1881 -
463.1882 -<br><br>
463.1883 -<a href="meth:__getnewargs__()">__getnewargs__()</a>
463.1884 -
463.1885 -<br><br>
463.1886 -<a href="meth:__hash__()">__hash__()</a>
463.1887 -
463.1888 -<br><br>
463.1889 - x.__hash__() <==> hash(x)
463.1890 -
463.1891 -<br><br>
463.1892 -<a href="meth:__init__()">__init__()</a>
463.1893 -
463.1894 -<br><br>
463.1895 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
463.1896 -
463.1897 -<br><br>
463.1898 -<a href="meth:__iter__()">__iter__()</a>
463.1899 -
463.1900 -<br><br>
463.1901 - x.__iter__() <==> iter(x)
463.1902 -
463.1903 -<br><br>
463.1904 -<a href="meth:__len__()">__len__()</a>
463.1905 -
463.1906 -<br><br>
463.1907 - x.__len__() <==> len(x)
463.1908 -
463.1909 -<br><br>
463.1910 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
463.1911 -
463.1912 -<br><br>
463.1913 - T.__new__(S, ...) -> a new object with type S, a subtype of T
463.1914 -
463.1915 -<br><br>
463.1916 -<a href="meth:__reduce__()">__reduce__()</a>
463.1917 -
463.1918 -<br><br>
463.1919 - helper for pickle
463.1920 -
463.1921 -<br><br>
463.1922 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
463.1923 -
463.1924 -<br><br>
463.1925 - helper for pickle
463.1926 -
463.1927 -<br><br>
463.1928 -<a href="meth:__repr__()">__repr__()</a>
463.1929 -
463.1930 -<br><br>
463.1931 - x.__repr__() <==> repr(x)
463.1932 -
463.1933 -<br><br>
463.1934 -<a href="meth:__rmul__(n)">__rmul__(n)</a>
463.1935 -
463.1936 -<br><br>
463.1937 - x.__rmul__(n) <==> n*x
463.1938 -
463.1939 -<br><br>
463.1940 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
463.1941 -
463.1942 -<br><br>
463.1943 - x.__setattr__('name', value) <==> x.name = value
463.1944 -
463.1945 -<br><br>
463.1946 -<a href="meth:__sizeof__()">__sizeof__()</a>
463.1947 -
463.1948 -<br><br>
463.1949 - T.__sizeof__() -- size of T in memory, in bytes
463.1950 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1951 -</div>
463.1952 -<a href="meth:__str__()">__str__()</a>
463.1953 - x.__str__() <==> str(x)
463.1954 -
463.1955 -<br><br>
463.1956 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
463.1957 -
463.1958 -<br><br>
463.1959 - Abstract classes can override this to customize issubclass().
463.1960 -
463.1961 -<br><br>
463.1962 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
463.1963 - It should return True, False or NotImplemented. If it returns
463.1964 - NotImplemented, the normal algorithm is used. Otherwise, it
463.1965 - overrides the normal algorithm (and the outcome is cached).
463.1966 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1967 -</div>
463.1968 -<a href="meth:count(value)">count(value)</a>
463.1969 - T.count(value) -> integer -- return number of occurrences of value
463.1970 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.1971 -</div>
463.1972 -<a href="class:str">str</a>
463.1973 - str(object) -> string
463.1974 -
463.1975 -<br><br>
463.1976 - Return a nice string representation of the object.
463.1977 - If the argument is a string, the return value is the same object.
463.1978 -
463.1979 -<br><br>
463.1980 -<a href="attr:__class__">__class__</a>
463.1981 -
463.1982 -<br><br>
463.1983 - str(object) -> string
463.1984 -
463.1985 -<br><br>
463.1986 - Return a nice string representation of the object.
463.1987 - If the argument is a string, the return value is the same object.
463.1988 -
463.1989 -<br><br>
463.1990 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
463.1991 -
463.1992 -<br><br>
463.1993 - x.__delattr__('name') <==> del x.name
463.1994 -
463.1995 -<br><br>
463.1996 -<a href="attr:__doc__">__doc__</a>
463.1997 -
463.1998 -<br><br>
463.1999 - str(object) -> string
463.2000 -
463.2001 -<br><br>
463.2002 - Return a nice string representation of the object.
463.2003 - If the argument is a string, the return value is the same object.
463.2004 -
463.2005 -<br><br>
463.2006 -<a href="meth:__format__(format_spec)">__format__(format_spec)</a>
463.2007 -
463.2008 -<br><br>
463.2009 - S.__format__(format_spec) -> unicode
463.2010 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.2011 -</div>
463.2012 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
463.2013 - x.__getattribute__('name') <==> x.name
463.2014 -
463.2015 -<br><br>
463.2016 -<a href="meth:__getnewargs__()">__getnewargs__()</a>
463.2017 -
463.2018 -<br><br>
463.2019 -<a href="meth:__hash__()">__hash__()</a>
463.2020 -
463.2021 -<br><br>
463.2022 - x.__hash__() <==> hash(x)
463.2023 -
463.2024 -<br><br>
463.2025 -<a href="meth:__init__()">__init__()</a>
463.2026 -
463.2027 -<br><br>
463.2028 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
463.2029 -
463.2030 -<br><br>
463.2031 -<a href="meth:__len__()">__len__()</a>
463.2032 -
463.2033 -<br><br>
463.2034 - x.__len__() <==> len(x)
463.2035 -
463.2036 -<br><br>
463.2037 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
463.2038 -
463.2039 -<br><br>
463.2040 - T.__new__(S, ...) -> a new object with type S, a subtype of T
463.2041 -
463.2042 -<br><br>
463.2043 -<a href="meth:__reduce__()">__reduce__()</a>
463.2044 -
463.2045 -<br><br>
463.2046 - helper for pickle
463.2047 -
463.2048 -<br><br>
463.2049 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
463.2050 -
463.2051 -<br><br>
463.2052 - helper for pickle
463.2053 -
463.2054 -<br><br>
463.2055 -<a href="meth:__repr__()">__repr__()</a>
463.2056 -
463.2057 -<br><br>
463.2058 - x.__repr__() <==> repr(x)
463.2059 -
463.2060 -<br><br>
463.2061 -<a href="meth:__rmod__(y)">__rmod__(y)</a>
463.2062 -
463.2063 -<br><br>
463.2064 - x.__rmod__(y) <==> y%x
463.2065 -
463.2066 -<br><br>
463.2067 -<a href="meth:__rmul__(n)">__rmul__(n)</a>
463.2068 -
463.2069 -<br><br>
463.2070 - x.__rmul__(n) <==> n*x
463.2071 -
463.2072 -<br><br>
463.2073 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
463.2074 -
463.2075 -<br><br>
463.2076 - x.__setattr__('name', value) <==> x.name = value
463.2077 -
463.2078 -<br><br>
463.2079 -<a href="meth:__sizeof__()">__sizeof__()</a>
463.2080 -
463.2081 -<br><br>
463.2082 - S.__sizeof__() -> size of S in memory, in bytes
463.2083 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.2084 -</div>
463.2085 -<a href="meth:__str__()">__str__()</a>
463.2086 - x.__str__() <==> str(x)
463.2087 -
463.2088 -<br><br>
463.2089 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
463.2090 -
463.2091 -<br><br>
463.2092 - Abstract classes can override this to customize issubclass().
463.2093 -
463.2094 -<br><br>
463.2095 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
463.2096 - It should return True, False or NotImplemented. If it returns
463.2097 - NotImplemented, the normal algorithm is used. Otherwise, it
463.2098 - overrides the normal algorithm (and the outcome is cached).
463.2099 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.2100 -</div>
463.2101 -<a href="meth:_formatter_field_name_split()">_formatter_field_name_split()</a>
463.2102 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.2103 -</div>
463.2104 -<a href="meth:_formatter_parser()">_formatter_parser()</a>
463.2105 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.2106 -</div>
463.2107 -<a href="class:unicode">unicode</a>
463.2108 - unicode(string [, encoding[, errors]]) -> object
463.2109 -
463.2110 -<br><br>
463.2111 - Create a new Unicode object from the given encoded string.
463.2112 - encoding defaults to the current default string encoding.
463.2113 - errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.
463.2114 -
463.2115 -<br><br>
463.2116 -<a href="attr:__class__">__class__</a>
463.2117 -
463.2118 -<br><br>
463.2119 - unicode(string [, encoding[, errors]]) -> object
463.2120 -
463.2121 -<br><br>
463.2122 - Create a new Unicode object from the given encoded string.
463.2123 - encoding defaults to the current default string encoding.
463.2124 - errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.
463.2125 -
463.2126 -<br><br>
463.2127 -<a href="meth:__delattr__(name)">__delattr__(name)</a>
463.2128 -
463.2129 -<br><br>
463.2130 - x.__delattr__('name') <==> del x.name
463.2131 -
463.2132 -<br><br>
463.2133 -<a href="attr:__doc__">__doc__</a>
463.2134 -
463.2135 -<br><br>
463.2136 - str(object) -> string
463.2137 -
463.2138 -<br><br>
463.2139 - Return a nice string representation of the object.
463.2140 - If the argument is a string, the return value is the same object.
463.2141 -
463.2142 -<br><br>
463.2143 -<a href="meth:__format__(format_spec)">__format__(format_spec)</a>
463.2144 -
463.2145 -<br><br>
463.2146 - S.__format__(format_spec) -> unicode
463.2147 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.2148 -</div>
463.2149 -<a href="meth:__getattribute__(name)">__getattribute__(name)</a>
463.2150 - x.__getattribute__('name') <==> x.name
463.2151 -
463.2152 -<br><br>
463.2153 -<a href="meth:__getnewargs__()">__getnewargs__()</a>
463.2154 -
463.2155 -<br><br>
463.2156 -<a href="meth:__hash__()">__hash__()</a>
463.2157 -
463.2158 -<br><br>
463.2159 - x.__hash__() <==> hash(x)
463.2160 -
463.2161 -<br><br>
463.2162 -<a href="meth:__init__()">__init__()</a>
463.2163 -
463.2164 -<br><br>
463.2165 - x.__init__(...) initializes x; see x.__class__.__doc__ for signature
463.2166 -
463.2167 -<br><br>
463.2168 -<a href="meth:__len__()">__len__()</a>
463.2169 -
463.2170 -<br><br>
463.2171 - x.__len__() <==> len(x)
463.2172 -
463.2173 -<br><br>
463.2174 -<a href="meth:__new__(S, ___)">__new__(S, ___)</a>
463.2175 -
463.2176 -<br><br>
463.2177 - T.__new__(S, ...) -> a new object with type S, a subtype of T
463.2178 -
463.2179 -<br><br>
463.2180 -<a href="meth:__reduce__()">__reduce__()</a>
463.2181 -
463.2182 -<br><br>
463.2183 - helper for pickle
463.2184 -
463.2185 -<br><br>
463.2186 -<a href="meth:__reduce_ex__()">__reduce_ex__()</a>
463.2187 -
463.2188 -<br><br>
463.2189 - helper for pickle
463.2190 -
463.2191 -<br><br>
463.2192 -<a href="meth:__repr__()">__repr__()</a>
463.2193 -
463.2194 -<br><br>
463.2195 - x.__repr__() <==> repr(x)
463.2196 -
463.2197 -<br><br>
463.2198 -<a href="meth:__rmod__(y)">__rmod__(y)</a>
463.2199 -
463.2200 -<br><br>
463.2201 - x.__rmod__(y) <==> y%x
463.2202 -
463.2203 -<br><br>
463.2204 -<a href="meth:__rmul__(n)">__rmul__(n)</a>
463.2205 -
463.2206 -<br><br>
463.2207 - x.__rmul__(n) <==> n*x
463.2208 -
463.2209 -<br><br>
463.2210 -<a href="meth:__setattr__(name, value)">__setattr__(name, value)</a>
463.2211 -
463.2212 -<br><br>
463.2213 - x.__setattr__('name', value) <==> x.name = value
463.2214 -
463.2215 -<br><br>
463.2216 -<a href="meth:__sizeof__()">__sizeof__()</a>
463.2217 -
463.2218 -<br><br>
463.2219 - S.__sizeof__() -> size of S in memory, in bytes
463.2220 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.2221 -</div>
463.2222 -<a href="meth:__str__()">__str__()</a>
463.2223 - x.__str__() <==> str(x)
463.2224 -
463.2225 -<br><br>
463.2226 -<a href="meth:__subclasshook__()">__subclasshook__()</a>
463.2227 -
463.2228 -<br><br>
463.2229 - Abstract classes can override this to customize issubclass().
463.2230 -
463.2231 -<br><br>
463.2232 - This is invoked early on by abc.ABCMeta.__subclasscheck__().
463.2233 - It should return True, False or NotImplemented. If it returns
463.2234 - NotImplemented, the normal algorithm is used. Otherwise, it
463.2235 - overrides the normal algorithm (and the outcome is cached).
463.2236 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.2237 -</div>
463.2238 -<a href="meth:_formatter_field_name_split()">_formatter_field_name_split()</a>
463.2239 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.2240 -</div>
463.2241 -<a href="meth:_formatter_parser()">_formatter_parser()</a>
463.2242 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.2243 -</div>
463.2244 -<a href="meth:capitalize()">capitalize()</a>
463.2245 - S.capitalize() -> unicode
463.2246 -
463.2247 -<br><br>
463.2248 - Return a capitalized version of S, i.e. make the first character
463.2249 - have upper case.
463.2250 -
463.2251 -<br><br>
463.2252 -<a href="meth:center(width)">center(width)</a>
463.2253 -
463.2254 -<br><br>
463.2255 - S.center(width[, fillchar]) -> unicode
463.2256 -
463.2257 -<br><br>
463.2258 - Return S centered in a Unicode string of length width. Padding is
463.2259 - done using the specified fill character (default is a space)
463.2260 -
463.2261 -<br><br>
463.2262 -<a href="meth:count(sub)">count(sub)</a>
463.2263 -
463.2264 -<br><br>
463.2265 - S.count(sub[, start[, end]]) -> int
463.2266 -
463.2267 -<br><br>
463.2268 - Return the number of non-overlapping occurrences of substring sub in
463.2269 - Unicode string S[start:end]. Optional arguments start and end are
463.2270 - interpreted as in slice notation.
463.2271 -
463.2272 -<br><br>
463.2273 -<a href="meth:decode()">decode()</a>
463.2274 -
463.2275 -<br><br>
463.2276 - S.decode([encoding[,errors]]) -> string or unicode
463.2277 -
463.2278 -<br><br>
463.2279 - Decodes S using the codec registered for encoding. encoding defaults
463.2280 - to the default encoding. errors may be given to set a different error
463.2281 - handling scheme. Default is 'strict' meaning that encoding errors raise
463.2282 - a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
463.2283 - as well as any other name registerd with codecs.register_error that is
463.2284 - able to handle UnicodeDecodeErrors.
463.2285 -
463.2286 -<br><br>
463.2287 -<a href="meth:encode()">encode()</a>
463.2288 -
463.2289 -<br><br>
463.2290 - S.encode([encoding[,errors]]) -> string or unicode
463.2291 -
463.2292 -<br><br>
463.2293 - Encodes S using the codec registered for encoding. encoding defaults
463.2294 - to the default encoding. errors may be given to set a different error
463.2295 - handling scheme. Default is 'strict' meaning that encoding errors raise
463.2296 - a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
463.2297 - 'xmlcharrefreplace' as well as any other name registered with
463.2298 - codecs.register_error that can handle UnicodeEncodeErrors.
463.2299 -
463.2300 -<br><br>
463.2301 -<a href="meth:endswith(suffix)">endswith(suffix)</a>
463.2302 -
463.2303 -<br><br>
463.2304 - S.endswith(suffix[, start[, end]]) -> bool
463.2305 -
463.2306 -<br><br>
463.2307 - Return True if S ends with the specified suffix, False otherwise.
463.2308 - With optional start, test S beginning at that position.
463.2309 - With optional end, stop comparing S at that position.
463.2310 - suffix can also be a tuple of strings to try.
463.2311 -
463.2312 -<br><br>
463.2313 -<a href="meth:expandtabs()">expandtabs()</a>
463.2314 -
463.2315 -<br><br>
463.2316 - S.expandtabs([tabsize]) -> unicode
463.2317 -
463.2318 -<br><br>
463.2319 - Return a copy of S where all tab characters are expanded using spaces.
463.2320 - If tabsize is not given, a tab size of 8 characters is assumed.
463.2321 -
463.2322 -<br><br>
463.2323 -<a href="meth:find(sub )">find(sub )</a>
463.2324 -
463.2325 -<br><br>
463.2326 - S.find(sub [,start [,end]]) -> int
463.2327 -
463.2328 -<br><br>
463.2329 - Return the lowest index in S where substring sub is found,
463.2330 - such that sub is contained within s[start:end]. Optional
463.2331 - arguments start and end are interpreted as in slice notation.
463.2332 -
463.2333 -<br><br>
463.2334 - Return -1 on failure.
463.2335 -
463.2336 -<br><br>
463.2337 -<a href="meth:format(*args, **kwargs)">format(*args, **kwargs)</a>
463.2338 -
463.2339 -<br><br>
463.2340 - S.format(*args, **kwargs) -> unicode
463.2341 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
463.2342 -</div>
463.2343 -<a href="meth:isalnum()">isalnum()</a>
463.2344 - S.isalnum() -> bool
463.2345 -
463.2346 -<br><br>
463.2347 - Return True if all characters in S are alphanumeric
463.2348 - and there is at least one character in S, False otherwise.
463.2349 -
463.2350 -<br><br>
463.2351 -<a href="meth:isalpha()">isalpha()</a>
463.2352 -
463.2353 -<br><br>
463.2354 - S.isalpha() -> bool
463.2355 -
463.2356 -<br><br>
463.2357 - Return True if all characters in S are alphabetic
463.2358 - and there is at least one character in S, False otherwise.
463.2359 -
463.2360 -<br><br>
463.2361 -<a href="meth:isdigit()">isdigit()</a>
463.2362 -
463.2363 -<br><br>
463.2364 - S.isdigit() -> bool
463.2365 -
463.2366 -<br><br>
463.2367 - Return True if all characters in S are digits
463.2368 - and there is at least one character in S, False otherwise.
463.2369 -
463.2370 -<br><br>
463.2371 -<a href="meth:islower()">islower()</a>
463.2372 -
463.2373 -<br><br>
463.2374 - S.islower() -> bool
463.2375 -
463.2376 -<br><br>
463.2377 - Return True if all cased characters in S are lowercase and there is
463.2378 - at least one cased character in S, False otherwise.
463.2379 -
463.2380 -<br><br>
463.2381 -<a href="meth:isspace()">isspace()</a>
463.2382 -
463.2383 -<br><br>
463.2384 - S.isspace() -> bool
463.2385 -
463.2386 -<br><br>
463.2387 - Return True if all characters in S are whitespace
463.2388 - and there is at least one character in S, False otherwise.
463.2389 -
463.2390 -<br><br>
463.2391 -<a href="meth:istitle()">istitle()</a>
463.2392 -
463.2393 -<br><br>
463.2394 - S.istitle() -> bool
463.2395 -
463.2396 -<br><br>
463.2397 - Return True if S is a titlecased string and there is at least one
463.2398 - character in S, i.e. upper- and titlecase characters may only
463.2399 - follow uncased characters and lowercase characters only cased ones.
463.2400 - Return False otherwise.
463.2401 -
463.2402 -<br><br>
463.2403 -<a href="meth:isupper()">isupper()</a>
463.2404 -
463.2405 -<br><br>
463.2406 - S.isupper() -> bool
463.2407 -
463.2408 -<br><br>
463.2409 - Return True if all cased characters in S are uppercase and there is
463.2410 - at least one cased character in S, False otherwise.
463.2411 -
463.2412 -<br><br>
463.2413 -<a href="meth:join(sequence)">join(sequence)</a>
463.2414 -
463.2415 -<br><br>
463.2416 - S.join(sequence) -> unicode
463.2417 -
463.2418 -<br><br>
463.2419 - Return a string which is the concatenation of the strings in the
463.2420 - sequence. The separator between elements is S.
463.2421 -
463.2422 -<br><br>
463.2423 -<a href="meth:ljust(width)">ljust(width)</a>
463.2424 -
463.2425 -<br><br>
463.2426 - S.ljust(width[, fillchar]) -> int
463.2427 -
463.2428 -<br><br>
463.2429 - Return S left justified in a Unicode string of length width. Padding is
463.2430 - done using the specified fill character (default is a space).
463.2431 -
463.2432 -<br><br>
463.2433 -<a href="meth:lower()">lower()</a>
463.2434 -
463.2435 -<br><br>
463.2436 - S.lower() -> unicode
463.2437 -
463.2438 -<br><br>
463.2439 - Return a copy of the string S converted to lowercase.
463.2440 -
463.2441 -<br><br>
463.2442 -<a href="meth:lstrip()">lstrip()</a>
463.2443 -
463.2444 -<br><br>
463.2445 - S.lstrip([chars]) -> unicode
463.2446 -
463.2447 -<br><br>
463.2448 - Return a copy of the string S with leading whitespace removed.
463.2449 - If chars is given and not None, remove characters in chars instead.
463.2450 - If chars is a str, it will be converted to unicode before stripping
463.2451 -
463.2452 -<br><br>
463.2453 -<a href="meth:partition(sep)">partition(sep)</a>
463.2454 -
463.2455 -<br><br>
463.2456 - S.partition(sep) -> (head, sep, tail)
463.2457 -
463.2458 -<br><br>
463.2459 - Searches for the separator sep in S, and returns the part before it,
463.2460 - the separator itself, and the part after it. If the separator is not
463.2461 - found, returns S and two empty strings.
463.2462 -
463.2463 -<br><br>
463.2464 -<a href="meth:replace(old, new)">replace(old, new)</a>
463.2465 -
463.2466 -<br><br>
463.2467 - S.replace (old, new[, count]) -> unicode
463.2468 -
463.2469 -<br><br>
463.2470 - Return a copy of S with all occurrences of substring
463.2471 - old replaced by new. If the optional argument count is
463.2472 - given, only the first count occurrences are replaced.
463.2473 -
463.2474 -<br><br>
463.2475 -<a href="meth:rfind(sub )">rfind(sub )</a>
463.2476 -
463.2477 -<br><br>
463.2478 - S.rfind(sub [,start [,end]]) -> int
463.2479 -
463.2480 -<br><br>
463.2481 - Return the highest index in S where substring sub is found,
463.2482 - such that sub is contained within s[start:end]. Optional
463.2483 - arguments start and end are interpreted as in slice notation.
463.2484 -
463.2485 -<br><br>
463.2486 - Return -1 on failure.
463.2487 -
463.2488 -<br><br>
463.2489 -<a href="meth:rindex(sub )">rindex(sub )</a>
463.2490 -
463.2491 -<br><br>
463.2492 - S.rindex(sub [,start [,end]]) -> int
463.2493 -
463.2494 -<br><br>
463.2495 - Like S.rfind() but raise ValueError when the substring is not found.
463.2496 -
463.2497 -<br><br>
463.2498 -<a href="meth:rjust(width)">rjust(width)</a>
463.2499 -
463.2500 -<br><br>
463.2501 - S.rjust(width[, fillchar]) -> unicode
463.2502 -
463.2503 -<br><br>
463.2504 - Return S right justified in a Unicode string of length width. Padding is
463.2505 - done using the specified fill character (default is a space).
463.2506 -
463.2507 -<br><br>
463.2508 -<a href="meth:rpartition(sep)">rpartition(sep)</a>
463.2509 -
463.2510 -<br><br>
463.2511 - S.rpartition(sep) -> (tail, sep, head)
463.2512 -
463.2513 -<br><br>
463.2514 - Searches for the separator sep in S, starting at the end of S, and returns
463.2515 - the part before it, the separator itself, and the part after it. If the
463.2516 - separator is not found, returns two empty strings and S.
463.2517 -
463.2518 -<br><br>
463.2519 -<a href="meth:rsplit()">rsplit()</a>
463.2520 -
463.2521 -<br><br>
463.2522 - S.rsplit([sep [,maxsplit]]) -> list of strings
463.2523 -
463.2524 -<br><br>
463.2525 - Return a list of the words in S, using sep as the
463.2526 - delimiter string, starting at the end of the string and
463.2527 - working to the front. If maxsplit is given, at most maxsplit
463.2528 - splits are done. If sep is not specified, any whitespace string
463.2529 - is a separator.
463.2530 -
463.2531 -<br><br>
463.2532 -<a href="meth:rstrip()">rstrip()</a>
463.2533 -
463.2534 -<br><br>
463.2535 - S.rstrip([chars]) -> unicode
463.2536 -
463.2537 -<br><br>
463.2538 - Return a copy of the string S with trailing whitespace removed.
463.2539 - If chars is given and not None, remove characters in chars instead.
463.2540 - If chars is a str, it will be converted to unicode before stripping
463.2541 -
463.2542 -<br><br>
463.2543 -<a href="meth:split()">split()</a>
463.2544 -
463.2545 -<br><br>
463.2546 - S.split([sep [,maxsplit]]) -> list of strings
463.2547 -
463.2548 -<br><br>
463.2549 - Return a list of the words in S, using sep as the
463.2550 - delimiter string. If maxsplit is given, at most maxsplit
463.2551 - splits are done. If sep is not specified or is None, any
463.2552 - whitespace string is a separator and empty strings are
463.2553 - removed from the result.
463.2554 -
463.2555 -<br><br>
463.2556 -<a href="meth:splitlines()">splitlines()</a>
463.2557 -
463.2558 -<br><br>
463.2559 - S.splitlines([keepends]]) -> list of strings
463.2560 -
463.2561 -<br><br>
463.2562 - Return a list of the lines in S, breaking at line boundaries.
463.2563 - Line breaks are not included in the resulting list unless keepends
463.2564 - is given and true.
463.2565 -
463.2566 -<br><br>
463.2567 -<a href="meth:startswith(prefix)">startswith(prefix)</a>
463.2568 -
463.2569 -<br><br>
463.2570 - S.startswith(prefix[, start[, end]]) -> bool
463.2571 -
463.2572 -<br><br>
463.2573 - Return True if S starts with the specified prefix, False otherwise.
463.2574 - With optional start, test S beginning at that position.
463.2575 - With optional end, stop comparing S at that position.
463.2576 - prefix can also be a tuple of strings to try.
463.2577 -
463.2578 -<br><br>
463.2579 -<a href="meth:strip()">strip()</a>
463.2580 -
463.2581 -<br><br>
463.2582 - S.strip([chars]) -> unicode
463.2583 -
463.2584 -<br><br>
463.2585 - Return a copy of the string S with leading and trailing
463.2586 - whitespace removed.
463.2587 - If chars is given and not None, remove characters in chars instead.
463.2588 - If chars is a str, it will be converted to unicode before stripping
463.2589 -
463.2590 -<br><br>
463.2591 -<a href="meth:swapcase()">swapcase()</a>
463.2592 -
463.2593 -<br><br>
463.2594 - S.swapcase() -> unicode
463.2595 -
463.2596 -<br><br>
463.2597 - Return a copy of S with uppercase characters converted to lowercase
463.2598 - and vice versa.
463.2599 -
463.2600 -<br><br>
463.2601 -<a href="meth:title()">title()</a>
463.2602 -
463.2603 -<br><br>
463.2604 - S.title() -> unicode
463.2605 -
463.2606 -<br><br>
463.2607 - Return a titlecased version of S, i.e. words start with title case
463.2608 - characters, all remaining cased characters have lower case.
463.2609 -
463.2610 -<br><br>
463.2611 -<a href="meth:translate(table)">translate(table)</a>
463.2612 -
463.2613 -<br><br>
463.2614 - S.translate(table) -> unicode
463.2615 -
463.2616 -<br><br>
463.2617 - Return a copy of the string S, where all characters have been mapped
463.2618 - through the given translation table, which must be a mapping of
463.2619 - Unicode ordinals to Unicode ordinals, Unicode strings or None.
463.2620 - Unmapped characters are left untouched. Characters mapped to None
463.2621 - are deleted.
463.2622 -
463.2623 -<br><br>
463.2624 -<a href="meth:upper()">upper()</a>
463.2625 -
463.2626 -<br><br>
463.2627 - S.upper() -> unicode
463.2628 -
463.2629 -<br><br>
463.2630 - Return a copy of S converted to uppercase.
463.2631 -
463.2632 -<br><br>
463.2633 -<a href="meth:zfill(width)">zfill(width)</a>
463.2634 -
463.2635 -<br><br>
463.2636 - S.zfill(width) -> unicode
463.2637 -
463.2638 -<br><br>
463.2639 - Pad a numeric string S with zeros on the left, to fill a field
463.2640 - of the specified width. The string S is never truncated.
463.2641 -</body></html>
464.1 --- a/python.editor/test/unit/data/testfiles/rst/stub_missing.rst.indexed Sun Jan 04 13:11:53 2015 -0600
464.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
464.3 @@ -1,486 +0,0 @@
464.4 -
464.5 -
464.6 -Document 0
464.7 -Searchable Keys:
464.8 - class : bool
464.9 - class-ig : bool
464.10 - in : stub_missing
464.11 - member : __abs__;F;|DOCUMENTED|DOC_ONLY|;;
464.12 - member : __add__;F;|DOCUMENTED|DOC_ONLY|;y;
464.13 - member : __and__;F;|DOCUMENTED|DOC_ONLY|;y;
464.14 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
464.15 - member : __cmp__;F;|DOCUMENTED|DOC_ONLY|;y;
464.16 - member : __coerce__;F;|DOCUMENTED|DOC_ONLY|;y;
464.17 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
464.18 - member : __div__;F;|DOCUMENTED|DOC_ONLY|;y;
464.19 - member : __divmod__;F;|DOCUMENTED|DOC_ONLY|;y;
464.20 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
464.21 - member : __float__;F;|DOCUMENTED|DOC_ONLY|;;
464.22 - member : __floordiv__;F;|DOCUMENTED|DOC_ONLY|;y;
464.23 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;;
464.24 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
464.25 - member : __getnewargs__;F;|DOCUMENTED|DOC_ONLY|;;
464.26 - member : __hash__;F;|DOCUMENTED|DOC_ONLY|;;
464.27 - member : __hex__;F;|DOCUMENTED|DOC_ONLY|;;
464.28 - member : __index__;F;|DOCUMENTED|DOC_ONLY|;;
464.29 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
464.30 - member : __int__;F;|DOCUMENTED|DOC_ONLY|;;
464.31 - member : __invert__;F;|DOCUMENTED|DOC_ONLY|;;
464.32 - member : __long__;F;|DOCUMENTED|DOC_ONLY|;;
464.33 - member : __lshift__;F;|DOCUMENTED|DOC_ONLY|;y;
464.34 - member : __mod__;F;|DOCUMENTED|DOC_ONLY|;y;
464.35 - member : __mul__;F;|DOCUMENTED|DOC_ONLY|;y;
464.36 - member : __neg__;F;|DOCUMENTED|DOC_ONLY|;;
464.37 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
464.38 - member : __nonzero__;F;|DOCUMENTED|DOC_ONLY|;;
464.39 - member : __oct__;F;|DOCUMENTED|DOC_ONLY|;;
464.40 - member : __or__;F;|DOCUMENTED|DOC_ONLY|;y;
464.41 - member : __pos__;F;|DOCUMENTED|DOC_ONLY|;;
464.42 - member : __pow__;F;|DOCUMENTED|DOC_ONLY|;y;
464.43 - member : __radd__;F;|DOCUMENTED|DOC_ONLY|;y;
464.44 - member : __rand__;F;|DOCUMENTED|DOC_ONLY|;y;
464.45 - member : __rdiv__;F;|DOCUMENTED|DOC_ONLY|;y;
464.46 - member : __rdivmod__;F;|DOCUMENTED|DOC_ONLY|;y;
464.47 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
464.48 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
464.49 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
464.50 - member : __rfloordiv__;F;|DOCUMENTED|DOC_ONLY|;y;
464.51 - member : __rlshift__;F;|DOCUMENTED|DOC_ONLY|;y;
464.52 - member : __rmod__;F;|DOCUMENTED|DOC_ONLY|;y;
464.53 - member : __rmul__;F;|DOCUMENTED|DOC_ONLY|;y;
464.54 - member : __ror__;F;|DOCUMENTED|DOC_ONLY|;y;
464.55 - member : __rpow__;F;|DOCUMENTED|DOC_ONLY|;x;
464.56 - member : __rrshift__;F;|DOCUMENTED|DOC_ONLY|;y;
464.57 - member : __rshift__;F;|DOCUMENTED|DOC_ONLY|;y;
464.58 - member : __rsub__;F;|DOCUMENTED|DOC_ONLY|;y;
464.59 - member : __rtruediv__;F;|DOCUMENTED|DOC_ONLY|;y;
464.60 - member : __rxor__;F;|DOCUMENTED|DOC_ONLY|;y;
464.61 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
464.62 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
464.63 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
464.64 - member : __sub__;F;|DOCUMENTED|DOC_ONLY|;y;
464.65 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
464.66 - member : __truediv__;F;|DOCUMENTED|DOC_ONLY|;y;
464.67 - member : __trunc__;F;|DOCUMENTED|DOC_ONLY|;;
464.68 - member : __xor__;F;|DOCUMENTED|DOC_ONLY|;y;
464.69 - member : conjugate;F;|DOCUMENTED|DOC_ONLY|;;
464.70 - member : denominator;A;|DOCUMENTED|DOC_ONLY|;
464.71 - member : imag;A;|DOCUMENTED|DOC_ONLY|;
464.72 - member : numerator;A;|DOCUMENTED|DOC_ONLY|;
464.73 - member : real;A;|DOCUMENTED|DOC_ONLY|;
464.74 -
464.75 -Not Searchable Keys:
464.76 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.77 -
464.78 -
464.79 -Document 1
464.80 -Searchable Keys:
464.81 - class : complex
464.82 - class-ig : complex
464.83 - in : stub_missing
464.84 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
464.85 - member : __coerce__;F;|DOCUMENTED|DOC_ONLY|;y;
464.86 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
464.87 - member : __divmod__;F;|DOCUMENTED|DOC_ONLY|;y;
464.88 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
464.89 - member : __float__;F;|DOCUMENTED|DOC_ONLY|;;
464.90 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;;
464.91 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
464.92 - member : __getnewargs__;F;|DOCUMENTED|DOC_ONLY|;;
464.93 - member : __hash__;F;|DOCUMENTED|DOC_ONLY|;;
464.94 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
464.95 - member : __int__;F;|DOCUMENTED|DOC_ONLY|;;
464.96 - member : __long__;F;|DOCUMENTED|DOC_ONLY|;;
464.97 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
464.98 - member : __nonzero__;F;|DOCUMENTED|DOC_ONLY|;;
464.99 - member : __radd__;F;|DOCUMENTED|DOC_ONLY|;y;
464.100 - member : __rdiv__;F;|DOCUMENTED|DOC_ONLY|;y;
464.101 - member : __rdivmod__;F;|DOCUMENTED|DOC_ONLY|;y;
464.102 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
464.103 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
464.104 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
464.105 - member : __rfloordiv__;F;|DOCUMENTED|DOC_ONLY|;y;
464.106 - member : __rmod__;F;|DOCUMENTED|DOC_ONLY|;y;
464.107 - member : __rmul__;F;|DOCUMENTED|DOC_ONLY|;y;
464.108 - member : __rpow__;F;|DOCUMENTED|DOC_ONLY|;x;
464.109 - member : __rsub__;F;|DOCUMENTED|DOC_ONLY|;y;
464.110 - member : __rtruediv__;F;|DOCUMENTED|DOC_ONLY|;y;
464.111 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
464.112 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
464.113 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
464.114 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
464.115 - member : conjugate;F;|DOCUMENTED|DOC_ONLY|;;
464.116 - member : imag;A;|DOCUMENTED|DOC_ONLY|;
464.117 - member : real;A;|DOCUMENTED|DOC_ONLY|;
464.118 -
464.119 -Not Searchable Keys:
464.120 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.121 -
464.122 -
464.123 -Document 2
464.124 -Searchable Keys:
464.125 - class : dict
464.126 - class-ig : dict
464.127 - in : stub_missing
464.128 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
464.129 - member : __cmp__;F;|DOCUMENTED|DOC_ONLY|;y;
464.130 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
464.131 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
464.132 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;;
464.133 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
464.134 - member : __hash__;A;|DOCUMENTED|DOC_ONLY|;
464.135 - member : __iter__;F;|DOCUMENTED|DOC_ONLY|;;
464.136 - member : __len__;F;|DOCUMENTED|DOC_ONLY|;;
464.137 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
464.138 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
464.139 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
464.140 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
464.141 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
464.142 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
464.143 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
464.144 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
464.145 -
464.146 -Not Searchable Keys:
464.147 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.148 -
464.149 -
464.150 -Document 3
464.151 -Searchable Keys:
464.152 - class : float
464.153 - class-ig : float
464.154 - in : stub_missing
464.155 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
464.156 - member : __coerce__;F;|DOCUMENTED|DOC_ONLY|;y;
464.157 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
464.158 - member : __divmod__;F;|DOCUMENTED|DOC_ONLY|;y;
464.159 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
464.160 - member : __float__;F;|DOCUMENTED|DOC_ONLY|;;
464.161 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;format_spec;
464.162 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
464.163 - member : __getformat__;F;|DOCUMENTED|DOC_ONLY|;typestr;
464.164 - member : __getnewargs__;F;|DOCUMENTED|DOC_ONLY|;;
464.165 - member : __hash__;F;|DOCUMENTED|DOC_ONLY|;;
464.166 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
464.167 - member : __int__;F;|DOCUMENTED|DOC_ONLY|;;
464.168 - member : __long__;F;|DOCUMENTED|DOC_ONLY|;;
464.169 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
464.170 - member : __nonzero__;F;|DOCUMENTED|DOC_ONLY|;;
464.171 - member : __radd__;F;|DOCUMENTED|DOC_ONLY|;y;
464.172 - member : __rdiv__;F;|DOCUMENTED|DOC_ONLY|;y;
464.173 - member : __rdivmod__;F;|DOCUMENTED|DOC_ONLY|;y;
464.174 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
464.175 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
464.176 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
464.177 - member : __rfloordiv__;F;|DOCUMENTED|DOC_ONLY|;y;
464.178 - member : __rmod__;F;|DOCUMENTED|DOC_ONLY|;y;
464.179 - member : __rmul__;F;|DOCUMENTED|DOC_ONLY|;y;
464.180 - member : __rpow__;F;|DOCUMENTED|DOC_ONLY|;x;
464.181 - member : __rsub__;F;|DOCUMENTED|DOC_ONLY|;y;
464.182 - member : __rtruediv__;F;|DOCUMENTED|DOC_ONLY|;y;
464.183 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
464.184 - member : __setformat__;F;|DOCUMENTED|DOC_ONLY|;typestr,fmt;
464.185 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
464.186 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
464.187 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
464.188 - member : __trunc__;F;|DOCUMENTED|DOC_ONLY|;;
464.189 - member : conjugate;F;|DOCUMENTED|DOC_ONLY|;;
464.190 - member : imag;A;|DOCUMENTED|DOC_ONLY|;
464.191 - member : is_integer;F;|DOCUMENTED|DOC_ONLY|;;
464.192 - member : real;A;|DOCUMENTED|DOC_ONLY|;
464.193 -
464.194 -Not Searchable Keys:
464.195 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.196 -
464.197 -
464.198 -Document 4
464.199 -Searchable Keys:
464.200 - class : int
464.201 - class-ig : int
464.202 - in : stub_missing
464.203 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
464.204 - member : __cmp__;F;|DOCUMENTED|DOC_ONLY|;y;
464.205 - member : __coerce__;F;|DOCUMENTED|DOC_ONLY|;y;
464.206 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
464.207 - member : __divmod__;F;|DOCUMENTED|DOC_ONLY|;y;
464.208 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
464.209 - member : __float__;F;|DOCUMENTED|DOC_ONLY|;;
464.210 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;;
464.211 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
464.212 - member : __getnewargs__;F;|DOCUMENTED|DOC_ONLY|;;
464.213 - member : __hash__;F;|DOCUMENTED|DOC_ONLY|;;
464.214 - member : __hex__;F;|DOCUMENTED|DOC_ONLY|;;
464.215 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
464.216 - member : __int__;F;|DOCUMENTED|DOC_ONLY|;;
464.217 - member : __long__;F;|DOCUMENTED|DOC_ONLY|;;
464.218 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
464.219 - member : __nonzero__;F;|DOCUMENTED|DOC_ONLY|;;
464.220 - member : __oct__;F;|DOCUMENTED|DOC_ONLY|;;
464.221 - member : __radd__;F;|DOCUMENTED|DOC_ONLY|;y;
464.222 - member : __rand__;F;|DOCUMENTED|DOC_ONLY|;y;
464.223 - member : __rdiv__;F;|DOCUMENTED|DOC_ONLY|;y;
464.224 - member : __rdivmod__;F;|DOCUMENTED|DOC_ONLY|;y;
464.225 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
464.226 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
464.227 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
464.228 - member : __rfloordiv__;F;|DOCUMENTED|DOC_ONLY|;y;
464.229 - member : __rlshift__;F;|DOCUMENTED|DOC_ONLY|;y;
464.230 - member : __rmod__;F;|DOCUMENTED|DOC_ONLY|;y;
464.231 - member : __rmul__;F;|DOCUMENTED|DOC_ONLY|;y;
464.232 - member : __ror__;F;|DOCUMENTED|DOC_ONLY|;y;
464.233 - member : __rpow__;F;|DOCUMENTED|DOC_ONLY|;x;
464.234 - member : __rrshift__;F;|DOCUMENTED|DOC_ONLY|;y;
464.235 - member : __rsub__;F;|DOCUMENTED|DOC_ONLY|;y;
464.236 - member : __rtruediv__;F;|DOCUMENTED|DOC_ONLY|;y;
464.237 - member : __rxor__;F;|DOCUMENTED|DOC_ONLY|;y;
464.238 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
464.239 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
464.240 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
464.241 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
464.242 - member : __trunc__;F;|DOCUMENTED|DOC_ONLY|;;
464.243 - member : conjugate;F;|DOCUMENTED|DOC_ONLY|;;
464.244 - member : denominator;A;|DOCUMENTED|DOC_ONLY|;
464.245 - member : imag;A;|DOCUMENTED|DOC_ONLY|;
464.246 - member : numerator;A;|DOCUMENTED|DOC_ONLY|;
464.247 - member : real;A;|DOCUMENTED|DOC_ONLY|;
464.248 -
464.249 -Not Searchable Keys:
464.250 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.251 -
464.252 -
464.253 -Document 5
464.254 -Searchable Keys:
464.255 - class : list
464.256 - class-ig : list
464.257 - in : stub_missing
464.258 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
464.259 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
464.260 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
464.261 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;;
464.262 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
464.263 - member : __hash__;A;|DOCUMENTED|DOC_ONLY|;
464.264 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
464.265 - member : __iter__;F;|DOCUMENTED|DOC_ONLY|;;
464.266 - member : __len__;F;|DOCUMENTED|DOC_ONLY|;;
464.267 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
464.268 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
464.269 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
464.270 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
464.271 - member : __reversed__;F;|DOCUMENTED|DOC_ONLY|;;
464.272 - member : __rmul__;F;|DOCUMENTED|DOC_ONLY|;n;
464.273 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
464.274 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
464.275 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
464.276 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
464.277 - member : append;F;|DOCUMENTED|DOC_ONLY|;;
464.278 - member : count;F;|DOCUMENTED|DOC_ONLY|;value;
464.279 - member : extend;F;|DOCUMENTED|DOC_ONLY|;;
464.280 - member : insert;F;|DOCUMENTED|DOC_ONLY|;;
464.281 - member : pop;F;|DOCUMENTED|DOC_ONLY|;;
464.282 - member : remove;F;|DOCUMENTED|DOC_ONLY|;;
464.283 - member : reverse;F;|DOCUMENTED|DOC_ONLY|;;
464.284 - member : sort;F;|DOCUMENTED|DOC_ONLY|;cmp,key,reverse;
464.285 -
464.286 -Not Searchable Keys:
464.287 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.288 -
464.289 -
464.290 -Document 6
464.291 -Searchable Keys:
464.292 - class : long
464.293 - class-ig : long
464.294 - in : stub_missing
464.295 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
464.296 - member : __cmp__;F;|DOCUMENTED|DOC_ONLY|;y;
464.297 - member : __coerce__;F;|DOCUMENTED|DOC_ONLY|;y;
464.298 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
464.299 - member : __divmod__;F;|DOCUMENTED|DOC_ONLY|;y;
464.300 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
464.301 - member : __float__;F;|DOCUMENTED|DOC_ONLY|;;
464.302 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;;
464.303 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
464.304 - member : __getnewargs__;F;|DOCUMENTED|DOC_ONLY|;;
464.305 - member : __hash__;F;|DOCUMENTED|DOC_ONLY|;;
464.306 - member : __hex__;F;|DOCUMENTED|DOC_ONLY|;;
464.307 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
464.308 - member : __int__;F;|DOCUMENTED|DOC_ONLY|;;
464.309 - member : __long__;F;|DOCUMENTED|DOC_ONLY|;;
464.310 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
464.311 - member : __nonzero__;F;|DOCUMENTED|DOC_ONLY|;;
464.312 - member : __oct__;F;|DOCUMENTED|DOC_ONLY|;;
464.313 - member : __radd__;F;|DOCUMENTED|DOC_ONLY|;y;
464.314 - member : __rand__;F;|DOCUMENTED|DOC_ONLY|;y;
464.315 - member : __rdiv__;F;|DOCUMENTED|DOC_ONLY|;y;
464.316 - member : __rdivmod__;F;|DOCUMENTED|DOC_ONLY|;y;
464.317 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
464.318 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
464.319 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
464.320 - member : __rfloordiv__;F;|DOCUMENTED|DOC_ONLY|;y;
464.321 - member : __rlshift__;F;|DOCUMENTED|DOC_ONLY|;y;
464.322 - member : __rmod__;F;|DOCUMENTED|DOC_ONLY|;y;
464.323 - member : __rmul__;F;|DOCUMENTED|DOC_ONLY|;y;
464.324 - member : __ror__;F;|DOCUMENTED|DOC_ONLY|;y;
464.325 - member : __rpow__;F;|DOCUMENTED|DOC_ONLY|;x;
464.326 - member : __rrshift__;F;|DOCUMENTED|DOC_ONLY|;y;
464.327 - member : __rsub__;F;|DOCUMENTED|DOC_ONLY|;y;
464.328 - member : __rtruediv__;F;|DOCUMENTED|DOC_ONLY|;y;
464.329 - member : __rxor__;F;|DOCUMENTED|DOC_ONLY|;y;
464.330 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
464.331 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
464.332 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
464.333 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
464.334 - member : __trunc__;F;|DOCUMENTED|DOC_ONLY|;;
464.335 - member : conjugate;F;|DOCUMENTED|DOC_ONLY|;;
464.336 - member : denominator;A;|DOCUMENTED|DOC_ONLY|;
464.337 - member : imag;A;|DOCUMENTED|DOC_ONLY|;
464.338 - member : numerator;A;|DOCUMENTED|DOC_ONLY|;
464.339 - member : real;A;|DOCUMENTED|DOC_ONLY|;
464.340 -
464.341 -Not Searchable Keys:
464.342 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.343 -
464.344 -
464.345 -Document 7
464.346 -Searchable Keys:
464.347 - class : str
464.348 - class-ig : str
464.349 - in : stub_missing
464.350 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
464.351 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
464.352 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
464.353 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;format_spec;
464.354 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
464.355 - member : __getnewargs__;F;|DOCUMENTED|DOC_ONLY|;;
464.356 - member : __hash__;F;|DOCUMENTED|DOC_ONLY|;;
464.357 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
464.358 - member : __len__;F;|DOCUMENTED|DOC_ONLY|;;
464.359 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
464.360 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
464.361 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
464.362 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
464.363 - member : __rmod__;F;|DOCUMENTED|DOC_ONLY|;y;
464.364 - member : __rmul__;F;|DOCUMENTED|DOC_ONLY|;n;
464.365 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
464.366 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
464.367 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
464.368 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
464.369 - member : _formatter_field_name_split;F;|DOCUMENTED|PRIVATE|DOC_ONLY|;;
464.370 - member : _formatter_parser;F;|DOCUMENTED|PRIVATE|DOC_ONLY|;;
464.371 -
464.372 -Not Searchable Keys:
464.373 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.374 -
464.375 -
464.376 -Document 8
464.377 -Searchable Keys:
464.378 - class : tuple
464.379 - class-ig : tuple
464.380 - in : stub_missing
464.381 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
464.382 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
464.383 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
464.384 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;;
464.385 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
464.386 - member : __getnewargs__;F;|DOCUMENTED|DOC_ONLY|;;
464.387 - member : __hash__;F;|DOCUMENTED|DOC_ONLY|;;
464.388 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
464.389 - member : __iter__;F;|DOCUMENTED|DOC_ONLY|;;
464.390 - member : __len__;F;|DOCUMENTED|DOC_ONLY|;;
464.391 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
464.392 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
464.393 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
464.394 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
464.395 - member : __rmul__;F;|DOCUMENTED|DOC_ONLY|;n;
464.396 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
464.397 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
464.398 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
464.399 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
464.400 - member : count;F;|DOCUMENTED|DOC_ONLY|;value;
464.401 -
464.402 -Not Searchable Keys:
464.403 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.404 -
464.405 -
464.406 -Document 9
464.407 -Searchable Keys:
464.408 - class : unicode
464.409 - class-ig : unicode
464.410 - in : stub_missing
464.411 - member : __class__;A;|DOCUMENTED|DOC_ONLY|;
464.412 - member : __delattr__;F;|DOCUMENTED|DOC_ONLY|;name;
464.413 - member : __doc__;A;|DOCUMENTED|DOC_ONLY|;
464.414 - member : __format__;F;|DOCUMENTED|DOC_ONLY|;format_spec;
464.415 - member : __getattribute__;F;|DOCUMENTED|DOC_ONLY|;name;
464.416 - member : __getnewargs__;F;|DOCUMENTED|DOC_ONLY|;;
464.417 - member : __hash__;F;|DOCUMENTED|DOC_ONLY|;;
464.418 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;;
464.419 - member : __len__;F;|DOCUMENTED|DOC_ONLY|;;
464.420 - member : __new__;F;|DOCUMENTED|DOC_ONLY|;S,___;
464.421 - member : __reduce__;F;|DOCUMENTED|DOC_ONLY|;;
464.422 - member : __reduce_ex__;F;|DOCUMENTED|DOC_ONLY|;;
464.423 - member : __repr__;F;|DOCUMENTED|DOC_ONLY|;;
464.424 - member : __rmod__;F;|DOCUMENTED|DOC_ONLY|;y;
464.425 - member : __rmul__;F;|DOCUMENTED|DOC_ONLY|;n;
464.426 - member : __setattr__;F;|DOCUMENTED|DOC_ONLY|;name,value;
464.427 - member : __sizeof__;F;|DOCUMENTED|DOC_ONLY|;;
464.428 - member : __str__;F;|DOCUMENTED|DOC_ONLY|;;
464.429 - member : __subclasshook__;F;|DOCUMENTED|DOC_ONLY|;;
464.430 - member : _formatter_field_name_split;F;|DOCUMENTED|PRIVATE|DOC_ONLY|;;
464.431 - member : _formatter_parser;F;|DOCUMENTED|PRIVATE|DOC_ONLY|;;
464.432 - member : capitalize;F;|DOCUMENTED|DOC_ONLY|;;
464.433 - member : center;F;|DOCUMENTED|DOC_ONLY|;width;
464.434 - member : count;F;|DOCUMENTED|DOC_ONLY|;sub;
464.435 - member : decode;F;|DOCUMENTED|DOC_ONLY|;;
464.436 - member : encode;F;|DOCUMENTED|DOC_ONLY|;;
464.437 - member : endswith;F;|DOCUMENTED|DOC_ONLY|;suffix;
464.438 - member : expandtabs;F;|DOCUMENTED|DOC_ONLY|;;
464.439 - member : find;F;|DOCUMENTED|DOC_ONLY|;sub;
464.440 - member : format;F;|DOCUMENTED|DOC_ONLY|;*args,**kwargs;
464.441 - member : isalnum;F;|DOCUMENTED|DOC_ONLY|;;
464.442 - member : isalpha;F;|DOCUMENTED|DOC_ONLY|;;
464.443 - member : isdigit;F;|DOCUMENTED|DOC_ONLY|;;
464.444 - member : islower;F;|DOCUMENTED|DOC_ONLY|;;
464.445 - member : isspace;F;|DOCUMENTED|DOC_ONLY|;;
464.446 - member : istitle;F;|DOCUMENTED|DOC_ONLY|;;
464.447 - member : isupper;F;|DOCUMENTED|DOC_ONLY|;;
464.448 - member : join;F;|DOCUMENTED|DOC_ONLY|;sequence;
464.449 - member : ljust;F;|DOCUMENTED|DOC_ONLY|;width;
464.450 - member : lower;F;|DOCUMENTED|DOC_ONLY|;;
464.451 - member : lstrip;F;|DOCUMENTED|DOC_ONLY|;;
464.452 - member : partition;F;|DOCUMENTED|DOC_ONLY|;sep;
464.453 - member : replace;F;|DOCUMENTED|DOC_ONLY|;old,new;
464.454 - member : rfind;F;|DOCUMENTED|DOC_ONLY|;sub;
464.455 - member : rindex;F;|DOCUMENTED|DOC_ONLY|;sub;
464.456 - member : rjust;F;|DOCUMENTED|DOC_ONLY|;width;
464.457 - member : rpartition;F;|DOCUMENTED|DOC_ONLY|;sep;
464.458 - member : rsplit;F;|DOCUMENTED|DOC_ONLY|;;
464.459 - member : rstrip;F;|DOCUMENTED|DOC_ONLY|;;
464.460 - member : split;F;|DOCUMENTED|DOC_ONLY|;;
464.461 - member : splitlines;F;|DOCUMENTED|DOC_ONLY|;;
464.462 - member : startswith;F;|DOCUMENTED|DOC_ONLY|;prefix;
464.463 - member : strip;F;|DOCUMENTED|DOC_ONLY|;;
464.464 - member : swapcase;F;|DOCUMENTED|DOC_ONLY|;;
464.465 - member : title;F;|DOCUMENTED|DOC_ONLY|;;
464.466 - member : translate;F;|DOCUMENTED|DOC_ONLY|;table;
464.467 - member : upper;F;|DOCUMENTED|DOC_ONLY|;;
464.468 - member : zfill;F;|DOCUMENTED|DOC_ONLY|;width;
464.469 -
464.470 -Not Searchable Keys:
464.471 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
464.472 -
464.473 -
464.474 -Document 10
464.475 -Searchable Keys:
464.476 - item : bool;C;|DOCUMENTED|DOC_ONLY|;
464.477 - item : complex;C;|DOCUMENTED|DOC_ONLY|;
464.478 - item : dict;C;|DOCUMENTED|DOC_ONLY|;
464.479 - item : float;C;|DOCUMENTED|DOC_ONLY|;
464.480 - item : int;C;|DOCUMENTED|DOC_ONLY|;
464.481 - item : list;C;|DOCUMENTED|DOC_ONLY|;
464.482 - item : long;C;|DOCUMENTED|DOC_ONLY|;
464.483 - item : str;C;|DOCUMENTED|DOC_ONLY|;
464.484 - item : tuple;C;|DOCUMENTED|DOC_ONLY|;
464.485 - item : unicode;C;|DOCUMENTED|DOC_ONLY|;
464.486 - module : stub_missing
464.487 -
464.488 -Not Searchable Keys:
464.489 - modattrs : S
465.1 --- a/python.editor/test/unit/data/testfiles/rst/zipfile.rst Sun Jan 04 13:11:53 2015 -0600
465.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
465.3 @@ -1,451 +0,0 @@
465.4 -
465.5 -:mod:`zipfile` --- Work with ZIP archives
465.6 -=========================================
465.7 -
465.8 -.. module:: zipfile
465.9 - :synopsis: Read and write ZIP-format archive files.
465.10 -.. moduleauthor:: James C. Ahlstrom <jim@interet.com>
465.11 -.. sectionauthor:: James C. Ahlstrom <jim@interet.com>
465.12 -
465.13 -.. versionadded:: 1.6
465.14 -
465.15 -The ZIP file format is a common archive and compression standard. This module
465.16 -provides tools to create, read, write, append, and list a ZIP file. Any
465.17 -advanced use of this module will require an understanding of the format, as
465.18 -defined in `PKZIP Application Note
465.19 -<http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_.
465.20 -
465.21 -This module does not currently handle multi-disk ZIP files, or ZIP files
465.22 -which have appended comments (although it correctly handles comments
465.23 -added to individual archive members---for which see the :ref:`zipinfo-objects`
465.24 -documentation). It can handle ZIP files that use the ZIP64 extensions
465.25 -(that is ZIP files that are more than 4 GByte in size). It supports
465.26 -decryption of encrypted files in ZIP archives, but it currently cannot
465.27 -create an encrypted file. Decryption is extremely slow as it is
465.28 -implemented in native python rather than C.
465.29 -
465.30 -For other archive formats, see the :mod:`bz2`, :mod:`gzip`, and
465.31 -:mod:`tarfile` modules.
465.32 -
465.33 -The module defines the following items:
465.34 -
465.35 -.. exception:: BadZipfile
465.36 -
465.37 - The error raised for bad ZIP files (old name: ``zipfile.error``).
465.38 -
465.39 -
465.40 -.. exception:: LargeZipFile
465.41 -
465.42 - The error raised when a ZIP file would require ZIP64 functionality but that has
465.43 - not been enabled.
465.44 -
465.45 -
465.46 -.. class:: ZipFile
465.47 -
465.48 - The class for reading and writing ZIP files. See section
465.49 - :ref:`zipfile-objects` for constructor details.
465.50 -
465.51 -
465.52 -.. class:: PyZipFile
465.53 -
465.54 - Class for creating ZIP archives containing Python libraries.
465.55 -
465.56 -
465.57 -.. class:: ZipInfo([filename[, date_time]])
465.58 -
465.59 - Class used to represent information about a member of an archive. Instances
465.60 - of this class are returned by the :meth:`getinfo` and :meth:`infolist`
465.61 - methods of :class:`ZipFile` objects. Most users of the :mod:`zipfile` module
465.62 - will not need to create these, but only use those created by this
465.63 - module. *filename* should be the full name of the archive member, and
465.64 - *date_time* should be a tuple containing six fields which describe the time
465.65 - of the last modification to the file; the fields are described in section
465.66 - :ref:`zipinfo-objects`.
465.67 -
465.68 -
465.69 -.. function:: is_zipfile(filename)
465.70 -
465.71 - Returns ``True`` if *filename* is a valid ZIP file based on its magic number,
465.72 - otherwise returns ``False``. This module does not currently handle ZIP files
465.73 - which have appended comments.
465.74 -
465.75 -
465.76 -.. data:: ZIP_STORED
465.77 -
465.78 - The numeric constant for an uncompressed archive member.
465.79 -
465.80 -
465.81 -.. data:: ZIP_DEFLATED
465.82 -
465.83 - The numeric constant for the usual ZIP compression method. This requires the
465.84 - zlib module. No other compression methods are currently supported.
465.85 -
465.86 -
465.87 -.. seealso::
465.88 -
465.89 - `PKZIP Application Note <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_
465.90 - Documentation on the ZIP file format by Phil Katz, the creator of the format and
465.91 - algorithms used.
465.92 -
465.93 - `Info-ZIP Home Page <http://www.info-zip.org/>`_
465.94 - Information about the Info-ZIP project's ZIP archive programs and development
465.95 - libraries.
465.96 -
465.97 -
465.98 -.. _zipfile-objects:
465.99 -
465.100 -ZipFile Objects
465.101 ----------------
465.102 -
465.103 -
465.104 -.. class:: ZipFile(file[, mode[, compression[, allowZip64]]])
465.105 -
465.106 - Open a ZIP file, where *file* can be either a path to a file (a string) or a
465.107 - file-like object. The *mode* parameter should be ``'r'`` to read an existing
465.108 - file, ``'w'`` to truncate and write a new file, or ``'a'`` to append to an
465.109 - existing file. If *mode* is ``'a'`` and *file* refers to an existing ZIP file,
465.110 - then additional files are added to it. If *file* does not refer to a ZIP file,
465.111 - then a new ZIP archive is appended to the file. This is meant for adding a ZIP
465.112 - archive to another file, such as :file:`python.exe`. Using ::
465.113 -
465.114 - cat myzip.zip >> python.exe
465.115 -
465.116 - also works, and at least :program:`WinZip` can read such files. If *mode* is
465.117 - ``a`` and the file does not exist at all, it is created. *compression* is the
465.118 - ZIP compression method to use when writing the archive, and should be
465.119 - :const:`ZIP_STORED` or :const:`ZIP_DEFLATED`; unrecognized values will cause
465.120 - :exc:`RuntimeError` to be raised. If :const:`ZIP_DEFLATED` is specified but the
465.121 - :mod:`zlib` module is not available, :exc:`RuntimeError` is also raised. The
465.122 - default is :const:`ZIP_STORED`. If *allowZip64* is ``True`` zipfile will create
465.123 - ZIP files that use the ZIP64 extensions when the zipfile is larger than 2 GB. If
465.124 - it is false (the default) :mod:`zipfile` will raise an exception when the ZIP
465.125 - file would require ZIP64 extensions. ZIP64 extensions are disabled by default
465.126 - because the default :program:`zip` and :program:`unzip` commands on Unix (the
465.127 - InfoZIP utilities) don't support these extensions.
465.128 -
465.129 - .. versionchanged:: 2.6
465.130 - If the file does not exist, it is created if the mode is 'a'.
465.131 -
465.132 -
465.133 -.. method:: ZipFile.close()
465.134 -
465.135 - Close the archive file. You must call :meth:`close` before exiting your program
465.136 - or essential records will not be written.
465.137 -
465.138 -
465.139 -.. method:: ZipFile.getinfo(name)
465.140 -
465.141 - Return a :class:`ZipInfo` object with information about the archive member
465.142 - *name*. Calling :meth:`getinfo` for a name not currently contained in the
465.143 - archive will raise a :exc:`KeyError`.
465.144 -
465.145 -
465.146 -.. method:: ZipFile.infolist()
465.147 -
465.148 - Return a list containing a :class:`ZipInfo` object for each member of the
465.149 - archive. The objects are in the same order as their entries in the actual ZIP
465.150 - file on disk if an existing archive was opened.
465.151 -
465.152 -
465.153 -.. method:: ZipFile.namelist()
465.154 -
465.155 - Return a list of archive members by name.
465.156 -
465.157 -
465.158 -.. method:: ZipFile.open(name[, mode[, pwd]])
465.159 -
465.160 - Extract a member from the archive as a file-like object (ZipExtFile). *name* is
465.161 - the name of the file in the archive, or a :class:`ZipInfo` object. The *mode*
465.162 - parameter, if included, must be one of the following: ``'r'`` (the default),
465.163 - ``'U'``, or ``'rU'``. Choosing ``'U'`` or ``'rU'`` will enable universal newline
465.164 - support in the read-only object. *pwd* is the password used for encrypted files.
465.165 - Calling :meth:`open` on a closed ZipFile will raise a :exc:`RuntimeError`.
465.166 -
465.167 - .. note::
465.168 -
465.169 - The file-like object is read-only and provides the following methods:
465.170 - :meth:`read`, :meth:`readline`, :meth:`readlines`, :meth:`__iter__`,
465.171 - :meth:`next`.
465.172 -
465.173 - .. note::
465.174 -
465.175 - If the ZipFile was created by passing in a file-like object as the first
465.176 - argument to the constructor, then the object returned by :meth:`.open` shares the
465.177 - ZipFile's file pointer. Under these circumstances, the object returned by
465.178 - :meth:`.open` should not be used after any additional operations are performed
465.179 - on the ZipFile object. If the ZipFile was created by passing in a string (the
465.180 - filename) as the first argument to the constructor, then :meth:`.open` will
465.181 - create a new file object that will be held by the ZipExtFile, allowing it to
465.182 - operate independently of the ZipFile.
465.183 -
465.184 - .. note::
465.185 -
465.186 - The :meth:`open`, :meth:`read` and :meth:`extract` methods can take a filename
465.187 - or a :class:`ZipInfo` object. You will appreciate this when trying to read a
465.188 - ZIP file that contains members with duplicate names.
465.189 -
465.190 - .. versionadded:: 2.6
465.191 -
465.192 -
465.193 -.. method:: ZipFile.extract(member[, path[, pwd]])
465.194 -
465.195 - Extract a member from the archive to the current working directory; *member*
465.196 - must be its full name or a :class:`ZipInfo` object). Its file information is
465.197 - extracted as accurately as possible. *path* specifies a different directory
465.198 - to extract to. *member* can be a filename or a :class:`ZipInfo` object.
465.199 - *pwd* is the password used for encrypted files.
465.200 -
465.201 - .. versionadded:: 2.6
465.202 -
465.203 -
465.204 -.. method:: ZipFile.extractall([path[, members[, pwd]]])
465.205 -
465.206 - Extract all members from the archive to the current working directory. *path*
465.207 - specifies a different directory to extract to. *members* is optional and must
465.208 - be a subset of the list returned by :meth:`namelist`. *pwd* is the password
465.209 - used for encrypted files.
465.210 -
465.211 - .. versionadded:: 2.6
465.212 -
465.213 -
465.214 -.. method:: ZipFile.printdir()
465.215 -
465.216 - Print a table of contents for the archive to ``sys.stdout``.
465.217 -
465.218 -
465.219 -.. method:: ZipFile.setpassword(pwd)
465.220 -
465.221 - Set *pwd* as default password to extract encrypted files.
465.222 -
465.223 - .. versionadded:: 2.6
465.224 -
465.225 -
465.226 -.. method:: ZipFile.read(name[, pwd])
465.227 -
465.228 - Return the bytes of the file *name* in the archive. *name* is the name of the
465.229 - file in the archive, or a :class:`ZipInfo` object. The archive must be open for
465.230 - read or append. *pwd* is the password used for encrypted files and, if specified,
465.231 - it will override the default password set with :meth:`setpassword`. Calling
465.232 - :meth:`read` on a closed ZipFile will raise a :exc:`RuntimeError`.
465.233 -
465.234 - .. versionchanged:: 2.6
465.235 - *pwd* was added, and *name* can now be a :class:`ZipInfo` object.
465.236 -
465.237 -
465.238 -.. method:: ZipFile.testzip()
465.239 -
465.240 - Read all the files in the archive and check their CRC's and file headers.
465.241 - Return the name of the first bad file, or else return ``None``. Calling
465.242 - :meth:`testzip` on a closed ZipFile will raise a :exc:`RuntimeError`.
465.243 -
465.244 -
465.245 -.. method:: ZipFile.write(filename[, arcname[, compress_type]])
465.246 -
465.247 - Write the file named *filename* to the archive, giving it the archive name
465.248 - *arcname* (by default, this will be the same as *filename*, but without a drive
465.249 - letter and with leading path separators removed). If given, *compress_type*
465.250 - overrides the value given for the *compression* parameter to the constructor for
465.251 - the new entry. The archive must be open with mode ``'w'`` or ``'a'`` -- calling
465.252 - :meth:`write` on a ZipFile created with mode ``'r'`` will raise a
465.253 - :exc:`RuntimeError`. Calling :meth:`write` on a closed ZipFile will raise a
465.254 - :exc:`RuntimeError`.
465.255 -
465.256 - .. note::
465.257 -
465.258 - There is no official file name encoding for ZIP files. If you have unicode file
465.259 - names, you must convert them to byte strings in your desired encoding before
465.260 - passing them to :meth:`write`. WinZip interprets all file names as encoded in
465.261 - CP437, also known as DOS Latin.
465.262 -
465.263 - .. note::
465.264 -
465.265 - Archive names should be relative to the archive root, that is, they should not
465.266 - start with a path separator.
465.267 -
465.268 - .. note::
465.269 -
465.270 - If ``arcname`` (or ``filename``, if ``arcname`` is not given) contains a null
465.271 - byte, the name of the file in the archive will be truncated at the null byte.
465.272 -
465.273 -
465.274 -.. method:: ZipFile.writestr(zinfo_or_arcname, bytes)
465.275 -
465.276 - Write the string *bytes* to the archive; *zinfo_or_arcname* is either the file
465.277 - name it will be given in the archive, or a :class:`ZipInfo` instance. If it's
465.278 - an instance, at least the filename, date, and time must be given. If it's a
465.279 - name, the date and time is set to the current date and time. The archive must be
465.280 - opened with mode ``'w'`` or ``'a'`` -- calling :meth:`writestr` on a ZipFile
465.281 - created with mode ``'r'`` will raise a :exc:`RuntimeError`. Calling
465.282 - :meth:`writestr` on a closed ZipFile will raise a :exc:`RuntimeError`.
465.283 -
465.284 - .. note::
465.285 -
465.286 - When passing a :class:`ZipInfo` instance as the *zinfo_or_acrname* parameter,
465.287 - the compression method used will be that specified in the *compress_type*
465.288 - member of the given :class:`ZipInfo` instance. By default, the
465.289 - :class:`ZipInfo` constructor sets this member to :const:`ZIP_STORED`.
465.290 -
465.291 -The following data attributes are also available:
465.292 -
465.293 -
465.294 -.. attribute:: ZipFile.debug
465.295 -
465.296 - The level of debug output to use. This may be set from ``0`` (the default, no
465.297 - output) to ``3`` (the most output). Debugging information is written to
465.298 - ``sys.stdout``.
465.299 -
465.300 -.. attribute:: ZipFile.comment
465.301 -
465.302 - The comment text associated with the ZIP file. If assigning a comment to a
465.303 - :class:`ZipFile` instance created with mode 'a' or 'w', this should be a
465.304 - string no longer than 65535 bytes. Comments longer than this will be
465.305 - truncated in the written archive when :meth:`ZipFile.close` is called.
465.306 -
465.307 -.. _pyzipfile-objects:
465.308 -
465.309 -PyZipFile Objects
465.310 ------------------
465.311 -
465.312 -The :class:`PyZipFile` constructor takes the same parameters as the
465.313 -:class:`ZipFile` constructor. Instances have one method in addition to those of
465.314 -:class:`ZipFile` objects.
465.315 -
465.316 -
465.317 -.. method:: PyZipFile.writepy(pathname[, basename])
465.318 -
465.319 - Search for files :file:`\*.py` and add the corresponding file to the archive.
465.320 - The corresponding file is a :file:`\*.pyo` file if available, else a
465.321 - :file:`\*.pyc` file, compiling if necessary. If the pathname is a file, the
465.322 - filename must end with :file:`.py`, and just the (corresponding
465.323 - :file:`\*.py[co]`) file is added at the top level (no path information). If the
465.324 - pathname is a file that does not end with :file:`.py`, a :exc:`RuntimeError`
465.325 - will be raised. If it is a directory, and the directory is not a package
465.326 - directory, then all the files :file:`\*.py[co]` are added at the top level. If
465.327 - the directory is a package directory, then all :file:`\*.py[co]` are added under
465.328 - the package name as a file path, and if any subdirectories are package
465.329 - directories, all of these are added recursively. *basename* is intended for
465.330 - internal use only. The :meth:`writepy` method makes archives with file names
465.331 - like this::
465.332 -
465.333 - string.pyc # Top level name
465.334 - test/__init__.pyc # Package directory
465.335 - test/test_support.pyc # Module test.test_support
465.336 - test/bogus/__init__.pyc # Subpackage directory
465.337 - test/bogus/myfile.pyc # Submodule test.bogus.myfile
465.338 -
465.339 -
465.340 -.. _zipinfo-objects:
465.341 -
465.342 -ZipInfo Objects
465.343 ----------------
465.344 -
465.345 -Instances of the :class:`ZipInfo` class are returned by the :meth:`getinfo` and
465.346 -:meth:`infolist` methods of :class:`ZipFile` objects. Each object stores
465.347 -information about a single member of the ZIP archive.
465.348 -
465.349 -Instances have the following attributes:
465.350 -
465.351 -
465.352 -.. attribute:: ZipInfo.filename
465.353 -
465.354 - Name of the file in the archive.
465.355 -
465.356 -
465.357 -.. attribute:: ZipInfo.date_time
465.358 -
465.359 - The time and date of the last modification to the archive member. This is a
465.360 - tuple of six values:
465.361 -
465.362 - +-------+--------------------------+
465.363 - | Index | Value |
465.364 - +=======+==========================+
465.365 - | ``0`` | Year |
465.366 - +-------+--------------------------+
465.367 - | ``1`` | Month (one-based) |
465.368 - +-------+--------------------------+
465.369 - | ``2`` | Day of month (one-based) |
465.370 - +-------+--------------------------+
465.371 - | ``3`` | Hours (zero-based) |
465.372 - +-------+--------------------------+
465.373 - | ``4`` | Minutes (zero-based) |
465.374 - +-------+--------------------------+
465.375 - | ``5`` | Seconds (zero-based) |
465.376 - +-------+--------------------------+
465.377 -
465.378 -
465.379 -.. attribute:: ZipInfo.compress_type
465.380 -
465.381 - Type of compression for the archive member.
465.382 -
465.383 -
465.384 -.. attribute:: ZipInfo.comment
465.385 -
465.386 - Comment for the individual archive member.
465.387 -
465.388 -
465.389 -.. attribute:: ZipInfo.extra
465.390 -
465.391 - Expansion field data. The `PKZIP Application Note
465.392 - <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_ contains
465.393 - some comments on the internal structure of the data contained in this string.
465.394 -
465.395 -
465.396 -.. attribute:: ZipInfo.create_system
465.397 -
465.398 - System which created ZIP archive.
465.399 -
465.400 -
465.401 -.. attribute:: ZipInfo.create_version
465.402 -
465.403 - PKZIP version which created ZIP archive.
465.404 -
465.405 -
465.406 -.. attribute:: ZipInfo.extract_version
465.407 -
465.408 - PKZIP version needed to extract archive.
465.409 -
465.410 -
465.411 -.. attribute:: ZipInfo.reserved
465.412 -
465.413 - Must be zero.
465.414 -
465.415 -
465.416 -.. attribute:: ZipInfo.flag_bits
465.417 -
465.418 - ZIP flag bits.
465.419 -
465.420 -
465.421 -.. attribute:: ZipInfo.volume
465.422 -
465.423 - Volume number of file header.
465.424 -
465.425 -
465.426 -.. attribute:: ZipInfo.internal_attr
465.427 -
465.428 - Internal attributes.
465.429 -
465.430 -
465.431 -.. attribute:: ZipInfo.external_attr
465.432 -
465.433 - External file attributes.
465.434 -
465.435 -
465.436 -.. attribute:: ZipInfo.header_offset
465.437 -
465.438 - Byte offset to the file header.
465.439 -
465.440 -
465.441 -.. attribute:: ZipInfo.CRC
465.442 -
465.443 - CRC-32 of the uncompressed file.
465.444 -
465.445 -
465.446 -.. attribute:: ZipInfo.compress_size
465.447 -
465.448 - Size of the compressed data.
465.449 -
465.450 -
465.451 -.. attribute:: ZipInfo.file_size
465.452 -
465.453 - Size of the uncompressed file.
465.454 -
466.1 --- a/python.editor/test/unit/data/testfiles/rst/zipfile.rst.html Sun Jan 04 13:11:53 2015 -0600
466.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
466.3 @@ -1,453 +0,0 @@
466.4 -<html><body>
466.5 -<h2><a href="mod:zipfile">zipfile</a> --- Work with ZIP archives
466.6 -</h2>
466.7 -<a href="module:zipfile">zipfile</a><br>
466.8 - Read and write ZIP-format archive files.
466.9 -<br>Module Author:</b> James C. Ahlstrom <jim@interet.com>
466.10 -<br>Section Author:</b> James C. Ahlstrom <jim@interet.com>
466.11 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 1.6
466.12 -</div>
466.13 -The ZIP file format is a common archive and compression standard. This module
466.14 -provides tools to create, read, write, append, and list a ZIP file. Any
466.15 -advanced use of this module will require an understanding of the format, as
466.16 -defined in `PKZIP Application Note
466.17 -<http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_.
466.18 -
466.19 -<br><br>
466.20 -This module does not currently handle multi-disk ZIP files, or ZIP files
466.21 -which have appended comments (although it correctly handles comments
466.22 -added to individual archive members---for which see the <code>zipinfo-objects</code>
466.23 -documentation). It can handle ZIP files that use the ZIP64 extensions
466.24 -(that is ZIP files that are more than 4 GByte in size). It supports
466.25 -decryption of encrypted files in ZIP archives, but it currently cannot
466.26 -create an encrypted file. Decryption is extremely slow as it is
466.27 -implemented in native python rather than C.
466.28 -
466.29 -<br><br>
466.30 -For other archive formats, see the <a href="mod:bz2">bz2</a>, <a href="mod:gzip">gzip</a>, and
466.31 -<a href="mod:tarfile">tarfile</a> modules.
466.32 -
466.33 -<br><br>
466.34 -The module defines the following items:
466.35 -
466.36 -<br><br>
466.37 -.. exception:: BadZipfile
466.38 -
466.39 -<br><br>
466.40 - The error raised for bad ZIP files (old name: <code>zipfile.error</code>).
466.41 -
466.42 -<br><br>
466.43 -.. exception:: LargeZipFile
466.44 -
466.45 -<br><br>
466.46 - The error raised when a ZIP file would require ZIP64 functionality but that has
466.47 - not been enabled.
466.48 -
466.49 -<br><br>
466.50 -<a href="class:ZipFile">ZipFile</a>
466.51 -
466.52 -<br><br>
466.53 - The class for reading and writing ZIP files. See section
466.54 - <code>zipfile-objects</code> for constructor details.
466.55 -
466.56 -<br><br>
466.57 -<a href="class:PyZipFile">PyZipFile</a>
466.58 -
466.59 -<br><br>
466.60 - Class for creating ZIP archives containing Python libraries.
466.61 -
466.62 -<br><br>
466.63 -<a href="class:ZipInfo([filename[, date_time]])">ZipInfo([filename[, date_time]])</a>
466.64 -
466.65 -<br><br>
466.66 - Class used to represent information about a member of an archive. Instances
466.67 - of this class are returned by the <a href="meth:getinfo">getinfo</a> and <a href="meth:infolist">infolist</a>
466.68 - methods of <a href="class:ZipFile">ZipFile</a> objects. Most users of the <a href="mod:zipfile">zipfile</a> module
466.69 - will not need to create these, but only use those created by this
466.70 - module. <b>filename</b> should be the full name of the archive member, and
466.71 - <b>date_time</b> should be a tuple containing six fields which describe the time
466.72 - of the last modification to the file; the fields are described in section
466.73 - <code>zipinfo-objects</code>.
466.74 -
466.75 -<br><br>
466.76 -<a href="func:is_zipfile(filename)">is_zipfile(filename)</a>
466.77 -
466.78 -<br><br>
466.79 - Returns <code>True</code> if <b>filename</b> is a valid ZIP file based on its magic number,
466.80 - otherwise returns <code>False</code>. This module does not currently handle ZIP files
466.81 - which have appended comments.
466.82 -
466.83 -<br><br>
466.84 -<a href="data:ZIP_STORED">ZIP_STORED</a>
466.85 -
466.86 -<br><br>
466.87 - The numeric constant for an uncompressed archive member.
466.88 -
466.89 -<br><br>
466.90 -<a href="data:ZIP_DEFLATED">ZIP_DEFLATED</a>
466.91 -
466.92 -<br><br>
466.93 - The numeric constant for the usual ZIP compression method. This requires the
466.94 - zlib module. No other compression methods are currently supported.
466.95 -<div style="margin: 5px 5px; background: #ddffdd; border-size: 1px; padding: 5px"><b>See Also</b>:
466.96 -
466.97 -<br><br>
466.98 - `PKZIP Application Note <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_
466.99 - Documentation on the ZIP file format by Phil Katz, the creator of the format and
466.100 - algorithms used.
466.101 -
466.102 -<br><br>
466.103 - `Info-ZIP Home Page <http://www.info-zip.org/>`_
466.104 - Information about the Info-ZIP project's ZIP archive programs and development
466.105 - libraries.
466.106 -</div>
466.107 -<h3>ZipFile Objects
466.108 -</h3>
466.109 -<a href="class:ZipFile(file[, mode[, compression[, allowZip64]]])">ZipFile(file[, mode[, compression[, allowZip64]]])</a>
466.110 -
466.111 -<br><br>
466.112 - Open a ZIP file, where <b>file</b> can be either a path to a file (a string) or a
466.113 - file-like object. The <b>mode</b> parameter should be <code>'r'</code> to read an existing
466.114 - file, <code>'w'</code> to truncate and write a new file, or <code>'a'</code> to append to an
466.115 - existing file. If <b>mode</b> is <code>'a'</code> and <b>file</b> refers to an existing ZIP file,
466.116 - then additional files are added to it. If <b>file</b> does not refer to a ZIP file,
466.117 - then a new ZIP archive is appended to the file. This is meant for adding a ZIP
466.118 - archive to another file, such as :file:`python.exe`. Using ::
466.119 -
466.120 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
466.121 - <span style="">cat</span> <span style="">myzip</span><span style="">.</span><span style="">zip</span> <span style="">>></span> <span style="">python</span><span style="">.</span><span style="">exe</span><span style="color:#000000;"><br></span></pre>
466.122 - also works, and at least :program:<code>WinZip</code> can read such files. If <b>mode</b> is
466.123 - <code>a</code> and the file does not exist at all, it is created. <b>compression</b> is the
466.124 - ZIP compression method to use when writing the archive, and should be
466.125 - :const:<code>ZIP_STORED</code> or :const:<code>ZIP_DEFLATED</code>; unrecognized values will cause
466.126 - <a href="exc:RuntimeError">RuntimeError</a> to be raised. If :const:<code>ZIP_DEFLATED</code> is specified but the
466.127 - <a href="mod:zlib">zlib</a> module is not available, <a href="exc:RuntimeError">RuntimeError</a> is also raised. The
466.128 - default is :const:<code>ZIP_STORED</code>. If <b>allowZip64</b> is <code>True</code> zipfile will create
466.129 - ZIP files that use the ZIP64 extensions when the zipfile is larger than 2 GB. If
466.130 - it is false (the default) <a href="mod:zipfile">zipfile</a> will raise an exception when the ZIP
466.131 - file would require ZIP64 extensions. ZIP64 extensions are disabled by default
466.132 - because the default :program:<code>zip</code> and :program:<code>unzip</code> commands on Unix (the
466.133 - InfoZIP utilities) don't support these extensions.
466.134 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.6
466.135 - If the file does not exist, it is created if the mode is 'a'.
466.136 -</div>
466.137 -<a href="meth:ZipFile.close()">ZipFile.close()</a>
466.138 - Close the archive file. You must call <a href="meth:close">close</a> before exiting your program
466.139 - or essential records will not be written.
466.140 -
466.141 -<br><br>
466.142 -<a href="meth:ZipFile.getinfo(name)">ZipFile.getinfo(name)</a>
466.143 -
466.144 -<br><br>
466.145 - Return a <a href="class:ZipInfo">ZipInfo</a> object with information about the archive member
466.146 - <b>name</b>. Calling <a href="meth:getinfo">getinfo</a> for a name not currently contained in the
466.147 - archive will raise a <a href="exc:KeyError">KeyError</a>.
466.148 -
466.149 -<br><br>
466.150 -<a href="meth:ZipFile.infolist()">ZipFile.infolist()</a>
466.151 -
466.152 -<br><br>
466.153 - Return a list containing a <a href="class:ZipInfo">ZipInfo</a> object for each member of the
466.154 - archive. The objects are in the same order as their entries in the actual ZIP
466.155 - file on disk if an existing archive was opened.
466.156 -
466.157 -<br><br>
466.158 -<a href="meth:ZipFile.namelist()">ZipFile.namelist()</a>
466.159 -
466.160 -<br><br>
466.161 - Return a list of archive members by name.
466.162 -
466.163 -<br><br>
466.164 -<a href="meth:ZipFile.open(name[, mode[, pwd]])">ZipFile.open(name[, mode[, pwd]])</a>
466.165 -
466.166 -<br><br>
466.167 - Extract a member from the archive as a file-like object (ZipExtFile). <b>name</b> is
466.168 - the name of the file in the archive, or a <a href="class:ZipInfo">ZipInfo</a> object. The <b>mode</b>
466.169 - parameter, if included, must be one of the following: <code>'r'</code> (the default),
466.170 - <code>'U'</code>, or <code>'rU'</code>. Choosing <code>'U'</code> or <code>'rU'</code> will enable universal newline
466.171 - support in the read-only object. <b>pwd</b> is the password used for encrypted files.
466.172 - Calling <a href="meth:open">open</a> on a closed ZipFile will raise a <a href="exc:RuntimeError">RuntimeError</a>.
466.173 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
466.174 -
466.175 -<br><br>
466.176 - The file-like object is read-only and provides the following methods:
466.177 - <a href="meth:read">read</a>, <a href="meth:readline">readline</a>, <a href="meth:readlines">readlines</a>, <a href="meth:__iter__">__iter__</a>,
466.178 - <a href="meth:next">next</a>.
466.179 -</div>
466.180 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
466.181 - If the ZipFile was created by passing in a file-like object as the first
466.182 - argument to the constructor, then the object returned by <a href="meth:.open">.open</a> shares the
466.183 - ZipFile's file pointer. Under these circumstances, the object returned by
466.184 - <a href="meth:.open">.open</a> should not be used after any additional operations are performed
466.185 - on the ZipFile object. If the ZipFile was created by passing in a string (the
466.186 - filename) as the first argument to the constructor, then <a href="meth:.open">.open</a> will
466.187 - create a new file object that will be held by the ZipExtFile, allowing it to
466.188 - operate independently of the ZipFile.
466.189 -</div>
466.190 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
466.191 - The <a href="meth:open">open</a>, <a href="meth:read">read</a> and <a href="meth:extract">extract</a> methods can take a filename
466.192 - or a <a href="class:ZipInfo">ZipInfo</a> object. You will appreciate this when trying to read a
466.193 - ZIP file that contains members with duplicate names.
466.194 -</div>
466.195 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
466.196 -</div>
466.197 -<a href="meth:ZipFile.extract(member[, path[, pwd]])">ZipFile.extract(member[, path[, pwd]])</a>
466.198 - Extract a member from the archive to the current working directory; <b>member</b>
466.199 - must be its full name or a <a href="class:ZipInfo">ZipInfo</a> object). Its file information is
466.200 - extracted as accurately as possible. <b>path</b> specifies a different directory
466.201 - to extract to. <b>member</b> can be a filename or a <a href="class:ZipInfo">ZipInfo</a> object.
466.202 - <b>pwd</b> is the password used for encrypted files.
466.203 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
466.204 -</div>
466.205 -<a href="meth:ZipFile.extractall([path[, members[, pwd]]])">ZipFile.extractall([path[, members[, pwd]]])</a>
466.206 - Extract all members from the archive to the current working directory. <b>path</b>
466.207 - specifies a different directory to extract to. <b>members</b> is optional and must
466.208 - be a subset of the list returned by <a href="meth:namelist">namelist</a>. <b>pwd</b> is the password
466.209 - used for encrypted files.
466.210 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
466.211 -</div>
466.212 -<a href="meth:ZipFile.printdir()">ZipFile.printdir()</a>
466.213 - Print a table of contents for the archive to <code>sys.stdout</code>.
466.214 -
466.215 -<br><br>
466.216 -<a href="meth:ZipFile.setpassword(pwd)">ZipFile.setpassword(pwd)</a>
466.217 -
466.218 -<br><br>
466.219 - Set <b>pwd</b> as default password to extract encrypted files.
466.220 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Added</b>: 2.6
466.221 -</div>
466.222 -<a href="meth:ZipFile.read(name[, pwd])">ZipFile.read(name[, pwd])</a>
466.223 - Return the bytes of the file <b>name</b> in the archive. <b>name</b> is the name of the
466.224 - file in the archive, or a <a href="class:ZipInfo">ZipInfo</a> object. The archive must be open for
466.225 - read or append. <b>pwd</b> is the password used for encrypted files and, if specified,
466.226 - it will override the default password set with <a href="meth:setpassword">setpassword</a>. Calling
466.227 - <a href="meth:read">read</a> on a closed ZipFile will raise a <a href="exc:RuntimeError">RuntimeError</a>.
466.228 -<div style="margin: 5px 5px; background: #dddddd; border-size: 1px; padding: 5px"><b>Version Changed</b>: 2.6
466.229 - <b>pwd</b> was added, and <b>name</b> can now be a <a href="class:ZipInfo">ZipInfo</a> object.
466.230 -</div>
466.231 -<a href="meth:ZipFile.testzip()">ZipFile.testzip()</a>
466.232 - Read all the files in the archive and check their CRC's and file headers.
466.233 - Return the name of the first bad file, or else return <code>None</code>. Calling
466.234 - <a href="meth:testzip">testzip</a> on a closed ZipFile will raise a <a href="exc:RuntimeError">RuntimeError</a>.
466.235 -
466.236 -<br><br>
466.237 -<a href="meth:ZipFile.write(filename[, arcname[, compress_type]])">ZipFile.write(filename[, arcname[, compress_type]])</a>
466.238 -
466.239 -<br><br>
466.240 - Write the file named <b>filename</b> to the archive, giving it the archive name
466.241 - <b>arcname</b> (by default, this will be the same as <b>filename</b>, but without a drive
466.242 - letter and with leading path separators removed). If given, <b>compress_type</b>
466.243 - overrides the value given for the <b>compression</b> parameter to the constructor for
466.244 - the new entry. The archive must be open with mode <code>'w'</code> or <code>'a'</code> -- calling
466.245 - <a href="meth:write">write</a> on a ZipFile created with mode <code>'r'</code> will raise a
466.246 - <a href="exc:RuntimeError">RuntimeError</a>. Calling <a href="meth:write">write</a> on a closed ZipFile will raise a
466.247 - <a href="exc:RuntimeError">RuntimeError</a>.
466.248 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
466.249 -
466.250 -<br><br>
466.251 - There is no official file name encoding for ZIP files. If you have unicode file
466.252 - names, you must convert them to byte strings in your desired encoding before
466.253 - passing them to <a href="meth:write">write</a>. WinZip interprets all file names as encoded in
466.254 - CP437, also known as DOS Latin.
466.255 -</div>
466.256 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
466.257 - Archive names should be relative to the archive root, that is, they should not
466.258 - start with a path separator.
466.259 -</div>
466.260 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
466.261 - If <code>arcname</code> (or <code>filename</code>, if <code>arcname</code> is not given) contains a null
466.262 - byte, the name of the file in the archive will be truncated at the null byte.
466.263 -</div>
466.264 -<a href="meth:ZipFile.writestr(zinfo_or_arcname, bytes)">ZipFile.writestr(zinfo_or_arcname, bytes)</a>
466.265 - Write the string <b>bytes</b> to the archive; <b>zinfo_or_arcname</b> is either the file
466.266 - name it will be given in the archive, or a <a href="class:ZipInfo">ZipInfo</a> instance. If it's
466.267 - an instance, at least the filename, date, and time must be given. If it's a
466.268 - name, the date and time is set to the current date and time. The archive must be
466.269 - opened with mode <code>'w'</code> or <code>'a'</code> -- calling <a href="meth:writestr">writestr</a> on a ZipFile
466.270 - created with mode <code>'r'</code> will raise a <a href="exc:RuntimeError">RuntimeError</a>. Calling
466.271 - <a href="meth:writestr">writestr</a> on a closed ZipFile will raise a <a href="exc:RuntimeError">RuntimeError</a>.
466.272 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
466.273 -
466.274 -<br><br>
466.275 - When passing a <a href="class:ZipInfo">ZipInfo</a> instance as the <b>zinfo_or_acrname</b> parameter,
466.276 - the compression method used will be that specified in the <b>compress_type</b>
466.277 - member of the given <a href="class:ZipInfo">ZipInfo</a> instance. By default, the
466.278 - <a href="class:ZipInfo">ZipInfo</a> constructor sets this member to :const:<code>ZIP_STORED</code>.
466.279 -</div>
466.280 -The following data attributes are also available:
466.281 -<a href="attr:ZipFile.debug">ZipFile.debug</a>
466.282 -
466.283 -<br><br>
466.284 - The level of debug output to use. This may be set from <code>0</code> (the default, no
466.285 - output) to <code>3</code> (the most output). Debugging information is written to
466.286 - <code>sys.stdout</code>.
466.287 -
466.288 -<br><br>
466.289 -<a href="attr:ZipFile.comment">ZipFile.comment</a>
466.290 -
466.291 -<br><br>
466.292 - The comment text associated with the ZIP file. If assigning a comment to a
466.293 - <a href="class:ZipFile">ZipFile</a> instance created with mode 'a' or 'w', this should be a
466.294 - string no longer than 65535 bytes. Comments longer than this will be
466.295 - truncated in the written archive when <a href="meth:ZipFile.close">ZipFile.close</a> is called.
466.296 -
466.297 -<br><br>
466.298 -
466.299 -<br><br>
466.300 -<h3>PyZipFile Objects
466.301 -</h3>
466.302 -The <a href="class:PyZipFile">PyZipFile</a> constructor takes the same parameters as the
466.303 -<a href="class:ZipFile">ZipFile</a> constructor. Instances have one method in addition to those of
466.304 -<a href="class:ZipFile">ZipFile</a> objects.
466.305 -
466.306 -<br><br>
466.307 -<a href="meth:PyZipFile.writepy(pathname[, basename])">PyZipFile.writepy(pathname[, basename])</a>
466.308 -
466.309 -<br><br>
466.310 - Search for files :file:`\*.py` and add the corresponding file to the archive.
466.311 - The corresponding file is a :file:`\*.pyo` file if available, else a
466.312 - :file:`\*.pyc` file, compiling if necessary. If the pathname is a file, the
466.313 - filename must end with :file:`.py`, and just the (corresponding
466.314 - :file:`\*.py[co]`) file is added at the top level (no path information). If the
466.315 - pathname is a file that does not end with :file:`.py`, a <a href="exc:RuntimeError">RuntimeError</a>
466.316 - will be raised. If it is a directory, and the directory is not a package
466.317 - directory, then all the files :file:`\*.py[co]` are added at the top level. If
466.318 - the directory is a package directory, then all :file:`\*.py[co]` are added under
466.319 - the package name as a file path, and if any subdirectories are package
466.320 - directories, all of these are added recursively. <b>basename</b> is intended for
466.321 - internal use only. The <a href="meth:writepy">writepy</a> method makes archives with file names
466.322 - like this::
466.323 -
466.324 -
466.325 -<pre style="border-color: #dddddd; border-style: solid; border-width: 1px; color:#000000;">
466.326 - <span style="">string</span><span style="">.</span><span style="">pyc</span> <span style="color:#969696"><span style="color:#969696;"># Top level name </span></span><span style="color:#000000;"><br></span> <span style="">test</span><span style="">/</span><span style="">__init__</span><span style="">.</span><span style="">pyc</span> <span style="color:#969696"><span style="color:#969696;"># Package directory </span></span><span style="color:#000000;"><br></span> <span style="">test</span><span style="">/</span><span style="">test_support</span><span style="">.</span><span style="">pyc</span> <span style="color:#969696"><span style="color:#969696;"># Module test.test_support</span></span><span style="color:#000000;"><br></span> <span style="">test</span><span style="">/</span><span style="">bogus</span><span style="">/</span><span style="">__init__</span><span style="">.</span><span style="">pyc</span> <span style="color:#969696"><span style="color:#969696;"># Subpackage directory </span></span><span style="color:#000000;"><br></span> <span style="">test</span><span style="">/</span><span style="">bogus</span><span style="">/</span><span style="">myfile</span><span style="">.</span><span style="">pyc</span> <span style="color:#969696"><span style="color:#969696;"># Submodule test.bogus.myfile</span></span><span style="color:#000000;"><br></span></pre>
466.327 -<h3>ZipInfo Objects
466.328 -</h3>
466.329 -Instances of the <a href="class:ZipInfo">ZipInfo</a> class are returned by the <a href="meth:getinfo">getinfo</a> and
466.330 -<a href="meth:infolist">infolist</a> methods of <a href="class:ZipFile">ZipFile</a> objects. Each object stores
466.331 -information about a single member of the ZIP archive.
466.332 -
466.333 -<br><br>
466.334 -Instances have the following attributes:
466.335 -
466.336 -<br><br>
466.337 -<a href="attr:ZipInfo.filename">ZipInfo.filename</a>
466.338 -
466.339 -<br><br>
466.340 - Name of the file in the archive.
466.341 -
466.342 -<br><br>
466.343 -<a href="attr:ZipInfo.date_time">ZipInfo.date_time</a>
466.344 -
466.345 -<br><br>
466.346 - The time and date of the last modification to the archive member. This is a
466.347 - tuple of six values:
466.348 -
466.349 -<br><br>
466.350 -<pre> +-------+--------------------------+
466.351 - | Index | Value |
466.352 - +=======+==========================+
466.353 - | ``0`` | Year |
466.354 - +-------+--------------------------+
466.355 - | ``1`` | Month (one-based) |
466.356 - +-------+--------------------------+
466.357 - | ``2`` | Day of month (one-based) |
466.358 - +-------+--------------------------+
466.359 - | ``3`` | Hours (zero-based) |
466.360 - +-------+--------------------------+
466.361 - | ``4`` | Minutes (zero-based) |
466.362 - +-------+--------------------------+
466.363 - | ``5`` | Seconds (zero-based) |
466.364 - +-------+--------------------------+
466.365 -</pre>
466.366 -<a href="attr:ZipInfo.compress_type">ZipInfo.compress_type</a>
466.367 -
466.368 -<br><br>
466.369 - Type of compression for the archive member.
466.370 -
466.371 -<br><br>
466.372 -<a href="attr:ZipInfo.comment">ZipInfo.comment</a>
466.373 -
466.374 -<br><br>
466.375 - Comment for the individual archive member.
466.376 -
466.377 -<br><br>
466.378 -<a href="attr:ZipInfo.extra">ZipInfo.extra</a>
466.379 -
466.380 -<br><br>
466.381 - Expansion field data. The `PKZIP Application Note
466.382 - <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_ contains
466.383 - some comments on the internal structure of the data contained in this string.
466.384 -
466.385 -<br><br>
466.386 -<a href="attr:ZipInfo.create_system">ZipInfo.create_system</a>
466.387 -
466.388 -<br><br>
466.389 - System which created ZIP archive.
466.390 -
466.391 -<br><br>
466.392 -<a href="attr:ZipInfo.create_version">ZipInfo.create_version</a>
466.393 -
466.394 -<br><br>
466.395 - PKZIP version which created ZIP archive.
466.396 -
466.397 -<br><br>
466.398 -<a href="attr:ZipInfo.extract_version">ZipInfo.extract_version</a>
466.399 -
466.400 -<br><br>
466.401 - PKZIP version needed to extract archive.
466.402 -
466.403 -<br><br>
466.404 -<a href="attr:ZipInfo.reserved">ZipInfo.reserved</a>
466.405 -
466.406 -<br><br>
466.407 - Must be zero.
466.408 -
466.409 -<br><br>
466.410 -<a href="attr:ZipInfo.flag_bits">ZipInfo.flag_bits</a>
466.411 -
466.412 -<br><br>
466.413 - ZIP flag bits.
466.414 -
466.415 -<br><br>
466.416 -<a href="attr:ZipInfo.volume">ZipInfo.volume</a>
466.417 -
466.418 -<br><br>
466.419 - Volume number of file header.
466.420 -
466.421 -<br><br>
466.422 -<a href="attr:ZipInfo.internal_attr">ZipInfo.internal_attr</a>
466.423 -
466.424 -<br><br>
466.425 - Internal attributes.
466.426 -
466.427 -<br><br>
466.428 -<a href="attr:ZipInfo.external_attr">ZipInfo.external_attr</a>
466.429 -
466.430 -<br><br>
466.431 - External file attributes.
466.432 -
466.433 -<br><br>
466.434 -<a href="attr:ZipInfo.header_offset">ZipInfo.header_offset</a>
466.435 -
466.436 -<br><br>
466.437 - Byte offset to the file header.
466.438 -
466.439 -<br><br>
466.440 -<a href="attr:ZipInfo.CRC">ZipInfo.CRC</a>
466.441 -
466.442 -<br><br>
466.443 - CRC-32 of the uncompressed file.
466.444 -
466.445 -<br><br>
466.446 -<a href="attr:ZipInfo.compress_size">ZipInfo.compress_size</a>
466.447 -
466.448 -<br><br>
466.449 - Size of the compressed data.
466.450 -
466.451 -<br><br>
466.452 -<a href="attr:ZipInfo.file_size">ZipInfo.file_size</a>
466.453 -
466.454 -<br><br>
466.455 - Size of the uncompressed file.
466.456 -</body></html>
467.1 --- a/python.editor/test/unit/data/testfiles/rst/zipfile.rst.indexed Sun Jan 04 13:11:53 2015 -0600
467.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
467.3 @@ -1,113 +0,0 @@
467.4 -
467.5 -
467.6 -Document 0
467.7 -Searchable Keys:
467.8 - class : BadZipfile
467.9 - class-ig : badzipfile
467.10 - extends : Exception
467.11 - in : zipfile
467.12 -
467.13 -Not Searchable Keys:
467.14 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
467.15 -
467.16 -
467.17 -Document 1
467.18 -Searchable Keys:
467.19 - class : LargeZipFile
467.20 - class-ig : largezipfile
467.21 - extends : Exception
467.22 - in : zipfile
467.23 -
467.24 -Not Searchable Keys:
467.25 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
467.26 -
467.27 -
467.28 -Document 2
467.29 -Searchable Keys:
467.30 - class : PyZipFile
467.31 - class-ig : pyzipfile
467.32 - in : zipfile
467.33 - member : writepy;F;|DOCUMENTED|DOC_ONLY|;pathname,basename;
467.34 -
467.35 -Not Searchable Keys:
467.36 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
467.37 -
467.38 -
467.39 -Document 3
467.40 -Searchable Keys:
467.41 - class : ZipFile
467.42 - class-ig : zipfile
467.43 - in : zipfile
467.44 -
467.45 -Not Searchable Keys:
467.46 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
467.47 -
467.48 -
467.49 -Document 4
467.50 -Searchable Keys:
467.51 - class : ZipFile
467.52 - class-ig : zipfile
467.53 - in : zipfile
467.54 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;file,mode,compression,allowZip64;
467.55 - member : close;F;|DOCUMENTED|DOC_ONLY|;;
467.56 - member : comment;A;|DOCUMENTED|DOC_ONLY|;
467.57 - member : debug;A;|DOCUMENTED|DOC_ONLY|;
467.58 - member : extract;F;|DOCUMENTED|DOC_ONLY|;member,path,pwd;
467.59 - member : extractall;F;|DOCUMENTED|DOC_ONLY|;path,members,pwd;
467.60 - member : getinfo;F;|DOCUMENTED|DOC_ONLY|;name;
467.61 - member : infolist;F;|DOCUMENTED|DOC_ONLY|;;
467.62 - member : namelist;F;|DOCUMENTED|DOC_ONLY|;;
467.63 - member : open;F;|DOCUMENTED|DOC_ONLY|;name,mode,pwd;
467.64 - member : printdir;F;|DOCUMENTED|DOC_ONLY|;;
467.65 - member : read;F;|DOCUMENTED|DOC_ONLY|;name,pwd;
467.66 - member : setpassword;F;|DOCUMENTED|DOC_ONLY|;pwd;
467.67 - member : testzip;F;|DOCUMENTED|DOC_ONLY|;;
467.68 - member : write;F;|DOCUMENTED|DOC_ONLY|;filename,arcname,compress_type;
467.69 - member : writestr;F;|DOCUMENTED|DOC_ONLY|;zinfo_or_arcname,bytes;
467.70 -
467.71 -Not Searchable Keys:
467.72 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
467.73 -
467.74 -
467.75 -Document 5
467.76 -Searchable Keys:
467.77 - class : ZipInfo
467.78 - class-ig : zipinfo
467.79 - in : zipfile
467.80 - member : CRC;A;|DOCUMENTED|DOC_ONLY|;
467.81 - member : __init__;c;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;filename,date_time;
467.82 - member : comment;A;|DOCUMENTED|DOC_ONLY|;
467.83 - member : compress_size;A;|DOCUMENTED|DOC_ONLY|;
467.84 - member : compress_type;A;|DOCUMENTED|DOC_ONLY|;
467.85 - member : create_system;A;|DOCUMENTED|DOC_ONLY|;
467.86 - member : create_version;A;|DOCUMENTED|DOC_ONLY|;
467.87 - member : date_time;A;|DOCUMENTED|DOC_ONLY|;
467.88 - member : external_attr;A;|DOCUMENTED|DOC_ONLY|;
467.89 - member : extra;A;|DOCUMENTED|DOC_ONLY|;
467.90 - member : extract_version;A;|DOCUMENTED|DOC_ONLY|;
467.91 - member : file_size;A;|DOCUMENTED|DOC_ONLY|;
467.92 - member : filename;A;|DOCUMENTED|DOC_ONLY|;
467.93 - member : flag_bits;A;|DOCUMENTED|DOC_ONLY|;
467.94 - member : header_offset;A;|DOCUMENTED|DOC_ONLY|;
467.95 - member : internal_attr;A;|DOCUMENTED|DOC_ONLY|;
467.96 - member : reserved;A;|DOCUMENTED|DOC_ONLY|;
467.97 - member : volume;A;|DOCUMENTED|DOC_ONLY|;
467.98 -
467.99 -Not Searchable Keys:
467.100 - clzattrs : ;|DOCUMENTED|CONSTRUCTOR|DOC_ONLY|;
467.101 -
467.102 -
467.103 -Document 6
467.104 -Searchable Keys:
467.105 - item : BadZipfile;C;|DOCUMENTED|DOC_ONLY|;
467.106 - item : LargeZipFile;C;|DOCUMENTED|DOC_ONLY|;
467.107 - item : PyZipFile;C;|DOCUMENTED|DOC_ONLY|;
467.108 - item : ZIP_DEFLATED;D;|DOCUMENTED|DOC_ONLY|;
467.109 - item : ZIP_STORED;D;|DOCUMENTED|DOC_ONLY|;
467.110 - item : ZipFile;C;|DOCUMENTED|DOC_ONLY|;
467.111 - item : ZipInfo;C;|DOCUMENTED|DOC_ONLY|;
467.112 - item : is_zipfile;F;|DOCUMENTED|DOC_ONLY|;filename;
467.113 - module : zipfile
467.114 -
467.115 -Not Searchable Keys:
467.116 - modattrs : S
468.1 --- a/python.editor/test/unit/data/testfiles/rst/zipfile.rst.testGetDoc1.html Sun Jan 04 13:11:53 2015 -0600
468.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
468.3 @@ -1,5 +0,0 @@
468.4 -<html><body><pre><b>ZIP_STORED</b></pre>
468.5 -
468.6 -<hr>
468.7 - The numeric constant for an uncompressed archive member.
468.8 -</body></html>
469.1 --- a/python.editor/test/unit/data/testfiles/rst/zipfile.rst.testGetDoc3.html Sun Jan 04 13:11:53 2015 -0600
469.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
469.3 @@ -1,27 +0,0 @@
469.4 -<html><body><pre><b>ZipFile.write</b><font color="#808080">(filename[, arcname[, compress_type]])</font></pre>
469.5 -<hr>
469.6 - Write the file named <b>filename</b> to the archive, giving it the archive name
469.7 - <b>arcname</b> (by default, this will be the same as <b>filename</b>, but without a drive
469.8 - letter and with leading path separators removed). If given, <b>compress_type</b>
469.9 - overrides the value given for the <b>compression</b> parameter to the constructor for
469.10 - the new entry. The archive must be open with mode <code>'w'</code> or <code>'a'</code> -- calling
469.11 - <a href="meth:write">write</a> on a ZipFile created with mode <code>'r'</code> will raise a
469.12 - <a href="exc:RuntimeError">RuntimeError</a>. Calling <a href="meth:write">write</a> on a closed ZipFile will raise a
469.13 - <a href="exc:RuntimeError">RuntimeError</a>.
469.14 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
469.15 -
469.16 -<br><br>
469.17 - There is no official file name encoding for ZIP files. If you have unicode file
469.18 - names, you must convert them to byte strings in your desired encoding before
469.19 - passing them to <a href="meth:write">write</a>. WinZip interprets all file names as encoded in
469.20 - CP437, also known as DOS Latin.
469.21 -</div>
469.22 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
469.23 - Archive names should be relative to the archive root, that is, they should not
469.24 - start with a path separator.
469.25 -</div>
469.26 -<div style="margin: 5px 5px; background: #ffdddd; border-size: 1px; padding: 5px"><b>NOTE</b>:
469.27 - If <code>arcname</code> (or <code>filename</code>, if <code>arcname</code> is not given) contains a null
469.28 - byte, the name of the file in the archive will be truncated at the null byte.
469.29 -</div>
469.30 -</body></html>
470.1 --- a/python.editor/test/unit/data/testfiles/samelinedef.py Sun Jan 04 13:11:53 2015 -0600
470.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
470.3 @@ -1,7 +0,0 @@
470.4 - # To be overridden -- handlers for unknown objects
470.5 - def unknown_starttag(self, tag, attrs): pass
470.6 - def unknown_endtag(self, tag): pass
470.7 - def unknown_charref(self, ref): pass
470.8 - def unknown_entityref(self, name):
470.9 - self.syntax_error("reference to unknown entity `&%s;'" % name)
470.10 -
471.1 --- a/python.editor/test/unit/data/testfiles/scope.py Sun Jan 04 13:11:53 2015 -0600
471.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
471.3 @@ -1,33 +0,0 @@
471.4 -import module1
471.5 -import module2
471.6 -import module3 as module4
471.7 -
471.8 -toplevelvar = 1
471.9 -toplevelvar2 = 2
471.10 -toplevelvar3 = 3
471.11 -toplevelvar4 = 4
471.12 -
471.13 -def myfunc(funcparam):
471.14 - localvar = 1
471.15 - toplevelvar4 = 6
471.16 - print toplevelvar4
471.17 - pass
471.18 -
471.19 -class MyClass(SuperClass):
471.20 - var_in_class = 1
471.21 - def mymethod(self,param1,param2):
471.22 - in_method = 1
471.23 - in_method = 2
471.24 - print in_method
471.25 - print var_in_class
471.26 - print toplevelvar
471.27 - toplevelvar3 = 3
471.28 - def myfunc():
471.29 - in_func = 1
471.30 - print in_method
471.31 - print in_func
471.32 - in_method = 2
471.33 -
471.34 - def othermethod(self,param3):
471.35 - pass
471.36 -
472.1 --- a/python.editor/test/unit/data/testfiles/scope.py.indexed Sun Jan 04 13:11:53 2015 -0600
472.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
472.3 @@ -1,29 +0,0 @@
472.4 -
472.5 -
472.6 -Document 0
472.7 -Searchable Keys:
472.8 - class : MyClass
472.9 - class-ig : myclass
472.10 - extends : SuperClass
472.11 - in : scope
472.12 - member : mymethod;F;;self,param1,param2;
472.13 - member : othermethod;F;;self,param3;
472.14 - member : var_in_class;D;;
472.15 -
472.16 -Not Searchable Keys:
472.17 -
472.18 -
472.19 -Document 1
472.20 -Searchable Keys:
472.21 - item : MyClass;C;;
472.22 - item : module1;I;;
472.23 - item : module2;I;;
472.24 - item : module4;I;;
472.25 - item : myfunc;F;;funcparam;
472.26 - item : toplevelvar2;D;;
472.27 - item : toplevelvar3;D;;
472.28 - item : toplevelvar4;D;;
472.29 - item : toplevelvar;D;;
472.30 - module : scope
472.31 -
472.32 -Not Searchable Keys:
473.1 --- a/python.editor/test/unit/data/testfiles/scope.py.scopes Sun Jan 04 13:11:53 2015 -0600
473.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
473.3 @@ -1,46 +0,0 @@
473.4 -=============================================
473.5 -<file-top>: Module : OffsetRange[0,625>
473.6 -MyClass [bound][class][def][node=ClassDef]
473.7 -SuperClass [read][UNRESOLVED][node=Name]
473.8 -module1 [bound][imported][data][node=Import]
473.9 -module2 [bound][imported][data][node=Import]
473.10 -module4 [bound][imported][data][node=Import]
473.11 -myfunc [bound][function][def][node=FunctionDef]
473.12 -toplevelvar [bound][data][read][node=Name]
473.13 -toplevelvar2 [bound][data][node=Name]
473.14 -toplevelvar3 [bound][data][node=Name]
473.15 -toplevelvar4 [bound][data][node=Name]
473.16 -
473.17 - =============================================
473.18 - myfunc: FunctionDef : OffsetRange[125,219>
473.19 - funcparam [bound][param][data][unused][node=Name]
473.20 - localvar [bound][data][unused][node=Name]
473.21 - toplevelvar4 [bound][data][read][node=Name]
473.22 -
473.23 - =============================================
473.24 - class MyClass: ClassDef : OffsetRange[219,625>
473.25 - mymethod [bound][function][def][node=FunctionDef]
473.26 - othermethod [bound][function][def][node=FunctionDef]
473.27 - var_in_class [bound][data][node=Name]
473.28 -
473.29 - =============================================
473.30 - mymethod: FunctionDef : OffsetRange[271,581>
473.31 - in_method [bound][data][read][node=Name]
473.32 - myfunc [bound][function][def][node=FunctionDef]
473.33 - param1 [bound][param][data][unused][node=Name]
473.34 - param2 [bound][param][data][unused][node=Name]
473.35 - self [bound][param][data][unused][node=Name]
473.36 - toplevelvar [free][read][node=Name]
473.37 - toplevelvar3 [bound][data][unused][node=Name]
473.38 - var_in_class [free][read][node=Name]
473.39 -
473.40 - =============================================
473.41 - myfunc: FunctionDef : OffsetRange[459,581>
473.42 - in_func [bound][data][read][node=Name]
473.43 - in_method [bound][data][read][node=Name]
473.44 -
473.45 - =============================================
473.46 - othermethod: FunctionDef : OffsetRange[582,625>
473.47 - param3 [bound][param][data][unused][node=Name]
473.48 - self [bound][param][data][unused][node=Name]
473.49 -
474.1 --- a/python.editor/test/unit/data/testfiles/scope2.py Sun Jan 04 13:11:53 2015 -0600
474.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
474.3 @@ -1,4 +0,0 @@
474.4 -x = 1
474.5 -def foo():
474.6 - print x
474.7 -
475.1 --- a/python.editor/test/unit/data/testfiles/scope2.py.scopes Sun Jan 04 13:11:53 2015 -0600
475.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
475.3 @@ -1,9 +0,0 @@
475.4 -=============================================
475.5 -<file-top>: Module : OffsetRange[0,29>
475.6 -foo [bound][function][def][node=FunctionDef]
475.7 -x [bound][data][read][node=Name]
475.8 -
475.9 - =============================================
475.10 - foo: FunctionDef : OffsetRange[6,29>
475.11 - x [free][read][node=Name]
475.12 -
476.1 --- a/python.editor/test/unit/data/testfiles/scope3.py Sun Jan 04 13:11:53 2015 -0600
476.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
476.3 @@ -1,10 +0,0 @@
476.4 -__all__ = [ "MyPublicClass" ]
476.5 -
476.6 -class MyPublicClass:
476.7 - def mymethod(self):
476.8 - pass
476.9 -
476.10 -class MyPrivateClass:
476.11 - def mymethod2(self):
476.12 - pass
476.13 -
477.1 --- a/python.editor/test/unit/data/testfiles/scope3.py.scopes Sun Jan 04 13:11:53 2015 -0600
477.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
477.3 @@ -1,22 +0,0 @@
477.4 -=============================================
477.5 -<file-top>: Module : OffsetRange[0,150>
477.6 -MyPrivateClass [bound][private][class][def][node=ClassDef]
477.7 -MyPublicClass [bound][class][def][node=ClassDef]
477.8 -__all__ [bound][data][node=Name]
477.9 -
477.10 - =============================================
477.11 - class MyPublicClass: ClassDef : OffsetRange[31,90>
477.12 - mymethod [bound][function][def][node=FunctionDef]
477.13 -
477.14 - =============================================
477.15 - mymethod: FunctionDef : OffsetRange[56,90>
477.16 - self [bound][param][data][unused][node=Name]
477.17 -
477.18 - =============================================
477.19 - class MyPrivateClass: ClassDef : OffsetRange[90,150>
477.20 - mymethod2 [bound][private][function][def][node=FunctionDef]
477.21 -
477.22 - =============================================
477.23 - mymethod2: FunctionDef : OffsetRange[116,150>
477.24 - self [bound][param][private][data][unused][node=Name]
477.25 -
478.1 --- a/python.editor/test/unit/data/testfiles/simple.py Sun Jan 04 13:11:53 2015 -0600
478.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
478.3 @@ -1,2 +0,0 @@
478.4 -x = 1
478.5 -y = 2
479.1 --- a/python.editor/test/unit/data/testfiles/simple.py.testHint4.hints Sun Jan 04 13:11:53 2015 -0600
479.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
479.3 @@ -1,7 +0,0 @@
479.4 -x = 1
479.5 -
479.6 -HINT:Surround With...
479.7 -FIX:Surround With Try/Except
479.8 -FIX:Surround With Try/Except/Finally
479.9 -FIX:Surround With Try/Finally
479.10 -y = 2^
480.1 --- a/python.editor/test/unit/data/testfiles/socket.py Sun Jan 04 13:11:53 2015 -0600
480.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
480.3 @@ -1,1368 +0,0 @@
480.4 -"""
480.5 -This is an updated socket module for use on JVMs > 1.4; it is derived from the
480.6 -old jython socket module.
480.7 -The primary extra it provides is non-blocking support.
480.8 -
480.9 -XXX Restrictions:
480.10 -
480.11 -- Only INET sockets
480.12 -- No asynchronous behavior
480.13 -- No socket options
480.14 -- Can't do a very good gethostbyaddr() right...
480.15 -AMAK: 20050527: added socket timeouts
480.16 -AMAK: 20070515: Added non-blocking (asynchronous) support
480.17 -AMAK: 20070515: Added client-side SSL support
480.18 -AMAK: 20080513: Added support for options
480.19 -"""
480.20 -
480.21 -_defaulttimeout = None
480.22 -
480.23 -import errno
480.24 -import jarray
480.25 -import string
480.26 -import struct
480.27 -import sys
480.28 -import threading
480.29 -import time
480.30 -import types
480.31 -
480.32 -# Java.io classes
480.33 -import java.io.BufferedInputStream
480.34 -import java.io.BufferedOutputStream
480.35 -# Java.io exceptions
480.36 -import java.io.InterruptedIOException
480.37 -import java.io.IOException
480.38 -
480.39 -# Java.lang classes
480.40 -import java.lang.String
480.41 -# Java.lang exceptions
480.42 -import java.lang.Exception
480.43 -
480.44 -# Java.net classes
480.45 -import java.net.DatagramPacket
480.46 -import java.net.InetAddress
480.47 -import java.net.InetSocketAddress
480.48 -import java.net.Socket
480.49 -# Java.net exceptions
480.50 -import java.net.BindException
480.51 -import java.net.ConnectException
480.52 -import java.net.NoRouteToHostException
480.53 -import java.net.PortUnreachableException
480.54 -import java.net.ProtocolException
480.55 -import java.net.SocketException
480.56 -import java.net.SocketTimeoutException
480.57 -import java.net.UnknownHostException
480.58 -
480.59 -# Java.nio classes
480.60 -import java.nio.ByteBuffer
480.61 -import java.nio.channels.DatagramChannel
480.62 -import java.nio.channels.ServerSocketChannel
480.63 -import java.nio.channels.SocketChannel
480.64 -# Java.nio exceptions
480.65 -import java.nio.channels.AlreadyConnectedException
480.66 -import java.nio.channels.AsynchronousCloseException
480.67 -import java.nio.channels.CancelledKeyException
480.68 -import java.nio.channels.ClosedByInterruptException
480.69 -import java.nio.channels.ClosedChannelException
480.70 -import java.nio.channels.ClosedSelectorException
480.71 -import java.nio.channels.ConnectionPendingException
480.72 -import java.nio.channels.IllegalBlockingModeException
480.73 -import java.nio.channels.IllegalSelectorException
480.74 -import java.nio.channels.NoConnectionPendingException
480.75 -import java.nio.channels.NonReadableChannelException
480.76 -import java.nio.channels.NonWritableChannelException
480.77 -import java.nio.channels.NotYetBoundException
480.78 -import java.nio.channels.NotYetConnectedException
480.79 -import java.nio.channels.UnresolvedAddressException
480.80 -import java.nio.channels.UnsupportedAddressTypeException
480.81 -
480.82 -import javax.net.ssl.SSLSocketFactory
480.83 -
480.84 -import org.python.core.io.DatagramSocketIO
480.85 -import org.python.core.io.ServerSocketIO
480.86 -import org.python.core.io.SocketIO
480.87 -from org.python.core.Py import newString as asPyString
480.88 -
480.89 -class error(Exception): pass
480.90 -class herror(error): pass
480.91 -class gaierror(error): pass
480.92 -class timeout(error): pass
480.93 -
480.94 -ALL = None
480.95 -
480.96 -_exception_map = {
480.97 -
480.98 -# (<javaexception>, <circumstance>) : lambda: <code that raises the python equivalent>, or None to stub out as unmapped
480.99 -
480.100 -(java.io.IOException, ALL) : lambda: error(errno.ECONNRESET, 'Software caused connection abort'),
480.101 -(java.io.InterruptedIOException, ALL) : lambda: timeout('timed out'),
480.102 -
480.103 -(java.net.BindException, ALL) : lambda: error(errno.EADDRINUSE, 'Address already in use'),
480.104 -(java.net.ConnectException, ALL) : lambda: error(errno.ECONNREFUSED, 'Connection refused'),
480.105 -(java.net.NoRouteToHostException, ALL) : None,
480.106 -(java.net.PortUnreachableException, ALL) : None,
480.107 -(java.net.ProtocolException, ALL) : None,
480.108 -(java.net.SocketException, ALL) : None,
480.109 -(java.net.SocketTimeoutException, ALL) : lambda: timeout('timed out'),
480.110 -(java.net.UnknownHostException, ALL) : lambda: gaierror(errno.EGETADDRINFOFAILED, 'getaddrinfo failed'),
480.111 -
480.112 -(java.nio.channels.AlreadyConnectedException, ALL) : lambda: error(errno.EISCONN, 'Socket is already connected'),
480.113 -(java.nio.channels.AsynchronousCloseException, ALL) : None,
480.114 -(java.nio.channels.CancelledKeyException, ALL) : None,
480.115 -(java.nio.channels.ClosedByInterruptException, ALL) : None,
480.116 -(java.nio.channels.ClosedChannelException, ALL) : lambda: error(errno.EPIPE, 'Socket closed'),
480.117 -(java.nio.channels.ClosedSelectorException, ALL) : None,
480.118 -(java.nio.channels.ConnectionPendingException, ALL) : None,
480.119 -(java.nio.channels.IllegalBlockingModeException, ALL) : None,
480.120 -(java.nio.channels.IllegalSelectorException, ALL) : None,
480.121 -(java.nio.channels.NoConnectionPendingException, ALL) : None,
480.122 -(java.nio.channels.NonReadableChannelException, ALL) : None,
480.123 -(java.nio.channels.NonWritableChannelException, ALL) : None,
480.124 -(java.nio.channels.NotYetBoundException, ALL) : None,
480.125 -(java.nio.channels.NotYetConnectedException, ALL) : None,
480.126 -(java.nio.channels.UnresolvedAddressException, ALL) : lambda: gaierror(errno.EGETADDRINFOFAILED, 'getaddrinfo failed'),
480.127 -(java.nio.channels.UnsupportedAddressTypeException, ALL) : None,
480.128 -
480.129 -}
480.130 -
480.131 -def would_block_error(exc=None):
480.132 - return error(errno.EWOULDBLOCK, 'The socket operation could not complete without blocking')
480.133 -
480.134 -def _map_exception(exc, circumstance=ALL):
480.135 -# print "Mapping exception: %s" % exc
480.136 - mapped_exception = _exception_map.get((exc.__class__, circumstance))
480.137 - if mapped_exception:
480.138 - exception = mapped_exception()
480.139 - else:
480.140 - exception = error(-1, 'Unmapped exception: %s' % exc)
480.141 - exception.java_exception = exc
480.142 - return exception
480.143 -
480.144 -MODE_BLOCKING = 'block'
480.145 -MODE_NONBLOCKING = 'nonblock'
480.146 -MODE_TIMEOUT = 'timeout'
480.147 -
480.148 -_permitted_modes = (MODE_BLOCKING, MODE_NONBLOCKING, MODE_TIMEOUT)
480.149 -
480.150 -SHUT_RD = 0
480.151 -SHUT_WR = 1
480.152 -SHUT_RDWR = 2
480.153 -
480.154 -__all__ = ['AF_UNSPEC', 'AF_INET', 'AF_INET6', 'AI_PASSIVE', 'SOCK_DGRAM',
480.155 - 'SOCK_RAW', 'SOCK_RDM', 'SOCK_SEQPACKET', 'SOCK_STREAM', 'SOL_SOCKET',
480.156 - 'SO_BROADCAST', 'SO_ERROR', 'SO_KEEPALIVE', 'SO_LINGER', 'SO_OOBINLINE',
480.157 - 'SO_RCVBUF', 'SO_REUSEADDR', 'SO_SNDBUF', 'SO_TIMEOUT', 'TCP_NODELAY',
480.158 - 'SocketType', 'error', 'herror', 'gaierror', 'timeout',
480.159 - 'getfqdn', 'gethostbyaddr', 'gethostbyname', 'gethostname',
480.160 - 'socket', 'getaddrinfo', 'getdefaulttimeout', 'setdefaulttimeout',
480.161 - 'has_ipv6', 'htons', 'htonl', 'ntohs', 'ntohl',
480.162 - 'SHUT_RD', 'SHUT_WR', 'SHUT_RDWR',
480.163 - ]
480.164 -
480.165 -AF_UNSPEC = 0
480.166 -AF_INET = 2
480.167 -AF_INET6 = 23
480.168 -
480.169 -AI_PASSIVE=1
480.170 -
480.171 -SOCK_DGRAM = 1
480.172 -SOCK_STREAM = 2
480.173 -SOCK_RAW = 3 # not supported
480.174 -SOCK_RDM = 4 # not supported
480.175 -SOCK_SEQPACKET = 5 # not supported
480.176 -
480.177 -SOL_SOCKET = 0xFFFF
480.178 -
480.179 -SO_BROADCAST = 1
480.180 -SO_KEEPALIVE = 2
480.181 -SO_LINGER = 4
480.182 -SO_OOBINLINE = 8
480.183 -SO_RCVBUF = 16
480.184 -SO_REUSEADDR = 32
480.185 -SO_SNDBUF = 64
480.186 -SO_TIMEOUT = 128
480.187 -
480.188 -TCP_NODELAY = 256
480.189 -
480.190 -# Options with negative constants are not supported
480.191 -# They are being added here so that code that refers to them
480.192 -# will not break with an AttributeError
480.193 -
480.194 -SO_ACCEPTCONN = -1
480.195 -SO_DEBUG = -2
480.196 -SO_DONTROUTE = -4
480.197 -SO_ERROR = -8
480.198 -SO_EXCLUSIVEADDRUSE = -16
480.199 -SO_RCVLOWAT = -32
480.200 -SO_RCVTIMEO = -64
480.201 -SO_REUSEPORT = -128
480.202 -SO_SNDLOWAT = -256
480.203 -SO_SNDTIMEO = -512
480.204 -SO_TYPE = -1024
480.205 -SO_USELOOPBACK = -2048
480.206 -
480.207 -class _nio_impl:
480.208 -
480.209 - timeout = None
480.210 - mode = MODE_BLOCKING
480.211 -
480.212 - def read(self, buf):
480.213 - bytebuf = java.nio.ByteBuffer.wrap(buf)
480.214 - count = self.jchannel.read(bytebuf)
480.215 - return count
480.216 -
480.217 - def write(self, buf):
480.218 - bytebuf = java.nio.ByteBuffer.wrap(buf)
480.219 - count = self.jchannel.write(bytebuf)
480.220 - return count
480.221 -
480.222 - def getpeername(self):
480.223 - return (self.jsocket.getInetAddress().getHostAddress(), self.jsocket.getPort() )
480.224 -
480.225 - def config(self, mode, timeout):
480.226 - self.mode = mode
480.227 - if self.mode == MODE_BLOCKING:
480.228 - self.jchannel.configureBlocking(1)
480.229 - if self.mode == MODE_NONBLOCKING:
480.230 - self.jchannel.configureBlocking(0)
480.231 - if self.mode == MODE_TIMEOUT:
480.232 - self._timeout_millis = int(timeout*1000)
480.233 - self.jsocket.setSoTimeout(self._timeout_millis)
480.234 -
480.235 - def getsockopt(self, option):
480.236 - if self.options.has_key(option):
480.237 - result = getattr(self.jsocket, "get%s" % self.options[option])()
480.238 - if option == SO_LINGER:
480.239 - if result == -1:
480.240 - enabled, linger_time = 0, 0
480.241 - else:
480.242 - enabled, linger_time = 1, result
480.243 - return struct.pack('ii', enabled, linger_time)
480.244 - return result
480.245 - else:
480.246 - raise error(errno.ENOPROTOOPT, "Option not supported on socket(%s): %d" % (str(self.jsocket), option))
480.247 -
480.248 - def setsockopt(self, option, value):
480.249 - if self.options.has_key(option):
480.250 - if option == SO_LINGER:
480.251 - values = struct.unpack('ii', value)
480.252 - self.jsocket.setSoLinger(*values)
480.253 - else:
480.254 - getattr(self.jsocket, "set%s" % self.options[option])(value)
480.255 - else:
480.256 - raise error(errno.ENOPROTOOPT, "Option not supported on socket(%s): %d" % (str(self.jsocket), option))
480.257 -
480.258 - def close(self):
480.259 - self.jsocket.close()
480.260 -
480.261 - def shutdownInput(self):
480.262 - try:
480.263 - self.jsocket.shutdownInput()
480.264 - except AttributeError, ax:
480.265 - pass # Fail silently server sockets
480.266 - except java.lang.Exception, jlx:
480.267 - raise _map_exception(jlx)
480.268 -
480.269 - def shutdownOutput(self):
480.270 - try:
480.271 - self.jsocket.shutdownOutput()
480.272 - except AttributeError, ax:
480.273 - pass # Fail silently server sockets
480.274 - except java.lang.Exception, jlx:
480.275 - raise _map_exception(jlx)
480.276 -
480.277 - def getchannel(self):
480.278 - return self.jchannel
480.279 -
480.280 - def fileno(self):
480.281 - return self.socketio
480.282 -
480.283 -class _client_socket_impl(_nio_impl):
480.284 -
480.285 - options = {
480.286 - SO_KEEPALIVE: 'KeepAlive',
480.287 - SO_LINGER: 'SoLinger',
480.288 - SO_OOBINLINE: 'OOBInline',
480.289 - SO_RCVBUF: 'ReceiveBufferSize',
480.290 - SO_REUSEADDR: 'ReuseAddress',
480.291 - SO_SNDBUF: 'SendBufferSize',
480.292 - SO_TIMEOUT: 'SoTimeout',
480.293 - TCP_NODELAY: 'TcpNoDelay',
480.294 - }
480.295 -
480.296 - def __init__(self, socket=None):
480.297 - if socket:
480.298 - self.jchannel = socket.getChannel()
480.299 - self.host = socket.getInetAddress().getHostAddress()
480.300 - self.port = socket.getPort()
480.301 - else:
480.302 - self.jchannel = java.nio.channels.SocketChannel.open()
480.303 - self.host = None
480.304 - self.port = None
480.305 - self.jsocket = self.jchannel.socket()
480.306 - self.socketio = org.python.core.io.SocketIO(self.jchannel, 'rw')
480.307 -
480.308 - def bind(self, host, port, reuse_addr):
480.309 - self.jsocket.setReuseAddress(reuse_addr)
480.310 - self.jsocket.bind(java.net.InetSocketAddress(host, port))
480.311 -
480.312 - def connect(self, host, port):
480.313 - self.host = host
480.314 - self.port = port
480.315 - if self.mode == MODE_TIMEOUT:
480.316 - self.jsocket.connect(java.net.InetSocketAddress(self.host, self.port), self._timeout_millis)
480.317 - else:
480.318 - self.jchannel.connect(java.net.InetSocketAddress(self.host, self.port))
480.319 -
480.320 - def finish_connect(self):
480.321 - return self.jchannel.finishConnect()
480.322 -
480.323 -class _server_socket_impl(_nio_impl):
480.324 -
480.325 - options = {
480.326 - SO_RCVBUF: 'ReceiveBufferSize',
480.327 - SO_REUSEADDR: 'ReuseAddress',
480.328 - SO_TIMEOUT: 'SoTimeout',
480.329 - }
480.330 -
480.331 - def __init__(self, host, port, backlog, reuse_addr):
480.332 - self.jchannel = java.nio.channels.ServerSocketChannel.open()
480.333 - self.jsocket = self.jchannel.socket()
480.334 - if host:
480.335 - bindaddr = java.net.InetSocketAddress(host, port)
480.336 - else:
480.337 - bindaddr = java.net.InetSocketAddress(port)
480.338 - self.jsocket.setReuseAddress(reuse_addr)
480.339 - self.jsocket.bind(bindaddr, backlog)
480.340 - self.socketio = org.python.core.io.ServerSocketIO(self.jchannel, 'rw')
480.341 -
480.342 - def accept(self):
480.343 - if self.mode in (MODE_BLOCKING, MODE_NONBLOCKING):
480.344 - new_cli_chan = self.jchannel.accept()
480.345 - if new_cli_chan != None:
480.346 - return _client_socket_impl(new_cli_chan.socket())
480.347 - else:
480.348 - return None
480.349 - else:
480.350 - # In timeout mode now
480.351 - new_cli_sock = self.jsocket.accept()
480.352 - return _client_socket_impl(new_cli_sock)
480.353 -
480.354 -class _datagram_socket_impl(_nio_impl):
480.355 -
480.356 - options = {
480.357 - SO_BROADCAST: 'Broadcast',
480.358 - SO_RCVBUF: 'ReceiveBufferSize',
480.359 - SO_REUSEADDR: 'ReuseAddress',
480.360 - SO_SNDBUF: 'SendBufferSize',
480.361 - SO_TIMEOUT: 'SoTimeout',
480.362 - }
480.363 -
480.364 - def __init__(self, port=None, address=None, reuse_addr=0):
480.365 - self.jchannel = java.nio.channels.DatagramChannel.open()
480.366 - self.jsocket = self.jchannel.socket()
480.367 - if port:
480.368 - if address is not None:
480.369 - local_address = java.net.InetSocketAddress(address, port)
480.370 - else:
480.371 - local_address = java.net.InetSocketAddress(port)
480.372 - self.jsocket.setReuseAddress(reuse_addr)
480.373 - self.jsocket.bind(local_address)
480.374 - self.socketio = org.python.core.io.DatagramSocketIO(self.jchannel, 'rw')
480.375 -
480.376 - def connect(self, host, port):
480.377 - self.jchannel.connect(java.net.InetSocketAddress(host, port))
480.378 -
480.379 - def finish_connect(self):
480.380 - return self.jchannel.finishConnect()
480.381 -
480.382 - def disconnect(self):
480.383 - """
480.384 - Disconnect the datagram socket.
480.385 - cpython appears not to have this operation
480.386 - """
480.387 - self.jchannel.disconnect()
480.388 -
480.389 - def _do_send_net(self, byte_array, socket_address, flags):
480.390 - # Need two separate implementations because the java.nio APIs do not support timeouts
480.391 - num_bytes = len(byte_array)
480.392 - if socket_address:
480.393 - packet = java.net.DatagramPacket(byte_array, num_bytes, socket_address)
480.394 - else:
480.395 - packet = java.net.DatagramPacket(byte_array, num_bytes)
480.396 - self.jsocket.send(packet)
480.397 - return num_bytes
480.398 -
480.399 - def _do_send_nio(self, byte_array, socket_address, flags):
480.400 - byte_buf = java.nio.ByteBuffer.wrap(byte_array)
480.401 - bytes_sent = self.jchannel.send(byte_buf, socket_address)
480.402 - return bytes_sent
480.403 -
480.404 - def sendto(self, byte_array, host, port, flags):
480.405 - socket_address = java.net.InetSocketAddress(host, port)
480.406 - if self.mode == MODE_TIMEOUT:
480.407 - return self._do_send_net(byte_array, socket_address, flags)
480.408 - else:
480.409 - return self._do_send_nio(byte_array, socket_address, flags)
480.410 -
480.411 - def send(self, byte_array, flags):
480.412 - if self.mode == MODE_TIMEOUT:
480.413 - return self._do_send_net(byte_array, None, flags)
480.414 - else:
480.415 - return self._do_send_nio(byte_array, None, flags)
480.416 -
480.417 - def _do_receive_net(self, return_source_address, num_bytes, flags):
480.418 - byte_array = jarray.zeros(num_bytes, 'b')
480.419 - packet = java.net.DatagramPacket(byte_array, num_bytes)
480.420 - self.jsocket.receive(packet)
480.421 - bytes_rcvd = packet.getLength()
480.422 - if bytes_rcvd < num_bytes:
480.423 - byte_array = byte_array[:bytes_rcvd]
480.424 - return_data = byte_array.tostring()
480.425 - if return_source_address:
480.426 - host = None
480.427 - if packet.getAddress():
480.428 - host = packet.getAddress().getHostAddress()
480.429 - port = packet.getPort()
480.430 - return return_data, (host, port)
480.431 - else:
480.432 - return return_data
480.433 -
480.434 - def _do_receive_nio(self, return_source_address, num_bytes, flags):
480.435 - byte_array = jarray.zeros(num_bytes, 'b')
480.436 - byte_buf = java.nio.ByteBuffer.wrap(byte_array)
480.437 - source_address = self.jchannel.receive(byte_buf)
480.438 - if source_address is None and not self.jchannel.isBlocking():
480.439 - raise would_block_error()
480.440 - byte_buf.flip() ; bytes_read = byte_buf.remaining()
480.441 - if bytes_read < num_bytes:
480.442 - byte_array = byte_array[:bytes_read]
480.443 - return_data = byte_array.tostring()
480.444 - if return_source_address:
480.445 - return return_data, (source_address.getAddress().getHostAddress(), source_address.getPort())
480.446 - else:
480.447 - return return_data
480.448 -
480.449 - def recvfrom(self, num_bytes, flags):
480.450 - if self.mode == MODE_TIMEOUT:
480.451 - return self._do_receive_net(1, num_bytes, flags)
480.452 - else:
480.453 - return self._do_receive_nio(1, num_bytes, flags)
480.454 -
480.455 - def recv(self, num_bytes, flags):
480.456 - if self.mode == MODE_TIMEOUT:
480.457 - return self._do_receive_net(0, num_bytes, flags)
480.458 - else:
480.459 - return self._do_receive_nio(0, num_bytes, flags)
480.460 -
480.461 -# Name and address functions
480.462 -
480.463 -has_ipv6 = 1
480.464 -
480.465 -def _gethostbyaddr(name):
480.466 - # This is as close as I can get; at least the types are correct...
480.467 - addresses = java.net.InetAddress.getAllByName(gethostbyname(name))
480.468 - names = []
480.469 - addrs = []
480.470 - for addr in addresses:
480.471 - names.append(asPyString(addr.getHostName()))
480.472 - addrs.append(asPyString(addr.getHostAddress()))
480.473 - return (names, addrs)
480.474 -
480.475 -def getfqdn(name=None):
480.476 - """
480.477 - Return a fully qualified domain name for name. If name is omitted or empty
480.478 - it is interpreted as the local host. To find the fully qualified name,
480.479 - the hostname returned by gethostbyaddr() is checked, then aliases for the
480.480 - host, if available. The first name which includes a period is selected.
480.481 - In case no fully qualified domain name is available, the hostname is retur
480.482 - New in version 2.0.
480.483 - """
480.484 - if not name:
480.485 - name = gethostname()
480.486 - names, addrs = _gethostbyaddr(name)
480.487 - for a in names:
480.488 - if a.find(".") >= 0:
480.489 - return a
480.490 - return name
480.491 -
480.492 -def gethostname():
480.493 - try:
480.494 - return asPyString(java.net.InetAddress.getLocalHost().getHostName())
480.495 - except java.lang.Exception, jlx:
480.496 - raise _map_exception(jlx)
480.497 -
480.498 -def gethostbyname(name):
480.499 - try:
480.500 - return asPyString(java.net.InetAddress.getByName(name).getHostAddress())
480.501 - except java.lang.Exception, jlx:
480.502 - raise _map_exception(jlx)
480.503 -
480.504 -def gethostbyaddr(name):
480.505 - names, addrs = _gethostbyaddr(name)
480.506 - return (names[0], names, addrs)
480.507 -
480.508 -def getservbyname(servicename, protocolname=None):
480.509 - # http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071389
480.510 - # How complex is the structure of /etc/services?
480.511 - raise NotImplementedError("getservbyname not yet supported on jython.")
480.512 -
480.513 -def getservbyport(port, protocolname=None):
480.514 - # Same situation as above
480.515 - raise NotImplementedError("getservbyport not yet supported on jython.")
480.516 -
480.517 -def getprotobyname(protocolname=None):
480.518 - # Same situation as above
480.519 - raise NotImplementedError("getprotobyname not yet supported on jython.")
480.520 -
480.521 -def _realsocket(family = AF_INET, type = SOCK_STREAM, flags=0):
480.522 - assert family == AF_INET
480.523 - assert type in (SOCK_DGRAM, SOCK_STREAM)
480.524 - assert flags == 0
480.525 - if type == SOCK_STREAM:
480.526 - return _tcpsocket()
480.527 - else:
480.528 - return _udpsocket()
480.529 -
480.530 -def getaddrinfo(host, port, family=AF_INET, socktype=None, proto=0, flags=None):
480.531 - try:
480.532 - if not family in [AF_INET, AF_INET6, AF_UNSPEC]:
480.533 - raise gaierror(errno.EIO, 'ai_family not supported')
480.534 - filter_fns = []
480.535 - filter_fns.append({
480.536 - AF_INET: lambda x: isinstance(x, java.net.Inet4Address),
480.537 - AF_INET6: lambda x: isinstance(x, java.net.Inet6Address),
480.538 - AF_UNSPEC: lambda x: isinstance(x, java.net.InetAddress),
480.539 - }[family])
480.540 - # Cant see a way to support AI_PASSIVE right now.
480.541 - # if flags and flags & AI_PASSIVE:
480.542 - # pass
480.543 - results = []
480.544 - for a in java.net.InetAddress.getAllByName(host):
480.545 - if len([f for f in filter_fns if f(a)]):
480.546 - family = {java.net.Inet4Address: AF_INET, java.net.Inet6Address: AF_INET6}[a.getClass()]
480.547 - # TODO: Include flowinfo and scopeid in a 4-tuple for IPv6 addresses
480.548 - canonname = asPyString(a.getCanonicalHostName())
480.549 - sockname = asPyString(a.getHostAddress())
480.550 - results.append((family, socktype, proto, canonname, (sockname, port)))
480.551 - return results
480.552 - except java.lang.Exception, jlx:
480.553 - raise _map_exception(jlx)
480.554 -
480.555 -def getnameinfo(sock_addr, flags):
480.556 - raise NotImplementedError("getnameinfo not yet supported on jython.")
480.557 -
480.558 -def getdefaulttimeout():
480.559 - return _defaulttimeout
480.560 -
480.561 -def _calctimeoutvalue(value):
480.562 - if value is None:
480.563 - return None
480.564 - try:
480.565 - floatvalue = float(value)
480.566 - except:
480.567 - raise TypeError('Socket timeout value must be a number or None')
480.568 - if floatvalue < 0.0:
480.569 - raise ValueError("Socket timeout value cannot be negative")
480.570 - if floatvalue < 0.000001:
480.571 - return 0.0
480.572 - return floatvalue
480.573 -
480.574 -def setdefaulttimeout(timeout):
480.575 - global _defaulttimeout
480.576 - try:
480.577 - _defaulttimeout = _calctimeoutvalue(timeout)
480.578 - finally:
480.579 - _nonblocking_api_mixin.timeout = _defaulttimeout
480.580 -
480.581 -def htons(x): return x
480.582 -def htonl(x): return x
480.583 -def ntohs(x): return x
480.584 -def ntohl(x): return x
480.585 -
480.586 -class _nonblocking_api_mixin:
480.587 -
480.588 - timeout = _defaulttimeout
480.589 - mode = MODE_BLOCKING
480.590 - reference_count = 0
480.591 - close_lock = threading.Lock()
480.592 -
480.593 - def __init__(self):
480.594 - self.pending_options = {
480.595 - SO_REUSEADDR: 0,
480.596 - }
480.597 -
480.598 - def gettimeout(self):
480.599 - return self.timeout
480.600 -
480.601 - def settimeout(self, timeout):
480.602 - self.timeout = _calctimeoutvalue(timeout)
480.603 - if self.timeout is None:
480.604 - self.mode = MODE_BLOCKING
480.605 - elif self.timeout < 0.000001:
480.606 - self.mode = MODE_NONBLOCKING
480.607 - else:
480.608 - self.mode = MODE_TIMEOUT
480.609 - self._config()
480.610 -
480.611 - def setblocking(self, flag):
480.612 - if flag:
480.613 - self.mode = MODE_BLOCKING
480.614 - self.timeout = None
480.615 - else:
480.616 - self.mode = MODE_NONBLOCKING
480.617 - self.timeout = 0.0
480.618 - self._config()
480.619 -
480.620 - def getblocking(self):
480.621 - return self.mode == MODE_BLOCKING
480.622 -
480.623 - def setsockopt(self, level, optname, value):
480.624 - if level != SOL_SOCKET: return
480.625 - try:
480.626 - if self.sock_impl:
480.627 - self.sock_impl.setsockopt(optname, value)
480.628 - else:
480.629 - self.pending_options[optname] = value
480.630 - except java.lang.Exception, jlx:
480.631 - raise _map_exception(jlx)
480.632 -
480.633 - def getsockopt(self, level, optname):
480.634 - if level != SOL_SOCKET: return
480.635 - try:
480.636 - if self.sock_impl:
480.637 - return self.sock_impl.getsockopt(optname)
480.638 - else:
480.639 - return self.pending_options.get(optname, None)
480.640 - except java.lang.Exception, jlx:
480.641 - raise _map_exception(jlx)
480.642 -
480.643 - def _config(self):
480.644 - assert self.mode in _permitted_modes
480.645 - if self.sock_impl:
480.646 - self.sock_impl.config(self.mode, self.timeout)
480.647 - for k in self.pending_options.keys():
480.648 - if k != SO_REUSEADDR:
480.649 - self.sock_impl.setsockopt(k, self.pending_options[k])
480.650 -
480.651 - def getchannel(self):
480.652 - if not self.sock_impl:
480.653 - return None
480.654 - return self.sock_impl.getchannel()
480.655 -
480.656 - def fileno(self):
480.657 - if not self.sock_impl:
480.658 - return None
480.659 - return self.sock_impl.fileno()
480.660 -
480.661 - def _get_jsocket(self):
480.662 - return self.sock_impl.jsocket
480.663 -
480.664 -def _unpack_address_tuple(address_tuple, for_tx=False):
480.665 - # TODO: Upgrade to support the 4-tuples used for IPv6 addresses
480.666 - # which include flowinfo and scope_id.
480.667 - # To be upgraded in synch with getaddrinfo
480.668 - error_message = "Address must be a tuple of (hostname, port)"
480.669 - if not isinstance(address_tuple, tuple) or \
480.670 - not isinstance(address_tuple[0], basestring) or \
480.671 - not isinstance(address_tuple[1], (int, long)):
480.672 - raise TypeError(error_message)
480.673 - hostname = address_tuple[0]
480.674 - if isinstance(hostname, unicode):
480.675 - # XXX: Should be encode('idna') (See CPython
480.676 - # socketmodule::getsockaddrarg), but Jython's idna support is
480.677 - # currently broken
480.678 - hostname = hostname.encode()
480.679 - hostname = hostname.strip()
480.680 - if hostname == "<broadcast>":
480.681 - if for_tx:
480.682 - hostname = "255.255.255.255"
480.683 - else:
480.684 - hostname = "0.0.0.0"
480.685 - return hostname, address_tuple[1]
480.686 -
480.687 -class _tcpsocket(_nonblocking_api_mixin):
480.688 -
480.689 - sock_impl = None
480.690 - istream = None
480.691 - ostream = None
480.692 - local_addr = None
480.693 - server = 0
480.694 -
480.695 - def __init__(self):
480.696 - _nonblocking_api_mixin.__init__(self)
480.697 -
480.698 - def bind(self, addr):
480.699 - assert not self.sock_impl
480.700 - assert not self.local_addr
480.701 - # Do the address format check
480.702 - _unpack_address_tuple(addr)
480.703 - self.local_addr = addr
480.704 -
480.705 - def listen(self, backlog):
480.706 - "This signifies a server socket"
480.707 - try:
480.708 - assert not self.sock_impl
480.709 - self.server = 1
480.710 - if self.local_addr:
480.711 - host, port = _unpack_address_tuple(self.local_addr)
480.712 - else:
480.713 - host, port = "", 0
480.714 - self.sock_impl = _server_socket_impl(host, port, backlog, self.pending_options[SO_REUSEADDR])
480.715 - self._config()
480.716 - except java.lang.Exception, jlx:
480.717 - raise _map_exception(jlx)
480.718 -
480.719 - def accept(self):
480.720 - "This signifies a server socket"
480.721 - try:
480.722 - if not self.sock_impl:
480.723 - self.listen()
480.724 - assert self.server
480.725 - new_sock = self.sock_impl.accept()
480.726 - if not new_sock:
480.727 - raise would_block_error()
480.728 - cliconn = _tcpsocket()
480.729 - cliconn.pending_options[SO_REUSEADDR] = new_sock.jsocket.getReuseAddress()
480.730 - cliconn.sock_impl = new_sock
480.731 - cliconn._setup()
480.732 - return cliconn, new_sock.getpeername()
480.733 - except java.lang.Exception, jlx:
480.734 - raise _map_exception(jlx)
480.735 -
480.736 - def _get_host_port(self, addr):
480.737 - host, port = _unpack_address_tuple(addr)
480.738 - if host == "":
480.739 - host = java.net.InetAddress.getLocalHost()
480.740 - return host, port
480.741 -
480.742 - def _do_connect(self, addr):
480.743 - try:
480.744 - assert not self.sock_impl
480.745 - host, port = self._get_host_port(addr)
480.746 - self.sock_impl = _client_socket_impl()
480.747 - if self.local_addr: # Has the socket been bound to a local address?
480.748 - bind_host, bind_port = _unpack_address_tuple(self.local_addr)
480.749 - self.sock_impl.bind(bind_host, bind_port, self.pending_options[SO_REUSEADDR])
480.750 - self._config() # Configure timeouts, etc, now that the socket exists
480.751 - self.sock_impl.connect(host, port)
480.752 - except java.lang.Exception, jlx:
480.753 - raise _map_exception(jlx)
480.754 -
480.755 - def connect(self, addr):
480.756 - "This signifies a client socket"
480.757 - self._do_connect(addr)
480.758 - self._setup()
480.759 -
480.760 - def connect_ex(self, addr):
480.761 - "This signifies a client socket"
480.762 - if not self.sock_impl:
480.763 - self._do_connect(addr)
480.764 - if self.sock_impl.finish_connect():
480.765 - self._setup()
480.766 - if self.mode == MODE_NONBLOCKING:
480.767 - return errno.EISCONN
480.768 - return 0
480.769 - return errno.EINPROGRESS
480.770 -
480.771 - def _setup(self):
480.772 - if self.mode != MODE_NONBLOCKING:
480.773 - self.istream = self.sock_impl.jsocket.getInputStream()
480.774 - self.ostream = self.sock_impl.jsocket.getOutputStream()
480.775 -
480.776 - def recv(self, n):
480.777 - try:
480.778 - if not self.sock_impl: raise error(errno.ENOTCONN, 'Socket is not connected')
480.779 - if self.sock_impl.jchannel.isConnectionPending():
480.780 - self.sock_impl.jchannel.finishConnect()
480.781 - data = jarray.zeros(n, 'b')
480.782 - m = self.sock_impl.read(data)
480.783 - if m == -1:#indicates EOF has been reached, so we just return the empty string
480.784 - return ""
480.785 - elif m <= 0:
480.786 - if self.mode == MODE_NONBLOCKING:
480.787 - raise would_block_error()
480.788 - return ""
480.789 - if m < n:
480.790 - data = data[:m]
480.791 - return data.tostring()
480.792 - except java.lang.Exception, jlx:
480.793 - raise _map_exception(jlx)
480.794 -
480.795 - def recvfrom(self, n):
480.796 - return self.recv(n), None
480.797 -
480.798 - def send(self, s):
480.799 - try:
480.800 - if not self.sock_impl: raise error(errno.ENOTCONN, 'Socket is not connected')
480.801 - if self.sock_impl.jchannel.isConnectionPending():
480.802 - self.sock_impl.jchannel.finishConnect()
480.803 - numwritten = self.sock_impl.write(s)
480.804 - return numwritten
480.805 - except java.lang.Exception, jlx:
480.806 - raise _map_exception(jlx)
480.807 -
480.808 - sendall = send
480.809 -
480.810 - def getsockname(self):
480.811 - try:
480.812 - if not self.sock_impl:
480.813 - host, port = self.local_addr or ("", 0)
480.814 - host = java.net.InetAddress.getByName(host).getHostAddress()
480.815 - else:
480.816 - if self.server:
480.817 - host = self.sock_impl.jsocket.getInetAddress().getHostAddress()
480.818 - else:
480.819 - host = self.sock_impl.jsocket.getLocalAddress().getHostAddress()
480.820 - port = self.sock_impl.jsocket.getLocalPort()
480.821 - return (host, port)
480.822 - except java.lang.Exception, jlx:
480.823 - raise _map_exception(jlx)
480.824 -
480.825 - def getpeername(self):
480.826 - try:
480.827 - assert self.sock_impl
480.828 - assert not self.server
480.829 - host = self.sock_impl.jsocket.getInetAddress().getHostAddress()
480.830 - port = self.sock_impl.jsocket.getPort()
480.831 - return (host, port)
480.832 - except java.lang.Exception, jlx:
480.833 - raise _map_exception(jlx)
480.834 -
480.835 - def shutdown(self, how):
480.836 - if not self.sock_impl:
480.837 - raise error(errno.ENOTCONN, "Transport endpoint is not connected")
480.838 - assert how in (SHUT_RD, SHUT_WR, SHUT_RDWR)
480.839 - if how in (SHUT_RD, SHUT_RDWR):
480.840 - self.sock_impl.shutdownInput()
480.841 - if how in (SHUT_WR, SHUT_RDWR):
480.842 - self.sock_impl.shutdownOutput()
480.843 -
480.844 - def close(self):
480.845 - try:
480.846 - if self.istream:
480.847 - self.istream.close()
480.848 - if self.ostream:
480.849 - self.ostream.close()
480.850 - if self.sock_impl:
480.851 - self.sock_impl.close()
480.852 - except java.lang.Exception, jlx:
480.853 - raise _map_exception(jlx)
480.854 -
480.855 -
480.856 -class _udpsocket(_nonblocking_api_mixin):
480.857 -
480.858 - sock_impl = None
480.859 - addr = None
480.860 -
480.861 - def __init__(self):
480.862 - _nonblocking_api_mixin.__init__(self)
480.863 -
480.864 - def bind(self, addr):
480.865 - try:
480.866 - assert not self.sock_impl
480.867 - host, port = _unpack_address_tuple(addr)
480.868 - host_address = java.net.InetAddress.getByName(host)
480.869 - self.sock_impl = _datagram_socket_impl(port, host_address, self.pending_options[SO_REUSEADDR])
480.870 - self._config()
480.871 - except java.lang.Exception, jlx:
480.872 - raise _map_exception(jlx)
480.873 -
480.874 - def _do_connect(self, addr):
480.875 - try:
480.876 - host, port = _unpack_address_tuple(addr)
480.877 - assert not self.addr
480.878 - self.addr = addr
480.879 - if not self.sock_impl:
480.880 - self.sock_impl = _datagram_socket_impl()
480.881 - self._config()
480.882 - self.sock_impl.connect(host, port)
480.883 - except java.lang.Exception, jlx:
480.884 - raise _map_exception(jlx)
480.885 -
480.886 - def connect(self, addr):
480.887 - self._do_connect(addr)
480.888 -
480.889 - def connect_ex(self, addr):
480.890 - if not self.sock_impl:
480.891 - self._do_connect(addr)
480.892 - if self.sock_impl.finish_connect():
480.893 - if self.mode == MODE_NONBLOCKING:
480.894 - return errno.EISCONN
480.895 - return 0
480.896 - return errno.EINPROGRESS
480.897 -
480.898 - def sendto(self, data, p1, p2=None):
480.899 - try:
480.900 - if not p2:
480.901 - flags, addr = 0, p1
480.902 - else:
480.903 - flags, addr = 0, p2
480.904 - if not self.sock_impl:
480.905 - self.sock_impl = _datagram_socket_impl()
480.906 - self._config()
480.907 - host, port = _unpack_address_tuple(addr, True)
480.908 - byte_array = java.lang.String(data).getBytes('iso-8859-1')
480.909 - result = self.sock_impl.sendto(byte_array, host, port, flags)
480.910 - return result
480.911 - except java.lang.Exception, jlx:
480.912 - raise _map_exception(jlx)
480.913 -
480.914 - def send(self, data, flags=None):
480.915 - if not self.addr: raise error(errno.ENOTCONN, "Socket is not connected")
480.916 - byte_array = java.lang.String(data).getBytes('iso-8859-1')
480.917 - return self.sock_impl.send(byte_array, flags)
480.918 -
480.919 - def recvfrom(self, num_bytes, flags=None):
480.920 - """
480.921 - There is some disagreement as to what the behaviour should be if
480.922 - a recvfrom operation is requested on an unbound socket.
480.923 - See the following links for more information
480.924 - http://bugs.jython.org/issue1005
480.925 - http://bugs.sun.com/view_bug.do?bug_id=6621689
480.926 - """
480.927 - try:
480.928 - # This is the old 2.1 behaviour
480.929 - #assert self.sock_impl
480.930 - # This is amak's preferred interpretation
480.931 - #raise error(errno.ENOTCONN, "Recvfrom on unbound udp socket meaningless operation")
480.932 - # And this is the option for cpython compatibility
480.933 - if not self.sock_impl:
480.934 - self.sock_impl = _datagram_socket_impl()
480.935 - self._config()
480.936 - return self.sock_impl.recvfrom(num_bytes, flags)
480.937 - except java.lang.Exception, jlx:
480.938 - raise _map_exception(jlx)
480.939 -
480.940 - def recv(self, num_bytes, flags=None):
480.941 - if not self.sock_impl: raise error(errno.ENOTCONN, "Socket is not connected")
480.942 - try:
480.943 - return self.sock_impl.recv(num_bytes, flags)
480.944 - except java.lang.Exception, jlx:
480.945 - raise _map_exception(jlx)
480.946 -
480.947 - def getsockname(self):
480.948 - try:
480.949 - assert self.sock_impl
480.950 - host = self.sock_impl.jsocket.getLocalAddress().getHostAddress()
480.951 - port = self.sock_impl.jsocket.getLocalPort()
480.952 - return (host, port)
480.953 - except java.lang.Exception, jlx:
480.954 - raise _map_exception(jlx)
480.955 -
480.956 - def getpeername(self):
480.957 - try:
480.958 - assert self.sock
480.959 - host = self.sock_impl.jsocket.getInetAddress().getHostAddress()
480.960 - port = self.sock_impl.jsocket.getPort()
480.961 - return (host, port)
480.962 - except java.lang.Exception, jlx:
480.963 - raise _map_exception(jlx)
480.964 -
480.965 - def __del__(self):
480.966 - self.close()
480.967 -
480.968 - def close(self):
480.969 - try:
480.970 - if self.sock_impl:
480.971 - self.sock_impl.close()
480.972 - except java.lang.Exception, jlx:
480.973 - raise _map_exception(jlx)
480.974 -
480.975 -_socketmethods = (
480.976 - 'bind', 'connect', 'connect_ex', 'fileno', 'listen',
480.977 - 'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
480.978 - 'sendall', 'setblocking',
480.979 - 'settimeout', 'gettimeout', 'shutdown', 'getchannel')
480.980 -
480.981 -# All the method names that must be delegated to either the real socket
480.982 -# object or the _closedsocket object.
480.983 -_delegate_methods = ("recv", "recvfrom", "recv_into", "recvfrom_into",
480.984 - "send", "sendto")
480.985 -
480.986 -class _closedsocket(object):
480.987 - __slots__ = []
480.988 - def _dummy(*args):
480.989 - raise error(errno.EBADF, 'Bad file descriptor')
480.990 - # All _delegate_methods must also be initialized here.
480.991 - send = recv = recv_into = sendto = recvfrom = recvfrom_into = _dummy
480.992 - __getattr__ = _dummy
480.993 -
480.994 -class _socketobject(object):
480.995 -
480.996 - __doc__ = _realsocket.__doc__
480.997 -
480.998 - __slots__ = ["_sock", "__weakref__"] + list(_delegate_methods)
480.999 -
480.1000 - def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
480.1001 - if _sock is None:
480.1002 - _sock = _realsocket(family, type, proto)
480.1003 - _sock.reference_count += 1
480.1004 - elif isinstance(_sock, _nonblocking_api_mixin):
480.1005 - _sock.reference_count += 1
480.1006 - self._sock = _sock
480.1007 - for method in _delegate_methods:
480.1008 - meth = getattr(_sock, method, None)
480.1009 - if meth:
480.1010 - setattr(self, method, meth)
480.1011 -
480.1012 - def close(self):
480.1013 - _sock = self._sock
480.1014 - if isinstance(_sock, _nonblocking_api_mixin):
480.1015 - _sock.close_lock.acquire()
480.1016 - try:
480.1017 - _sock.reference_count -=1
480.1018 - if not _sock.reference_count:
480.1019 - _sock.close()
480.1020 - self._sock = _closedsocket()
480.1021 - dummy = self._sock._dummy
480.1022 - for method in _delegate_methods:
480.1023 - setattr(self, method, dummy)
480.1024 - self.send = self.recv = self.sendto = self.recvfrom = \
480.1025 - self._sock._dummy
480.1026 - finally:
480.1027 - _sock.close_lock.release()
480.1028 - #close.__doc__ = _realsocket.close.__doc__
480.1029 -
480.1030 - def accept(self):
480.1031 - sock, addr = self._sock.accept()
480.1032 - return _socketobject(_sock=sock), addr
480.1033 - #accept.__doc__ = _realsocket.accept.__doc__
480.1034 -
480.1035 - def dup(self):
480.1036 - """dup() -> socket object
480.1037 -
480.1038 - Return a new socket object connected to the same system resource."""
480.1039 - _sock = self._sock
480.1040 - if not isinstance(_sock, _nonblocking_api_mixin):
480.1041 - return _socketobject(_sock=_sock)
480.1042 -
480.1043 - _sock.close_lock.acquire()
480.1044 - try:
480.1045 - duped = _socketobject(_sock=_sock)
480.1046 - finally:
480.1047 - _sock.close_lock.release()
480.1048 - return duped
480.1049 -
480.1050 - def makefile(self, mode='r', bufsize=-1):
480.1051 - """makefile([mode[, bufsize]]) -> file object
480.1052 -
480.1053 - Return a regular file object corresponding to the socket. The mode
480.1054 - and bufsize arguments are as for the built-in open() function."""
480.1055 - _sock = self._sock
480.1056 - if not isinstance(_sock, _nonblocking_api_mixin):
480.1057 - return _fileobject(_sock, mode, bufsize)
480.1058 -
480.1059 - _sock.close_lock.acquire()
480.1060 - try:
480.1061 - fileobject = _fileobject(_sock, mode, bufsize)
480.1062 - finally:
480.1063 - _sock.close_lock.release()
480.1064 - return fileobject
480.1065 -
480.1066 - family = property(lambda self: self._sock.family, doc="the socket family")
480.1067 - type = property(lambda self: self._sock.type, doc="the socket type")
480.1068 - proto = property(lambda self: self._sock.proto, doc="the socket protocol")
480.1069 -
480.1070 - _s = ("def %s(self, *args): return self._sock.%s(*args)\n\n"
480.1071 - #"%s.__doc__ = _realsocket.%s.__doc__\n")
480.1072 - )
480.1073 - for _m in _socketmethods:
480.1074 - #exec _s % (_m, _m, _m, _m)
480.1075 - exec _s % (_m, _m)
480.1076 - del _m, _s
480.1077 -
480.1078 -socket = SocketType = _socketobject
480.1079 -
480.1080 -class _fileobject(object):
480.1081 - """Faux file object attached to a socket object."""
480.1082 -
480.1083 - default_bufsize = 8192
480.1084 - name = "<socket>"
480.1085 -
480.1086 - __slots__ = ["mode", "bufsize", "softspace",
480.1087 - # "closed" is a property, see below
480.1088 - "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf",
480.1089 - "_close"]
480.1090 -
480.1091 - def __init__(self, sock, mode='rb', bufsize=-1, close=False):
480.1092 - self._sock = sock
480.1093 - if isinstance(sock, _nonblocking_api_mixin):
480.1094 - sock.reference_count += 1
480.1095 - self.mode = mode # Not actually used in this version
480.1096 - if bufsize < 0:
480.1097 - bufsize = self.default_bufsize
480.1098 - self.bufsize = bufsize
480.1099 - self.softspace = False
480.1100 - if bufsize == 0:
480.1101 - self._rbufsize = 1
480.1102 - elif bufsize == 1:
480.1103 - self._rbufsize = self.default_bufsize
480.1104 - else:
480.1105 - self._rbufsize = bufsize
480.1106 - self._wbufsize = bufsize
480.1107 - self._rbuf = "" # A string
480.1108 - self._wbuf = [] # A list of strings
480.1109 - self._close = close
480.1110 -
480.1111 - def _getclosed(self):
480.1112 - return self._sock is None
480.1113 - closed = property(_getclosed, doc="True if the file is closed")
480.1114 -
480.1115 - def close(self):
480.1116 - try:
480.1117 - if self._sock:
480.1118 - self.flush()
480.1119 - finally:
480.1120 - if self._sock:
480.1121 - if isinstance(self._sock, _nonblocking_api_mixin):
480.1122 - self._sock.reference_count -= 1
480.1123 - if not self._sock.reference_count or self._close:
480.1124 - self._sock.close()
480.1125 - elif self._close:
480.1126 - self._sock.close()
480.1127 - self._sock = None
480.1128 -
480.1129 - def __del__(self):
480.1130 - try:
480.1131 - self.close()
480.1132 - except:
480.1133 - # close() may fail if __init__ didn't complete
480.1134 - pass
480.1135 -
480.1136 - def flush(self):
480.1137 - if self._wbuf:
480.1138 - buffer = "".join(self._wbuf)
480.1139 - self._wbuf = []
480.1140 - self._sock.sendall(buffer)
480.1141 -
480.1142 - def fileno(self):
480.1143 - return self._sock.fileno()
480.1144 -
480.1145 - def write(self, data):
480.1146 - data = str(data) # XXX Should really reject non-string non-buffers
480.1147 - if not data:
480.1148 - return
480.1149 - self._wbuf.append(data)
480.1150 - if (self._wbufsize == 0 or
480.1151 - self._wbufsize == 1 and '\n' in data or
480.1152 - self._get_wbuf_len() >= self._wbufsize):
480.1153 - self.flush()
480.1154 -
480.1155 - def writelines(self, list):
480.1156 - # XXX We could do better here for very long lists
480.1157 - # XXX Should really reject non-string non-buffers
480.1158 - self._wbuf.extend(filter(None, map(str, list)))
480.1159 - if (self._wbufsize <= 1 or
480.1160 - self._get_wbuf_len() >= self._wbufsize):
480.1161 - self.flush()
480.1162 -
480.1163 - def _get_wbuf_len(self):
480.1164 - buf_len = 0
480.1165 - for x in self._wbuf:
480.1166 - buf_len += len(x)
480.1167 - return buf_len
480.1168 -
480.1169 - def read(self, size=-1):
480.1170 - data = self._rbuf
480.1171 - if size < 0:
480.1172 - # Read until EOF
480.1173 - buffers = []
480.1174 - if data:
480.1175 - buffers.append(data)
480.1176 - self._rbuf = ""
480.1177 - if self._rbufsize <= 1:
480.1178 - recv_size = self.default_bufsize
480.1179 - else:
480.1180 - recv_size = self._rbufsize
480.1181 - while True:
480.1182 - data = self._sock.recv(recv_size)
480.1183 - if not data:
480.1184 - break
480.1185 - buffers.append(data)
480.1186 - return "".join(buffers)
480.1187 - else:
480.1188 - # Read until size bytes or EOF seen, whichever comes first
480.1189 - buf_len = len(data)
480.1190 - if buf_len >= size:
480.1191 - self._rbuf = data[size:]
480.1192 - return data[:size]
480.1193 - buffers = []
480.1194 - if data:
480.1195 - buffers.append(data)
480.1196 - self._rbuf = ""
480.1197 - while True:
480.1198 - left = size - buf_len
480.1199 - recv_size = min(self._rbufsize, left)
480.1200 - data = self._sock.recv(recv_size)
480.1201 - if not data:
480.1202 - break
480.1203 - buffers.append(data)
480.1204 - n = len(data)
480.1205 - if n >= left:
480.1206 - self._rbuf = data[left:]
480.1207 - buffers[-1] = data[:left]
480.1208 - break
480.1209 - buf_len += n
480.1210 - return "".join(buffers)
480.1211 -
480.1212 - def readline(self, size=-1):
480.1213 - data = self._rbuf
480.1214 - if size < 0:
480.1215 - # Read until \n or EOF, whichever comes first
480.1216 - if self._rbufsize <= 1:
480.1217 - # Speed up unbuffered case
480.1218 - assert data == ""
480.1219 - buffers = []
480.1220 - recv = self._sock.recv
480.1221 - while data != "\n":
480.1222 - data = recv(1)
480.1223 - if not data:
480.1224 - break
480.1225 - buffers.append(data)
480.1226 - return "".join(buffers)
480.1227 - nl = data.find('\n')
480.1228 - if nl >= 0:
480.1229 - nl += 1
480.1230 - self._rbuf = data[nl:]
480.1231 - return data[:nl]
480.1232 - buffers = []
480.1233 - if data:
480.1234 - buffers.append(data)
480.1235 - self._rbuf = ""
480.1236 - while True:
480.1237 - data = self._sock.recv(self._rbufsize)
480.1238 - if not data:
480.1239 - break
480.1240 - buffers.append(data)
480.1241 - nl = data.find('\n')
480.1242 - if nl >= 0:
480.1243 - nl += 1
480.1244 - self._rbuf = data[nl:]
480.1245 - buffers[-1] = data[:nl]
480.1246 - break
480.1247 - return "".join(buffers)
480.1248 - else:
480.1249 - # Read until size bytes or \n or EOF seen, whichever comes first
480.1250 - nl = data.find('\n', 0, size)
480.1251 - if nl >= 0:
480.1252 - nl += 1
480.1253 - self._rbuf = data[nl:]
480.1254 - return data[:nl]
480.1255 - buf_len = len(data)
480.1256 - if buf_len >= size:
480.1257 - self._rbuf = data[size:]
480.1258 - return data[:size]
480.1259 - buffers = []
480.1260 - if data:
480.1261 - buffers.append(data)
480.1262 - self._rbuf = ""
480.1263 - while True:
480.1264 - data = self._sock.recv(self._rbufsize)
480.1265 - if not data:
480.1266 - break
480.1267 - buffers.append(data)
480.1268 - left = size - buf_len
480.1269 - nl = data.find('\n', 0, left)
480.1270 - if nl >= 0:
480.1271 - nl += 1
480.1272 - self._rbuf = data[nl:]
480.1273 - buffers[-1] = data[:nl]
480.1274 - break
480.1275 - n = len(data)
480.1276 - if n >= left:
480.1277 - self._rbuf = data[left:]
480.1278 - buffers[-1] = data[:left]
480.1279 - break
480.1280 - buf_len += n
480.1281 - return "".join(buffers)
480.1282 -
480.1283 - def readlines(self, sizehint=0):
480.1284 - total = 0
480.1285 - list = []
480.1286 - while True:
480.1287 - line = self.readline()
480.1288 - if not line:
480.1289 - break
480.1290 - list.append(line)
480.1291 - total += len(line)
480.1292 - if sizehint and total >= sizehint:
480.1293 - break
480.1294 - return list
480.1295 -
480.1296 - # Iterator protocols
480.1297 -
480.1298 - def __iter__(self):
480.1299 - return self
480.1300 -
480.1301 - def next(self):
480.1302 - line = self.readline()
480.1303 - if not line:
480.1304 - raise StopIteration
480.1305 - return line
480.1306 -
480.1307 -
480.1308 -# Define the SSL support
480.1309 -
480.1310 -class ssl:
480.1311 -
480.1312 - def __init__(self, plain_sock, keyfile=None, certfile=None):
480.1313 - self.ssl_sock = self.make_ssl_socket(plain_sock)
480.1314 -
480.1315 - def make_ssl_socket(self, plain_socket, auto_close=0):
480.1316 - java_net_socket = plain_socket._get_jsocket()
480.1317 - assert isinstance(java_net_socket, java.net.Socket)
480.1318 - host = java_net_socket.getInetAddress().getHostAddress()
480.1319 - port = java_net_socket.getPort()
480.1320 - factory = javax.net.ssl.SSLSocketFactory.getDefault();
480.1321 - ssl_socket = factory.createSocket(java_net_socket, host, port, auto_close)
480.1322 - ssl_socket.setEnabledCipherSuites(ssl_socket.getSupportedCipherSuites())
480.1323 - ssl_socket.startHandshake()
480.1324 - return ssl_socket
480.1325 -
480.1326 - def read(self, n=4096):
480.1327 - # Probably needs some work on efficency
480.1328 - in_buf = java.io.BufferedInputStream(self.ssl_sock.getInputStream())
480.1329 - data = jarray.zeros(n, 'b')
480.1330 - m = in_buf.read(data, 0, n)
480.1331 - if m <= 0:
480.1332 - return ""
480.1333 - if m < n:
480.1334 - data = data[:m]
480.1335 - return data.tostring()
480.1336 -
480.1337 - def write(self, s):
480.1338 - # Probably needs some work on efficency
480.1339 - out = java.io.BufferedOutputStream(self.ssl_sock.getOutputStream())
480.1340 - out.write(s)
480.1341 - out.flush()
480.1342 -
480.1343 - def _get_server_cert(self):
480.1344 - return self.ssl_sock.getSession().getPeerCertificates()[0]
480.1345 -
480.1346 - def server(self):
480.1347 - cert = self._get_server_cert()
480.1348 - return cert.getSubjectDN().toString()
480.1349 -
480.1350 - def issuer(self):
480.1351 - cert = self._get_server_cert()
480.1352 - return cert.getIssuerDN().toString()
480.1353 -
480.1354 -_realssl = ssl
480.1355 -def ssl(sock, keyfile=None, certfile=None):
480.1356 - if hasattr(sock, "_sock"):
480.1357 - sock = sock._sock
480.1358 - return _realssl(sock, keyfile, certfile)
480.1359 -
480.1360 -def test():
480.1361 - s = socket(AF_INET, SOCK_STREAM)
480.1362 - s.connect(("", 80))
480.1363 - s.send("GET / HTTP/1.0\r\n\r\n")
480.1364 - while 1:
480.1365 - data = s.recv(2000)
480.1366 - print data
480.1367 - if not data:
480.1368 - break
480.1369 -
480.1370 -if __name__ == '__main__':
480.1371 - test()
481.1 --- a/python.editor/test/unit/data/testfiles/socket.py.indexed Sun Jan 04 13:11:53 2015 -0600
481.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
481.3 @@ -1,486 +0,0 @@
481.4 -
481.5 -
481.6 -Document 0
481.7 -Searchable Keys:
481.8 - class : SocketType
481.9 - class-ig : sockettype
481.10 - extends : object
481.11 - in : socket
481.12 - member : __doc__;D;|PRIVATE|;
481.13 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,family,type,proto,_sock;
481.14 - member : __slots__;D;|PRIVATE|;
481.15 - member : _m;D;|PRIVATE|;
481.16 - member : _s;D;|PRIVATE|;
481.17 - member : _sock;D;|PRIVATE|;
481.18 - member : accept;F;|PRIVATE|;self;
481.19 - member : close;F;|PRIVATE|;self;
481.20 - member : dup;F;|PRIVATE|;self;
481.21 - member : family;D;|PRIVATE|;
481.22 - member : makefile;F;|PRIVATE|;self,mode,bufsize;
481.23 - member : proto;D;|PRIVATE|;
481.24 - member : recv;D;;
481.25 - member : recvfrom;D;;
481.26 - member : send;D;;
481.27 - member : sendto;D;;
481.28 - member : type;D;|PRIVATE|;
481.29 -
481.30 -Not Searchable Keys:
481.31 -
481.32 -
481.33 -Document 1
481.34 -Searchable Keys:
481.35 - class : _client_socket_impl
481.36 - class-ig : _client_socket_impl
481.37 - extends : _nio_impl
481.38 - in : socket
481.39 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,socket;
481.40 - member : bind;F;|PRIVATE|;self,host,port,reuse_addr;
481.41 - member : connect;F;|PRIVATE|;self,host,port;
481.42 - member : finish_connect;F;|PRIVATE|;self;
481.43 - member : host;D;;
481.44 - member : jchannel;D;;
481.45 - member : jsocket;D;;
481.46 - member : options;D;|PRIVATE|;
481.47 - member : port;D;;
481.48 - member : socketio;D;;
481.49 -
481.50 -Not Searchable Keys:
481.51 - clzattrs : ;|PRIVATE|;
481.52 -
481.53 -
481.54 -Document 2
481.55 -Searchable Keys:
481.56 - class : _closedsocket
481.57 - class-ig : _closedsocket
481.58 - extends : object
481.59 - in : socket
481.60 - member : __getattr__;F;|PRIVATE|;args;
481.61 - member : __slots__;D;|PRIVATE|;
481.62 - member : _dummy;F;|PRIVATE|;args;
481.63 - member : recv;F;|PRIVATE|;args;
481.64 - member : recv_into;F;|PRIVATE|;args;
481.65 - member : recvfrom;F;|PRIVATE|;args;
481.66 - member : recvfrom_into;F;|PRIVATE|;args;
481.67 - member : send;F;|PRIVATE|;args;
481.68 - member : sendto;F;|PRIVATE|;args;
481.69 -
481.70 -Not Searchable Keys:
481.71 - clzattrs : ;|PRIVATE|;
481.72 -
481.73 -
481.74 -Document 3
481.75 -Searchable Keys:
481.76 - class : _datagram_socket_impl
481.77 - class-ig : _datagram_socket_impl
481.78 - extends : _nio_impl
481.79 - in : socket
481.80 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,port,address,reuse_addr;
481.81 - member : _do_receive_net;F;|PRIVATE|;self,return_source_address,num_bytes,flags;
481.82 - member : _do_receive_nio;F;|PRIVATE|;self,return_source_address,num_bytes,flags;
481.83 - member : _do_send_net;F;|PRIVATE|;self,byte_array,socket_address,flags;
481.84 - member : _do_send_nio;F;|PRIVATE|;self,byte_array,socket_address,flags;
481.85 - member : connect;F;|PRIVATE|;self,host,port;
481.86 - member : disconnect;F;|PRIVATE|;self;
481.87 - member : finish_connect;F;|PRIVATE|;self;
481.88 - member : jchannel;D;;
481.89 - member : jsocket;D;;
481.90 - member : options;D;|PRIVATE|;
481.91 - member : recv;F;|PRIVATE|;self,num_bytes,flags;
481.92 - member : recvfrom;F;|PRIVATE|;self,num_bytes,flags;
481.93 - member : send;F;|PRIVATE|;self,byte_array,flags;
481.94 - member : sendto;F;|PRIVATE|;self,byte_array,host,port,flags;
481.95 - member : socketio;D;;
481.96 -
481.97 -Not Searchable Keys:
481.98 - clzattrs : ;|PRIVATE|;
481.99 -
481.100 -
481.101 -Document 4
481.102 -Searchable Keys:
481.103 - class : _fileobject
481.104 - class-ig : _fileobject
481.105 - extends : object
481.106 - in : socket
481.107 - member : __del__;F;|PRIVATE|;self;
481.108 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,sock,mode,bufsize,close;
481.109 - member : __iter__;F;|PRIVATE|;self;
481.110 - member : __slots__;D;|PRIVATE|;
481.111 - member : _close;D;|PRIVATE|;
481.112 - member : _get_wbuf_len;F;|PRIVATE|;self;
481.113 - member : _getclosed;F;|PRIVATE|;self;
481.114 - member : _rbuf;D;|PRIVATE|;
481.115 - member : _rbufsize;D;|PRIVATE|;
481.116 - member : _sock;D;|PRIVATE|;
481.117 - member : _wbuf;D;|PRIVATE|;
481.118 - member : _wbufsize;D;|PRIVATE|;
481.119 - member : bufsize;D;;
481.120 - member : close;F;|PRIVATE|;self;
481.121 - member : closed;D;|PRIVATE|;
481.122 - member : default_bufsize;D;|PRIVATE|;
481.123 - member : fileno;F;|PRIVATE|;self;
481.124 - member : flush;F;|PRIVATE|;self;
481.125 - member : mode;D;;
481.126 - member : name;D;|PRIVATE|;
481.127 - member : next;F;|PRIVATE|;self;
481.128 - member : read;F;|PRIVATE|;self,size;
481.129 - member : readline;F;|PRIVATE|;self,size;
481.130 - member : readlines;F;|PRIVATE|;self,sizehint;
481.131 - member : softspace;D;;
481.132 - member : write;F;|PRIVATE|;self,data;
481.133 - member : writelines;F;|PRIVATE|;self,list;
481.134 -
481.135 -Not Searchable Keys:
481.136 - clzattrs : ;|PRIVATE|;
481.137 -
481.138 -
481.139 -Document 5
481.140 -Searchable Keys:
481.141 - class : _nio_impl
481.142 - class-ig : _nio_impl
481.143 - in : socket
481.144 - member : _timeout_millis;D;|PRIVATE|;
481.145 - member : close;F;|PRIVATE|;self;
481.146 - member : config;F;|PRIVATE|;self,mode,timeout;
481.147 - member : fileno;F;|PRIVATE|;self;
481.148 - member : getchannel;F;|PRIVATE|;self;
481.149 - member : getpeername;F;|PRIVATE|;self;
481.150 - member : getsockopt;F;|PRIVATE|;self,option;
481.151 - member : mode;D;;
481.152 - member : mode;D;|PRIVATE|;
481.153 - member : read;F;|PRIVATE|;self,buf;
481.154 - member : setsockopt;F;|PRIVATE|;self,option,value;
481.155 - member : shutdownInput;F;|PRIVATE|;self;
481.156 - member : shutdownOutput;F;|PRIVATE|;self;
481.157 - member : timeout;D;|PRIVATE|;
481.158 - member : write;F;|PRIVATE|;self,buf;
481.159 -
481.160 -Not Searchable Keys:
481.161 - clzattrs : ;|PRIVATE|;
481.162 -
481.163 -
481.164 -Document 6
481.165 -Searchable Keys:
481.166 - class : _nonblocking_api_mixin
481.167 - class-ig : _nonblocking_api_mixin
481.168 - in : socket
481.169 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self;
481.170 - member : _config;F;|PRIVATE|;self;
481.171 - member : _get_jsocket;F;|PRIVATE|;self;
481.172 - member : close_lock;D;|PRIVATE|;
481.173 - member : fileno;F;|PRIVATE|;self;
481.174 - member : getblocking;F;|PRIVATE|;self;
481.175 - member : getchannel;F;|PRIVATE|;self;
481.176 - member : getsockopt;F;|PRIVATE|;self,level,optname;
481.177 - member : gettimeout;F;|PRIVATE|;self;
481.178 - member : mode;D;;
481.179 - member : mode;D;|PRIVATE|;
481.180 - member : pending_options;D;;
481.181 - member : reference_count;D;|PRIVATE|;
481.182 - member : setblocking;F;|PRIVATE|;self,flag;
481.183 - member : setsockopt;F;|PRIVATE|;self,level,optname,value;
481.184 - member : settimeout;F;|PRIVATE|;self,timeout;
481.185 - member : timeout;D;;
481.186 - member : timeout;D;|PRIVATE|;
481.187 -
481.188 -Not Searchable Keys:
481.189 - clzattrs : ;|PRIVATE|;
481.190 -
481.191 -
481.192 -Document 7
481.193 -Searchable Keys:
481.194 - class : _realssl
481.195 - class-ig : _realssl
481.196 - in : socket
481.197 - member : __init__;c;|CONSTRUCTOR|;self,plain_sock,keyfile,certfile;
481.198 - member : _get_server_cert;F;|PRIVATE|;self;
481.199 - member : issuer;F;;self;
481.200 - member : make_ssl_socket;F;;self,plain_socket,auto_close;
481.201 - member : read;F;;self,n;
481.202 - member : server;F;;self;
481.203 - member : ssl_sock;D;;
481.204 - member : write;F;;self,s;
481.205 -
481.206 -Not Searchable Keys:
481.207 - clzattrs : ;|PRIVATE|;
481.208 -
481.209 -
481.210 -Document 8
481.211 -Searchable Keys:
481.212 - class : _server_socket_impl
481.213 - class-ig : _server_socket_impl
481.214 - extends : _nio_impl
481.215 - in : socket
481.216 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,host,port,backlog,reuse_addr;
481.217 - member : accept;F;|PRIVATE|;self;
481.218 - member : jchannel;D;;
481.219 - member : jsocket;D;;
481.220 - member : options;D;|PRIVATE|;
481.221 - member : socketio;D;;
481.222 -
481.223 -Not Searchable Keys:
481.224 - clzattrs : ;|PRIVATE|;
481.225 -
481.226 -
481.227 -Document 9
481.228 -Searchable Keys:
481.229 - class : _socketobject
481.230 - class-ig : _socketobject
481.231 - extends : object
481.232 - in : socket
481.233 - member : __doc__;D;|PRIVATE|;
481.234 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,family,type,proto,_sock;
481.235 - member : __slots__;D;|PRIVATE|;
481.236 - member : _m;D;|PRIVATE|;
481.237 - member : _s;D;|PRIVATE|;
481.238 - member : _sock;D;|PRIVATE|;
481.239 - member : accept;F;|PRIVATE|;self;
481.240 - member : close;F;|PRIVATE|;self;
481.241 - member : dup;F;|PRIVATE|;self;
481.242 - member : family;D;|PRIVATE|;
481.243 - member : makefile;F;|PRIVATE|;self,mode,bufsize;
481.244 - member : proto;D;|PRIVATE|;
481.245 - member : recv;D;;
481.246 - member : recvfrom;D;;
481.247 - member : send;D;;
481.248 - member : sendto;D;;
481.249 - member : type;D;|PRIVATE|;
481.250 -
481.251 -Not Searchable Keys:
481.252 - clzattrs : ;|PRIVATE|;
481.253 -
481.254 -
481.255 -Document 10
481.256 -Searchable Keys:
481.257 - class : _tcpsocket
481.258 - class-ig : _tcpsocket
481.259 - extends : _nonblocking_api_mixin
481.260 - in : socket
481.261 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self;
481.262 - member : _do_connect;F;|PRIVATE|;self,addr;
481.263 - member : _get_host_port;F;|PRIVATE|;self,addr;
481.264 - member : _setup;F;|PRIVATE|;self;
481.265 - member : accept;F;|PRIVATE|;self;
481.266 - member : bind;F;|PRIVATE|;self,addr;
481.267 - member : close;F;|PRIVATE|;self;
481.268 - member : connect;F;|PRIVATE|;self,addr;
481.269 - member : connect_ex;F;|PRIVATE|;self,addr;
481.270 - member : getpeername;F;|PRIVATE|;self;
481.271 - member : getsockname;F;|PRIVATE|;self;
481.272 - member : istream;D;;
481.273 - member : istream;D;|PRIVATE|;
481.274 - member : listen;F;|PRIVATE|;self,backlog;
481.275 - member : local_addr;D;;
481.276 - member : local_addr;D;|PRIVATE|;
481.277 - member : ostream;D;;
481.278 - member : ostream;D;|PRIVATE|;
481.279 - member : recv;F;|PRIVATE|;self,n;
481.280 - member : recvfrom;F;|PRIVATE|;self,n;
481.281 - member : send;F;|PRIVATE|;self,s;
481.282 - member : sendall;F;|PRIVATE|;self,s;
481.283 - member : server;D;;
481.284 - member : server;D;|PRIVATE|;
481.285 - member : shutdown;F;|PRIVATE|;self,how;
481.286 - member : sock_impl;D;;
481.287 - member : sock_impl;D;|PRIVATE|;
481.288 -
481.289 -Not Searchable Keys:
481.290 - clzattrs : ;|PRIVATE|;
481.291 -
481.292 -
481.293 -Document 11
481.294 -Searchable Keys:
481.295 - class : _udpsocket
481.296 - class-ig : _udpsocket
481.297 - extends : _nonblocking_api_mixin
481.298 - in : socket
481.299 - member : __del__;F;|PRIVATE|;self;
481.300 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self;
481.301 - member : _do_connect;F;|PRIVATE|;self,addr;
481.302 - member : addr;D;;
481.303 - member : addr;D;|PRIVATE|;
481.304 - member : bind;F;|PRIVATE|;self,addr;
481.305 - member : close;F;|PRIVATE|;self;
481.306 - member : connect;F;|PRIVATE|;self,addr;
481.307 - member : connect_ex;F;|PRIVATE|;self,addr;
481.308 - member : getpeername;F;|PRIVATE|;self;
481.309 - member : getsockname;F;|PRIVATE|;self;
481.310 - member : recv;F;|PRIVATE|;self,num_bytes,flags;
481.311 - member : recvfrom;F;|PRIVATE|;self,num_bytes,flags;
481.312 - member : send;F;|PRIVATE|;self,data,flags;
481.313 - member : sendto;F;|PRIVATE|;self,data,p1,p2;
481.314 - member : sock_impl;D;;
481.315 - member : sock_impl;D;|PRIVATE|;
481.316 -
481.317 -Not Searchable Keys:
481.318 - clzattrs : ;|PRIVATE|;
481.319 -
481.320 -
481.321 -Document 12
481.322 -Searchable Keys:
481.323 - class : error
481.324 - class-ig : error
481.325 - extends : Exception
481.326 - in : socket
481.327 -
481.328 -Not Searchable Keys:
481.329 -
481.330 -
481.331 -Document 13
481.332 -Searchable Keys:
481.333 - class : gaierror
481.334 - class-ig : gaierror
481.335 - extends : error
481.336 - in : socket
481.337 -
481.338 -Not Searchable Keys:
481.339 -
481.340 -
481.341 -Document 14
481.342 -Searchable Keys:
481.343 - class : herror
481.344 - class-ig : herror
481.345 - extends : error
481.346 - in : socket
481.347 -
481.348 -Not Searchable Keys:
481.349 -
481.350 -
481.351 -Document 15
481.352 -Searchable Keys:
481.353 - class : socket
481.354 - class-ig : socket
481.355 - extends : object
481.356 - in : socket
481.357 - member : __doc__;D;|PRIVATE|;
481.358 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,family,type,proto,_sock;
481.359 - member : __slots__;D;|PRIVATE|;
481.360 - member : _m;D;|PRIVATE|;
481.361 - member : _s;D;|PRIVATE|;
481.362 - member : _sock;D;|PRIVATE|;
481.363 - member : accept;F;|PRIVATE|;self;
481.364 - member : close;F;|PRIVATE|;self;
481.365 - member : dup;F;|PRIVATE|;self;
481.366 - member : family;D;|PRIVATE|;
481.367 - member : makefile;F;|PRIVATE|;self,mode,bufsize;
481.368 - member : proto;D;|PRIVATE|;
481.369 - member : recv;D;;
481.370 - member : recvfrom;D;;
481.371 - member : send;D;;
481.372 - member : sendto;D;;
481.373 - member : type;D;|PRIVATE|;
481.374 -
481.375 -Not Searchable Keys:
481.376 -
481.377 -
481.378 -Document 16
481.379 -Searchable Keys:
481.380 - class : timeout
481.381 - class-ig : timeout
481.382 - extends : error
481.383 - in : socket
481.384 -
481.385 -Not Searchable Keys:
481.386 -
481.387 -
481.388 -Document 17
481.389 -Searchable Keys:
481.390 - item : AF_INET6;D;;
481.391 - item : AF_INET;D;;
481.392 - item : AF_UNSPEC;D;;
481.393 - item : AI_PASSIVE;D;;
481.394 - item : ALL;D;|PRIVATE|;
481.395 - item : MODE_BLOCKING;D;|PRIVATE|;
481.396 - item : MODE_NONBLOCKING;D;|PRIVATE|;
481.397 - item : MODE_TIMEOUT;D;|PRIVATE|;
481.398 - item : SHUT_RD;D;;
481.399 - item : SHUT_RDWR;D;;
481.400 - item : SHUT_WR;D;;
481.401 - item : SOCK_DGRAM;D;;
481.402 - item : SOCK_RAW;D;;
481.403 - item : SOCK_RDM;D;;
481.404 - item : SOCK_SEQPACKET;D;;
481.405 - item : SOCK_STREAM;D;;
481.406 - item : SOL_SOCKET;D;;
481.407 - item : SO_ACCEPTCONN;D;|PRIVATE|;
481.408 - item : SO_BROADCAST;D;;
481.409 - item : SO_DEBUG;D;|PRIVATE|;
481.410 - item : SO_DONTROUTE;D;|PRIVATE|;
481.411 - item : SO_ERROR;D;;
481.412 - item : SO_EXCLUSIVEADDRUSE;D;|PRIVATE|;
481.413 - item : SO_KEEPALIVE;D;;
481.414 - item : SO_LINGER;D;;
481.415 - item : SO_OOBINLINE;D;;
481.416 - item : SO_RCVBUF;D;;
481.417 - item : SO_RCVLOWAT;D;|PRIVATE|;
481.418 - item : SO_RCVTIMEO;D;|PRIVATE|;
481.419 - item : SO_REUSEADDR;D;;
481.420 - item : SO_REUSEPORT;D;|PRIVATE|;
481.421 - item : SO_SNDBUF;D;;
481.422 - item : SO_SNDLOWAT;D;|PRIVATE|;
481.423 - item : SO_SNDTIMEO;D;|PRIVATE|;
481.424 - item : SO_TIMEOUT;D;;
481.425 - item : SO_TYPE;D;|PRIVATE|;
481.426 - item : SO_USELOOPBACK;D;|PRIVATE|;
481.427 - item : SocketType;C;;
481.428 - item : TCP_NODELAY;D;;
481.429 - item : __all__;D;;
481.430 - item : _calctimeoutvalue;F;|PRIVATE|;value;
481.431 - item : _client_socket_impl;C;|PRIVATE|;
481.432 - item : _closedsocket;C;|PRIVATE|;
481.433 - item : _datagram_socket_impl;C;|PRIVATE|;
481.434 - item : _defaulttimeout;D;|PRIVATE|;
481.435 - item : _delegate_methods;D;|PRIVATE|;
481.436 - item : _exception_map;D;|PRIVATE|;
481.437 - item : _fileobject;C;|PRIVATE|;
481.438 - item : _gethostbyaddr;F;|PRIVATE|;name;
481.439 - item : _map_exception;F;|PRIVATE|;exc,circumstance;
481.440 - item : _nio_impl;C;|PRIVATE|;
481.441 - item : _nonblocking_api_mixin;C;|PRIVATE|;
481.442 - item : _permitted_modes;D;|PRIVATE|;
481.443 - item : _realsocket;F;|PRIVATE|;family,type,flags;
481.444 - item : _realssl;C;|PRIVATE|;
481.445 - item : _server_socket_impl;C;|PRIVATE|;
481.446 - item : _socketmethods;D;|PRIVATE|;
481.447 - item : _socketobject;C;|PRIVATE|;
481.448 - item : _tcpsocket;C;|PRIVATE|;
481.449 - item : _udpsocket;C;|PRIVATE|;
481.450 - item : _unpack_address_tuple;F;|PRIVATE|;address_tuple,for_tx;
481.451 - item : asPyString;I;|PRIVATE|;
481.452 - item : errno;I;|PRIVATE|;
481.453 - item : error;C;;
481.454 - item : gaierror;C;;
481.455 - item : getaddrinfo;F;;host,port,family,socktype,proto,flags;
481.456 - item : getdefaulttimeout;F;;;
481.457 - item : getfqdn;F;;name;
481.458 - item : gethostbyaddr;F;;name;
481.459 - item : gethostbyname;F;;name;
481.460 - item : gethostname;F;;;
481.461 - item : getnameinfo;F;|PRIVATE|;sock_addr,flags;
481.462 - item : getprotobyname;F;|PRIVATE|;protocolname;
481.463 - item : getservbyname;F;|PRIVATE|;servicename,protocolname;
481.464 - item : getservbyport;F;|PRIVATE|;port,protocolname;
481.465 - item : has_ipv6;D;;
481.466 - item : herror;C;;
481.467 - item : htonl;F;;x;
481.468 - item : htons;F;;x;
481.469 - item : jarray;I;|PRIVATE|;
481.470 - item : java;I;|PRIVATE|;
481.471 - item : javax;I;|PRIVATE|;
481.472 - item : ntohl;F;;x;
481.473 - item : ntohs;F;;x;
481.474 - item : org;I;|PRIVATE|;
481.475 - item : setdefaulttimeout;F;;timeout;
481.476 - item : socket;C;;
481.477 - item : ssl;C;|PRIVATE|;
481.478 - item : string;I;|PRIVATE|;
481.479 - item : struct;I;|PRIVATE|;
481.480 - item : sys;I;|PRIVATE|;
481.481 - item : test;F;|PRIVATE|;;
481.482 - item : threading;I;|PRIVATE|;
481.483 - item : time;I;|PRIVATE|;
481.484 - item : timeout;C;;
481.485 - item : types;I;|PRIVATE|;
481.486 - item : would_block_error;F;|PRIVATE|;exc;
481.487 - module : socket
481.488 -
481.489 -Not Searchable Keys:
482.1 --- a/python.editor/test/unit/data/testfiles/split_imports.py Sun Jan 04 13:11:53 2015 -0600
482.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
482.3 @@ -1,10 +0,0 @@
482.4 -import os
482.5 -import sys
482.6 -import sys, os
482.7 -import sys, os, foobar
482.8 -import sys as foo, os
482.9 -import sys, os as bar
482.10 -import sys as whatever, os as bar
482.11 -from subprocess import Popen, PIPE
482.12 -
482.13 -
483.1 --- a/python.editor/test/unit/data/testfiles/split_imports.py.testFix1.fixed Sun Jan 04 13:11:53 2015 -0600
483.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
483.3 @@ -1,11 +0,0 @@
483.4 -import os
483.5 -import sys
483.6 -import sys
483.7 -import os
483.8 -import sys, os, foobar
483.9 -import sys as foo, os
483.10 -import sys, os as bar
483.11 -import sys as whatever, os as bar
483.12 -from subprocess import Popen, PIPE
483.13 -
483.14 -
484.1 --- a/python.editor/test/unit/data/testfiles/split_imports.py.testFix2.fixed Sun Jan 04 13:11:53 2015 -0600
484.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
484.3 @@ -1,11 +0,0 @@
484.4 -import os
484.5 -import sys
484.6 -import sys, os
484.7 -import sys, os, foobar
484.8 -import sys as foo, os
484.9 -import sys
484.10 -import os as bar
484.11 -import sys as whatever, os as bar
484.12 -from subprocess import Popen, PIPE
484.13 -
484.14 -
485.1 --- a/python.editor/test/unit/data/testfiles/split_imports.py.testHint1.hints Sun Jan 04 13:11:53 2015 -0600
485.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
485.3 @@ -1,20 +0,0 @@
485.4 -import sys, os
485.5 ---------------
485.6 -HINT:Multiple imports per import statement is discouraged
485.7 -FIX:Split import into individual import statements
485.8 -import sys, os, foobar
485.9 -----------------------
485.10 -HINT:Multiple imports per import statement is discouraged
485.11 -FIX:Split import into individual import statements
485.12 -import sys as foo, os
485.13 ----------------------
485.14 -HINT:Multiple imports per import statement is discouraged
485.15 -FIX:Split import into individual import statements
485.16 -import sys, os as bar
485.17 ----------------------
485.18 -HINT:Multiple imports per import statement is discouraged
485.19 -FIX:Split import into individual import statements
485.20 -import sys as whatever, os as bar
485.21 ----------------------------------
485.22 -HINT:Multiple imports per import statement is discouraged
485.23 -FIX:Split import into individual import statements
486.1 --- a/python.editor/test/unit/data/testfiles/star_arg.py Sun Jan 04 13:11:53 2015 -0600
486.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
486.3 @@ -1,12 +0,0 @@
486.4 -def myfunc(funcparam):
486.5 - localvar = 1
486.6 - toplevelvar4 = 6
486.7 - fn(*args)
486.8 - x*3
486.9 - print toplevelvar4
486.10 -
486.11 - x = myfunc
486.12 - myfunc(5)
486.13 - x()
486.14 - pass
486.15 -
487.1 --- a/python.editor/test/unit/data/testfiles/star_arg.py.formatted Sun Jan 04 13:11:53 2015 -0600
487.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
487.3 @@ -1,12 +0,0 @@
487.4 -def myfunc(funcparam):
487.5 - localvar = 1
487.6 - toplevelvar4 = 6
487.7 - fn(*args)
487.8 - x * 3
487.9 - print toplevelvar4
487.10 -
487.11 - x = myfunc
487.12 - myfunc(5)
487.13 - x()
487.14 - pass
487.15 -
488.1 --- a/python.editor/test/unit/data/testfiles/staticmethods.py Sun Jan 04 13:11:53 2015 -0600
488.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
488.3 @@ -1,14 +0,0 @@
488.4 -class Page(object):
488.5 - def __init__(self, name, entity=None):
488.6 - self.name = name
488.7 - self.entity = entity
488.8 -
488.9 - @staticmethod
488.10 - def load(name):
488.11 - pass
488.12 -
488.13 - @staticmethod
488.14 - def exists(name):
488.15 - pass
488.16 -
488.17 -
489.1 --- a/python.editor/test/unit/data/testfiles/staticmethods.py.offsets Sun Jan 04 13:11:53 2015 -0600
489.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
489.3 @@ -1,15 +0,0 @@
489.4 -
489.5 -<Module><ClassDef>class Page(<Name>object</Name>):
489.6 - <FunctionDef>def __init__(<Name>self</Name>, <Name>name</Name>, <Name>entity</Name>=<Name>None</Name>):
489.7 - <Assign><Attribute><Name>self</Name>.name</Attribute> = <Name>name</Name></Assign>
489.8 - <Assign><Attribute><Name>self</Name>.entity</Attribute> = <Name>entity</Name></Assign>
489.9 -
489.10 - </FunctionDef> <FunctionDef><Name>@staticmethod
489.11 -</Name> def load(<Name>name</Name>):
489.12 - <Pass>pass</Pass>
489.13 -
489.14 - </FunctionDef> <FunctionDef><Name>@staticmethod
489.15 -</Name> def exists(<Name>name</Name>):
489.16 - <Pass>pass</Pass>
489.17 -
489.18 -</FunctionDef></ClassDef></Module>
490.1 --- a/python.editor/test/unit/data/testfiles/staticmethods.py.semantic Sun Jan 04 13:11:53 2015 -0600
490.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
490.3 @@ -1,14 +0,0 @@
490.4 -class Page(object):
490.5 - def |>METHOD:__init__<|(|>PARAMETER:self<|, |>PARAMETER:name<|, |>PARAMETER:entity<|=None):
490.6 - |>PARAMETER:self<|.name = |>PARAMETER:name<|
490.7 - |>PARAMETER:self<|.entity = |>PARAMETER:entity<|
490.8 -
490.9 - @staticmethod
490.10 - def |>METHOD:load<|(|>PARAMETER,UNUSED:name<|):
490.11 - pass
490.12 -
490.13 - @staticmethod
490.14 - def |>METHOD:exists<|(|>PARAMETER,UNUSED:name<|):
490.15 - pass
490.16 -
490.17 -
491.1 --- a/python.editor/test/unit/data/testfiles/surround.py Sun Jan 04 13:11:53 2015 -0600
491.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
491.3 @@ -1,7 +0,0 @@
491.4 -def loadstable(name,theglobals=None,thelocals=None,fromlist=None,level=-1):
491.5 - if name.split('.')[0]!=theglobals
491.6 - print "first"
491.7 - print "second"
491.8 - print "third"
491.9 -
491.10 -
492.1 --- a/python.editor/test/unit/data/testfiles/surround.py.testFix4.fixed Sun Jan 04 13:11:53 2015 -0600
492.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
492.3 @@ -1,10 +0,0 @@
492.4 -def loadstable(name,theglobals=None,thelocals=None,fromlist=None,level=-1):
492.5 - if name.split('.')[0]!=theglobals
492.6 - print "first"
492.7 - try:
492.8 - print "second"
492.9 - finally:
492.10 -
492.11 - print "third"
492.12 -
492.13 -
493.1 --- a/python.editor/test/unit/data/testfiles/syntax-string.py.txt Sun Jan 04 13:11:53 2015 -0600
493.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
493.3 @@ -1,63 +0,0 @@
493.4 -.t.e.s.t. Escapes
493.5 -Here's an \nescape, here's another one: \\, and here's several: \n\\\\\\
493.6 -Here's an unbalanced one \
493.7 -.e.o.f.
493.8 -
493.9 -.t.e.s.t. URLs
493.10 -See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
493.11 -See https://foobar/baz
493.12 -
493.13 -For more about DST than you ever wanted to know, see
493.14 -ftp://elsie.nci.nih.gov/pub/
493.15 -.e.o.f.
493.16 -
493.17 -.t.e.s.t. String 1
493.18 -
493.19 -This is the "example" module.
493.20 -
493.21 -The example module supplies one function, factorial(). For example,
493.22 -
493.23 ->>> factorial(5)
493.24 -120
493.25 -.e.o.f.
493.26 -
493.27 -.t.e.s.t. String 2
493.28 -Return the factorial of n, an exact integer >= 0.
493.29 -
493.30 - If the result is small enough to fit in an int, return an int.
493.31 - Else return a long.
493.32 -
493.33 - >>> [factorial(n) for n in range(6)]
493.34 - [1, 1, 2, 6, 24, 120]
493.35 - >>> [factorial(long(n)) for n in range(6)]
493.36 - [1, 1, 2, 6, 24, 120]
493.37 - >>> factorial(30)
493.38 - 265252859812191058636308480000000L
493.39 - >>> factorial(30L)
493.40 - 265252859812191058636308480000000L
493.41 - >>> factorial(-1)
493.42 - Traceback (most recent call last):
493.43 - ...
493.44 - ValueError: n must be >= 0
493.45 - x = \n foo
493.46 -
493.47 - Factorials of floats are OK, but the float must be an exact integer:
493.48 - >>> factorial(30.1)
493.49 - Traceback (most recent call last):
493.50 - ...
493.51 - ValueError: n must be exact integer
493.52 - >>> factorial(30.0)
493.53 - 265252859812191058636308480000000L
493.54 -
493.55 - It must also not be ridiculously large:
493.56 - >>> factorial(1e100)
493.57 - Traceback (most recent call last):
493.58 - ...
493.59 - OverflowError: n too large
493.60 -
493.61 -.e.o.f.
493.62 -.t.e.s.t. Errors
493.63 -Here's another one:
493.64 ->> Wrong
493.65 ->>>
493.66 -.e.o.f.
494.1 --- a/python.editor/test/unit/data/testfiles/syntax-string.py.txt.tokens.txt Sun Jan 04 13:11:53 2015 -0600
494.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
494.3 @@ -1,59 +0,0 @@
494.4 -.t.e.s.t. Escapes
494.5 -STRING_TEXT "Here's an ", la=1
494.6 -STRING_ESCAPE "\\n"
494.7 -STRING_TEXT "escape, here's another one: ", la=1
494.8 -STRING_ESCAPE "\\\\"
494.9 -STRING_TEXT ", and here's several: ", la=1
494.10 -STRING_ESCAPE "\\n"
494.11 -STRING_ESCAPE "\\\\"
494.12 -STRING_ESCAPE "\\\\"
494.13 -STRING_ESCAPE "\\\\"
494.14 -STRING_TEXT "\nHere's an unbalanced one ", la=1
494.15 -STRING_INVALID "\\", la=1
494.16 ------ EOF -----
494.17 -
494.18 -.t.e.s.t. URLs
494.19 -STRING_TEXT "See ", la=58
494.20 -URL "http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage", la=1
494.21 -STRING_TEXT "\nSee ", la=19
494.22 -URL "https://foobar/baz", la=1
494.23 -STRING_TEXT "\n\nFor more about DST than you ever wanted to know, see\n", la=29
494.24 -URL "ftp://elsie.nci.nih.gov/pub/", la=1
494.25 ------ EOF -----
494.26 -
494.27 -.t.e.s.t. String 1
494.28 -STRING_TEXT "This is the "example" module.\n\nThe example module supplies one function, factorial(). For example,\n\n", la=3
494.29 -EMBEDDED_PYTHON ">>> factorial(5)", la=1
494.30 -STRING_TEXT "\n120", la=1
494.31 ------ EOF -----
494.32 -
494.33 -.t.e.s.t. String 2
494.34 -STRING_TEXT "Return the factorial of n, an exact integer >= 0.\n\n If the result is small enough to fit in an int, return an int.\n Else return a long.\n\n ", la=3
494.35 -EMBEDDED_PYTHON ">>> [factorial(n) for n in range(6)]", la=1
494.36 -STRING_TEXT "\n [1, 1, 2, 6, 24, 120]\n ", la=3
494.37 -EMBEDDED_PYTHON ">>> [factorial(long(n)) for n in range(6)]", la=1
494.38 -STRING_TEXT "\n [1, 1, 2, 6, 24, 120]\n ", la=3
494.39 -EMBEDDED_PYTHON ">>> factorial(30)", la=1
494.40 -STRING_TEXT "\n 265252859812191058636308480000000L\n ", la=3
494.41 -EMBEDDED_PYTHON ">>> factorial(30L)", la=1
494.42 -STRING_TEXT "\n 265252859812191058636308480000000L\n ", la=3
494.43 -EMBEDDED_PYTHON ">>> factorial(-1)", la=1
494.44 -STRING_TEXT "\n Traceback (most recent call last):\n ...\n ValueError: n must be >= 0\n x = ", la=1
494.45 -STRING_ESCAPE "\\n"
494.46 -STRING_TEXT " foo\n\n Factorials of floats are OK, but the float must be an exact integer:\n ", la=3
494.47 -EMBEDDED_PYTHON ">>> factorial(30.1)", la=1
494.48 -STRING_TEXT "\n Traceback (most recent call last):\n ...\n ValueError: n must be exact integer\n ", la=3
494.49 -EMBEDDED_PYTHON ">>> factorial(30.0)", la=1
494.50 -STRING_TEXT "\n 265252859812191058636308480000000L\n\n It must also not be ridiculously large:\n ", la=3
494.51 -EMBEDDED_PYTHON ">>> factorial(1e100)", la=1
494.52 -STRING_TEXT "\n Traceback (most recent call last):\n ...\n OverflowError: n too large\n ", la=1
494.53 ------ EOF -----
494.54 -
494.55 -.t.e.s.t. Errors
494.56 -STRING_TEXT "Here's another one:\n>> Wrong\n", la=3
494.57 -STRING_TEXT ">>>", la=1
494.58 ------ EOF -----
494.59 -
494.60 -<Unnamed test>
494.61 ------ EOF -----
494.62 -
495.1 --- a/python.editor/test/unit/data/testfiles/syntax.py.txt Sun Jan 04 13:11:53 2015 -0600
495.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
495.3 @@ -1,75 +0,0 @@
495.4 -.t.e.s.t. Keywords
495.5 -and del from not while
495.6 -as elif global or with
495.7 -assert else if pass yield
495.8 -break except import print
495.9 -class exec in raise
495.10 -continue finally is return
495.11 -def for lambda try
495.12 -.e.o.f.
495.13 -
495.14 -.t.e.s.t. Decorators
495.15 -@staticmethod
495.16 -@classmethod
495.17 -.e.o.f.
495.18 -
495.19 -.t.e.s.t. Strings
495.20 -r'foo'
495.21 -UR'foo'
495.22 -u"foo"
495.23 -'foo\bbar'
495.24 -"foo\nbar"
495.25 -'''triple'''
495.26 -"""when no section matches a requested option."""
495.27 -"""triple"""
495.28 -.e.o.f.
495.29 -
495.30 -.t.e.s.t. Integers and Long Integers
495.31 -7 2147483647 0177
495.32 -3L 79228162514264337593543950336L 0377L 0x100000000L
495.33 - 79228162514264337593543950336 0xdeadbeef
495.34 -.e.o.f.
495.35 -
495.36 -.t.e.s.t. Floating point numbers
495.37 -3.14 10. .001 1e100 3.14e-10 0e0
495.38 -.e.o.f.
495.39 -
495.40 -.t.e.s.t. Imaginary literals
495.41 -3.14j 10.j 10j .001j 1e100j 3.14e-10j
495.42 -.e.o.f.
495.43 -
495.44 -.t.e.s.t. Operators
495.45 -+ - * ** / // %
495.46 -<< >> & | ^ ~
495.47 -< > <= >= == != <>
495.48 -.e.o.f.
495.49 -
495.50 -.t.e.s.t. Delimiters
495.51 -( ) [ ] { } @
495.52 -, : . ` = ;
495.53 -+= -= *= /= //= %=
495.54 -&= |= ^= >>= <<= **=
495.55 -.e.o.f.
495.56 -
495.57 -.t.e.s.t. Comments
495.58 -# This is a line comment
495.59 -code()#More comments
495.60 -.e.o.f.
495.61 -
495.62 -.t.e.s.t. Identifiers
495.63 -a ab aB2 x
495.64 -yZ_
495.65 -z
495.66 -.e.o.f.
495.67 -
495.68 -.t.e.s.t. Joined Lines
495.69 -if 1900 < year < 2100 and 1 <= month <= 12 \
495.70 - and 1 <= day <= 31 and 0 <= hour < 24 \
495.71 - and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
495.72 - return 1
495.73 -.e.o.f.
495.74 -
495.75 -.t.e.s.t. Not an identifier, not a keyword
495.76 -2a
495.77 -None
495.78 -.e.o.f.
496.1 --- a/python.editor/test/unit/data/testfiles/syntax.py.txt.tokens.txt Sun Jan 04 13:11:53 2015 -0600
496.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
496.3 @@ -1,374 +0,0 @@
496.4 -.t.e.s.t. Keywords
496.5 -ANY_KEYWORD "and", la=1, st=INIT
496.6 -WHITESPACE " ", la=1, st=INIT
496.7 -ANY_KEYWORD "del", la=1, st=INIT
496.8 -WHITESPACE " ", la=1, st=INIT
496.9 -FROM "from", la=1, st=INIT
496.10 -WHITESPACE " ", la=1, st=INIT
496.11 -ANY_KEYWORD "not", la=1, st=INIT
496.12 -WHITESPACE " ", la=1, st=INIT
496.13 -ANY_KEYWORD "while", la=1, st=INIT
496.14 -WHITESPACE " ", la=1, st=INIT
496.15 -NEWLINE "\n", st=INIT
496.16 -ANY_KEYWORD "as", la=1, st=INIT
496.17 -WHITESPACE " ", la=1, st=INIT
496.18 -ELIF "elif", la=1, st=INIT
496.19 -WHITESPACE " ", la=1, st=INIT
496.20 -ANY_KEYWORD "global", la=1, st=INIT
496.21 -WHITESPACE " ", la=1, st=INIT
496.22 -ANY_KEYWORD "or", la=1, st=INIT
496.23 -WHITESPACE " ", la=1, st=INIT
496.24 -ANY_KEYWORD "with", la=1, st=INIT
496.25 -WHITESPACE " ", la=1, st=INIT
496.26 -NEWLINE "\n", st=INIT
496.27 -ANY_KEYWORD "assert", la=1, st=INIT
496.28 -WHITESPACE " ", la=1, st=INIT
496.29 -ELSE "else", la=1, st=INIT
496.30 -WHITESPACE " ", la=1, st=INIT
496.31 -IF "if", la=1, st=INIT
496.32 -WHITESPACE " ", la=1, st=INIT
496.33 -PASS "pass", la=1, st=INIT
496.34 -WHITESPACE " ", la=1, st=INIT
496.35 -ANY_KEYWORD "yield", la=1, st=INIT
496.36 -WHITESPACE " ", la=1, st=INIT
496.37 -NEWLINE "\n", st=INIT
496.38 -ANY_KEYWORD "break", la=1, st=INIT
496.39 -WHITESPACE " ", la=1, st=INIT
496.40 -EXCEPT "except", la=1, st=INIT
496.41 -WHITESPACE " ", la=1, st=INIT
496.42 -IMPORT "import", la=1, st=INIT
496.43 -WHITESPACE " ", la=1, st=INIT
496.44 -ANY_KEYWORD "print", la=1, st=INIT
496.45 -WHITESPACE " ", la=1, st=INIT
496.46 -NEWLINE "\n", st=INIT
496.47 -CLASS "class", la=1, st=INIT
496.48 -WHITESPACE " ", la=1, st=INIT
496.49 -ANY_KEYWORD "exec", la=1, st=INIT
496.50 -WHITESPACE " ", la=1, st=INIT
496.51 -ANY_KEYWORD "in", la=1, st=INIT
496.52 -WHITESPACE " ", la=1, st=INIT
496.53 -RAISE "raise", la=1, st=INIT
496.54 -WHITESPACE " ", la=1, st=INIT
496.55 -NEWLINE "\n", st=INIT
496.56 -ANY_KEYWORD "continue", la=1, st=INIT
496.57 -WHITESPACE " ", la=1, st=INIT
496.58 -FINALLY "finally", la=1, st=INIT
496.59 -WHITESPACE " ", la=1, st=INIT
496.60 -ANY_KEYWORD "is", la=1, st=INIT
496.61 -WHITESPACE " ", la=1, st=INIT
496.62 -RETURN "return", la=1, st=INIT
496.63 -WHITESPACE " ", la=1, st=INIT
496.64 -NEWLINE "\n", st=INIT
496.65 -DEF "def", la=1, st=INIT
496.66 -WHITESPACE " ", la=1, st=INIT
496.67 -ANY_KEYWORD "for", la=1, st=INIT
496.68 -WHITESPACE " ", la=1, st=INIT
496.69 -ANY_KEYWORD "lambda", la=1, st=INIT
496.70 -WHITESPACE " ", la=1, st=INIT
496.71 -TRY "try", la=1, st=INIT
496.72 ------ EOF -----
496.73 -
496.74 -.t.e.s.t. Decorators
496.75 -DECORATOR "@staticmethod", la=1, st=INIT
496.76 -NEWLINE "\n", st=INIT
496.77 -DECORATOR "@classmethod", la=1, st=INIT
496.78 ------ EOF -----
496.79 -
496.80 -.t.e.s.t. Strings
496.81 -STRING_BEGIN "r'", la=1, st=BEGIN_SHORTSTRING_SINGLE
496.82 -STRING_LITERAL "foo", la=1, st=END_SHORTSTRING_SINGLE
496.83 -STRING_END "'", st=INIT
496.84 -NEWLINE "\n", st=INIT
496.85 -STRING_BEGIN "UR'", la=1, st=BEGIN_SHORTSTRING_SINGLE
496.86 -STRING_LITERAL "foo", la=1, st=END_SHORTSTRING_SINGLE
496.87 -STRING_END "'", st=INIT
496.88 -NEWLINE "\n", st=INIT
496.89 -STRING_BEGIN "u"", la=1, st=BEGIN_SHORTSTRING_DOUBLE
496.90 -STRING_LITERAL "foo", la=1, st=END_SHORTSTRING_DOUBLE
496.91 -STRING_END """, st=INIT
496.92 -NEWLINE "\n", st=INIT
496.93 -STRING_BEGIN "'", la=1, st=BEGIN_SHORTSTRING_SINGLE
496.94 -STRING_LITERAL "foo\\bbar", la=1, st=END_SHORTSTRING_SINGLE
496.95 -STRING_END "'", st=INIT
496.96 -NEWLINE "\n", st=INIT
496.97 -STRING_BEGIN """, la=1, st=BEGIN_SHORTSTRING_DOUBLE
496.98 -STRING_LITERAL "foo\\nbar", la=1, st=END_SHORTSTRING_DOUBLE
496.99 -STRING_END """, st=INIT
496.100 -NEWLINE "\n", st=INIT
496.101 -STRING_BEGIN "'''", st=BEGIN_LONGSTRING_SINGLE
496.102 -STRING_LITERAL "triple", la=3, st=END_LONGSTRING_SINGLE
496.103 -STRING_END "'''", st=INIT
496.104 -NEWLINE "\n", st=INIT
496.105 -STRING_BEGIN """"", st=BEGIN_LONGSTRING_DOUBLE
496.106 -STRING_LITERAL "when no section matches a requested option.", la=3, st=END_LONGSTRING_DOUBLE
496.107 -STRING_END """"", st=INIT
496.108 -NEWLINE "\n", st=INIT
496.109 -STRING_BEGIN """"", st=BEGIN_LONGSTRING_DOUBLE
496.110 -STRING_LITERAL "triple", la=3, st=END_LONGSTRING_DOUBLE
496.111 -STRING_END """"", st=INIT
496.112 ------ EOF -----
496.113 -
496.114 -.t.e.s.t. Integers and Long Integers
496.115 -INT_LITERAL "7", la=1, st=INIT
496.116 -WHITESPACE " ", la=1, st=INIT
496.117 -INT_LITERAL "2147483647", la=1, st=INIT
496.118 -WHITESPACE " ", la=1, st=INIT
496.119 -INT_LITERAL "0177", la=1, st=INIT
496.120 -NEWLINE "\n", st=INIT
496.121 -INT_LITERAL "3L", st=INIT
496.122 -WHITESPACE " ", la=1, st=INIT
496.123 -INT_LITERAL "79228162514264337593543950336L", st=INIT
496.124 -WHITESPACE " ", la=1, st=INIT
496.125 -INT_LITERAL "0377L", st=INIT
496.126 -WHITESPACE " ", la=1, st=INIT
496.127 -INT_LITERAL "0x100000000L", st=INIT
496.128 -NEWLINE "\n", st=INIT
496.129 -WHITESPACE " ", la=1, st=INIT
496.130 -INT_LITERAL "79228162514264337593543950336", la=1, st=INIT
496.131 -WHITESPACE " ", la=1, st=INIT
496.132 -INT_LITERAL "0xdeadbeef", la=1, st=INIT
496.133 ------ EOF -----
496.134 -
496.135 -.t.e.s.t. Floating point numbers
496.136 -FLOAT_LITERAL "3.14", la=1, st=INIT
496.137 -WHITESPACE " ", la=1, st=INIT
496.138 -FLOAT_LITERAL "10.", la=1, st=INIT
496.139 -WHITESPACE " ", la=1, st=INIT
496.140 -FLOAT_LITERAL ".001", la=1, st=INIT
496.141 -WHITESPACE " ", la=1, st=INIT
496.142 -FLOAT_LITERAL "1e100", la=1, st=INIT
496.143 -WHITESPACE " ", la=1, st=INIT
496.144 -FLOAT_LITERAL "3.14e-10", la=1, st=INIT
496.145 -WHITESPACE " ", la=1, st=INIT
496.146 -FLOAT_LITERAL "0e0", la=1, st=INIT
496.147 ------ EOF -----
496.148 -
496.149 -.t.e.s.t. Imaginary literals
496.150 -FLOAT_LITERAL "3.14j", st=INIT
496.151 -WHITESPACE " ", la=1, st=INIT
496.152 -FLOAT_LITERAL "10.j", st=INIT
496.153 -WHITESPACE " ", la=1, st=INIT
496.154 -FLOAT_LITERAL "10j", st=INIT
496.155 -WHITESPACE " ", la=1, st=INIT
496.156 -FLOAT_LITERAL ".001j", st=INIT
496.157 -WHITESPACE " ", la=1, st=INIT
496.158 -FLOAT_LITERAL "1e100j", st=INIT
496.159 -WHITESPACE " ", la=1, st=INIT
496.160 -FLOAT_LITERAL "3.14e-10j", st=INIT
496.161 ------ EOF -----
496.162 -
496.163 -.t.e.s.t. Operators
496.164 -ANY_OPERATOR "+", la=1, st=INIT
496.165 -WHITESPACE " ", la=1, st=INIT
496.166 -ANY_OPERATOR "-", la=1, st=INIT
496.167 -WHITESPACE " ", la=1, st=INIT
496.168 -ANY_OPERATOR "*", la=1, st=INIT
496.169 -WHITESPACE " ", la=1, st=INIT
496.170 -ANY_OPERATOR "**", la=1, st=INIT
496.171 -WHITESPACE " ", la=1, st=INIT
496.172 -ANY_OPERATOR "/", la=1, st=INIT
496.173 -WHITESPACE " ", la=1, st=INIT
496.174 -ANY_OPERATOR "//", la=1, st=INIT
496.175 -WHITESPACE " ", la=1, st=INIT
496.176 -ANY_OPERATOR "%", la=1, st=INIT
496.177 -NEWLINE "\n", st=INIT
496.178 -ANY_OPERATOR "<<", la=1, st=INIT
496.179 -WHITESPACE " ", la=1, st=INIT
496.180 -ANY_OPERATOR ">>", la=1, st=INIT
496.181 -WHITESPACE " ", la=1, st=INIT
496.182 -ANY_OPERATOR "&", la=1, st=INIT
496.183 -WHITESPACE " ", la=1, st=INIT
496.184 -ANY_OPERATOR "|", la=1, st=INIT
496.185 -WHITESPACE " ", la=1, st=INIT
496.186 -ANY_OPERATOR "^", la=1, st=INIT
496.187 -WHITESPACE " ", la=1, st=INIT
496.188 -ANY_OPERATOR "~", st=INIT
496.189 -NEWLINE "\n", st=INIT
496.190 -ANY_OPERATOR "<", la=1, st=INIT
496.191 -WHITESPACE " ", la=1, st=INIT
496.192 -ANY_OPERATOR ">", la=1, st=INIT
496.193 -WHITESPACE " ", la=1, st=INIT
496.194 -ANY_OPERATOR "<=", st=INIT
496.195 -WHITESPACE " ", la=1, st=INIT
496.196 -ANY_OPERATOR ">=", st=INIT
496.197 -WHITESPACE " ", la=1, st=INIT
496.198 -ANY_OPERATOR "==", st=INIT
496.199 -WHITESPACE " ", la=1, st=INIT
496.200 -ANY_OPERATOR "!=", st=INIT
496.201 -WHITESPACE " ", la=1, st=INIT
496.202 -ANY_OPERATOR "<>", st=INIT
496.203 ------ EOF -----
496.204 -
496.205 -.t.e.s.t. Delimiters
496.206 -LPAREN "(", st=INIT
496.207 -WHITESPACE " ", la=1, st=INIT
496.208 -RPAREN ")", st=INIT
496.209 -WHITESPACE " ", la=1, st=INIT
496.210 -LBRACKET "[", st=INIT
496.211 -WHITESPACE " ", la=1, st=INIT
496.212 -RBRACKET "]", st=INIT
496.213 -WHITESPACE " ", la=1, st=INIT
496.214 -LBRACE "{", st=INIT
496.215 -WHITESPACE " ", la=1, st=INIT
496.216 -RBRACE "}", st=INIT
496.217 -WHITESPACE " ", la=1, st=INIT
496.218 -DECORATOR "@", la=1, st=INIT
496.219 -NEWLINE "\n", st=INIT
496.220 -COMMA ",", st=INIT
496.221 -WHITESPACE " ", la=1, st=INIT
496.222 -COLON ":", st=INIT
496.223 -WHITESPACE " ", la=1, st=INIT
496.224 -DOT ".", la=1, st=INIT
496.225 -WHITESPACE " ", la=1, st=INIT
496.226 -ANY_OPERATOR "`", st=INIT
496.227 -WHITESPACE " ", la=1, st=INIT
496.228 -ANY_OPERATOR "=", la=1, st=INIT
496.229 -WHITESPACE " ", la=1, st=INIT
496.230 -ANY_OPERATOR ";", st=INIT
496.231 -NEWLINE "\n", st=INIT
496.232 -ANY_OPERATOR "+=", st=INIT
496.233 -WHITESPACE " ", la=1, st=INIT
496.234 -ANY_OPERATOR "-=", st=INIT
496.235 -WHITESPACE " ", la=1, st=INIT
496.236 -ANY_OPERATOR "*=", st=INIT
496.237 -WHITESPACE " ", la=1, st=INIT
496.238 -ANY_OPERATOR "/=", st=INIT
496.239 -WHITESPACE " ", la=1, st=INIT
496.240 -ANY_OPERATOR "//=", st=INIT
496.241 -WHITESPACE " ", la=1, st=INIT
496.242 -ANY_OPERATOR "%=", st=INIT
496.243 -NEWLINE "\n", st=INIT
496.244 -ANY_OPERATOR "&=", st=INIT
496.245 -WHITESPACE " ", la=1, st=INIT
496.246 -ANY_OPERATOR "|=", st=INIT
496.247 -WHITESPACE " ", la=1, st=INIT
496.248 -ANY_OPERATOR "^=", st=INIT
496.249 -WHITESPACE " ", la=1, st=INIT
496.250 -ANY_OPERATOR ">>=", st=INIT
496.251 -WHITESPACE " ", la=1, st=INIT
496.252 -ANY_OPERATOR "<<=", st=INIT
496.253 -WHITESPACE " ", la=1, st=INIT
496.254 -ANY_OPERATOR "**=", st=INIT
496.255 ------ EOF -----
496.256 -
496.257 -.t.e.s.t. Comments
496.258 -COMMENT "# This is a line comment", la=1, st=INIT
496.259 -NEWLINE "\n", st=INIT
496.260 -IDENTIFIER "code", la=1, st=INIT
496.261 -LPAREN "(", st=INIT
496.262 -RPAREN ")", st=INIT
496.263 -COMMENT "#More comments", la=1, st=INIT
496.264 ------ EOF -----
496.265 -
496.266 -.t.e.s.t. Identifiers
496.267 -IDENTIFIER "a", la=1, st=INIT
496.268 -WHITESPACE " ", la=1, st=INIT
496.269 -IDENTIFIER "ab", la=1, st=INIT
496.270 -WHITESPACE " ", la=1, st=INIT
496.271 -IDENTIFIER "aB2", la=1, st=INIT
496.272 -WHITESPACE " ", la=1, st=INIT
496.273 -IDENTIFIER "x", la=1, st=INIT
496.274 -NEWLINE "\n", st=INIT
496.275 -IDENTIFIER "yZ_", la=1, st=INIT
496.276 -NEWLINE "\n", st=INIT
496.277 -IDENTIFIER "z", la=1, st=INIT
496.278 ------ EOF -----
496.279 -
496.280 -.t.e.s.t. Joined Lines
496.281 -IF "if", la=1, st=INIT
496.282 -WHITESPACE " ", la=1, st=INIT
496.283 -INT_LITERAL "1900", la=1, st=INIT
496.284 -WHITESPACE " ", la=1, st=INIT
496.285 -ANY_OPERATOR "<", la=1, st=INIT
496.286 -WHITESPACE " ", la=1, st=INIT
496.287 -IDENTIFIER "year", la=1, st=INIT
496.288 -WHITESPACE " ", la=1, st=INIT
496.289 -ANY_OPERATOR "<", la=1, st=INIT
496.290 -WHITESPACE " ", la=1, st=INIT
496.291 -INT_LITERAL "2100", la=1, st=INIT
496.292 -WHITESPACE " ", la=1, st=INIT
496.293 -ANY_KEYWORD "and", la=1, st=INIT
496.294 -WHITESPACE " ", la=1, st=INIT
496.295 -INT_LITERAL "1", la=1, st=INIT
496.296 -WHITESPACE " ", la=1, st=INIT
496.297 -ANY_OPERATOR "<=", st=INIT
496.298 -WHITESPACE " ", la=1, st=INIT
496.299 -IDENTIFIER "month", la=1, st=INIT
496.300 -WHITESPACE " ", la=1, st=INIT
496.301 -ANY_OPERATOR "<=", st=INIT
496.302 -WHITESPACE " ", la=1, st=INIT
496.303 -INT_LITERAL "12", la=1, st=INIT
496.304 -WHITESPACE " ", la=1, st=INIT
496.305 -ESC "\\", st=INIT
496.306 -NEWLINE "\n", st=INIT
496.307 -WHITESPACE " ", la=1, st=INIT
496.308 -ANY_KEYWORD "and", la=1, st=INIT
496.309 -WHITESPACE " ", la=1, st=INIT
496.310 -INT_LITERAL "1", la=1, st=INIT
496.311 -WHITESPACE " ", la=1, st=INIT
496.312 -ANY_OPERATOR "<=", st=INIT
496.313 -WHITESPACE " ", la=1, st=INIT
496.314 -IDENTIFIER "day", la=1, st=INIT
496.315 -WHITESPACE " ", la=1, st=INIT
496.316 -ANY_OPERATOR "<=", st=INIT
496.317 -WHITESPACE " ", la=1, st=INIT
496.318 -INT_LITERAL "31", la=1, st=INIT
496.319 -WHITESPACE " ", la=1, st=INIT
496.320 -ANY_KEYWORD "and", la=1, st=INIT
496.321 -WHITESPACE " ", la=1, st=INIT
496.322 -INT_LITERAL "0", la=1, st=INIT
496.323 -WHITESPACE " ", la=1, st=INIT
496.324 -ANY_OPERATOR "<=", st=INIT
496.325 -WHITESPACE " ", la=1, st=INIT
496.326 -IDENTIFIER "hour", la=1, st=INIT
496.327 -WHITESPACE " ", la=1, st=INIT
496.328 -ANY_OPERATOR "<", la=1, st=INIT
496.329 -WHITESPACE " ", la=1, st=INIT
496.330 -INT_LITERAL "24", la=1, st=INIT
496.331 -WHITESPACE " ", la=1, st=INIT
496.332 -ESC "\\", st=INIT
496.333 -NEWLINE "\n", st=INIT
496.334 -WHITESPACE " ", la=1, st=INIT
496.335 -ANY_KEYWORD "and", la=1, st=INIT
496.336 -WHITESPACE " ", la=1, st=INIT
496.337 -INT_LITERAL "0", la=1, st=INIT
496.338 -WHITESPACE " ", la=1, st=INIT
496.339 -ANY_OPERATOR "<=", st=INIT
496.340 -WHITESPACE " ", la=1, st=INIT
496.341 -IDENTIFIER "minute", la=1, st=INIT
496.342 -WHITESPACE " ", la=1, st=INIT
496.343 -ANY_OPERATOR "<", la=1, st=INIT
496.344 -WHITESPACE " ", la=1, st=INIT
496.345 -INT_LITERAL "60", la=1, st=INIT
496.346 -WHITESPACE " ", la=1, st=INIT
496.347 -ANY_KEYWORD "and", la=1, st=INIT
496.348 -WHITESPACE " ", la=1, st=INIT
496.349 -INT_LITERAL "0", la=1, st=INIT
496.350 -WHITESPACE " ", la=1, st=INIT
496.351 -ANY_OPERATOR "<=", st=INIT
496.352 -WHITESPACE " ", la=1, st=INIT
496.353 -IDENTIFIER "second", la=1, st=INIT
496.354 -WHITESPACE " ", la=1, st=INIT
496.355 -ANY_OPERATOR "<", la=1, st=INIT
496.356 -WHITESPACE " ", la=1, st=INIT
496.357 -INT_LITERAL "60", la=1, st=INIT
496.358 -COLON ":", st=INIT
496.359 -WHITESPACE " ", la=1, st=INIT
496.360 -COMMENT "# Looks like a valid date", la=1, st=INIT
496.361 -NEWLINE "\n", st=INIT
496.362 -WHITESPACE " ", la=1, st=INIT
496.363 -RETURN "return", la=1, st=INIT
496.364 -WHITESPACE " ", la=1, st=INIT
496.365 -INT_LITERAL "1", la=1, st=INIT
496.366 ------ EOF -----
496.367 -
496.368 -.t.e.s.t. Not an identifier, not a keyword
496.369 -INT_LITERAL "2", la=1, st=INIT
496.370 -IDENTIFIER "a", la=1, st=INIT
496.371 -NEWLINE "\n", st=INIT
496.372 -IDENTIFIER "None", la=1, st=INIT
496.373 ------ EOF -----
496.374 -
496.375 -<Unnamed test>
496.376 ------ EOF -----
496.377 -
497.1 --- a/python.editor/test/unit/data/testfiles/tarfile.py Sun Jan 04 13:11:53 2015 -0600
497.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
497.3 @@ -1,2176 +0,0 @@
497.4 -#!/usr/bin/env python
497.5 -# -*- coding: iso-8859-1 -*-
497.6 -#-------------------------------------------------------------------
497.7 -# tarfile.py
497.8 -#-------------------------------------------------------------------
497.9 -# Copyright (C) 2002 Lars Gustäbel <lars@gustaebel.de>
497.10 -# All rights reserved.
497.11 -#
497.12 -# Permission is hereby granted, free of charge, to any person
497.13 -# obtaining a copy of this software and associated documentation
497.14 -# files (the "Software"), to deal in the Software without
497.15 -# restriction, including without limitation the rights to use,
497.16 -# copy, modify, merge, publish, distribute, sublicense, and/or sell
497.17 -# copies of the Software, and to permit persons to whom the
497.18 -# Software is furnished to do so, subject to the following
497.19 -# conditions:
497.20 -#
497.21 -# The above copyright notice and this permission notice shall be
497.22 -# included in all copies or substantial portions of the Software.
497.23 -#
497.24 -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
497.25 -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
497.26 -# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
497.27 -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
497.28 -# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
497.29 -# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
497.30 -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
497.31 -# OTHER DEALINGS IN THE SOFTWARE.
497.32 -#
497.33 -"""Read from and write to tar format archives.
497.34 -"""
497.35 -
497.36 -__version__ = "$Revision: 53162 $"
497.37 -# $Source$
497.38 -
497.39 -version = "0.8.0"
497.40 -__author__ = "Lars Gustäbel (lars@gustaebel.de)"
497.41 -__date__ = "$Date: 2006-12-27 21:36:58 +1100 (Wed, 27 Dec 2006) $"
497.42 -__cvsid__ = "$Id: tarfile.py 53162 2006-12-27 10:36:58Z lars.gustaebel $"
497.43 -__credits__ = "Gustavo Niemeyer, Niels Gustäbel, Richard Townsend."
497.44 -
497.45 -#---------
497.46 -# Imports
497.47 -#---------
497.48 -import sys
497.49 -import os
497.50 -import shutil
497.51 -import stat
497.52 -import errno
497.53 -import time
497.54 -import struct
497.55 -import copy
497.56 -
497.57 -if sys.platform == 'mac':
497.58 - # This module needs work for MacOS9, especially in the area of pathname
497.59 - # handling. In many places it is assumed a simple substitution of / by the
497.60 - # local os.path.sep is good enough to convert pathnames, but this does not
497.61 - # work with the mac rooted:path:name versus :nonrooted:path:name syntax
497.62 - raise ImportError, "tarfile does not work for platform==mac"
497.63 -
497.64 -try:
497.65 - import grp, pwd
497.66 -except ImportError:
497.67 - grp = pwd = None
497.68 -
497.69 -# from tarfile import *
497.70 -__all__ = ["TarFile", "TarInfo", "is_tarfile", "TarError"]
497.71 -
497.72 -#---------------------------------------------------------
497.73 -# tar constants
497.74 -#---------------------------------------------------------
497.75 -NUL = "\0" # the null character
497.76 -BLOCKSIZE = 512 # length of processing blocks
497.77 -RECORDSIZE = BLOCKSIZE * 20 # length of records
497.78 -MAGIC = "ustar" # magic tar string
497.79 -VERSION = "00" # version number
497.80 -
497.81 -LENGTH_NAME = 100 # maximum length of a filename
497.82 -LENGTH_LINK = 100 # maximum length of a linkname
497.83 -LENGTH_PREFIX = 155 # maximum length of the prefix field
497.84 -MAXSIZE_MEMBER = 077777777777L # maximum size of a file (11 octal digits)
497.85 -
497.86 -REGTYPE = "0" # regular file
497.87 -AREGTYPE = "\0" # regular file
497.88 -LNKTYPE = "1" # link (inside tarfile)
497.89 -SYMTYPE = "2" # symbolic link
497.90 -CHRTYPE = "3" # character special device
497.91 -BLKTYPE = "4" # block special device
497.92 -DIRTYPE = "5" # directory
497.93 -FIFOTYPE = "6" # fifo special device
497.94 -CONTTYPE = "7" # contiguous file
497.95 -
497.96 -GNUTYPE_LONGNAME = "L" # GNU tar extension for longnames
497.97 -GNUTYPE_LONGLINK = "K" # GNU tar extension for longlink
497.98 -GNUTYPE_SPARSE = "S" # GNU tar extension for sparse file
497.99 -
497.100 -#---------------------------------------------------------
497.101 -# tarfile constants
497.102 -#---------------------------------------------------------
497.103 -SUPPORTED_TYPES = (REGTYPE, AREGTYPE, LNKTYPE, # file types that tarfile
497.104 - SYMTYPE, DIRTYPE, FIFOTYPE, # can cope with.
497.105 - CONTTYPE, CHRTYPE, BLKTYPE,
497.106 - GNUTYPE_LONGNAME, GNUTYPE_LONGLINK,
497.107 - GNUTYPE_SPARSE)
497.108 -
497.109 -REGULAR_TYPES = (REGTYPE, AREGTYPE, # file types that somehow
497.110 - CONTTYPE, GNUTYPE_SPARSE) # represent regular files
497.111 -
497.112 -#---------------------------------------------------------
497.113 -# Bits used in the mode field, values in octal.
497.114 -#---------------------------------------------------------
497.115 -S_IFLNK = 0120000 # symbolic link
497.116 -S_IFREG = 0100000 # regular file
497.117 -S_IFBLK = 0060000 # block device
497.118 -S_IFDIR = 0040000 # directory
497.119 -S_IFCHR = 0020000 # character device
497.120 -S_IFIFO = 0010000 # fifo
497.121 -
497.122 -TSUID = 04000 # set UID on execution
497.123 -TSGID = 02000 # set GID on execution
497.124 -TSVTX = 01000 # reserved
497.125 -
497.126 -TUREAD = 0400 # read by owner
497.127 -TUWRITE = 0200 # write by owner
497.128 -TUEXEC = 0100 # execute/search by owner
497.129 -TGREAD = 0040 # read by group
497.130 -TGWRITE = 0020 # write by group
497.131 -TGEXEC = 0010 # execute/search by group
497.132 -TOREAD = 0004 # read by other
497.133 -TOWRITE = 0002 # write by other
497.134 -TOEXEC = 0001 # execute/search by other
497.135 -
497.136 -#---------------------------------------------------------
497.137 -# Some useful functions
497.138 -#---------------------------------------------------------
497.139 -
497.140 -def stn(s, length):
497.141 - """Convert a python string to a null-terminated string buffer.
497.142 - """
497.143 - return s[:length] + (length - len(s)) * NUL
497.144 -
497.145 -def nti(s):
497.146 - """Convert a number field to a python number.
497.147 - """
497.148 - # There are two possible encodings for a number field, see
497.149 - # itn() below.
497.150 - if s[0] != chr(0200):
497.151 - n = int(s.rstrip(NUL + " ") or "0", 8)
497.152 - else:
497.153 - n = 0L
497.154 - for i in xrange(len(s) - 1):
497.155 - n <<= 8
497.156 - n += ord(s[i + 1])
497.157 - return n
497.158 -
497.159 -def itn(n, digits=8, posix=False):
497.160 - """Convert a python number to a number field.
497.161 - """
497.162 - # POSIX 1003.1-1988 requires numbers to be encoded as a string of
497.163 - # octal digits followed by a null-byte, this allows values up to
497.164 - # (8**(digits-1))-1. GNU tar allows storing numbers greater than
497.165 - # that if necessary. A leading 0200 byte indicates this particular
497.166 - # encoding, the following digits-1 bytes are a big-endian
497.167 - # representation. This allows values up to (256**(digits-1))-1.
497.168 - if 0 <= n < 8 ** (digits - 1):
497.169 - s = "%0*o" % (digits - 1, n) + NUL
497.170 - else:
497.171 - if posix:
497.172 - raise ValueError("overflow in number field")
497.173 -
497.174 - if n < 0:
497.175 - # XXX We mimic GNU tar's behaviour with negative numbers,
497.176 - # this could raise OverflowError.
497.177 - n = struct.unpack("L", struct.pack("l", n))[0]
497.178 -
497.179 - s = ""
497.180 - for i in xrange(digits - 1):
497.181 - s = chr(n & 0377) + s
497.182 - n >>= 8
497.183 - s = chr(0200) + s
497.184 - return s
497.185 -
497.186 -def calc_chksums(buf):
497.187 - """Calculate the checksum for a member's header by summing up all
497.188 - characters except for the chksum field which is treated as if
497.189 - it was filled with spaces. According to the GNU tar sources,
497.190 - some tars (Sun and NeXT) calculate chksum with signed char,
497.191 - which will be different if there are chars in the buffer with
497.192 - the high bit set. So we calculate two checksums, unsigned and
497.193 - signed.
497.194 - """
497.195 - unsigned_chksum = 256 + sum(struct.unpack("148B", buf[:148]) + struct.unpack("356B", buf[156:512]))
497.196 - signed_chksum = 256 + sum(struct.unpack("148b", buf[:148]) + struct.unpack("356b", buf[156:512]))
497.197 - return unsigned_chksum, signed_chksum
497.198 -
497.199 -def copyfileobj(src, dst, length=None):
497.200 - """Copy length bytes from fileobj src to fileobj dst.
497.201 - If length is None, copy the entire content.
497.202 - """
497.203 - if length == 0:
497.204 - return
497.205 - if length is None:
497.206 - shutil.copyfileobj(src, dst)
497.207 - return
497.208 -
497.209 - BUFSIZE = 16 * 1024
497.210 - blocks, remainder = divmod(length, BUFSIZE)
497.211 - for b in xrange(blocks):
497.212 - buf = src.read(BUFSIZE)
497.213 - if len(buf) < BUFSIZE:
497.214 - raise IOError("end of file reached")
497.215 - dst.write(buf)
497.216 -
497.217 - if remainder != 0:
497.218 - buf = src.read(remainder)
497.219 - if len(buf) < remainder:
497.220 - raise IOError("end of file reached")
497.221 - dst.write(buf)
497.222 - return
497.223 -
497.224 -filemode_table = (
497.225 - ((S_IFLNK, "l"),
497.226 - (S_IFREG, "-"),
497.227 - (S_IFBLK, "b"),
497.228 - (S_IFDIR, "d"),
497.229 - (S_IFCHR, "c"),
497.230 - (S_IFIFO, "p")),
497.231 -
497.232 - ((TUREAD, "r"),),
497.233 - ((TUWRITE, "w"),),
497.234 - ((TUEXEC|TSUID, "s"),
497.235 - (TSUID, "S"),
497.236 - (TUEXEC, "x")),
497.237 -
497.238 - ((TGREAD, "r"),),
497.239 - ((TGWRITE, "w"),),
497.240 - ((TGEXEC|TSGID, "s"),
497.241 - (TSGID, "S"),
497.242 - (TGEXEC, "x")),
497.243 -
497.244 - ((TOREAD, "r"),),
497.245 - ((TOWRITE, "w"),),
497.246 - ((TOEXEC|TSVTX, "t"),
497.247 - (TSVTX, "T"),
497.248 - (TOEXEC, "x"))
497.249 -)
497.250 -
497.251 -def filemode(mode):
497.252 - """Convert a file's mode to a string of the form
497.253 - -rwxrwxrwx.
497.254 - Used by TarFile.list()
497.255 - """
497.256 - perm = []
497.257 - for table in filemode_table:
497.258 - for bit, char in table:
497.259 - if mode & bit == bit:
497.260 - perm.append(char)
497.261 - break
497.262 - else:
497.263 - perm.append("-")
497.264 - return "".join(perm)
497.265 -
497.266 -if os.sep != "/":
497.267 - normpath = lambda path: os.path.normpath(path).replace(os.sep, "/")
497.268 -else:
497.269 - normpath = os.path.normpath
497.270 -
497.271 -class TarError(Exception):
497.272 - """Base exception."""
497.273 - pass
497.274 -class ExtractError(TarError):
497.275 - """General exception for extract errors."""
497.276 - pass
497.277 -class ReadError(TarError):
497.278 - """Exception for unreadble tar archives."""
497.279 - pass
497.280 -class CompressionError(TarError):
497.281 - """Exception for unavailable compression methods."""
497.282 - pass
497.283 -class StreamError(TarError):
497.284 - """Exception for unsupported operations on stream-like TarFiles."""
497.285 - pass
497.286 -
497.287 -#---------------------------
497.288 -# internal stream interface
497.289 -#---------------------------
497.290 -class _LowLevelFile:
497.291 - """Low-level file object. Supports reading and writing.
497.292 - It is used instead of a regular file object for streaming
497.293 - access.
497.294 - """
497.295 -
497.296 - def __init__(self, name, mode):
497.297 - mode = {
497.298 - "r": os.O_RDONLY,
497.299 - "w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
497.300 - }[mode]
497.301 - if hasattr(os, "O_BINARY"):
497.302 - mode |= os.O_BINARY
497.303 - self.fd = os.open(name, mode)
497.304 -
497.305 - def close(self):
497.306 - os.close(self.fd)
497.307 -
497.308 - def read(self, size):
497.309 - return os.read(self.fd, size)
497.310 -
497.311 - def write(self, s):
497.312 - os.write(self.fd, s)
497.313 -
497.314 -class _Stream:
497.315 - """Class that serves as an adapter between TarFile and
497.316 - a stream-like object. The stream-like object only
497.317 - needs to have a read() or write() method and is accessed
497.318 - blockwise. Use of gzip or bzip2 compression is possible.
497.319 - A stream-like object could be for example: sys.stdin,
497.320 - sys.stdout, a socket, a tape device etc.
497.321 -
497.322 - _Stream is intended to be used only internally.
497.323 - """
497.324 -
497.325 - def __init__(self, name, mode, comptype, fileobj, bufsize):
497.326 - """Construct a _Stream object.
497.327 - """
497.328 - self._extfileobj = True
497.329 - if fileobj is None:
497.330 - fileobj = _LowLevelFile(name, mode)
497.331 - self._extfileobj = False
497.332 -
497.333 - if comptype == '*':
497.334 - # Enable transparent compression detection for the
497.335 - # stream interface
497.336 - fileobj = _StreamProxy(fileobj)
497.337 - comptype = fileobj.getcomptype()
497.338 -
497.339 - self.name = name or ""
497.340 - self.mode = mode
497.341 - self.comptype = comptype
497.342 - self.fileobj = fileobj
497.343 - self.bufsize = bufsize
497.344 - self.buf = ""
497.345 - self.pos = 0L
497.346 - self.closed = False
497.347 -
497.348 - if comptype == "gz":
497.349 - try:
497.350 - import zlib
497.351 - except ImportError:
497.352 - raise CompressionError("zlib module is not available")
497.353 - self.zlib = zlib
497.354 - self.crc = zlib.crc32("")
497.355 - if mode == "r":
497.356 - self._init_read_gz()
497.357 - else:
497.358 - self._init_write_gz()
497.359 -
497.360 - if comptype == "bz2":
497.361 - try:
497.362 - import bz2
497.363 - except ImportError:
497.364 - raise CompressionError("bz2 module is not available")
497.365 - if mode == "r":
497.366 - self.dbuf = ""
497.367 - self.cmp = bz2.BZ2Decompressor()
497.368 - else:
497.369 - self.cmp = bz2.BZ2Compressor()
497.370 -
497.371 - def __del__(self):
497.372 - if hasattr(self, "closed") and not self.closed:
497.373 - self.close()
497.374 -
497.375 - def _init_write_gz(self):
497.376 - """Initialize for writing with gzip compression.
497.377 - """
497.378 - self.cmp = self.zlib.compressobj(9, self.zlib.DEFLATED,
497.379 - -self.zlib.MAX_WBITS,
497.380 - self.zlib.DEF_MEM_LEVEL,
497.381 - 0)
497.382 - timestamp = struct.pack("<L", long(time.time()))
497.383 - self.__write("\037\213\010\010%s\002\377" % timestamp)
497.384 - if self.name.endswith(".gz"):
497.385 - self.name = self.name[:-3]
497.386 - self.__write(self.name + NUL)
497.387 -
497.388 - def write(self, s):
497.389 - """Write string s to the stream.
497.390 - """
497.391 - if self.comptype == "gz":
497.392 - self.crc = self.zlib.crc32(s, self.crc)
497.393 - self.pos += len(s)
497.394 - if self.comptype != "tar":
497.395 - s = self.cmp.compress(s)
497.396 - self.__write(s)
497.397 -
497.398 - def __write(self, s):
497.399 - """Write string s to the stream if a whole new block
497.400 - is ready to be written.
497.401 - """
497.402 - self.buf += s
497.403 - while len(self.buf) > self.bufsize:
497.404 - self.fileobj.write(self.buf[:self.bufsize])
497.405 - self.buf = self.buf[self.bufsize:]
497.406 -
497.407 - def close(self):
497.408 - """Close the _Stream object. No operation should be
497.409 - done on it afterwards.
497.410 - """
497.411 - if self.closed:
497.412 - return
497.413 -
497.414 - if self.mode == "w" and self.comptype != "tar":
497.415 - self.buf += self.cmp.flush()
497.416 -
497.417 - if self.mode == "w" and self.buf:
497.418 - self.fileobj.write(self.buf)
497.419 - self.buf = ""
497.420 - if self.comptype == "gz":
497.421 - # The native zlib crc is an unsigned 32-bit integer, but
497.422 - # the Python wrapper implicitly casts that to a signed C
497.423 - # long. So, on a 32-bit box self.crc may "look negative",
497.424 - # while the same crc on a 64-bit box may "look positive".
497.425 - # To avoid irksome warnings from the `struct` module, force
497.426 - # it to look positive on all boxes.
497.427 - self.fileobj.write(struct.pack("<L", self.crc & 0xffffffffL))
497.428 - self.fileobj.write(struct.pack("<L", self.pos & 0xffffFFFFL))
497.429 -
497.430 - if not self._extfileobj:
497.431 - self.fileobj.close()
497.432 -
497.433 - self.closed = True
497.434 -
497.435 - def _init_read_gz(self):
497.436 - """Initialize for reading a gzip compressed fileobj.
497.437 - """
497.438 - self.cmp = self.zlib.decompressobj(-self.zlib.MAX_WBITS)
497.439 - self.dbuf = ""
497.440 -
497.441 - # taken from gzip.GzipFile with some alterations
497.442 - if self.__read(2) != "\037\213":
497.443 - raise ReadError("not a gzip file")
497.444 - if self.__read(1) != "\010":
497.445 - raise CompressionError("unsupported compression method")
497.446 -
497.447 - flag = ord(self.__read(1))
497.448 - self.__read(6)
497.449 -
497.450 - if flag & 4:
497.451 - xlen = ord(self.__read(1)) + 256 * ord(self.__read(1))
497.452 - self.read(xlen)
497.453 - if flag & 8:
497.454 - while True:
497.455 - s = self.__read(1)
497.456 - if not s or s == NUL:
497.457 - break
497.458 - if flag & 16:
497.459 - while True:
497.460 - s = self.__read(1)
497.461 - if not s or s == NUL:
497.462 - break
497.463 - if flag & 2:
497.464 - self.__read(2)
497.465 -
497.466 - def tell(self):
497.467 - """Return the stream's file pointer position.
497.468 - """
497.469 - return self.pos
497.470 -
497.471 - def seek(self, pos=0):
497.472 - """Set the stream's file pointer to pos. Negative seeking
497.473 - is forbidden.
497.474 - """
497.475 - if pos - self.pos >= 0:
497.476 - blocks, remainder = divmod(pos - self.pos, self.bufsize)
497.477 - for i in xrange(blocks):
497.478 - self.read(self.bufsize)
497.479 - self.read(remainder)
497.480 - else:
497.481 - raise StreamError("seeking backwards is not allowed")
497.482 - return self.pos
497.483 -
497.484 - def read(self, size=None):
497.485 - """Return the next size number of bytes from the stream.
497.486 - If size is not defined, return all bytes of the stream
497.487 - up to EOF.
497.488 - """
497.489 - if size is None:
497.490 - t = []
497.491 - while True:
497.492 - buf = self._read(self.bufsize)
497.493 - if not buf:
497.494 - break
497.495 - t.append(buf)
497.496 - buf = "".join(t)
497.497 - else:
497.498 - buf = self._read(size)
497.499 - self.pos += len(buf)
497.500 - return buf
497.501 -
497.502 - def _read(self, size):
497.503 - """Return size bytes from the stream.
497.504 - """
497.505 - if self.comptype == "tar":
497.506 - return self.__read(size)
497.507 -
497.508 - c = len(self.dbuf)
497.509 - t = [self.dbuf]
497.510 - while c < size:
497.511 - buf = self.__read(self.bufsize)
497.512 - if not buf:
497.513 - break
497.514 - buf = self.cmp.decompress(buf)
497.515 - t.append(buf)
497.516 - c += len(buf)
497.517 - t = "".join(t)
497.518 - self.dbuf = t[size:]
497.519 - return t[:size]
497.520 -
497.521 - def __read(self, size):
497.522 - """Return size bytes from stream. If internal buffer is empty,
497.523 - read another block from the stream.
497.524 - """
497.525 - c = len(self.buf)
497.526 - t = [self.buf]
497.527 - while c < size:
497.528 - buf = self.fileobj.read(self.bufsize)
497.529 - if not buf:
497.530 - break
497.531 - t.append(buf)
497.532 - c += len(buf)
497.533 - t = "".join(t)
497.534 - self.buf = t[size:]
497.535 - return t[:size]
497.536 -# class _Stream
497.537 -
497.538 -class _StreamProxy(object):
497.539 - """Small proxy class that enables transparent compression
497.540 - detection for the Stream interface (mode 'r|*').
497.541 - """
497.542 -
497.543 - def __init__(self, fileobj):
497.544 - self.fileobj = fileobj
497.545 - self.buf = self.fileobj.read(BLOCKSIZE)
497.546 -
497.547 - def read(self, size):
497.548 - self.read = self.fileobj.read
497.549 - return self.buf
497.550 -
497.551 - def getcomptype(self):
497.552 - if self.buf.startswith("\037\213\010"):
497.553 - return "gz"
497.554 - if self.buf.startswith("BZh91"):
497.555 - return "bz2"
497.556 - return "tar"
497.557 -
497.558 - def close(self):
497.559 - self.fileobj.close()
497.560 -# class StreamProxy
497.561 -
497.562 -class _BZ2Proxy(object):
497.563 - """Small proxy class that enables external file object
497.564 - support for "r:bz2" and "w:bz2" modes. This is actually
497.565 - a workaround for a limitation in bz2 module's BZ2File
497.566 - class which (unlike gzip.GzipFile) has no support for
497.567 - a file object argument.
497.568 - """
497.569 -
497.570 - blocksize = 16 * 1024
497.571 -
497.572 - def __init__(self, fileobj, mode):
497.573 - self.fileobj = fileobj
497.574 - self.mode = mode
497.575 - self.init()
497.576 -
497.577 - def init(self):
497.578 - import bz2
497.579 - self.pos = 0
497.580 - if self.mode == "r":
497.581 - self.bz2obj = bz2.BZ2Decompressor()
497.582 - self.fileobj.seek(0)
497.583 - self.buf = ""
497.584 - else:
497.585 - self.bz2obj = bz2.BZ2Compressor()
497.586 -
497.587 - def read(self, size):
497.588 - b = [self.buf]
497.589 - x = len(self.buf)
497.590 - while x < size:
497.591 - try:
497.592 - raw = self.fileobj.read(self.blocksize)
497.593 - data = self.bz2obj.decompress(raw)
497.594 - b.append(data)
497.595 - except EOFError:
497.596 - break
497.597 - x += len(data)
497.598 - self.buf = "".join(b)
497.599 -
497.600 - buf = self.buf[:size]
497.601 - self.buf = self.buf[size:]
497.602 - self.pos += len(buf)
497.603 - return buf
497.604 -
497.605 - def seek(self, pos):
497.606 - if pos < self.pos:
497.607 - self.init()
497.608 - self.read(pos - self.pos)
497.609 -
497.610 - def tell(self):
497.611 - return self.pos
497.612 -
497.613 - def write(self, data):
497.614 - self.pos += len(data)
497.615 - raw = self.bz2obj.compress(data)
497.616 - self.fileobj.write(raw)
497.617 -
497.618 - def close(self):
497.619 - if self.mode == "w":
497.620 - raw = self.bz2obj.flush()
497.621 - self.fileobj.write(raw)
497.622 - self.fileobj.close()
497.623 -# class _BZ2Proxy
497.624 -
497.625 -#------------------------
497.626 -# Extraction file object
497.627 -#------------------------
497.628 -class _FileInFile(object):
497.629 - """A thin wrapper around an existing file object that
497.630 - provides a part of its data as an individual file
497.631 - object.
497.632 - """
497.633 -
497.634 - def __init__(self, fileobj, offset, size, sparse=None):
497.635 - self.fileobj = fileobj
497.636 - self.offset = offset
497.637 - self.size = size
497.638 - self.sparse = sparse
497.639 - self.position = 0
497.640 -
497.641 - def tell(self):
497.642 - """Return the current file position.
497.643 - """
497.644 - return self.position
497.645 -
497.646 - def seek(self, position):
497.647 - """Seek to a position in the file.
497.648 - """
497.649 - self.position = position
497.650 -
497.651 - def read(self, size=None):
497.652 - """Read data from the file.
497.653 - """
497.654 - if size is None:
497.655 - size = self.size - self.position
497.656 - else:
497.657 - size = min(size, self.size - self.position)
497.658 -
497.659 - if self.sparse is None:
497.660 - return self.readnormal(size)
497.661 - else:
497.662 - return self.readsparse(size)
497.663 -
497.664 - def readnormal(self, size):
497.665 - """Read operation for regular files.
497.666 - """
497.667 - self.fileobj.seek(self.offset + self.position)
497.668 - self.position += size
497.669 - return self.fileobj.read(size)
497.670 -
497.671 - def readsparse(self, size):
497.672 - """Read operation for sparse files.
497.673 - """
497.674 - data = []
497.675 - while size > 0:
497.676 - buf = self.readsparsesection(size)
497.677 - if not buf:
497.678 - break
497.679 - size -= len(buf)
497.680 - data.append(buf)
497.681 - return "".join(data)
497.682 -
497.683 - def readsparsesection(self, size):
497.684 - """Read a single section of a sparse file.
497.685 - """
497.686 - section = self.sparse.find(self.position)
497.687 -
497.688 - if section is None:
497.689 - return ""
497.690 -
497.691 - size = min(size, section.offset + section.size - self.position)
497.692 -
497.693 - if isinstance(section, _data):
497.694 - realpos = section.realpos + self.position - section.offset
497.695 - self.fileobj.seek(self.offset + realpos)
497.696 - self.position += size
497.697 - return self.fileobj.read(size)
497.698 - else:
497.699 - self.position += size
497.700 - return NUL * size
497.701 -#class _FileInFile
497.702 -
497.703 -
497.704 -class ExFileObject(object):
497.705 - """File-like object for reading an archive member.
497.706 - Is returned by TarFile.extractfile().
497.707 - """
497.708 - blocksize = 1024
497.709 -
497.710 - def __init__(self, tarfile, tarinfo):
497.711 - self.fileobj = _FileInFile(tarfile.fileobj,
497.712 - tarinfo.offset_data,
497.713 - tarinfo.size,
497.714 - getattr(tarinfo, "sparse", None))
497.715 - self.name = tarinfo.name
497.716 - self.mode = "r"
497.717 - self.closed = False
497.718 - self.size = tarinfo.size
497.719 -
497.720 - self.position = 0
497.721 - self.buffer = ""
497.722 -
497.723 - def read(self, size=None):
497.724 - """Read at most size bytes from the file. If size is not
497.725 - present or None, read all data until EOF is reached.
497.726 - """
497.727 - if self.closed:
497.728 - raise ValueError("I/O operation on closed file")
497.729 -
497.730 - buf = ""
497.731 - if self.buffer:
497.732 - if size is None:
497.733 - buf = self.buffer
497.734 - self.buffer = ""
497.735 - else:
497.736 - buf = self.buffer[:size]
497.737 - self.buffer = self.buffer[size:]
497.738 -
497.739 - if size is None:
497.740 - buf += self.fileobj.read()
497.741 - else:
497.742 - buf += self.fileobj.read(size - len(buf))
497.743 -
497.744 - self.position += len(buf)
497.745 - return buf
497.746 -
497.747 - def readline(self, size=-1):
497.748 - """Read one entire line from the file. If size is present
497.749 - and non-negative, return a string with at most that
497.750 - size, which may be an incomplete line.
497.751 - """
497.752 - if self.closed:
497.753 - raise ValueError("I/O operation on closed file")
497.754 -
497.755 - if "\n" in self.buffer:
497.756 - pos = self.buffer.find("\n") + 1
497.757 - else:
497.758 - buffers = [self.buffer]
497.759 - while True:
497.760 - buf = self.fileobj.read(self.blocksize)
497.761 - buffers.append(buf)
497.762 - if not buf or "\n" in buf:
497.763 - self.buffer = "".join(buffers)
497.764 - pos = self.buffer.find("\n") + 1
497.765 - if pos == 0:
497.766 - # no newline found.
497.767 - pos = len(self.buffer)
497.768 - break
497.769 -
497.770 - if size != -1:
497.771 - pos = min(size, pos)
497.772 -
497.773 - buf = self.buffer[:pos]
497.774 - self.buffer = self.buffer[pos:]
497.775 - self.position += len(buf)
497.776 - return buf
497.777 -
497.778 - def readlines(self):
497.779 - """Return a list with all remaining lines.
497.780 - """
497.781 - result = []
497.782 - while True:
497.783 - line = self.readline()
497.784 - if not line: break
497.785 - result.append(line)
497.786 - return result
497.787 -
497.788 - def tell(self):
497.789 - """Return the current file position.
497.790 - """
497.791 - if self.closed:
497.792 - raise ValueError("I/O operation on closed file")
497.793 -
497.794 - return self.position
497.795 -
497.796 - def seek(self, pos, whence=os.SEEK_SET):
497.797 - """Seek to a position in the file.
497.798 - """
497.799 - if self.closed:
497.800 - raise ValueError("I/O operation on closed file")
497.801 -
497.802 - if whence == os.SEEK_SET:
497.803 - self.position = min(max(pos, 0), self.size)
497.804 - elif whence == os.SEEK_CUR:
497.805 - if pos < 0:
497.806 - self.position = max(self.position + pos, 0)
497.807 - else:
497.808 - self.position = min(self.position + pos, self.size)
497.809 - elif whence == os.SEEK_END:
497.810 - self.position = max(min(self.size + pos, self.size), 0)
497.811 - else:
497.812 - raise ValueError("Invalid argument")
497.813 -
497.814 - self.buffer = ""
497.815 - self.fileobj.seek(self.position)
497.816 -
497.817 - def close(self):
497.818 - """Close the file object.
497.819 - """
497.820 - self.closed = True
497.821 -
497.822 - def __iter__(self):
497.823 - """Get an iterator over the file's lines.
497.824 - """
497.825 - while True:
497.826 - line = self.readline()
497.827 - if not line:
497.828 - break
497.829 - yield line
497.830 -#class ExFileObject
497.831 -
497.832 -#------------------
497.833 -# Exported Classes
497.834 -#------------------
497.835 -class TarInfo(object):
497.836 - """Informational class which holds the details about an
497.837 - archive member given by a tar header block.
497.838 - TarInfo objects are returned by TarFile.getmember(),
497.839 - TarFile.getmembers() and TarFile.gettarinfo() and are
497.840 - usually created internally.
497.841 - """
497.842 -
497.843 - def __init__(self, name=""):
497.844 - """Construct a TarInfo object. name is the optional name
497.845 - of the member.
497.846 - """
497.847 - self.name = name # member name (dirnames must end with '/')
497.848 - self.mode = 0666 # file permissions
497.849 - self.uid = 0 # user id
497.850 - self.gid = 0 # group id
497.851 - self.size = 0 # file size
497.852 - self.mtime = 0 # modification time
497.853 - self.chksum = 0 # header checksum
497.854 - self.type = REGTYPE # member type
497.855 - self.linkname = "" # link name
497.856 - self.uname = "user" # user name
497.857 - self.gname = "group" # group name
497.858 - self.devmajor = 0 # device major number
497.859 - self.devminor = 0 # device minor number
497.860 -
497.861 - self.offset = 0 # the tar header starts here
497.862 - self.offset_data = 0 # the file's data starts here
497.863 -
497.864 - def __repr__(self):
497.865 - return "<%s %r at %#x>" % (self.__class__.__name__,self.name,id(self))
497.866 -
497.867 - @classmethod
497.868 - def frombuf(cls, buf):
497.869 - """Construct a TarInfo object from a 512 byte string buffer.
497.870 - """
497.871 - if len(buf) != BLOCKSIZE:
497.872 - raise ValueError("truncated header")
497.873 - if buf.count(NUL) == BLOCKSIZE:
497.874 - raise ValueError("empty header")
497.875 -
497.876 - tarinfo = cls()
497.877 - tarinfo.buf = buf
497.878 - tarinfo.name = buf[0:100].rstrip(NUL)
497.879 - tarinfo.mode = nti(buf[100:108])
497.880 - tarinfo.uid = nti(buf[108:116])
497.881 - tarinfo.gid = nti(buf[116:124])
497.882 - tarinfo.size = nti(buf[124:136])
497.883 - tarinfo.mtime = nti(buf[136:148])
497.884 - tarinfo.chksum = nti(buf[148:156])
497.885 - tarinfo.type = buf[156:157]
497.886 - tarinfo.linkname = buf[157:257].rstrip(NUL)
497.887 - tarinfo.uname = buf[265:297].rstrip(NUL)
497.888 - tarinfo.gname = buf[297:329].rstrip(NUL)
497.889 - tarinfo.devmajor = nti(buf[329:337])
497.890 - tarinfo.devminor = nti(buf[337:345])
497.891 - prefix = buf[345:500].rstrip(NUL)
497.892 -
497.893 - if prefix and not tarinfo.issparse():
497.894 - tarinfo.name = prefix + "/" + tarinfo.name
497.895 -
497.896 - if tarinfo.chksum not in calc_chksums(buf):
497.897 - raise ValueError("invalid header")
497.898 - return tarinfo
497.899 -
497.900 - def tobuf(self, posix=False):
497.901 - """Return a tar header as a string of 512 byte blocks.
497.902 - """
497.903 - buf = ""
497.904 - type = self.type
497.905 - prefix = ""
497.906 -
497.907 - if self.name.endswith("/"):
497.908 - type = DIRTYPE
497.909 -
497.910 - if type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):
497.911 - # Prevent "././@LongLink" from being normalized.
497.912 - name = self.name
497.913 - else:
497.914 - name = normpath(self.name)
497.915 -
497.916 - if type == DIRTYPE:
497.917 - # directories should end with '/'
497.918 - name += "/"
497.919 -
497.920 - linkname = self.linkname
497.921 - if linkname:
497.922 - # if linkname is empty we end up with a '.'
497.923 - linkname = normpath(linkname)
497.924 -
497.925 - if posix:
497.926 - if self.size > MAXSIZE_MEMBER:
497.927 - raise ValueError("file is too large (>= 8 GB)")
497.928 -
497.929 - if len(self.linkname) > LENGTH_LINK:
497.930 - raise ValueError("linkname is too long (>%d)" % (LENGTH_LINK))
497.931 -
497.932 - if len(name) > LENGTH_NAME:
497.933 - prefix = name[:LENGTH_PREFIX + 1]
497.934 - while prefix and prefix[-1] != "/":
497.935 - prefix = prefix[:-1]
497.936 -
497.937 - name = name[len(prefix):]
497.938 - prefix = prefix[:-1]
497.939 -
497.940 - if not prefix or len(name) > LENGTH_NAME:
497.941 - raise ValueError("name is too long")
497.942 -
497.943 - else:
497.944 - if len(self.linkname) > LENGTH_LINK:
497.945 - buf += self._create_gnulong(self.linkname, GNUTYPE_LONGLINK)
497.946 -
497.947 - if len(name) > LENGTH_NAME:
497.948 - buf += self._create_gnulong(name, GNUTYPE_LONGNAME)
497.949 -
497.950 - parts = [
497.951 - stn(name, 100),
497.952 - itn(self.mode & 07777, 8, posix),
497.953 - itn(self.uid, 8, posix),
497.954 - itn(self.gid, 8, posix),
497.955 - itn(self.size, 12, posix),
497.956 - itn(self.mtime, 12, posix),
497.957 - " ", # checksum field
497.958 - type,
497.959 - stn(self.linkname, 100),
497.960 - stn(MAGIC, 6),
497.961 - stn(VERSION, 2),
497.962 - stn(self.uname, 32),
497.963 - stn(self.gname, 32),
497.964 - itn(self.devmajor, 8, posix),
497.965 - itn(self.devminor, 8, posix),
497.966 - stn(prefix, 155)
497.967 - ]
497.968 -
497.969 - buf += struct.pack("%ds" % BLOCKSIZE, "".join(parts))
497.970 - chksum = calc_chksums(buf[-BLOCKSIZE:])[0]
497.971 - buf = buf[:-364] + "%06o\0" % chksum + buf[-357:]
497.972 - self.buf = buf
497.973 - return buf
497.974 -
497.975 - def _create_gnulong(self, name, type):
497.976 - """Create a GNU longname/longlink header from name.
497.977 - It consists of an extended tar header, with the length
497.978 - of the longname as size, followed by data blocks,
497.979 - which contain the longname as a null terminated string.
497.980 - """
497.981 - name += NUL
497.982 -
497.983 - tarinfo = self.__class__()
497.984 - tarinfo.name = "././@LongLink"
497.985 - tarinfo.type = type
497.986 - tarinfo.mode = 0
497.987 - tarinfo.size = len(name)
497.988 -
497.989 - # create extended header
497.990 - buf = tarinfo.tobuf()
497.991 - # create name blocks
497.992 - buf += name
497.993 - blocks, remainder = divmod(len(name), BLOCKSIZE)
497.994 - if remainder > 0:
497.995 - buf += (BLOCKSIZE - remainder) * NUL
497.996 - return buf
497.997 -
497.998 - def isreg(self):
497.999 - return self.type in REGULAR_TYPES
497.1000 - def isfile(self):
497.1001 - return self.isreg()
497.1002 - def isdir(self):
497.1003 - return self.type == DIRTYPE
497.1004 - def issym(self):
497.1005 - return self.type == SYMTYPE
497.1006 - def islnk(self):
497.1007 - return self.type == LNKTYPE
497.1008 - def ischr(self):
497.1009 - return self.type == CHRTYPE
497.1010 - def isblk(self):
497.1011 - return self.type == BLKTYPE
497.1012 - def isfifo(self):
497.1013 - return self.type == FIFOTYPE
497.1014 - def issparse(self):
497.1015 - return self.type == GNUTYPE_SPARSE
497.1016 - def isdev(self):
497.1017 - return self.type in (CHRTYPE, BLKTYPE, FIFOTYPE)
497.1018 -# class TarInfo
497.1019 -
497.1020 -class TarFile(object):
497.1021 - """The TarFile Class provides an interface to tar archives.
497.1022 - """
497.1023 -
497.1024 - debug = 0 # May be set from 0 (no msgs) to 3 (all msgs)
497.1025 -
497.1026 - dereference = False # If true, add content of linked file to the
497.1027 - # tar file, else the link.
497.1028 -
497.1029 - ignore_zeros = False # If true, skips empty or invalid blocks and
497.1030 - # continues processing.
497.1031 -
497.1032 - errorlevel = 0 # If 0, fatal errors only appear in debug
497.1033 - # messages (if debug >= 0). If > 0, errors
497.1034 - # are passed to the caller as exceptions.
497.1035 -
497.1036 - posix = False # If True, generates POSIX.1-1990-compliant
497.1037 - # archives (no GNU extensions!)
497.1038 -
497.1039 - fileobject = ExFileObject
497.1040 -
497.1041 - def __init__(self, name=None, mode="r", fileobj=None):
497.1042 - """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to
497.1043 - read from an existing archive, 'a' to append data to an existing
497.1044 - file or 'w' to create a new file overwriting an existing one. `mode'
497.1045 - defaults to 'r'.
497.1046 - If `fileobj' is given, it is used for reading or writing data. If it
497.1047 - can be determined, `mode' is overridden by `fileobj's mode.
497.1048 - `fileobj' is not closed, when TarFile is closed.
497.1049 - """
497.1050 - self.name = os.path.abspath(name)
497.1051 -
497.1052 - if len(mode) > 1 or mode not in "raw":
497.1053 - raise ValueError("mode must be 'r', 'a' or 'w'")
497.1054 - self._mode = mode
497.1055 - self.mode = {"r": "rb", "a": "r+b", "w": "wb"}[mode]
497.1056 -
497.1057 - if not fileobj:
497.1058 - fileobj = file(self.name, self.mode)
497.1059 - self._extfileobj = False
497.1060 - else:
497.1061 - if self.name is None and hasattr(fileobj, "name"):
497.1062 - self.name = os.path.abspath(fileobj.name)
497.1063 - if hasattr(fileobj, "mode"):
497.1064 - self.mode = fileobj.mode
497.1065 - self._extfileobj = True
497.1066 - self.fileobj = fileobj
497.1067 -
497.1068 - # Init datastructures
497.1069 - self.closed = False
497.1070 - self.members = [] # list of members as TarInfo objects
497.1071 - self._loaded = False # flag if all members have been read
497.1072 - self.offset = 0L # current position in the archive file
497.1073 - self.inodes = {} # dictionary caching the inodes of
497.1074 - # archive members already added
497.1075 -
497.1076 - if self._mode == "r":
497.1077 - self.firstmember = None
497.1078 - self.firstmember = self.next()
497.1079 -
497.1080 - if self._mode == "a":
497.1081 - # Move to the end of the archive,
497.1082 - # before the first empty block.
497.1083 - self.firstmember = None
497.1084 - while True:
497.1085 - try:
497.1086 - tarinfo = self.next()
497.1087 - except ReadError:
497.1088 - self.fileobj.seek(0)
497.1089 - break
497.1090 - if tarinfo is None:
497.1091 - self.fileobj.seek(- BLOCKSIZE, 1)
497.1092 - break
497.1093 -
497.1094 - if self._mode in "aw":
497.1095 - self._loaded = True
497.1096 -
497.1097 - #--------------------------------------------------------------------------
497.1098 - # Below are the classmethods which act as alternate constructors to the
497.1099 - # TarFile class. The open() method is the only one that is needed for
497.1100 - # public use; it is the "super"-constructor and is able to select an
497.1101 - # adequate "sub"-constructor for a particular compression using the mapping
497.1102 - # from OPEN_METH.
497.1103 - #
497.1104 - # This concept allows one to subclass TarFile without losing the comfort of
497.1105 - # the super-constructor. A sub-constructor is registered and made available
497.1106 - # by adding it to the mapping in OPEN_METH.
497.1107 -
497.1108 - @classmethod
497.1109 - def open(cls, name=None, mode="r", fileobj=None, bufsize=20*512):
497.1110 - """Open a tar archive for reading, writing or appending. Return
497.1111 - an appropriate TarFile class.
497.1112 -
497.1113 - mode:
497.1114 - 'r' or 'r:*' open for reading with transparent compression
497.1115 - 'r:' open for reading exclusively uncompressed
497.1116 - 'r:gz' open for reading with gzip compression
497.1117 - 'r:bz2' open for reading with bzip2 compression
497.1118 - 'a' or 'a:' open for appending
497.1119 - 'w' or 'w:' open for writing without compression
497.1120 - 'w:gz' open for writing with gzip compression
497.1121 - 'w:bz2' open for writing with bzip2 compression
497.1122 -
497.1123 - 'r|*' open a stream of tar blocks with transparent compression
497.1124 - 'r|' open an uncompressed stream of tar blocks for reading
497.1125 - 'r|gz' open a gzip compressed stream of tar blocks
497.1126 - 'r|bz2' open a bzip2 compressed stream of tar blocks
497.1127 - 'w|' open an uncompressed stream for writing
497.1128 - 'w|gz' open a gzip compressed stream for writing
497.1129 - 'w|bz2' open a bzip2 compressed stream for writing
497.1130 - """
497.1131 -
497.1132 - if not name and not fileobj:
497.1133 - raise ValueError("nothing to open")
497.1134 -
497.1135 - if mode in ("r", "r:*"):
497.1136 - # Find out which *open() is appropriate for opening the file.
497.1137 - for comptype in cls.OPEN_METH:
497.1138 - func = getattr(cls, cls.OPEN_METH[comptype])
497.1139 - if fileobj is not None:
497.1140 - saved_pos = fileobj.tell()
497.1141 - try:
497.1142 - return func(name, "r", fileobj)
497.1143 - except (ReadError, CompressionError):
497.1144 - if fileobj is not None:
497.1145 - fileobj.seek(saved_pos)
497.1146 - continue
497.1147 - raise ReadError("file could not be opened successfully")
497.1148 -
497.1149 - elif ":" in mode:
497.1150 - filemode, comptype = mode.split(":", 1)
497.1151 - filemode = filemode or "r"
497.1152 - comptype = comptype or "tar"
497.1153 -
497.1154 - # Select the *open() function according to
497.1155 - # given compression.
497.1156 - if comptype in cls.OPEN_METH:
497.1157 - func = getattr(cls, cls.OPEN_METH[comptype])
497.1158 - else:
497.1159 - raise CompressionError("unknown compression type %r" % comptype)
497.1160 - return func(name, filemode, fileobj)
497.1161 -
497.1162 - elif "|" in mode:
497.1163 - filemode, comptype = mode.split("|", 1)
497.1164 - filemode = filemode or "r"
497.1165 - comptype = comptype or "tar"
497.1166 -
497.1167 - if filemode not in "rw":
497.1168 - raise ValueError("mode must be 'r' or 'w'")
497.1169 -
497.1170 - t = cls(name, filemode,
497.1171 - _Stream(name, filemode, comptype, fileobj, bufsize))
497.1172 - t._extfileobj = False
497.1173 - return t
497.1174 -
497.1175 - elif mode in "aw":
497.1176 - return cls.taropen(name, mode, fileobj)
497.1177 -
497.1178 - raise ValueError("undiscernible mode")
497.1179 -
497.1180 - @classmethod
497.1181 - def taropen(cls, name, mode="r", fileobj=None):
497.1182 - """Open uncompressed tar archive name for reading or writing.
497.1183 - """
497.1184 - if len(mode) > 1 or mode not in "raw":
497.1185 - raise ValueError("mode must be 'r', 'a' or 'w'")
497.1186 - return cls(name, mode, fileobj)
497.1187 -
497.1188 - @classmethod
497.1189 - def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9):
497.1190 - """Open gzip compressed tar archive name for reading or writing.
497.1191 - Appending is not allowed.
497.1192 - """
497.1193 - if len(mode) > 1 or mode not in "rw":
497.1194 - raise ValueError("mode must be 'r' or 'w'")
497.1195 -
497.1196 - try:
497.1197 - import gzip
497.1198 - gzip.GzipFile
497.1199 - except (ImportError, AttributeError):
497.1200 - raise CompressionError("gzip module is not available")
497.1201 -
497.1202 - if fileobj is None:
497.1203 - fileobj = file(name, mode + "b")
497.1204 -
497.1205 - try:
497.1206 - t = cls.taropen(name, mode,
497.1207 - gzip.GzipFile(name, mode, compresslevel, fileobj))
497.1208 - except IOError:
497.1209 - raise ReadError("not a gzip file")
497.1210 - t._extfileobj = False
497.1211 - return t
497.1212 -
497.1213 - @classmethod
497.1214 - def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9):
497.1215 - """Open bzip2 compressed tar archive name for reading or writing.
497.1216 - Appending is not allowed.
497.1217 - """
497.1218 - if len(mode) > 1 or mode not in "rw":
497.1219 - raise ValueError("mode must be 'r' or 'w'.")
497.1220 -
497.1221 - try:
497.1222 - import bz2
497.1223 - except ImportError:
497.1224 - raise CompressionError("bz2 module is not available")
497.1225 -
497.1226 - if fileobj is not None:
497.1227 - fileobj = _BZ2Proxy(fileobj, mode)
497.1228 - else:
497.1229 - fileobj = bz2.BZ2File(name, mode, compresslevel=compresslevel)
497.1230 -
497.1231 - try:
497.1232 - t = cls.taropen(name, mode, fileobj)
497.1233 - except IOError:
497.1234 - raise ReadError("not a bzip2 file")
497.1235 - t._extfileobj = False
497.1236 - return t
497.1237 -
497.1238 - # All *open() methods are registered here.
497.1239 - OPEN_METH = {
497.1240 - "tar": "taropen", # uncompressed tar
497.1241 - "gz": "gzopen", # gzip compressed tar
497.1242 - "bz2": "bz2open" # bzip2 compressed tar
497.1243 - }
497.1244 -
497.1245 - #--------------------------------------------------------------------------
497.1246 - # The public methods which TarFile provides:
497.1247 -
497.1248 - def close(self):
497.1249 - """Close the TarFile. In write-mode, two finishing zero blocks are
497.1250 - appended to the archive.
497.1251 - """
497.1252 - if self.closed:
497.1253 - return
497.1254 -
497.1255 - if self._mode in "aw":
497.1256 - self.fileobj.write(NUL * (BLOCKSIZE * 2))
497.1257 - self.offset += (BLOCKSIZE * 2)
497.1258 - # fill up the end with zero-blocks
497.1259 - # (like option -b20 for tar does)
497.1260 - blocks, remainder = divmod(self.offset, RECORDSIZE)
497.1261 - if remainder > 0:
497.1262 - self.fileobj.write(NUL * (RECORDSIZE - remainder))
497.1263 -
497.1264 - if not self._extfileobj:
497.1265 - self.fileobj.close()
497.1266 - self.closed = True
497.1267 -
497.1268 - def getmember(self, name):
497.1269 - """Return a TarInfo object for member `name'. If `name' can not be
497.1270 - found in the archive, KeyError is raised. If a member occurs more
497.1271 - than once in the archive, its last occurence is assumed to be the
497.1272 - most up-to-date version.
497.1273 - """
497.1274 - tarinfo = self._getmember(name)
497.1275 - if tarinfo is None:
497.1276 - raise KeyError("filename %r not found" % name)
497.1277 - return tarinfo
497.1278 -
497.1279 - def getmembers(self):
497.1280 - """Return the members of the archive as a list of TarInfo objects. The
497.1281 - list has the same order as the members in the archive.
497.1282 - """
497.1283 - self._check()
497.1284 - if not self._loaded: # if we want to obtain a list of
497.1285 - self._load() # all members, we first have to
497.1286 - # scan the whole archive.
497.1287 - return self.members
497.1288 -
497.1289 - def getnames(self):
497.1290 - """Return the members of the archive as a list of their names. It has
497.1291 - the same order as the list returned by getmembers().
497.1292 - """
497.1293 - return [tarinfo.name for tarinfo in self.getmembers()]
497.1294 -
497.1295 - def gettarinfo(self, name=None, arcname=None, fileobj=None):
497.1296 - """Create a TarInfo object for either the file `name' or the file
497.1297 - object `fileobj' (using os.fstat on its file descriptor). You can
497.1298 - modify some of the TarInfo's attributes before you add it using
497.1299 - addfile(). If given, `arcname' specifies an alternative name for the
497.1300 - file in the archive.
497.1301 - """
497.1302 - self._check("aw")
497.1303 -
497.1304 - # When fileobj is given, replace name by
497.1305 - # fileobj's real name.
497.1306 - if fileobj is not None:
497.1307 - name = fileobj.name
497.1308 -
497.1309 - # Building the name of the member in the archive.
497.1310 - # Backward slashes are converted to forward slashes,
497.1311 - # Absolute paths are turned to relative paths.
497.1312 - if arcname is None:
497.1313 - arcname = name
497.1314 - arcname = normpath(arcname)
497.1315 - drv, arcname = os.path.splitdrive(arcname)
497.1316 - while arcname[0:1] == "/":
497.1317 - arcname = arcname[1:]
497.1318 -
497.1319 - # Now, fill the TarInfo object with
497.1320 - # information specific for the file.
497.1321 - tarinfo = TarInfo()
497.1322 -
497.1323 - # Use os.stat or os.lstat, depending on platform
497.1324 - # and if symlinks shall be resolved.
497.1325 - if fileobj is None:
497.1326 - if hasattr(os, "lstat") and not self.dereference:
497.1327 - statres = os.lstat(name)
497.1328 - else:
497.1329 - statres = os.stat(name)
497.1330 - else:
497.1331 - statres = os.fstat(fileobj.fileno())
497.1332 - linkname = ""
497.1333 -
497.1334 - stmd = statres.st_mode
497.1335 - if stat.S_ISREG(stmd):
497.1336 - inode = (statres.st_ino, statres.st_dev)
497.1337 - if not self.dereference and \
497.1338 - statres.st_nlink > 1 and inode in self.inodes:
497.1339 - # Is it a hardlink to an already
497.1340 - # archived file?
497.1341 - type = LNKTYPE
497.1342 - linkname = self.inodes[inode]
497.1343 - else:
497.1344 - # The inode is added only if its valid.
497.1345 - # For win32 it is always 0.
497.1346 - type = REGTYPE
497.1347 - if inode[0]:
497.1348 - self.inodes[inode] = arcname
497.1349 - elif stat.S_ISDIR(stmd):
497.1350 - type = DIRTYPE
497.1351 - if arcname[-1:] != "/":
497.1352 - arcname += "/"
497.1353 - elif stat.S_ISFIFO(stmd):
497.1354 - type = FIFOTYPE
497.1355 - elif stat.S_ISLNK(stmd):
497.1356 - type = SYMTYPE
497.1357 - linkname = os.readlink(name)
497.1358 - elif stat.S_ISCHR(stmd):
497.1359 - type = CHRTYPE
497.1360 - elif stat.S_ISBLK(stmd):
497.1361 - type = BLKTYPE
497.1362 - else:
497.1363 - return None
497.1364 -
497.1365 - # Fill the TarInfo object with all
497.1366 - # information we can get.
497.1367 - tarinfo.name = arcname
497.1368 - tarinfo.mode = stmd
497.1369 - tarinfo.uid = statres.st_uid
497.1370 - tarinfo.gid = statres.st_gid
497.1371 - if stat.S_ISREG(stmd):
497.1372 - tarinfo.size = statres.st_size
497.1373 - else:
497.1374 - tarinfo.size = 0L
497.1375 - tarinfo.mtime = statres.st_mtime
497.1376 - tarinfo.type = type
497.1377 - tarinfo.linkname = linkname
497.1378 - if pwd:
497.1379 - try:
497.1380 - tarinfo.uname = pwd.getpwuid(tarinfo.uid)[0]
497.1381 - except KeyError:
497.1382 - pass
497.1383 - if grp:
497.1384 - try:
497.1385 - tarinfo.gname = grp.getgrgid(tarinfo.gid)[0]
497.1386 - except KeyError:
497.1387 - pass
497.1388 -
497.1389 - if type in (CHRTYPE, BLKTYPE):
497.1390 - if hasattr(os, "major") and hasattr(os, "minor"):
497.1391 - tarinfo.devmajor = os.major(statres.st_rdev)
497.1392 - tarinfo.devminor = os.minor(statres.st_rdev)
497.1393 - return tarinfo
497.1394 -
497.1395 - def list(self, verbose=True):
497.1396 - """Print a table of contents to sys.stdout. If `verbose' is False, only
497.1397 - the names of the members are printed. If it is True, an `ls -l'-like
497.1398 - output is produced.
497.1399 - """
497.1400 - self._check()
497.1401 -
497.1402 - for tarinfo in self:
497.1403 - if verbose:
497.1404 - print filemode(tarinfo.mode),
497.1405 - print "%s/%s" % (tarinfo.uname or tarinfo.uid,
497.1406 - tarinfo.gname or tarinfo.gid),
497.1407 - if tarinfo.ischr() or tarinfo.isblk():
497.1408 - print "%10s" % ("%d,%d" \
497.1409 - % (tarinfo.devmajor, tarinfo.devminor)),
497.1410 - else:
497.1411 - print "%10d" % tarinfo.size,
497.1412 - print "%d-%02d-%02d %02d:%02d:%02d" \
497.1413 - % time.localtime(tarinfo.mtime)[:6],
497.1414 -
497.1415 - print tarinfo.name,
497.1416 -
497.1417 - if verbose:
497.1418 - if tarinfo.issym():
497.1419 - print "->", tarinfo.linkname,
497.1420 - if tarinfo.islnk():
497.1421 - print "link to", tarinfo.linkname,
497.1422 - print
497.1423 -
497.1424 - def add(self, name, arcname=None, recursive=True):
497.1425 - """Add the file `name' to the archive. `name' may be any type of file
497.1426 - (directory, fifo, symbolic link, etc.). If given, `arcname'
497.1427 - specifies an alternative name for the file in the archive.
497.1428 - Directories are added recursively by default. This can be avoided by
497.1429 - setting `recursive' to False.
497.1430 - """
497.1431 - self._check("aw")
497.1432 -
497.1433 - if arcname is None:
497.1434 - arcname = name
497.1435 -
497.1436 - # Skip if somebody tries to archive the archive...
497.1437 - if self.name is not None and os.path.abspath(name) == self.name:
497.1438 - self._dbg(2, "tarfile: Skipped %r" % name)
497.1439 - return
497.1440 -
497.1441 - # Special case: The user wants to add the current
497.1442 - # working directory.
497.1443 - if name == ".":
497.1444 - if recursive:
497.1445 - if arcname == ".":
497.1446 - arcname = ""
497.1447 - for f in os.listdir("."):
497.1448 - self.add(f, os.path.join(arcname, f))
497.1449 - return
497.1450 -
497.1451 - self._dbg(1, name)
497.1452 -
497.1453 - # Create a TarInfo object from the file.
497.1454 - tarinfo = self.gettarinfo(name, arcname)
497.1455 -
497.1456 - if tarinfo is None:
497.1457 - self._dbg(1, "tarfile: Unsupported type %r" % name)
497.1458 - return
497.1459 -
497.1460 - # Append the tar header and data to the archive.
497.1461 - if tarinfo.isreg():
497.1462 - f = file(name, "rb")
497.1463 - self.addfile(tarinfo, f)
497.1464 - f.close()
497.1465 -
497.1466 - elif tarinfo.isdir():
497.1467 - self.addfile(tarinfo)
497.1468 - if recursive:
497.1469 - for f in os.listdir(name):
497.1470 - self.add(os.path.join(name, f), os.path.join(arcname, f))
497.1471 -
497.1472 - else:
497.1473 - self.addfile(tarinfo)
497.1474 -
497.1475 - def addfile(self, tarinfo, fileobj=None):
497.1476 - """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is
497.1477 - given, tarinfo.size bytes are read from it and added to the archive.
497.1478 - You can create TarInfo objects using gettarinfo().
497.1479 - On Windows platforms, `fileobj' should always be opened with mode
497.1480 - 'rb' to avoid irritation about the file size.
497.1481 - """
497.1482 - self._check("aw")
497.1483 -
497.1484 - tarinfo = copy.copy(tarinfo)
497.1485 -
497.1486 - buf = tarinfo.tobuf(self.posix)
497.1487 - self.fileobj.write(buf)
497.1488 - self.offset += len(buf)
497.1489 -
497.1490 - # If there's data to follow, append it.
497.1491 - if fileobj is not None:
497.1492 - copyfileobj(fileobj, self.fileobj, tarinfo.size)
497.1493 - blocks, remainder = divmod(tarinfo.size, BLOCKSIZE)
497.1494 - if remainder > 0:
497.1495 - self.fileobj.write(NUL * (BLOCKSIZE - remainder))
497.1496 - blocks += 1
497.1497 - self.offset += blocks * BLOCKSIZE
497.1498 -
497.1499 - self.members.append(tarinfo)
497.1500 -
497.1501 - def extractall(self, path=".", members=None):
497.1502 - """Extract all members from the archive to the current working
497.1503 - directory and set owner, modification time and permissions on
497.1504 - directories afterwards. `path' specifies a different directory
497.1505 - to extract to. `members' is optional and must be a subset of the
497.1506 - list returned by getmembers().
497.1507 - """
497.1508 - directories = []
497.1509 -
497.1510 - if members is None:
497.1511 - members = self
497.1512 -
497.1513 - for tarinfo in members:
497.1514 - if tarinfo.isdir():
497.1515 - # Extract directory with a safe mode, so that
497.1516 - # all files below can be extracted as well.
497.1517 - try:
497.1518 - os.makedirs(os.path.join(path, tarinfo.name), 0777)
497.1519 - except EnvironmentError:
497.1520 - pass
497.1521 - directories.append(tarinfo)
497.1522 - else:
497.1523 - self.extract(tarinfo, path)
497.1524 -
497.1525 - # Reverse sort directories.
497.1526 - directories.sort(lambda a, b: cmp(a.name, b.name))
497.1527 - directories.reverse()
497.1528 -
497.1529 - # Set correct owner, mtime and filemode on directories.
497.1530 - for tarinfo in directories:
497.1531 - path = os.path.join(path, tarinfo.name)
497.1532 - try:
497.1533 - self.chown(tarinfo, path)
497.1534 - self.utime(tarinfo, path)
497.1535 - self.chmod(tarinfo, path)
497.1536 - except ExtractError, e:
497.1537 - if self.errorlevel > 1:
497.1538 - raise
497.1539 - else:
497.1540 - self._dbg(1, "tarfile: %s" % e)
497.1541 -
497.1542 - def extract(self, member, path=""):
497.1543 - """Extract a member from the archive to the current working directory,
497.1544 - using its full name. Its file information is extracted as accurately
497.1545 - as possible. `member' may be a filename or a TarInfo object. You can
497.1546 - specify a different directory using `path'.
497.1547 - """
497.1548 - self._check("r")
497.1549 -
497.1550 - if isinstance(member, TarInfo):
497.1551 - tarinfo = member
497.1552 - else:
497.1553 - tarinfo = self.getmember(member)
497.1554 -
497.1555 - # Prepare the link target for makelink().
497.1556 - if tarinfo.islnk():
497.1557 - tarinfo._link_target = os.path.join(path, tarinfo.linkname)
497.1558 -
497.1559 - try:
497.1560 - self._extract_member(tarinfo, os.path.join(path, tarinfo.name))
497.1561 - except EnvironmentError, e:
497.1562 - if self.errorlevel > 0:
497.1563 - raise
497.1564 - else:
497.1565 - if e.filename is None:
497.1566 - self._dbg(1, "tarfile: %s" % e.strerror)
497.1567 - else:
497.1568 - self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename))
497.1569 - except ExtractError, e:
497.1570 - if self.errorlevel > 1:
497.1571 - raise
497.1572 - else:
497.1573 - self._dbg(1, "tarfile: %s" % e)
497.1574 -
497.1575 - def extractfile(self, member):
497.1576 - """Extract a member from the archive as a file object. `member' may be
497.1577 - a filename or a TarInfo object. If `member' is a regular file, a
497.1578 - file-like object is returned. If `member' is a link, a file-like
497.1579 - object is constructed from the link's target. If `member' is none of
497.1580 - the above, None is returned.
497.1581 - The file-like object is read-only and provides the following
497.1582 - methods: read(), readline(), readlines(), seek() and tell()
497.1583 - """
497.1584 - self._check("r")
497.1585 -
497.1586 - if isinstance(member, TarInfo):
497.1587 - tarinfo = member
497.1588 - else:
497.1589 - tarinfo = self.getmember(member)
497.1590 -
497.1591 - if tarinfo.isreg():
497.1592 - return self.fileobject(self, tarinfo)
497.1593 -
497.1594 - elif tarinfo.type not in SUPPORTED_TYPES:
497.1595 - # If a member's type is unknown, it is treated as a
497.1596 - # regular file.
497.1597 - return self.fileobject(self, tarinfo)
497.1598 -
497.1599 - elif tarinfo.islnk() or tarinfo.issym():
497.1600 - if isinstance(self.fileobj, _Stream):
497.1601 - # A small but ugly workaround for the case that someone tries
497.1602 - # to extract a (sym)link as a file-object from a non-seekable
497.1603 - # stream of tar blocks.
497.1604 - raise StreamError("cannot extract (sym)link as file object")
497.1605 - else:
497.1606 - # A (sym)link's file object is its target's file object.
497.1607 - return self.extractfile(self._getmember(tarinfo.linkname,
497.1608 - tarinfo))
497.1609 - else:
497.1610 - # If there's no data associated with the member (directory, chrdev,
497.1611 - # blkdev, etc.), return None instead of a file object.
497.1612 - return None
497.1613 -
497.1614 - def _extract_member(self, tarinfo, targetpath):
497.1615 - """Extract the TarInfo object tarinfo to a physical
497.1616 - file called targetpath.
497.1617 - """
497.1618 - # Fetch the TarInfo object for the given name
497.1619 - # and build the destination pathname, replacing
497.1620 - # forward slashes to platform specific separators.
497.1621 - if targetpath[-1:] == "/":
497.1622 - targetpath = targetpath[:-1]
497.1623 - targetpath = os.path.normpath(targetpath)
497.1624 -
497.1625 - # Create all upper directories.
497.1626 - upperdirs = os.path.dirname(targetpath)
497.1627 - if upperdirs and not os.path.exists(upperdirs):
497.1628 - ti = TarInfo()
497.1629 - ti.name = upperdirs
497.1630 - ti.type = DIRTYPE
497.1631 - ti.mode = 0777
497.1632 - ti.mtime = tarinfo.mtime
497.1633 - ti.uid = tarinfo.uid
497.1634 - ti.gid = tarinfo.gid
497.1635 - ti.uname = tarinfo.uname
497.1636 - ti.gname = tarinfo.gname
497.1637 - try:
497.1638 - self._extract_member(ti, ti.name)
497.1639 - except:
497.1640 - pass
497.1641 -
497.1642 - if tarinfo.islnk() or tarinfo.issym():
497.1643 - self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname))
497.1644 - else:
497.1645 - self._dbg(1, tarinfo.name)
497.1646 -
497.1647 - if tarinfo.isreg():
497.1648 - self.makefile(tarinfo, targetpath)
497.1649 - elif tarinfo.isdir():
497.1650 - self.makedir(tarinfo, targetpath)
497.1651 - elif tarinfo.isfifo():
497.1652 - self.makefifo(tarinfo, targetpath)
497.1653 - elif tarinfo.ischr() or tarinfo.isblk():
497.1654 - self.makedev(tarinfo, targetpath)
497.1655 - elif tarinfo.islnk() or tarinfo.issym():
497.1656 - self.makelink(tarinfo, targetpath)
497.1657 - elif tarinfo.type not in SUPPORTED_TYPES:
497.1658 - self.makeunknown(tarinfo, targetpath)
497.1659 - else:
497.1660 - self.makefile(tarinfo, targetpath)
497.1661 -
497.1662 - self.chown(tarinfo, targetpath)
497.1663 - if not tarinfo.issym():
497.1664 - self.chmod(tarinfo, targetpath)
497.1665 - self.utime(tarinfo, targetpath)
497.1666 -
497.1667 - #--------------------------------------------------------------------------
497.1668 - # Below are the different file methods. They are called via
497.1669 - # _extract_member() when extract() is called. They can be replaced in a
497.1670 - # subclass to implement other functionality.
497.1671 -
497.1672 - def makedir(self, tarinfo, targetpath):
497.1673 - """Make a directory called targetpath.
497.1674 - """
497.1675 - try:
497.1676 - os.mkdir(targetpath)
497.1677 - except EnvironmentError, e:
497.1678 - if e.errno != errno.EEXIST:
497.1679 - raise
497.1680 -
497.1681 - def makefile(self, tarinfo, targetpath):
497.1682 - """Make a file called targetpath.
497.1683 - """
497.1684 - source = self.extractfile(tarinfo)
497.1685 - target = file(targetpath, "wb")
497.1686 - copyfileobj(source, target)
497.1687 - source.close()
497.1688 - target.close()
497.1689 -
497.1690 - def makeunknown(self, tarinfo, targetpath):
497.1691 - """Make a file from a TarInfo object with an unknown type
497.1692 - at targetpath.
497.1693 - """
497.1694 - self.makefile(tarinfo, targetpath)
497.1695 - self._dbg(1, "tarfile: Unknown file type %r, " \
497.1696 - "extracted as regular file." % tarinfo.type)
497.1697 -
497.1698 - def makefifo(self, tarinfo, targetpath):
497.1699 - """Make a fifo called targetpath.
497.1700 - """
497.1701 - if hasattr(os, "mkfifo"):
497.1702 - os.mkfifo(targetpath)
497.1703 - else:
497.1704 - raise ExtractError("fifo not supported by system")
497.1705 -
497.1706 - def makedev(self, tarinfo, targetpath):
497.1707 - """Make a character or block device called targetpath.
497.1708 - """
497.1709 - if not hasattr(os, "mknod") or not hasattr(os, "makedev"):
497.1710 - raise ExtractError("special devices not supported by system")
497.1711 -
497.1712 - mode = tarinfo.mode
497.1713 - if tarinfo.isblk():
497.1714 - mode |= stat.S_IFBLK
497.1715 - else:
497.1716 - mode |= stat.S_IFCHR
497.1717 -
497.1718 - os.mknod(targetpath, mode,
497.1719 - os.makedev(tarinfo.devmajor, tarinfo.devminor))
497.1720 -
497.1721 - def makelink(self, tarinfo, targetpath):
497.1722 - """Make a (symbolic) link called targetpath. If it cannot be created
497.1723 - (platform limitation), we try to make a copy of the referenced file
497.1724 - instead of a link.
497.1725 - """
497.1726 - linkpath = tarinfo.linkname
497.1727 - try:
497.1728 - if tarinfo.issym():
497.1729 - os.symlink(linkpath, targetpath)
497.1730 - else:
497.1731 - # See extract().
497.1732 - os.link(tarinfo._link_target, targetpath)
497.1733 - except AttributeError:
497.1734 - if tarinfo.issym():
497.1735 - linkpath = os.path.join(os.path.dirname(tarinfo.name),
497.1736 - linkpath)
497.1737 - linkpath = normpath(linkpath)
497.1738 -
497.1739 - try:
497.1740 - self._extract_member(self.getmember(linkpath), targetpath)
497.1741 - except (EnvironmentError, KeyError), e:
497.1742 - linkpath = os.path.normpath(linkpath)
497.1743 - try:
497.1744 - shutil.copy2(linkpath, targetpath)
497.1745 - except EnvironmentError, e:
497.1746 - raise IOError("link could not be created")
497.1747 -
497.1748 - def chown(self, tarinfo, targetpath):
497.1749 - """Set owner of targetpath according to tarinfo.
497.1750 - """
497.1751 - if pwd and hasattr(os, "geteuid") and os.geteuid() == 0:
497.1752 - # We have to be root to do so.
497.1753 - try:
497.1754 - g = grp.getgrnam(tarinfo.gname)[2]
497.1755 - except KeyError:
497.1756 - try:
497.1757 - g = grp.getgrgid(tarinfo.gid)[2]
497.1758 - except KeyError:
497.1759 - g = os.getgid()
497.1760 - try:
497.1761 - u = pwd.getpwnam(tarinfo.uname)[2]
497.1762 - except KeyError:
497.1763 - try:
497.1764 - u = pwd.getpwuid(tarinfo.uid)[2]
497.1765 - except KeyError:
497.1766 - u = os.getuid()
497.1767 - try:
497.1768 - if tarinfo.issym() and hasattr(os, "lchown"):
497.1769 - os.lchown(targetpath, u, g)
497.1770 - else:
497.1771 - if sys.platform != "os2emx":
497.1772 - os.chown(targetpath, u, g)
497.1773 - except EnvironmentError, e:
497.1774 - raise ExtractError("could not change owner")
497.1775 -
497.1776 - def chmod(self, tarinfo, targetpath):
497.1777 - """Set file permissions of targetpath according to tarinfo.
497.1778 - """
497.1779 - if hasattr(os, 'chmod'):
497.1780 - try:
497.1781 - os.chmod(targetpath, tarinfo.mode)
497.1782 - except EnvironmentError, e:
497.1783 - raise ExtractError("could not change mode")
497.1784 -
497.1785 - def utime(self, tarinfo, targetpath):
497.1786 - """Set modification time of targetpath according to tarinfo.
497.1787 - """
497.1788 - if not hasattr(os, 'utime'):
497.1789 - return
497.1790 - if sys.platform == "win32" and tarinfo.isdir():
497.1791 - # According to msdn.microsoft.com, it is an error (EACCES)
497.1792 - # to use utime() on directories.
497.1793 - return
497.1794 - try:
497.1795 - os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime))
497.1796 - except EnvironmentError, e:
497.1797 - raise ExtractError("could not change modification time")
497.1798 -
497.1799 - #--------------------------------------------------------------------------
497.1800 - def next(self):
497.1801 - """Return the next member of the archive as a TarInfo object, when
497.1802 - TarFile is opened for reading. Return None if there is no more
497.1803 - available.
497.1804 - """
497.1805 - self._check("ra")
497.1806 - if self.firstmember is not None:
497.1807 - m = self.firstmember
497.1808 - self.firstmember = None
497.1809 - return m
497.1810 -
497.1811 - # Read the next block.
497.1812 - self.fileobj.seek(self.offset)
497.1813 - while True:
497.1814 - buf = self.fileobj.read(BLOCKSIZE)
497.1815 - if not buf:
497.1816 - return None
497.1817 -
497.1818 - try:
497.1819 - tarinfo = TarInfo.frombuf(buf)
497.1820 -
497.1821 - # Set the TarInfo object's offset to the current position of the
497.1822 - # TarFile and set self.offset to the position where the data blocks
497.1823 - # should begin.
497.1824 - tarinfo.offset = self.offset
497.1825 - self.offset += BLOCKSIZE
497.1826 -
497.1827 - tarinfo = self.proc_member(tarinfo)
497.1828 -
497.1829 - except ValueError, e:
497.1830 - if self.ignore_zeros:
497.1831 - self._dbg(2, "0x%X: empty or invalid block: %s" %
497.1832 - (self.offset, e))
497.1833 - self.offset += BLOCKSIZE
497.1834 - continue
497.1835 - else:
497.1836 - if self.offset == 0:
497.1837 - raise ReadError("empty, unreadable or compressed "
497.1838 - "file: %s" % e)
497.1839 - return None
497.1840 - break
497.1841 -
497.1842 - # Some old tar programs represent a directory as a regular
497.1843 - # file with a trailing slash.
497.1844 - if tarinfo.isreg() and tarinfo.name.endswith("/"):
497.1845 - tarinfo.type = DIRTYPE
497.1846 -
497.1847 - # Directory names should have a '/' at the end.
497.1848 - if tarinfo.isdir():
497.1849 - tarinfo.name += "/"
497.1850 -
497.1851 - self.members.append(tarinfo)
497.1852 - return tarinfo
497.1853 -
497.1854 - #--------------------------------------------------------------------------
497.1855 - # The following are methods that are called depending on the type of a
497.1856 - # member. The entry point is proc_member() which is called with a TarInfo
497.1857 - # object created from the header block from the current offset. The
497.1858 - # proc_member() method can be overridden in a subclass to add custom
497.1859 - # proc_*() methods. A proc_*() method MUST implement the following
497.1860 - # operations:
497.1861 - # 1. Set tarinfo.offset_data to the position where the data blocks begin,
497.1862 - # if there is data that follows.
497.1863 - # 2. Set self.offset to the position where the next member's header will
497.1864 - # begin.
497.1865 - # 3. Return tarinfo or another valid TarInfo object.
497.1866 - def proc_member(self, tarinfo):
497.1867 - """Choose the right processing method for tarinfo depending
497.1868 - on its type and call it.
497.1869 - """
497.1870 - if tarinfo.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):
497.1871 - return self.proc_gnulong(tarinfo)
497.1872 - elif tarinfo.type == GNUTYPE_SPARSE:
497.1873 - return self.proc_sparse(tarinfo)
497.1874 - else:
497.1875 - return self.proc_builtin(tarinfo)
497.1876 -
497.1877 - def proc_builtin(self, tarinfo):
497.1878 - """Process a builtin type member or an unknown member
497.1879 - which will be treated as a regular file.
497.1880 - """
497.1881 - tarinfo.offset_data = self.offset
497.1882 - if tarinfo.isreg() or tarinfo.type not in SUPPORTED_TYPES:
497.1883 - # Skip the following data blocks.
497.1884 - self.offset += self._block(tarinfo.size)
497.1885 - return tarinfo
497.1886 -
497.1887 - def proc_gnulong(self, tarinfo):
497.1888 - """Process the blocks that hold a GNU longname
497.1889 - or longlink member.
497.1890 - """
497.1891 - buf = ""
497.1892 - count = tarinfo.size
497.1893 - while count > 0:
497.1894 - block = self.fileobj.read(BLOCKSIZE)
497.1895 - buf += block
497.1896 - self.offset += BLOCKSIZE
497.1897 - count -= BLOCKSIZE
497.1898 -
497.1899 - # Fetch the next header and process it.
497.1900 - b = self.fileobj.read(BLOCKSIZE)
497.1901 - t = TarInfo.frombuf(b)
497.1902 - t.offset = self.offset
497.1903 - self.offset += BLOCKSIZE
497.1904 - next = self.proc_member(t)
497.1905 -
497.1906 - # Patch the TarInfo object from the next header with
497.1907 - # the longname information.
497.1908 - next.offset = tarinfo.offset
497.1909 - if tarinfo.type == GNUTYPE_LONGNAME:
497.1910 - next.name = buf.rstrip(NUL)
497.1911 - elif tarinfo.type == GNUTYPE_LONGLINK:
497.1912 - next.linkname = buf.rstrip(NUL)
497.1913 -
497.1914 - return next
497.1915 -
497.1916 - def proc_sparse(self, tarinfo):
497.1917 - """Process a GNU sparse header plus extra headers.
497.1918 - """
497.1919 - buf = tarinfo.buf
497.1920 - sp = _ringbuffer()
497.1921 - pos = 386
497.1922 - lastpos = 0L
497.1923 - realpos = 0L
497.1924 - # There are 4 possible sparse structs in the
497.1925 - # first header.
497.1926 - for i in xrange(4):
497.1927 - try:
497.1928 - offset = nti(buf[pos:pos + 12])
497.1929 - numbytes = nti(buf[pos + 12:pos + 24])
497.1930 - except ValueError:
497.1931 - break
497.1932 - if offset > lastpos:
497.1933 - sp.append(_hole(lastpos, offset - lastpos))
497.1934 - sp.append(_data(offset, numbytes, realpos))
497.1935 - realpos += numbytes
497.1936 - lastpos = offset + numbytes
497.1937 - pos += 24
497.1938 -
497.1939 - isextended = ord(buf[482])
497.1940 - origsize = nti(buf[483:495])
497.1941 -
497.1942 - # If the isextended flag is given,
497.1943 - # there are extra headers to process.
497.1944 - while isextended == 1:
497.1945 - buf = self.fileobj.read(BLOCKSIZE)
497.1946 - self.offset += BLOCKSIZE
497.1947 - pos = 0
497.1948 - for i in xrange(21):
497.1949 - try:
497.1950 - offset = nti(buf[pos:pos + 12])
497.1951 - numbytes = nti(buf[pos + 12:pos + 24])
497.1952 - except ValueError:
497.1953 - break
497.1954 - if offset > lastpos:
497.1955 - sp.append(_hole(lastpos, offset - lastpos))
497.1956 - sp.append(_data(offset, numbytes, realpos))
497.1957 - realpos += numbytes
497.1958 - lastpos = offset + numbytes
497.1959 - pos += 24
497.1960 - isextended = ord(buf[504])
497.1961 -
497.1962 - if lastpos < origsize:
497.1963 - sp.append(_hole(lastpos, origsize - lastpos))
497.1964 -
497.1965 - tarinfo.sparse = sp
497.1966 -
497.1967 - tarinfo.offset_data = self.offset
497.1968 - self.offset += self._block(tarinfo.size)
497.1969 - tarinfo.size = origsize
497.1970 -
497.1971 - return tarinfo
497.1972 -
497.1973 - #--------------------------------------------------------------------------
497.1974 - # Little helper methods:
497.1975 -
497.1976 - def _block(self, count):
497.1977 - """Round up a byte count by BLOCKSIZE and return it,
497.1978 - e.g. _block(834) => 1024.
497.1979 - """
497.1980 - blocks, remainder = divmod(count, BLOCKSIZE)
497.1981 - if remainder:
497.1982 - blocks += 1
497.1983 - return blocks * BLOCKSIZE
497.1984 -
497.1985 - def _getmember(self, name, tarinfo=None):
497.1986 - """Find an archive member by name from bottom to top.
497.1987 - If tarinfo is given, it is used as the starting point.
497.1988 - """
497.1989 - # Ensure that all members have been loaded.
497.1990 - members = self.getmembers()
497.1991 -
497.1992 - if tarinfo is None:
497.1993 - end = len(members)
497.1994 - else:
497.1995 - end = members.index(tarinfo)
497.1996 -
497.1997 - for i in xrange(end - 1, -1, -1):
497.1998 - if name == members[i].name:
497.1999 - return members[i]
497.2000 -
497.2001 - def _load(self):
497.2002 - """Read through the entire archive file and look for readable
497.2003 - members.
497.2004 - """
497.2005 - while True:
497.2006 - tarinfo = self.next()
497.2007 - if tarinfo is None:
497.2008 - break
497.2009 - self._loaded = True
497.2010 -
497.2011 - def _check(self, mode=None):
497.2012 - """Check if TarFile is still open, and if the operation's mode
497.2013 - corresponds to TarFile's mode.
497.2014 - """
497.2015 - if self.closed:
497.2016 - raise IOError("%s is closed" % self.__class__.__name__)
497.2017 - if mode is not None and self._mode not in mode:
497.2018 - raise IOError("bad operation for mode %r" % self._mode)
497.2019 -
497.2020 - def __iter__(self):
497.2021 - """Provide an iterator object.
497.2022 - """
497.2023 - if self._loaded:
497.2024 - return iter(self.members)
497.2025 - else:
497.2026 - return TarIter(self)
497.2027 -
497.2028 - def _dbg(self, level, msg):
497.2029 - """Write debugging output to sys.stderr.
497.2030 - """
497.2031 - if level <= self.debug:
497.2032 - print >> sys.stderr, msg
497.2033 -# class TarFile
497.2034 -
497.2035 -class TarIter:
497.2036 - """Iterator Class.
497.2037 -
497.2038 - for tarinfo in TarFile(...):
497.2039 - suite...
497.2040 - """
497.2041 -
497.2042 - def __init__(self, tarfile):
497.2043 - """Construct a TarIter object.
497.2044 - """
497.2045 - self.tarfile = tarfile
497.2046 - self.index = 0
497.2047 - def __iter__(self):
497.2048 - """Return iterator object.
497.2049 - """
497.2050 - return self
497.2051 - def next(self):
497.2052 - """Return the next item using TarFile's next() method.
497.2053 - When all members have been read, set TarFile as _loaded.
497.2054 - """
497.2055 - # Fix for SF #1100429: Under rare circumstances it can
497.2056 - # happen that getmembers() is called during iteration,
497.2057 - # which will cause TarIter to stop prematurely.
497.2058 - if not self.tarfile._loaded:
497.2059 - tarinfo = self.tarfile.next()
497.2060 - if not tarinfo:
497.2061 - self.tarfile._loaded = True
497.2062 - raise StopIteration
497.2063 - else:
497.2064 - try:
497.2065 - tarinfo = self.tarfile.members[self.index]
497.2066 - except IndexError:
497.2067 - raise StopIteration
497.2068 - self.index += 1
497.2069 - return tarinfo
497.2070 -
497.2071 -# Helper classes for sparse file support
497.2072 -class _section:
497.2073 - """Base class for _data and _hole.
497.2074 - """
497.2075 - def __init__(self, offset, size):
497.2076 - self.offset = offset
497.2077 - self.size = size
497.2078 - def __contains__(self, offset):
497.2079 - return self.offset <= offset < self.offset + self.size
497.2080 -
497.2081 -class _data(_section):
497.2082 - """Represent a data section in a sparse file.
497.2083 - """
497.2084 - def __init__(self, offset, size, realpos):
497.2085 - _section.__init__(self, offset, size)
497.2086 - self.realpos = realpos
497.2087 -
497.2088 -class _hole(_section):
497.2089 - """Represent a hole section in a sparse file.
497.2090 - """
497.2091 - pass
497.2092 -
497.2093 -class _ringbuffer(list):
497.2094 - """Ringbuffer class which increases performance
497.2095 - over a regular list.
497.2096 - """
497.2097 - def __init__(self):
497.2098 - self.idx = 0
497.2099 - def find(self, offset):
497.2100 - idx = self.idx
497.2101 - while True:
497.2102 - item = self[idx]
497.2103 - if offset in item:
497.2104 - break
497.2105 - idx += 1
497.2106 - if idx == len(self):
497.2107 - idx = 0
497.2108 - if idx == self.idx:
497.2109 - # End of File
497.2110 - return None
497.2111 - self.idx = idx
497.2112 - return item
497.2113 -
497.2114 -#---------------------------------------------
497.2115 -# zipfile compatible TarFile class
497.2116 -#---------------------------------------------
497.2117 -TAR_PLAIN = 0 # zipfile.ZIP_STORED
497.2118 -TAR_GZIPPED = 8 # zipfile.ZIP_DEFLATED
497.2119 -class TarFileCompat:
497.2120 - """TarFile class compatible with standard module zipfile's
497.2121 - ZipFile class.
497.2122 - """
497.2123 - def __init__(self, file, mode="r", compression=TAR_PLAIN):
497.2124 - if compression == TAR_PLAIN:
497.2125 - self.tarfile = TarFile.taropen(file, mode)
497.2126 - elif compression == TAR_GZIPPED:
497.2127 - self.tarfile = TarFile.gzopen(file, mode)
497.2128 - else:
497.2129 - raise ValueError("unknown compression constant")
497.2130 - if mode[0:1] == "r":
497.2131 - members = self.tarfile.getmembers()
497.2132 - for m in members:
497.2133 - m.filename = m.name
497.2134 - m.file_size = m.size
497.2135 - m.date_time = time.gmtime(m.mtime)[:6]
497.2136 - def namelist(self):
497.2137 - return map(lambda m: m.name, self.infolist())
497.2138 - def infolist(self):
497.2139 - return filter(lambda m: m.type in REGULAR_TYPES,
497.2140 - self.tarfile.getmembers())
497.2141 - def printdir(self):
497.2142 - self.tarfile.list()
497.2143 - def testzip(self):
497.2144 - return
497.2145 - def getinfo(self, name):
497.2146 - return self.tarfile.getmember(name)
497.2147 - def read(self, name):
497.2148 - return self.tarfile.extractfile(self.tarfile.getmember(name)).read()
497.2149 - def write(self, filename, arcname=None, compress_type=None):
497.2150 - self.tarfile.add(filename, arcname)
497.2151 - def writestr(self, zinfo, bytes):
497.2152 - try:
497.2153 - from cStringIO import StringIO
497.2154 - except ImportError:
497.2155 - from StringIO import StringIO
497.2156 - import calendar
497.2157 - zinfo.name = zinfo.filename
497.2158 - zinfo.size = zinfo.file_size
497.2159 - zinfo.mtime = calendar.timegm(zinfo.date_time)
497.2160 - self.tarfile.addfile(zinfo, StringIO(bytes))
497.2161 - def close(self):
497.2162 - self.tarfile.close()
497.2163 -#class TarFileCompat
497.2164 -
497.2165 -#--------------------
497.2166 -# exported functions
497.2167 -#--------------------
497.2168 -def is_tarfile(name):
497.2169 - """Return True if name points to a tar archive that we
497.2170 - are able to handle, else return False.
497.2171 - """
497.2172 - try:
497.2173 - t = open(name)
497.2174 - t.close()
497.2175 - return True
497.2176 - except TarError:
497.2177 - return False
497.2178 -
497.2179 -open = TarFile.open
498.1 --- a/python.editor/test/unit/data/testfiles/tarfile.py.indexed Sun Jan 04 13:11:53 2015 -0600
498.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
498.3 @@ -1,486 +0,0 @@
498.4 -
498.5 -
498.6 -Document 0
498.7 -Searchable Keys:
498.8 - class : CompressionError
498.9 - class-ig : compressionerror
498.10 - extends : TarError
498.11 - in : tarfile
498.12 -
498.13 -Not Searchable Keys:
498.14 - clzattrs : ;|PRIVATE|;
498.15 -
498.16 -
498.17 -Document 1
498.18 -Searchable Keys:
498.19 - class : ExFileObject
498.20 - class-ig : exfileobject
498.21 - extends : object
498.22 - in : tarfile
498.23 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,tarfile,tarinfo;
498.24 - member : __iter__;F;|PRIVATE|;self;
498.25 - member : blocksize;D;|PRIVATE|;
498.26 - member : buffer;D;;
498.27 - member : close;F;|PRIVATE|;self;
498.28 - member : closed;D;;
498.29 - member : fileobj;D;;
498.30 - member : mode;D;;
498.31 - member : name;D;;
498.32 - member : position;D;;
498.33 - member : read;F;|PRIVATE|;self,size;
498.34 - member : readline;F;|PRIVATE|;self,size;
498.35 - member : readlines;F;|PRIVATE|;self;
498.36 - member : seek;F;|PRIVATE|;self,pos,whence;
498.37 - member : size;D;;
498.38 - member : tell;F;|PRIVATE|;self;
498.39 -
498.40 -Not Searchable Keys:
498.41 - clzattrs : ;|PRIVATE|;
498.42 -
498.43 -
498.44 -Document 2
498.45 -Searchable Keys:
498.46 - class : ExtractError
498.47 - class-ig : extracterror
498.48 - extends : TarError
498.49 - in : tarfile
498.50 -
498.51 -Not Searchable Keys:
498.52 - clzattrs : ;|PRIVATE|;
498.53 -
498.54 -
498.55 -Document 3
498.56 -Searchable Keys:
498.57 - class : ReadError
498.58 - class-ig : readerror
498.59 - extends : TarError
498.60 - in : tarfile
498.61 -
498.62 -Not Searchable Keys:
498.63 - clzattrs : ;|PRIVATE|;
498.64 -
498.65 -
498.66 -Document 4
498.67 -Searchable Keys:
498.68 - class : StreamError
498.69 - class-ig : streamerror
498.70 - extends : TarError
498.71 - in : tarfile
498.72 -
498.73 -Not Searchable Keys:
498.74 - clzattrs : ;|PRIVATE|;
498.75 -
498.76 -
498.77 -Document 5
498.78 -Searchable Keys:
498.79 - class : TarError
498.80 - class-ig : tarerror
498.81 - extends : Exception
498.82 - in : tarfile
498.83 -
498.84 -Not Searchable Keys:
498.85 -
498.86 -
498.87 -Document 6
498.88 -Searchable Keys:
498.89 - class : TarFile
498.90 - class-ig : tarfile
498.91 - extends : object
498.92 - in : tarfile
498.93 - member : OPEN_METH;D;;
498.94 - member : __init__;c;|CONSTRUCTOR|;self,name,mode,fileobj;
498.95 - member : __iter__;F;;self;
498.96 - member : _block;F;|PRIVATE|;self,count;
498.97 - member : _check;F;|PRIVATE|;self,mode;
498.98 - member : _dbg;F;|PRIVATE|;self,level,msg;
498.99 - member : _extfileobj;D;|PRIVATE|;
498.100 - member : _extract_member;F;|PRIVATE|;self,tarinfo,targetpath;
498.101 - member : _getmember;F;|PRIVATE|;self,name,tarinfo;
498.102 - member : _load;F;|PRIVATE|;self;
498.103 - member : _loaded;D;|PRIVATE|;
498.104 - member : _mode;D;|PRIVATE|;
498.105 - member : add;F;;self,name,arcname,recursive;
498.106 - member : addfile;F;;self,tarinfo,fileobj;
498.107 - member : bz2open;c;|CONSTRUCTOR|STATIC|;cls,name,mode,fileobj,compresslevel;
498.108 - member : chmod;F;;self,tarinfo,targetpath;
498.109 - member : chown;F;;self,tarinfo,targetpath;
498.110 - member : close;F;;self;
498.111 - member : closed;D;;
498.112 - member : debug;D;;
498.113 - member : dereference;D;;
498.114 - member : errorlevel;D;;
498.115 - member : extract;F;;self,member,path;
498.116 - member : extractall;F;;self,path,members;
498.117 - member : extractfile;F;;self,member;
498.118 - member : fileobj;D;;
498.119 - member : fileobject;D;;
498.120 - member : firstmember;D;;
498.121 - member : getmember;F;;self,name;
498.122 - member : getmembers;F;;self;
498.123 - member : getnames;F;;self;
498.124 - member : gettarinfo;F;;self,name,arcname,fileobj;
498.125 - member : gzopen;c;|CONSTRUCTOR|STATIC|;cls,name,mode,fileobj,compresslevel;
498.126 - member : ignore_zeros;D;;
498.127 - member : inodes;D;;
498.128 - member : list;F;;self,verbose;
498.129 - member : makedev;F;;self,tarinfo,targetpath;
498.130 - member : makedir;F;;self,tarinfo,targetpath;
498.131 - member : makefifo;F;;self,tarinfo,targetpath;
498.132 - member : makefile;F;;self,tarinfo,targetpath;
498.133 - member : makelink;F;;self,tarinfo,targetpath;
498.134 - member : makeunknown;F;;self,tarinfo,targetpath;
498.135 - member : members;D;;
498.136 - member : mode;D;;
498.137 - member : name;D;;
498.138 - member : next;F;;self;
498.139 - member : offset;D;;
498.140 - member : open;c;|CONSTRUCTOR|STATIC|;cls,name,mode,fileobj,bufsize;
498.141 - member : posix;D;;
498.142 - member : proc_builtin;F;;self,tarinfo;
498.143 - member : proc_gnulong;F;;self,tarinfo;
498.144 - member : proc_member;F;;self,tarinfo;
498.145 - member : proc_sparse;F;;self,tarinfo;
498.146 - member : taropen;c;|CONSTRUCTOR|STATIC|;cls,name,mode,fileobj;
498.147 - member : utime;F;;self,tarinfo,targetpath;
498.148 -
498.149 -Not Searchable Keys:
498.150 -
498.151 -
498.152 -Document 7
498.153 -Searchable Keys:
498.154 - class : TarFileCompat
498.155 - class-ig : tarfilecompat
498.156 - in : tarfile
498.157 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,file,mode,compression;
498.158 - member : close;F;|PRIVATE|;self;
498.159 - member : getinfo;F;|PRIVATE|;self,name;
498.160 - member : infolist;F;|PRIVATE|;self;
498.161 - member : namelist;F;|PRIVATE|;self;
498.162 - member : printdir;F;|PRIVATE|;self;
498.163 - member : read;F;|PRIVATE|;self,name;
498.164 - member : tarfile;D;;
498.165 - member : testzip;F;|PRIVATE|;self;
498.166 - member : write;F;|PRIVATE|;self,filename,arcname,compress_type;
498.167 - member : writestr;F;|PRIVATE|;self,zinfo,bytes;
498.168 -
498.169 -Not Searchable Keys:
498.170 - clzattrs : ;|PRIVATE|;
498.171 -
498.172 -
498.173 -Document 8
498.174 -Searchable Keys:
498.175 - class : TarInfo
498.176 - class-ig : tarinfo
498.177 - extends : object
498.178 - in : tarfile
498.179 - member : __init__;c;|CONSTRUCTOR|;self,name;
498.180 - member : __repr__;F;;self;
498.181 - member : _create_gnulong;F;|PRIVATE|;self,name,type;
498.182 - member : buf;D;;
498.183 - member : chksum;D;;
498.184 - member : devmajor;D;;
498.185 - member : devminor;D;;
498.186 - member : frombuf;c;|CONSTRUCTOR|STATIC|;cls,buf;
498.187 - member : gid;D;;
498.188 - member : gname;D;;
498.189 - member : isblk;F;;self;
498.190 - member : ischr;F;;self;
498.191 - member : isdev;F;;self;
498.192 - member : isdir;F;;self;
498.193 - member : isfifo;F;;self;
498.194 - member : isfile;F;;self;
498.195 - member : islnk;F;;self;
498.196 - member : isreg;F;;self;
498.197 - member : issparse;F;;self;
498.198 - member : issym;F;;self;
498.199 - member : linkname;D;;
498.200 - member : mode;D;;
498.201 - member : mtime;D;;
498.202 - member : name;D;;
498.203 - member : offset;D;;
498.204 - member : offset_data;D;;
498.205 - member : size;D;;
498.206 - member : tobuf;F;;self,posix;
498.207 - member : type;D;;
498.208 - member : uid;D;;
498.209 - member : uname;D;;
498.210 -
498.211 -Not Searchable Keys:
498.212 -
498.213 -
498.214 -Document 9
498.215 -Searchable Keys:
498.216 - class : TarIter
498.217 - class-ig : tariter
498.218 - in : tarfile
498.219 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,tarfile;
498.220 - member : __iter__;F;|PRIVATE|;self;
498.221 - member : index;D;;
498.222 - member : next;F;|PRIVATE|;self;
498.223 - member : tarfile;D;;
498.224 -
498.225 -Not Searchable Keys:
498.226 - clzattrs : ;|PRIVATE|;
498.227 -
498.228 -
498.229 -Document 10
498.230 -Searchable Keys:
498.231 - class : _BZ2Proxy
498.232 - class-ig : _bz2proxy
498.233 - extends : object
498.234 - in : tarfile
498.235 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,fileobj,mode;
498.236 - member : blocksize;D;|PRIVATE|;
498.237 - member : buf;D;;
498.238 - member : bz2obj;D;;
498.239 - member : close;F;|PRIVATE|;self;
498.240 - member : fileobj;D;;
498.241 - member : init;F;|PRIVATE|;self;
498.242 - member : mode;D;;
498.243 - member : pos;D;;
498.244 - member : read;F;|PRIVATE|;self,size;
498.245 - member : seek;F;|PRIVATE|;self,pos;
498.246 - member : tell;F;|PRIVATE|;self;
498.247 - member : write;F;|PRIVATE|;self,data;
498.248 -
498.249 -Not Searchable Keys:
498.250 - clzattrs : ;|PRIVATE|;
498.251 -
498.252 -
498.253 -Document 11
498.254 -Searchable Keys:
498.255 - class : _FileInFile
498.256 - class-ig : _fileinfile
498.257 - extends : object
498.258 - in : tarfile
498.259 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,fileobj,offset,size,sparse;
498.260 - member : fileobj;D;;
498.261 - member : offset;D;;
498.262 - member : position;D;;
498.263 - member : read;F;|PRIVATE|;self,size;
498.264 - member : readnormal;F;|PRIVATE|;self,size;
498.265 - member : readsparse;F;|PRIVATE|;self,size;
498.266 - member : readsparsesection;F;|PRIVATE|;self,size;
498.267 - member : seek;F;|PRIVATE|;self,position;
498.268 - member : size;D;;
498.269 - member : sparse;D;;
498.270 - member : tell;F;|PRIVATE|;self;
498.271 -
498.272 -Not Searchable Keys:
498.273 - clzattrs : ;|PRIVATE|;
498.274 -
498.275 -
498.276 -Document 12
498.277 -Searchable Keys:
498.278 - class : _LowLevelFile
498.279 - class-ig : _lowlevelfile
498.280 - in : tarfile
498.281 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,name,mode;
498.282 - member : close;F;|PRIVATE|;self;
498.283 - member : fd;D;;
498.284 - member : read;F;|PRIVATE|;self,size;
498.285 - member : write;F;|PRIVATE|;self,s;
498.286 -
498.287 -Not Searchable Keys:
498.288 - clzattrs : ;|PRIVATE|;
498.289 -
498.290 -
498.291 -Document 13
498.292 -Searchable Keys:
498.293 - class : _Stream
498.294 - class-ig : _stream
498.295 - in : tarfile
498.296 - member : __del__;F;|PRIVATE|;self;
498.297 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,name,mode,comptype,fileobj,bufsize;
498.298 - member : __read;F;|PRIVATE|;self,size;
498.299 - member : __write;F;|PRIVATE|;self,s;
498.300 - member : _extfileobj;D;|PRIVATE|;
498.301 - member : _init_read_gz;F;|PRIVATE|;self;
498.302 - member : _init_write_gz;F;|PRIVATE|;self;
498.303 - member : _read;F;|PRIVATE|;self,size;
498.304 - member : buf;D;;
498.305 - member : bufsize;D;;
498.306 - member : close;F;|PRIVATE|;self;
498.307 - member : closed;D;;
498.308 - member : cmp;D;;
498.309 - member : comptype;D;;
498.310 - member : crc;D;;
498.311 - member : dbuf;D;;
498.312 - member : fileobj;D;;
498.313 - member : mode;D;;
498.314 - member : name;D;;
498.315 - member : pos;D;;
498.316 - member : read;F;|PRIVATE|;self,size;
498.317 - member : seek;F;|PRIVATE|;self,pos;
498.318 - member : tell;F;|PRIVATE|;self;
498.319 - member : write;F;|PRIVATE|;self,s;
498.320 - member : zlib;D;;
498.321 -
498.322 -Not Searchable Keys:
498.323 - clzattrs : ;|PRIVATE|;
498.324 -
498.325 -
498.326 -Document 14
498.327 -Searchable Keys:
498.328 - class : _StreamProxy
498.329 - class-ig : _streamproxy
498.330 - extends : object
498.331 - in : tarfile
498.332 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,fileobj;
498.333 - member : buf;D;;
498.334 - member : close;F;|PRIVATE|;self;
498.335 - member : fileobj;D;;
498.336 - member : getcomptype;F;|PRIVATE|;self;
498.337 - member : read;D;;
498.338 - member : read;F;|PRIVATE|;self,size;
498.339 -
498.340 -Not Searchable Keys:
498.341 - clzattrs : ;|PRIVATE|;
498.342 -
498.343 -
498.344 -Document 15
498.345 -Searchable Keys:
498.346 - class : _data
498.347 - class-ig : _data
498.348 - extends : _section
498.349 - in : tarfile
498.350 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,offset,size,realpos;
498.351 - member : realpos;D;;
498.352 -
498.353 -Not Searchable Keys:
498.354 - clzattrs : ;|PRIVATE|;
498.355 -
498.356 -
498.357 -Document 16
498.358 -Searchable Keys:
498.359 - class : _hole
498.360 - class-ig : _hole
498.361 - extends : _section
498.362 - in : tarfile
498.363 -
498.364 -Not Searchable Keys:
498.365 - clzattrs : ;|PRIVATE|;
498.366 -
498.367 -
498.368 -Document 17
498.369 -Searchable Keys:
498.370 - class : _ringbuffer
498.371 - class-ig : _ringbuffer
498.372 - extends : list
498.373 - in : tarfile
498.374 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self;
498.375 - member : find;F;|PRIVATE|;self,offset;
498.376 - member : idx;D;;
498.377 -
498.378 -Not Searchable Keys:
498.379 - clzattrs : ;|PRIVATE|;
498.380 -
498.381 -
498.382 -Document 18
498.383 -Searchable Keys:
498.384 - class : _section
498.385 - class-ig : _section
498.386 - in : tarfile
498.387 - member : __contains__;F;|PRIVATE|;self,offset;
498.388 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,offset,size;
498.389 - member : offset;D;;
498.390 - member : size;D;;
498.391 -
498.392 -Not Searchable Keys:
498.393 - clzattrs : ;|PRIVATE|;
498.394 -
498.395 -
498.396 -Document 19
498.397 -Searchable Keys:
498.398 - item : AREGTYPE;D;|PRIVATE|;
498.399 - item : BLKTYPE;D;|PRIVATE|;
498.400 - item : BLOCKSIZE;D;|PRIVATE|;
498.401 - item : CHRTYPE;D;|PRIVATE|;
498.402 - item : CONTTYPE;D;|PRIVATE|;
498.403 - item : CompressionError;C;|PRIVATE|;
498.404 - item : DIRTYPE;D;|PRIVATE|;
498.405 - item : ExFileObject;C;|PRIVATE|;
498.406 - item : ExtractError;C;|PRIVATE|;
498.407 - item : FIFOTYPE;D;|PRIVATE|;
498.408 - item : GNUTYPE_LONGLINK;D;|PRIVATE|;
498.409 - item : GNUTYPE_LONGNAME;D;|PRIVATE|;
498.410 - item : GNUTYPE_SPARSE;D;|PRIVATE|;
498.411 - item : LENGTH_LINK;D;|PRIVATE|;
498.412 - item : LENGTH_NAME;D;|PRIVATE|;
498.413 - item : LENGTH_PREFIX;D;|PRIVATE|;
498.414 - item : LNKTYPE;D;|PRIVATE|;
498.415 - item : MAGIC;D;|PRIVATE|;
498.416 - item : MAXSIZE_MEMBER;D;|PRIVATE|;
498.417 - item : NUL;D;|PRIVATE|;
498.418 - item : RECORDSIZE;D;|PRIVATE|;
498.419 - item : REGTYPE;D;|PRIVATE|;
498.420 - item : REGULAR_TYPES;D;|PRIVATE|;
498.421 - item : ReadError;C;|PRIVATE|;
498.422 - item : SUPPORTED_TYPES;D;|PRIVATE|;
498.423 - item : SYMTYPE;D;|PRIVATE|;
498.424 - item : S_IFBLK;D;|PRIVATE|;
498.425 - item : S_IFCHR;D;|PRIVATE|;
498.426 - item : S_IFDIR;D;|PRIVATE|;
498.427 - item : S_IFIFO;D;|PRIVATE|;
498.428 - item : S_IFLNK;D;|PRIVATE|;
498.429 - item : S_IFREG;D;|PRIVATE|;
498.430 - item : StreamError;C;|PRIVATE|;
498.431 - item : TAR_GZIPPED;D;|PRIVATE|;
498.432 - item : TAR_PLAIN;D;|PRIVATE|;
498.433 - item : TGEXEC;D;|PRIVATE|;
498.434 - item : TGREAD;D;|PRIVATE|;
498.435 - item : TGWRITE;D;|PRIVATE|;
498.436 - item : TOEXEC;D;|PRIVATE|;
498.437 - item : TOREAD;D;|PRIVATE|;
498.438 - item : TOWRITE;D;|PRIVATE|;
498.439 - item : TSGID;D;|PRIVATE|;
498.440 - item : TSUID;D;|PRIVATE|;
498.441 - item : TSVTX;D;|PRIVATE|;
498.442 - item : TUEXEC;D;|PRIVATE|;
498.443 - item : TUREAD;D;|PRIVATE|;
498.444 - item : TUWRITE;D;|PRIVATE|;
498.445 - item : TarError;C;;
498.446 - item : TarFile;C;;
498.447 - item : TarFileCompat;C;|PRIVATE|;
498.448 - item : TarInfo;C;;
498.449 - item : TarIter;C;|PRIVATE|;
498.450 - item : VERSION;D;|PRIVATE|;
498.451 - item : _BZ2Proxy;C;|PRIVATE|;
498.452 - item : _FileInFile;C;|PRIVATE|;
498.453 - item : _LowLevelFile;C;|PRIVATE|;
498.454 - item : _Stream;C;|PRIVATE|;
498.455 - item : _StreamProxy;C;|PRIVATE|;
498.456 - item : __all__;D;;
498.457 - item : __author__;D;|PRIVATE|;
498.458 - item : __credits__;D;|PRIVATE|;
498.459 - item : __cvsid__;D;|PRIVATE|;
498.460 - item : __date__;D;|PRIVATE|;
498.461 - item : __version__;D;|PRIVATE|;
498.462 - item : _data;C;|PRIVATE|;
498.463 - item : _hole;C;|PRIVATE|;
498.464 - item : _ringbuffer;C;|PRIVATE|;
498.465 - item : _section;C;|PRIVATE|;
498.466 - item : calc_chksums;F;|PRIVATE|;buf;
498.467 - item : copy;I;|PRIVATE|;
498.468 - item : copyfileobj;F;|PRIVATE|;src,dst,length;
498.469 - item : errno;I;|PRIVATE|;
498.470 - item : filemode;F;|PRIVATE|;mode;
498.471 - item : filemode_table;D;|PRIVATE|;
498.472 - item : grp;I;|PRIVATE|;
498.473 - item : is_tarfile;F;;name;
498.474 - item : itn;F;|PRIVATE|;n,digits,posix;
498.475 - item : normpath;D;|PRIVATE|;
498.476 - item : nti;F;|PRIVATE|;s;
498.477 - item : open;D;|PRIVATE|;
498.478 - item : os;I;|PRIVATE|;
498.479 - item : pwd;I;|PRIVATE|;
498.480 - item : shutil;I;|PRIVATE|;
498.481 - item : stat;I;|PRIVATE|;
498.482 - item : stn;F;|PRIVATE|;s,length;
498.483 - item : struct;I;|PRIVATE|;
498.484 - item : sys;I;|PRIVATE|;
498.485 - item : time;I;|PRIVATE|;
498.486 - item : version;D;|PRIVATE|;
498.487 - module : tarfile
498.488 -
498.489 -Not Searchable Keys:
499.1 --- a/python.editor/test/unit/data/testfiles/test_scope.py Sun Jan 04 13:11:53 2015 -0600
499.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
499.3 @@ -1,530 +0,0 @@
499.4 -from test_support import verify, TestFailed, check_syntax
499.5 -
499.6 -import warnings
499.7 -warnings.filterwarnings("ignore", r"import \*", SyntaxWarning, "<string>")
499.8 -
499.9 -print "1. simple nesting"
499.10 -
499.11 -def make_adder(x):
499.12 - def adder(y):
499.13 - return x + y
499.14 - return adder
499.15 -
499.16 -inc = make_adder(1)
499.17 -plus10 = make_adder(10)
499.18 -
499.19 -verify(inc(1) == 2)
499.20 -verify(plus10(-2) == 8)
499.21 -
499.22 -print "2. extra nesting"
499.23 -
499.24 -def make_adder2(x):
499.25 - def extra(): # check freevars passing through non-use scopes
499.26 - def adder(y):
499.27 - return x + y
499.28 - return adder
499.29 - return extra()
499.30 -
499.31 -inc = make_adder2(1)
499.32 -plus10 = make_adder2(10)
499.33 -
499.34 -verify(inc(1) == 2)
499.35 -verify(plus10(-2) == 8)
499.36 -
499.37 -print "3. simple nesting + rebinding"
499.38 -
499.39 -def make_adder3(x):
499.40 - def adder(y):
499.41 - return x + y
499.42 - x = x + 1 # check tracking of assignment to x in defining scope
499.43 - return adder
499.44 -
499.45 -inc = make_adder3(0)
499.46 -plus10 = make_adder3(9)
499.47 -
499.48 -verify(inc(1) == 2)
499.49 -verify(plus10(-2) == 8)
499.50 -
499.51 -print "4. nesting with global but no free"
499.52 -
499.53 -def make_adder4(): # XXX add exta level of indirection
499.54 - def nest():
499.55 - def nest():
499.56 - def adder(y):
499.57 - return global_x + y # check that plain old globals work
499.58 - return adder
499.59 - return nest()
499.60 - return nest()
499.61 -
499.62 -global_x = 1
499.63 -adder = make_adder4()
499.64 -verify(adder(1) == 2)
499.65 -
499.66 -global_x = 10
499.67 -verify(adder(-2) == 8)
499.68 -
499.69 -print "5. nesting through class"
499.70 -
499.71 -def make_adder5(x):
499.72 - class Adder:
499.73 - def __call__(self, y):
499.74 - return x + y
499.75 - return Adder()
499.76 -
499.77 -inc = make_adder5(1)
499.78 -plus10 = make_adder5(10)
499.79 -
499.80 -verify(inc(1) == 2)
499.81 -verify(plus10(-2) == 8)
499.82 -
499.83 -print "6. nesting plus free ref to global"
499.84 -
499.85 -def make_adder6(x):
499.86 - global global_nest_x
499.87 - def adder(y):
499.88 - return global_nest_x + y
499.89 - global_nest_x = x
499.90 - return adder
499.91 -
499.92 -inc = make_adder6(1)
499.93 -plus10 = make_adder6(10)
499.94 -
499.95 -verify(inc(1) == 11) # there's only one global
499.96 -verify(plus10(-2) == 8)
499.97 -
499.98 -print "7. nearest enclosing scope"
499.99 -
499.100 -def f(x):
499.101 - def g(y):
499.102 - x = 42 # check that this masks binding in f()
499.103 - def h(z):
499.104 - return x + z
499.105 - return h
499.106 - return g(2)
499.107 -
499.108 -test_func = f(10)
499.109 -verify(test_func(5) == 47)
499.110 -
499.111 -print "8. mixed freevars and cellvars"
499.112 -
499.113 -def identity(x):
499.114 - return x
499.115 -
499.116 -def f(x, y, z):
499.117 - def g(a, b, c):
499.118 - a = a + x # 3
499.119 - def h():
499.120 - # z * (4 + 9)
499.121 - # 3 * 13
499.122 - return identity(z * (b + y))
499.123 - y = c + z # 9
499.124 - return h
499.125 - return g
499.126 -
499.127 -g = f(1, 2, 3)
499.128 -h = g(2, 4, 6)
499.129 -verify(h() == 39)
499.130 -
499.131 -print "9. free variable in method"
499.132 -
499.133 -def test():
499.134 - method_and_var = "var"
499.135 - class Test:
499.136 - def method_and_var(self):
499.137 - return "method"
499.138 - def test(self):
499.139 - return method_and_var
499.140 - def actual_global(self):
499.141 - return str("global")
499.142 - def str(self):
499.143 - return str(self)
499.144 - return Test()
499.145 -
499.146 -t = test()
499.147 -verify(t.test() == "var")
499.148 -verify(t.method_and_var() == "method")
499.149 -verify(t.actual_global() == "global")
499.150 -
499.151 -method_and_var = "var"
499.152 -class Test:
499.153 - # this class is not nested, so the rules are different
499.154 - def method_and_var(self):
499.155 - return "method"
499.156 - def test(self):
499.157 - return method_and_var
499.158 - def actual_global(self):
499.159 - return str("global")
499.160 - def str(self):
499.161 - return str(self)
499.162 -
499.163 -t = Test()
499.164 -verify(t.test() == "var")
499.165 -verify(t.method_and_var() == "method")
499.166 -verify(t.actual_global() == "global")
499.167 -
499.168 -print "10. recursion"
499.169 -
499.170 -def f(x):
499.171 - def fact(n):
499.172 - if n == 0:
499.173 - return 1
499.174 - else:
499.175 - return n * fact(n - 1)
499.176 - if x >= 0:
499.177 - return fact(x)
499.178 - else:
499.179 - raise ValueError, "x must be >= 0"
499.180 -
499.181 -verify(f(6) == 720)
499.182 -
499.183 -
499.184 -print "11. unoptimized namespaces"
499.185 -
499.186 -check_syntax("""\
499.187 -def unoptimized_clash1(strip):
499.188 - def f(s):
499.189 - from string import *
499.190 - return strip(s) # ambiguity: free or local
499.191 - return f
499.192 -""")
499.193 -
499.194 -check_syntax("""\
499.195 -def unoptimized_clash2():
499.196 - from string import *
499.197 - def f(s):
499.198 - return strip(s) # ambiguity: global or local
499.199 - return f
499.200 -""")
499.201 -
499.202 -check_syntax("""\
499.203 -def unoptimized_clash2():
499.204 - from string import *
499.205 - def g():
499.206 - def f(s):
499.207 - return strip(s) # ambiguity: global or local
499.208 - return f
499.209 -""")
499.210 -
499.211 -# XXX could allow this for exec with const argument, but what's the point
499.212 -check_syntax("""\
499.213 -def error(y):
499.214 - exec "a = 1"
499.215 - def f(x):
499.216 - return x + y
499.217 - return f
499.218 -""")
499.219 -
499.220 -check_syntax("""\
499.221 -def f(x):
499.222 - def g():
499.223 - return x
499.224 - del x # can't del name
499.225 -""")
499.226 -
499.227 -check_syntax("""\
499.228 -def f():
499.229 - def g():
499.230 - from string import *
499.231 - return strip # global or local?
499.232 -""")
499.233 -
499.234 -# and verify a few cases that should work
499.235 -
499.236 -exec """
499.237 -def noproblem1():
499.238 - from string import *
499.239 - f = lambda x:x
499.240 -
499.241 -def noproblem2():
499.242 - from string import *
499.243 - def f(x):
499.244 - return x + 1
499.245 -
499.246 -def noproblem3():
499.247 - from string import *
499.248 - def f(x):
499.249 - global y
499.250 - y = x
499.251 -"""
499.252 -
499.253 -print "12. lambdas"
499.254 -
499.255 -f1 = lambda x: lambda y: x + y
499.256 -inc = f1(1)
499.257 -plus10 = f1(10)
499.258 -verify(inc(1) == 2)
499.259 -verify(plus10(5) == 15)
499.260 -
499.261 -f2 = lambda x: (lambda : lambda y: x + y)()
499.262 -inc = f2(1)
499.263 -plus10 = f2(10)
499.264 -verify(inc(1) == 2)
499.265 -verify(plus10(5) == 15)
499.266 -
499.267 -f3 = lambda x: lambda y: global_x + y
499.268 -global_x = 1
499.269 -inc = f3(None)
499.270 -verify(inc(2) == 3)
499.271 -
499.272 -f8 = lambda x, y, z: lambda a, b, c: lambda : z * (b + y)
499.273 -g = f8(1, 2, 3)
499.274 -h = g(2, 4, 6)
499.275 -verify(h() == 18)
499.276 -
499.277 -print "13. UnboundLocal"
499.278 -
499.279 -def errorInOuter():
499.280 - print y
499.281 - def inner():
499.282 - return y
499.283 - y = 1
499.284 -
499.285 -def errorInInner():
499.286 - def inner():
499.287 - return y
499.288 - inner()
499.289 - y = 1
499.290 -
499.291 -try:
499.292 - errorInOuter()
499.293 -except UnboundLocalError:
499.294 - pass
499.295 -else:
499.296 - raise TestFailed
499.297 -
499.298 -try:
499.299 - errorInInner()
499.300 -except NameError:
499.301 - pass
499.302 -else:
499.303 - raise TestFailed
499.304 -
499.305 -print "14. complex definitions"
499.306 -
499.307 -def makeReturner(*lst):
499.308 - def returner():
499.309 - return lst
499.310 - return returner
499.311 -
499.312 -verify(makeReturner(1,2,3)() == (1,2,3))
499.313 -
499.314 -def makeReturner2(**kwargs):
499.315 - def returner():
499.316 - return kwargs
499.317 - return returner
499.318 -
499.319 -verify(makeReturner2(a=11)()['a'] == 11)
499.320 -
499.321 -def makeAddPair((a, b)):
499.322 - def addPair((c, d)):
499.323 - return (a + c, b + d)
499.324 - return addPair
499.325 -
499.326 -verify(makeAddPair((1, 2))((100, 200)) == (101,202))
499.327 -
499.328 -print "15. scope of global statements"
499.329 -# Examples posted by Samuele Pedroni to python-dev on 3/1/2001
499.330 -
499.331 -# I
499.332 -x = 7
499.333 -def f():
499.334 - x = 1
499.335 - def g():
499.336 - global x
499.337 - def i():
499.338 - def h():
499.339 - return x
499.340 - return h()
499.341 - return i()
499.342 - return g()
499.343 -verify(f() == 7)
499.344 -verify(x == 7)
499.345 -
499.346 -# II
499.347 -x = 7
499.348 -def f():
499.349 - x = 1
499.350 - def g():
499.351 - x = 2
499.352 - def i():
499.353 - def h():
499.354 - return x
499.355 - return h()
499.356 - return i()
499.357 - return g()
499.358 -verify(f() == 2)
499.359 -verify(x == 7)
499.360 -
499.361 -# III
499.362 -x = 7
499.363 -def f():
499.364 - x = 1
499.365 - def g():
499.366 - global x
499.367 - x = 2
499.368 - def i():
499.369 - def h():
499.370 - return x
499.371 - return h()
499.372 - return i()
499.373 - return g()
499.374 -verify(f() == 2)
499.375 -verify(x == 2)
499.376 -
499.377 -# IV
499.378 -x = 7
499.379 -def f():
499.380 - x = 3
499.381 - def g():
499.382 - global x
499.383 - x = 2
499.384 - def i():
499.385 - def h():
499.386 - return x
499.387 - return h()
499.388 - return i()
499.389 - return g()
499.390 -verify(f() == 2)
499.391 -verify(x == 2)
499.392 -
499.393 -print "16. check leaks"
499.394 -
499.395 -class Foo:
499.396 - count = 0
499.397 -
499.398 - def __init__(self):
499.399 - Foo.count += 1
499.400 -
499.401 - def __del__(self):
499.402 - Foo.count -= 1
499.403 -
499.404 -def f1():
499.405 - x = Foo()
499.406 - def f2():
499.407 - return x
499.408 - f2()
499.409 -
499.410 -for i in range(100):
499.411 - f1()
499.412 -
499.413 -import os
499.414 -if os.name == 'java':
499.415 - from java.lang import System, Thread
499.416 - System.gc()
499.417 - Thread.sleep(100)
499.418 - System.gc()
499.419 -verify(Foo.count == 0)
499.420 -
499.421 -print "17. class and global"
499.422 -
499.423 -def test(x):
499.424 - class Foo:
499.425 - global x
499.426 - def __call__(self, y):
499.427 - return x + y
499.428 - return Foo()
499.429 -
499.430 -x = 0
499.431 -verify(test(6)(2) == 8)
499.432 -x = -1
499.433 -verify(test(3)(2) == 5)
499.434 -
499.435 -print "18. verify that locals() works"
499.436 -
499.437 -def f(x):
499.438 - def g(y):
499.439 - def h(z):
499.440 - return y + z
499.441 - w = x + y
499.442 - y += 3
499.443 - return locals()
499.444 - return g
499.445 -
499.446 -d = f(2)(4)
499.447 -verify(d.has_key('h'))
499.448 -del d['h']
499.449 -verify(d == {'x': 2, 'y': 7, 'w': 6})
499.450 -
499.451 -print "19. var is bound and free in class"
499.452 -
499.453 -def f(x):
499.454 - class C:
499.455 - def m(self):
499.456 - return x
499.457 - a = x
499.458 - return C
499.459 -
499.460 -inst = f(3)()
499.461 -verify(inst.a == inst.m())
499.462 -
499.463 -print "20. interaction with trace function"
499.464 -
499.465 -import sys
499.466 -def tracer(a,b,c):
499.467 - return tracer
499.468 -
499.469 -def adaptgetter(name, klass, getter):
499.470 - kind, des = getter
499.471 - if kind == 1: # AV happens when stepping from this line to next
499.472 - if des == "":
499.473 - des = "_%s__%s" % (klass.__name__, name)
499.474 - return lambda obj: getattr(obj, des)
499.475 -
499.476 -class TestClass:
499.477 - pass
499.478 -
499.479 -sys.settrace(tracer)
499.480 -adaptgetter("foo", TestClass, (1, ""))
499.481 -sys.settrace(None)
499.482 -
499.483 -try: sys.settrace()
499.484 -except TypeError: pass
499.485 -else: raise TestFailed, 'sys.settrace() did not raise TypeError'
499.486 -
499.487 -print "20. eval and exec with free variables"
499.488 -
499.489 -def f(x):
499.490 - return lambda: x + 1
499.491 -
499.492 -g = f(3)
499.493 -try:
499.494 - eval(g.func_code)
499.495 -except TypeError:
499.496 - pass
499.497 -else:
499.498 - print "eval() should have failed, because code contained free vars"
499.499 -
499.500 -try:
499.501 - exec g.func_code
499.502 -except TypeError:
499.503 - pass
499.504 -else:
499.505 - print "exec should have failed, because code contained free vars"
499.506 -
499.507 -print "21. list comprehension with local variables"
499.508 -
499.509 -try:
499.510 - print bad
499.511 -except NameError:
499.512 - pass
499.513 -else:
499.514 - print "bad should not be defined"
499.515 -
499.516 -def x():
499.517 - [bad for s in 'a b' for bad in s.split()]
499.518 -
499.519 -x()
499.520 -try:
499.521 - print bad
499.522 -except NameError:
499.523 - pass
499.524 -
499.525 -print "22. eval with free variables"
499.526 -
499.527 -def f(x):
499.528 - def g():
499.529 - x
499.530 - eval("x + 1")
499.531 - return g
499.532 -
499.533 -f(4)()
500.1 --- a/python.editor/test/unit/data/testfiles/test_scope.py.folds Sun Jan 04 13:11:53 2015 -0600
500.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
500.3 @@ -1,531 +0,0 @@
500.4 - from test_support import verify, TestFailed, check_syntax
500.5 -
500.6 - import warnings
500.7 - warnings.filterwarnings("ignore", r"import \*", SyntaxWarning, "<string>")
500.8 -
500.9 - print "1. simple nesting"
500.10 -
500.11 -+ def make_adder(x):
500.12 -+ def adder(y):
500.13 -- return x + y
500.14 -| return adder
500.15 --
500.16 - inc = make_adder(1)
500.17 - plus10 = make_adder(10)
500.18 -
500.19 - verify(inc(1) == 2)
500.20 - verify(plus10(-2) == 8)
500.21 -
500.22 - print "2. extra nesting"
500.23 -
500.24 -+ def make_adder2(x):
500.25 -+ def extra(): # check freevars passing through non-use scopes
500.26 -+ def adder(y):
500.27 -- return x + y
500.28 -- return adder
500.29 -| return extra()
500.30 --
500.31 - inc = make_adder2(1)
500.32 - plus10 = make_adder2(10)
500.33 -
500.34 - verify(inc(1) == 2)
500.35 - verify(plus10(-2) == 8)
500.36 -
500.37 - print "3. simple nesting + rebinding"
500.38 -
500.39 -+ def make_adder3(x):
500.40 -+ def adder(y):
500.41 -- return x + y
500.42 -| x = x + 1 # check tracking of assignment to x in defining scope
500.43 -| return adder
500.44 --
500.45 - inc = make_adder3(0)
500.46 - plus10 = make_adder3(9)
500.47 -
500.48 - verify(inc(1) == 2)
500.49 - verify(plus10(-2) == 8)
500.50 -
500.51 - print "4. nesting with global but no free"
500.52 -
500.53 -+ def make_adder4(): # XXX add exta level of indirection
500.54 -+ def nest():
500.55 -+ def nest():
500.56 -+ def adder(y):
500.57 -- return global_x + y # check that plain old globals work
500.58 -- return adder
500.59 -- return nest()
500.60 -| return nest()
500.61 --
500.62 - global_x = 1
500.63 - adder = make_adder4()
500.64 - verify(adder(1) == 2)
500.65 -
500.66 - global_x = 10
500.67 - verify(adder(-2) == 8)
500.68 -
500.69 - print "5. nesting through class"
500.70 -
500.71 -+ def make_adder5(x):
500.72 -+ class Adder:
500.73 -+ def __call__(self, y):
500.74 -- return x + y
500.75 -| return Adder()
500.76 --
500.77 - inc = make_adder5(1)
500.78 - plus10 = make_adder5(10)
500.79 -
500.80 - verify(inc(1) == 2)
500.81 - verify(plus10(-2) == 8)
500.82 -
500.83 - print "6. nesting plus free ref to global"
500.84 -
500.85 -+ def make_adder6(x):
500.86 -| global global_nest_x
500.87 -+ def adder(y):
500.88 -- return global_nest_x + y
500.89 -| global_nest_x = x
500.90 -| return adder
500.91 --
500.92 - inc = make_adder6(1)
500.93 - plus10 = make_adder6(10)
500.94 -
500.95 - verify(inc(1) == 11) # there's only one global
500.96 - verify(plus10(-2) == 8)
500.97 -
500.98 - print "7. nearest enclosing scope"
500.99 -
500.100 -+ def f(x):
500.101 -+ def g(y):
500.102 -| x = 42 # check that this masks binding in f()
500.103 -+ def h(z):
500.104 -- return x + z
500.105 -- return h
500.106 -| return g(2)
500.107 --
500.108 - test_func = f(10)
500.109 - verify(test_func(5) == 47)
500.110 -
500.111 - print "8. mixed freevars and cellvars"
500.112 -
500.113 -+ def identity(x):
500.114 -| return x
500.115 --
500.116 -+ def f(x, y, z):
500.117 -+ def g(a, b, c):
500.118 -| a = a + x # 3
500.119 -+ def h():
500.120 -| # z * (4 + 9)
500.121 -| # 3 * 13
500.122 -- return identity(z * (b + y))
500.123 -| y = c + z # 9
500.124 -- return h
500.125 -| return g
500.126 --
500.127 - g = f(1, 2, 3)
500.128 - h = g(2, 4, 6)
500.129 - verify(h() == 39)
500.130 -
500.131 - print "9. free variable in method"
500.132 -
500.133 -+ def test():
500.134 -| method_and_var = "var"
500.135 -+ class Test:
500.136 -+ def method_and_var(self):
500.137 -- return "method"
500.138 -+ def test(self):
500.139 -- return method_and_var
500.140 -+ def actual_global(self):
500.141 -- return str("global")
500.142 -+ def str(self):
500.143 -- return str(self)
500.144 -| return Test()
500.145 --
500.146 - t = test()
500.147 - verify(t.test() == "var")
500.148 - verify(t.method_and_var() == "method")
500.149 - verify(t.actual_global() == "global")
500.150 -
500.151 - method_and_var = "var"
500.152 -+ class Test:
500.153 -| # this class is not nested, so the rules are different
500.154 -+ def method_and_var(self):
500.155 -- return "method"
500.156 -+ def test(self):
500.157 -- return method_and_var
500.158 -+ def actual_global(self):
500.159 -- return str("global")
500.160 -+ def str(self):
500.161 -| return str(self)
500.162 --
500.163 - t = Test()
500.164 - verify(t.test() == "var")
500.165 - verify(t.method_and_var() == "method")
500.166 - verify(t.actual_global() == "global")
500.167 -
500.168 - print "10. recursion"
500.169 -
500.170 -+ def f(x):
500.171 -+ def fact(n):
500.172 -| if n == 0:
500.173 -| return 1
500.174 -| else:
500.175 -- return n * fact(n - 1)
500.176 -| if x >= 0:
500.177 -| return fact(x)
500.178 -| else:
500.179 -| raise ValueError, "x must be >= 0"
500.180 --
500.181 - verify(f(6) == 720)
500.182 -
500.183 -
500.184 - print "11. unoptimized namespaces"
500.185 -
500.186 -+ check_syntax("""\
500.187 -| def unoptimized_clash1(strip):
500.188 -| def f(s):
500.189 -| from string import *
500.190 -| return strip(s) # ambiguity: free or local
500.191 -- return f
500.192 - """)
500.193 -
500.194 -+ check_syntax("""\
500.195 -| def unoptimized_clash2():
500.196 -| from string import *
500.197 -| def f(s):
500.198 -| return strip(s) # ambiguity: global or local
500.199 -- return f
500.200 - """)
500.201 -
500.202 -+ check_syntax("""\
500.203 -| def unoptimized_clash2():
500.204 -| from string import *
500.205 -| def g():
500.206 -| def f(s):
500.207 -| return strip(s) # ambiguity: global or local
500.208 -- return f
500.209 - """)
500.210 -
500.211 - # XXX could allow this for exec with const argument, but what's the point
500.212 -+ check_syntax("""\
500.213 -| def error(y):
500.214 -| exec "a = 1"
500.215 -| def f(x):
500.216 -| return x + y
500.217 -- return f
500.218 - """)
500.219 -
500.220 -+ check_syntax("""\
500.221 -| def f(x):
500.222 -| def g():
500.223 -| return x
500.224 -- del x # can't del name
500.225 - """)
500.226 -
500.227 -+ check_syntax("""\
500.228 -| def f():
500.229 -| def g():
500.230 -| from string import *
500.231 -- return strip # global or local?
500.232 - """)
500.233 -
500.234 - # and verify a few cases that should work
500.235 -
500.236 -+ exec """
500.237 -| def noproblem1():
500.238 -| from string import *
500.239 -| f = lambda x:x
500.240 -|
500.241 -| def noproblem2():
500.242 -| from string import *
500.243 -| def f(x):
500.244 -| return x + 1
500.245 -|
500.246 -| def noproblem3():
500.247 -| from string import *
500.248 -| def f(x):
500.249 -| global y
500.250 -| y = x
500.251 -- """
500.252 -
500.253 - print "12. lambdas"
500.254 -
500.255 - f1 = lambda x: lambda y: x + y
500.256 - inc = f1(1)
500.257 - plus10 = f1(10)
500.258 - verify(inc(1) == 2)
500.259 - verify(plus10(5) == 15)
500.260 -
500.261 - f2 = lambda x: (lambda : lambda y: x + y)()
500.262 - inc = f2(1)
500.263 - plus10 = f2(10)
500.264 - verify(inc(1) == 2)
500.265 - verify(plus10(5) == 15)
500.266 -
500.267 - f3 = lambda x: lambda y: global_x + y
500.268 - global_x = 1
500.269 - inc = f3(None)
500.270 - verify(inc(2) == 3)
500.271 -
500.272 - f8 = lambda x, y, z: lambda a, b, c: lambda : z * (b + y)
500.273 - g = f8(1, 2, 3)
500.274 - h = g(2, 4, 6)
500.275 - verify(h() == 18)
500.276 -
500.277 - print "13. UnboundLocal"
500.278 -
500.279 -+ def errorInOuter():
500.280 -| print y
500.281 -+ def inner():
500.282 -- return y
500.283 -| y = 1
500.284 --
500.285 -+ def errorInInner():
500.286 -+ def inner():
500.287 -- return y
500.288 -| inner()
500.289 -| y = 1
500.290 --
500.291 - try:
500.292 - errorInOuter()
500.293 - except UnboundLocalError:
500.294 - pass
500.295 - else:
500.296 - raise TestFailed
500.297 -
500.298 - try:
500.299 - errorInInner()
500.300 - except NameError:
500.301 - pass
500.302 - else:
500.303 - raise TestFailed
500.304 -
500.305 - print "14. complex definitions"
500.306 -
500.307 -+ def makeReturner(*lst):
500.308 -+ def returner():
500.309 -- return lst
500.310 -| return returner
500.311 --
500.312 - verify(makeReturner(1,2,3)() == (1,2,3))
500.313 -
500.314 -+ def makeReturner2(**kwargs):
500.315 -+ def returner():
500.316 -- return kwargs
500.317 -| return returner
500.318 --
500.319 - verify(makeReturner2(a=11)()['a'] == 11)
500.320 -
500.321 -+ def makeAddPair((a, b)):
500.322 -+ def addPair((c, d)):
500.323 -- return (a + c, b + d)
500.324 -| return addPair
500.325 --
500.326 - verify(makeAddPair((1, 2))((100, 200)) == (101,202))
500.327 -
500.328 - print "15. scope of global statements"
500.329 - # Examples posted by Samuele Pedroni to python-dev on 3/1/2001
500.330 -
500.331 - # I
500.332 - x = 7
500.333 -+ def f():
500.334 -| x = 1
500.335 -+ def g():
500.336 -| global x
500.337 -+ def i():
500.338 -+ def h():
500.339 -- return x
500.340 -- return h()
500.341 -- return i()
500.342 -- return g()
500.343 - verify(f() == 7)
500.344 - verify(x == 7)
500.345 -
500.346 - # II
500.347 - x = 7
500.348 -+ def f():
500.349 -| x = 1
500.350 -+ def g():
500.351 -| x = 2
500.352 -+ def i():
500.353 -+ def h():
500.354 -- return x
500.355 -- return h()
500.356 -- return i()
500.357 -- return g()
500.358 - verify(f() == 2)
500.359 - verify(x == 7)
500.360 -
500.361 - # III
500.362 - x = 7
500.363 -+ def f():
500.364 -| x = 1
500.365 -+ def g():
500.366 -| global x
500.367 -| x = 2
500.368 -+ def i():
500.369 -+ def h():
500.370 -- return x
500.371 -- return h()
500.372 -- return i()
500.373 -- return g()
500.374 - verify(f() == 2)
500.375 - verify(x == 2)
500.376 -
500.377 - # IV
500.378 - x = 7
500.379 -+ def f():
500.380 -| x = 3
500.381 -+ def g():
500.382 -| global x
500.383 -| x = 2
500.384 -+ def i():
500.385 -+ def h():
500.386 -- return x
500.387 -- return h()
500.388 -- return i()
500.389 -- return g()
500.390 - verify(f() == 2)
500.391 - verify(x == 2)
500.392 -
500.393 - print "16. check leaks"
500.394 -
500.395 -+ class Foo:
500.396 -| count = 0
500.397 -|
500.398 -+ def __init__(self):
500.399 -| Foo.count += 1
500.400 --
500.401 -+ def __del__(self):
500.402 -| Foo.count -= 1
500.403 --
500.404 -+ def f1():
500.405 -| x = Foo()
500.406 -+ def f2():
500.407 -- return x
500.408 -| f2()
500.409 --
500.410 - for i in range(100):
500.411 - f1()
500.412 -
500.413 - import os
500.414 - if os.name == 'java':
500.415 - from java.lang import System, Thread
500.416 - System.gc()
500.417 - Thread.sleep(100)
500.418 - System.gc()
500.419 - verify(Foo.count == 0)
500.420 -
500.421 - print "17. class and global"
500.422 -
500.423 -+ def test(x):
500.424 -+ class Foo:
500.425 -| global x
500.426 -+ def __call__(self, y):
500.427 -- return x + y
500.428 -| return Foo()
500.429 --
500.430 - x = 0
500.431 - verify(test(6)(2) == 8)
500.432 - x = -1
500.433 - verify(test(3)(2) == 5)
500.434 -
500.435 - print "18. verify that locals() works"
500.436 -
500.437 -+ def f(x):
500.438 -+ def g(y):
500.439 -+ def h(z):
500.440 -- return y + z
500.441 -| w = x + y
500.442 -| y += 3
500.443 -- return locals()
500.444 -| return g
500.445 --
500.446 - d = f(2)(4)
500.447 - verify(d.has_key('h'))
500.448 - del d['h']
500.449 - verify(d == {'x': 2, 'y': 7, 'w': 6})
500.450 -
500.451 - print "19. var is bound and free in class"
500.452 -
500.453 -+ def f(x):
500.454 -+ class C:
500.455 -+ def m(self):
500.456 -- return x
500.457 -- a = x
500.458 -| return C
500.459 --
500.460 - inst = f(3)()
500.461 - verify(inst.a == inst.m())
500.462 -
500.463 - print "20. interaction with trace function"
500.464 -
500.465 - import sys
500.466 -+ def tracer(a,b,c):
500.467 -| return tracer
500.468 --
500.469 -+ def adaptgetter(name, klass, getter):
500.470 -| kind, des = getter
500.471 -| if kind == 1: # AV happens when stepping from this line to next
500.472 -| if des == "":
500.473 -| des = "_%s__%s" % (klass.__name__, name)
500.474 -| return lambda obj: getattr(obj, des)
500.475 --
500.476 -+ class TestClass:
500.477 -| pass
500.478 --
500.479 - sys.settrace(tracer)
500.480 - adaptgetter("foo", TestClass, (1, ""))
500.481 - sys.settrace(None)
500.482 -
500.483 - try: sys.settrace()
500.484 - except TypeError: pass
500.485 - else: raise TestFailed, 'sys.settrace() did not raise TypeError'
500.486 -
500.487 - print "20. eval and exec with free variables"
500.488 -
500.489 -+ def f(x):
500.490 -| return lambda: x + 1
500.491 --
500.492 - g = f(3)
500.493 - try:
500.494 - eval(g.func_code)
500.495 - except TypeError:
500.496 - pass
500.497 - else:
500.498 - print "eval() should have failed, because code contained free vars"
500.499 -
500.500 - try:
500.501 - exec g.func_code
500.502 - except TypeError:
500.503 - pass
500.504 - else:
500.505 - print "exec should have failed, because code contained free vars"
500.506 -
500.507 - print "21. list comprehension with local variables"
500.508 -
500.509 - try:
500.510 - print bad
500.511 - except NameError:
500.512 - pass
500.513 - else:
500.514 - print "bad should not be defined"
500.515 -
500.516 -+ def x():
500.517 -| [bad for s in 'a b' for bad in s.split()]
500.518 --
500.519 - x()
500.520 - try:
500.521 - print bad
500.522 - except NameError:
500.523 - pass
500.524 -
500.525 - print "22. eval with free variables"
500.526 -
500.527 -+ def f(x):
500.528 -+ def g():
500.529 -| x
500.530 -- eval("x + 1")
500.531 -| return g
500.532 --
500.533 - f(4)()
500.534 -
501.1 --- a/python.editor/test/unit/data/testfiles/test_scope.py.nameoffsets Sun Jan 04 13:11:53 2015 -0600
501.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
501.3 @@ -1,531 +0,0 @@
501.4 -
501.5 -from test_support import verify, TestFailed, check_syntax
501.6 -
501.7 -import warnings
501.8 -<Attribute><Name>warnings</Name></Attribute>.<Call>filterwarnings</Call>("ignore", r"import \*", <Name>SyntaxWarning</Name>, "<string>")
501.9 -
501.10 -print "1. simple nesting"
501.11 -
501.12 -def <FunctionDef>make_adder</FunctionDef>(<Name>x</Name>):
501.13 - def <FunctionDef>adder</FunctionDef>(<Name>y</Name>):
501.14 - return <Name>x</Name> + <Name>y</Name>
501.15 - return <Name>adder</Name>
501.16 -
501.17 -<Name>inc</Name> = <Call><Name>make_adder</Name></Call>(1)
501.18 -<Name>plus10</Name> = <Call><Name>make_adder</Name></Call>(10)
501.19 -
501.20 -<Call><Name>verify</Name></Call>(<Call><Name>inc</Name></Call>(1) == 2)
501.21 -<Call><Name>verify</Name></Call>(<Call><Name>plus10</Name></Call>(-2) == 8)
501.22 -
501.23 -print "2. extra nesting"
501.24 -
501.25 -def <FunctionDef>make_adder2</FunctionDef>(<Name>x</Name>):
501.26 - def <FunctionDef>extra</FunctionDef>(): # check freevars passing through non-use scopes
501.27 - def <FunctionDef>adder</FunctionDef>(<Name>y</Name>):
501.28 - return <Name>x</Name> + <Name>y</Name>
501.29 - return <Name>adder</Name>
501.30 - return <Call><Name>extra</Name></Call>()
501.31 -
501.32 -<Name>inc</Name> = <Call><Name>make_adder2</Name></Call>(1)
501.33 -<Name>plus10</Name> = <Call><Name>make_adder2</Name></Call>(10)
501.34 -
501.35 -<Call><Name>verify</Name></Call>(<Call><Name>inc</Name></Call>(1) == 2)
501.36 -<Call><Name>verify</Name></Call>(<Call><Name>plus10</Name></Call>(-2) == 8)
501.37 -
501.38 -print "3. simple nesting + rebinding"
501.39 -
501.40 -def <FunctionDef>make_adder3</FunctionDef>(<Name>x</Name>):
501.41 - def <FunctionDef>adder</FunctionDef>(<Name>y</Name>):
501.42 - return <Name>x</Name> + <Name>y</Name>
501.43 - <Name>x</Name> = <Name>x</Name> + 1 # check tracking of assignment to x in defining scope
501.44 - return <Name>adder</Name>
501.45 -
501.46 -<Name>inc</Name> = <Call><Name>make_adder3</Name></Call>(0)
501.47 -<Name>plus10</Name> = <Call><Name>make_adder3</Name></Call>(9)
501.48 -
501.49 -<Call><Name>verify</Name></Call>(<Call><Name>inc</Name></Call>(1) == 2)
501.50 -<Call><Name>verify</Name></Call>(<Call><Name>plus10</Name></Call>(-2) == 8)
501.51 -
501.52 -print "4. nesting with global but no free"
501.53 -
501.54 -def <FunctionDef>make_adder4</FunctionDef>(): # XXX add exta level of indirection
501.55 - def <FunctionDef>nest</FunctionDef>():
501.56 - def <FunctionDef>nest</FunctionDef>():
501.57 - def <FunctionDef>adder</FunctionDef>(<Name>y</Name>):
501.58 - return <Name>global_x</Name> + <Name>y</Name> # check that plain old globals work
501.59 - return <Name>adder</Name>
501.60 - return <Call><Name>nest</Name></Call>()
501.61 - return <Call><Name>nest</Name></Call>()
501.62 -
501.63 -<Name>global_x</Name> = 1
501.64 -<Name>adder</Name> = <Call><Name>make_adder4</Name></Call>()
501.65 -<Call><Name>verify</Name></Call>(<Call><Name>adder</Name></Call>(1) == 2)
501.66 -
501.67 -<Name>global_x</Name> = 10
501.68 -<Call><Name>verify</Name></Call>(<Call><Name>adder</Name></Call>(-2) == 8)
501.69 -
501.70 -print "5. nesting through class"
501.71 -
501.72 -def <FunctionDef>make_adder5</FunctionDef>(<Name>x</Name>):
501.73 - class <ClassDef>Adder</ClassDef>:
501.74 - def <FunctionDef>__call__</FunctionDef>(<Name>self</Name>, <Name>y</Name>):
501.75 - return <Name>x</Name> + <Name>y</Name>
501.76 - return <Call><Name>Adder</Name></Call>()
501.77 -
501.78 -<Name>inc</Name> = <Call><Name>make_adder5</Name></Call>(1)
501.79 -<Name>plus10</Name> = <Call><Name>make_adder5</Name></Call>(10)
501.80 -
501.81 -<Call><Name>verify</Name></Call>(<Call><Name>inc</Name></Call>(1) == 2)
501.82 -<Call><Name>verify</Name></Call>(<Call><Name>plus10</Name></Call>(-2) == 8)
501.83 -
501.84 -print "6. nesting plus free ref to global"
501.85 -
501.86 -def <FunctionDef>make_adder6</FunctionDef>(<Name>x</Name>):
501.87 - global global_nest_x
501.88 - def <FunctionDef>adder</FunctionDef>(<Name>y</Name>):
501.89 - return <Name>global_nest_x</Name> + <Name>y</Name>
501.90 - <Name>global_nest_x</Name> = <Name>x</Name>
501.91 - return <Name>adder</Name>
501.92 -
501.93 -<Name>inc</Name> = <Call><Name>make_adder6</Name></Call>(1)
501.94 -<Name>plus10</Name> = <Call><Name>make_adder6</Name></Call>(10)
501.95 -
501.96 -<Call><Name>verify</Name></Call>(<Call><Name>inc</Name></Call>(1) == 11) # there's only one global
501.97 -<Call><Name>verify</Name></Call>(<Call><Name>plus10</Name></Call>(-2) == 8)
501.98 -
501.99 -print "7. nearest enclosing scope"
501.100 -
501.101 -def <FunctionDef>f</FunctionDef>(<Name>x</Name>):
501.102 - def <FunctionDef>g</FunctionDef>(<Name>y</Name>):
501.103 - <Name>x</Name> = 42 # check that this masks binding in f()
501.104 - def <FunctionDef>h</FunctionDef>(<Name>z</Name>):
501.105 - return <Name>x</Name> + <Name>z</Name>
501.106 - return <Name>h</Name>
501.107 - return <Call><Name>g</Name></Call>(2)
501.108 -
501.109 -<Name>test_func</Name> = <Call><Name>f</Name></Call>(10)
501.110 -<Call><Name>verify</Name></Call>(<Call><Name>test_func</Name></Call>(5) == 47)
501.111 -
501.112 -print "8. mixed freevars and cellvars"
501.113 -
501.114 -def <FunctionDef>identity</FunctionDef>(<Name>x</Name>):
501.115 - return <Name>x</Name>
501.116 -
501.117 -def <FunctionDef>f</FunctionDef>(<Name>x</Name>, <Name>y</Name>, <Name>z</Name>):
501.118 - def <FunctionDef>g</FunctionDef>(<Name>a</Name>, <Name>b</Name>, <Name>c</Name>):
501.119 - <Name>a</Name> = <Name>a</Name> + <Name>x</Name> # 3
501.120 - def <FunctionDef>h</FunctionDef>():
501.121 - # z * (4 + 9)
501.122 - # 3 * 13
501.123 - return <Call><Name>identity</Name></Call>(<Name>z</Name> * (<Name>b</Name> + <Name>y</Name>))
501.124 - <Name>y</Name> = <Name>c</Name> + <Name>z</Name> # 9
501.125 - return <Name>h</Name>
501.126 - return <Name>g</Name>
501.127 -
501.128 -<Name>g</Name> = <Call><Name>f</Name></Call>(1, 2, 3)
501.129 -<Name>h</Name> = <Call><Name>g</Name></Call>(2, 4, 6)
501.130 -<Call><Name>verify</Name></Call>(<Call><Name>h</Name></Call>() == 39)
501.131 -
501.132 -print "9. free variable in method"
501.133 -
501.134 -def <FunctionDef>test</FunctionDef>():
501.135 - <Name>method_and_var</Name> = "var"
501.136 - class <ClassDef>Test</ClassDef>:
501.137 - def <FunctionDef>method_and_var</FunctionDef>(<Name>self</Name>):
501.138 - return "method"
501.139 - def <FunctionDef>test</FunctionDef>(<Name>self</Name>):
501.140 - return <Name>method_and_var</Name>
501.141 - def <FunctionDef>actual_global</FunctionDef>(<Name>self</Name>):
501.142 - return <Call><Name>str</Name></Call>("global")
501.143 - def <FunctionDef>str</FunctionDef>(<Name>self</Name>):
501.144 - return <Call><Name>str</Name></Call>(<Name>self</Name>)
501.145 - return <Call><Name>Test</Name></Call>()
501.146 -
501.147 -<Name>t</Name> = <Call><Name>test</Name></Call>()
501.148 -<Call><Name>verify</Name></Call>(<Attribute><Name>t</Name></Attribute>.<Call>test</Call>() == "var")
501.149 -<Call><Name>verify</Name></Call>(<Attribute><Name>t</Name></Attribute>.<Call>method_and_var</Call>() == "method")
501.150 -<Call><Name>verify</Name></Call>(<Attribute><Name>t</Name></Attribute>.<Call>actual_global</Call>() == "global")
501.151 -
501.152 -<Name>method_and_var</Name> = "var"
501.153 -class <ClassDef>Test</ClassDef>:
501.154 - # this class is not nested, so the rules are different
501.155 - def <FunctionDef>method_and_var</FunctionDef>(<Name>self</Name>):
501.156 - return "method"
501.157 - def <FunctionDef>test</FunctionDef>(<Name>self</Name>):
501.158 - return <Name>method_and_var</Name>
501.159 - def <FunctionDef>actual_global</FunctionDef>(<Name>self</Name>):
501.160 - return <Call><Name>str</Name></Call>("global")
501.161 - def <FunctionDef>str</FunctionDef>(<Name>self</Name>):
501.162 - return <Call><Name>str</Name></Call>(<Name>self</Name>)
501.163 -
501.164 -<Name>t</Name> = <Call><Name>Test</Name></Call>()
501.165 -<Call><Name>verify</Name></Call>(<Attribute><Name>t</Name></Attribute>.<Call>test</Call>() == "var")
501.166 -<Call><Name>verify</Name></Call>(<Attribute><Name>t</Name></Attribute>.<Call>method_and_var</Call>() == "method")
501.167 -<Call><Name>verify</Name></Call>(<Attribute><Name>t</Name></Attribute>.<Call>actual_global</Call>() == "global")
501.168 -
501.169 -print "10. recursion"
501.170 -
501.171 -def <FunctionDef>f</FunctionDef>(<Name>x</Name>):
501.172 - def <FunctionDef>fact</FunctionDef>(<Name>n</Name>):
501.173 - if <Name>n</Name> == 0:
501.174 - return 1
501.175 - else:
501.176 - return <Name>n</Name> * <Call><Name>fact</Name></Call>(<Name>n</Name> - 1)
501.177 - if <Name>x</Name> >= 0:
501.178 - return <Call><Name>fact</Name></Call>(<Name>x</Name>)
501.179 - else:
501.180 - raise <Name>ValueError</Name>, "x must be >= 0"
501.181 -
501.182 -<Call><Name>verify</Name></Call>(<Call><Name>f</Name></Call>(6) == 720)
501.183 -
501.184 -
501.185 -print "11. unoptimized namespaces"
501.186 -
501.187 -<Call><Name>check_syntax</Name></Call>("""\
501.188 -def unoptimized_clash1(strip):
501.189 - def f(s):
501.190 - from string import *
501.191 - return strip(s) # ambiguity: free or local
501.192 - return f
501.193 -""")
501.194 -
501.195 -<Call><Name>check_syntax</Name></Call>("""\
501.196 -def unoptimized_clash2():
501.197 - from string import *
501.198 - def f(s):
501.199 - return strip(s) # ambiguity: global or local
501.200 - return f
501.201 -""")
501.202 -
501.203 -<Call><Name>check_syntax</Name></Call>("""\
501.204 -def unoptimized_clash2():
501.205 - from string import *
501.206 - def g():
501.207 - def f(s):
501.208 - return strip(s) # ambiguity: global or local
501.209 - return f
501.210 -""")
501.211 -
501.212 -# XXX could allow this for exec with const argument, but what's the point
501.213 -<Call><Name>check_syntax</Name></Call>("""\
501.214 -def error(y):
501.215 - exec "a = 1"
501.216 - def f(x):
501.217 - return x + y
501.218 - return f
501.219 -""")
501.220 -
501.221 -<Call><Name>check_syntax</Name></Call>("""\
501.222 -def f(x):
501.223 - def g():
501.224 - return x
501.225 - del x # can't del name
501.226 -""")
501.227 -
501.228 -<Call><Name>check_syntax</Name></Call>("""\
501.229 -def f():
501.230 - def g():
501.231 - from string import *
501.232 - return strip # global or local?
501.233 -""")
501.234 -
501.235 -# and verify a few cases that should work
501.236 -
501.237 -exec """
501.238 -def noproblem1():
501.239 - from string import *
501.240 - f = lambda x:x
501.241 -
501.242 -def noproblem2():
501.243 - from string import *
501.244 - def f(x):
501.245 - return x + 1
501.246 -
501.247 -def noproblem3():
501.248 - from string import *
501.249 - def f(x):
501.250 - global y
501.251 - y = x
501.252 -"""
501.253 -
501.254 -print "12. lambdas"
501.255 -
501.256 -<Name>f1</Name> = lambda <Name>x</Name>: lambda <Name>y</Name>: <Name>x</Name> + <Name>y</Name>
501.257 -<Name>inc</Name> = <Call><Name>f1</Name></Call>(1)
501.258 -<Name>plus10</Name> = <Call><Name>f1</Name></Call>(10)
501.259 -<Call><Name>verify</Name></Call>(<Call><Name>inc</Name></Call>(1) == 2)
501.260 -<Call><Name>verify</Name></Call>(<Call><Name>plus10</Name></Call>(5) == 15)
501.261 -
501.262 -<Name>f2</Name> = lambda <Name>x</Name>: (lambda : lambda <Name>y</Name>: <Name>x</Name> + <Name>y</Name>)()
501.263 -<Name>inc</Name> = <Call><Name>f2</Name></Call>(1)
501.264 -<Name>plus10</Name> = <Call><Name>f2</Name></Call>(10)
501.265 -<Call><Name>verify</Name></Call>(<Call><Name>inc</Name></Call>(1) == 2)
501.266 -<Call><Name>verify</Name></Call>(<Call><Name>plus10</Name></Call>(5) == 15)
501.267 -
501.268 -<Name>f3</Name> = lambda <Name>x</Name>: lambda <Name>y</Name>: <Name>global_x</Name> + <Name>y</Name>
501.269 -<Name>global_x</Name> = 1
501.270 -<Name>inc</Name> = <Call><Name>f3</Name></Call>(<Name>None</Name>)
501.271 -<Call><Name>verify</Name></Call>(<Call><Name>inc</Name></Call>(2) == 3)
501.272 -
501.273 -<Name>f8</Name> = lambda <Name>x</Name>, <Name>y</Name>, <Name>z</Name>: lambda <Name>a</Name>, <Name>b</Name>, <Name>c</Name>: lambda : <Name>z</Name> * (<Name>b</Name> + <Name>y</Name>)
501.274 -<Name>g</Name> = <Call><Name>f8</Name></Call>(1, 2, 3)
501.275 -<Name>h</Name> = <Call><Name>g</Name></Call>(2, 4, 6)
501.276 -<Call><Name>verify</Name></Call>(<Call><Name>h</Name></Call>() == 18)
501.277 -
501.278 -print "13. UnboundLocal"
501.279 -
501.280 -def <FunctionDef>errorInOuter</FunctionDef>():
501.281 - print <Name>y</Name>
501.282 - def <FunctionDef>inner</FunctionDef>():
501.283 - return <Name>y</Name>
501.284 - <Name>y</Name> = 1
501.285 -
501.286 -def <FunctionDef>errorInInner</FunctionDef>():
501.287 - def <FunctionDef>inner</FunctionDef>():
501.288 - return <Name>y</Name>
501.289 - <Call><Name>inner</Name></Call>()
501.290 - <Name>y</Name> = 1
501.291 -
501.292 -try:
501.293 - <Call><Name>errorInOuter</Name></Call>()
501.294 -except <Name>UnboundLocalError</Name>:
501.295 - pass
501.296 -else:
501.297 - raise <Name>TestFailed</Name>
501.298 -
501.299 -try:
501.300 - <Call><Name>errorInInner</Name></Call>()
501.301 -except <Name>NameError</Name>:
501.302 - pass
501.303 -else:
501.304 - raise <Name>TestFailed</Name>
501.305 -
501.306 -print "14. complex definitions"
501.307 -
501.308 -def <FunctionDef>makeReturner</FunctionDef>(*lst):
501.309 - def <FunctionDef>returner</FunctionDef>():
501.310 - return <Name>lst</Name>
501.311 - return <Name>returner</Name>
501.312 -
501.313 -<Call><Name>verify</Name></Call>(<Call><Call><Name>makeReturner</Name></Call></Call>(1,2,3)() == (1,2,3))
501.314 -
501.315 -def <FunctionDef>makeReturner2</FunctionDef>(**kwargs):
501.316 - def <FunctionDef>returner</FunctionDef>():
501.317 - return <Name>kwargs</Name>
501.318 - return <Name>returner</Name>
501.319 -
501.320 -<Call><Name>verify</Name></Call>(<Call><Name>makeReturner2</Name></Call>(a=11)<Call>()['a'] == 11</Call>)
501.321 -
501.322 -def <FunctionDef>makeAddPair</FunctionDef>((<Name>a</Name>, <Name>b</Name>)):
501.323 - def <FunctionDef>addPair</FunctionDef>((<Name>c</Name>, <Name>d</Name>)):
501.324 - return (<Name>a</Name> + <Name>c</Name>, <Name>b</Name> + <Name>d</Name>)
501.325 - return <Name>addPair</Name>
501.326 -
501.327 -<Call><Name>verify</Name></Call>(<Call><Call><Name>makeAddPair</Name></Call></Call>((1, 2))((100, 200)) == (101,202))
501.328 -
501.329 -print "15. scope of global statements"
501.330 -# Examples posted by Samuele Pedroni to python-dev on 3/1/2001
501.331 -
501.332 -# I
501.333 -<Name>x</Name> = 7
501.334 -def <FunctionDef>f</FunctionDef>():
501.335 - <Name>x</Name> = 1
501.336 - def <FunctionDef>g</FunctionDef>():
501.337 - global x
501.338 - def <FunctionDef>i</FunctionDef>():
501.339 - def <FunctionDef>h</FunctionDef>():
501.340 - return <Name>x</Name>
501.341 - return <Call><Name>h</Name></Call>()
501.342 - return <Call><Name>i</Name></Call>()
501.343 - return <Call><Name>g</Name></Call>()
501.344 -<Call><Name>verify</Name></Call>(<Call><Name>f</Name></Call>() == 7)
501.345 -<Call><Name>verify</Name></Call>(<Name>x</Name> == 7)
501.346 -
501.347 -# II
501.348 -<Name>x</Name> = 7
501.349 -def <FunctionDef>f</FunctionDef>():
501.350 - <Name>x</Name> = 1
501.351 - def <FunctionDef>g</FunctionDef>():
501.352 - <Name>x</Name> = 2
501.353 - def <FunctionDef>i</FunctionDef>():
501.354 - def <FunctionDef>h</FunctionDef>():
501.355 - return <Name>x</Name>
501.356 - return <Call><Name>h</Name></Call>()
501.357 - return <Call><Name>i</Name></Call>()
501.358 - return <Call><Name>g</Name></Call>()
501.359 -<Call><Name>verify</Name></Call>(<Call><Name>f</Name></Call>() == 2)
501.360 -<Call><Name>verify</Name></Call>(<Name>x</Name> == 7)
501.361 -
501.362 -# III
501.363 -<Name>x</Name> = 7
501.364 -def <FunctionDef>f</FunctionDef>():
501.365 - <Name>x</Name> = 1
501.366 - def <FunctionDef>g</FunctionDef>():
501.367 - global x
501.368 - <Name>x</Name> = 2
501.369 - def <FunctionDef>i</FunctionDef>():
501.370 - def <FunctionDef>h</FunctionDef>():
501.371 - return <Name>x</Name>
501.372 - return <Call><Name>h</Name></Call>()
501.373 - return <Call><Name>i</Name></Call>()
501.374 - return <Call><Name>g</Name></Call>()
501.375 -<Call><Name>verify</Name></Call>(<Call><Name>f</Name></Call>() == 2)
501.376 -<Call><Name>verify</Name></Call>(<Name>x</Name> == 2)
501.377 -
501.378 -# IV
501.379 -<Name>x</Name> = 7
501.380 -def <FunctionDef>f</FunctionDef>():
501.381 - <Name>x</Name> = 3
501.382 - def <FunctionDef>g</FunctionDef>():
501.383 - global x
501.384 - <Name>x</Name> = 2
501.385 - def <FunctionDef>i</FunctionDef>():
501.386 - def <FunctionDef>h</FunctionDef>():
501.387 - return <Name>x</Name>
501.388 - return <Call><Name>h</Name></Call>()
501.389 - return <Call><Name>i</Name></Call>()
501.390 - return <Call><Name>g</Name></Call>()
501.391 -<Call><Name>verify</Name></Call>(<Call><Name>f</Name></Call>() == 2)
501.392 -<Call><Name>verify</Name></Call>(<Name>x</Name> == 2)
501.393 -
501.394 -print "16. check leaks"
501.395 -
501.396 -class <ClassDef>Foo</ClassDef>:
501.397 - <Name>count</Name> = 0
501.398 -
501.399 - def <FunctionDef>__init__</FunctionDef>(<Name>self</Name>):
501.400 - <Attribute><Name>Foo</Name></Attribute>.count += 1
501.401 -
501.402 - def <FunctionDef>__del__</FunctionDef>(<Name>self</Name>):
501.403 - <Attribute><Name>Foo</Name></Attribute>.count -= 1
501.404 -
501.405 -def <FunctionDef>f1</FunctionDef>():
501.406 - <Name>x</Name> = <Call><Name>Foo</Name></Call>()
501.407 - def <FunctionDef>f2</FunctionDef>():
501.408 - return <Name>x</Name>
501.409 - <Call><Name>f2</Name></Call>()
501.410 -
501.411 -for <Name>i</Name> in <Call><Name>range</Name></Call>(100):
501.412 - <Call><Name>f1</Name></Call>()
501.413 -
501.414 -import os
501.415 -if <Attribute><Name>os</Name></Attribute>.name == 'java':
501.416 - from java.lang import System, Thread
501.417 - <Attribute><Name>System</Name></Attribute>.<Call>gc</Call>()
501.418 - <Attribute><Name>Thread</Name></Attribute>.<Call>sleep</Call>(100)
501.419 - <Attribute><Name>System</Name></Attribute>.<Call>gc</Call>()
501.420 -<Call><Name>verify</Name></Call>(<Attribute><Name>Foo</Name></Attribute>.count == 0)
501.421 -
501.422 -print "17. class and global"
501.423 -
501.424 -def <FunctionDef>test</FunctionDef>(<Name>x</Name>):
501.425 - class <ClassDef>Foo</ClassDef>:
501.426 - global x
501.427 - def <FunctionDef>__call__</FunctionDef>(<Name>self</Name>, <Name>y</Name>):
501.428 - return <Name>x</Name> + <Name>y</Name>
501.429 - return <Call><Name>Foo</Name></Call>()
501.430 -
501.431 -<Name>x</Name> = 0
501.432 -<Call><Name>verify</Name></Call>(<Call><Call><Name>test</Name></Call></Call>(6)(2) == 8)
501.433 -<Name>x</Name> = -1
501.434 -<Call><Name>verify</Name></Call>(<Call><Call><Name>test</Name></Call></Call>(3)(2) == 5)
501.435 -
501.436 -print "18. verify that locals() works"
501.437 -
501.438 -def <FunctionDef>f</FunctionDef>(<Name>x</Name>):
501.439 - def <FunctionDef>g</FunctionDef>(<Name>y</Name>):
501.440 - def <FunctionDef>h</FunctionDef>(<Name>z</Name>):
501.441 - return <Name>y</Name> + <Name>z</Name>
501.442 - <Name>w</Name> = <Name>x</Name> + <Name>y</Name>
501.443 - <Name>y</Name> += 3
501.444 - return <Call><Name>locals</Name></Call>()
501.445 - return <Name>g</Name>
501.446 -
501.447 -<Name>d</Name> = <Call><Call><Name>f</Name></Call></Call>(2)(4)
501.448 -<Call><Name>verify</Name></Call>(<Attribute><Name>d</Name></Attribute>.<Call>has_key</Call>('h'))
501.449 -del <Name>d</Name>['h']
501.450 -<Call><Name>verify</Name></Call>(<Name>d</Name> == {'x': 2, 'y': 7, 'w': 6})
501.451 -
501.452 -print "19. var is bound and free in class"
501.453 -
501.454 -def <FunctionDef>f</FunctionDef>(<Name>x</Name>):
501.455 - class <ClassDef>C</ClassDef>:
501.456 - def <FunctionDef>m</FunctionDef>(<Name>self</Name>):
501.457 - return <Name>x</Name>
501.458 - <Name>a</Name> = <Name>x</Name>
501.459 - return <Name>C</Name>
501.460 -
501.461 -<Name>inst</Name> = <Call><Call><Name>f</Name></Call></Call>(3)()
501.462 -<Call><Name>verify</Name></Call>(<Attribute><Name>inst</Name></Attribute>.a == <Attribute><Name>inst</Name></Attribute>.<Call>m</Call>())
501.463 -
501.464 -print "20. interaction with trace function"
501.465 -
501.466 -import sys
501.467 -def <FunctionDef>tracer</FunctionDef>(<Name>a</Name>,<Name>b</Name>,<Name>c</Name>):
501.468 - return <Name>tracer</Name>
501.469 -
501.470 -def <FunctionDef>adaptgetter</FunctionDef>(<Name>name</Name>, <Name>klass</Name>, <Name>getter</Name>):
501.471 - <Name>kind</Name>, <Name>des</Name> = <Name>getter</Name>
501.472 - if <Name>kind</Name> == 1: # AV happens when stepping from this line to next
501.473 - if <Name>des</Name> == "":
501.474 - <Name>des</Name> = "_%s__%s" % (<Attribute><Name>klass</Name></Attribute>.__name__, <Name>name</Name>)
501.475 - return lambda <Name>obj</Name>: <Call><Name>getattr</Name></Call>(<Name>obj</Name>, <Name>des</Name>)
501.476 -
501.477 -class <ClassDef>TestClass</ClassDef>:
501.478 - pass
501.479 -
501.480 -<Attribute><Name>sys</Name></Attribute>.<Call>settrace</Call>(<Name>tracer</Name>)
501.481 -<Call><Name>adaptgetter</Name></Call>("foo", <Name>TestClass</Name>, (1, ""))
501.482 -<Attribute><Name>sys</Name></Attribute>.<Call>settrace</Call>(<Name>None</Name>)
501.483 -
501.484 -try: <Attribute><Name>sys</Name></Attribute>.<Call>settrace</Call>()
501.485 -except <Name>TypeError</Name>: pass
501.486 -else: raise <Name>TestFailed</Name>, 'sys.settrace() did not raise TypeError'
501.487 -
501.488 -print "20. eval and exec with free variables"
501.489 -
501.490 -def <FunctionDef>f</FunctionDef>(<Name>x</Name>):
501.491 - return lambda: <Name>x</Name> + 1
501.492 -
501.493 -<Name>g</Name> = <Call><Name>f</Name></Call>(3)
501.494 -try:
501.495 - <Call><Name>eval</Name></Call>(<Attribute><Name>g</Name></Attribute>.func_code)
501.496 -except <Name>TypeError</Name>:
501.497 - pass
501.498 -else:
501.499 - print "eval() should have failed, because code contained free vars"
501.500 -
501.501 -try:
501.502 - exec <Attribute><Name>g</Name></Attribute>.func_code
501.503 -except <Name>TypeError</Name>:
501.504 - pass
501.505 -else:
501.506 - print "exec should have failed, because code contained free vars"
501.507 -
501.508 -print "21. list comprehension with local variables"
501.509 -
501.510 -try:
501.511 - print <Name>bad</Name>
501.512 -except <Name>NameError</Name>:
501.513 - pass
501.514 -else:
501.515 - print "bad should not be defined"
501.516 -
501.517 -def <FunctionDef>x</FunctionDef>():
501.518 - [<Name>bad</Name> for <Name>s</Name> in 'a b' for <Name>bad</Name> in <Attribute><Name>s</Name></Attribute>.<Call>split</Call>()]
501.519 -
501.520 -<Call><Name>x</Name></Call>()
501.521 -try:
501.522 - print <Name>bad</Name>
501.523 -except <Name>NameError</Name>:
501.524 - pass
501.525 -
501.526 -print "22. eval with free variables"
501.527 -
501.528 -def <FunctionDef>f</FunctionDef>(<Name>x</Name>):
501.529 - def <FunctionDef>g</FunctionDef>():
501.530 - <Name>x</Name>
501.531 - <Call><Name>eval</Name></Call>("x + 1")
501.532 - return <Name>g</Name>
501.533 -
501.534 -<Call><Call><Name>f</Name></Call></Call>(4)()
502.1 --- a/python.editor/test/unit/data/testfiles/test_scope.py.offsets Sun Jan 04 13:11:53 2015 -0600
502.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
502.3 @@ -1,531 +0,0 @@
502.4 -
502.5 -<Module><ImportFrom>from test_support import verify, TestFailed, check_syntax</ImportFrom>
502.6 -
502.7 -<Import>import warnings</Import>
502.8 -<Expr><Call><Attribute><Name>warnings</Name>.filterwarnings</Attribute>(<Str>"ignore"</Str>, <Str>r"import \*"</Str>, <Name>SyntaxWarning</Name>, <Str>"<string>"</Str>)</Call></Expr>
502.9 -
502.10 -<Print>print <Str>"1. simple nesting"</Str></Print>
502.11 -
502.12 -<FunctionDef>def make_adder(<Name>x</Name>):
502.13 - <FunctionDef>def adder(<Name>y</Name>):
502.14 - <Return>return <BinOp><Name>x</Name> + <Name>y</Name></BinOp></Return>
502.15 - </FunctionDef> <Return>return <Name>adder</Name></Return>
502.16 -
502.17 -</FunctionDef><Assign><Name>inc</Name> = <Call><Name>make_adder</Name>(<Num>1</Num>)</Call></Assign>
502.18 -<Assign><Name>plus10</Name> = <Call><Name>make_adder</Name>(<Num>10</Num>)</Call></Assign>
502.19 -
502.20 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>inc</Name>(<Num>1</Num>)</Call> == <Num>2</Num></Compare>)</Call></Expr>
502.21 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>plus10</Name>(<Num>-2</Num>)</Call> == <Num>8</Num></Compare>)</Call></Expr>
502.22 -
502.23 -<Print>print <Str>"2. extra nesting"</Str></Print>
502.24 -
502.25 -<FunctionDef>def make_adder2(<Name>x</Name>):
502.26 - <FunctionDef>def extra(): # check freevars passing through non-use scopes
502.27 - <FunctionDef>def adder(<Name>y</Name>):
502.28 - <Return>return <BinOp><Name>x</Name> + <Name>y</Name></BinOp></Return>
502.29 - </FunctionDef> <Return>return <Name>adder</Name></Return>
502.30 - </FunctionDef> <Return>return <Call><Name>extra</Name>()</Call></Return>
502.31 -
502.32 -</FunctionDef><Assign><Name>inc</Name> = <Call><Name>make_adder2</Name>(<Num>1</Num>)</Call></Assign>
502.33 -<Assign><Name>plus10</Name> = <Call><Name>make_adder2</Name>(<Num>10</Num>)</Call></Assign>
502.34 -
502.35 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>inc</Name>(<Num>1</Num>)</Call> == <Num>2</Num></Compare>)</Call></Expr>
502.36 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>plus10</Name>(<Num>-2</Num>)</Call> == <Num>8</Num></Compare>)</Call></Expr>
502.37 -
502.38 -<Print>print <Str>"3. simple nesting + rebinding"</Str></Print>
502.39 -
502.40 -<FunctionDef>def make_adder3(<Name>x</Name>):
502.41 - <FunctionDef>def adder(<Name>y</Name>):
502.42 - <Return>return <BinOp><Name>x</Name> + <Name>y</Name></BinOp></Return>
502.43 - </FunctionDef> <Assign><Name>x</Name> = <BinOp><Name>x</Name> + <Num>1</Num></BinOp></Assign> # check tracking of assignment to x in defining scope
502.44 - <Return>return <Name>adder</Name></Return>
502.45 -
502.46 -</FunctionDef><Assign><Name>inc</Name> = <Call><Name>make_adder3</Name>(<Num>0</Num>)</Call></Assign>
502.47 -<Assign><Name>plus10</Name> = <Call><Name>make_adder3</Name>(<Num>9</Num>)</Call></Assign>
502.48 -
502.49 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>inc</Name>(<Num>1</Num>)</Call> == <Num>2</Num></Compare>)</Call></Expr>
502.50 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>plus10</Name>(<Num>-2</Num>)</Call> == <Num>8</Num></Compare>)</Call></Expr>
502.51 -
502.52 -<Print>print <Str>"4. nesting with global but no free"</Str></Print>
502.53 -
502.54 -<FunctionDef>def make_adder4(): # XXX add exta level of indirection
502.55 - <FunctionDef>def nest():
502.56 - <FunctionDef>def nest():
502.57 - <FunctionDef>def adder(<Name>y</Name>):
502.58 - <Return>return <BinOp><Name>global_x</Name> + <Name>y</Name></BinOp></Return> # check that plain old globals work
502.59 - </FunctionDef> <Return>return <Name>adder</Name></Return>
502.60 - </FunctionDef> <Return>return <Call><Name>nest</Name>()</Call></Return>
502.61 - </FunctionDef> <Return>return <Call><Name>nest</Name>()</Call></Return>
502.62 -
502.63 -</FunctionDef><Assign><Name>global_x</Name> = <Num>1</Num></Assign>
502.64 -<Assign><Name>adder</Name> = <Call><Name>make_adder4</Name>()</Call></Assign>
502.65 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>adder</Name>(<Num>1</Num>)</Call> == <Num>2</Num></Compare>)</Call></Expr>
502.66 -
502.67 -<Assign><Name>global_x</Name> = <Num>10</Num></Assign>
502.68 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>adder</Name>(<Num>-2</Num>)</Call> == <Num>8</Num></Compare>)</Call></Expr>
502.69 -
502.70 -<Print>print <Str>"5. nesting through class"</Str></Print>
502.71 -
502.72 -<FunctionDef>def make_adder5(<Name>x</Name>):
502.73 - <ClassDef>class Adder:
502.74 - <FunctionDef>def __call__(<Name>self</Name>, <Name>y</Name>):
502.75 - <Return>return <BinOp><Name>x</Name> + <Name>y</Name></BinOp></Return>
502.76 - </FunctionDef></ClassDef> <Return>return <Call><Name>Adder</Name>()</Call></Return>
502.77 -
502.78 -</FunctionDef><Assign><Name>inc</Name> = <Call><Name>make_adder5</Name>(<Num>1</Num>)</Call></Assign>
502.79 -<Assign><Name>plus10</Name> = <Call><Name>make_adder5</Name>(<Num>10</Num>)</Call></Assign>
502.80 -
502.81 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>inc</Name>(<Num>1</Num>)</Call> == <Num>2</Num></Compare>)</Call></Expr>
502.82 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>plus10</Name>(<Num>-2</Num>)</Call> == <Num>8</Num></Compare>)</Call></Expr>
502.83 -
502.84 -<Print>print <Str>"6. nesting plus free ref to global"</Str></Print>
502.85 -
502.86 -<FunctionDef>def make_adder6(<Name>x</Name>):
502.87 - <Global>global global_nest_x</Global>
502.88 - <FunctionDef>def adder(<Name>y</Name>):
502.89 - <Return>return <BinOp><Name>global_nest_x</Name> + <Name>y</Name></BinOp></Return>
502.90 - </FunctionDef> <Assign><Name>global_nest_x</Name> = <Name>x</Name></Assign>
502.91 - <Return>return <Name>adder</Name></Return>
502.92 -
502.93 -</FunctionDef><Assign><Name>inc</Name> = <Call><Name>make_adder6</Name>(<Num>1</Num>)</Call></Assign>
502.94 -<Assign><Name>plus10</Name> = <Call><Name>make_adder6</Name>(<Num>10</Num>)</Call></Assign>
502.95 -
502.96 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>inc</Name>(<Num>1</Num>)</Call> == <Num>11</Num></Compare>)</Call></Expr> # there's only one global
502.97 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>plus10</Name>(<Num>-2</Num>)</Call> == <Num>8</Num></Compare>)</Call></Expr>
502.98 -
502.99 -<Print>print <Str>"7. nearest enclosing scope"</Str></Print>
502.100 -
502.101 -<FunctionDef>def f(<Name>x</Name>):
502.102 - <FunctionDef>def g(<Name>y</Name>):
502.103 - <Assign><Name>x</Name> = <Num>42</Num></Assign> # check that this masks binding in f()
502.104 - <FunctionDef>def h(<Name>z</Name>):
502.105 - <Return>return <BinOp><Name>x</Name> + <Name>z</Name></BinOp></Return>
502.106 - </FunctionDef> <Return>return <Name>h</Name></Return>
502.107 - </FunctionDef> <Return>return <Call><Name>g</Name>(<Num>2</Num>)</Call></Return>
502.108 -
502.109 -</FunctionDef><Assign><Name>test_func</Name> = <Call><Name>f</Name>(<Num>10</Num>)</Call></Assign>
502.110 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>test_func</Name>(<Num>5</Num>)</Call> == <Num>47</Num></Compare>)</Call></Expr>
502.111 -
502.112 -<Print>print <Str>"8. mixed freevars and cellvars"</Str></Print>
502.113 -
502.114 -<FunctionDef>def identity(<Name>x</Name>):
502.115 - <Return>return <Name>x</Name></Return>
502.116 -
502.117 -</FunctionDef><FunctionDef>def f(<Name>x</Name>, <Name>y</Name>, <Name>z</Name>):
502.118 - <FunctionDef>def g(<Name>a</Name>, <Name>b</Name>, <Name>c</Name>):
502.119 - <Assign><Name>a</Name> = <BinOp><Name>a</Name> + <Name>x</Name></BinOp></Assign> # 3
502.120 - <FunctionDef>def h():
502.121 - # z * (4 + 9)
502.122 - # 3 * 13
502.123 - <Return>return <Call><Name>identity</Name>(<BinOp><Name>z</Name> * <BinOp>(<Name>b</Name> + <Name>y</Name>)</BinOp></BinOp>)</Call></Return>
502.124 - </FunctionDef> <Assign><Name>y</Name> = <BinOp><Name>c</Name> + <Name>z</Name></BinOp></Assign> # 9
502.125 - <Return>return <Name>h</Name></Return>
502.126 - </FunctionDef> <Return>return <Name>g</Name></Return>
502.127 -
502.128 -</FunctionDef><Assign><Name>g</Name> = <Call><Name>f</Name>(<Num>1</Num>, <Num>2</Num>, <Num>3</Num>)</Call></Assign>
502.129 -<Assign><Name>h</Name> = <Call><Name>g</Name>(<Num>2</Num>, <Num>4</Num>, <Num>6</Num>)</Call></Assign>
502.130 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>h</Name>()</Call> == <Num>39</Num></Compare>)</Call></Expr>
502.131 -
502.132 -<Print>print <Str>"9. free variable in method"</Str></Print>
502.133 -
502.134 -<FunctionDef>def test():
502.135 - <Assign><Name>method_and_var</Name> = <Str>"var"</Str></Assign>
502.136 - <ClassDef>class Test:
502.137 - <FunctionDef>def method_and_var(<Name>self</Name>):
502.138 - <Return>return <Str>"method"</Str></Return>
502.139 - </FunctionDef> <FunctionDef>def test(<Name>self</Name>):
502.140 - <Return>return <Name>method_and_var</Name></Return>
502.141 - </FunctionDef> <FunctionDef>def actual_global(<Name>self</Name>):
502.142 - <Return>return <Call><Name>str</Name>(<Str>"global"</Str>)</Call></Return>
502.143 - </FunctionDef> <FunctionDef>def str(<Name>self</Name>):
502.144 - <Return>return <Call><Name>str</Name>(<Name>self</Name>)</Call></Return>
502.145 - </FunctionDef></ClassDef> <Return>return <Call><Name>Test</Name>()</Call></Return>
502.146 -
502.147 -</FunctionDef><Assign><Name>t</Name> = <Call><Name>test</Name>()</Call></Assign>
502.148 -<Expr><Call><Name>verify</Name>(<Compare><Call><Attribute><Name>t</Name>.test</Attribute>()</Call> == <Str>"var"</Str></Compare>)</Call></Expr>
502.149 -<Expr><Call><Name>verify</Name>(<Compare><Call><Attribute><Name>t</Name>.method_and_var</Attribute>()</Call> == <Str>"method"</Str></Compare>)</Call></Expr>
502.150 -<Expr><Call><Name>verify</Name>(<Compare><Call><Attribute><Name>t</Name>.actual_global</Attribute>()</Call> == <Str>"global"</Str></Compare>)</Call></Expr>
502.151 -
502.152 -<Assign><Name>method_and_var</Name> = <Str>"var"</Str></Assign>
502.153 -<ClassDef>class Test:
502.154 - # this class is not nested, so the rules are different
502.155 - <FunctionDef>def method_and_var(<Name>self</Name>):
502.156 - <Return>return <Str>"method"</Str></Return>
502.157 - </FunctionDef> <FunctionDef>def test(<Name>self</Name>):
502.158 - <Return>return <Name>method_and_var</Name></Return>
502.159 - </FunctionDef> <FunctionDef>def actual_global(<Name>self</Name>):
502.160 - <Return>return <Call><Name>str</Name>(<Str>"global"</Str>)</Call></Return>
502.161 - </FunctionDef> <FunctionDef>def str(<Name>self</Name>):
502.162 - <Return>return <Call><Name>str</Name>(<Name>self</Name>)</Call></Return>
502.163 -
502.164 -</FunctionDef></ClassDef><Assign><Name>t</Name> = <Call><Name>Test</Name>()</Call></Assign>
502.165 -<Expr><Call><Name>verify</Name>(<Compare><Call><Attribute><Name>t</Name>.test</Attribute>()</Call> == <Str>"var"</Str></Compare>)</Call></Expr>
502.166 -<Expr><Call><Name>verify</Name>(<Compare><Call><Attribute><Name>t</Name>.method_and_var</Attribute>()</Call> == <Str>"method"</Str></Compare>)</Call></Expr>
502.167 -<Expr><Call><Name>verify</Name>(<Compare><Call><Attribute><Name>t</Name>.actual_global</Attribute>()</Call> == <Str>"global"</Str></Compare>)</Call></Expr>
502.168 -
502.169 -<Print>print <Str>"10. recursion"</Str></Print>
502.170 -
502.171 -<FunctionDef>def f(<Name>x</Name>):
502.172 - <FunctionDef>def fact(<Name>n</Name>):
502.173 - <If>if <Compare><Name>n</Name> == <Num>0</Num></Compare>:
502.174 - <Return>return <Num>1</Num></Return>
502.175 - else:
502.176 - <Return>return <BinOp><Name>n</Name> * <Call><Name>fact</Name>(<BinOp><Name>n</Name> - <Num>1</Num></BinOp>)</Call></BinOp></Return>
502.177 - </If></FunctionDef> <If>if <Compare><Name>x</Name> >= <Num>0</Num></Compare>:
502.178 - <Return>return <Call><Name>fact</Name>(<Name>x</Name>)</Call></Return>
502.179 - else:
502.180 - <Raise>raise <Name>ValueError</Name>, <Str>"x must be >= 0"</Str></Raise>
502.181 -
502.182 -</If></FunctionDef><Expr><Call><Name>verify</Name>(<Compare><Call><Name>f</Name>(<Num>6</Num>)</Call> == <Num>720</Num></Compare>)</Call></Expr>
502.183 -
502.184 -
502.185 -<Print>print <Str>"11. unoptimized namespaces"</Str></Print>
502.186 -
502.187 -<Expr><Call><Name>check_syntax</Name>(<Str>"""\
502.188 -def unoptimized_clash1(strip):
502.189 - def f(s):
502.190 - from string import *
502.191 - return strip(s) # ambiguity: free or local
502.192 - return f
502.193 -"""</Str>)</Call></Expr>
502.194 -
502.195 -<Expr><Call><Name>check_syntax</Name>(<Str>"""\
502.196 -def unoptimized_clash2():
502.197 - from string import *
502.198 - def f(s):
502.199 - return strip(s) # ambiguity: global or local
502.200 - return f
502.201 -"""</Str>)</Call></Expr>
502.202 -
502.203 -<Expr><Call><Name>check_syntax</Name>(<Str>"""\
502.204 -def unoptimized_clash2():
502.205 - from string import *
502.206 - def g():
502.207 - def f(s):
502.208 - return strip(s) # ambiguity: global or local
502.209 - return f
502.210 -"""</Str>)</Call></Expr>
502.211 -
502.212 -# XXX could allow this for exec with const argument, but what's the point
502.213 -<Expr><Call><Name>check_syntax</Name>(<Str>"""\
502.214 -def error(y):
502.215 - exec "a = 1"
502.216 - def f(x):
502.217 - return x + y
502.218 - return f
502.219 -"""</Str>)</Call></Expr>
502.220 -
502.221 -<Expr><Call><Name>check_syntax</Name>(<Str>"""\
502.222 -def f(x):
502.223 - def g():
502.224 - return x
502.225 - del x # can't del name
502.226 -"""</Str>)</Call></Expr>
502.227 -
502.228 -<Expr><Call><Name>check_syntax</Name>(<Str>"""\
502.229 -def f():
502.230 - def g():
502.231 - from string import *
502.232 - return strip # global or local?
502.233 -"""</Str>)</Call></Expr>
502.234 -
502.235 -# and verify a few cases that should work
502.236 -
502.237 -<Exec>exec <Str>"""
502.238 -def noproblem1():
502.239 - from string import *
502.240 - f = lambda x:x
502.241 -
502.242 -def noproblem2():
502.243 - from string import *
502.244 - def f(x):
502.245 - return x + 1
502.246 -
502.247 -def noproblem3():
502.248 - from string import *
502.249 - def f(x):
502.250 - global y
502.251 - y = x
502.252 -"""</Str></Exec>
502.253 -
502.254 -<Print>print <Str>"12. lambdas"</Str></Print>
502.255 -
502.256 -<Assign><Name>f1</Name> = <Lambda>lambda <Name>x</Name>: <Lambda>lambda <Name>y</Name>: <BinOp><Name>x</Name> + <Name>y</Name></BinOp></Lambda></Lambda></Assign>
502.257 -<Assign><Name>inc</Name> = <Call><Name>f1</Name>(<Num>1</Num>)</Call></Assign>
502.258 -<Assign><Name>plus10</Name> = <Call><Name>f1</Name>(<Num>10</Num>)</Call></Assign>
502.259 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>inc</Name>(<Num>1</Num>)</Call> == <Num>2</Num></Compare>)</Call></Expr>
502.260 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>plus10</Name>(<Num>5</Num>)</Call> == <Num>15</Num></Compare>)</Call></Expr>
502.261 -
502.262 -<Assign><Name>f2</Name> = <Lambda>lambda <Name>x</Name>: <Call><Lambda>(lambda : <Lambda>lambda <Name>y</Name>: <BinOp><Name>x</Name> + <Name>y</Name></BinOp></Lambda>)</Lambda>()</Call></Lambda></Assign>
502.263 -<Assign><Name>inc</Name> = <Call><Name>f2</Name>(<Num>1</Num>)</Call></Assign>
502.264 -<Assign><Name>plus10</Name> = <Call><Name>f2</Name>(<Num>10</Num>)</Call></Assign>
502.265 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>inc</Name>(<Num>1</Num>)</Call> == <Num>2</Num></Compare>)</Call></Expr>
502.266 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>plus10</Name>(<Num>5</Num>)</Call> == <Num>15</Num></Compare>)</Call></Expr>
502.267 -
502.268 -<Assign><Name>f3</Name> = <Lambda>lambda <Name>x</Name>: <Lambda>lambda <Name>y</Name>: <BinOp><Name>global_x</Name> + <Name>y</Name></BinOp></Lambda></Lambda></Assign>
502.269 -<Assign><Name>global_x</Name> = <Num>1</Num></Assign>
502.270 -<Assign><Name>inc</Name> = <Call><Name>f3</Name>(<Name>None</Name>)</Call></Assign>
502.271 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>inc</Name>(<Num>2</Num>)</Call> == <Num>3</Num></Compare>)</Call></Expr>
502.272 -
502.273 -<Assign><Name>f8</Name> = <Lambda>lambda <Name>x</Name>, <Name>y</Name>, <Name>z</Name>: <Lambda>lambda <Name>a</Name>, <Name>b</Name>, <Name>c</Name>: <Lambda>lambda : <BinOp><Name>z</Name> * <BinOp>(<Name>b</Name> + <Name>y</Name>)</BinOp></BinOp></Lambda></Lambda></Lambda></Assign>
502.274 -<Assign><Name>g</Name> = <Call><Name>f8</Name>(<Num>1</Num>, <Num>2</Num>, <Num>3</Num>)</Call></Assign>
502.275 -<Assign><Name>h</Name> = <Call><Name>g</Name>(<Num>2</Num>, <Num>4</Num>, <Num>6</Num>)</Call></Assign>
502.276 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>h</Name>()</Call> == <Num>18</Num></Compare>)</Call></Expr>
502.277 -
502.278 -<Print>print <Str>"13. UnboundLocal"</Str></Print>
502.279 -
502.280 -<FunctionDef>def errorInOuter():
502.281 - <Print>print <Name>y</Name></Print>
502.282 - <FunctionDef>def inner():
502.283 - <Return>return <Name>y</Name></Return>
502.284 - </FunctionDef> <Assign><Name>y</Name> = <Num>1</Num></Assign>
502.285 -
502.286 -</FunctionDef><FunctionDef>def errorInInner():
502.287 - <FunctionDef>def inner():
502.288 - <Return>return <Name>y</Name></Return>
502.289 - </FunctionDef> <Expr><Call><Name>inner</Name>()</Call></Expr>
502.290 - <Assign><Name>y</Name> = <Num>1</Num></Assign>
502.291 -
502.292 -</FunctionDef><TryExcept>try:
502.293 - <Expr><Call><Name>errorInOuter</Name>()</Call></Expr>
502.294 -<ExceptHandler>except <Name>UnboundLocalError</Name>:
502.295 - <Pass>pass</Pass>
502.296 -</ExceptHandler>else:
502.297 - <Raise>raise <Name>TestFailed</Name></Raise>
502.298 -
502.299 -</TryExcept><TryExcept>try:
502.300 - <Expr><Call><Name>errorInInner</Name>()</Call></Expr>
502.301 -<ExceptHandler>except <Name>NameError</Name>:
502.302 - <Pass>pass</Pass>
502.303 -</ExceptHandler>else:
502.304 - <Raise>raise <Name>TestFailed</Name></Raise>
502.305 -
502.306 -</TryExcept><Print>print <Str>"14. complex definitions"</Str></Print>
502.307 -
502.308 -<FunctionDef>def makeReturner(*lst):
502.309 - <FunctionDef>def returner():
502.310 - <Return>return <Name>lst</Name></Return>
502.311 - </FunctionDef> <Return>return <Name>returner</Name></Return>
502.312 -
502.313 -</FunctionDef><Expr><Call><Name>verify</Name>(<Compare><Call><Name>makeReturner</Name><Call>(<Num>1</Num>,<Num>2</Num>,<Num>3</Num>)</Call>()</Call> == <Tuple>(<Num>1</Num>,<Num>2</Num>,<Num>3</Num>)</Tuple></Compare>)</Call></Expr>
502.314 -
502.315 -<FunctionDef>def makeReturner2(**kwargs):
502.316 - <FunctionDef>def returner():
502.317 - <Return>return <Name>kwargs</Name></Return>
502.318 - </FunctionDef> <Return>return <Name>returner</Name></Return>
502.319 -
502.320 -</FunctionDef><Expr><Call><Name>verify</Name>(<Compare><Subscript><Name>makeReturner2</Name><Call>(a=<Num>11</Num>)</Call><Call>()</Call>[<Index><Str>'a'</Str></Index>]</Subscript> == <Num>11</Num></Compare>)</Call></Expr>
502.321 -
502.322 -<FunctionDef>def makeAddPair(<Tuple>(<Name>a</Name>, <Name>b</Name>)</Tuple>):
502.323 - <FunctionDef>def addPair(<Tuple>(<Name>c</Name>, <Name>d</Name>)</Tuple>):
502.324 - <Return>return <Tuple>(<BinOp><Name>a</Name> + <Name>c</Name></BinOp>, <BinOp><Name>b</Name> + <Name>d</Name></BinOp>)</Tuple></Return>
502.325 - </FunctionDef> <Return>return <Name>addPair</Name></Return>
502.326 -
502.327 -</FunctionDef><Expr><Call><Name>verify</Name>(<Compare><Call><Name>makeAddPair</Name><Call>(<Tuple>(<Num>1</Num>, <Num>2</Num>)</Tuple>)</Call>(<Tuple>(<Num>100</Num>, <Num>200</Num>)</Tuple>)</Call> == <Tuple>(<Num>101</Num>,<Num>202</Num>)</Tuple></Compare>)</Call></Expr>
502.328 -
502.329 -<Print>print <Str>"15. scope of global statements"</Str></Print>
502.330 -# Examples posted by Samuele Pedroni to python-dev on 3/1/2001
502.331 -
502.332 -# I
502.333 -<Assign><Name>x</Name> = <Num>7</Num></Assign>
502.334 -<FunctionDef>def f():
502.335 - <Assign><Name>x</Name> = <Num>1</Num></Assign>
502.336 - <FunctionDef>def g():
502.337 - <Global>global x</Global>
502.338 - <FunctionDef>def i():
502.339 - <FunctionDef>def h():
502.340 - <Return>return <Name>x</Name></Return>
502.341 - </FunctionDef> <Return>return <Call><Name>h</Name>()</Call></Return>
502.342 - </FunctionDef> <Return>return <Call><Name>i</Name>()</Call></Return>
502.343 - </FunctionDef> <Return>return <Call><Name>g</Name>()</Call></Return>
502.344 -</FunctionDef><Expr><Call><Name>verify</Name>(<Compare><Call><Name>f</Name>()</Call> == <Num>7</Num></Compare>)</Call></Expr>
502.345 -<Expr><Call><Name>verify</Name>(<Compare><Name>x</Name> == <Num>7</Num></Compare>)</Call></Expr>
502.346 -
502.347 -# II
502.348 -<Assign><Name>x</Name> = <Num>7</Num></Assign>
502.349 -<FunctionDef>def f():
502.350 - <Assign><Name>x</Name> = <Num>1</Num></Assign>
502.351 - <FunctionDef>def g():
502.352 - <Assign><Name>x</Name> = <Num>2</Num></Assign>
502.353 - <FunctionDef>def i():
502.354 - <FunctionDef>def h():
502.355 - <Return>return <Name>x</Name></Return>
502.356 - </FunctionDef> <Return>return <Call><Name>h</Name>()</Call></Return>
502.357 - </FunctionDef> <Return>return <Call><Name>i</Name>()</Call></Return>
502.358 - </FunctionDef> <Return>return <Call><Name>g</Name>()</Call></Return>
502.359 -</FunctionDef><Expr><Call><Name>verify</Name>(<Compare><Call><Name>f</Name>()</Call> == <Num>2</Num></Compare>)</Call></Expr>
502.360 -<Expr><Call><Name>verify</Name>(<Compare><Name>x</Name> == <Num>7</Num></Compare>)</Call></Expr>
502.361 -
502.362 -# III
502.363 -<Assign><Name>x</Name> = <Num>7</Num></Assign>
502.364 -<FunctionDef>def f():
502.365 - <Assign><Name>x</Name> = <Num>1</Num></Assign>
502.366 - <FunctionDef>def g():
502.367 - <Global>global x</Global>
502.368 - <Assign><Name>x</Name> = <Num>2</Num></Assign>
502.369 - <FunctionDef>def i():
502.370 - <FunctionDef>def h():
502.371 - <Return>return <Name>x</Name></Return>
502.372 - </FunctionDef> <Return>return <Call><Name>h</Name>()</Call></Return>
502.373 - </FunctionDef> <Return>return <Call><Name>i</Name>()</Call></Return>
502.374 - </FunctionDef> <Return>return <Call><Name>g</Name>()</Call></Return>
502.375 -</FunctionDef><Expr><Call><Name>verify</Name>(<Compare><Call><Name>f</Name>()</Call> == <Num>2</Num></Compare>)</Call></Expr>
502.376 -<Expr><Call><Name>verify</Name>(<Compare><Name>x</Name> == <Num>2</Num></Compare>)</Call></Expr>
502.377 -
502.378 -# IV
502.379 -<Assign><Name>x</Name> = <Num>7</Num></Assign>
502.380 -<FunctionDef>def f():
502.381 - <Assign><Name>x</Name> = <Num>3</Num></Assign>
502.382 - <FunctionDef>def g():
502.383 - <Global>global x</Global>
502.384 - <Assign><Name>x</Name> = <Num>2</Num></Assign>
502.385 - <FunctionDef>def i():
502.386 - <FunctionDef>def h():
502.387 - <Return>return <Name>x</Name></Return>
502.388 - </FunctionDef> <Return>return <Call><Name>h</Name>()</Call></Return>
502.389 - </FunctionDef> <Return>return <Call><Name>i</Name>()</Call></Return>
502.390 - </FunctionDef> <Return>return <Call><Name>g</Name>()</Call></Return>
502.391 -</FunctionDef><Expr><Call><Name>verify</Name>(<Compare><Call><Name>f</Name>()</Call> == <Num>2</Num></Compare>)</Call></Expr>
502.392 -<Expr><Call><Name>verify</Name>(<Compare><Name>x</Name> == <Num>2</Num></Compare>)</Call></Expr>
502.393 -
502.394 -<Print>print <Str>"16. check leaks"</Str></Print>
502.395 -
502.396 -<ClassDef>class Foo:
502.397 - <Assign><Name>count</Name> = <Num>0</Num></Assign>
502.398 -
502.399 - <FunctionDef>def __init__(<Name>self</Name>):
502.400 - <AugAssign><Attribute><Name>Foo</Name>.count</Attribute> += <Num>1</Num></AugAssign>
502.401 -
502.402 - </FunctionDef> <FunctionDef>def __del__(<Name>self</Name>):
502.403 - <AugAssign><Attribute><Name>Foo</Name>.count</Attribute> -= <Num>1</Num></AugAssign>
502.404 -
502.405 -</FunctionDef></ClassDef><FunctionDef>def f1():
502.406 - <Assign><Name>x</Name> = <Call><Name>Foo</Name>()</Call></Assign>
502.407 - <FunctionDef>def f2():
502.408 - <Return>return <Name>x</Name></Return>
502.409 - </FunctionDef> <Expr><Call><Name>f2</Name>()</Call></Expr>
502.410 -
502.411 -</FunctionDef><For>for <Name>i</Name> in <Call><Name>range</Name>(<Num>100</Num>)</Call>:
502.412 - <Expr><Call><Name>f1</Name>()</Call></Expr>
502.413 -
502.414 -</For><Import>import os</Import>
502.415 -<If>if <Compare><Attribute><Name>os</Name>.name</Attribute> == <Str>'java'</Str></Compare>:
502.416 - <ImportFrom>from java.lang import System, Thread</ImportFrom>
502.417 - <Expr><Call><Attribute><Name>System</Name>.gc</Attribute>()</Call></Expr>
502.418 - <Expr><Call><Attribute><Name>Thread</Name>.sleep</Attribute>(<Num>100</Num>)</Call></Expr>
502.419 - <Expr><Call><Attribute><Name>System</Name>.gc</Attribute>()</Call></Expr>
502.420 -</If><Expr><Call><Name>verify</Name>(<Compare><Attribute><Name>Foo</Name>.count</Attribute> == <Num>0</Num></Compare>)</Call></Expr>
502.421 -
502.422 -<Print>print <Str>"17. class and global"</Str></Print>
502.423 -
502.424 -<FunctionDef>def test(<Name>x</Name>):
502.425 - <ClassDef>class Foo:
502.426 - <Global>global x</Global>
502.427 - <FunctionDef>def __call__(<Name>self</Name>, <Name>y</Name>):
502.428 - <Return>return <BinOp><Name>x</Name> + <Name>y</Name></BinOp></Return>
502.429 - </FunctionDef></ClassDef> <Return>return <Call><Name>Foo</Name>()</Call></Return>
502.430 -
502.431 -</FunctionDef><Assign><Name>x</Name> = <Num>0</Num></Assign>
502.432 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>test</Name><Call>(<Num>6</Num>)</Call>(<Num>2</Num>)</Call> == <Num>8</Num></Compare>)</Call></Expr>
502.433 -<Assign><Name>x</Name> = <Num>-1</Num></Assign>
502.434 -<Expr><Call><Name>verify</Name>(<Compare><Call><Name>test</Name><Call>(<Num>3</Num>)</Call>(<Num>2</Num>)</Call> == <Num>5</Num></Compare>)</Call></Expr>
502.435 -
502.436 -<Print>print <Str>"18. verify that locals() works"</Str></Print>
502.437 -
502.438 -<FunctionDef>def f(<Name>x</Name>):
502.439 - <FunctionDef>def g(<Name>y</Name>):
502.440 - <FunctionDef>def h(<Name>z</Name>):
502.441 - <Return>return <BinOp><Name>y</Name> + <Name>z</Name></BinOp></Return>
502.442 - </FunctionDef> <Assign><Name>w</Name> = <BinOp><Name>x</Name> + <Name>y</Name></BinOp></Assign>
502.443 - <AugAssign><Name>y</Name> += <Num>3</Num></AugAssign>
502.444 - <Return>return <Call><Name>locals</Name>()</Call></Return>
502.445 - </FunctionDef> <Return>return <Name>g</Name></Return>
502.446 -
502.447 -</FunctionDef><Assign><Name>d</Name> = <Call><Name>f</Name><Call>(<Num>2</Num>)</Call>(<Num>4</Num>)</Call></Assign>
502.448 -<Expr><Call><Name>verify</Name>(<Call><Attribute><Name>d</Name>.has_key</Attribute>(<Str>'h'</Str>)</Call>)</Call></Expr>
502.449 -<Delete>del <Subscript><Name>d</Name>[<Index><Str>'h'</Str></Index>]</Subscript></Delete>
502.450 -<Expr><Call><Name>verify</Name>(<Compare><Name>d</Name> == <Dict>{<Str>'x'</Str>: <Num>2</Num>, <Str>'y'</Str>: <Num>7</Num>, <Str>'w'</Str>: <Num>6</Num>}</Dict></Compare>)</Call></Expr>
502.451 -
502.452 -<Print>print <Str>"19. var is bound and free in class"</Str></Print>
502.453 -
502.454 -<FunctionDef>def f(<Name>x</Name>):
502.455 - <ClassDef>class C:
502.456 - <FunctionDef>def m(<Name>self</Name>):
502.457 - <Return>return <Name>x</Name></Return>
502.458 - </FunctionDef> <Assign><Name>a</Name> = <Name>x</Name></Assign>
502.459 - </ClassDef> <Return>return <Name>C</Name></Return>
502.460 -
502.461 -</FunctionDef><Assign><Name>inst</Name> = <Call><Name>f</Name><Call>(<Num>3</Num>)</Call>()</Call></Assign>
502.462 -<Expr><Call><Name>verify</Name>(<Compare><Attribute><Name>inst</Name>.a</Attribute> == <Call><Attribute><Name>inst</Name>.m</Attribute>()</Call></Compare>)</Call></Expr>
502.463 -
502.464 -<Print>print <Str>"20. interaction with trace function"</Str></Print>
502.465 -
502.466 -<Import>import sys</Import>
502.467 -<FunctionDef>def tracer(<Name>a</Name>,<Name>b</Name>,<Name>c</Name>):
502.468 - <Return>return <Name>tracer</Name></Return>
502.469 -
502.470 -</FunctionDef><FunctionDef>def adaptgetter(<Name>name</Name>, <Name>klass</Name>, <Name>getter</Name>):
502.471 - <Assign><Tuple><Name>kind</Name>, <Name>des</Name></Tuple> = <Name>getter</Name></Assign>
502.472 - <If>if <Compare><Name>kind</Name> == <Num>1</Num></Compare>: # AV happens when stepping from this line to next
502.473 - <If>if <Compare><Name>des</Name> == <Str>""</Str></Compare>:
502.474 - <Assign><Name>des</Name> = <BinOp><Str>"_%s__%s"</Str> % <Tuple>(<Attribute><Name>klass</Name>.__name__</Attribute>, <Name>name</Name>)</Tuple></BinOp></Assign>
502.475 - </If> <Return>return <Lambda>lambda <Name>obj</Name>: <Call><Name>getattr</Name>(<Name>obj</Name>, <Name>des</Name>)</Call></Lambda></Return>
502.476 -
502.477 -</If></FunctionDef><ClassDef>class TestClass:
502.478 - <Pass>pass</Pass>
502.479 -
502.480 -</ClassDef><Expr><Call><Attribute><Name>sys</Name>.settrace</Attribute>(<Name>tracer</Name>)</Call></Expr>
502.481 -<Expr><Call><Name>adaptgetter</Name>(<Str>"foo"</Str>, <Name>TestClass</Name>, <Tuple>(<Num>1</Num>, <Str>""</Str>)</Tuple>)</Call></Expr>
502.482 -<Expr><Call><Attribute><Name>sys</Name>.settrace</Attribute>(<Name>None</Name>)</Call></Expr>
502.483 -
502.484 -<TryExcept>try: <Expr><Call><Attribute><Name>sys</Name>.settrace</Attribute>()</Call></Expr>
502.485 -<ExceptHandler>except <Name>TypeError</Name>: <Pass>pass</Pass>
502.486 -</ExceptHandler>else: <Raise>raise <Name>TestFailed</Name>, <Str>'sys.settrace() did not raise TypeError'</Str></Raise>
502.487 -
502.488 -</TryExcept><Print>print <Str>"20. eval and exec with free variables"</Str></Print>
502.489 -
502.490 -<FunctionDef>def f(<Name>x</Name>):
502.491 - <Return>return <Lambda>lambda: <BinOp><Name>x</Name> + <Num>1</Num></BinOp></Lambda></Return>
502.492 -
502.493 -</FunctionDef><Assign><Name>g</Name> = <Call><Name>f</Name>(<Num>3</Num>)</Call></Assign>
502.494 -<TryExcept>try:
502.495 - <Expr><Call><Name>eval</Name>(<Attribute><Name>g</Name>.func_code</Attribute>)</Call></Expr>
502.496 -<ExceptHandler>except <Name>TypeError</Name>:
502.497 - <Pass>pass</Pass>
502.498 -</ExceptHandler>else:
502.499 - <Print>print <Str>"eval() should have failed, because code contained free vars"</Str></Print>
502.500 -
502.501 -</TryExcept><TryExcept>try:
502.502 - <Exec>exec <Attribute><Name>g</Name>.func_code</Attribute></Exec>
502.503 -<ExceptHandler>except <Name>TypeError</Name>:
502.504 - <Pass>pass</Pass>
502.505 -</ExceptHandler>else:
502.506 - <Print>print <Str>"exec should have failed, because code contained free vars"</Str></Print>
502.507 -
502.508 -</TryExcept><Print>print <Str>"21. list comprehension with local variables"</Str></Print>
502.509 -
502.510 -<TryExcept>try:
502.511 - <Print>print <Name>bad</Name></Print>
502.512 -<ExceptHandler>except <Name>NameError</Name>:
502.513 - <Pass>pass</Pass>
502.514 -</ExceptHandler>else:
502.515 - <Print>print <Str>"bad should not be defined"</Str></Print>
502.516 -
502.517 -</TryExcept><FunctionDef>def x():
502.518 - <Expr><ListComp>[<Name>bad</Name> for <Name>s</Name> in <Str>'a b'</Str> for <Name>bad</Name> in <Call><Attribute><Name>s</Name>.split</Attribute>()</Call>]</ListComp></Expr>
502.519 -
502.520 -</FunctionDef><Expr><Call><Name>x</Name>()</Call></Expr>
502.521 -<TryExcept>try:
502.522 - <Print>print <Name>bad</Name></Print>
502.523 -<ExceptHandler>except <Name>NameError</Name>:
502.524 - <Pass>pass</Pass>
502.525 -
502.526 -</ExceptHandler></TryExcept><Print>print <Str>"22. eval with free variables"</Str></Print>
502.527 -
502.528 -<FunctionDef>def f(<Name>x</Name>):
502.529 - <FunctionDef>def g():
502.530 - <Expr><Name>x</Name></Expr>
502.531 - <Expr><Call><Name>eval</Name>(<Str>"x + 1"</Str>)</Call></Expr>
502.532 - </FunctionDef> <Return>return <Name>g</Name></Return>
502.533 -
502.534 -</FunctionDef><Expr><Call><Name>f</Name><Call>(<Num>4</Num>)</Call>()</Call></Expr></Module>
503.1 --- a/python.editor/test/unit/data/testfiles/test_scope.py.semantic Sun Jan 04 13:11:53 2015 -0600
503.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
503.3 @@ -1,530 +0,0 @@
503.4 -from test_support import verify, TestFailed, check_syntax
503.5 -
503.6 -import warnings
503.7 -warnings.filterwarnings("ignore", r"import \*", SyntaxWarning, "<string>")
503.8 -
503.9 -print "1. simple nesting"
503.10 -
503.11 -def |>METHOD:make_adder<|(|>PARAMETER:x<|):
503.12 - def |>METHOD:adder<|(|>PARAMETER:y<|):
503.13 - return x + |>PARAMETER:y<|
503.14 - return adder
503.15 -
503.16 -inc = make_adder(1)
503.17 -plus10 = make_adder(10)
503.18 -
503.19 -verify(inc(1) == 2)
503.20 -verify(plus10(-2) == 8)
503.21 -
503.22 -print "2. extra nesting"
503.23 -
503.24 -def |>METHOD:make_adder2<|(|>PARAMETER:x<|):
503.25 - def |>METHOD:extra<|(): # check freevars passing through non-use scopes
503.26 - def |>METHOD:adder<|(|>PARAMETER:y<|):
503.27 - return x + |>PARAMETER:y<|
503.28 - return adder
503.29 - return extra()
503.30 -
503.31 -inc = make_adder2(1)
503.32 -plus10 = make_adder2(10)
503.33 -
503.34 -verify(inc(1) == 2)
503.35 -verify(plus10(-2) == 8)
503.36 -
503.37 -print "3. simple nesting + rebinding"
503.38 -
503.39 -def |>METHOD:make_adder3<|(|>PARAMETER:x<|):
503.40 - def |>METHOD:adder<|(|>PARAMETER:y<|):
503.41 - return x + |>PARAMETER:y<|
503.42 - |>PARAMETER:x<| = |>PARAMETER:x<| + 1 # check tracking of assignment to x in defining scope
503.43 - return adder
503.44 -
503.45 -inc = make_adder3(0)
503.46 -plus10 = make_adder3(9)
503.47 -
503.48 -verify(inc(1) == 2)
503.49 -verify(plus10(-2) == 8)
503.50 -
503.51 -print "4. nesting with global but no free"
503.52 -
503.53 -def |>METHOD:make_adder4<|(): # XXX add exta level of indirection
503.54 - def |>METHOD:nest<|():
503.55 - def |>METHOD:nest<|():
503.56 - def |>METHOD:adder<|(|>PARAMETER:y<|):
503.57 - return global_x + |>PARAMETER:y<| # check that plain old globals work
503.58 - return adder
503.59 - return nest()
503.60 - return nest()
503.61 -
503.62 -global_x = 1
503.63 -adder = make_adder4()
503.64 -verify(adder(1) == 2)
503.65 -
503.66 -global_x = 10
503.67 -verify(adder(-2) == 8)
503.68 -
503.69 -print "5. nesting through class"
503.70 -
503.71 -def |>METHOD:make_adder5<|(|>PARAMETER:x<|):
503.72 - class Adder:
503.73 - def |>METHOD:__call__<|(|>PARAMETER,UNUSED:self<|, |>PARAMETER:y<|):
503.74 - return x + |>PARAMETER:y<|
503.75 - return Adder()
503.76 -
503.77 -inc = make_adder5(1)
503.78 -plus10 = make_adder5(10)
503.79 -
503.80 -verify(inc(1) == 2)
503.81 -verify(plus10(-2) == 8)
503.82 -
503.83 -print "6. nesting plus free ref to global"
503.84 -
503.85 -def |>METHOD:make_adder6<|(|>PARAMETER:x<|):
503.86 - global global_nest_x
503.87 - def |>METHOD:adder<|(|>PARAMETER:y<|):
503.88 - return global_nest_x + |>PARAMETER:y<|
503.89 - global_nest_x = |>PARAMETER:x<|
503.90 - return adder
503.91 -
503.92 -inc = make_adder6(1)
503.93 -plus10 = make_adder6(10)
503.94 -
503.95 -verify(inc(1) == 11) # there's only one global
503.96 -verify(plus10(-2) == 8)
503.97 -
503.98 -print "7. nearest enclosing scope"
503.99 -
503.100 -def |>METHOD:f<|(|>PARAMETER,UNUSED:x<|):
503.101 - def |>METHOD:g<|(|>PARAMETER,UNUSED:y<|):
503.102 - x = 42 # check that this masks binding in f()
503.103 - def |>METHOD:h<|(|>PARAMETER:z<|):
503.104 - return x + |>PARAMETER:z<|
503.105 - return h
503.106 - return g(2)
503.107 -
503.108 -test_func = f(10)
503.109 -verify(test_func(5) == 47)
503.110 -
503.111 -print "8. mixed freevars and cellvars"
503.112 -
503.113 -def |>METHOD:identity<|(|>PARAMETER:x<|):
503.114 - return |>PARAMETER:x<|
503.115 -
503.116 -def |>METHOD:f<|(|>PARAMETER:x<|, |>PARAMETER,UNUSED:y<|, |>PARAMETER:z<|):
503.117 - def |>METHOD:g<|(|>PARAMETER:a<|, |>PARAMETER:b<|, |>PARAMETER:c<|):
503.118 - |>PARAMETER:a<| = |>PARAMETER:a<| + x # 3
503.119 - def |>METHOD:h<|():
503.120 - # z * (4 + 9)
503.121 - # 3 * 13
503.122 - return identity(z * (b + y))
503.123 - |>UNUSED:y<| = |>PARAMETER:c<| + z # 9
503.124 - return h
503.125 - return g
503.126 -
503.127 -g = f(1, 2, 3)
503.128 -h = g(2, 4, 6)
503.129 -verify(h() == 39)
503.130 -
503.131 -print "9. free variable in method"
503.132 -
503.133 -def |>METHOD:test<|():
503.134 - method_and_var = "var"
503.135 - class Test:
503.136 - def |>METHOD:method_and_var<|(|>PARAMETER,UNUSED:self<|):
503.137 - return "method"
503.138 - def |>METHOD:test<|(|>PARAMETER,UNUSED:self<|):
503.139 - return method_and_var
503.140 - def |>METHOD:actual_global<|(|>PARAMETER,UNUSED:self<|):
503.141 - return str("global")
503.142 - def |>METHOD:str<|(|>PARAMETER:self<|):
503.143 - return str(|>PARAMETER:self<|)
503.144 - return Test()
503.145 -
503.146 -t = test()
503.147 -verify(t.test() == "var")
503.148 -verify(t.method_and_var() == "method")
503.149 -verify(t.actual_global() == "global")
503.150 -
503.151 -method_and_var = "var"
503.152 -class Test:
503.153 - # this class is not nested, so the rules are different
503.154 - def |>METHOD:method_and_var<|(|>PARAMETER,UNUSED:self<|):
503.155 - return "method"
503.156 - def |>METHOD:test<|(|>PARAMETER,UNUSED:self<|):
503.157 - return method_and_var
503.158 - def |>METHOD:actual_global<|(|>PARAMETER,UNUSED:self<|):
503.159 - return str("global")
503.160 - def |>METHOD:str<|(|>PARAMETER:self<|):
503.161 - return str(|>PARAMETER:self<|)
503.162 -
503.163 -t = Test()
503.164 -verify(t.test() == "var")
503.165 -verify(t.method_and_var() == "method")
503.166 -verify(t.actual_global() == "global")
503.167 -
503.168 -print "10. recursion"
503.169 -
503.170 -def |>METHOD:f<|(|>PARAMETER:x<|):
503.171 - def |>METHOD:fact<|(|>PARAMETER:n<|):
503.172 - if |>PARAMETER:n<| == 0:
503.173 - return 1
503.174 - else:
503.175 - return |>PARAMETER:n<| * fact(|>PARAMETER:n<| - 1)
503.176 - if |>PARAMETER:x<| >= 0:
503.177 - return fact(|>PARAMETER:x<|)
503.178 - else:
503.179 - raise ValueError, "x must be >= 0"
503.180 -
503.181 -verify(f(6) == 720)
503.182 -
503.183 -
503.184 -print "11. unoptimized namespaces"
503.185 -
503.186 -check_syntax("""\
503.187 -def unoptimized_clash1(strip):
503.188 - def f(s):
503.189 - from string import *
503.190 - return strip(s) # ambiguity: free or local
503.191 - return f
503.192 -""")
503.193 -
503.194 -check_syntax("""\
503.195 -def unoptimized_clash2():
503.196 - from string import *
503.197 - def f(s):
503.198 - return strip(s) # ambiguity: global or local
503.199 - return f
503.200 -""")
503.201 -
503.202 -check_syntax("""\
503.203 -def unoptimized_clash2():
503.204 - from string import *
503.205 - def g():
503.206 - def f(s):
503.207 - return strip(s) # ambiguity: global or local
503.208 - return f
503.209 -""")
503.210 -
503.211 -# XXX could allow this for exec with const argument, but what's the point
503.212 -check_syntax("""\
503.213 -def error(y):
503.214 - exec "a = 1"
503.215 - def f(x):
503.216 - return x + y
503.217 - return f
503.218 -""")
503.219 -
503.220 -check_syntax("""\
503.221 -def f(x):
503.222 - def g():
503.223 - return x
503.224 - del x # can't del name
503.225 -""")
503.226 -
503.227 -check_syntax("""\
503.228 -def f():
503.229 - def g():
503.230 - from string import *
503.231 - return strip # global or local?
503.232 -""")
503.233 -
503.234 -# and verify a few cases that should work
503.235 -
503.236 -exec """
503.237 -def noproblem1():
503.238 - from string import *
503.239 - f = lambda x:x
503.240 -
503.241 -def noproblem2():
503.242 - from string import *
503.243 - def f(x):
503.244 - return x + 1
503.245 -
503.246 -def noproblem3():
503.247 - from string import *
503.248 - def f(x):
503.249 - global y
503.250 - y = x
503.251 -"""
503.252 -
503.253 -print "12. lambdas"
503.254 -
503.255 -f1 = lambda x: lambda y: x + y
503.256 -inc = f1(1)
503.257 -plus10 = f1(10)
503.258 -verify(inc(1) == 2)
503.259 -verify(plus10(5) == 15)
503.260 -
503.261 -f2 = lambda x: (lambda : lambda y: x + y)()
503.262 -inc = f2(1)
503.263 -plus10 = f2(10)
503.264 -verify(inc(1) == 2)
503.265 -verify(plus10(5) == 15)
503.266 -
503.267 -f3 = lambda x: lambda y: global_x + y
503.268 -global_x = 1
503.269 -inc = f3(None)
503.270 -verify(inc(2) == 3)
503.271 -
503.272 -f8 = lambda x, y, z: lambda a, b, c: lambda : z * (b + y)
503.273 -g = f8(1, 2, 3)
503.274 -h = g(2, 4, 6)
503.275 -verify(h() == 18)
503.276 -
503.277 -print "13. UnboundLocal"
503.278 -
503.279 -def |>METHOD:errorInOuter<|():
503.280 - print y
503.281 - def |>METHOD:inner<|():
503.282 - return y
503.283 - y = 1
503.284 -
503.285 -def |>METHOD:errorInInner<|():
503.286 - def |>METHOD:inner<|():
503.287 - return y
503.288 - inner()
503.289 - |>UNUSED:y<| = 1
503.290 -
503.291 -try:
503.292 - errorInOuter()
503.293 -except UnboundLocalError:
503.294 - pass
503.295 -else:
503.296 - raise TestFailed
503.297 -
503.298 -try:
503.299 - errorInInner()
503.300 -except NameError:
503.301 - pass
503.302 -else:
503.303 - raise TestFailed
503.304 -
503.305 -print "14. complex definitions"
503.306 -
503.307 -def |>METHOD:makeReturner<|(*lst):
503.308 - def |>METHOD:returner<|():
503.309 - return lst
503.310 - return returner
503.311 -
503.312 -verify(makeReturner(1,2,3)() == (1,2,3))
503.313 -
503.314 -def |>METHOD:makeReturner2<|(**kwargs):
503.315 - def |>METHOD:returner<|():
503.316 - return kwargs
503.317 - return returner
503.318 -
503.319 -verify(makeReturner2(a=11)()['a'] == 11)
503.320 -
503.321 -def |>METHOD:makeAddPair<|((|>PARAMETER:a<|, |>PARAMETER:b<|)):
503.322 - def |>METHOD:addPair<|((|>PARAMETER:c<|, |>PARAMETER:d<|)):
503.323 - return (a + |>PARAMETER:c<|, b + |>PARAMETER:d<|)
503.324 - return addPair
503.325 -
503.326 -verify(makeAddPair((1, 2))((100, 200)) == (101,202))
503.327 -
503.328 -print "15. scope of global statements"
503.329 -# Examples posted by Samuele Pedroni to python-dev on 3/1/2001
503.330 -
503.331 -# I
503.332 -x = 7
503.333 -def |>METHOD:f<|():
503.334 - |>UNUSED:x<| = 1
503.335 - def |>METHOD:g<|():
503.336 - global x
503.337 - def |>METHOD:i<|():
503.338 - def |>METHOD:h<|():
503.339 - return x
503.340 - return h()
503.341 - return i()
503.342 - return g()
503.343 -verify(f() == 7)
503.344 -verify(x == 7)
503.345 -
503.346 -# II
503.347 -x = 7
503.348 -def |>METHOD:f<|():
503.349 - |>UNUSED:x<| = 1
503.350 - def |>METHOD:g<|():
503.351 - x = 2
503.352 - def |>METHOD:i<|():
503.353 - def |>METHOD:h<|():
503.354 - return x
503.355 - return h()
503.356 - return i()
503.357 - return g()
503.358 -verify(f() == 2)
503.359 -verify(x == 7)
503.360 -
503.361 -# III
503.362 -x = 7
503.363 -def |>METHOD:f<|():
503.364 - |>UNUSED:x<| = 1
503.365 - def |>METHOD:g<|():
503.366 - global x
503.367 - x = 2
503.368 - def |>METHOD:i<|():
503.369 - def |>METHOD:h<|():
503.370 - return x
503.371 - return h()
503.372 - return i()
503.373 - return g()
503.374 -verify(f() == 2)
503.375 -verify(x == 2)
503.376 -
503.377 -# IV
503.378 -x = 7
503.379 -def |>METHOD:f<|():
503.380 - |>UNUSED:x<| = 3
503.381 - def |>METHOD:g<|():
503.382 - global x
503.383 - x = 2
503.384 - def |>METHOD:i<|():
503.385 - def |>METHOD:h<|():
503.386 - return x
503.387 - return h()
503.388 - return i()
503.389 - return g()
503.390 -verify(f() == 2)
503.391 -verify(x == 2)
503.392 -
503.393 -print "16. check leaks"
503.394 -
503.395 -class Foo:
503.396 - count = 0
503.397 -
503.398 - def |>METHOD:__init__<|(|>PARAMETER,UNUSED:self<|):
503.399 - Foo.count += 1
503.400 -
503.401 - def |>METHOD:__del__<|(|>PARAMETER,UNUSED:self<|):
503.402 - Foo.count -= 1
503.403 -
503.404 -def |>METHOD:f1<|():
503.405 - x = Foo()
503.406 - def |>METHOD:f2<|():
503.407 - return x
503.408 - f2()
503.409 -
503.410 -for i in range(100):
503.411 - f1()
503.412 -
503.413 -import os
503.414 -if os.name == 'java':
503.415 - from java.lang import System, Thread
503.416 - System.gc()
503.417 - Thread.sleep(100)
503.418 - System.gc()
503.419 -verify(Foo.count == 0)
503.420 -
503.421 -print "17. class and global"
503.422 -
503.423 -def |>METHOD:test<|(|>PARAMETER:x<|):
503.424 - class Foo:
503.425 - global x
503.426 - def |>METHOD:__call__<|(|>PARAMETER,UNUSED:self<|, |>PARAMETER:y<|):
503.427 - return x + |>PARAMETER:y<|
503.428 - return Foo()
503.429 -
503.430 -x = 0
503.431 -verify(test(6)(2) == 8)
503.432 -x = -1
503.433 -verify(test(3)(2) == 5)
503.434 -
503.435 -print "18. verify that locals() works"
503.436 -
503.437 -def |>METHOD:f<|(|>PARAMETER:x<|):
503.438 - def |>METHOD:g<|(|>PARAMETER:y<|):
503.439 - def |>METHOD:h<|(|>PARAMETER:z<|):
503.440 - return y + |>PARAMETER:z<|
503.441 - |>UNUSED:w<| = x + |>PARAMETER:y<|
503.442 - |>PARAMETER:y<| += 3
503.443 - return locals()
503.444 - return g
503.445 -
503.446 -d = f(2)(4)
503.447 -verify(d.has_key('h'))
503.448 -del d['h']
503.449 -verify(d == {'x': 2, 'y': 7, 'w': 6})
503.450 -
503.451 -print "19. var is bound and free in class"
503.452 -
503.453 -def |>METHOD:f<|(|>PARAMETER:x<|):
503.454 - class C:
503.455 - def |>METHOD:m<|(|>PARAMETER,UNUSED:self<|):
503.456 - return x
503.457 - a = x
503.458 - return C
503.459 -
503.460 -inst = f(3)()
503.461 -verify(inst.a == inst.m())
503.462 -
503.463 -print "20. interaction with trace function"
503.464 -
503.465 -import sys
503.466 -def |>METHOD:tracer<|(|>PARAMETER,UNUSED:a<|,|>PARAMETER,UNUSED:b<|,|>PARAMETER,UNUSED:c<|):
503.467 - return tracer
503.468 -
503.469 -def |>METHOD:adaptgetter<|(|>PARAMETER:name<|, |>PARAMETER:klass<|, |>PARAMETER:getter<|):
503.470 - kind, des = |>PARAMETER:getter<|
503.471 - if kind == 1: # AV happens when stepping from this line to next
503.472 - if des == "":
503.473 - des = "_%s__%s" % (|>PARAMETER:klass<|.__name__, |>PARAMETER:name<|)
503.474 - return lambda obj: getattr(obj, des)
503.475 -
503.476 -class TestClass:
503.477 - pass
503.478 -
503.479 -sys.settrace(tracer)
503.480 -adaptgetter("foo", TestClass, (1, ""))
503.481 -sys.settrace(None)
503.482 -
503.483 -try: sys.settrace()
503.484 -except TypeError: pass
503.485 -else: raise TestFailed, 'sys.settrace() did not raise TypeError'
503.486 -
503.487 -print "20. eval and exec with free variables"
503.488 -
503.489 -def |>METHOD:f<|(|>PARAMETER:x<|):
503.490 - return lambda: |>PARAMETER:x<| + 1
503.491 -
503.492 -g = f(3)
503.493 -try:
503.494 - eval(g.func_code)
503.495 -except TypeError:
503.496 - pass
503.497 -else:
503.498 - print "eval() should have failed, because code contained free vars"
503.499 -
503.500 -try:
503.501 - exec g.func_code
503.502 -except TypeError:
503.503 - pass
503.504 -else:
503.505 - print "exec should have failed, because code contained free vars"
503.506 -
503.507 -print "21. list comprehension with local variables"
503.508 -
503.509 -try:
503.510 - print bad
503.511 -except NameError:
503.512 - pass
503.513 -else:
503.514 - print "bad should not be defined"
503.515 -
503.516 -def |>METHOD:x<|():
503.517 - [bad for s in 'a b' for bad in s.split()]
503.518 -
503.519 -x()
503.520 -try:
503.521 - print bad
503.522 -except NameError:
503.523 - pass
503.524 -
503.525 -print "22. eval with free variables"
503.526 -
503.527 -def |>METHOD:f<|(|>PARAMETER:x<|):
503.528 - def |>METHOD:g<|():
503.529 - x
503.530 - eval("x + 1")
503.531 - return g
503.532 -
503.533 -f(4)()
504.1 --- a/python.editor/test/unit/data/testfiles/test_scope.py.structure Sun Jan 04 13:11:53 2015 -0600
504.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
504.3 @@ -1,83 +0,0 @@
504.4 -make_adder:METHOD:[]:ESCAPED{make_adder}(PARAMETERS{ESCAPED{x}}):
504.5 - adder:METHOD:[]:ESCAPED{adder}(PARAMETERS{ESCAPED{y}}):
504.6 -make_adder2:METHOD:[]:ESCAPED{make_adder2}(PARAMETERS{ESCAPED{x}}):
504.7 - extra:METHOD:[]:ESCAPED{extra}:
504.8 - adder:METHOD:[]:ESCAPED{adder}(PARAMETERS{ESCAPED{y}}):
504.9 -make_adder3:METHOD:[]:ESCAPED{make_adder3}(PARAMETERS{ESCAPED{x}}):
504.10 - adder:METHOD:[]:ESCAPED{adder}(PARAMETERS{ESCAPED{y}}):
504.11 -make_adder4:METHOD:[]:ESCAPED{make_adder4}:
504.12 - nest:METHOD:[]:ESCAPED{nest}:
504.13 - nest:METHOD:[]:ESCAPED{nest}:
504.14 - adder:METHOD:[]:ESCAPED{adder}(PARAMETERS{ESCAPED{y}}):
504.15 -make_adder5:METHOD:[]:ESCAPED{make_adder5}(PARAMETERS{ESCAPED{x}}):
504.16 - Adder:CLASS:[]:ESCAPED{Adder}:
504.17 - __call__:METHOD:[]:ESCAPED{__call__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{y}}):
504.18 -make_adder6:METHOD:[]:ESCAPED{make_adder6}(PARAMETERS{ESCAPED{x}}):
504.19 - adder:METHOD:[]:ESCAPED{adder}(PARAMETERS{ESCAPED{y}}):
504.20 -f:METHOD:[]:ESCAPED{f}(PARAMETERS{ESCAPED{x}}):
504.21 - g:METHOD:[]:ESCAPED{g}(PARAMETERS{ESCAPED{y}}):
504.22 - h:METHOD:[]:ESCAPED{h}(PARAMETERS{ESCAPED{z}}):
504.23 -identity:METHOD:[]:ESCAPED{identity}(PARAMETERS{ESCAPED{x}}):
504.24 -f:METHOD:[]:ESCAPED{f}(PARAMETERS{ESCAPED{x}ESCAPED{,}ESCAPED{y}ESCAPED{,}ESCAPED{z}}):
504.25 - g:METHOD:[]:ESCAPED{g}(PARAMETERS{ESCAPED{a}ESCAPED{,}ESCAPED{b}ESCAPED{,}ESCAPED{c}}):
504.26 - h:METHOD:[]:ESCAPED{h}:
504.27 -test:METHOD:[]:ESCAPED{test}:
504.28 - Test:CLASS:[]:ESCAPED{Test}:
504.29 - actual_global:METHOD:[]:ESCAPED{actual_global}(PARAMETERS{ESCAPED{self}}):
504.30 - method_and_var:METHOD:[]:ESCAPED{method_and_var}(PARAMETERS{ESCAPED{self}}):
504.31 - str:METHOD:[]:ESCAPED{str}(PARAMETERS{ESCAPED{self}}):
504.32 - test:METHOD:[]:ESCAPED{test}(PARAMETERS{ESCAPED{self}}):
504.33 -Test:CLASS:[]:ESCAPED{Test}:
504.34 - actual_global:METHOD:[]:ESCAPED{actual_global}(PARAMETERS{ESCAPED{self}}):
504.35 - method_and_var:METHOD:[]:ESCAPED{method_and_var}(PARAMETERS{ESCAPED{self}}):
504.36 - str:METHOD:[]:ESCAPED{str}(PARAMETERS{ESCAPED{self}}):
504.37 - test:METHOD:[]:ESCAPED{test}(PARAMETERS{ESCAPED{self}}):
504.38 -f:METHOD:[]:ESCAPED{f}(PARAMETERS{ESCAPED{x}}):
504.39 - fact:METHOD:[]:ESCAPED{fact}(PARAMETERS{ESCAPED{n}}):
504.40 -errorInOuter:METHOD:[]:ESCAPED{errorInOuter}:
504.41 - inner:METHOD:[]:ESCAPED{inner}:
504.42 -errorInInner:METHOD:[]:ESCAPED{errorInInner}:
504.43 - inner:METHOD:[]:ESCAPED{inner}:
504.44 -makeReturner:METHOD:[]:ESCAPED{makeReturner}(PARAMETERS{ESCAPED{lst}}):
504.45 - returner:METHOD:[]:ESCAPED{returner}:
504.46 -makeReturner2:METHOD:[]:ESCAPED{makeReturner2}(PARAMETERS{ESCAPED{kwargs}}):
504.47 - returner:METHOD:[]:ESCAPED{returner}:
504.48 -makeAddPair:METHOD:[]:ESCAPED{makeAddPair}:
504.49 - addPair:METHOD:[]:ESCAPED{addPair}:
504.50 -f:METHOD:[]:ESCAPED{f}:
504.51 - g:METHOD:[]:ESCAPED{g}:
504.52 - i:METHOD:[]:ESCAPED{i}:
504.53 - h:METHOD:[]:ESCAPED{h}:
504.54 -f:METHOD:[]:ESCAPED{f}:
504.55 - g:METHOD:[]:ESCAPED{g}:
504.56 - i:METHOD:[]:ESCAPED{i}:
504.57 - h:METHOD:[]:ESCAPED{h}:
504.58 -f:METHOD:[]:ESCAPED{f}:
504.59 - g:METHOD:[]:ESCAPED{g}:
504.60 - i:METHOD:[]:ESCAPED{i}:
504.61 - h:METHOD:[]:ESCAPED{h}:
504.62 -f:METHOD:[]:ESCAPED{f}:
504.63 - g:METHOD:[]:ESCAPED{g}:
504.64 - i:METHOD:[]:ESCAPED{i}:
504.65 - h:METHOD:[]:ESCAPED{h}:
504.66 -Foo:CLASS:[]:ESCAPED{Foo}:
504.67 - __del__:METHOD:[]:ESCAPED{__del__}(PARAMETERS{ESCAPED{self}}):
504.68 - __init__:CONSTRUCTOR:[]:ESCAPED{__init__}(PARAMETERS{ESCAPED{self}}):
504.69 -f1:METHOD:[]:ESCAPED{f1}:
504.70 - f2:METHOD:[]:ESCAPED{f2}:
504.71 -test:METHOD:[]:ESCAPED{test}(PARAMETERS{ESCAPED{x}}):
504.72 - Foo:CLASS:[]:ESCAPED{Foo}:
504.73 - __call__:METHOD:[]:ESCAPED{__call__}(PARAMETERS{ESCAPED{self}ESCAPED{,}ESCAPED{y}}):
504.74 -f:METHOD:[]:ESCAPED{f}(PARAMETERS{ESCAPED{x}}):
504.75 - g:METHOD:[]:ESCAPED{g}(PARAMETERS{ESCAPED{y}}):
504.76 - h:METHOD:[]:ESCAPED{h}(PARAMETERS{ESCAPED{z}}):
504.77 -f:METHOD:[]:ESCAPED{f}(PARAMETERS{ESCAPED{x}}):
504.78 - C:CLASS:[]:ESCAPED{C}:
504.79 - m:METHOD:[]:ESCAPED{m}(PARAMETERS{ESCAPED{self}}):
504.80 -tracer:METHOD:[]:ESCAPED{tracer}(PARAMETERS{ESCAPED{a}ESCAPED{,}ESCAPED{b}ESCAPED{,}ESCAPED{c}}):
504.81 -adaptgetter:METHOD:[]:ESCAPED{adaptgetter}(PARAMETERS{ESCAPED{name}ESCAPED{,}ESCAPED{klass}ESCAPED{,}ESCAPED{getter}}):
504.82 -TestClass:CLASS:[]:ESCAPED{TestClass}:
504.83 -f:METHOD:[]:ESCAPED{f}(PARAMETERS{ESCAPED{x}}):
504.84 -x:METHOD:[]:ESCAPED{x}:
504.85 -f:METHOD:[]:ESCAPED{f}(PARAMETERS{ESCAPED{x}}):
504.86 - g:METHOD:[]:ESCAPED{g}:
505.1 --- a/python.editor/test/unit/data/testfiles/test_scope.py.testHint6.hints Sun Jan 04 13:11:53 2015 -0600
505.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
505.3 @@ -1,36 +0,0 @@
505.4 -def errorInOuter():
505.5 - ------------
505.6 -HINT:Name "errorInOuter" is not a valid function name according to your code style (lowercase_with_underscores)
505.7 -FIX:Ignore name violations for "errorInOuter"
505.8 -FIX:Change preferred function name style to mixedCase
505.9 -FIX:Turn off function name style checks
505.10 -def errorInInner():
505.11 - ------------
505.12 -HINT:Name "errorInInner" is not a valid function name according to your code style (lowercase_with_underscores)
505.13 -FIX:Ignore name violations for "errorInInner"
505.14 -FIX:Change preferred function name style to mixedCase
505.15 -FIX:Turn off function name style checks
505.16 -def makeReturner(*lst):
505.17 - ------------
505.18 -HINT:Name "makeReturner" is not a valid function name according to your code style (lowercase_with_underscores)
505.19 -FIX:Ignore name violations for "makeReturner"
505.20 -FIX:Change preferred function name style to mixedCase
505.21 -FIX:Turn off function name style checks
505.22 -def makeReturner2(**kwargs):
505.23 - -------------
505.24 -HINT:Name "makeReturner2" is not a valid function name according to your code style (lowercase_with_underscores)
505.25 -FIX:Ignore name violations for "makeReturner2"
505.26 -FIX:Change preferred function name style to mixedCase
505.27 -FIX:Turn off function name style checks
505.28 -def makeAddPair((a, b)):
505.29 - -----------
505.30 -HINT:Name "makeAddPair" is not a valid function name according to your code style (lowercase_with_underscores)
505.31 -FIX:Ignore name violations for "makeAddPair"
505.32 -FIX:Change preferred function name style to mixedCase
505.33 -FIX:Turn off function name style checks
505.34 - def addPair((c, d)):
505.35 - -------
505.36 -HINT:Name "addPair" is not a valid function name according to your code style (lowercase_with_underscores)
505.37 -FIX:Ignore name violations for "addPair"
505.38 -FIX:Change preferred function name style to mixedCase
505.39 -FIX:Turn off function name style checks
506.1 --- a/python.editor/test/unit/data/testfiles/test_scope.py.testNoStringCompletion.completion Sun Jan 04 13:11:53 2015 -0600
506.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
506.3 @@ -1,3 +0,0 @@
506.4 -Code completion result for source line:
506.5 -warnings.filterwarnings("ignore", r"i|mport \*", SyntaxWarning, "<string>")
506.6 -(QueryType=COMPLETION, NameKind=PREFIX)
507.1 --- a/python.editor/test/unit/data/testfiles/tokenize.py Sun Jan 04 13:11:53 2015 -0600
507.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
507.3 @@ -1,345 +0,0 @@
507.4 -"""Tokenization help for Python programs.
507.5 -
507.6 -generate_tokens(readline) is a generator that breaks a stream of
507.7 -text into Python tokens. It accepts a readline-like method which is called
507.8 -repeatedly to get the next line of input (or "" for EOF). It generates
507.9 -5-tuples with these members:
507.10 -
507.11 - the token type (see token.py)
507.12 - the token (a string)
507.13 - the starting (row, column) indices of the token (a 2-tuple of ints)
507.14 - the ending (row, column) indices of the token (a 2-tuple of ints)
507.15 - the original line (string)
507.16 -
507.17 -It is designed to match the working of the Python tokenizer exactly, except
507.18 -that it produces COMMENT tokens for comments and gives type OP for all
507.19 -operators
507.20 -
507.21 -Older entry points
507.22 - tokenize_loop(readline, tokeneater)
507.23 - tokenize(readline, tokeneater=printtoken)
507.24 -are the same, except instead of generating tokens, tokeneater is a callback
507.25 -function to which the 5 fields described above are passed as 5 arguments,
507.26 -each time a new token is found."""
507.27 -
507.28 -__author__ = 'Ka-Ping Yee <ping@lfw.org>'
507.29 -__credits__ = \
507.30 - 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro'
507.31 -
507.32 -import string, re
507.33 -from token import *
507.34 -
507.35 -import token
507.36 -__all__ = [x for x in dir(token) if x[0] != '_'] + ["COMMENT", "tokenize",
507.37 - "generate_tokens", "NL", "untokenize"]
507.38 -del x
507.39 -del token
507.40 -
507.41 -COMMENT = N_TOKENS
507.42 -tok_name[COMMENT] = 'COMMENT'
507.43 -NL = N_TOKENS + 1
507.44 -tok_name[NL] = 'NL'
507.45 -N_TOKENS += 2
507.46 -
507.47 -def group(*choices): return '(' + '|'.join(choices) + ')'
507.48 -def any(*choices): return group(*choices) + '*'
507.49 -def maybe(*choices): return group(*choices) + '?'
507.50 -
507.51 -Whitespace = r'[ \f\t]*'
507.52 -Comment = r'#[^\r\n]*'
507.53 -Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
507.54 -Name = r'[a-zA-Z_]\w*'
507.55 -
507.56 -Hexnumber = r'0[xX][\da-fA-F]*[lL]?'
507.57 -Octnumber = r'0[0-7]*[lL]?'
507.58 -Decnumber = r'[1-9]\d*[lL]?'
507.59 -Intnumber = group(Hexnumber, Octnumber, Decnumber)
507.60 -Exponent = r'[eE][-+]?\d+'
507.61 -Pointfloat = group(r'\d+\.\d*', r'\.\d+') + maybe(Exponent)
507.62 -Expfloat = r'\d+' + Exponent
507.63 -Floatnumber = group(Pointfloat, Expfloat)
507.64 -Imagnumber = group(r'\d+[jJ]', Floatnumber + r'[jJ]')
507.65 -Number = group(Imagnumber, Floatnumber, Intnumber)
507.66 -
507.67 -# Tail end of ' string.
507.68 -Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
507.69 -# Tail end of " string.
507.70 -Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
507.71 -# Tail end of ''' string.
507.72 -Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
507.73 -# Tail end of """ string.
507.74 -Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
507.75 -Triple = group("[uU]?[rR]?'''", '[uU]?[rR]?"""')
507.76 -# Single-line ' or " string.
507.77 -String = group(r"[uU]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
507.78 - r'[uU]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
507.79 -
507.80 -# Because of leftmost-then-longest match semantics, be sure to put the
507.81 -# longest operators first (e.g., if = came before ==, == would get
507.82 -# recognized as two instances of =).
507.83 -Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=",
507.84 - r"//=?",
507.85 - r"[+\-*/%&|^=<>]=?",
507.86 - r"~")
507.87 -
507.88 -Bracket = '[][(){}]'
507.89 -Special = group(r'\r?\n', r'[:;.,`@]')
507.90 -Funny = group(Operator, Bracket, Special)
507.91 -
507.92 -PlainToken = group(Number, Funny, String, Name)
507.93 -Token = Ignore + PlainToken
507.94 -
507.95 -# First (or only) line of ' or " string.
507.96 -ContStr = group(r"[uU]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*" +
507.97 - group("'", r'\\\r?\n'),
507.98 - r'[uU]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*' +
507.99 - group('"', r'\\\r?\n'))
507.100 -PseudoExtras = group(r'\\\r?\n', Comment, Triple)
507.101 -PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
507.102 -
507.103 -tokenprog, pseudoprog, single3prog, double3prog = map(
507.104 - re.compile, (Token, PseudoToken, Single3, Double3))
507.105 -endprogs = {"'": re.compile(Single), '"': re.compile(Double),
507.106 - "'''": single3prog, '"""': double3prog,
507.107 - "r'''": single3prog, 'r"""': double3prog,
507.108 - "u'''": single3prog, 'u"""': double3prog,
507.109 - "ur'''": single3prog, 'ur"""': double3prog,
507.110 - "R'''": single3prog, 'R"""': double3prog,
507.111 - "U'''": single3prog, 'U"""': double3prog,
507.112 - "uR'''": single3prog, 'uR"""': double3prog,
507.113 - "Ur'''": single3prog, 'Ur"""': double3prog,
507.114 - "UR'''": single3prog, 'UR"""': double3prog,
507.115 - 'r': None, 'R': None, 'u': None, 'U': None}
507.116 -
507.117 -triple_quoted = {}
507.118 -for t in ("'''", '"""',
507.119 - "r'''", 'r"""', "R'''", 'R"""',
507.120 - "u'''", 'u"""', "U'''", 'U"""',
507.121 - "ur'''", 'ur"""', "Ur'''", 'Ur"""',
507.122 - "uR'''", 'uR"""', "UR'''", 'UR"""'):
507.123 - triple_quoted[t] = t
507.124 -single_quoted = {}
507.125 -for t in ("'", '"',
507.126 - "r'", 'r"', "R'", 'R"',
507.127 - "u'", 'u"', "U'", 'U"',
507.128 - "ur'", 'ur"', "Ur'", 'Ur"',
507.129 - "uR'", 'uR"', "UR'", 'UR"' ):
507.130 - single_quoted[t] = t
507.131 -
507.132 -tabsize = 8
507.133 -
507.134 -class TokenError(Exception): pass
507.135 -
507.136 -class StopTokenizing(Exception): pass
507.137 -
507.138 -def printtoken(type, token, (srow, scol), (erow, ecol), line): # for testing
507.139 - print "%d,%d-%d,%d:\t%s\t%s" % \
507.140 - (srow, scol, erow, ecol, tok_name[type], repr(token))
507.141 -
507.142 -def tokenize(readline, tokeneater=printtoken):
507.143 - """
507.144 - The tokenize() function accepts two parameters: one representing the
507.145 - input stream, and one providing an output mechanism for tokenize().
507.146 -
507.147 - The first parameter, readline, must be a callable object which provides
507.148 - the same interface as the readline() method of built-in file objects.
507.149 - Each call to the function should return one line of input as a string.
507.150 -
507.151 - The second parameter, tokeneater, must also be a callable object. It is
507.152 - called once for each token, with five arguments, corresponding to the
507.153 - tuples generated by generate_tokens().
507.154 - """
507.155 - try:
507.156 - tokenize_loop(readline, tokeneater)
507.157 - except StopTokenizing:
507.158 - pass
507.159 -
507.160 -# backwards compatible interface
507.161 -def tokenize_loop(readline, tokeneater):
507.162 - for token_info in generate_tokens(readline):
507.163 - tokeneater(*token_info)
507.164 -
507.165 -
507.166 -def untokenize(iterable):
507.167 - """Transform tokens back into Python source code.
507.168 -
507.169 - Each element returned by the iterable must be a token sequence
507.170 - with at least two elements, a token number and token value.
507.171 -
507.172 - Round-trip invariant:
507.173 - # Output text will tokenize the back to the input
507.174 - t1 = [tok[:2] for tok in generate_tokens(f.readline)]
507.175 - newcode = untokenize(t1)
507.176 - readline = iter(newcode.splitlines(1)).next
507.177 - t2 = [tok[:2] for tokin generate_tokens(readline)]
507.178 - assert t1 == t2
507.179 - """
507.180 -
507.181 - startline = False
507.182 - indents = []
507.183 - toks = []
507.184 - toks_append = toks.append
507.185 - for tok in iterable:
507.186 - toknum, tokval = tok[:2]
507.187 -
507.188 - if toknum in (NAME, NUMBER):
507.189 - tokval += ' '
507.190 -
507.191 - if toknum == INDENT:
507.192 - indents.append(tokval)
507.193 - continue
507.194 - elif toknum == DEDENT:
507.195 - indents.pop()
507.196 - continue
507.197 - elif toknum in (NEWLINE, COMMENT, NL):
507.198 - startline = True
507.199 - elif startline and indents:
507.200 - toks_append(indents[-1])
507.201 - startline = False
507.202 - toks_append(tokval)
507.203 - return ''.join(toks)
507.204 -
507.205 -
507.206 -def generate_tokens(readline):
507.207 - """
507.208 - The generate_tokens() generator requires one argment, readline, which
507.209 - must be a callable object which provides the same interface as the
507.210 - readline() method of built-in file objects. Each call to the function
507.211 - should return one line of input as a string. Alternately, readline
507.212 - can be a callable function terminating with StopIteration:
507.213 - readline = open(myfile).next # Example of alternate readline
507.214 -
507.215 - The generator produces 5-tuples with these members: the token type; the
507.216 - token string; a 2-tuple (srow, scol) of ints specifying the row and
507.217 - column where the token begins in the source; a 2-tuple (erow, ecol) of
507.218 - ints specifying the row and column where the token ends in the source;
507.219 - and the line on which the token was found. The line passed is the
507.220 - logical line; continuation lines are included.
507.221 - """
507.222 - lnum = parenlev = continued = 0
507.223 - namechars, numchars = string.ascii_letters + '_', '0123456789'
507.224 - contstr, needcont = '', 0
507.225 - contline = None
507.226 - indents = [0]
507.227 -
507.228 - while 1: # loop over lines in stream
507.229 - try:
507.230 - line = readline()
507.231 - except StopIteration:
507.232 - line = ''
507.233 - lnum = lnum + 1
507.234 - pos, max = 0, len(line)
507.235 -
507.236 - if contstr: # continued string
507.237 - if not line:
507.238 - raise TokenError, ("EOF in multi-line string", strstart)
507.239 - endmatch = endprog.match(line)
507.240 - if endmatch:
507.241 - pos = end = endmatch.end(0)
507.242 - yield (STRING, contstr + line[:end],
507.243 - strstart, (lnum, end), contline + line)
507.244 - contstr, needcont = '', 0
507.245 - contline = None
507.246 - elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
507.247 - yield (ERRORTOKEN, contstr + line,
507.248 - strstart, (lnum, len(line)), contline)
507.249 - contstr = ''
507.250 - contline = None
507.251 - continue
507.252 - else:
507.253 - contstr = contstr + line
507.254 - contline = contline + line
507.255 - continue
507.256 -
507.257 - elif parenlev == 0 and not continued: # new statement
507.258 - if not line: break
507.259 - column = 0
507.260 - while pos < max: # measure leading whitespace
507.261 - if line[pos] == ' ': column = column + 1
507.262 - elif line[pos] == '\t': column = (column/tabsize + 1)*tabsize
507.263 - elif line[pos] == '\f': column = 0
507.264 - else: break
507.265 - pos = pos + 1
507.266 - if pos == max: break
507.267 -
507.268 - if line[pos] in '#\r\n': # skip comments or blank lines
507.269 - yield ((NL, COMMENT)[line[pos] == '#'], line[pos:],
507.270 - (lnum, pos), (lnum, len(line)), line)
507.271 - continue
507.272 -
507.273 - if column > indents[-1]: # count indents or dedents
507.274 - indents.append(column)
507.275 - yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
507.276 - while column < indents[-1]:
507.277 - if column not in indents:
507.278 - raise IndentationError(
507.279 - "unindent does not match any outer indentation level",
507.280 - ("<tokenize>", lnum, pos, line))
507.281 - indents = indents[:-1]
507.282 - yield (DEDENT, '', (lnum, pos), (lnum, pos), line)
507.283 -
507.284 - else: # continued statement
507.285 - if not line:
507.286 - raise TokenError, ("EOF in multi-line statement", (lnum, 0))
507.287 - continued = 0
507.288 -
507.289 - while pos < max:
507.290 - pseudomatch = pseudoprog.match(line, pos)
507.291 - if pseudomatch: # scan for tokens
507.292 - start, end = pseudomatch.span(1)
507.293 - spos, epos, pos = (lnum, start), (lnum, end), end
507.294 - token, initial = line[start:end], line[start]
507.295 -
507.296 - if initial in numchars or \
507.297 - (initial == '.' and token != '.'): # ordinary number
507.298 - yield (NUMBER, token, spos, epos, line)
507.299 - elif initial in '\r\n':
507.300 - yield (parenlev > 0 and NL or NEWLINE,
507.301 - token, spos, epos, line)
507.302 - elif initial == '#':
507.303 - yield (COMMENT, token, spos, epos, line)
507.304 - elif token in triple_quoted:
507.305 - endprog = endprogs[token]
507.306 - endmatch = endprog.match(line, pos)
507.307 - if endmatch: # all on one line
507.308 - pos = endmatch.end(0)
507.309 - token = line[start:pos]
507.310 - yield (STRING, token, spos, (lnum, pos), line)
507.311 - else:
507.312 - strstart = (lnum, start) # multiple lines
507.313 - contstr = line[start:]
507.314 - contline = line
507.315 - break
507.316 - elif initial in single_quoted or \
507.317 - token[:2] in single_quoted or \
507.318 - token[:3] in single_quoted:
507.319 - if token[-1] == '\n': # continued string
507.320 - strstart = (lnum, start)
507.321 - endprog = (endprogs[initial] or endprogs[token[1]] or
507.322 - endprogs[token[2]])
507.323 - contstr, needcont = line[start:], 1
507.324 - contline = line
507.325 - break
507.326 - else: # ordinary string
507.327 - yield (STRING, token, spos, epos, line)
507.328 - elif initial in namechars: # ordinary name
507.329 - yield (NAME, token, spos, epos, line)
507.330 - elif initial == '\\': # continued stmt
507.331 - continued = 1
507.332 - else:
507.333 - if initial in '([{': parenlev = parenlev + 1
507.334 - elif initial in ')]}': parenlev = parenlev - 1
507.335 - yield (OP, token, spos, epos, line)
507.336 - else:
507.337 - yield (ERRORTOKEN, line[pos],
507.338 - (lnum, pos), (lnum, pos+1), line)
507.339 - pos = pos + 1
507.340 -
507.341 - for indent in indents[1:]: # pop remaining indent levels
507.342 - yield (DEDENT, '', (lnum, 0), (lnum, 0), '')
507.343 - yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '')
507.344 -
507.345 -if __name__ == '__main__': # testing
507.346 - import sys
507.347 - if len(sys.argv) > 1: tokenize(open(sys.argv[1]).readline)
507.348 - else: tokenize(sys.stdin.readline)
508.1 --- a/python.editor/test/unit/data/testfiles/tokenize.py.scopes Sun Jan 04 13:11:53 2015 -0600
508.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
508.3 @@ -1,190 +0,0 @@
508.4 -=============================================
508.5 -<file-top>: Module : OffsetRange[0,13553>
508.6 -* [bound][imported][data][node=ImportFrom]
508.7 -Bracket [bound][data][read][node=Name]
508.8 -COMMENT [bound][data][read][node=Name]
508.9 -Comment [bound][data][read][node=Name]
508.10 -ContStr [bound][data][read][node=Name]
508.11 -Decnumber [bound][data][read][node=Name]
508.12 -Double [bound][data][read][node=Name]
508.13 -Double3 [bound][data][read][node=Name]
508.14 -Exception [read][UNRESOLVED][node=Name]
508.15 -Expfloat [bound][data][read][node=Name]
508.16 -Exponent [bound][data][read][node=Name]
508.17 -Floatnumber [bound][data][read][node=Name]
508.18 -Funny [bound][data][read][node=Name]
508.19 -Hexnumber [bound][data][read][node=Name]
508.20 -Ignore [bound][data][read][node=Name]
508.21 -Imagnumber [bound][data][read][node=Name]
508.22 -Intnumber [bound][data][read][node=Name]
508.23 -NL [bound][data][read][node=Name]
508.24 -N_TOKENS [bound][data][read][node=Name]
508.25 -Name [bound][data][read][node=Name]
508.26 -None [read][UNRESOLVED][node=Name]
508.27 -Number [bound][data][read][node=Name]
508.28 -Octnumber [bound][data][read][node=Name]
508.29 -Operator [bound][data][read][node=Name]
508.30 -PlainToken [bound][data][read][node=Name]
508.31 -Pointfloat [bound][data][read][node=Name]
508.32 -PseudoExtras [bound][data][read][node=Name]
508.33 -PseudoToken [bound][data][read][node=Name]
508.34 -Single [bound][data][read][node=Name]
508.35 -Single3 [bound][data][read][node=Name]
508.36 -Special [bound][data][read][node=Name]
508.37 -StopTokenizing [bound][class][def][read][node=ClassDef]
508.38 -String [bound][data][read][node=Name]
508.39 -Token [bound][data][read][node=Name]
508.40 -TokenError [bound][class][def][read][node=ClassDef]
508.41 -Triple [bound][data][read][node=Name]
508.42 -Whitespace [bound][data][read][node=Name]
508.43 -_[33_11] [bound][private][data][node=ListComp]
508.44 -__all__ [bound][data][node=Name]
508.45 -__author__ [bound][data][node=Name]
508.46 -__credits__ [bound][data][node=Name]
508.47 -__name__ [read][UNRESOLVED][node=Name]
508.48 -any [bound][function][def][read][called][node=FunctionDef]
508.49 -dir [read][called][UNRESOLVED][node=Name]
508.50 -double3prog [bound][data][read][node=Name]
508.51 -endprogs [bound][data][read][node=Name]
508.52 -generate_tokens [bound][function][def][node=FunctionDef]
508.53 -group [bound][function][def][read][called][node=FunctionDef]
508.54 -len [read][called][UNRESOLVED][node=Name]
508.55 -map [read][called][UNRESOLVED][node=Name]
508.56 -maybe [bound][function][def][read][called][node=FunctionDef]
508.57 -open [read][called][UNRESOLVED][node=Name]
508.58 -printtoken [bound][function][def][read][node=FunctionDef]
508.59 -pseudoprog [bound][data][read][node=Name]
508.60 -re [bound][imported][data][read][node=Import]
508.61 -single3prog [bound][data][read][node=Name]
508.62 -single_quoted [bound][data][read][node=Name]
508.63 -string [bound][imported][data][read][node=Import]
508.64 -sys [bound][imported][data][read][node=Import]
508.65 -t [bound][data][read][node=Name]
508.66 -tabsize [bound][data][read][node=Name]
508.67 -tok_name [read][UNRESOLVED][node=Name]
508.68 -token [bound][imported][data][read][node=Import]
508.69 -tokenize [bound][function][def][read][called][node=FunctionDef]
508.70 -tokenize_loop [bound][function][def][node=FunctionDef]
508.71 -tokenprog [bound][data][node=Name]
508.72 -triple_quoted [bound][data][read][node=Name]
508.73 -untokenize [bound][function][def][node=FunctionDef]
508.74 -x [bound][data][read][node=Name]
508.75 -
508.76 - =============================================
508.77 - group: FunctionDef : OffsetRange[1394,1452>
508.78 - choices [bound][param][data][read][node=arguments]
508.79 -
508.80 - =============================================
508.81 - any: FunctionDef : OffsetRange[1452,1500>
508.82 - choices [bound][param][data][read][node=arguments]
508.83 - group [free][read][called][node=Name]
508.84 -
508.85 - =============================================
508.86 - maybe: FunctionDef : OffsetRange[1500,1551>
508.87 - choices [bound][param][data][read][node=arguments]
508.88 - group [free][read][called][node=Name]
508.89 -
508.90 - =============================================
508.91 - class TokenError: ClassDef : OffsetRange[4630,4665>
508.92 -
508.93 - =============================================
508.94 - class StopTokenizing: ClassDef : OffsetRange[4665,4704>
508.95 -
508.96 - =============================================
508.97 - printtoken: FunctionDef : OffsetRange[4704,4881>
508.98 - (erow, ecol) [bound][param][data][read][node=Tuple]
508.99 - (srow, scol) [bound][param][data][read][node=Tuple]
508.100 - ecol [bound][from-param][data][read][node=Name]
508.101 - erow [bound][from-param][data][read][node=Name]
508.102 - line [bound][param][data][unused][node=Name]
508.103 - repr [free][read][called][node=Name]
508.104 - scol [bound][from-param][data][read][node=Name]
508.105 - srow [bound][from-param][data][read][node=Name]
508.106 - tok_name [free][read][node=Name]
508.107 - token [bound][param][data][read][node=Name]
508.108 - type [bound][param][data][read][node=Name]
508.109 -
508.110 - =============================================
508.111 - tokenize: FunctionDef : OffsetRange[4881,5636>
508.112 - StopTokenizing [free][read][node=Name]
508.113 - readline [bound][param][data][read][node=Name]
508.114 - tokeneater [bound][param][data][read][node=Name]
508.115 - tokenize_loop [free][read][called][node=Name]
508.116 -
508.117 - =============================================
508.118 - tokenize_loop: FunctionDef : OffsetRange[5636,5760>
508.119 - generate_tokens [free][read][called][node=Name]
508.120 - readline [bound][param][data][read][node=Name]
508.121 - token_info [bound][data][read][node=Name]
508.122 - tokeneater [bound][param][data][read][called][node=Name]
508.123 -
508.124 - =============================================
508.125 - untokenize: FunctionDef : OffsetRange[5760,6899>
508.126 - COMMENT [free][read][node=Name]
508.127 - DEDENT [free][read][node=Name]
508.128 - False [free][read][node=Name]
508.129 - INDENT [free][read][node=Name]
508.130 - NAME [free][read][node=Name]
508.131 - NEWLINE [free][read][node=Name]
508.132 - NL [free][read][node=Name]
508.133 - NUMBER [free][read][node=Name]
508.134 - True [free][read][node=Name]
508.135 - indents [bound][data][read][node=Name]
508.136 - iterable [bound][param][data][read][node=Name]
508.137 - startline [bound][data][read][node=Name]
508.138 - tok [bound][data][read][node=Name]
508.139 - toknum [bound][data][read][node=Name]
508.140 - toks [bound][data][read][node=Name]
508.141 - toks_append [bound][data][read][called][node=Name]
508.142 - tokval [bound][data][read][node=Name]
508.143 -
508.144 - =============================================
508.145 - generate_tokens: FunctionDef : OffsetRange[6899,13380>
508.146 - COMMENT [free][read][node=Name]
508.147 - DEDENT [free][read][node=Name]
508.148 - ENDMARKER [free][read][node=Name]
508.149 - ERRORTOKEN [free][read][node=Name]
508.150 - INDENT [free][read][node=Name]
508.151 - IndentationError [free][read][called][node=Name]
508.152 - NAME [free][read][node=Name]
508.153 - NEWLINE [free][read][node=Name]
508.154 - NL [free][read][node=Name]
508.155 - NUMBER [free][read][node=Name]
508.156 - None [free][read][node=Name]
508.157 - OP [free][read][node=Name]
508.158 - STRING [free][read][node=Name]
508.159 - StopIteration [free][read][node=Name]
508.160 - TokenError [free][read][node=Name]
508.161 - column [bound][data][read][node=Name]
508.162 - continued [bound][data][read][node=Name]
508.163 - contline [bound][data][read][node=Name]
508.164 - contstr [bound][data][read][node=Name]
508.165 - end [bound][data][read][node=Name]
508.166 - endmatch [bound][data][read][node=Name]
508.167 - endprog [bound][data][read][node=Name]
508.168 - endprogs [free][read][node=Name]
508.169 - epos [bound][data][read][node=Name]
508.170 - indent [bound][data][unused][node=Name]
508.171 - indents [bound][data][read][node=Name]
508.172 - initial [bound][data][read][node=Name]
508.173 - len [free][read][called][node=Name]
508.174 - line [bound][data][read][node=Name]
508.175 - lnum [bound][data][read][node=Name]
508.176 - max [bound][data][read][node=Name]
508.177 - namechars [bound][data][read][node=Name]
508.178 - needcont [bound][data][read][node=Name]
508.179 - numchars [bound][data][read][node=Name]
508.180 - parenlev [bound][data][read][node=Name]
508.181 - pos [bound][data][read][node=Name]
508.182 - pseudomatch [bound][data][read][node=Name]
508.183 - pseudoprog [free][read][node=Name]
508.184 - readline [bound][param][data][read][called][node=Name]
508.185 - single_quoted [free][read][node=Name]
508.186 - spos [bound][data][read][node=Name]
508.187 - start [bound][data][read][node=Name]
508.188 - string [free][read][node=Name]
508.189 - strstart [bound][data][read][node=Name]
508.190 - tabsize [free][read][node=Name]
508.191 - token [bound][data][read][node=Name]
508.192 - triple_quoted [free][read][node=Name]
508.193 -
509.1 --- a/python.editor/test/unit/data/testfiles/toppkg/__init__.py Sun Jan 04 13:11:53 2015 -0600
509.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
509.3 @@ -1,33 +0,0 @@
509.4 -"""distutils.command
509.5 -
509.6 -Package containing implementation of all the standard Distutils
509.7 -commands."""
509.8 -
509.9 -# This module should be kept compatible with Python 2.1.
509.10 -
509.11 -__revision__ = "$Id: __init__.py 37828 2004-11-10 22:23:15Z loewis $"
509.12 -
509.13 -__all__ = ['build',
509.14 - 'build_py',
509.15 - 'build_ext',
509.16 - 'build_clib',
509.17 - 'build_scripts',
509.18 - 'clean',
509.19 - 'install',
509.20 - 'install_lib',
509.21 - 'install_headers',
509.22 - 'install_scripts',
509.23 - 'install_data',
509.24 - 'sdist',
509.25 - 'register',
509.26 - 'bdist',
509.27 - 'bdist_dumb',
509.28 - 'bdist_rpm',
509.29 - 'bdist_wininst',
509.30 - # These two are reserved for future use:
509.31 - #'bdist_sdux',
509.32 - #'bdist_pkgtool',
509.33 - # Note:
509.34 - # bdist_packager is not included because it only provides
509.35 - # an abstract base class
509.36 - ]
510.1 --- a/python.editor/test/unit/data/testfiles/toppkg/medpkg/__init__.py Sun Jan 04 13:11:53 2015 -0600
510.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
510.3 @@ -1,33 +0,0 @@
510.4 -"""distutils.command
510.5 -
510.6 -Package containing implementation of all the standard Distutils
510.7 -commands."""
510.8 -
510.9 -# This module should be kept compatible with Python 2.1.
510.10 -
510.11 -__revision__ = "$Id: __init__.py 37828 2004-11-10 22:23:15Z loewis $"
510.12 -
510.13 -__all__ = ['build',
510.14 - 'build_py',
510.15 - 'build_ext',
510.16 - 'build_clib',
510.17 - 'build_scripts',
510.18 - 'clean',
510.19 - 'install',
510.20 - 'install_lib',
510.21 - 'install_headers',
510.22 - 'install_scripts',
510.23 - 'install_data',
510.24 - 'sdist',
510.25 - 'register',
510.26 - 'bdist',
510.27 - 'bdist_dumb',
510.28 - 'bdist_rpm',
510.29 - 'bdist_wininst',
510.30 - # These two are reserved for future use:
510.31 - #'bdist_sdux',
510.32 - #'bdist_pkgtool',
510.33 - # Note:
510.34 - # bdist_packager is not included because it only provides
510.35 - # an abstract base class
510.36 - ]
511.1 --- a/python.editor/test/unit/data/testfiles/toppkg/medpkg/lowpkg/__init__.py Sun Jan 04 13:11:53 2015 -0600
511.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
511.3 @@ -1,33 +0,0 @@
511.4 -"""distutils.command
511.5 -
511.6 -Package containing implementation of all the standard Distutils
511.7 -commands."""
511.8 -
511.9 -# This module should be kept compatible with Python 2.1.
511.10 -
511.11 -__revision__ = "$Id: __init__.py 37828 2004-11-10 22:23:15Z loewis $"
511.12 -
511.13 -__all__ = ['build',
511.14 - 'build_py',
511.15 - 'build_ext',
511.16 - 'build_clib',
511.17 - 'build_scripts',
511.18 - 'clean',
511.19 - 'install',
511.20 - 'install_lib',
511.21 - 'install_headers',
511.22 - 'install_scripts',
511.23 - 'install_data',
511.24 - 'sdist',
511.25 - 'register',
511.26 - 'bdist',
511.27 - 'bdist_dumb',
511.28 - 'bdist_rpm',
511.29 - 'bdist_wininst',
511.30 - # These two are reserved for future use:
511.31 - #'bdist_sdux',
511.32 - #'bdist_pkgtool',
511.33 - # Note:
511.34 - # bdist_packager is not included because it only provides
511.35 - # an abstract base class
511.36 - ]
512.1 --- a/python.editor/test/unit/data/testfiles/toppkg/medpkg/lowpkg/imports.py Sun Jan 04 13:11:53 2015 -0600
512.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
512.3 @@ -1,9 +0,0 @@
512.4 -from .moduleY import spam
512.5 -from .moduleY import spam as ham
512.6 -from . import moduleY
512.7 -from ..subpackage1 import moduleY
512.8 -from ..subpackage2.moduleZ import eggs
512.9 -from ..moduleA import foo
512.10 -from ...package import bar
512.11 -from ...sys import path
512.12 -
513.1 --- a/python.editor/test/unit/data/testfiles/toppkg/medpkg/lowpkg/imports.py.testFix1.fixed Sun Jan 04 13:11:53 2015 -0600
513.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
513.3 @@ -1,9 +0,0 @@
513.4 -from toppkg.medpkg.lowpkg.moduleY import spam
513.5 -from .moduleY import spam as ham
513.6 -from . import moduleY
513.7 -from ..subpackage1 import moduleY
513.8 -from ..subpackage2.moduleZ import eggs
513.9 -from ..moduleA import foo
513.10 -from ...package import bar
513.11 -from ...sys import path
513.12 -
514.1 --- a/python.editor/test/unit/data/testfiles/toppkg/medpkg/lowpkg/imports.py.testFix2.fixed Sun Jan 04 13:11:53 2015 -0600
514.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
514.3 @@ -1,9 +0,0 @@
514.4 -from .moduleY import spam
514.5 -from .moduleY import spam as ham
514.6 -from . import moduleY
514.7 -from toppkg.medpkg.subpackage1 import moduleY
514.8 -from ..subpackage2.moduleZ import eggs
514.9 -from ..moduleA import foo
514.10 -from ...package import bar
514.11 -from ...sys import path
514.12 -
515.1 --- a/python.editor/test/unit/data/testfiles/toppkg/medpkg/lowpkg/imports.py.testFix3.fixed Sun Jan 04 13:11:53 2015 -0600
515.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
515.3 @@ -1,9 +0,0 @@
515.4 -from .moduleY import spam
515.5 -from .moduleY import spam as ham
515.6 -from . import moduleY
515.7 -from ..subpackage1 import moduleY
515.8 -from ..subpackage2.moduleZ import eggs
515.9 -from ..moduleA import foo
515.10 -from toppkg.package import bar
515.11 -from ...sys import path
515.12 -
516.1 --- a/python.editor/test/unit/data/testfiles/toppkg/medpkg/lowpkg/imports.py.testHint1.hints Sun Jan 04 13:11:53 2015 -0600
516.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
516.3 @@ -1,32 +0,0 @@
516.4 -from .moduleY import spam
516.5 --------------------------
516.6 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
516.7 -FIX:Replace with absolute import
516.8 -from .moduleY import spam as ham
516.9 ---------------------------------
516.10 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
516.11 -FIX:Replace with absolute import
516.12 -from . import moduleY
516.13 ----------------------
516.14 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
516.15 -FIX:Replace with absolute import
516.16 -from ..subpackage1 import moduleY
516.17 ----------------------------------
516.18 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
516.19 -FIX:Replace with absolute import
516.20 -from ..subpackage2.moduleZ import eggs
516.21 ---------------------------------------
516.22 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
516.23 -FIX:Replace with absolute import
516.24 -from ..moduleA import foo
516.25 --------------------------
516.26 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
516.27 -FIX:Replace with absolute import
516.28 -from ...package import bar
516.29 ---------------------------
516.30 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
516.31 -FIX:Replace with absolute import
516.32 -from ...sys import path
516.33 ------------------------
516.34 -HINT:Relative imports for intra-package imports are actively discouraged (as per PEP-008)
516.35 -FIX:Replace with absolute import
517.1 --- a/python.editor/test/unit/data/testfiles/tuples.py Sun Jan 04 13:11:53 2015 -0600
517.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
517.3 @@ -1,15 +0,0 @@
517.4 -def foo():
517.5 - for x, y in None:
517.6 - print y
517.7 - for z in None:
517.8 - pass
517.9 - (a, b) = None
517.10 - c = None
517.11 - print b
517.12 - for dirpath, dirnames, filenames in os.walk(src): # dirnames unused
517.13 - for i, (name, path) in enumerate(result): # i unused
517.14 - pass
517.15 - aliases, entry = cmdutil.findcmd(command, table) # aliases unused
517.16 - for rev, node, fnode in self._hgtagsnodes(): # rev & node unused
517.17 - pass
517.18 -
518.1 --- a/python.editor/test/unit/data/testfiles/tuples.py.testUnusedHints7.hints Sun Jan 04 13:11:53 2015 -0600
518.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
518.3 @@ -1,31 +0,0 @@
518.4 - for x, y in None:
518.5 - -
518.6 -HINT:Unused Variable x
518.7 - for z in None:
518.8 - -
518.9 -HINT:Unused Variable z
518.10 - (a, b) = None
518.11 - -
518.12 -HINT:Unused Variable a
518.13 - c = None
518.14 - -
518.15 -HINT:Unused Variable c
518.16 - for dirpath, dirnames, filenames in os.walk(src): # dirnames unused
518.17 - ---------
518.18 -HINT:Unused Variable dirnames
518.19 -HINT:Unused Variable dirpath
518.20 -HINT:Unused Variable filenames
518.21 - for i, (name, path) in enumerate(result): # i unused
518.22 - ----
518.23 -HINT:Unused Variable i
518.24 -HINT:Unused Variable name
518.25 -HINT:Unused Variable path
518.26 - aliases, entry = cmdutil.findcmd(command, table) # aliases unused
518.27 - -----
518.28 -HINT:Unused Variable aliases
518.29 -HINT:Unused Variable entry
518.30 - for rev, node, fnode in self._hgtagsnodes(): # rev & node unused
518.31 - -----
518.32 -HINT:Unused Variable fnode
518.33 -HINT:Unused Variable node
518.34 -HINT:Unused Variable rev
519.1 --- a/python.editor/test/unit/data/testfiles/tuples.py.testUnusedHints8.hints Sun Jan 04 13:11:53 2015 -0600
519.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
519.3 @@ -1,6 +0,0 @@
519.4 - for z in None:
519.5 - -
519.6 -HINT:Unused Variable z
519.7 - c = None
519.8 - -
519.9 -HINT:Unused Variable c
520.1 --- a/python.editor/test/unit/data/testfiles/types.py Sun Jan 04 13:11:53 2015 -0600
520.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
520.3 @@ -1,25 +0,0 @@
520.4 -x = y = SomeOtherClass()
520.5 -z = y
520.6 -w = 5
520.7 -yz = "foo"
520.8 -someObject = SomeClass().foo();
520.9 -
520.10 -# Type variables
520.11 -# @type defined1: int
520.12 -#defined1.x()
520.13 -
520.14 -#FIRST_CARET_POS
520.15 -
520.16 -# Redefine
520.17 -# @type defined1: str
520.18 -#defined1.y()
520.19 -
520.20 -x = Other()
520.21 -y = 5
520.22 -z = "str"
520.23 -
520.24 -# Type assertions
520.25 -assert isinstanceof(s, basestring)
520.26 -s.i
520.27 -
520.28 -#SECOND_CARET_POS
521.1 --- a/python.editor/test/unit/data/testfiles/typevars.py Sun Jan 04 13:11:53 2015 -0600
521.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
521.3 @@ -1,9 +0,0 @@
521.4 -# Tests for Python type assertions
521.5 -
521.6 -# @type xy str
521.7 -xy.s1
521.8 -zs.t
521.9 -# @type xy int
521.10 -xy.s2
521.11 -
521.12 -
522.1 --- a/python.editor/test/unit/data/testfiles/typevars.py.testMarks11.occurrences Sun Jan 04 13:11:53 2015 -0600
522.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
522.3 @@ -1,4 +0,0 @@
522.4 -# @type ^|>MARK_OCCURRENCES:xy<| str
522.5 -|>MARK_OCCURRENCES:xy<|.s1
522.6 -# @type |>MARK_OCCURRENCES:xy<| int
522.7 -|>MARK_OCCURRENCES:xy<|.s2
523.1 --- a/python.editor/test/unit/data/testfiles/typevars.py.testRename7.rename Sun Jan 04 13:11:53 2015 -0600
523.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
523.3 @@ -1,4 +0,0 @@
523.4 -3: # @type |>xy<| str
523.5 -4: |>xy<|.s1
523.6 -6: # @type |>xy<| int
523.7 -7: |>xy<|.s2
524.1 --- a/python.editor/test/unit/data/testfiles/typevars.py.testRename8.rename Sun Jan 04 13:11:53 2015 -0600
524.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
524.3 @@ -1,4 +0,0 @@
524.4 -3: # @type |>xy<| str
524.5 -4: |>xy<|.s1
524.6 -6: # @type |>xy<| int
524.7 -7: |>xy<|.s2
525.1 --- a/python.editor/test/unit/data/testfiles/unittest.py Sun Jan 04 13:11:53 2015 -0600
525.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
525.3 @@ -1,816 +0,0 @@
525.4 -#!/usr/bin/env python
525.5 -'''
525.6 -Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's
525.7 -Smalltalk testing framework.
525.8 -
525.9 -This module contains the core framework classes that form the basis of
525.10 -specific test cases and suites (TestCase, TestSuite etc.), and also a
525.11 -text-based utility class for running the tests and reporting the results
525.12 - (TextTestRunner).
525.13 -
525.14 -Simple usage:
525.15 -
525.16 - import unittest
525.17 -
525.18 - class IntegerArithmenticTestCase(unittest.TestCase):
525.19 - def testAdd(self): ## test method names begin 'test*'
525.20 - self.assertEquals((1 + 2), 3)
525.21 - self.assertEquals(0 + 1, 1)
525.22 - def testMultiply(self):
525.23 - self.assertEquals((0 * 10), 0)
525.24 - self.assertEquals((5 * 8), 40)
525.25 -
525.26 - if __name__ == '__main__':
525.27 - unittest.main()
525.28 -
525.29 -Further information is available in the bundled documentation, and from
525.30 -
525.31 - http://pyunit.sourceforge.net/
525.32 -
525.33 -Copyright (c) 1999-2003 Steve Purcell
525.34 -This module is free software, and you may redistribute it and/or modify
525.35 -it under the same terms as Python itself, so long as this copyright message
525.36 -and disclaimer are retained in their original form.
525.37 -
525.38 -IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
525.39 -SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
525.40 -THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
525.41 -DAMAGE.
525.42 -
525.43 -THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
525.44 -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
525.45 -PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
525.46 -AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
525.47 -SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
525.48 -'''
525.49 -
525.50 -__author__ = "Steve Purcell"
525.51 -__email__ = "stephen_purcell at yahoo dot com"
525.52 -__version__ = "#Revision: 1.63 $"[11:-2]
525.53 -
525.54 -import time
525.55 -import sys
525.56 -import traceback
525.57 -import os
525.58 -import types
525.59 -
525.60 -##############################################################################
525.61 -# Exported classes and functions
525.62 -##############################################################################
525.63 -__all__ = ['TestResult', 'TestCase', 'TestSuite', 'TextTestRunner',
525.64 - 'TestLoader', 'FunctionTestCase', 'main', 'defaultTestLoader']
525.65 -
525.66 -# Expose obsolete functions for backwards compatibility
525.67 -__all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])
525.68 -
525.69 -
525.70 -##############################################################################
525.71 -# Backward compatibility
525.72 -##############################################################################
525.73 -if sys.version_info[:2] < (2, 2):
525.74 - False, True = 0, 1
525.75 - def isinstance(obj, clsinfo):
525.76 - import __builtin__
525.77 - if type(clsinfo) in (tuple, list):
525.78 - for cls in clsinfo:
525.79 - if cls is type: cls = types.ClassType
525.80 - if __builtin__.isinstance(obj, cls):
525.81 - return 1
525.82 - return 0
525.83 - else: return __builtin__.isinstance(obj, clsinfo)
525.84 -
525.85 -
525.86 -##############################################################################
525.87 -# Test framework core
525.88 -##############################################################################
525.89 -
525.90 -# All classes defined herein are 'new-style' classes, allowing use of 'super()'
525.91 -__metaclass__ = type
525.92 -
525.93 -def _strclass(cls):
525.94 - return "%s.%s" % (cls.__module__, cls.__name__)
525.95 -
525.96 -__unittest = 1
525.97 -
525.98 -class TestResult:
525.99 - """Holder for test result information.
525.100 -
525.101 - Test results are automatically managed by the TestCase and TestSuite
525.102 - classes, and do not need to be explicitly manipulated by writers of tests.
525.103 -
525.104 - Each instance holds the total number of tests run, and collections of
525.105 - failures and errors that occurred among those test runs. The collections
525.106 - contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
525.107 - formatted traceback of the error that occurred.
525.108 - """
525.109 - def __init__(self):
525.110 - self.failures = []
525.111 - self.errors = []
525.112 - self.testsRun = 0
525.113 - self.shouldStop = 0
525.114 -
525.115 - def startTest(self, test):
525.116 - "Called when the given test is about to be run"
525.117 - self.testsRun = self.testsRun + 1
525.118 -
525.119 - def stopTest(self, test):
525.120 - "Called when the given test has been run"
525.121 - pass
525.122 -
525.123 - def addError(self, test, err):
525.124 - """Called when an error has occurred. 'err' is a tuple of values as
525.125 - returned by sys.exc_info().
525.126 - """
525.127 - self.errors.append((test, self._exc_info_to_string(err, test)))
525.128 -
525.129 - def addFailure(self, test, err):
525.130 - """Called when an error has occurred. 'err' is a tuple of values as
525.131 - returned by sys.exc_info()."""
525.132 - self.failures.append((test, self._exc_info_to_string(err, test)))
525.133 -
525.134 - def addSuccess(self, test):
525.135 - "Called when a test has completed successfully"
525.136 - pass
525.137 -
525.138 - def wasSuccessful(self):
525.139 - "Tells whether or not this result was a success"
525.140 - return len(self.failures) == len(self.errors) == 0
525.141 -
525.142 - def stop(self):
525.143 - "Indicates that the tests should be aborted"
525.144 - self.shouldStop = True
525.145 -
525.146 - def _exc_info_to_string(self, err, test):
525.147 - """Converts a sys.exc_info()-style tuple of values into a string."""
525.148 - exctype, value, tb = err
525.149 - # Skip test runner traceback levels
525.150 - while tb and self._is_relevant_tb_level(tb):
525.151 - tb = tb.tb_next
525.152 - if exctype is test.failureException:
525.153 - # Skip assert*() traceback levels
525.154 - length = self._count_relevant_tb_levels(tb)
525.155 - return ''.join(traceback.format_exception(exctype, value, tb, length))
525.156 - return ''.join(traceback.format_exception(exctype, value, tb))
525.157 -
525.158 - def _is_relevant_tb_level(self, tb):
525.159 - return tb.tb_frame.f_globals.has_key('__unittest')
525.160 -
525.161 - def _count_relevant_tb_levels(self, tb):
525.162 - length = 0
525.163 - while tb and not self._is_relevant_tb_level(tb):
525.164 - length += 1
525.165 - tb = tb.tb_next
525.166 - return length
525.167 -
525.168 - def __repr__(self):
525.169 - return "<%s run=%i errors=%i failures=%i>" % \
525.170 - (_strclass(self.__class__), self.testsRun, len(self.errors),
525.171 - len(self.failures))
525.172 -
525.173 -class TestCase:
525.174 - """A class whose instances are single test cases.
525.175 -
525.176 - By default, the test code itself should be placed in a method named
525.177 - 'runTest'.
525.178 -
525.179 - If the fixture may be used for many test cases, create as
525.180 - many test methods as are needed. When instantiating such a TestCase
525.181 - subclass, specify in the constructor arguments the name of the test method
525.182 - that the instance is to execute.
525.183 -
525.184 - Test authors should subclass TestCase for their own tests. Construction
525.185 - and deconstruction of the test's environment ('fixture') can be
525.186 - implemented by overriding the 'setUp' and 'tearDown' methods respectively.
525.187 -
525.188 - If it is necessary to override the __init__ method, the base class
525.189 - __init__ method must always be called. It is important that subclasses
525.190 - should not change the signature of their __init__ method, since instances
525.191 - of the classes are instantiated automatically by parts of the framework
525.192 - in order to be run.
525.193 - """
525.194 -
525.195 - # This attribute determines which exception will be raised when
525.196 - # the instance's assertion methods fail; test methods raising this
525.197 - # exception will be deemed to have 'failed' rather than 'errored'
525.198 -
525.199 - failureException = AssertionError
525.200 -
525.201 - def __init__(self, methodName='runTest'):
525.202 - """Create an instance of the class that will use the named test
525.203 - method when executed. Raises a ValueError if the instance does
525.204 - not have a method with the specified name.
525.205 - """
525.206 - try:
525.207 - self._testMethodName = methodName
525.208 - testMethod = getattr(self, methodName)
525.209 - self._testMethodDoc = testMethod.__doc__
525.210 - except AttributeError:
525.211 - raise ValueError, "no such test method in %s: %s" % \
525.212 - (self.__class__, methodName)
525.213 -
525.214 - def setUp(self):
525.215 - "Hook method for setting up the test fixture before exercising it."
525.216 - pass
525.217 -
525.218 - def tearDown(self):
525.219 - "Hook method for deconstructing the test fixture after testing it."
525.220 - pass
525.221 -
525.222 - def countTestCases(self):
525.223 - return 1
525.224 -
525.225 - def defaultTestResult(self):
525.226 - return TestResult()
525.227 -
525.228 - def shortDescription(self):
525.229 - """Returns a one-line description of the test, or None if no
525.230 - description has been provided.
525.231 -
525.232 - The default implementation of this method returns the first line of
525.233 - the specified test method's docstring.
525.234 - """
525.235 - doc = self._testMethodDoc
525.236 - return doc and doc.split("\n")[0].strip() or None
525.237 -
525.238 - def id(self):
525.239 - return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
525.240 -
525.241 - def __str__(self):
525.242 - return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
525.243 -
525.244 - def __repr__(self):
525.245 - return "<%s testMethod=%s>" % \
525.246 - (_strclass(self.__class__), self._testMethodName)
525.247 -
525.248 - def run(self, result=None):
525.249 - if result is None: result = self.defaultTestResult()
525.250 - result.startTest(self)
525.251 - testMethod = getattr(self, self._testMethodName)
525.252 - try:
525.253 - try:
525.254 - self.setUp()
525.255 - except KeyboardInterrupt:
525.256 - raise
525.257 - except:
525.258 - result.addError(self, self._exc_info())
525.259 - return
525.260 -
525.261 - ok = False
525.262 - try:
525.263 - testMethod()
525.264 - ok = True
525.265 - except self.failureException:
525.266 - result.addFailure(self, self._exc_info())
525.267 - except KeyboardInterrupt:
525.268 - raise
525.269 - except:
525.270 - result.addError(self, self._exc_info())
525.271 -
525.272 - try:
525.273 - self.tearDown()
525.274 - except KeyboardInterrupt:
525.275 - raise
525.276 - except:
525.277 - result.addError(self, self._exc_info())
525.278 - ok = False
525.279 - if ok: result.addSuccess(self)
525.280 - finally:
525.281 - result.stopTest(self)
525.282 -
525.283 - def __call__(self, *args, **kwds):
525.284 - return self.run(*args, **kwds)
525.285 -
525.286 - def debug(self):
525.287 - """Run the test without collecting errors in a TestResult"""
525.288 - self.setUp()
525.289 - getattr(self, self._testMethodName)()
525.290 - self.tearDown()
525.291 -
525.292 - def _exc_info(self):
525.293 - """Return a version of sys.exc_info() with the traceback frame
525.294 - minimised; usually the top level of the traceback frame is not
525.295 - needed.
525.296 - """
525.297 - exctype, excvalue, tb = sys.exc_info()
525.298 - if sys.platform[:4] == 'java': ## tracebacks look different in Jython
525.299 - return (exctype, excvalue, tb)
525.300 - return (exctype, excvalue, tb)
525.301 -
525.302 - def fail(self, msg=None):
525.303 - """Fail immediately, with the given message."""
525.304 - raise self.failureException, msg
525.305 -
525.306 - def failIf(self, expr, msg=None):
525.307 - "Fail the test if the expression is true."
525.308 - if expr: raise self.failureException, msg
525.309 -
525.310 - def failUnless(self, expr, msg=None):
525.311 - """Fail the test unless the expression is true."""
525.312 - if not expr: raise self.failureException, msg
525.313 -
525.314 - def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
525.315 - """Fail unless an exception of class excClass is thrown
525.316 - by callableObj when invoked with arguments args and keyword
525.317 - arguments kwargs. If a different type of exception is
525.318 - thrown, it will not be caught, and the test case will be
525.319 - deemed to have suffered an error, exactly as for an
525.320 - unexpected exception.
525.321 - """
525.322 - try:
525.323 - callableObj(*args, **kwargs)
525.324 - except excClass:
525.325 - return
525.326 - else:
525.327 - if hasattr(excClass,'__name__'): excName = excClass.__name__
525.328 - else: excName = str(excClass)
525.329 - raise self.failureException, "%s not raised" % excName
525.330 -
525.331 - def failUnlessEqual(self, first, second, msg=None):
525.332 - """Fail if the two objects are unequal as determined by the '=='
525.333 - operator.
525.334 - """
525.335 - if not first == second:
525.336 - raise self.failureException, \
525.337 - (msg or '%r != %r' % (first, second))
525.338 -
525.339 - def failIfEqual(self, first, second, msg=None):
525.340 - """Fail if the two objects are equal as determined by the '=='
525.341 - operator.
525.342 - """
525.343 - if first == second:
525.344 - raise self.failureException, \
525.345 - (msg or '%r == %r' % (first, second))
525.346 -
525.347 - def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
525.348 - """Fail if the two objects are unequal as determined by their
525.349 - difference rounded to the given number of decimal places
525.350 - (default 7) and comparing to zero.
525.351 -
525.352 - Note that decimal places (from zero) are usually not the same
525.353 - as significant digits (measured from the most signficant digit).
525.354 - """
525.355 - if round(second-first, places) != 0:
525.356 - raise self.failureException, \
525.357 - (msg or '%r != %r within %r places' % (first, second, places))
525.358 -
525.359 - def failIfAlmostEqual(self, first, second, places=7, msg=None):
525.360 - """Fail if the two objects are equal as determined by their
525.361 - difference rounded to the given number of decimal places
525.362 - (default 7) and comparing to zero.
525.363 -
525.364 - Note that decimal places (from zero) are usually not the same
525.365 - as significant digits (measured from the most signficant digit).
525.366 - """
525.367 - if round(second-first, places) == 0:
525.368 - raise self.failureException, \
525.369 - (msg or '%r == %r within %r places' % (first, second, places))
525.370 -
525.371 - # Synonyms for assertion methods
525.372 -
525.373 - assertEqual = assertEquals = failUnlessEqual
525.374 -
525.375 - assertNotEqual = assertNotEquals = failIfEqual
525.376 -
525.377 - assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual
525.378 -
525.379 - assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual
525.380 -
525.381 - assertRaises = failUnlessRaises
525.382 -
525.383 - assert_ = assertTrue = failUnless
525.384 -
525.385 - assertFalse = failIf
525.386 -
525.387 -
525.388 -
525.389 -class TestSuite:
525.390 - """A test suite is a composite test consisting of a number of TestCases.
525.391 -
525.392 - For use, create an instance of TestSuite, then add test case instances.
525.393 - When all tests have been added, the suite can be passed to a test
525.394 - runner, such as TextTestRunner. It will run the individual test cases
525.395 - in the order in which they were added, aggregating the results. When
525.396 - subclassing, do not forget to call the base class constructor.
525.397 - """
525.398 - def __init__(self, tests=()):
525.399 - self._tests = []
525.400 - self.addTests(tests)
525.401 -
525.402 - def __repr__(self):
525.403 - return "<%s tests=%s>" % (_strclass(self.__class__), self._tests)
525.404 -
525.405 - __str__ = __repr__
525.406 -
525.407 - def __iter__(self):
525.408 - return iter(self._tests)
525.409 -
525.410 - def countTestCases(self):
525.411 - cases = 0
525.412 - for test in self._tests:
525.413 - cases += test.countTestCases()
525.414 - return cases
525.415 -
525.416 - def addTest(self, test):
525.417 - # sanity checks
525.418 - if not callable(test):
525.419 - raise TypeError("the test to add must be callable")
525.420 - if (isinstance(test, (type, types.ClassType)) and
525.421 - issubclass(test, (TestCase, TestSuite))):
525.422 - raise TypeError("TestCases and TestSuites must be instantiated "
525.423 - "before passing them to addTest()")
525.424 - self._tests.append(test)
525.425 -
525.426 - def addTests(self, tests):
525.427 - if isinstance(tests, basestring):
525.428 - raise TypeError("tests must be an iterable of tests, not a string")
525.429 - for test in tests:
525.430 - self.addTest(test)
525.431 -
525.432 - def run(self, result):
525.433 - for test in self._tests:
525.434 - if result.shouldStop:
525.435 - break
525.436 - test(result)
525.437 - return result
525.438 -
525.439 - def __call__(self, *args, **kwds):
525.440 - return self.run(*args, **kwds)
525.441 -
525.442 - def debug(self):
525.443 - """Run the tests without collecting errors in a TestResult"""
525.444 - for test in self._tests: test.debug()
525.445 -
525.446 -
525.447 -class FunctionTestCase(TestCase):
525.448 - """A test case that wraps a test function.
525.449 -
525.450 - This is useful for slipping pre-existing test functions into the
525.451 - PyUnit framework. Optionally, set-up and tidy-up functions can be
525.452 - supplied. As with TestCase, the tidy-up ('tearDown') function will
525.453 - always be called if the set-up ('setUp') function ran successfully.
525.454 - """
525.455 -
525.456 - def __init__(self, testFunc, setUp=None, tearDown=None,
525.457 - description=None):
525.458 - TestCase.__init__(self)
525.459 - self.__setUpFunc = setUp
525.460 - self.__tearDownFunc = tearDown
525.461 - self.__testFunc = testFunc
525.462 - self.__description = description
525.463 -
525.464 - def setUp(self):
525.465 - if self.__setUpFunc is not None:
525.466 - self.__setUpFunc()
525.467 -
525.468 - def tearDown(self):
525.469 - if self.__tearDownFunc is not None:
525.470 - self.__tearDownFunc()
525.471 -
525.472 - def runTest(self):
525.473 - self.__testFunc()
525.474 -
525.475 - def id(self):
525.476 - return self.__testFunc.__name__
525.477 -
525.478 - def __str__(self):
525.479 - return "%s (%s)" % (_strclass(self.__class__), self.__testFunc.__name__)
525.480 -
525.481 - def __repr__(self):
525.482 - return "<%s testFunc=%s>" % (_strclass(self.__class__), self.__testFunc)
525.483 -
525.484 - def shortDescription(self):
525.485 - if self.__description is not None: return self.__description
525.486 - doc = self.__testFunc.__doc__
525.487 - return doc and doc.split("\n")[0].strip() or None
525.488 -
525.489 -
525.490 -
525.491 -##############################################################################
525.492 -# Locating and loading tests
525.493 -##############################################################################
525.494 -
525.495 -class TestLoader:
525.496 - """This class is responsible for loading tests according to various
525.497 - criteria and returning them wrapped in a Test
525.498 - """
525.499 - testMethodPrefix = 'test'
525.500 - sortTestMethodsUsing = cmp
525.501 - suiteClass = TestSuite
525.502 -
525.503 - def loadTestsFromTestCase(self, testCaseClass):
525.504 - """Return a suite of all tests cases contained in testCaseClass"""
525.505 - if issubclass(testCaseClass, TestSuite):
525.506 - raise TypeError("Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?")
525.507 - testCaseNames = self.getTestCaseNames(testCaseClass)
525.508 - if not testCaseNames and hasattr(testCaseClass, 'runTest'):
525.509 - testCaseNames = ['runTest']
525.510 - return self.suiteClass(map(testCaseClass, testCaseNames))
525.511 -
525.512 - def loadTestsFromModule(self, module):
525.513 - """Return a suite of all tests cases contained in the given module"""
525.514 - tests = []
525.515 - for name in dir(module):
525.516 - obj = getattr(module, name)
525.517 - if (isinstance(obj, (type, types.ClassType)) and
525.518 - issubclass(obj, TestCase)):
525.519 - tests.append(self.loadTestsFromTestCase(obj))
525.520 - return self.suiteClass(tests)
525.521 -
525.522 - def loadTestsFromName(self, name, module=None):
525.523 - """Return a suite of all tests cases given a string specifier.
525.524 -
525.525 - The name may resolve either to a module, a test case class, a
525.526 - test method within a test case class, or a callable object which
525.527 - returns a TestCase or TestSuite instance.
525.528 -
525.529 - The method optionally resolves the names relative to a given module.
525.530 - """
525.531 - parts = name.split('.')
525.532 - if module is None:
525.533 - parts_copy = parts[:]
525.534 - while parts_copy:
525.535 - try:
525.536 - module = __import__('.'.join(parts_copy))
525.537 - break
525.538 - except ImportError:
525.539 - del parts_copy[-1]
525.540 - if not parts_copy: raise
525.541 - parts = parts[1:]
525.542 - obj = module
525.543 - for part in parts:
525.544 - parent, obj = obj, getattr(obj, part)
525.545 -
525.546 - if type(obj) == types.ModuleType:
525.547 - return self.loadTestsFromModule(obj)
525.548 - elif (isinstance(obj, (type, types.ClassType)) and
525.549 - issubclass(obj, TestCase)):
525.550 - return self.loadTestsFromTestCase(obj)
525.551 - elif type(obj) == types.UnboundMethodType:
525.552 - return parent(obj.__name__)
525.553 - elif isinstance(obj, TestSuite):
525.554 - return obj
525.555 - elif callable(obj):
525.556 - test = obj()
525.557 - if not isinstance(test, (TestCase, TestSuite)):
525.558 - raise ValueError, \
525.559 - "calling %s returned %s, not a test" % (obj,test)
525.560 - return test
525.561 - else:
525.562 - raise ValueError, "don't know how to make test from: %s" % obj
525.563 -
525.564 - def loadTestsFromNames(self, names, module=None):
525.565 - """Return a suite of all tests cases found using the given sequence
525.566 - of string specifiers. See 'loadTestsFromName()'.
525.567 - """
525.568 - suites = [self.loadTestsFromName(name, module) for name in names]
525.569 - return self.suiteClass(suites)
525.570 -
525.571 - def getTestCaseNames(self, testCaseClass):
525.572 - """Return a sorted sequence of method names found within testCaseClass
525.573 - """
525.574 - def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
525.575 - return attrname.startswith(prefix) and callable(getattr(testCaseClass, attrname))
525.576 - testFnNames = filter(isTestMethod, dir(testCaseClass))
525.577 - for baseclass in testCaseClass.__bases__:
525.578 - for testFnName in self.getTestCaseNames(baseclass):
525.579 - if testFnName not in testFnNames: # handle overridden methods
525.580 - testFnNames.append(testFnName)
525.581 - if self.sortTestMethodsUsing:
525.582 - testFnNames.sort(self.sortTestMethodsUsing)
525.583 - return testFnNames
525.584 -
525.585 -
525.586 -
525.587 -defaultTestLoader = TestLoader()
525.588 -
525.589 -
525.590 -##############################################################################
525.591 -# Patches for old functions: these functions should be considered obsolete
525.592 -##############################################################################
525.593 -
525.594 -def _makeLoader(prefix, sortUsing, suiteClass=None):
525.595 - loader = TestLoader()
525.596 - loader.sortTestMethodsUsing = sortUsing
525.597 - loader.testMethodPrefix = prefix
525.598 - if suiteClass: loader.suiteClass = suiteClass
525.599 - return loader
525.600 -
525.601 -def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
525.602 - return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
525.603 -
525.604 -def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
525.605 - return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
525.606 -
525.607 -def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
525.608 - return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
525.609 -
525.610 -
525.611 -##############################################################################
525.612 -# Text UI
525.613 -##############################################################################
525.614 -
525.615 -class _WritelnDecorator:
525.616 - """Used to decorate file-like objects with a handy 'writeln' method"""
525.617 - def __init__(self,stream):
525.618 - self.stream = stream
525.619 -
525.620 - def __getattr__(self, attr):
525.621 - return getattr(self.stream,attr)
525.622 -
525.623 - def writeln(self, arg=None):
525.624 - if arg: self.write(arg)
525.625 - self.write('\n') # text-mode streams translate to \r\n if needed
525.626 -
525.627 -
525.628 -class _TextTestResult(TestResult):
525.629 - """A test result class that can print formatted text results to a stream.
525.630 -
525.631 - Used by TextTestRunner.
525.632 - """
525.633 - separator1 = '=' * 70
525.634 - separator2 = '-' * 70
525.635 -
525.636 - def __init__(self, stream, descriptions, verbosity):
525.637 - TestResult.__init__(self)
525.638 - self.stream = stream
525.639 - self.showAll = verbosity > 1
525.640 - self.dots = verbosity == 1
525.641 - self.descriptions = descriptions
525.642 -
525.643 - def getDescription(self, test):
525.644 - if self.descriptions:
525.645 - return test.shortDescription() or str(test)
525.646 - else:
525.647 - return str(test)
525.648 -
525.649 - def startTest(self, test):
525.650 - TestResult.startTest(self, test)
525.651 - if self.showAll:
525.652 - self.stream.write(self.getDescription(test))
525.653 - self.stream.write(" ... ")
525.654 -
525.655 - def addSuccess(self, test):
525.656 - TestResult.addSuccess(self, test)
525.657 - if self.showAll:
525.658 - self.stream.writeln("ok")
525.659 - elif self.dots:
525.660 - self.stream.write('.')
525.661 -
525.662 - def addError(self, test, err):
525.663 - TestResult.addError(self, test, err)
525.664 - if self.showAll:
525.665 - self.stream.writeln("ERROR")
525.666 - elif self.dots:
525.667 - self.stream.write('E')
525.668 -
525.669 - def addFailure(self, test, err):
525.670 - TestResult.addFailure(self, test, err)
525.671 - if self.showAll:
525.672 - self.stream.writeln("FAIL")
525.673 - elif self.dots:
525.674 - self.stream.write('F')
525.675 -
525.676 - def printErrors(self):
525.677 - if self.dots or self.showAll:
525.678 - self.stream.writeln()
525.679 - self.printErrorList('ERROR', self.errors)
525.680 - self.printErrorList('FAIL', self.failures)
525.681 -
525.682 - def printErrorList(self, flavour, errors):
525.683 - for test, err in errors:
525.684 - self.stream.writeln(self.separator1)
525.685 - self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
525.686 - self.stream.writeln(self.separator2)
525.687 - self.stream.writeln("%s" % err)
525.688 -
525.689 -
525.690 -class TextTestRunner:
525.691 - """A test runner class that displays results in textual form.
525.692 -
525.693 - It prints out the names of tests as they are run, errors as they
525.694 - occur, and a summary of the results at the end of the test run.
525.695 - """
525.696 - def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
525.697 - self.stream = _WritelnDecorator(stream)
525.698 - self.descriptions = descriptions
525.699 - self.verbosity = verbosity
525.700 -
525.701 - def _makeResult(self):
525.702 - return _TextTestResult(self.stream, self.descriptions, self.verbosity)
525.703 -
525.704 - def run(self, test):
525.705 - "Run the given test case or test suite."
525.706 - result = self._makeResult()
525.707 - startTime = time.time()
525.708 - test(result)
525.709 - stopTime = time.time()
525.710 - timeTaken = stopTime - startTime
525.711 - result.printErrors()
525.712 - self.stream.writeln(result.separator2)
525.713 - run = result.testsRun
525.714 - self.stream.writeln("Ran %d test%s in %.3fs" %
525.715 - (run, run != 1 and "s" or "", timeTaken))
525.716 - self.stream.writeln()
525.717 - if not result.wasSuccessful():
525.718 - self.stream.write("FAILED (")
525.719 - failed, errored = map(len, (result.failures, result.errors))
525.720 - if failed:
525.721 - self.stream.write("failures=%d" % failed)
525.722 - if errored:
525.723 - if failed: self.stream.write(", ")
525.724 - self.stream.write("errors=%d" % errored)
525.725 - self.stream.writeln(")")
525.726 - else:
525.727 - self.stream.writeln("OK")
525.728 - return result
525.729 -
525.730 -
525.731 -
525.732 -##############################################################################
525.733 -# Facilities for running tests from the command line
525.734 -##############################################################################
525.735 -
525.736 -class TestProgram:
525.737 - """A command-line program that runs a set of tests; this is primarily
525.738 - for making test modules conveniently executable.
525.739 - """
525.740 - USAGE = """\
525.741 -Usage: %(progName)s [options] [test] [...]
525.742 -
525.743 -Options:
525.744 - -h, --help Show this message
525.745 - -v, --verbose Verbose output
525.746 - -q, --quiet Minimal output
525.747 -
525.748 -Examples:
525.749 - %(progName)s - run default set of tests
525.750 - %(progName)s MyTestSuite - run suite 'MyTestSuite'
525.751 - %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
525.752 - %(progName)s MyTestCase - run all 'test*' test methods
525.753 - in MyTestCase
525.754 -"""
525.755 - def __init__(self, module='__main__', defaultTest=None,
525.756 - argv=None, testRunner=None, testLoader=defaultTestLoader):
525.757 - if type(module) == type(''):
525.758 - self.module = __import__(module)
525.759 - for part in module.split('.')[1:]:
525.760 - self.module = getattr(self.module, part)
525.761 - else:
525.762 - self.module = module
525.763 - if argv is None:
525.764 - argv = sys.argv
525.765 - self.verbosity = 1
525.766 - self.defaultTest = defaultTest
525.767 - self.testRunner = testRunner
525.768 - self.testLoader = testLoader
525.769 - self.progName = os.path.basename(argv[0])
525.770 - self.parseArgs(argv)
525.771 - self.runTests()
525.772 -
525.773 - def usageExit(self, msg=None):
525.774 - if msg: print msg
525.775 - print self.USAGE % self.__dict__
525.776 - sys.exit(2)
525.777 -
525.778 - def parseArgs(self, argv):
525.779 - import getopt
525.780 - try:
525.781 - options, args = getopt.getopt(argv[1:], 'hHvq',
525.782 - ['help','verbose','quiet'])
525.783 - for opt, value in options:
525.784 - if opt in ('-h','-H','--help'):
525.785 - self.usageExit()
525.786 - if opt in ('-q','--quiet'):
525.787 - self.verbosity = 0
525.788 - if opt in ('-v','--verbose'):
525.789 - self.verbosity = 2
525.790 - if len(args) == 0 and self.defaultTest is None:
525.791 - self.test = self.testLoader.loadTestsFromModule(self.module)
525.792 - return
525.793 - if len(args) > 0:
525.794 - self.testNames = args
525.795 - else:
525.796 - self.testNames = (self.defaultTest,)
525.797 - self.createTests()
525.798 - except getopt.error, msg:
525.799 - self.usageExit(msg)
525.800 -
525.801 - def createTests(self):
525.802 - self.test = self.testLoader.loadTestsFromNames(self.testNames,
525.803 - self.module)
525.804 -
525.805 - def runTests(self):
525.806 - if self.testRunner is None:
525.807 - self.testRunner = TextTestRunner(verbosity=self.verbosity)
525.808 - result = self.testRunner.run(self.test)
525.809 - sys.exit(not result.wasSuccessful())
525.810 -
525.811 -main = TestProgram
525.812 -
525.813 -
525.814 -##############################################################################
525.815 -# Executing this module from the command line
525.816 -##############################################################################
525.817 -
525.818 -if __name__ == "__main__":
525.819 - main(module=None)
526.1 --- a/python.editor/test/unit/data/testfiles/unittest.py.indexed Sun Jan 04 13:11:53 2015 -0600
526.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
526.3 @@ -1,267 +0,0 @@
526.4 -
526.5 -
526.6 -Document 0
526.7 -Searchable Keys:
526.8 - class : FunctionTestCase
526.9 - class-ig : functiontestcase
526.10 - extends : TestCase
526.11 - in : unittest
526.12 - member : __description;D;|PRIVATE|;
526.13 - member : __init__;c;|CONSTRUCTOR|;self,testFunc,setUp,tearDown,description;
526.14 - member : __repr__;F;;self;
526.15 - member : __setUpFunc;D;|PRIVATE|;
526.16 - member : __str__;F;;self;
526.17 - member : __tearDownFunc;D;|PRIVATE|;
526.18 - member : __testFunc;D;|PRIVATE|;
526.19 - member : id;F;;self;
526.20 - member : runTest;F;;self;
526.21 - member : setUp;F;;self;
526.22 - member : shortDescription;F;;self;
526.23 - member : tearDown;F;;self;
526.24 -
526.25 -Not Searchable Keys:
526.26 -
526.27 -
526.28 -Document 1
526.29 -Searchable Keys:
526.30 - class : TestCase
526.31 - class-ig : testcase
526.32 - in : unittest
526.33 - member : __call__;F;;self,args,kwds;
526.34 - member : __init__;c;|CONSTRUCTOR|;self,methodName;
526.35 - member : __repr__;F;;self;
526.36 - member : __str__;F;;self;
526.37 - member : _exc_info;F;|PRIVATE|;self;
526.38 - member : _testMethodDoc;D;|PRIVATE|;
526.39 - member : _testMethodName;D;|PRIVATE|;
526.40 - member : assertAlmostEqual;F;;self,first,second,places,msg;
526.41 - member : assertAlmostEquals;F;;self,first,second,places,msg;
526.42 - member : assertEqual;F;;self,first,second,msg;
526.43 - member : assertEquals;F;;self,first,second,msg;
526.44 - member : assertFalse;F;;self,expr,msg;
526.45 - member : assertNotAlmostEqual;F;;self,first,second,places,msg;
526.46 - member : assertNotAlmostEquals;F;;self,first,second,places,msg;
526.47 - member : assertNotEqual;F;;self,first,second,msg;
526.48 - member : assertNotEquals;F;;self,first,second,msg;
526.49 - member : assertRaises;F;;self,excClass,callableObj,args,kwargs;
526.50 - member : assertTrue;F;;self,expr,msg;
526.51 - member : assert_;F;;self,expr,msg;
526.52 - member : countTestCases;F;;self;
526.53 - member : debug;F;;self;
526.54 - member : defaultTestResult;F;;self;
526.55 - member : fail;F;;self,msg;
526.56 - member : failIf;F;;self,expr,msg;
526.57 - member : failIfAlmostEqual;F;;self,first,second,places,msg;
526.58 - member : failIfEqual;F;;self,first,second,msg;
526.59 - member : failUnless;F;;self,expr,msg;
526.60 - member : failUnlessAlmostEqual;F;;self,first,second,places,msg;
526.61 - member : failUnlessEqual;F;;self,first,second,msg;
526.62 - member : failUnlessRaises;F;;self,excClass,callableObj,args,kwargs;
526.63 - member : failureException;D;;
526.64 - member : id;F;;self;
526.65 - member : run;F;;self,result;
526.66 - member : setUp;F;;self;
526.67 - member : shortDescription;F;;self;
526.68 - member : tearDown;F;;self;
526.69 -
526.70 -Not Searchable Keys:
526.71 -
526.72 -
526.73 -Document 2
526.74 -Searchable Keys:
526.75 - class : TestLoader
526.76 - class-ig : testloader
526.77 - in : unittest
526.78 - member : getTestCaseNames;F;;self,testCaseClass;
526.79 - member : loadTestsFromModule;F;;self,module;
526.80 - member : loadTestsFromName;F;;self,name,module;
526.81 - member : loadTestsFromNames;F;;self,names,module;
526.82 - member : loadTestsFromTestCase;F;;self,testCaseClass;
526.83 - member : sortTestMethodsUsing;D;;
526.84 - member : suiteClass;D;;
526.85 - member : testMethodPrefix;D;;
526.86 -
526.87 -Not Searchable Keys:
526.88 -
526.89 -
526.90 -Document 3
526.91 -Searchable Keys:
526.92 - class : TestProgram
526.93 - class-ig : testprogram
526.94 - in : unittest
526.95 - member : USAGE;D;|PRIVATE|;
526.96 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,module,defaultTest,argv,testRunner,testLoader;
526.97 - member : createTests;F;|PRIVATE|;self;
526.98 - member : defaultTest;D;;
526.99 - member : module;D;;
526.100 - member : parseArgs;F;|PRIVATE|;self,argv;
526.101 - member : progName;D;;
526.102 - member : runTests;F;|PRIVATE|;self;
526.103 - member : test;D;;
526.104 - member : testLoader;D;;
526.105 - member : testNames;D;;
526.106 - member : testRunner;D;;
526.107 - member : usageExit;F;|PRIVATE|;self,msg;
526.108 - member : verbosity;D;;
526.109 -
526.110 -Not Searchable Keys:
526.111 - clzattrs : ;|PRIVATE|;
526.112 -
526.113 -
526.114 -Document 4
526.115 -Searchable Keys:
526.116 - class : TestResult
526.117 - class-ig : testresult
526.118 - in : unittest
526.119 - member : __init__;c;|CONSTRUCTOR|;self;
526.120 - member : __repr__;F;;self;
526.121 - member : _count_relevant_tb_levels;F;|PRIVATE|;self,tb;
526.122 - member : _exc_info_to_string;F;|PRIVATE|;self,err,test;
526.123 - member : _is_relevant_tb_level;F;|PRIVATE|;self,tb;
526.124 - member : addError;F;;self,test,err;
526.125 - member : addFailure;F;;self,test,err;
526.126 - member : addSuccess;F;;self,test;
526.127 - member : errors;D;;
526.128 - member : failures;D;;
526.129 - member : shouldStop;D;;
526.130 - member : startTest;F;;self,test;
526.131 - member : stop;F;;self;
526.132 - member : stopTest;F;;self,test;
526.133 - member : testsRun;D;;
526.134 - member : wasSuccessful;F;;self;
526.135 -
526.136 -Not Searchable Keys:
526.137 -
526.138 -
526.139 -Document 5
526.140 -Searchable Keys:
526.141 - class : TestSuite
526.142 - class-ig : testsuite
526.143 - in : unittest
526.144 - member : __call__;F;;self,args,kwds;
526.145 - member : __init__;c;|CONSTRUCTOR|;self,tests;
526.146 - member : __iter__;F;;self;
526.147 - member : __repr__;F;;self;
526.148 - member : __str__;F;;self;
526.149 - member : _tests;D;|PRIVATE|;
526.150 - member : addTest;F;;self,test;
526.151 - member : addTests;F;;self,tests;
526.152 - member : countTestCases;F;;self;
526.153 - member : debug;F;;self;
526.154 - member : run;F;;self,result;
526.155 -
526.156 -Not Searchable Keys:
526.157 -
526.158 -
526.159 -Document 6
526.160 -Searchable Keys:
526.161 - class : TextTestRunner
526.162 - class-ig : texttestrunner
526.163 - in : unittest
526.164 - member : __init__;c;|CONSTRUCTOR|;self,stream,descriptions,verbosity;
526.165 - member : _makeResult;F;|PRIVATE|;self;
526.166 - member : descriptions;D;;
526.167 - member : run;F;;self,test;
526.168 - member : stream;D;;
526.169 - member : verbosity;D;;
526.170 -
526.171 -Not Searchable Keys:
526.172 -
526.173 -
526.174 -Document 7
526.175 -Searchable Keys:
526.176 - class : _TextTestResult
526.177 - class-ig : _texttestresult
526.178 - extends : TestResult
526.179 - in : unittest
526.180 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,stream,descriptions,verbosity;
526.181 - member : addError;F;|PRIVATE|;self,test,err;
526.182 - member : addFailure;F;|PRIVATE|;self,test,err;
526.183 - member : addSuccess;F;|PRIVATE|;self,test;
526.184 - member : descriptions;D;;
526.185 - member : dots;D;;
526.186 - member : getDescription;F;|PRIVATE|;self,test;
526.187 - member : printErrorList;F;|PRIVATE|;self,flavour,errors;
526.188 - member : printErrors;F;|PRIVATE|;self;
526.189 - member : separator1;D;|PRIVATE|;
526.190 - member : separator2;D;|PRIVATE|;
526.191 - member : showAll;D;;
526.192 - member : startTest;F;|PRIVATE|;self,test;
526.193 - member : stream;D;;
526.194 -
526.195 -Not Searchable Keys:
526.196 - clzattrs : ;|PRIVATE|;
526.197 -
526.198 -
526.199 -Document 8
526.200 -Searchable Keys:
526.201 - class : _WritelnDecorator
526.202 - class-ig : _writelndecorator
526.203 - in : unittest
526.204 - member : __getattr__;F;|PRIVATE|;self,attr;
526.205 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,stream;
526.206 - member : stream;D;;
526.207 - member : writeln;F;|PRIVATE|;self,arg;
526.208 -
526.209 -Not Searchable Keys:
526.210 - clzattrs : ;|PRIVATE|;
526.211 -
526.212 -
526.213 -Document 9
526.214 -Searchable Keys:
526.215 - class : main
526.216 - class-ig : main
526.217 - in : unittest
526.218 - member : USAGE;D;|PRIVATE|;
526.219 - member : __init__;c;|PRIVATE|CONSTRUCTOR|;self,module,defaultTest,argv,testRunner,testLoader;
526.220 - member : createTests;F;|PRIVATE|;self;
526.221 - member : defaultTest;D;;
526.222 - member : module;D;;
526.223 - member : parseArgs;F;|PRIVATE|;self,argv;
526.224 - member : progName;D;;
526.225 - member : runTests;F;|PRIVATE|;self;
526.226 - member : test;D;;
526.227 - member : testLoader;D;;
526.228 - member : testNames;D;;
526.229 - member : testRunner;D;;
526.230 - member : usageExit;F;|PRIVATE|;self,msg;
526.231 - member : verbosity;D;;
526.232 -
526.233 -Not Searchable Keys:
526.234 -
526.235 -
526.236 -Document 10
526.237 -Searchable Keys:
526.238 - item : False;D;|PRIVATE|;
526.239 - item : FunctionTestCase;C;;
526.240 - item : TestCase;C;;
526.241 - item : TestLoader;C;;
526.242 - item : TestProgram;C;|PRIVATE|;
526.243 - item : TestResult;C;;
526.244 - item : TestSuite;C;;
526.245 - item : TextTestRunner;C;;
526.246 - item : True;D;|PRIVATE|;
526.247 - item : _TextTestResult;C;|PRIVATE|;
526.248 - item : _WritelnDecorator;C;|PRIVATE|;
526.249 - item : __all__;D;;
526.250 - item : __author__;D;|PRIVATE|;
526.251 - item : __email__;D;|PRIVATE|;
526.252 - item : __metaclass__;D;|PRIVATE|;
526.253 - item : __unittest;D;|PRIVATE|;
526.254 - item : __version__;D;|PRIVATE|;
526.255 - item : _makeLoader;F;|PRIVATE|;prefix,sortUsing,suiteClass;
526.256 - item : _strclass;F;|PRIVATE|;cls;
526.257 - item : defaultTestLoader;D;;
526.258 - item : findTestCases;F;;module,prefix,sortUsing,suiteClass;
526.259 - item : getTestCaseNames;F;;testCaseClass,prefix,sortUsing;
526.260 - item : isinstance;F;|PRIVATE|;obj,clsinfo;
526.261 - item : main;C;;
526.262 - item : makeSuite;F;;testCaseClass,prefix,sortUsing,suiteClass;
526.263 - item : os;I;|PRIVATE|;
526.264 - item : sys;I;|PRIVATE|;
526.265 - item : time;I;|PRIVATE|;
526.266 - item : traceback;I;|PRIVATE|;
526.267 - item : types;I;|PRIVATE|;
526.268 - module : unittest
526.269 -
526.270 -Not Searchable Keys:
527.1 --- a/python.editor/test/unit/data/testfiles/unittest.py.scopes Sun Jan 04 13:11:53 2015 -0600
527.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
527.3 @@ -1,969 +0,0 @@
527.4 -=============================================
527.5 -<file-top>: Module : OffsetRange[22,29392>
527.6 -False [bound][private][data][read][node=Name]
527.7 -FunctionTestCase [bound][class][def][node=ClassDef]
527.8 -None [private][read][UNRESOLVED][node=Name]
527.9 -TestCase [bound][class][def][read][node=ClassDef]
527.10 -TestLoader [bound][class][def][read][called][node=ClassDef]
527.11 -TestProgram [bound][private][class][def][read][node=ClassDef]
527.12 -TestResult [bound][class][def][read][called][node=ClassDef]
527.13 -TestSuite [bound][class][def][read][node=ClassDef]
527.14 -TextTestRunner [bound][class][def][read][called][node=ClassDef]
527.15 -True [bound][private][data][read][node=Name]
527.16 -_TextTestResult [bound][private][class][def][read][called][node=ClassDef]
527.17 -_WritelnDecorator [bound][private][class][def][read][called][node=ClassDef]
527.18 -__all__ [bound][data][read][node=Name]
527.19 -__author__ [bound][private][data][node=Name]
527.20 -__email__ [bound][private][data][node=Name]
527.21 -__metaclass__ [bound][private][data][node=Name]
527.22 -__name__ [private][read][UNRESOLVED][node=Name]
527.23 -__unittest [bound][private][data][node=Name]
527.24 -__version__ [bound][private][data][node=Name]
527.25 -_makeLoader [bound][private][function][def][read][called][node=FunctionDef]
527.26 -_strclass [bound][private][function][def][read][called][node=FunctionDef]
527.27 -cmp [private][read][UNRESOLVED][node=Name]
527.28 -defaultTestLoader [bound][data][read][node=Name]
527.29 -findTestCases [bound][function][def][node=FunctionDef]
527.30 -getTestCaseNames [bound][function][def][node=FunctionDef]
527.31 -isinstance [bound][private][function][def][read][called][node=FunctionDef]
527.32 -main [bound][class][read][alias][called][node=ClassDef]
527.33 -makeSuite [bound][function][def][node=FunctionDef]
527.34 -os [bound][imported][private][data][read][node=Import]
527.35 -sys [bound][imported][private][data][read][node=Import]
527.36 -time [bound][imported][private][data][read][node=Import]
527.37 -traceback [bound][imported][private][data][read][node=Import]
527.38 -type [private][read][UNRESOLVED][node=Name]
527.39 -types [bound][imported][private][data][read][node=Import]
527.40 -
527.41 - =============================================
527.42 - isinstance: FunctionDef : OffsetRange[2570,3180>
527.43 - __builtin__ [bound][imported][private][data][read][node=Import]
527.44 - cls [bound][private][data][read][node=Name]
527.45 - clsinfo [bound][param][private][data][read][node=Name]
527.46 - list [free][private][read][node=Name]
527.47 - obj [bound][param][private][data][read][node=Name]
527.48 - tuple [free][private][read][node=Name]
527.49 - type [free][private][read][called][node=Name]
527.50 - types [free][private][read][node=Name]
527.51 -
527.52 - =============================================
527.53 - _strclass: FunctionDef : OffsetRange[3202,3275>
527.54 - cls [bound][param][private][data][read][node=Name]
527.55 -
527.56 - =============================================
527.57 - class TestResult: ClassDef : OffsetRange[3291,6032>
527.58 - __init__ [bound][function][def][node=FunctionDef]
527.59 - __repr__ [bound][function][def][node=FunctionDef]
527.60 - _count_relevant_tb_levels [bound][private][function][def][node=FunctionDef]
527.61 - _exc_info_to_string [bound][private][function][def][node=FunctionDef]
527.62 - _is_relevant_tb_level [bound][private][function][def][node=FunctionDef]
527.63 - addError [bound][function][def][node=FunctionDef]
527.64 - addFailure [bound][function][def][node=FunctionDef]
527.65 - addSuccess [bound][function][def][node=FunctionDef]
527.66 - startTest [bound][function][def][node=FunctionDef]
527.67 - stop [bound][function][def][node=FunctionDef]
527.68 - stopTest [bound][function][def][node=FunctionDef]
527.69 - wasSuccessful [bound][function][def][node=FunctionDef]
527.70 - ------ Attributes ---------------------------------------
527.71 - errors : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.72 - failures : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.73 - shouldStop : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.74 - testsRun : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.75 -
527.76 - =============================================
527.77 - __init__: FunctionDef : OffsetRange[3797,3927>
527.78 - self [bound][param][data][read][node=Name]
527.79 -
527.80 - =============================================
527.81 - startTest: FunctionDef : OffsetRange[3928,4057>
527.82 - self [bound][param][data][read][node=Name]
527.83 - test [bound][param][data][unused][node=Name]
527.84 - ------ Attributes ---------------------------------------
527.85 - testsRun : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.86 -
527.87 - =============================================
527.88 - stopTest: FunctionDef : OffsetRange[4058,4151>
527.89 - self [bound][param][data][unused][node=Name]
527.90 - test [bound][param][data][unused][node=Name]
527.91 -
527.92 - =============================================
527.93 - addError: FunctionDef : OffsetRange[4152,4383>
527.94 - err [bound][param][data][read][node=Name]
527.95 - self [bound][param][data][read][node=Name]
527.96 - test [bound][param][data][read][node=Name]
527.97 - ------ Attributes ---------------------------------------
527.98 - _exc_info_to_string : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
527.99 - errors : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.100 -
527.101 - =============================================
527.102 - addFailure: FunctionDef : OffsetRange[4384,4610>
527.103 - err [bound][param][data][read][node=Name]
527.104 - self [bound][param][data][read][node=Name]
527.105 - test [bound][param][data][read][node=Name]
527.106 - ------ Attributes ---------------------------------------
527.107 - _exc_info_to_string : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
527.108 - failures : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.109 -
527.110 - =============================================
527.111 - addSuccess: FunctionDef : OffsetRange[4611,4712>
527.112 - self [bound][param][data][unused][node=Name]
527.113 - test [bound][param][data][unused][node=Name]
527.114 -
527.115 - =============================================
527.116 - wasSuccessful: FunctionDef : OffsetRange[4713,4858>
527.117 - len [free][read][called][node=Name]
527.118 - self [bound][param][data][read][node=Name]
527.119 - ------ Attributes ---------------------------------------
527.120 - errors : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.121 - failures : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.122 -
527.123 - =============================================
527.124 - stop: FunctionDef : OffsetRange[4859,4963>
527.125 - True [free][read][node=Name]
527.126 - self [bound][param][data][read][node=Name]
527.127 -
527.128 - =============================================
527.129 - _exc_info_to_string: FunctionDef : OffsetRange[4964,5546>
527.130 - err [bound][param][data][read][node=Name]
527.131 - exctype [bound][data][read][node=Name]
527.132 - length [bound][data][read][node=Name]
527.133 - self [bound][param][data][read][node=Name]
527.134 - tb [bound][data][read][node=Name]
527.135 - test [bound][param][data][read][node=Name]
527.136 - traceback [free][read][node=Name]
527.137 - value [bound][data][read][node=Name]
527.138 - ------ Attributes ---------------------------------------
527.139 - _count_relevant_tb_levels : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
527.140 - _is_relevant_tb_level : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
527.141 -
527.142 - =============================================
527.143 - _is_relevant_tb_level: FunctionDef : OffsetRange[5547,5647>
527.144 - self [bound][param][data][unused][node=Name]
527.145 - tb [bound][param][data][read][node=Name]
527.146 -
527.147 - =============================================
527.148 - _count_relevant_tb_levels: FunctionDef : OffsetRange[5648,5843>
527.149 - length [bound][data][read][node=Name]
527.150 - self [bound][param][data][read][node=Name]
527.151 - tb [bound][param][data][read][node=Name]
527.152 - ------ Attributes ---------------------------------------
527.153 - _is_relevant_tb_level : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
527.154 -
527.155 - =============================================
527.156 - __repr__: FunctionDef : OffsetRange[5844,6032>
527.157 - _strclass [free][read][called][node=Name]
527.158 - len [free][read][called][node=Name]
527.159 - self [bound][param][data][read][node=Name]
527.160 - ------ Attributes ---------------------------------------
527.161 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.162 - errors : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.163 - failures : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.164 - testsRun : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.165 -
527.166 - =============================================
527.167 - class TestCase: ClassDef : OffsetRange[6032,13849>
527.168 - AssertionError [free][read][node=Name]
527.169 - None [free][read][node=Name]
527.170 - __call__ [bound][function][def][node=FunctionDef]
527.171 - __init__ [bound][function][def][node=FunctionDef]
527.172 - __repr__ [bound][function][def][node=FunctionDef]
527.173 - __str__ [bound][function][def][node=FunctionDef]
527.174 - _exc_info [bound][private][function][def][node=FunctionDef]
527.175 - assertAlmostEqual [bound][function][alias][node=FunctionDef]
527.176 - assertAlmostEquals [bound][function][alias][node=FunctionDef]
527.177 - assertEqual [bound][function][alias][node=FunctionDef]
527.178 - assertEquals [bound][function][alias][node=FunctionDef]
527.179 - assertFalse [bound][function][alias][node=FunctionDef]
527.180 - assertNotAlmostEqual [bound][function][alias][node=FunctionDef]
527.181 - assertNotAlmostEquals [bound][function][alias][node=FunctionDef]
527.182 - assertNotEqual [bound][function][alias][node=FunctionDef]
527.183 - assertNotEquals [bound][function][alias][node=FunctionDef]
527.184 - assertRaises [bound][function][alias][node=FunctionDef]
527.185 - assertTrue [bound][function][alias][node=FunctionDef]
527.186 - assert_ [bound][function][alias][node=FunctionDef]
527.187 - countTestCases [bound][function][def][node=FunctionDef]
527.188 - debug [bound][function][def][node=FunctionDef]
527.189 - defaultTestResult [bound][function][def][node=FunctionDef]
527.190 - fail [bound][function][def][node=FunctionDef]
527.191 - failIf [bound][function][def][read][node=FunctionDef]
527.192 - failIfAlmostEqual [bound][function][def][read][node=FunctionDef]
527.193 - failIfEqual [bound][function][def][read][node=FunctionDef]
527.194 - failUnless [bound][function][def][read][node=FunctionDef]
527.195 - failUnlessAlmostEqual [bound][function][def][read][node=FunctionDef]
527.196 - failUnlessEqual [bound][function][def][read][node=FunctionDef]
527.197 - failUnlessRaises [bound][function][def][read][node=FunctionDef]
527.198 - failureException [bound][data][node=Name]
527.199 - id [bound][function][def][node=FunctionDef]
527.200 - run [bound][function][def][node=FunctionDef]
527.201 - setUp [bound][function][def][node=FunctionDef]
527.202 - shortDescription [bound][function][def][node=FunctionDef]
527.203 - tearDown [bound][function][def][node=FunctionDef]
527.204 - ------ Attributes ---------------------------------------
527.205 - _testMethodDoc : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.206 - _testMethodName : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.207 -
527.208 - =============================================
527.209 - __init__: FunctionDef : OffsetRange[7252,7817>
527.210 - AttributeError [free][read][node=Name]
527.211 - ValueError [free][read][node=Name]
527.212 - getattr [free][read][called][node=Name]
527.213 - methodName [bound][param][data][read][node=Name]
527.214 - self [bound][param][data][read][node=Name]
527.215 - testMethod [bound][data][read][node=Name]
527.216 - ------ Attributes ---------------------------------------
527.217 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.218 -
527.219 - =============================================
527.220 - setUp: FunctionDef : OffsetRange[7818,7928>
527.221 - self [bound][param][data][unused][node=Name]
527.222 -
527.223 - =============================================
527.224 - tearDown: FunctionDef : OffsetRange[7929,8042>
527.225 - self [bound][param][data][unused][node=Name]
527.226 -
527.227 - =============================================
527.228 - countTestCases: FunctionDef : OffsetRange[8043,8090>
527.229 - self [bound][param][data][unused][node=Name]
527.230 -
527.231 - =============================================
527.232 - defaultTestResult: FunctionDef : OffsetRange[8091,8152>
527.233 - TestResult [free][read][called][node=Name]
527.234 - self [bound][param][data][unused][node=Name]
527.235 -
527.236 - =============================================
527.237 - shortDescription: FunctionDef : OffsetRange[8153,8521>
527.238 - None [free][read][node=Name]
527.239 - doc [bound][data][read][node=Name]
527.240 - self [bound][param][data][read][node=Name]
527.241 - ------ Attributes ---------------------------------------
527.242 - _testMethodDoc : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
527.243 -
527.244 - =============================================
527.245 - id: FunctionDef : OffsetRange[8522,8615>
527.246 - _strclass [free][read][called][node=Name]
527.247 - self [bound][param][data][read][node=Name]
527.248 - ------ Attributes ---------------------------------------
527.249 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.250 - _testMethodName : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
527.251 -
527.252 - =============================================
527.253 - __str__: FunctionDef : OffsetRange[8616,8716>
527.254 - _strclass [free][read][called][node=Name]
527.255 - self [bound][param][data][read][node=Name]
527.256 - ------ Attributes ---------------------------------------
527.257 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.258 - _testMethodName : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
527.259 -
527.260 - =============================================
527.261 - __repr__: FunctionDef : OffsetRange[8717,8846>
527.262 - _strclass [free][read][called][node=Name]
527.263 - self [bound][param][data][read][node=Name]
527.264 - ------ Attributes ---------------------------------------
527.265 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.266 - _testMethodName : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
527.267 -
527.268 - =============================================
527.269 - run: FunctionDef : OffsetRange[8847,9885>
527.270 - False [free][read][node=Name]
527.271 - KeyboardInterrupt [free][read][node=Name]
527.272 - None [free][read][node=Name]
527.273 - True [free][read][node=Name]
527.274 - getattr [free][read][called][node=Name]
527.275 - ok [bound][data][read][node=Name]
527.276 - result [bound][param][data][read][node=Name]
527.277 - self [bound][param][data][read][node=Name]
527.278 - testMethod [bound][data][read][called][node=Name]
527.279 - ------ Attributes ---------------------------------------
527.280 - _exc_info : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
527.281 - _testMethodName : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
527.282 - defaultTestResult : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.283 - failureException : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.284 - setUp : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.285 - tearDown : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.286 -
527.287 - =============================================
527.288 - __call__: FunctionDef : OffsetRange[9886,9964>
527.289 - args [bound][param][data][read][node=arguments]
527.290 - kwds [bound][param][data][read][node=arguments]
527.291 - self [bound][param][data][read][node=Name]
527.292 - ------ Attributes ---------------------------------------
527.293 - run : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.294 -
527.295 - =============================================
527.296 - debug: FunctionDef : OffsetRange[9965,10146>
527.297 - getattr [free][read][called][node=Name]
527.298 - self [bound][param][data][read][node=Name]
527.299 - ------ Attributes ---------------------------------------
527.300 - _testMethodName : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
527.301 - setUp : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.302 - tearDown : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.303 -
527.304 - =============================================
527.305 - _exc_info: FunctionDef : OffsetRange[10147,10555>
527.306 - exctype [bound][data][read][node=Name]
527.307 - excvalue [bound][data][read][node=Name]
527.308 - self [bound][param][data][unused][node=Name]
527.309 - sys [free][read][node=Name]
527.310 - tb [bound][data][read][node=Name]
527.311 -
527.312 - =============================================
527.313 - fail: FunctionDef : OffsetRange[10556,10683>
527.314 - msg [bound][param][data][read][node=Name]
527.315 - self [bound][param][data][read][node=Name]
527.316 - ------ Attributes ---------------------------------------
527.317 - failureException : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.318 -
527.319 - =============================================
527.320 - failIf: FunctionDef : OffsetRange[10684,10823>
527.321 - expr [bound][param][data][read][node=Name]
527.322 - msg [bound][param][data][read][node=Name]
527.323 - self [bound][param][data][read][node=Name]
527.324 - ------ Attributes ---------------------------------------
527.325 - failureException : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.326 -
527.327 - =============================================
527.328 - failUnless: FunctionDef : OffsetRange[10824,10979>
527.329 - expr [bound][param][data][read][node=Name]
527.330 - msg [bound][param][data][read][node=Name]
527.331 - self [bound][param][data][read][node=Name]
527.332 - ------ Attributes ---------------------------------------
527.333 - failureException : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.334 -
527.335 - =============================================
527.336 - failUnlessRaises: FunctionDef : OffsetRange[10980,11722>
527.337 - args [bound][param][data][read][node=arguments]
527.338 - callableObj [bound][param][data][read][called][node=Name]
527.339 - excClass [bound][param][data][read][node=Name]
527.340 - excName [bound][data][read][node=Name]
527.341 - hasattr [free][read][called][node=Name]
527.342 - kwargs [bound][param][data][read][node=arguments]
527.343 - self [bound][param][data][read][node=Name]
527.344 - str [free][read][called][node=Name]
527.345 - ------ Attributes ---------------------------------------
527.346 - failureException : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.347 -
527.348 - =============================================
527.349 - failUnlessEqual: FunctionDef : OffsetRange[11723,12016>
527.350 - first [bound][param][data][read][node=Name]
527.351 - msg [bound][param][data][read][node=Name]
527.352 - second [bound][param][data][read][node=Name]
527.353 - self [bound][param][data][read][node=Name]
527.354 - ------ Attributes ---------------------------------------
527.355 - failureException : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.356 -
527.357 - =============================================
527.358 - failIfEqual: FunctionDef : OffsetRange[12017,12300>
527.359 - first [bound][param][data][read][node=Name]
527.360 - msg [bound][param][data][read][node=Name]
527.361 - second [bound][param][data][read][node=Name]
527.362 - self [bound][param][data][read][node=Name]
527.363 - ------ Attributes ---------------------------------------
527.364 - failureException : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.365 -
527.366 - =============================================
527.367 - failUnlessAlmostEqual: FunctionDef : OffsetRange[12301,12888>
527.368 - first [bound][param][data][read][node=Name]
527.369 - msg [bound][param][data][read][node=Name]
527.370 - places [bound][param][data][read][node=Name]
527.371 - round [free][read][called][node=Name]
527.372 - second [bound][param][data][read][node=Name]
527.373 - self [bound][param][data][read][node=Name]
527.374 - ------ Attributes ---------------------------------------
527.375 - failureException : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.376 -
527.377 - =============================================
527.378 - failIfAlmostEqual: FunctionDef : OffsetRange[12889,13508>
527.379 - first [bound][param][data][read][node=Name]
527.380 - msg [bound][param][data][read][node=Name]
527.381 - places [bound][param][data][read][node=Name]
527.382 - round [free][read][called][node=Name]
527.383 - second [bound][param][data][read][node=Name]
527.384 - self [bound][param][data][read][node=Name]
527.385 - ------ Attributes ---------------------------------------
527.386 - failureException : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.387 -
527.388 - =============================================
527.389 - class TestSuite: ClassDef : OffsetRange[13849,15757>
527.390 - __call__ [bound][function][def][node=FunctionDef]
527.391 - __init__ [bound][function][def][node=FunctionDef]
527.392 - __iter__ [bound][function][def][node=FunctionDef]
527.393 - __repr__ [bound][function][def][read][node=FunctionDef]
527.394 - __str__ [bound][function][alias][node=FunctionDef]
527.395 - addTest [bound][function][def][node=FunctionDef]
527.396 - addTests [bound][function][def][node=FunctionDef]
527.397 - countTestCases [bound][function][def][node=FunctionDef]
527.398 - debug [bound][function][def][node=FunctionDef]
527.399 - run [bound][function][def][node=FunctionDef]
527.400 - ------ Attributes ---------------------------------------
527.401 - _tests : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.402 -
527.403 - =============================================
527.404 - __init__: FunctionDef : OffsetRange[14316,14404>
527.405 - self [bound][param][data][read][node=Name]
527.406 - tests [bound][param][data][read][node=Name]
527.407 - ------ Attributes ---------------------------------------
527.408 - addTests : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.409 -
527.410 - =============================================
527.411 - __repr__: FunctionDef : OffsetRange[14405,14503>
527.412 - _strclass [free][read][called][node=Name]
527.413 - self [bound][param][data][read][node=Name]
527.414 - ------ Attributes ---------------------------------------
527.415 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.416 - _tests : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
527.417 -
527.418 - =============================================
527.419 - __iter__: FunctionDef : OffsetRange[14528,14585>
527.420 - iter [free][read][called][node=Name]
527.421 - self [bound][param][data][read][node=Name]
527.422 - ------ Attributes ---------------------------------------
527.423 - _tests : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
527.424 -
527.425 - =============================================
527.426 - countTestCases: FunctionDef : OffsetRange[14586,14731>
527.427 - cases [bound][data][read][node=Name]
527.428 - self [bound][param][data][read][node=Name]
527.429 - test [bound][data][read][node=Name]
527.430 - ------ Attributes ---------------------------------------
527.431 - _tests : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
527.432 -
527.433 - =============================================
527.434 - addTest: FunctionDef : OffsetRange[14732,15166>
527.435 - TestCase [free][read][node=Name]
527.436 - TestSuite [free][read][node=Name]
527.437 - TypeError [free][read][called][node=Name]
527.438 - callable [free][read][called][node=Name]
527.439 - isinstance [free][read][called][node=Name]
527.440 - issubclass [free][read][called][node=Name]
527.441 - self [bound][param][data][read][node=Name]
527.442 - test [bound][param][data][read][node=Name]
527.443 - type [free][read][node=Name]
527.444 - types [free][read][node=Name]
527.445 - ------ Attributes ---------------------------------------
527.446 - _tests : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
527.447 -
527.448 - =============================================
527.449 - addTests: FunctionDef : OffsetRange[15167,15378>
527.450 - TypeError [free][read][called][node=Name]
527.451 - basestring [free][read][node=Name]
527.452 - isinstance [free][read][called][node=Name]
527.453 - self [bound][param][data][read][node=Name]
527.454 - test [bound][data][read][node=Name]
527.455 - tests [bound][param][data][read][node=Name]
527.456 - ------ Attributes ---------------------------------------
527.457 - addTest : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.458 -
527.459 - =============================================
527.460 - run: FunctionDef : OffsetRange[15379,15542>
527.461 - result [bound][param][data][read][node=Name]
527.462 - self [bound][param][data][read][node=Name]
527.463 - test [bound][data][read][called][node=Name]
527.464 - ------ Attributes ---------------------------------------
527.465 - _tests : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
527.466 -
527.467 - =============================================
527.468 - __call__: FunctionDef : OffsetRange[15543,15621>
527.469 - args [bound][param][data][read][node=arguments]
527.470 - kwds [bound][param][data][read][node=arguments]
527.471 - self [bound][param][data][read][node=Name]
527.472 - ------ Attributes ---------------------------------------
527.473 - run : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.474 -
527.475 - =============================================
527.476 - debug: FunctionDef : OffsetRange[15622,15757>
527.477 - self [bound][param][data][read][node=Name]
527.478 - test [bound][data][read][node=Name]
527.479 - ------ Attributes ---------------------------------------
527.480 - _tests : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
527.481 -
527.482 - =============================================
527.483 - class FunctionTestCase: ClassDef : OffsetRange[15757,17312>
527.484 - None [free][read][node=Name]
527.485 - __init__ [bound][function][def][node=FunctionDef]
527.486 - __repr__ [bound][function][def][node=FunctionDef]
527.487 - __str__ [bound][function][def][node=FunctionDef]
527.488 - id [bound][function][def][node=FunctionDef]
527.489 - runTest [bound][function][def][node=FunctionDef]
527.490 - setUp [bound][function][def][node=FunctionDef]
527.491 - shortDescription [bound][function][def][node=FunctionDef]
527.492 - tearDown [bound][function][def][node=FunctionDef]
527.493 - ------ Attributes ---------------------------------------
527.494 - __description : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.495 - __setUpFunc : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.496 - __tearDownFunc : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.497 - __testFunc : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.498 -
527.499 - =============================================
527.500 - __init__: FunctionDef : OffsetRange[16134,16410>
527.501 - TestCase [free][read][node=Name]
527.502 - description [bound][param][data][read][node=Name]
527.503 - self [bound][param][data][read][node=Name]
527.504 - setUp [bound][param][data][read][node=Name]
527.505 - tearDown [bound][param][data][read][node=Name]
527.506 - testFunc [bound][param][data][read][node=Name]
527.507 - ------ Attributes ---------------------------------------
527.508 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.509 -
527.510 - =============================================
527.511 - setUp: FunctionDef : OffsetRange[16411,16504>
527.512 - None [free][read][node=Name]
527.513 - self [bound][param][data][read][node=Name]
527.514 - ------ Attributes ---------------------------------------
527.515 - __setUpFunc : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
527.516 -
527.517 - =============================================
527.518 - tearDown: FunctionDef : OffsetRange[16505,16607>
527.519 - None [free][read][node=Name]
527.520 - self [bound][param][data][read][node=Name]
527.521 - ------ Attributes ---------------------------------------
527.522 - __tearDownFunc : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
527.523 -
527.524 - =============================================
527.525 - runTest: FunctionDef : OffsetRange[16608,16657>
527.526 - self [bound][param][data][read][node=Name]
527.527 - ------ Attributes ---------------------------------------
527.528 - __testFunc : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
527.529 -
527.530 - =============================================
527.531 - id: FunctionDef : OffsetRange[16658,16716>
527.532 - self [bound][param][data][read][node=Name]
527.533 - ------ Attributes ---------------------------------------
527.534 - __testFunc : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
527.535 -
527.536 - =============================================
527.537 - __str__: FunctionDef : OffsetRange[16717,16821>
527.538 - _strclass [free][read][called][node=Name]
527.539 - self [bound][param][data][read][node=Name]
527.540 - ------ Attributes ---------------------------------------
527.541 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.542 - __testFunc : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
527.543 -
527.544 - =============================================
527.545 - __repr__: FunctionDef : OffsetRange[16822,16927>
527.546 - _strclass [free][read][called][node=Name]
527.547 - self [bound][param][data][read][node=Name]
527.548 - ------ Attributes ---------------------------------------
527.549 - __class__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.550 - __testFunc : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
527.551 -
527.552 - =============================================
527.553 - shortDescription: FunctionDef : OffsetRange[16928,17312>
527.554 - None [free][read][node=Name]
527.555 - doc [bound][data][read][node=Name]
527.556 - self [bound][param][data][read][node=Name]
527.557 - ------ Attributes ---------------------------------------
527.558 - __description : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
527.559 - __testFunc : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
527.560 -
527.561 - =============================================
527.562 - class TestLoader: ClassDef : OffsetRange[17312,21193>
527.563 - None [free][read][node=Name]
527.564 - TestSuite [free][read][node=Name]
527.565 - cmp [free][read][node=Name]
527.566 - getTestCaseNames [bound][function][def][node=FunctionDef]
527.567 - loadTestsFromModule [bound][function][def][node=FunctionDef]
527.568 - loadTestsFromName [bound][function][def][node=FunctionDef]
527.569 - loadTestsFromNames [bound][function][def][node=FunctionDef]
527.570 - loadTestsFromTestCase [bound][function][def][node=FunctionDef]
527.571 - sortTestMethodsUsing [bound][data][node=Name]
527.572 - suiteClass [bound][data][node=Name]
527.573 - testMethodPrefix [bound][data][node=Name]
527.574 -
527.575 - =============================================
527.576 - loadTestsFromTestCase: FunctionDef : OffsetRange[17553,18085>
527.577 - TestSuite [free][read][node=Name]
527.578 - TypeError [free][read][called][node=Name]
527.579 - hasattr [free][read][called][node=Name]
527.580 - issubclass [free][read][called][node=Name]
527.581 - map [free][read][called][node=Name]
527.582 - self [bound][param][data][read][node=Name]
527.583 - testCaseClass [bound][param][data][read][node=Name]
527.584 - testCaseNames [bound][data][read][node=Name]
527.585 - ------ Attributes ---------------------------------------
527.586 - getTestCaseNames : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.587 - suiteClass : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.588 -
527.589 - =============================================
527.590 - loadTestsFromModule: FunctionDef : OffsetRange[18086,18504>
527.591 - TestCase [free][read][node=Name]
527.592 - dir [free][read][called][node=Name]
527.593 - getattr [free][read][called][node=Name]
527.594 - isinstance [free][read][called][node=Name]
527.595 - issubclass [free][read][called][node=Name]
527.596 - module [bound][param][data][read][node=Name]
527.597 - name [bound][data][read][node=Name]
527.598 - obj [bound][data][read][node=Name]
527.599 - self [bound][param][data][read][node=Name]
527.600 - tests [bound][data][read][node=Name]
527.601 - type [free][read][node=Name]
527.602 - types [free][read][node=Name]
527.603 - ------ Attributes ---------------------------------------
527.604 - loadTestsFromTestCase : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.605 - suiteClass : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.606 -
527.607 - =============================================
527.608 - loadTestsFromName: FunctionDef : OffsetRange[18505,20125>
527.609 - ImportError [free][read][node=Name]
527.610 - None [free][read][node=Name]
527.611 - TestCase [free][read][node=Name]
527.612 - TestSuite [free][read][node=Name]
527.613 - ValueError [free][read][node=Name]
527.614 - __import__ [free][read][called][node=Name]
527.615 - callable [free][read][called][node=Name]
527.616 - getattr [free][read][called][node=Name]
527.617 - isinstance [free][read][called][node=Name]
527.618 - issubclass [free][read][called][node=Name]
527.619 - module [bound][param][data][read][node=Name]
527.620 - name [bound][param][data][read][node=Name]
527.621 - obj [bound][data][read][called][node=Name]
527.622 - parent [bound][data][read][called][node=Name]
527.623 - part [bound][data][read][node=Name]
527.624 - parts [bound][data][read][node=Name]
527.625 - parts_copy [bound][data][read][node=Name]
527.626 - self [bound][param][data][read][node=Name]
527.627 - test [bound][data][read][node=Name]
527.628 - type [free][read][called][node=Name]
527.629 - types [free][read][node=Name]
527.630 - ------ Attributes ---------------------------------------
527.631 - loadTestsFromModule : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.632 - loadTestsFromTestCase : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.633 -
527.634 - =============================================
527.635 - loadTestsFromNames: FunctionDef : OffsetRange[20126,20438>
527.636 - _[565_18] [bound][private][data][unused][node=ListComp]
527.637 - module [bound][param][data][read][node=Name]
527.638 - name [bound][data][read][node=Name]
527.639 - names [bound][param][data][read][node=Name]
527.640 - self [bound][param][data][read][node=Name]
527.641 - suites [bound][data][read][node=Name]
527.642 - ------ Attributes ---------------------------------------
527.643 - loadTestsFromName : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.644 - suiteClass : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.645 -
527.646 - =============================================
527.647 - getTestCaseNames: FunctionDef : OffsetRange[20439,21193>
527.648 - baseclass [bound][data][read][node=Name]
527.649 - callable [free][node=null]
527.650 - dir [free][read][called][node=Name]
527.651 - filter [free][read][called][node=Name]
527.652 - getattr [free][node=null]
527.653 - isTestMethod [bound][function][def][read][node=FunctionDef]
527.654 - self [bound][param][data][read][node=Name]
527.655 - testCaseClass [bound][param][data][read][node=Name]
527.656 - testFnName [bound][data][read][node=Name]
527.657 - testFnNames [bound][data][read][node=Name]
527.658 - ---------------------------------------------
527.659 - inner_free: {callable=PRESENT, getattr=PRESENT}
527.660 - ------ Attributes ---------------------------------------
527.661 - getTestCaseNames : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.662 - sortTestMethodsUsing : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.663 - testMethodPrefix : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.664 -
527.665 - =============================================
527.666 - isTestMethod: FunctionDef : OffsetRange[20581,20769>
527.667 - attrname [bound][param][data][read][node=Name]
527.668 - callable [free][read][called][node=Name]
527.669 - getattr [free][read][called][node=Name]
527.670 - prefix [bound][param][data][read][node=Name]
527.671 - testCaseClass [bound][param][data][read][node=Name]
527.672 -
527.673 - =============================================
527.674 - _makeLoader: FunctionDef : OffsetRange[21462,21691>
527.675 - TestLoader [free][private][read][called][node=Name]
527.676 - loader [bound][private][data][read][node=Name]
527.677 - prefix [bound][param][private][data][read][node=Name]
527.678 - sortUsing [bound][param][private][data][read][node=Name]
527.679 - suiteClass [bound][param][private][data][read][node=Name]
527.680 -
527.681 - =============================================
527.682 - getTestCaseNames: FunctionDef : OffsetRange[21691,21826>
527.683 - _makeLoader [free][read][called][node=Name]
527.684 - prefix [bound][param][data][read][node=Name]
527.685 - sortUsing [bound][param][data][read][node=Name]
527.686 - testCaseClass [bound][param][data][read][node=Name]
527.687 -
527.688 - =============================================
527.689 - makeSuite: FunctionDef : OffsetRange[21826,22000>
527.690 - _makeLoader [free][read][called][node=Name]
527.691 - prefix [bound][param][data][read][node=Name]
527.692 - sortUsing [bound][param][data][read][node=Name]
527.693 - suiteClass [bound][param][data][read][node=Name]
527.694 - testCaseClass [bound][param][data][read][node=Name]
527.695 -
527.696 - =============================================
527.697 - findTestCases: FunctionDef : OffsetRange[22000,22332>
527.698 - _makeLoader [free][read][called][node=Name]
527.699 - module [bound][param][data][read][node=Name]
527.700 - prefix [bound][param][data][read][node=Name]
527.701 - sortUsing [bound][param][data][read][node=Name]
527.702 - suiteClass [bound][param][data][read][node=Name]
527.703 -
527.704 - =============================================
527.705 - class _WritelnDecorator: ClassDef : OffsetRange[22332,22708>
527.706 - None [free][private][read][node=Name]
527.707 - __getattr__ [bound][private][function][def][node=FunctionDef]
527.708 - __init__ [bound][private][function][def][node=FunctionDef]
527.709 - writeln [bound][private][function][def][node=FunctionDef]
527.710 - ------ Attributes ---------------------------------------
527.711 - stream : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.712 -
527.713 - =============================================
527.714 - __init__: FunctionDef : OffsetRange[22436,22496>
527.715 - self [bound][param][private][data][read][node=Name]
527.716 - stream [bound][param][private][data][read][node=Name]
527.717 -
527.718 - =============================================
527.719 - __getattr__: FunctionDef : OffsetRange[22497,22571>
527.720 - attr [bound][param][private][data][read][node=Name]
527.721 - getattr [free][private][read][called][node=Name]
527.722 - self [bound][param][private][data][read][node=Name]
527.723 - ------ Attributes ---------------------------------------
527.724 - stream : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.725 -
527.726 - =============================================
527.727 - writeln: FunctionDef : OffsetRange[22572,22708>
527.728 - arg [bound][param][private][data][read][node=Name]
527.729 - self [bound][param][private][data][read][node=Name]
527.730 - ------ Attributes ---------------------------------------
527.731 - write : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.732 -
527.733 - =============================================
527.734 - class _TextTestResult: ClassDef : OffsetRange[22708,24622>
527.735 - __init__ [bound][private][function][def][node=FunctionDef]
527.736 - addError [bound][private][function][def][node=FunctionDef]
527.737 - addFailure [bound][private][function][def][node=FunctionDef]
527.738 - addSuccess [bound][private][function][def][node=FunctionDef]
527.739 - getDescription [bound][private][function][def][node=FunctionDef]
527.740 - printErrorList [bound][private][function][def][node=FunctionDef]
527.741 - printErrors [bound][private][function][def][node=FunctionDef]
527.742 - separator1 [bound][private][data][node=Name]
527.743 - separator2 [bound][private][data][node=Name]
527.744 - startTest [bound][private][function][def][node=FunctionDef]
527.745 - ------ Attributes ---------------------------------------
527.746 - descriptions : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.747 - dots : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.748 - showAll : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.749 - stream : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.750 -
527.751 - =============================================
527.752 - __init__: FunctionDef : OffsetRange[22915,23148>
527.753 - TestResult [free][private][read][node=Name]
527.754 - descriptions [bound][param][private][data][read][node=Name]
527.755 - self [bound][param][private][data][read][node=Name]
527.756 - stream [bound][param][private][data][read][node=Name]
527.757 - verbosity [bound][param][private][data][read][node=Name]
527.758 - ------ Attributes ---------------------------------------
527.759 - __init__ : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.760 -
527.761 - =============================================
527.762 - getDescription: FunctionDef : OffsetRange[23149,23314>
527.763 - self [bound][param][private][data][read][node=Name]
527.764 - str [free][private][read][called][node=Name]
527.765 - test [bound][param][private][data][read][node=Name]
527.766 - ------ Attributes ---------------------------------------
527.767 - descriptions : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.768 -
527.769 - =============================================
527.770 - startTest: FunctionDef : OffsetRange[23315,23508>
527.771 - TestResult [free][private][read][node=Name]
527.772 - self [bound][param][private][data][read][node=Name]
527.773 - test [bound][param][private][data][read][node=Name]
527.774 - ------ Attributes ---------------------------------------
527.775 - getDescription : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.776 - showAll : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.777 - startTest : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.778 - stream : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.779 -
527.780 - =============================================
527.781 - addSuccess: FunctionDef : OffsetRange[23509,23705>
527.782 - TestResult [free][private][read][node=Name]
527.783 - self [bound][param][private][data][read][node=Name]
527.784 - test [bound][param][private][data][read][node=Name]
527.785 - ------ Attributes ---------------------------------------
527.786 - addSuccess : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.787 - dots : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.788 - showAll : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.789 - stream : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.790 -
527.791 - =============================================
527.792 - addError: FunctionDef : OffsetRange[23706,23911>
527.793 - TestResult [free][private][read][node=Name]
527.794 - err [bound][param][private][data][read][node=Name]
527.795 - self [bound][param][private][data][read][node=Name]
527.796 - test [bound][param][private][data][read][node=Name]
527.797 - ------ Attributes ---------------------------------------
527.798 - addError : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.799 - dots : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.800 - showAll : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.801 - stream : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.802 -
527.803 - =============================================
527.804 - addFailure: FunctionDef : OffsetRange[23912,24120>
527.805 - TestResult [free][private][read][node=Name]
527.806 - err [bound][param][private][data][read][node=Name]
527.807 - self [bound][param][private][data][read][node=Name]
527.808 - test [bound][param][private][data][read][node=Name]
527.809 - ------ Attributes ---------------------------------------
527.810 - addFailure : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.811 - dots : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.812 - showAll : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.813 - stream : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.814 -
527.815 - =============================================
527.816 - printErrors: FunctionDef : OffsetRange[24121,24321>
527.817 - self [bound][param][private][data][read][node=Name]
527.818 - ------ Attributes ---------------------------------------
527.819 - dots : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.820 - errors : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.821 - failures : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.822 - printErrorList : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.823 - showAll : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.824 - stream : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.825 -
527.826 - =============================================
527.827 - printErrorList: FunctionDef : OffsetRange[24322,24622>
527.828 - err [bound][private][data][read][node=Name]
527.829 - errors [bound][param][private][data][read][node=Name]
527.830 - flavour [bound][param][private][data][read][node=Name]
527.831 - self [bound][param][private][data][read][node=Name]
527.832 - test [bound][private][data][read][node=Name]
527.833 - ------ Attributes ---------------------------------------
527.834 - getDescription : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.835 - separator1 : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.836 - separator2 : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.837 - stream : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.838 -
527.839 - =============================================
527.840 - class TextTestRunner: ClassDef : OffsetRange[24622,26349>
527.841 - __init__ [bound][function][def][node=FunctionDef]
527.842 - _makeResult [bound][private][function][def][node=FunctionDef]
527.843 - run [bound][function][def][node=FunctionDef]
527.844 - sys [free][read][node=Name]
527.845 - ------ Attributes ---------------------------------------
527.846 - descriptions : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.847 - stream : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.848 - verbosity : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.849 -
527.850 - =============================================
527.851 - __init__: FunctionDef : OffsetRange[24860,25056>
527.852 - _WritelnDecorator [free][read][called][node=Name]
527.853 - descriptions [bound][param][data][read][node=Name]
527.854 - self [bound][param][data][read][node=Name]
527.855 - stream [bound][param][data][read][node=Name]
527.856 - verbosity [bound][param][data][read][node=Name]
527.857 -
527.858 - =============================================
527.859 - _makeResult: FunctionDef : OffsetRange[25057,25163>
527.860 - _TextTestResult [free][read][called][node=Name]
527.861 - self [bound][param][data][read][node=Name]
527.862 - ------ Attributes ---------------------------------------
527.863 - descriptions : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.864 - stream : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.865 - verbosity : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.866 -
527.867 - =============================================
527.868 - run: FunctionDef : OffsetRange[25164,26349>
527.869 - errored [bound][data][read][node=Name]
527.870 - failed [bound][data][read][node=Name]
527.871 - len [free][read][node=Name]
527.872 - map [free][read][called][node=Name]
527.873 - result [bound][data][read][node=Name]
527.874 - run [bound][data][read][node=Name]
527.875 - self [bound][param][data][read][node=Name]
527.876 - startTime [bound][data][read][node=Name]
527.877 - stopTime [bound][data][read][node=Name]
527.878 - test [bound][param][data][read][called][node=Name]
527.879 - time [free][read][node=Name]
527.880 - timeTaken [bound][data][read][node=Name]
527.881 - ------ Attributes ---------------------------------------
527.882 - _makeResult : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
527.883 - stream : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.884 -
527.885 - =============================================
527.886 - class TestProgram: ClassDef : OffsetRange[26349,29118>
527.887 - None [free][private][read][node=Name]
527.888 - USAGE [bound][private][data][node=Name]
527.889 - __init__ [bound][private][function][def][node=FunctionDef]
527.890 - createTests [bound][private][function][def][node=FunctionDef]
527.891 - defaultTestLoader [free][private][read][node=Name]
527.892 - parseArgs [bound][private][function][def][node=FunctionDef]
527.893 - runTests [bound][private][function][def][node=FunctionDef]
527.894 - usageExit [bound][private][function][def][node=FunctionDef]
527.895 - ------ Attributes ---------------------------------------
527.896 - defaultTest : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.897 - module : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.898 - progName : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.899 - test : SymInfo[8195 0 0][bound][func-global][data][member][generator][unused][node=Attribute]
527.900 - testLoader : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.901 - testNames : SymInfo[8195 0 0][bound][func-global][data][member][generator][unused][node=Attribute]
527.902 - testRunner : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.903 - verbosity : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
527.904 -
527.905 - =============================================
527.906 - __init__: FunctionDef : OffsetRange[27056,27721>
527.907 - None [free][private][read][node=Name]
527.908 - __import__ [free][private][read][called][node=Name]
527.909 - argv [bound][param][private][data][read][node=Name]
527.910 - defaultTest [bound][param][private][data][read][node=Name]
527.911 - getattr [free][private][read][called][node=Name]
527.912 - module [bound][param][private][data][read][node=Name]
527.913 - os [free][private][read][node=Name]
527.914 - part [bound][private][data][read][node=Name]
527.915 - self [bound][param][private][data][read][node=Name]
527.916 - sys [free][private][read][node=Name]
527.917 - testLoader [bound][param][private][data][read][node=Name]
527.918 - testRunner [bound][param][private][data][read][node=Name]
527.919 - type [free][private][read][called][node=Name]
527.920 - ------ Attributes ---------------------------------------
527.921 - module : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.922 - parseArgs : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.923 - runTests : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.924 -
527.925 - =============================================
527.926 - usageExit: FunctionDef : OffsetRange[27722,27844>
527.927 - msg [bound][param][private][data][read][node=Name]
527.928 - self [bound][param][private][data][read][node=Name]
527.929 - sys [free][private][read][node=Name]
527.930 - ------ Attributes ---------------------------------------
527.931 - USAGE : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.932 - __dict__ : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.933 -
527.934 - =============================================
527.935 - parseArgs: FunctionDef : OffsetRange[27845,28729>
527.936 - None [free][private][read][node=Name]
527.937 - args [bound][private][data][read][node=Name]
527.938 - argv [bound][param][private][data][read][node=Name]
527.939 - getopt [bound][imported][private][data][read][node=Import]
527.940 - len [free][private][read][called][node=Name]
527.941 - msg [bound][private][data][read][node=Name]
527.942 - opt [bound][private][data][read][node=Name]
527.943 - options [bound][private][data][read][node=Name]
527.944 - self [bound][param][private][data][read][node=Name]
527.945 - value [bound][private][data][unused][node=Name]
527.946 - ------ Attributes ---------------------------------------
527.947 - createTests : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.948 - defaultTest : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.949 - module : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.950 - testLoader : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.951 - usageExit : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
527.952 -
527.953 - =============================================
527.954 - createTests: FunctionDef : OffsetRange[28730,28896>
527.955 - self [bound][param][private][data][read][node=Name]
527.956 - ------ Attributes ---------------------------------------
527.957 - module : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.958 - testLoader : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.959 - testNames : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.960 -
527.961 - =============================================
527.962 - runTests: FunctionDef : OffsetRange[28897,29118>
527.963 - None [free][private][read][node=Name]
527.964 - TextTestRunner [free][private][read][called][node=Name]
527.965 - result [bound][private][data][read][node=Name]
527.966 - self [bound][param][private][data][read][node=Name]
527.967 - sys [free][private][read][node=Name]
527.968 - ------ Attributes ---------------------------------------
527.969 - test : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.970 - testRunner : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.971 - verbosity : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
527.972 -
528.1 --- a/python.editor/test/unit/data/testfiles/unresolved.py Sun Jan 04 13:11:53 2015 -0600
528.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
528.3 @@ -1,12 +0,0 @@
528.4 -import binascii
528.5 -
528.6 -print "Whatever"
528.7 -putenv("hehe", "hoho")
528.8 -sys.displayhook("value")
528.9 -zip = ZipFile()
528.10 -
528.11 -def foo(x=None):
528.12 - pass
528.13 -
528.14 -binascii.a2b_hex("0xff")
528.15 -
529.1 --- a/python.editor/test/unit/data/testfiles/unresolved.py.scopes Sun Jan 04 13:11:53 2015 -0600
529.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
529.3 @@ -1,14 +0,0 @@
529.4 -=============================================
529.5 -<file-top>: Module : OffsetRange[0,150>
529.6 -None [read][UNRESOLVED][node=Name]
529.7 -ZipFile [read][called][UNRESOLVED][node=Name]
529.8 -binascii [bound][imported][data][read][node=Import]
529.9 -foo [bound][function][def][node=FunctionDef]
529.10 -putenv [read][called][UNRESOLVED][node=Name]
529.11 -sys [read][UNRESOLVED][node=Name]
529.12 -zip [bound][data][node=Name]
529.13 -
529.14 - =============================================
529.15 - foo: FunctionDef : OffsetRange[99,126>
529.16 - x [bound][param][data][unused][node=Name]
529.17 -
530.1 --- a/python.editor/test/unit/data/testfiles/unresolved.py.testUnresolvedHints.hints Sun Jan 04 13:11:53 2015 -0600
530.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
530.3 @@ -1,12 +0,0 @@
530.4 -putenv("hehe", "hoho")
530.5 -------
530.6 -HINT:Undefined name "putenv"
530.7 -FIX:Import os: putenv(key,value)
530.8 -sys.displayhook("value")
530.9 ----
530.10 -HINT:Undefined name "sys"
530.11 -FIX:Import sys
530.12 -zip = ZipFile()
530.13 - -------
530.14 -HINT:Undefined name "ZipFile"
530.15 -FIX:Import zipfile: ZipFile
531.1 --- a/python.editor/test/unit/data/testfiles/unresolved2.py Sun Jan 04 13:11:53 2015 -0600
531.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
531.3 @@ -1,3 +0,0 @@
531.4 -from zipfile import *
531.5 -ZipFile
531.6 -
532.1 --- a/python.editor/test/unit/data/testfiles/unresolved3.py Sun Jan 04 13:11:53 2015 -0600
532.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
532.3 @@ -1,5 +0,0 @@
532.4 -if __name__ == "__main__":
532.5 - print "Hello"
532.6 -print __doc__
532.7 -print __builtins__
532.8 -
533.1 --- a/python.editor/test/unit/data/testfiles/unresolved4.py Sun Jan 04 13:11:53 2015 -0600
533.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
533.3 @@ -1,10 +0,0 @@
533.4 -if (true):
533.5 - pass
533.6 -if (false):
533.7 - pass
533.8 -x = 0
533.9 -if (x == null):
533.10 - pass
533.11 -if (x == nil):
533.12 - pass
533.13 -
534.1 --- a/python.editor/test/unit/data/testfiles/unresolved4.py.testUnresolvedHints4.hints Sun Jan 04 13:11:53 2015 -0600
534.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
534.3 @@ -1,12 +0,0 @@
534.4 -if (true):
534.5 - ------
534.6 -HINT:Undefined name "true" - did you mean "True" ?
534.7 -if (false):
534.8 - -------
534.9 -HINT:Undefined name "false" - did you mean "False" ?
534.10 -if (x == null):
534.11 - ----
534.12 -HINT:Undefined name "null" - did you mean "None" ?
534.13 -if (x == nil):
534.14 - ---
534.15 -HINT:Undefined name "nil" - did you mean "None" ?
535.1 --- a/python.editor/test/unit/data/testfiles/unresolved5.py Sun Jan 04 13:11:53 2015 -0600
535.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
535.3 @@ -1,2 +0,0 @@
535.4 -from sys import *
535.5 -exc_info()
536.1 --- a/python.editor/test/unit/data/testfiles/unresolved6.py Sun Jan 04 13:11:53 2015 -0600
536.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
536.3 @@ -1,9 +0,0 @@
536.4 -def toplevel():
536.5 - if false:
536.6 - raise ValuError("toplevel")
536.7 -
536.8 -class WikiPage():
536.9 - def get(self, page_name):
536.10 - if true:
536.11 - raise ValuError("get")
536.12 -
537.1 --- a/python.editor/test/unit/data/testfiles/unresolved6.py.testUnresolvedHints6.hints Sun Jan 04 13:11:53 2015 -0600
537.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
537.3 @@ -1,12 +0,0 @@
537.4 - if false:
537.5 - -----
537.6 -HINT:Undefined name "false" - did you mean "False" ?
537.7 - raise ValuError("toplevel")
537.8 - ---------
537.9 -HINT:Undefined name "ValuError"
537.10 - if true:
537.11 - ----
537.12 -HINT:Undefined name "true" - did you mean "True" ?
537.13 - raise ValuError("get")
537.14 - ---------
537.15 -HINT:Undefined name "ValuError"
538.1 --- a/python.editor/test/unit/data/testfiles/unresolvedattributes.py Sun Jan 04 13:11:53 2015 -0600
538.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
538.3 @@ -1,7 +0,0 @@
538.4 -class TestUnresolved :
538.5 - def __init__(self) :
538.6 - self.defined = "defined"
538.7 -
538.8 - def useAttr(self):
538.9 - print self.defined # OK
538.10 - print self.undefined # KO
538.11 \ No newline at end of file
539.1 --- a/python.editor/test/unit/data/testfiles/unresolvedattributes.py.testUnresolvedAttribute.hints Sun Jan 04 13:11:53 2015 -0600
539.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
539.3 @@ -1,3 +0,0 @@
539.4 - print self.undefined # KO
539.5 - --------------
539.6 -HINT:Undefined attribute "self.undefined"
540.1 --- a/python.editor/test/unit/data/testfiles/unresolvedparents.py Sun Jan 04 13:11:53 2015 -0600
540.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
540.3 @@ -1,31 +0,0 @@
540.4 -from socket import SocketType
540.5 -import bdb
540.6 -
540.7 -class GoodParent :
540.8 - """ simply a good top parent"""
540.9 - pass
540.10 -
540.11 -class GoodChild( GoodParent ):
540.12 - """ good inherit """
540.13 - pass
540.14 -
540.15 -class BadChild( BadParent ):
540.16 - """inherit from inexisting parent"""
540.17 - pass
540.18 -
540.19 -class GoodImportedFrom( SocketType ):
540.20 - """ inherit from a from imported class"""
540.21 - pass
540.22 -
540.23 -class GoodImported( bdb.Bdb ):
540.24 - """ inherit from an imported public module """
540.25 - pass
540.26 -
540.27 -class BadImported( undefined.Undefined ):
540.28 - """ inherit from bad module bad class """
540.29 - pass
540.30 -
540.31 -
540.32 -class BadImported2( pdb.Pdb ): # import missing
540.33 - """ inherit from non imported module """
540.34 - pass
540.35 \ No newline at end of file
541.1 --- a/python.editor/test/unit/data/testfiles/unresolvedparents.py.testUnresolvedParent.hints Sun Jan 04 13:11:53 2015 -0600
541.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
541.3 @@ -1,9 +0,0 @@
541.4 -class BadChild( BadParent ):
541.5 - ---------
541.6 -HINT:Inheriting from undefined parent class "BadParent"
541.7 -class BadImported( undefined.Undefined ):
541.8 - -------------------
541.9 -HINT:Inheriting from undefined parent class "undefined.Undefined"
541.10 -class BadImported2( pdb.Pdb ): # import missing
541.11 - -------
541.12 -HINT:Inheriting from undefined parent class "pdb.Pdb"
542.1 --- a/python.editor/test/unit/data/testfiles/unusedimports1.py Sun Jan 04 13:11:53 2015 -0600
542.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
542.3 @@ -1,22 +0,0 @@
542.4 -"""
542.5 -Test
542.6 -"""
542.7 -import math as _math
542.8 -import time as _time
542.9 -import sys
542.10 -import urimport
542.11 -import extract1b
542.12 -from foo import Sym1, Sym2
542.13 -from bar import Sym3
542.14 -from bar import Sym4
542.15 -from foo import Sym5, Sym6
542.16 -from foo import Sym7, Sym8
542.17 -
542.18 -
542.19 -sys.excepthook()
542.20 -_time.isused()
542.21 -Sym2()
542.22 -Sym3()
542.23 -Sym5()
542.24 -Sym6()
542.25 -
543.1 --- a/python.editor/test/unit/data/testfiles/unusedimports1.py.scopes Sun Jan 04 13:11:53 2015 -0600
543.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
543.3 @@ -1,16 +0,0 @@
543.4 -=============================================
543.5 -<file-top>: Module : OffsetRange[0,283>
543.6 -Sym1 [bound][imported][data][node=ImportFrom]
543.7 -Sym2 [bound][imported][data][read][called][node=ImportFrom]
543.8 -Sym3 [bound][imported][data][read][called][node=ImportFrom]
543.9 -Sym4 [bound][imported][data][node=ImportFrom]
543.10 -Sym5 [bound][imported][data][read][called][node=ImportFrom]
543.11 -Sym6 [bound][imported][data][read][called][node=ImportFrom]
543.12 -Sym7 [bound][imported][data][node=ImportFrom]
543.13 -Sym8 [bound][imported][data][node=ImportFrom]
543.14 -_math [bound][imported][private][data][node=Import]
543.15 -_time [bound][imported][private][data][read][node=Import]
543.16 -extract1b [bound][imported][data][node=Import]
543.17 -sys [bound][imported][data][read][node=Import]
543.18 -urimport [bound][imported][data][node=Import]
543.19 -
544.1 --- a/python.editor/test/unit/data/testfiles/unusedimports1.py.testFix1.fixed Sun Jan 04 13:11:53 2015 -0600
544.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
544.3 @@ -1,21 +0,0 @@
544.4 -"""
544.5 -Test
544.6 -"""
544.7 -import math as _math
544.8 -import time as _time
544.9 -import sys
544.10 -import extract1b
544.11 -from foo import Sym1, Sym2
544.12 -from bar import Sym3
544.13 -from bar import Sym4
544.14 -from foo import Sym5, Sym6
544.15 -from foo import Sym7, Sym8
544.16 -
544.17 -
544.18 -sys.excepthook()
544.19 -_time.isused()
544.20 -Sym2()
544.21 -Sym3()
544.22 -Sym5()
544.23 -Sym6()
544.24 -
545.1 --- a/python.editor/test/unit/data/testfiles/unusedimports1.py.testFix2.fixed Sun Jan 04 13:11:53 2015 -0600
545.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
545.3 @@ -1,17 +0,0 @@
545.4 -"""
545.5 -Test
545.6 -"""
545.7 -import time as _time
545.8 -import sys
545.9 -from foo import Sym2
545.10 -from bar import Sym3
545.11 -from foo import Sym5, Sym6
545.12 -
545.13 -
545.14 -sys.excepthook()
545.15 -_time.isused()
545.16 -Sym2()
545.17 -Sym3()
545.18 -Sym5()
545.19 -Sym6()
545.20 -
546.1 --- a/python.editor/test/unit/data/testfiles/unusedimports1.py.testFix3.fixed Sun Jan 04 13:11:53 2015 -0600
546.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
546.3 @@ -1,26 +0,0 @@
546.4 -"""
546.5 -Test
546.6 -"""
546.7 -import math as _math
546.8 -import sys
546.9 -import time as _time
546.10 -
546.11 -from bar import Sym3
546.12 -from bar import Sym4
546.13 -import extract1b
546.14 -from foo import Sym1
546.15 -from foo import Sym2
546.16 -from foo import Sym5
546.17 -from foo import Sym6
546.18 -from foo import Sym7
546.19 -from foo import Sym8
546.20 -import urimport
546.21 -
546.22 -
546.23 -sys.excepthook()
546.24 -_time.isused()
546.25 -Sym2()
546.26 -Sym3()
546.27 -Sym5()
546.28 -Sym6()
546.29 -
547.1 --- a/python.editor/test/unit/data/testfiles/unusedimports1.py.testFix4.fixed Sun Jan 04 13:11:53 2015 -0600
547.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
547.3 @@ -1,22 +0,0 @@
547.4 -"""
547.5 -Test
547.6 -"""
547.7 -import math as _math
547.8 -import time as _time
547.9 -import sys
547.10 -import urimport
547.11 -import extract1b
547.12 -from foo import Sym2
547.13 -from bar import Sym3
547.14 -from bar import Sym4
547.15 -from foo import Sym5, Sym6
547.16 -from foo import Sym7, Sym8
547.17 -
547.18 -
547.19 -sys.excepthook()
547.20 -_time.isused()
547.21 -Sym2()
547.22 -Sym3()
547.23 -Sym5()
547.24 -Sym6()
547.25 -
548.1 --- a/python.editor/test/unit/data/testfiles/unusedimports1.py.testHints.hints Sun Jan 04 13:11:53 2015 -0600
548.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
548.3 @@ -1,36 +0,0 @@
548.4 -import math as _math
548.5 ---------------------
548.6 -HINT:Unused Import
548.7 -FIX:Remove Unused Import
548.8 -FIX:Remove All Unused Imports
548.9 -FIX:Clean up and Organize Imports
548.10 -import urimport
548.11 ----------------
548.12 -HINT:Unused Import
548.13 -FIX:Remove Unused Import
548.14 -FIX:Remove All Unused Imports
548.15 -FIX:Clean up and Organize Imports
548.16 -import extract1b
548.17 -----------------
548.18 -HINT:Unused Import
548.19 -FIX:Remove Unused Import
548.20 -FIX:Remove All Unused Imports
548.21 -FIX:Clean up and Organize Imports
548.22 -from foo import Sym1, Sym2
548.23 ---------------------------
548.24 -HINT:Some symbols are unused ([Sym1])
548.25 -FIX:Remove [Sym1] from import
548.26 -FIX:Remove All Unused Imports
548.27 -FIX:Clean up and Organize Imports
548.28 -from bar import Sym4
548.29 ---------------------
548.30 -HINT:Unused Import
548.31 -FIX:Remove Unused Import
548.32 -FIX:Remove All Unused Imports
548.33 -FIX:Clean up and Organize Imports
548.34 -from foo import Sym7, Sym8
548.35 ---------------------------
548.36 -HINT:Unused Import
548.37 -FIX:Remove Unused Import
548.38 -FIX:Remove All Unused Imports
548.39 -FIX:Clean up and Organize Imports
549.1 --- a/python.editor/test/unit/data/testfiles/unusedimports2.py Sun Jan 04 13:11:53 2015 -0600
549.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
549.3 @@ -1,11 +0,0 @@
549.4 -"""
549.5 -Test
549.6 -"""
549.7 -import math as _math
549.8 -import time as _time
549.9 -import sys, os, four
549.10 -import urimport
549.11 -import extract1b
549.12 -
549.13 -sys.foo()
549.14 -
550.1 --- a/python.editor/test/unit/data/testfiles/unusedimports2.py.testFix5.fixed Sun Jan 04 13:11:53 2015 -0600
550.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
550.3 @@ -1,11 +0,0 @@
550.4 -"""
550.5 -Test
550.6 -"""
550.7 -import math as _math
550.8 -import time as _time
550.9 -import sys,
550.10 -import urimport
550.11 -import extract1b
550.12 -
550.13 -sys.foo()
550.14 -
551.1 --- a/python.editor/test/unit/data/testfiles/unusedimports3.py Sun Jan 04 13:11:53 2015 -0600
551.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
551.3 @@ -1,3 +0,0 @@
551.4 -import operator
551.5 -abs()
551.6 -
552.1 --- a/python.editor/test/unit/data/testfiles/unusedimports3.py.testNoHints2.hints Sun Jan 04 13:11:53 2015 -0600
552.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
552.3 @@ -1,6 +0,0 @@
552.4 -import operator
552.5 ----------------
552.6 -HINT:Unused Import
552.7 -FIX:Remove Unused Import
552.8 -FIX:Remove All Unused Imports
552.9 -FIX:Clean up and Organize Imports
553.1 --- a/python.editor/test/unit/data/testfiles/zipfile.py Sun Jan 04 13:11:53 2015 -0600
553.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
553.3 @@ -1,900 +0,0 @@
553.4 -"""
553.5 -Read and write ZIP files.
553.6 -"""
553.7 -import struct, os, time, sys
553.8 -import binascii, cStringIO
553.9 -
553.10 -try:
553.11 - import zlib # We may need its compression method
553.12 -except ImportError:
553.13 - zlib = None
553.14 -
553.15 -__all__ = ["BadZipfile", "error", "ZIP_STORED", "ZIP_DEFLATED", "is_zipfile",
553.16 - "ZipInfo", "ZipFile", "PyZipFile", "LargeZipFile" ]
553.17 -
553.18 -class BadZipfile(Exception):
553.19 - pass
553.20 -
553.21 -
553.22 -class LargeZipFile(Exception):
553.23 - """
553.24 - Raised when writing a zipfile, the zipfile requires ZIP64 extensions
553.25 - and those extensions are disabled.
553.26 - """
553.27 -
553.28 -error = BadZipfile # The exception raised by this module
553.29 -
553.30 -ZIP64_LIMIT= (1 << 31) - 1
553.31 -
553.32 -# constants for Zip file compression methods
553.33 -ZIP_STORED = 0
553.34 -ZIP_DEFLATED = 8
553.35 -# Other ZIP compression methods not supported
553.36 -
553.37 -# Here are some struct module formats for reading headers
553.38 -structEndArchive = "<4s4H2LH" # 9 items, end of archive, 22 bytes
553.39 -stringEndArchive = "PK\005\006" # magic number for end of archive record
553.40 -structCentralDir = "<4s4B4HlLL5HLL"# 19 items, central directory, 46 bytes
553.41 -stringCentralDir = "PK\001\002" # magic number for central directory
553.42 -structFileHeader = "<4s2B4HlLL2H" # 12 items, file header record, 30 bytes
553.43 -stringFileHeader = "PK\003\004" # magic number for file header
553.44 -structEndArchive64Locator = "<4slql" # 4 items, locate Zip64 header, 20 bytes
553.45 -stringEndArchive64Locator = "PK\x06\x07" # magic token for locator header
553.46 -structEndArchive64 = "<4sqhhllqqqq" # 10 items, end of archive (Zip64), 56 bytes
553.47 -stringEndArchive64 = "PK\x06\x06" # magic token for Zip64 header
553.48 -
553.49 -
553.50 -# indexes of entries in the central directory structure
553.51 -_CD_SIGNATURE = 0
553.52 -_CD_CREATE_VERSION = 1
553.53 -_CD_CREATE_SYSTEM = 2
553.54 -_CD_EXTRACT_VERSION = 3
553.55 -_CD_EXTRACT_SYSTEM = 4 # is this meaningful?
553.56 -_CD_FLAG_BITS = 5
553.57 -_CD_COMPRESS_TYPE = 6
553.58 -_CD_TIME = 7
553.59 -_CD_DATE = 8
553.60 -_CD_CRC = 9
553.61 -_CD_COMPRESSED_SIZE = 10
553.62 -_CD_UNCOMPRESSED_SIZE = 11
553.63 -_CD_FILENAME_LENGTH = 12
553.64 -_CD_EXTRA_FIELD_LENGTH = 13
553.65 -_CD_COMMENT_LENGTH = 14
553.66 -_CD_DISK_NUMBER_START = 15
553.67 -_CD_INTERNAL_FILE_ATTRIBUTES = 16
553.68 -_CD_EXTERNAL_FILE_ATTRIBUTES = 17
553.69 -_CD_LOCAL_HEADER_OFFSET = 18
553.70 -
553.71 -# indexes of entries in the local file header structure
553.72 -_FH_SIGNATURE = 0
553.73 -_FH_EXTRACT_VERSION = 1
553.74 -_FH_EXTRACT_SYSTEM = 2 # is this meaningful?
553.75 -_FH_GENERAL_PURPOSE_FLAG_BITS = 3
553.76 -_FH_COMPRESSION_METHOD = 4
553.77 -_FH_LAST_MOD_TIME = 5
553.78 -_FH_LAST_MOD_DATE = 6
553.79 -_FH_CRC = 7
553.80 -_FH_COMPRESSED_SIZE = 8
553.81 -_FH_UNCOMPRESSED_SIZE = 9
553.82 -_FH_FILENAME_LENGTH = 10
553.83 -_FH_EXTRA_FIELD_LENGTH = 11
553.84 -
553.85 -def is_zipfile(filename):
553.86 - """Quickly see if file is a ZIP file by checking the magic number."""
553.87 - try:
553.88 - fpin = open(filename, "rb")
553.89 - endrec = _EndRecData(fpin)
553.90 - fpin.close()
553.91 - if endrec:
553.92 - return True # file has correct magic number
553.93 - except IOError:
553.94 - pass
553.95 - return False
553.96 -
553.97 -def _EndRecData64(fpin, offset, endrec):
553.98 - """
553.99 - Read the ZIP64 end-of-archive records and use that to update endrec
553.100 - """
553.101 - locatorSize = struct.calcsize(structEndArchive64Locator)
553.102 - fpin.seek(offset - locatorSize, 2)
553.103 - data = fpin.read(locatorSize)
553.104 - sig, diskno, reloff, disks = struct.unpack(structEndArchive64Locator, data)
553.105 - if sig != stringEndArchive64Locator:
553.106 - return endrec
553.107 -
553.108 - if diskno != 0 or disks != 1:
553.109 - raise BadZipfile("zipfiles that span multiple disks are not supported")
553.110 -
553.111 - # Assume no 'zip64 extensible data'
553.112 - endArchiveSize = struct.calcsize(structEndArchive64)
553.113 - fpin.seek(offset - locatorSize - endArchiveSize, 2)
553.114 - data = fpin.read(endArchiveSize)
553.115 - sig, sz, create_version, read_version, disk_num, disk_dir, \
553.116 - dircount, dircount2, dirsize, diroffset = \
553.117 - struct.unpack(structEndArchive64, data)
553.118 - if sig != stringEndArchive64:
553.119 - return endrec
553.120 -
553.121 - # Update the original endrec using data from the ZIP64 record
553.122 - endrec[1] = disk_num
553.123 - endrec[2] = disk_dir
553.124 - endrec[3] = dircount
553.125 - endrec[4] = dircount2
553.126 - endrec[5] = dirsize
553.127 - endrec[6] = diroffset
553.128 - return endrec
553.129 -
553.130 -
553.131 -def _EndRecData(fpin):
553.132 - """Return data from the "End of Central Directory" record, or None.
553.133 -
553.134 - The data is a list of the nine items in the ZIP "End of central dir"
553.135 - record followed by a tenth item, the file seek offset of this record."""
553.136 - fpin.seek(-22, 2) # Assume no archive comment.
553.137 - filesize = fpin.tell() + 22 # Get file size
553.138 - data = fpin.read()
553.139 - if data[0:4] == stringEndArchive and data[-2:] == "\000\000":
553.140 - endrec = struct.unpack(structEndArchive, data)
553.141 - endrec = list(endrec)
553.142 - endrec.append("") # Append the archive comment
553.143 - endrec.append(filesize - 22) # Append the record start offset
553.144 - if endrec[-4] == -1 or endrec[-4] == 0xffffffff:
553.145 - return _EndRecData64(fpin, -22, endrec)
553.146 - return endrec
553.147 - # Search the last END_BLOCK bytes of the file for the record signature.
553.148 - # The comment is appended to the ZIP file and has a 16 bit length.
553.149 - # So the comment may be up to 64K long. We limit the search for the
553.150 - # signature to a few Kbytes at the end of the file for efficiency.
553.151 - # also, the signature must not appear in the comment.
553.152 - END_BLOCK = min(filesize, 1024 * 4)
553.153 - fpin.seek(filesize - END_BLOCK, 0)
553.154 - data = fpin.read()
553.155 - start = data.rfind(stringEndArchive)
553.156 - if start >= 0: # Correct signature string was found
553.157 - endrec = struct.unpack(structEndArchive, data[start:start+22])
553.158 - endrec = list(endrec)
553.159 - comment = data[start+22:]
553.160 - if endrec[7] == len(comment): # Comment length checks out
553.161 - # Append the archive comment and start offset
553.162 - endrec.append(comment)
553.163 - endrec.append(filesize - END_BLOCK + start)
553.164 - if endrec[-4] == -1 or endrec[-4] == 0xffffffff:
553.165 - return _EndRecData64(fpin, - END_BLOCK + start, endrec)
553.166 - return endrec
553.167 - return # Error, return None
553.168 -
553.169 -
553.170 -class ZipInfo (object):
553.171 - """Class with attributes describing each file in the ZIP archive."""
553.172 -
553.173 - __slots__ = (
553.174 - 'orig_filename',
553.175 - 'filename',
553.176 - 'date_time',
553.177 - 'compress_type',
553.178 - 'comment',
553.179 - 'extra',
553.180 - 'create_system',
553.181 - 'create_version',
553.182 - 'extract_version',
553.183 - 'reserved',
553.184 - 'flag_bits',
553.185 - 'volume',
553.186 - 'internal_attr',
553.187 - 'external_attr',
553.188 - 'header_offset',
553.189 - 'CRC',
553.190 - 'compress_size',
553.191 - 'file_size',
553.192 - )
553.193 -
553.194 - def __init__(self, filename="NoName", date_time=(1980,1,1,0,0,0)):
553.195 - self.orig_filename = filename # Original file name in archive
553.196 -
553.197 - # Terminate the file name at the first null byte. Null bytes in file
553.198 - # names are used as tricks by viruses in archives.
553.199 - null_byte = filename.find(chr(0))
553.200 - if null_byte >= 0:
553.201 - filename = filename[0:null_byte]
553.202 - # This is used to ensure paths in generated ZIP files always use
553.203 - # forward slashes as the directory separator, as required by the
553.204 - # ZIP format specification.
553.205 - if os.sep != "/" and os.sep in filename:
553.206 - filename = filename.replace(os.sep, "/")
553.207 -
553.208 - self.filename = filename # Normalized file name
553.209 - self.date_time = date_time # year, month, day, hour, min, sec
553.210 - # Standard values:
553.211 - self.compress_type = ZIP_STORED # Type of compression for the file
553.212 - self.comment = "" # Comment for each file
553.213 - self.extra = "" # ZIP extra data
553.214 - if sys.platform == 'win32':
553.215 - self.create_system = 0 # System which created ZIP archive
553.216 - else:
553.217 - # Assume everything else is unix-y
553.218 - self.create_system = 3 # System which created ZIP archive
553.219 - self.create_version = 20 # Version which created ZIP archive
553.220 - self.extract_version = 20 # Version needed to extract archive
553.221 - self.reserved = 0 # Must be zero
553.222 - self.flag_bits = 0 # ZIP flag bits
553.223 - self.volume = 0 # Volume number of file header
553.224 - self.internal_attr = 0 # Internal attributes
553.225 - self.external_attr = 0 # External file attributes
553.226 - # Other attributes are set by class ZipFile:
553.227 - # header_offset Byte offset to the file header
553.228 - # CRC CRC-32 of the uncompressed file
553.229 - # compress_size Size of the compressed file
553.230 - # file_size Size of the uncompressed file
553.231 -
553.232 - def FileHeader(self):
553.233 - """Return the per-file header as a string."""
553.234 - dt = self.date_time
553.235 - dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
553.236 - dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
553.237 - if self.flag_bits & 0x08:
553.238 - # Set these to zero because we write them after the file data
553.239 - CRC = compress_size = file_size = 0
553.240 - else:
553.241 - CRC = self.CRC
553.242 - compress_size = self.compress_size
553.243 - file_size = self.file_size
553.244 -
553.245 - extra = self.extra
553.246 -
553.247 - if file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT:
553.248 - # File is larger than what fits into a 4 byte integer,
553.249 - # fall back to the ZIP64 extension
553.250 - fmt = '<hhqq'
553.251 - extra = extra + struct.pack(fmt,
553.252 - 1, struct.calcsize(fmt)-4, file_size, compress_size)
553.253 - file_size = 0xffffffff # -1
553.254 - compress_size = 0xffffffff # -1
553.255 - self.extract_version = max(45, self.extract_version)
553.256 - self.create_version = max(45, self.extract_version)
553.257 -
553.258 - header = struct.pack(structFileHeader, stringFileHeader,
553.259 - self.extract_version, self.reserved, self.flag_bits,
553.260 - self.compress_type, dostime, dosdate, CRC,
553.261 - compress_size, file_size,
553.262 - len(self.filename), len(extra))
553.263 - return header + self.filename + extra
553.264 -
553.265 - def _decodeExtra(self):
553.266 - # Try to decode the extra field.
553.267 - extra = self.extra
553.268 - unpack = struct.unpack
553.269 - while extra:
553.270 - tp, ln = unpack('<hh', extra[:4])
553.271 - if tp == 1:
553.272 - if ln >= 24:
553.273 - counts = unpack('<qqq', extra[4:28])
553.274 - elif ln == 16:
553.275 - counts = unpack('<qq', extra[4:20])
553.276 - elif ln == 8:
553.277 - counts = unpack('<q', extra[4:12])
553.278 - elif ln == 0:
553.279 - counts = ()
553.280 - else:
553.281 - raise RuntimeError, "Corrupt extra field %s"%(ln,)
553.282 -
553.283 - idx = 0
553.284 -
553.285 - # ZIP64 extension (large files and/or large archives)
553.286 - if self.file_size == -1 or self.file_size == 0xFFFFFFFFL:
553.287 - self.file_size = counts[idx]
553.288 - idx += 1
553.289 -
553.290 - if self.compress_size == -1 or self.compress_size == 0xFFFFFFFFL:
553.291 - self.compress_size = counts[idx]
553.292 - idx += 1
553.293 -
553.294 - if self.header_offset == -1 or self.header_offset == 0xffffffffL:
553.295 - old = self.header_offset
553.296 - self.header_offset = counts[idx]
553.297 - idx+=1
553.298 -
553.299 - extra = extra[ln+4:]
553.300 -
553.301 -
553.302 -class ZipFile:
553.303 - """ Class with methods to open, read, write, close, list zip files.
553.304 -
553.305 - z = ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=True)
553.306 -
553.307 - file: Either the path to the file, or a file-like object.
553.308 - If it is a path, the file will be opened and closed by ZipFile.
553.309 - mode: The mode can be either read "r", write "w" or append "a".
553.310 - compression: ZIP_STORED (no compression) or ZIP_DEFLATED (requires zlib).
553.311 - allowZip64: if True ZipFile will create files with ZIP64 extensions when
553.312 - needed, otherwise it will raise an exception when this would
553.313 - be necessary.
553.314 -
553.315 - """
553.316 -
553.317 - fp = None # Set here since __del__ checks it
553.318 -
553.319 - def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=False):
553.320 - """Open the ZIP file with mode read "r", write "w" or append "a"."""
553.321 - self._allowZip64 = allowZip64
553.322 - self._didModify = False
553.323 - if compression == ZIP_STORED:
553.324 - pass
553.325 - elif compression == ZIP_DEFLATED:
553.326 - if not zlib:
553.327 - raise RuntimeError,\
553.328 - "Compression requires the (missing) zlib module"
553.329 - else:
553.330 - raise RuntimeError, "That compression method is not supported"
553.331 - self.debug = 0 # Level of printing: 0 through 3
553.332 - self.NameToInfo = {} # Find file info given name
553.333 - self.filelist = [] # List of ZipInfo instances for archive
553.334 - self.compression = compression # Method of compression
553.335 - self.mode = key = mode.replace('b', '')[0]
553.336 -
553.337 - # Check if we were passed a file-like object
553.338 - if isinstance(file, basestring):
553.339 - self._filePassed = 0
553.340 - self.filename = file
553.341 - modeDict = {'r' : 'rb', 'w': 'wb', 'a' : 'r+b'}
553.342 - self.fp = open(file, modeDict[mode])
553.343 - else:
553.344 - self._filePassed = 1
553.345 - self.fp = file
553.346 - self.filename = getattr(file, 'name', None)
553.347 -
553.348 - if key == 'r':
553.349 - self._GetContents()
553.350 - elif key == 'w':
553.351 - pass
553.352 - elif key == 'a':
553.353 - try: # See if file is a zip file
553.354 - self._RealGetContents()
553.355 - # seek to start of directory and overwrite
553.356 - self.fp.seek(self.start_dir, 0)
553.357 - except BadZipfile: # file is not a zip file, just append
553.358 - self.fp.seek(0, 2)
553.359 - else:
553.360 - if not self._filePassed:
553.361 - self.fp.close()
553.362 - self.fp = None
553.363 - raise RuntimeError, 'Mode must be "r", "w" or "a"'
553.364 -
553.365 - def _GetContents(self):
553.366 - """Read the directory, making sure we close the file if the format
553.367 - is bad."""
553.368 - try:
553.369 - self._RealGetContents()
553.370 - except BadZipfile:
553.371 - if not self._filePassed:
553.372 - self.fp.close()
553.373 - self.fp = None
553.374 - raise
553.375 -
553.376 - def _RealGetContents(self):
553.377 - """Read in the table of contents for the ZIP file."""
553.378 - fp = self.fp
553.379 - endrec = _EndRecData(fp)
553.380 - if not endrec:
553.381 - raise BadZipfile, "File is not a zip file"
553.382 - if self.debug > 1:
553.383 - print endrec
553.384 - size_cd = endrec[5] # bytes in central directory
553.385 - offset_cd = endrec[6] # offset of central directory
553.386 - self.comment = endrec[8] # archive comment
553.387 - # endrec[9] is the offset of the "End of Central Dir" record
553.388 - if endrec[9] > ZIP64_LIMIT:
553.389 - x = endrec[9] - size_cd - 56 - 20
553.390 - else:
553.391 - x = endrec[9] - size_cd
553.392 - # "concat" is zero, unless zip was concatenated to another file
553.393 - concat = x - offset_cd
553.394 - if self.debug > 2:
553.395 - print "given, inferred, offset", offset_cd, x, concat
553.396 - # self.start_dir: Position of start of central directory
553.397 - self.start_dir = offset_cd + concat
553.398 - fp.seek(self.start_dir, 0)
553.399 - data = fp.read(size_cd)
553.400 - fp = cStringIO.StringIO(data)
553.401 - total = 0
553.402 - while total < size_cd:
553.403 - centdir = fp.read(46)
553.404 - total = total + 46
553.405 - if centdir[0:4] != stringCentralDir:
553.406 - raise BadZipfile, "Bad magic number for central directory"
553.407 - centdir = struct.unpack(structCentralDir, centdir)
553.408 - if self.debug > 2:
553.409 - print centdir
553.410 - filename = fp.read(centdir[_CD_FILENAME_LENGTH])
553.411 - # Create ZipInfo instance to store file information
553.412 - x = ZipInfo(filename)
553.413 - x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH])
553.414 - x.comment = fp.read(centdir[_CD_COMMENT_LENGTH])
553.415 - total = (total + centdir[_CD_FILENAME_LENGTH]
553.416 - + centdir[_CD_EXTRA_FIELD_LENGTH]
553.417 - + centdir[_CD_COMMENT_LENGTH])
553.418 - x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET]
553.419 - (x.create_version, x.create_system, x.extract_version, x.reserved,
553.420 - x.flag_bits, x.compress_type, t, d,
553.421 - x.CRC, x.compress_size, x.file_size) = centdir[1:12]
553.422 - x.volume, x.internal_attr, x.external_attr = centdir[15:18]
553.423 - # Convert date/time code to (year, month, day, hour, min, sec)
553.424 - x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F,
553.425 - t>>11, (t>>5)&0x3F, (t&0x1F) * 2 )
553.426 -
553.427 - x._decodeExtra()
553.428 - x.header_offset = x.header_offset + concat
553.429 - self.filelist.append(x)
553.430 - self.NameToInfo[x.filename] = x
553.431 - if self.debug > 2:
553.432 - print "total", total
553.433 -
553.434 -
553.435 - def namelist(self):
553.436 - """Return a list of file names in the archive."""
553.437 - l = []
553.438 - for data in self.filelist:
553.439 - l.append(data.filename)
553.440 - return l
553.441 -
553.442 - def infolist(self):
553.443 - """Return a list of class ZipInfo instances for files in the
553.444 - archive."""
553.445 - return self.filelist
553.446 -
553.447 - def printdir(self):
553.448 - """Print a table of contents for the zip file."""
553.449 - print "%-46s %19s %12s" % ("File Name", "Modified ", "Size")
553.450 - for zinfo in self.filelist:
553.451 - date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6]
553.452 - print "%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size)
553.453 -
553.454 - def testzip(self):
553.455 - """Read all the files and check the CRC."""
553.456 - for zinfo in self.filelist:
553.457 - try:
553.458 - self.read(zinfo.filename) # Check CRC-32
553.459 - except BadZipfile:
553.460 - return zinfo.filename
553.461 -
553.462 -
553.463 - def getinfo(self, name):
553.464 - """Return the instance of ZipInfo given 'name'."""
553.465 - return self.NameToInfo[name]
553.466 -
553.467 - def read(self, name):
553.468 - """Return file bytes (as a string) for name."""
553.469 - if self.mode not in ("r", "a"):
553.470 - raise RuntimeError, 'read() requires mode "r" or "a"'
553.471 - if not self.fp:
553.472 - raise RuntimeError, \
553.473 - "Attempt to read ZIP archive that was already closed"
553.474 - zinfo = self.getinfo(name)
553.475 - filepos = self.fp.tell()
553.476 -
553.477 - self.fp.seek(zinfo.header_offset, 0)
553.478 -
553.479 - # Skip the file header:
553.480 - fheader = self.fp.read(30)
553.481 - if fheader[0:4] != stringFileHeader:
553.482 - raise BadZipfile, "Bad magic number for file header"
553.483 -
553.484 - fheader = struct.unpack(structFileHeader, fheader)
553.485 - fname = self.fp.read(fheader[_FH_FILENAME_LENGTH])
553.486 - if fheader[_FH_EXTRA_FIELD_LENGTH]:
553.487 - self.fp.read(fheader[_FH_EXTRA_FIELD_LENGTH])
553.488 -
553.489 - if fname != zinfo.orig_filename:
553.490 - raise BadZipfile, \
553.491 - 'File name in directory "%s" and header "%s" differ.' % (
553.492 - zinfo.orig_filename, fname)
553.493 -
553.494 - bytes = self.fp.read(zinfo.compress_size)
553.495 - self.fp.seek(filepos, 0)
553.496 - if zinfo.compress_type == ZIP_STORED:
553.497 - pass
553.498 - elif zinfo.compress_type == ZIP_DEFLATED:
553.499 - if not zlib:
553.500 - raise RuntimeError, \
553.501 - "De-compression requires the (missing) zlib module"
553.502 - # zlib compress/decompress code by Jeremy Hylton of CNRI
553.503 - dc = zlib.decompressobj(-15)
553.504 - bytes = dc.decompress(bytes)
553.505 - # need to feed in unused pad byte so that zlib won't choke
553.506 - ex = dc.decompress('Z') + dc.flush()
553.507 - if ex:
553.508 - bytes = bytes + ex
553.509 - else:
553.510 - raise BadZipfile, \
553.511 - "Unsupported compression method %d for file %s" % \
553.512 - (zinfo.compress_type, name)
553.513 - crc = binascii.crc32(bytes)
553.514 - if crc != zinfo.CRC:
553.515 - raise BadZipfile, "Bad CRC-32 for file %s" % name
553.516 - return bytes
553.517 -
553.518 - def _writecheck(self, zinfo):
553.519 - """Check for errors before writing a file to the archive."""
553.520 - if zinfo.filename in self.NameToInfo:
553.521 - if self.debug: # Warning for duplicate names
553.522 - print "Duplicate name:", zinfo.filename
553.523 - if self.mode not in ("w", "a"):
553.524 - raise RuntimeError, 'write() requires mode "w" or "a"'
553.525 - if not self.fp:
553.526 - raise RuntimeError, \
553.527 - "Attempt to write ZIP archive that was already closed"
553.528 - if zinfo.compress_type == ZIP_DEFLATED and not zlib:
553.529 - raise RuntimeError, \
553.530 - "Compression requires the (missing) zlib module"
553.531 - if zinfo.compress_type not in (ZIP_STORED, ZIP_DEFLATED):
553.532 - raise RuntimeError, \
553.533 - "That compression method is not supported"
553.534 - if zinfo.file_size > ZIP64_LIMIT:
553.535 - if not self._allowZip64:
553.536 - raise LargeZipFile("Filesize would require ZIP64 extensions")
553.537 - if zinfo.header_offset > ZIP64_LIMIT:
553.538 - if not self._allowZip64:
553.539 - raise LargeZipFile("Zipfile size would require ZIP64 extensions")
553.540 -
553.541 - def write(self, filename, arcname=None, compress_type=None):
553.542 - """Put the bytes from filename into the archive under the name
553.543 - arcname."""
553.544 - st = os.stat(filename)
553.545 - mtime = time.localtime(st.st_mtime)
553.546 - date_time = mtime[0:6]
553.547 - # Create ZipInfo instance to store file information
553.548 - if arcname is None:
553.549 - arcname = filename
553.550 - arcname = os.path.normpath(os.path.splitdrive(arcname)[1])
553.551 - while arcname[0] in (os.sep, os.altsep):
553.552 - arcname = arcname[1:]
553.553 - zinfo = ZipInfo(arcname, date_time)
553.554 - zinfo.external_attr = (st[0] & 0xFFFF) << 16L # Unix attributes
553.555 - if compress_type is None:
553.556 - zinfo.compress_type = self.compression
553.557 - else:
553.558 - zinfo.compress_type = compress_type
553.559 -
553.560 - zinfo.file_size = st.st_size
553.561 - zinfo.flag_bits = 0x00
553.562 - zinfo.header_offset = self.fp.tell() # Start of header bytes
553.563 -
553.564 - self._writecheck(zinfo)
553.565 - self._didModify = True
553.566 - fp = open(filename, "rb")
553.567 - # Must overwrite CRC and sizes with correct data later
553.568 - zinfo.CRC = CRC = 0
553.569 - zinfo.compress_size = compress_size = 0
553.570 - zinfo.file_size = file_size = 0
553.571 - self.fp.write(zinfo.FileHeader())
553.572 - if zinfo.compress_type == ZIP_DEFLATED:
553.573 - cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
553.574 - zlib.DEFLATED, -15)
553.575 - else:
553.576 - cmpr = None
553.577 - while 1:
553.578 - buf = fp.read(1024 * 8)
553.579 - if not buf:
553.580 - break
553.581 - file_size = file_size + len(buf)
553.582 - CRC = binascii.crc32(buf, CRC)
553.583 - if cmpr:
553.584 - buf = cmpr.compress(buf)
553.585 - compress_size = compress_size + len(buf)
553.586 - self.fp.write(buf)
553.587 - fp.close()
553.588 - if cmpr:
553.589 - buf = cmpr.flush()
553.590 - compress_size = compress_size + len(buf)
553.591 - self.fp.write(buf)
553.592 - zinfo.compress_size = compress_size
553.593 - else:
553.594 - zinfo.compress_size = file_size
553.595 - zinfo.CRC = CRC
553.596 - zinfo.file_size = file_size
553.597 - # Seek backwards and write CRC and file sizes
553.598 - position = self.fp.tell() # Preserve current position in file
553.599 - self.fp.seek(zinfo.header_offset + 14, 0)
553.600 - self.fp.write(struct.pack("<lLL", zinfo.CRC, zinfo.compress_size,
553.601 - zinfo.file_size))
553.602 - self.fp.seek(position, 0)
553.603 - self.filelist.append(zinfo)
553.604 - self.NameToInfo[zinfo.filename] = zinfo
553.605 -
553.606 - def writestr(self, zinfo_or_arcname, bytes):
553.607 - """Write a file into the archive. The contents is the string
553.608 - 'bytes'. 'zinfo_or_arcname' is either a ZipInfo instance or
553.609 - the name of the file in the archive."""
553.610 - if not isinstance(zinfo_or_arcname, ZipInfo):
553.611 - zinfo = ZipInfo(filename=zinfo_or_arcname,
553.612 - date_time=time.localtime(time.time())[:6])
553.613 - zinfo.compress_type = self.compression
553.614 - else:
553.615 - zinfo = zinfo_or_arcname
553.616 - zinfo.file_size = len(bytes) # Uncompressed size
553.617 - zinfo.header_offset = self.fp.tell() # Start of header bytes
553.618 - self._writecheck(zinfo)
553.619 - self._didModify = True
553.620 - zinfo.CRC = binascii.crc32(bytes) # CRC-32 checksum
553.621 - if zinfo.compress_type == ZIP_DEFLATED:
553.622 - co = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
553.623 - zlib.DEFLATED, -15)
553.624 - bytes = co.compress(bytes) + co.flush()
553.625 - zinfo.compress_size = len(bytes) # Compressed size
553.626 - else:
553.627 - zinfo.compress_size = zinfo.file_size
553.628 - zinfo.header_offset = self.fp.tell() # Start of header bytes
553.629 - self.fp.write(zinfo.FileHeader())
553.630 - self.fp.write(bytes)
553.631 - self.fp.flush()
553.632 - if zinfo.flag_bits & 0x08:
553.633 - # Write CRC and file sizes after the file data
553.634 - self.fp.write(struct.pack("<lLL", zinfo.CRC, zinfo.compress_size,
553.635 - zinfo.file_size))
553.636 - self.filelist.append(zinfo)
553.637 - self.NameToInfo[zinfo.filename] = zinfo
553.638 -
553.639 - def __del__(self):
553.640 - """Call the "close()" method in case the user forgot."""
553.641 - self.close()
553.642 -
553.643 - def close(self):
553.644 - """Close the file, and for mode "w" and "a" write the ending
553.645 - records."""
553.646 - if self.fp is None:
553.647 - return
553.648 -
553.649 - if self.mode in ("w", "a") and self._didModify: # write ending records
553.650 - count = 0
553.651 - pos1 = self.fp.tell()
553.652 - for zinfo in self.filelist: # write central directory
553.653 - count = count + 1
553.654 - dt = zinfo.date_time
553.655 - dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
553.656 - dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
553.657 - extra = []
553.658 - if zinfo.file_size > ZIP64_LIMIT \
553.659 - or zinfo.compress_size > ZIP64_LIMIT:
553.660 - extra.append(zinfo.file_size)
553.661 - extra.append(zinfo.compress_size)
553.662 - file_size = 0xffffffff #-1
553.663 - compress_size = 0xffffffff #-1
553.664 - else:
553.665 - file_size = zinfo.file_size
553.666 - compress_size = zinfo.compress_size
553.667 -
553.668 - if zinfo.header_offset > ZIP64_LIMIT:
553.669 - extra.append(zinfo.header_offset)
553.670 - header_offset = -1 # struct "l" format: 32 one bits
553.671 - else:
553.672 - header_offset = zinfo.header_offset
553.673 -
553.674 - extra_data = zinfo.extra
553.675 - if extra:
553.676 - # Append a ZIP64 field to the extra's
553.677 - extra_data = struct.pack(
553.678 - '<hh' + 'q'*len(extra),
553.679 - 1, 8*len(extra), *extra) + extra_data
553.680 -
553.681 - extract_version = max(45, zinfo.extract_version)
553.682 - create_version = max(45, zinfo.create_version)
553.683 - else:
553.684 - extract_version = zinfo.extract_version
553.685 - create_version = zinfo.create_version
553.686 -
553.687 - centdir = struct.pack(structCentralDir,
553.688 - stringCentralDir, create_version,
553.689 - zinfo.create_system, extract_version, zinfo.reserved,
553.690 - zinfo.flag_bits, zinfo.compress_type, dostime, dosdate,
553.691 - zinfo.CRC, compress_size, file_size,
553.692 - len(zinfo.filename), len(extra_data), len(zinfo.comment),
553.693 - 0, zinfo.internal_attr, zinfo.external_attr,
553.694 - header_offset)
553.695 - self.fp.write(centdir)
553.696 - self.fp.write(zinfo.filename)
553.697 - self.fp.write(extra_data)
553.698 - self.fp.write(zinfo.comment)
553.699 -
553.700 - pos2 = self.fp.tell()
553.701 - # Write end-of-zip-archive record
553.702 - if pos1 > ZIP64_LIMIT:
553.703 - # Need to write the ZIP64 end-of-archive records
553.704 - zip64endrec = struct.pack(
553.705 - structEndArchive64, stringEndArchive64,
553.706 - 44, 45, 45, 0, 0, count, count, pos2 - pos1, pos1)
553.707 - self.fp.write(zip64endrec)
553.708 -
553.709 - zip64locrec = struct.pack(
553.710 - structEndArchive64Locator,
553.711 - stringEndArchive64Locator, 0, pos2, 1)
553.712 - self.fp.write(zip64locrec)
553.713 -
553.714 - # XXX Why is `pos3` computed next? It's never referenced.
553.715 - pos3 = self.fp.tell()
553.716 - endrec = struct.pack(structEndArchive, stringEndArchive,
553.717 - 0, 0, count, count, pos2 - pos1, -1, 0)
553.718 - self.fp.write(endrec)
553.719 -
553.720 - else:
553.721 - endrec = struct.pack(structEndArchive, stringEndArchive,
553.722 - 0, 0, count, count, pos2 - pos1, pos1, 0)
553.723 - self.fp.write(endrec)
553.724 - self.fp.flush()
553.725 - if not self._filePassed:
553.726 - self.fp.close()
553.727 - self.fp = None
553.728 -
553.729 -
553.730 -class PyZipFile(ZipFile):
553.731 - """Class to create ZIP archives with Python library files and packages."""
553.732 -
553.733 - def writepy(self, pathname, basename = ""):
553.734 - """Add all files from "pathname" to the ZIP archive.
553.735 -
553.736 - If pathname is a package directory, search the directory and
553.737 - all package subdirectories recursively for all *.py and enter
553.738 - the modules into the archive. If pathname is a plain
553.739 - directory, listdir *.py and enter all modules. Else, pathname
553.740 - must be a Python *.py file and the module will be put into the
553.741 - archive. Added modules are always module.pyo or module.pyc.
553.742 - This method will compile the module.py into module.pyc if
553.743 - necessary.
553.744 - """
553.745 - dir, name = os.path.split(pathname)
553.746 - if os.path.isdir(pathname):
553.747 - initname = os.path.join(pathname, "__init__.py")
553.748 - if os.path.isfile(initname):
553.749 - # This is a package directory, add it
553.750 - if basename:
553.751 - basename = "%s/%s" % (basename, name)
553.752 - else:
553.753 - basename = name
553.754 - if self.debug:
553.755 - print "Adding package in", pathname, "as", basename
553.756 - fname, arcname = self._get_codename(initname[0:-3], basename)
553.757 - if self.debug:
553.758 - print "Adding", arcname
553.759 - self.write(fname, arcname)
553.760 - dirlist = os.listdir(pathname)
553.761 - dirlist.remove("__init__.py")
553.762 - # Add all *.py files and package subdirectories
553.763 - for filename in dirlist:
553.764 - path = os.path.join(pathname, filename)
553.765 - root, ext = os.path.splitext(filename)
553.766 - if os.path.isdir(path):
553.767 - if os.path.isfile(os.path.join(path, "__init__.py")):
553.768 - # This is a package directory, add it
553.769 - self.writepy(path, basename) # Recursive call
553.770 - elif ext == ".py":
553.771 - fname, arcname = self._get_codename(path[0:-3],
553.772 - basename)
553.773 - if self.debug:
553.774 - print "Adding", arcname
553.775 - self.write(fname, arcname)
553.776 - else:
553.777 - # This is NOT a package directory, add its files at top level
553.778 - if self.debug:
553.779 - print "Adding files from directory", pathname
553.780 - for filename in os.listdir(pathname):
553.781 - path = os.path.join(pathname, filename)
553.782 - root, ext = os.path.splitext(filename)
553.783 - if ext == ".py":
553.784 - fname, arcname = self._get_codename(path[0:-3],
553.785 - basename)
553.786 - if self.debug:
553.787 - print "Adding", arcname
553.788 - self.write(fname, arcname)
553.789 - else:
553.790 - if pathname[-3:] != ".py":
553.791 - raise RuntimeError, \
553.792 - 'Files added with writepy() must end with ".py"'
553.793 - fname, arcname = self._get_codename(pathname[0:-3], basename)
553.794 - if self.debug:
553.795 - print "Adding file", arcname
553.796 - self.write(fname, arcname)
553.797 -
553.798 - def _get_codename(self, pathname, basename):
553.799 - """Return (filename, archivename) for the path.
553.800 -
553.801 - Given a module name path, return the correct file path and
553.802 - archive name, compiling if necessary. For example, given
553.803 - /python/lib/string, return (/python/lib/string.pyc, string).
553.804 - """
553.805 - file_py = pathname + ".py"
553.806 - file_pyc = pathname + ".pyc"
553.807 - file_pyo = pathname + ".pyo"
553.808 - if os.path.isfile(file_pyo) and \
553.809 - os.stat(file_pyo).st_mtime >= os.stat(file_py).st_mtime:
553.810 - fname = file_pyo # Use .pyo file
553.811 - elif not os.path.isfile(file_pyc) or \
553.812 - os.stat(file_pyc).st_mtime < os.stat(file_py).st_mtime:
553.813 - import py_compile
553.814 - if self.debug:
553.815 - print "Compiling", file_py
553.816 - try:
553.817 - py_compile.compile(file_py, file_pyc, None, True)
553.818 - except py_compile.PyCompileError,err:
553.819 - print err.msg
553.820 - fname = file_pyc
553.821 - else:
553.822 - fname = file_pyc
553.823 - archivename = os.path.split(fname)[1]
553.824 - if basename:
553.825 - archivename = "%s/%s" % (basename, archivename)
553.826 - return (fname, archivename)
553.827 -
553.828 -
553.829 -def main(args = None):
553.830 - import textwrap
553.831 - USAGE=textwrap.dedent("""\
553.832 - Usage:
553.833 - zipfile.py -l zipfile.zip # Show listing of a zipfile
553.834 - zipfile.py -t zipfile.zip # Test if a zipfile is valid
553.835 - zipfile.py -e zipfile.zip target # Extract zipfile into target dir
553.836 - zipfile.py -c zipfile.zip src ... # Create zipfile from sources
553.837 - """)
553.838 - if args is None:
553.839 - args = sys.argv[1:]
553.840 -
553.841 - if not args or args[0] not in ('-l', '-c', '-e', '-t'):
553.842 - print USAGE
553.843 - sys.exit(1)
553.844 -
553.845 - if args[0] == '-l':
553.846 - if len(args) != 2:
553.847 - print USAGE
553.848 - sys.exit(1)
553.849 - zf = ZipFile(args[1], 'r')
553.850 - zf.printdir()
553.851 - zf.close()
553.852 -
553.853 - elif args[0] == '-t':
553.854 - if len(args) != 2:
553.855 - print USAGE
553.856 - sys.exit(1)
553.857 - zf = ZipFile(args[1], 'r')
553.858 - zf.testzip()
553.859 - print "Done testing"
553.860 -
553.861 - elif args[0] == '-e':
553.862 - if len(args) != 3:
553.863 - print USAGE
553.864 - sys.exit(1)
553.865 -
553.866 - zf = ZipFile(args[1], 'r')
553.867 - out = args[2]
553.868 - for path in zf.namelist():
553.869 - if path.startswith('./'):
553.870 - tgt = os.path.join(out, path[2:])
553.871 - else:
553.872 - tgt = os.path.join(out, path)
553.873 -
553.874 - tgtdir = os.path.dirname(tgt)
553.875 - if not os.path.exists(tgtdir):
553.876 - os.makedirs(tgtdir)
553.877 - fp = open(tgt, 'wb')
553.878 - fp.write(zf.read(path))
553.879 - fp.close()
553.880 - zf.close()
553.881 -
553.882 - elif args[0] == '-c':
553.883 - if len(args) < 3:
553.884 - print USAGE
553.885 - sys.exit(1)
553.886 -
553.887 - def addToZip(zf, path, zippath):
553.888 - if os.path.isfile(path):
553.889 - zf.write(path, zippath, ZIP_DEFLATED)
553.890 - elif os.path.isdir(path):
553.891 - for nm in os.listdir(path):
553.892 - addToZip(zf,
553.893 - os.path.join(path, nm), os.path.join(zippath, nm))
553.894 - # else: ignore
553.895 -
553.896 - zf = ZipFile(args[1], 'w', allowZip64=True)
553.897 - for src in args[2:]:
553.898 - addToZip(zf, src, os.path.basename(src))
553.899 -
553.900 - zf.close()
553.901 -
553.902 -if __name__ == "__main__":
553.903 - main()
554.1 --- a/python.editor/test/unit/data/testfiles/zipfile.py.indexed Sun Jan 04 13:11:53 2015 -0600
554.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
554.3 @@ -1,178 +0,0 @@
554.4 -
554.5 -
554.6 -Document 0
554.7 -Searchable Keys:
554.8 - class : BadZipfile
554.9 - class-ig : badzipfile
554.10 - extends : Exception
554.11 - in : zipfile
554.12 -
554.13 -Not Searchable Keys:
554.14 -
554.15 -
554.16 -Document 1
554.17 -Searchable Keys:
554.18 - class : LargeZipFile
554.19 - class-ig : largezipfile
554.20 - extends : Exception
554.21 - in : zipfile
554.22 -
554.23 -Not Searchable Keys:
554.24 -
554.25 -
554.26 -Document 2
554.27 -Searchable Keys:
554.28 - class : PyZipFile
554.29 - class-ig : pyzipfile
554.30 - extends : ZipFile
554.31 - in : zipfile
554.32 - member : _get_codename;F;|PRIVATE|;self,pathname,basename;
554.33 - member : writepy;F;;self,pathname,basename;
554.34 -
554.35 -Not Searchable Keys:
554.36 -
554.37 -
554.38 -Document 3
554.39 -Searchable Keys:
554.40 - class : ZipFile
554.41 - class-ig : zipfile
554.42 - in : zipfile
554.43 - member : NameToInfo;D;;
554.44 - member : _GetContents;F;|PRIVATE|;self;
554.45 - member : _RealGetContents;F;|PRIVATE|;self;
554.46 - member : __del__;F;;self;
554.47 - member : __init__;c;|CONSTRUCTOR|;self,file,mode,compression,allowZip64;
554.48 - member : _allowZip64;D;|PRIVATE|;
554.49 - member : _didModify;D;|PRIVATE|;
554.50 - member : _filePassed;D;|PRIVATE|;
554.51 - member : _writecheck;F;|PRIVATE|;self,zinfo;
554.52 - member : close;F;;self;
554.53 - member : comment;D;;
554.54 - member : compression;D;;
554.55 - member : debug;D;;
554.56 - member : filelist;D;;
554.57 - member : filename;D;;
554.58 - member : fp;D;;
554.59 - member : fp;D;;
554.60 - member : getinfo;F;;self,name;
554.61 - member : infolist;F;;self;
554.62 - member : mode;D;;
554.63 - member : namelist;F;;self;
554.64 - member : printdir;F;;self;
554.65 - member : read;F;;self,name;
554.66 - member : start_dir;D;;
554.67 - member : testzip;F;;self;
554.68 - member : write;F;;self,filename,arcname,compress_type;
554.69 - member : writestr;F;;self,zinfo_or_arcname,bytes;
554.70 -
554.71 -Not Searchable Keys:
554.72 -
554.73 -
554.74 -Document 4
554.75 -Searchable Keys:
554.76 - class : ZipInfo
554.77 - class-ig : zipinfo
554.78 - extends : object
554.79 - in : zipfile
554.80 - member : FileHeader;F;;self;
554.81 - member : __init__;c;|CONSTRUCTOR|;self,filename,date_time;
554.82 - member : __slots__;D;;
554.83 - member : _decodeExtra;F;|PRIVATE|;self;
554.84 - member : comment;D;;
554.85 - member : compress_size;D;;
554.86 - member : compress_type;D;;
554.87 - member : create_system;D;;
554.88 - member : create_version;D;;
554.89 - member : date_time;D;;
554.90 - member : external_attr;D;;
554.91 - member : extra;D;;
554.92 - member : extract_version;D;;
554.93 - member : file_size;D;;
554.94 - member : filename;D;;
554.95 - member : flag_bits;D;;
554.96 - member : header_offset;D;;
554.97 - member : internal_attr;D;;
554.98 - member : orig_filename;D;;
554.99 - member : reserved;D;;
554.100 - member : volume;D;;
554.101 -
554.102 -Not Searchable Keys:
554.103 -
554.104 -
554.105 -Document 5
554.106 -Searchable Keys:
554.107 - class : error
554.108 - class-ig : error
554.109 - extends : Exception
554.110 - in : zipfile
554.111 -
554.112 -Not Searchable Keys:
554.113 -
554.114 -
554.115 -Document 6
554.116 -Searchable Keys:
554.117 - item : BadZipfile;C;;
554.118 - item : LargeZipFile;C;;
554.119 - item : PyZipFile;C;;
554.120 - item : ZIP64_LIMIT;D;|PRIVATE|;
554.121 - item : ZIP_DEFLATED;D;;
554.122 - item : ZIP_STORED;D;;
554.123 - item : ZipFile;C;;
554.124 - item : ZipInfo;C;;
554.125 - item : _CD_COMMENT_LENGTH;D;|PRIVATE|;
554.126 - item : _CD_COMPRESSED_SIZE;D;|PRIVATE|;
554.127 - item : _CD_COMPRESS_TYPE;D;|PRIVATE|;
554.128 - item : _CD_CRC;D;|PRIVATE|;
554.129 - item : _CD_CREATE_SYSTEM;D;|PRIVATE|;
554.130 - item : _CD_CREATE_VERSION;D;|PRIVATE|;
554.131 - item : _CD_DATE;D;|PRIVATE|;
554.132 - item : _CD_DISK_NUMBER_START;D;|PRIVATE|;
554.133 - item : _CD_EXTERNAL_FILE_ATTRIBUTES;D;|PRIVATE|;
554.134 - item : _CD_EXTRACT_SYSTEM;D;|PRIVATE|;
554.135 - item : _CD_EXTRACT_VERSION;D;|PRIVATE|;
554.136 - item : _CD_EXTRA_FIELD_LENGTH;D;|PRIVATE|;
554.137 - item : _CD_FILENAME_LENGTH;D;|PRIVATE|;
554.138 - item : _CD_FLAG_BITS;D;|PRIVATE|;
554.139 - item : _CD_INTERNAL_FILE_ATTRIBUTES;D;|PRIVATE|;
554.140 - item : _CD_LOCAL_HEADER_OFFSET;D;|PRIVATE|;
554.141 - item : _CD_SIGNATURE;D;|PRIVATE|;
554.142 - item : _CD_TIME;D;|PRIVATE|;
554.143 - item : _CD_UNCOMPRESSED_SIZE;D;|PRIVATE|;
554.144 - item : _EndRecData64;F;|PRIVATE|;fpin,offset,endrec;
554.145 - item : _EndRecData;F;|PRIVATE|;fpin;
554.146 - item : _FH_COMPRESSED_SIZE;D;|PRIVATE|;
554.147 - item : _FH_COMPRESSION_METHOD;D;|PRIVATE|;
554.148 - item : _FH_CRC;D;|PRIVATE|;
554.149 - item : _FH_EXTRACT_SYSTEM;D;|PRIVATE|;
554.150 - item : _FH_EXTRACT_VERSION;D;|PRIVATE|;
554.151 - item : _FH_EXTRA_FIELD_LENGTH;D;|PRIVATE|;
554.152 - item : _FH_FILENAME_LENGTH;D;|PRIVATE|;
554.153 - item : _FH_GENERAL_PURPOSE_FLAG_BITS;D;|PRIVATE|;
554.154 - item : _FH_LAST_MOD_DATE;D;|PRIVATE|;
554.155 - item : _FH_LAST_MOD_TIME;D;|PRIVATE|;
554.156 - item : _FH_SIGNATURE;D;|PRIVATE|;
554.157 - item : _FH_UNCOMPRESSED_SIZE;D;|PRIVATE|;
554.158 - item : __all__;D;;
554.159 - item : binascii;I;|PRIVATE|;
554.160 - item : cStringIO;I;|PRIVATE|;
554.161 - item : error;C;;
554.162 - item : is_zipfile;F;;filename;
554.163 - item : main;F;|PRIVATE|;args;
554.164 - item : os;I;|PRIVATE|;
554.165 - item : stringCentralDir;D;|PRIVATE|;
554.166 - item : stringEndArchive64;D;|PRIVATE|;
554.167 - item : stringEndArchive64Locator;D;|PRIVATE|;
554.168 - item : stringEndArchive;D;|PRIVATE|;
554.169 - item : stringFileHeader;D;|PRIVATE|;
554.170 - item : struct;I;|PRIVATE|;
554.171 - item : structCentralDir;D;|PRIVATE|;
554.172 - item : structEndArchive64;D;|PRIVATE|;
554.173 - item : structEndArchive64Locator;D;|PRIVATE|;
554.174 - item : structEndArchive;D;|PRIVATE|;
554.175 - item : structFileHeader;D;|PRIVATE|;
554.176 - item : sys;I;|PRIVATE|;
554.177 - item : time;I;|PRIVATE|;
554.178 - item : zlib;I;|PRIVATE|;
554.179 - module : zipfile
554.180 -
554.181 -Not Searchable Keys:
555.1 --- a/python.editor/test/unit/data/testfiles/zipfile.py.scopes Sun Jan 04 13:11:53 2015 -0600
555.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
555.3 @@ -1,592 +0,0 @@
555.4 -=============================================
555.5 -<file-top>: Module : OffsetRange[0,35620>
555.6 -BadZipfile [bound][class][def][read][called][node=ClassDef]
555.7 -Exception [private][read][UNRESOLVED][node=Name]
555.8 -ImportError [private][read][UNRESOLVED][node=Name]
555.9 -LargeZipFile [bound][class][def][read][called][node=ClassDef]
555.10 -None [private][read][UNRESOLVED][node=Name]
555.11 -PyZipFile [bound][class][def][node=ClassDef]
555.12 -ZIP64_LIMIT [bound][private][data][read][node=Name]
555.13 -ZIP_DEFLATED [bound][data][read][node=Name]
555.14 -ZIP_STORED [bound][data][read][node=Name]
555.15 -ZipFile [bound][class][def][read][called][node=ClassDef]
555.16 -ZipInfo [bound][class][def][read][called][node=ClassDef]
555.17 -_CD_COMMENT_LENGTH [bound][private][data][read][node=Name]
555.18 -_CD_COMPRESSED_SIZE [bound][private][data][node=Name]
555.19 -_CD_COMPRESS_TYPE [bound][private][data][node=Name]
555.20 -_CD_CRC [bound][private][data][node=Name]
555.21 -_CD_CREATE_SYSTEM [bound][private][data][node=Name]
555.22 -_CD_CREATE_VERSION [bound][private][data][node=Name]
555.23 -_CD_DATE [bound][private][data][node=Name]
555.24 -_CD_DISK_NUMBER_START [bound][private][data][node=Name]
555.25 -_CD_EXTERNAL_FILE_ATTRIBUTES [bound][private][data][node=Name]
555.26 -_CD_EXTRACT_SYSTEM [bound][private][data][node=Name]
555.27 -_CD_EXTRACT_VERSION [bound][private][data][node=Name]
555.28 -_CD_EXTRA_FIELD_LENGTH [bound][private][data][read][node=Name]
555.29 -_CD_FILENAME_LENGTH [bound][private][data][read][node=Name]
555.30 -_CD_FLAG_BITS [bound][private][data][node=Name]
555.31 -_CD_INTERNAL_FILE_ATTRIBUTES [bound][private][data][node=Name]
555.32 -_CD_LOCAL_HEADER_OFFSET [bound][private][data][read][node=Name]
555.33 -_CD_SIGNATURE [bound][private][data][node=Name]
555.34 -_CD_TIME [bound][private][data][node=Name]
555.35 -_CD_UNCOMPRESSED_SIZE [bound][private][data][node=Name]
555.36 -_EndRecData [bound][private][function][def][read][called][node=FunctionDef]
555.37 -_EndRecData64 [bound][private][function][def][read][called][node=FunctionDef]
555.38 -_FH_COMPRESSED_SIZE [bound][private][data][node=Name]
555.39 -_FH_COMPRESSION_METHOD [bound][private][data][node=Name]
555.40 -_FH_CRC [bound][private][data][node=Name]
555.41 -_FH_EXTRACT_SYSTEM [bound][private][data][node=Name]
555.42 -_FH_EXTRACT_VERSION [bound][private][data][node=Name]
555.43 -_FH_EXTRA_FIELD_LENGTH [bound][private][data][read][node=Name]
555.44 -_FH_FILENAME_LENGTH [bound][private][data][read][node=Name]
555.45 -_FH_GENERAL_PURPOSE_FLAG_BITS [bound][private][data][node=Name]
555.46 -_FH_LAST_MOD_DATE [bound][private][data][node=Name]
555.47 -_FH_LAST_MOD_TIME [bound][private][data][node=Name]
555.48 -_FH_SIGNATURE [bound][private][data][node=Name]
555.49 -_FH_UNCOMPRESSED_SIZE [bound][private][data][node=Name]
555.50 -__all__ [bound][data][node=Name]
555.51 -__name__ [private][read][UNRESOLVED][node=Name]
555.52 -binascii [bound][imported][private][data][read][node=Import]
555.53 -cStringIO [bound][imported][private][data][read][node=Import]
555.54 -error [bound][class][alias][node=ClassDef]
555.55 -is_zipfile [bound][function][def][node=FunctionDef]
555.56 -main [bound][private][function][def][read][called][node=FunctionDef]
555.57 -object [private][read][UNRESOLVED][node=Name]
555.58 -os [bound][imported][private][data][read][node=Import]
555.59 -stringCentralDir [bound][private][data][read][node=Name]
555.60 -stringEndArchive [bound][private][data][read][node=Name]
555.61 -stringEndArchive64 [bound][private][data][read][node=Name]
555.62 -stringEndArchive64Locator [bound][private][data][read][node=Name]
555.63 -stringFileHeader [bound][private][data][read][node=Name]
555.64 -struct [bound][imported][private][data][read][node=Import]
555.65 -structCentralDir [bound][private][data][read][node=Name]
555.66 -structEndArchive [bound][private][data][read][node=Name]
555.67 -structEndArchive64 [bound][private][data][read][node=Name]
555.68 -structEndArchive64Locator [bound][private][data][read][node=Name]
555.69 -structFileHeader [bound][private][data][read][node=Name]
555.70 -sys [bound][imported][private][data][read][node=Import]
555.71 -time [bound][imported][private][data][read][node=Import]
555.72 -zlib [bound][imported][private][data][read][node=Import]
555.73 -
555.74 - =============================================
555.75 - class BadZipfile: ClassDef : OffsetRange[328,368>
555.76 -
555.77 - =============================================
555.78 - class LargeZipFile: ClassDef : OffsetRange[368,528>
555.79 -
555.80 - =============================================
555.81 - is_zipfile: FunctionDef : OffsetRange[2451,2794>
555.82 - False [free][read][node=Name]
555.83 - IOError [free][read][node=Name]
555.84 - True [free][read][node=Name]
555.85 - _EndRecData [free][read][called][node=Name]
555.86 - endrec [bound][data][read][node=Name]
555.87 - filename [bound][param][data][read][node=Name]
555.88 - fpin [bound][data][read][node=Name]
555.89 - open [free][read][called][node=Name]
555.90 -
555.91 - =============================================
555.92 - _EndRecData64: FunctionDef : OffsetRange[2794,3973>
555.93 - BadZipfile [free][private][read][called][node=Name]
555.94 - create_version [bound][private][data][unused][node=Name]
555.95 - data [bound][private][data][read][node=Name]
555.96 - dircount [bound][private][data][read][node=Name]
555.97 - dircount2 [bound][private][data][read][node=Name]
555.98 - diroffset [bound][private][data][read][node=Name]
555.99 - dirsize [bound][private][data][read][node=Name]
555.100 - disk_dir [bound][private][data][read][node=Name]
555.101 - disk_num [bound][private][data][read][node=Name]
555.102 - diskno [bound][private][data][read][node=Name]
555.103 - disks [bound][private][data][read][node=Name]
555.104 - endArchiveSize [bound][private][data][read][node=Name]
555.105 - endrec [bound][param][private][data][read][node=Name]
555.106 - fpin [bound][param][private][data][read][node=Name]
555.107 - locatorSize [bound][private][data][read][node=Name]
555.108 - offset [bound][param][private][data][read][node=Name]
555.109 - read_version [bound][private][data][unused][node=Name]
555.110 - reloff [bound][private][data][unused][node=Name]
555.111 - sig [bound][private][data][read][node=Name]
555.112 - stringEndArchive64 [free][private][read][node=Name]
555.113 - stringEndArchive64Locator [free][private][read][node=Name]
555.114 - struct [free][private][read][node=Name]
555.115 - structEndArchive64 [free][private][read][node=Name]
555.116 - structEndArchive64Locator [free][private][read][node=Name]
555.117 - sz [bound][private][data][unused][node=Name]
555.118 -
555.119 - =============================================
555.120 - _EndRecData: FunctionDef : OffsetRange[3973,5887>
555.121 - END_BLOCK [bound][private][data][read][node=Name]
555.122 - _EndRecData64 [free][private][read][called][node=Name]
555.123 - comment [bound][private][data][read][node=Name]
555.124 - data [bound][private][data][read][node=Name]
555.125 - endrec [bound][private][data][read][node=Name]
555.126 - filesize [bound][private][data][read][node=Name]
555.127 - fpin [bound][param][private][data][read][node=Name]
555.128 - len [free][private][read][called][node=Name]
555.129 - list [free][private][read][called][node=Name]
555.130 - min [free][private][read][called][node=Name]
555.131 - start [bound][private][data][read][node=Name]
555.132 - stringEndArchive [free][private][read][node=Name]
555.133 - struct [free][private][read][node=Name]
555.134 - structEndArchive [free][private][read][node=Name]
555.135 -
555.136 - =============================================
555.137 - class ZipInfo: ClassDef : OffsetRange[5887,11246>
555.138 - FileHeader [bound][function][def][node=FunctionDef]
555.139 - __init__ [bound][function][def][node=FunctionDef]
555.140 - __slots__ [bound][data][node=Name]
555.141 - _decodeExtra [bound][private][function][def][node=FunctionDef]
555.142 - ------ Attributes ---------------------------------------
555.143 - comment : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.144 - compress_size : SymInfo[8195 0 0][bound][func-global][data][member][generator][unused][node=Attribute]
555.145 - compress_type : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.146 - create_system : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.147 - create_version : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.148 - date_time : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.149 - external_attr : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.150 - extra : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.151 - extract_version : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.152 - file_size : SymInfo[8195 0 0][bound][func-global][data][member][generator][unused][node=Attribute]
555.153 - filename : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.154 - flag_bits : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.155 - header_offset : SymInfo[8195 0 0][bound][func-global][data][member][generator][unused][node=Attribute]
555.156 - internal_attr : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.157 - orig_filename : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.158 - reserved : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.159 - volume : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.160 -
555.161 - =============================================
555.162 - __init__: FunctionDef : OffsetRange[6490,8551>
555.163 - ZIP_STORED [free][read][node=Name]
555.164 - chr [free][read][called][node=Name]
555.165 - date_time [bound][param][data][read][node=Name]
555.166 - filename [bound][param][data][read][node=Name]
555.167 - null_byte [bound][data][read][node=Name]
555.168 - os [free][read][node=Name]
555.169 - self [bound][param][data][read][node=Name]
555.170 - sys [free][read][node=Name]
555.171 -
555.172 - =============================================
555.173 - FileHeader: FunctionDef : OffsetRange[8552,9961>
555.174 - CRC [bound][data][read][node=Name]
555.175 - ZIP64_LIMIT [free][read][node=Name]
555.176 - compress_size [bound][data][read][node=Name]
555.177 - dosdate [bound][data][read][node=Name]
555.178 - dostime [bound][data][read][node=Name]
555.179 - dt [bound][data][read][node=Name]
555.180 - extra [bound][data][read][node=Name]
555.181 - file_size [bound][data][read][node=Name]
555.182 - fmt [bound][data][read][node=Name]
555.183 - header [bound][data][read][node=Name]
555.184 - len [free][read][called][node=Name]
555.185 - max [free][read][called][node=Name]
555.186 - self [bound][param][data][read][node=Name]
555.187 - stringFileHeader [free][read][node=Name]
555.188 - struct [free][read][node=Name]
555.189 - structFileHeader [free][read][node=Name]
555.190 - ------ Attributes ---------------------------------------
555.191 - CRC : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.192 - compress_size : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.193 - compress_type : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.194 - date_time : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.195 - extra : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.196 - extract_version : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.197 - file_size : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.198 - filename : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.199 - flag_bits : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.200 - reserved : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.201 -
555.202 - =============================================
555.203 - _decodeExtra: FunctionDef : OffsetRange[9962,11246>
555.204 - RuntimeError [free][read][node=Name]
555.205 - counts [bound][data][read][node=Name]
555.206 - extra [bound][data][read][node=Name]
555.207 - idx [bound][data][read][node=Name]
555.208 - ln [bound][data][read][node=Name]
555.209 - old [bound][data][unused][node=Name]
555.210 - self [bound][param][data][read][node=Name]
555.211 - struct [free][read][node=Name]
555.212 - tp [bound][data][read][node=Name]
555.213 - unpack [bound][data][read][called][node=Name]
555.214 - ------ Attributes ---------------------------------------
555.215 - compress_size : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.216 - extra : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.217 - file_size : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.218 - header_offset : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.219 -
555.220 - =============================================
555.221 - class ZipFile: ClassDef : OffsetRange[11246,28949>
555.222 - False [free][read][node=Name]
555.223 - None [free][read][node=Name]
555.224 - ZIP_STORED [free][read][node=Name]
555.225 - _GetContents [bound][private][function][def][node=FunctionDef]
555.226 - _RealGetContents [bound][private][function][def][node=FunctionDef]
555.227 - __del__ [bound][function][def][node=FunctionDef]
555.228 - __init__ [bound][function][def][node=FunctionDef]
555.229 - _writecheck [bound][private][function][def][node=FunctionDef]
555.230 - close [bound][function][def][node=FunctionDef]
555.231 - fp [bound][data][node=Name]
555.232 - getinfo [bound][function][def][node=FunctionDef]
555.233 - infolist [bound][function][def][node=FunctionDef]
555.234 - namelist [bound][function][def][node=FunctionDef]
555.235 - printdir [bound][function][def][node=FunctionDef]
555.236 - read [bound][function][def][node=FunctionDef]
555.237 - testzip [bound][function][def][node=FunctionDef]
555.238 - write [bound][function][def][node=FunctionDef]
555.239 - writestr [bound][function][def][node=FunctionDef]
555.240 - ------ Attributes ---------------------------------------
555.241 - NameToInfo : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.242 - _allowZip64 : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.243 - _didModify : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.244 - _filePassed : SymInfo[155651 0 0][bound][func-global][private][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.245 - comment : SymInfo[8195 0 0][bound][func-global][data][member][generator][unused][node=Attribute]
555.246 - compression : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.247 - debug : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.248 - filelist : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.249 - filename : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.250 - fp : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.251 - mode : SymInfo[139267 0 0][bound][func-global][data][member][generator][bound-in-constructor][unused][node=Attribute]
555.252 - start_dir : SymInfo[8195 0 0][bound][func-global][data][member][generator][unused][node=Attribute]
555.253 -
555.254 - =============================================
555.255 - __init__: FunctionDef : OffsetRange[11956,13836>
555.256 - BadZipfile [free][read][node=Name]
555.257 - False [free][read][node=Name]
555.258 - None [free][read][node=Name]
555.259 - RuntimeError [free][read][node=Name]
555.260 - ZIP_DEFLATED [free][read][node=Name]
555.261 - ZIP_STORED [free][read][node=Name]
555.262 - allowZip64 [bound][param][data][read][node=Name]
555.263 - basestring [free][read][node=Name]
555.264 - compression [bound][param][data][read][node=Name]
555.265 - file [bound][param][data][read][node=Name]
555.266 - getattr [free][read][called][node=Name]
555.267 - isinstance [free][read][called][node=Name]
555.268 - key [bound][data][read][node=Name]
555.269 - mode [bound][param][data][read][node=Name]
555.270 - modeDict [bound][data][read][node=Name]
555.271 - open [free][read][called][node=Name]
555.272 - self [bound][param][data][read][node=Name]
555.273 - zlib [free][read][node=Name]
555.274 - ------ Attributes ---------------------------------------
555.275 - _GetContents : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
555.276 - _RealGetContents : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
555.277 - _filePassed : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
555.278 - fp : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.279 - start_dir : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.280 -
555.281 - =============================================
555.282 - _GetContents: FunctionDef : OffsetRange[13837,14153>
555.283 - BadZipfile [free][read][node=Name]
555.284 - None [free][read][node=Name]
555.285 - self [bound][param][data][read][node=Name]
555.286 - ------ Attributes ---------------------------------------
555.287 - _RealGetContents : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
555.288 - _filePassed : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
555.289 - fp : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.290 -
555.291 - =============================================
555.292 - _RealGetContents: FunctionDef : OffsetRange[14154,16820>
555.293 - BadZipfile [free][read][node=Name]
555.294 - ZIP64_LIMIT [free][read][node=Name]
555.295 - ZipInfo [free][read][called][node=Name]
555.296 - _CD_COMMENT_LENGTH [free][read][node=Name]
555.297 - _CD_EXTRA_FIELD_LENGTH [free][read][node=Name]
555.298 - _CD_FILENAME_LENGTH [free][read][node=Name]
555.299 - _CD_LOCAL_HEADER_OFFSET [free][read][node=Name]
555.300 - _EndRecData [free][read][called][node=Name]
555.301 - cStringIO [free][read][node=Name]
555.302 - centdir [bound][data][read][node=Name]
555.303 - concat [bound][data][read][node=Name]
555.304 - d [bound][data][read][node=Name]
555.305 - data [bound][data][read][node=Name]
555.306 - endrec [bound][data][read][node=Name]
555.307 - filename [bound][data][read][node=Name]
555.308 - fp [bound][data][read][node=Name]
555.309 - offset_cd [bound][data][read][node=Name]
555.310 - self [bound][param][data][read][node=Name]
555.311 - size_cd [bound][data][read][node=Name]
555.312 - stringCentralDir [free][read][node=Name]
555.313 - struct [free][read][node=Name]
555.314 - structCentralDir [free][read][node=Name]
555.315 - t [bound][data][read][node=Name]
555.316 - total [bound][data][read][node=Name]
555.317 - x [bound][data][read][node=Name]
555.318 - ------ Attributes ---------------------------------------
555.319 - NameToInfo : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.320 - debug : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.321 - filelist : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.322 - fp : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.323 - start_dir : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.324 -
555.325 - =============================================
555.326 - namelist: FunctionDef : OffsetRange[16821,17006>
555.327 - data [bound][data][read][node=Name]
555.328 - l [bound][data][read][node=Name]
555.329 - self [bound][param][data][read][node=Name]
555.330 - ------ Attributes ---------------------------------------
555.331 - filelist : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.332 -
555.333 - =============================================
555.334 - infolist: FunctionDef : OffsetRange[17007,17149>
555.335 - self [bound][param][data][read][node=Name]
555.336 - ------ Attributes ---------------------------------------
555.337 - filelist : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.338 -
555.339 - =============================================
555.340 - printdir: FunctionDef : OffsetRange[17150,17487>
555.341 - date [bound][data][read][node=Name]
555.342 - self [bound][param][data][read][node=Name]
555.343 - zinfo [bound][data][read][node=Name]
555.344 - ------ Attributes ---------------------------------------
555.345 - filelist : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.346 -
555.347 - =============================================
555.348 - testzip: FunctionDef : OffsetRange[17488,17749>
555.349 - BadZipfile [free][read][node=Name]
555.350 - self [bound][param][data][read][node=Name]
555.351 - zinfo [bound][data][read][node=Name]
555.352 - ------ Attributes ---------------------------------------
555.353 - filelist : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.354 - read : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
555.355 -
555.356 - =============================================
555.357 - getinfo: FunctionDef : OffsetRange[17750,17875>
555.358 - name [bound][param][data][read][node=Name]
555.359 - self [bound][param][data][read][node=Name]
555.360 - ------ Attributes ---------------------------------------
555.361 - NameToInfo : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.362 -
555.363 - =============================================
555.364 - read: FunctionDef : OffsetRange[17876,19878>
555.365 - BadZipfile [free][read][node=Name]
555.366 - RuntimeError [free][read][node=Name]
555.367 - ZIP_DEFLATED [free][read][node=Name]
555.368 - ZIP_STORED [free][read][node=Name]
555.369 - _FH_EXTRA_FIELD_LENGTH [free][read][node=Name]
555.370 - _FH_FILENAME_LENGTH [free][read][node=Name]
555.371 - binascii [free][read][node=Name]
555.372 - bytes [bound][data][read][node=Name]
555.373 - crc [bound][data][read][node=Name]
555.374 - dc [bound][data][read][node=Name]
555.375 - ex [bound][data][read][node=Name]
555.376 - fheader [bound][data][read][node=Name]
555.377 - filepos [bound][data][read][node=Name]
555.378 - fname [bound][data][read][node=Name]
555.379 - name [bound][param][data][read][node=Name]
555.380 - self [bound][param][data][read][node=Name]
555.381 - stringFileHeader [free][read][node=Name]
555.382 - struct [free][read][node=Name]
555.383 - structFileHeader [free][read][node=Name]
555.384 - zinfo [bound][data][read][node=Name]
555.385 - zlib [free][read][node=Name]
555.386 - ------ Attributes ---------------------------------------
555.387 - fp : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.388 - getinfo : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
555.389 - mode : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.390 -
555.391 - =============================================
555.392 - _writecheck: FunctionDef : OffsetRange[19879,21029>
555.393 - LargeZipFile [free][read][called][node=Name]
555.394 - RuntimeError [free][read][node=Name]
555.395 - ZIP64_LIMIT [free][read][node=Name]
555.396 - ZIP_DEFLATED [free][read][node=Name]
555.397 - ZIP_STORED [free][read][node=Name]
555.398 - self [bound][param][data][read][node=Name]
555.399 - zinfo [bound][param][data][read][node=Name]
555.400 - zlib [free][read][node=Name]
555.401 - ------ Attributes ---------------------------------------
555.402 - NameToInfo : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.403 - _allowZip64 : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
555.404 - debug : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.405 - fp : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.406 - mode : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.407 -
555.408 - =============================================
555.409 - write: FunctionDef : OffsetRange[21030,23534>
555.410 - CRC [bound][data][read][node=Name]
555.411 - None [free][read][node=Name]
555.412 - True [free][read][node=Name]
555.413 - ZIP_DEFLATED [free][read][node=Name]
555.414 - ZipInfo [free][read][called][node=Name]
555.415 - arcname [bound][param][data][read][node=Name]
555.416 - binascii [free][read][node=Name]
555.417 - buf [bound][data][read][node=Name]
555.418 - cmpr [bound][data][read][node=Name]
555.419 - compress_size [bound][data][read][node=Name]
555.420 - compress_type [bound][param][data][read][node=Name]
555.421 - date_time [bound][data][read][node=Name]
555.422 - file_size [bound][data][read][node=Name]
555.423 - filename [bound][param][data][read][node=Name]
555.424 - fp [bound][data][read][node=Name]
555.425 - len [free][read][called][node=Name]
555.426 - mtime [bound][data][read][node=Name]
555.427 - open [free][read][called][node=Name]
555.428 - os [free][read][node=Name]
555.429 - position [bound][data][read][node=Name]
555.430 - self [bound][param][data][read][node=Name]
555.431 - st [bound][data][read][node=Name]
555.432 - struct [free][read][node=Name]
555.433 - time [free][read][node=Name]
555.434 - zinfo [bound][data][read][node=Name]
555.435 - zlib [free][read][node=Name]
555.436 - ------ Attributes ---------------------------------------
555.437 - NameToInfo : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.438 - _writecheck : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
555.439 - compression : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.440 - filelist : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.441 - fp : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.442 -
555.443 - =============================================
555.444 - writestr: FunctionDef : OffsetRange[23535,25110>
555.445 - True [free][read][node=Name]
555.446 - ZIP_DEFLATED [free][read][node=Name]
555.447 - ZipInfo [free][read][called][node=Name]
555.448 - binascii [free][read][node=Name]
555.449 - bytes [bound][param][data][read][node=Name]
555.450 - co [bound][data][read][node=Name]
555.451 - isinstance [free][read][called][node=Name]
555.452 - len [free][read][called][node=Name]
555.453 - self [bound][param][data][read][node=Name]
555.454 - struct [free][read][node=Name]
555.455 - time [free][read][node=Name]
555.456 - zinfo [bound][data][read][node=Name]
555.457 - zinfo_or_arcname [bound][param][data][read][node=Name]
555.458 - zlib [free][read][node=Name]
555.459 - ------ Attributes ---------------------------------------
555.460 - NameToInfo : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.461 - _writecheck : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
555.462 - compression : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.463 - filelist : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.464 - fp : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.465 -
555.466 - =============================================
555.467 - __del__: FunctionDef : OffsetRange[25111,25220>
555.468 - self [bound][param][data][read][node=Name]
555.469 - ------ Attributes ---------------------------------------
555.470 - close : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
555.471 -
555.472 - =============================================
555.473 - close: FunctionDef : OffsetRange[25221,28949>
555.474 - None [free][read][node=Name]
555.475 - ZIP64_LIMIT [free][read][node=Name]
555.476 - centdir [bound][data][read][node=Name]
555.477 - compress_size [bound][data][read][node=Name]
555.478 - count [bound][data][read][node=Name]
555.479 - create_version [bound][data][read][node=Name]
555.480 - dosdate [bound][data][read][node=Name]
555.481 - dostime [bound][data][read][node=Name]
555.482 - dt [bound][data][read][node=Name]
555.483 - endrec [bound][data][read][node=Name]
555.484 - extra [bound][data][read][node=Name]
555.485 - extra_data [bound][data][read][node=Name]
555.486 - extract_version [bound][data][read][node=Name]
555.487 - file_size [bound][data][read][node=Name]
555.488 - header_offset [bound][data][read][node=Name]
555.489 - len [free][read][called][node=Name]
555.490 - max [free][read][called][node=Name]
555.491 - pos1 [bound][data][read][node=Name]
555.492 - pos2 [bound][data][read][node=Name]
555.493 - pos3 [bound][data][unused][node=Name]
555.494 - self [bound][param][data][read][node=Name]
555.495 - stringCentralDir [free][read][node=Name]
555.496 - stringEndArchive [free][read][node=Name]
555.497 - stringEndArchive64 [free][read][node=Name]
555.498 - stringEndArchive64Locator [free][read][node=Name]
555.499 - struct [free][read][node=Name]
555.500 - structCentralDir [free][read][node=Name]
555.501 - structEndArchive [free][read][node=Name]
555.502 - structEndArchive64 [free][read][node=Name]
555.503 - structEndArchive64Locator [free][read][node=Name]
555.504 - zinfo [bound][data][read][node=Name]
555.505 - zip64endrec [bound][data][read][node=Name]
555.506 - zip64locrec [bound][data][read][node=Name]
555.507 - ------ Attributes ---------------------------------------
555.508 - _didModify : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
555.509 - _filePassed : SymInfo[16514 0 0][func-global][private][read][UNRESOLVED][node=Attribute]
555.510 - filelist : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.511 - fp : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.512 - mode : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.513 -
555.514 - =============================================
555.515 - class PyZipFile: ClassDef : OffsetRange[28949,33475>
555.516 - _get_codename [bound][private][function][def][node=FunctionDef]
555.517 - writepy [bound][function][def][node=FunctionDef]
555.518 -
555.519 - =============================================
555.520 - writepy: FunctionDef : OffsetRange[29059,32257>
555.521 - RuntimeError [free][read][node=Name]
555.522 - arcname [bound][data][read][node=Name]
555.523 - basename [bound][param][data][read][node=Name]
555.524 - dir [bound][data][unused][node=Name]
555.525 - dirlist [bound][data][read][node=Name]
555.526 - ext [bound][data][read][node=Name]
555.527 - filename [bound][data][read][node=Name]
555.528 - fname [bound][data][read][node=Name]
555.529 - initname [bound][data][read][node=Name]
555.530 - name [bound][data][read][node=Name]
555.531 - os [free][read][node=Name]
555.532 - path [bound][data][read][node=Name]
555.533 - pathname [bound][param][data][read][node=Name]
555.534 - root [bound][data][unused][node=Name]
555.535 - self [bound][param][data][read][node=Name]
555.536 - ------ Attributes ---------------------------------------
555.537 - _get_codename : SymInfo[20866 0 0][func-global][private][function][read][called][UNRESOLVED][node=Attribute]
555.538 - debug : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.539 - write : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
555.540 - writepy : SymInfo[4482 0 0][func-global][function][read][called][UNRESOLVED][node=Attribute]
555.541 -
555.542 - =============================================
555.543 - _get_codename: FunctionDef : OffsetRange[32258,33475>
555.544 - None [free][read][node=Name]
555.545 - True [free][read][node=Name]
555.546 - archivename [bound][data][read][node=Name]
555.547 - basename [bound][param][data][read][node=Name]
555.548 - err [bound][data][read][node=Name]
555.549 - file_py [bound][data][read][node=Name]
555.550 - file_pyc [bound][data][read][node=Name]
555.551 - file_pyo [bound][data][read][node=Name]
555.552 - fname [bound][data][read][node=Name]
555.553 - os [free][read][node=Name]
555.554 - pathname [bound][param][data][read][node=Name]
555.555 - py_compile [bound][imported][data][read][node=Import]
555.556 - self [bound][param][data][read][node=Name]
555.557 - ------ Attributes ---------------------------------------
555.558 - debug : SymInfo[130 0 0][func-global][read][UNRESOLVED][node=Attribute]
555.559 -
555.560 - =============================================
555.561 - main: FunctionDef : OffsetRange[33475,35583>
555.562 - None [free][private][read][node=Name]
555.563 - True [free][private][read][node=Name]
555.564 - USAGE [bound][private][data][read][node=Name]
555.565 - ZIP_DEFLATED [free][private][node=null]
555.566 - ZipFile [free][private][read][called][node=Name]
555.567 - addToZip [bound][cell][private][function][def][read][called][node=FunctionDef]
555.568 - args [bound][param][private][data][read][node=Name]
555.569 - fp [bound][private][data][read][node=Name]
555.570 - len [free][private][read][called][node=Name]
555.571 - open [free][private][read][called][node=Name]
555.572 - os [free][private][read][node=Name]
555.573 - out [bound][private][data][read][node=Name]
555.574 - path [bound][private][data][read][node=Name]
555.575 - src [bound][private][data][read][node=Name]
555.576 - sys [free][private][read][node=Name]
555.577 - textwrap [bound][imported][private][data][read][node=Import]
555.578 - tgt [bound][private][data][read][node=Name]
555.579 - tgtdir [bound][private][data][read][node=Name]
555.580 - zf [bound][private][data][read][node=Name]
555.581 - ---------------------------------------------
555.582 - inner_free: {ZIP_DEFLATED=PRESENT, addToZip=PRESENT, os=PRESENT}
555.583 - cellvars: [addToZip]
555.584 - jy_npurecell: 1
555.585 -
555.586 - =============================================
555.587 - addToZip: FunctionDef : OffsetRange[35082,35435>
555.588 - ZIP_DEFLATED [free][private][read][node=Name]
555.589 - addToZip [free][private][read][called][node=Name]
555.590 - nm [bound][private][data][read][node=Name]
555.591 - os [free][private][read][node=Name]
555.592 - path [bound][param][private][data][read][node=Name]
555.593 - zf [bound][param][private][data][read][node=Name]
555.594 - zippath [bound][param][private][data][read][node=Name]
555.595 -
556.1 --- a/python.editor/test/unit/src/META-INF/services/org.netbeans.modules.gsf.api.SourceModelFactory Sun Jan 04 13:11:53 2015 -0600
556.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
556.3 @@ -1,2 +0,0 @@
556.4 -org.netbeans.modules.gsf.TestSourceModelFactory
556.5 -#position=1
557.1 --- a/python.editor/test/unit/src/META-INF/services/org.openide.modules.InstalledFileLocator Sun Jan 04 13:11:53 2015 -0600
557.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
557.3 @@ -1,1 +0,0 @@
557.4 -org.netbeans.modules.python.editor.InstalledFileLocatorImpl
558.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/AstPathTest.java Sun Jan 04 13:11:53 2015 -0600
558.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
558.3 @@ -1,147 +0,0 @@
558.4 -/*
558.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
558.6 - *
558.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
558.8 - *
558.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
558.10 - * Other names may be trademarks of their respective owners.
558.11 - *
558.12 - * The contents of this file are subject to the terms of either the GNU
558.13 - * General Public License Version 2 only ("GPL") or the Common
558.14 - * Development and Distribution License("CDDL") (collectively, the
558.15 - * "License"). You may not use this file except in compliance with the
558.16 - * License. You can obtain a copy of the License at
558.17 - * http://www.netbeans.org/cddl-gplv2.html
558.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
558.19 - * specific language governing permissions and limitations under the
558.20 - * License. When distributing the software, include this License Header
558.21 - * Notice in each file and include the License file at
558.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
558.23 - * particular file as subject to the "Classpath" exception as provided
558.24 - * by Oracle in the GPL Version 2 section of the License file that
558.25 - * accompanied this code. If applicable, add the following below the
558.26 - * License Header, with the fields enclosed by brackets [] replaced by
558.27 - * your own identifying information:
558.28 - * "Portions Copyrighted [year] [name of copyright owner]"
558.29 - *
558.30 - * If you wish your version of this file to be governed by only the CDDL
558.31 - * or only the GPL Version 2, indicate your decision by adding
558.32 - * "[Contributor] elects to include this software in this distribution
558.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
558.34 - * single choice of license, a recipient has the option to distribute
558.35 - * your version of this file under either the CDDL, the GPL Version 2 or
558.36 - * to extend the choice of license to its licensees as provided above.
558.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
558.38 - * Version 2 license, then the option applies only if the new code is
558.39 - * made subject to such option by the copyright holder.
558.40 - *
558.41 - * Contributor(s):
558.42 - *
558.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
558.44 - */
558.45 -
558.46 -package org.netbeans.modules.python.editor;
558.47 -
558.48 -import java.util.Iterator;
558.49 -import org.netbeans.modules.gsf.api.CompilationInfo;
558.50 -import org.netbeans.modules.gsf.api.OffsetRange;
558.51 -import org.python.antlr.PythonTree;
558.52 -import org.python.antlr.ast.ClassDef;
558.53 -import org.python.antlr.ast.FunctionDef;
558.54 -
558.55 -/**
558.56 - *
558.57 - * @author Tor Norbye
558.58 - */
558.59 -public class AstPathTest extends PythonTestBase {
558.60 -
558.61 - public AstPathTest(String name) {
558.62 - super(name);
558.63 - }
558.64 -
558.65 - protected String annotatePath(AstPath path) {
558.66 - StringBuilder sb = new StringBuilder();
558.67 -
558.68 - Iterator<PythonTree> it = path.rootToLeaf();
558.69 - while (it.hasNext()) {
558.70 - PythonTree node = it.next();
558.71 -
558.72 - sb.append(node.getClass().getSimpleName());
558.73 - sb.append(":");
558.74 - OffsetRange range = PythonAstUtils.getRange(node);
558.75 - sb.append(range);
558.76 -
558.77 - sb.append("\n");
558.78 - }
558.79 -
558.80 - return sb.toString();
558.81 - }
558.82 -
558.83 - public AstPath getPath(String relFilePath, String caretLine) throws Exception {
558.84 - CompilationInfo info = getInfo(relFilePath);
558.85 - PythonTree root = PythonAstUtils.getRoot(info);
558.86 - int caretOffset = getCaretOffset(info.getText(), caretLine);
558.87 - AstPath path = AstPath.get(root, caretOffset);
558.88 -
558.89 - return path;
558.90 - }
558.91 -
558.92 - public void checkPath(String relFilePath, String caretLine) throws Exception {
558.93 - AstPath path = getPath(relFilePath, caretLine);
558.94 - String pathDesc = annotatePath(path);
558.95 - assertDescriptionMatches(relFilePath, pathDesc, true, ".path"); // NOI18N
558.96 - }
558.97 -
558.98 - public void testGetByCaretOffset() throws Exception {
558.99 - String relFilePath = "testfiles/ConfigParser.py";
558.100 - String caretLine = "Error.__init__(se^lf, \"Section %r already exists\" % section)";
558.101 - checkPath(relFilePath, caretLine);
558.102 - }
558.103 -
558.104 - public void testGetByNode1() throws Exception {
558.105 - String relFilePath = "testfiles/ConfigParser.py";
558.106 - String caretLine = "Error.__init__(se^lf, \"Section %r already exists\" % section)";
558.107 - AstPath path = getPath(relFilePath, caretLine);
558.108 -
558.109 - PythonTree node = path.leaf();
558.110 - PythonTree root = path.root();
558.111 - AstPath newPath = AstPath.get(root, node);
558.112 - String pathDesc = annotatePath(newPath);
558.113 - assertDescriptionMatches(relFilePath, pathDesc, true, ".path"); // NOI18N
558.114 - }
558.115 -
558.116 - public void testGetByNode2() throws Exception {
558.117 - String relFilePath = "testfiles/ConfigParser.py";
558.118 - String caretLine = "Error.__init__(se^lf, \"Section %r already exists\" % section)";
558.119 - AstPath path = getPath(relFilePath, caretLine);
558.120 -
558.121 - PythonTree node = path.leafParent();
558.122 - PythonTree root = path.root();
558.123 - AstPath newPath = AstPath.get(root, node);
558.124 - String pathDesc = annotatePath(newPath);
558.125 - assertDescriptionMatches(relFilePath, pathDesc, true, ".path"); // NOI18N
558.126 - }
558.127 -
558.128 - public void testGetTypedAncestor() throws Exception {
558.129 - String relFilePath = "testfiles/ConfigParser.py";
558.130 - String caretLine = "Error.__init__(se^lf, \"Section %r already exists\" % section)";
558.131 - AstPath path = getPath(relFilePath, caretLine);
558.132 - ClassDef def = (ClassDef)path.getTypedAncestor(ClassDef.class);
558.133 - assertNotNull(def);
558.134 - assertEquals("DuplicateSectionError", def.getInternalName());
558.135 - }
558.136 -
558.137 - public void testGetTypedAncestorFrom() throws Exception {
558.138 - String relFilePath = "testfiles/test_scope.py";
558.139 - String caretLine = "def meth^od_and_var(self):";
558.140 - AstPath path = getPath(relFilePath, caretLine);
558.141 - assertEquals(FunctionDef.class, path.leaf().getClass());
558.142 -
558.143 - PythonTree parent = path.leafParent();
558.144 - assertEquals(ClassDef.class, parent.getClass());
558.145 -
558.146 - FunctionDef def = (FunctionDef)path.getTypedAncestor(FunctionDef.class, parent);
558.147 - assertNotNull(def);
558.148 - assertEquals("test", def.getInternalName());
558.149 - }
558.150 -}
559.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/CompleteApiTest.java Sun Jan 04 13:11:53 2015 -0600
559.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
559.3 @@ -1,331 +0,0 @@
559.4 -/*
559.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
559.6 - *
559.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
559.8 - *
559.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
559.10 - * Other names may be trademarks of their respective owners.
559.11 - *
559.12 - * The contents of this file are subject to the terms of either the GNU
559.13 - * General Public License Version 2 only ("GPL") or the Common
559.14 - * Development and Distribution License("CDDL") (collectively, the
559.15 - * "License"). You may not use this file except in compliance with the
559.16 - * License. You can obtain a copy of the License at
559.17 - * http://www.netbeans.org/cddl-gplv2.html
559.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
559.19 - * specific language governing permissions and limitations under the
559.20 - * License. When distributing the software, include this License Header
559.21 - * Notice in each file and include the License file at
559.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
559.23 - * particular file as subject to the "Classpath" exception as provided
559.24 - * by Oracle in the GPL Version 2 section of the License file that
559.25 - * accompanied this code. If applicable, add the following below the
559.26 - * License Header, with the fields enclosed by brackets [] replaced by
559.27 - * your own identifying information:
559.28 - * "Portions Copyrighted [year] [name of copyright owner]"
559.29 - *
559.30 - * If you wish your version of this file to be governed by only the CDDL
559.31 - * or only the GPL Version 2, indicate your decision by adding
559.32 - * "[Contributor] elects to include this software in this distribution
559.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
559.34 - * single choice of license, a recipient has the option to distribute
559.35 - * your version of this file under either the CDDL, the GPL Version 2 or
559.36 - * to extend the choice of license to its licensees as provided above.
559.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
559.38 - * Version 2 license, then the option applies only if the new code is
559.39 - * made subject to such option by the copyright holder.
559.40 - *
559.41 - * Contributor(s):
559.42 - *
559.43 - * Portions Copyrighted 2009 Sun Microsystems, Inc.
559.44 - */
559.45 -package org.netbeans.modules.python.editor;
559.46 -
559.47 -import java.util.ArrayList;
559.48 -import java.util.Arrays;
559.49 -import java.util.Collections;
559.50 -import java.util.HashMap;
559.51 -import java.util.HashSet;
559.52 -import java.util.List;
559.53 -import java.util.Map;
559.54 -import java.util.Set;
559.55 -import org.netbeans.modules.gsf.GsfTestCompilationInfo;
559.56 -import org.netbeans.modules.gsf.api.IndexDocument;
559.57 -import org.netbeans.modules.gsf.api.IndexDocumentFactory;
559.58 -import org.netbeans.modules.gsf.api.ParserResult;
559.59 -import org.openide.filesystems.FileObject;
559.60 -
559.61 -/**
559.62 - * This test ensures that we're picking up all the expected
559.63 - * APIs for the various core classes (str, list, etc).
559.64 - *
559.65 - * @author Tor Norbye
559.66 - */
559.67 -public class CompleteApiTest extends PythonTestBase {
559.68 - public CompleteApiTest(String name) {
559.69 - super(name);
559.70 - }
559.71 -
559.72 - // Computed by doing things like "dir(5),dir(5.0),dir("s"),dir(1==1),dir(complex(5,1)),dir([]),dir({}),dir(5L),dir((1,2)),dir(u"s")" and
559.73 - // so on for various literal types in the python console.
559.74 - // This is for Python 2.6.1.
559.75 - String[] INT_ATTRS = new String[]{"__abs__", "__add__", "__and__", "__class__", "__cmp__", "__coerce__", "__delattr__", "__div__", "__divmod__", "__doc__", "__float__", "__floordiv__", "__format__", "__getattribute__", "__getnewargs__", "__hash__", "__hex__", "__index__", "__init__", "__int__", "__invert__", "__long__", "__lshift__", "__mod__", "__mul__", "__neg__", "__new__", "__nonzero__", "__oct__", "__or__", "__pos__", "__pow__", "__radd__", "__rand__", "__rdiv__", "__rdivmod__", "__reduce__", "__reduce_ex__", "__repr__", "__rfloordiv__", "__rlshift__", "__rmod__", "__rmul__", "__ror__", "__rpow__", "__rrshift__", "__rshift__", "__rsub__", "__rtruediv__", "__rxor__", "__setattr__", "__sizeof__", "__str__", "__sub__", "__subclasshook__", "__truediv__", "__trunc__", "__xor__", "conjugate", "denominator", "imag", "numerator", "real"};
559.76 - String[] FLOAT_ATTRS = new String[] {"__abs__", "__add__", "__class__", "__coerce__", "__delattr__", "__div__", "__divmod__", "__doc__", "__eq__", "__float__", "__floordiv__", "__format__", "__ge__", "__getattribute__", "__getformat__", "__getnewargs__", "__gt__", "__hash__", "__init__", "__int__", "__le__", "__long__", "__lt__", "__mod__", "__mul__", "__ne__", "__neg__", "__new__", "__nonzero__", "__pos__", "__pow__", "__radd__", "__rdiv__", "__rdivmod__", "__reduce__", "__reduce_ex__", "__repr__", "__rfloordiv__", "__rmod__", "__rmul__", "__rpow__", "__rsub__", "__rtruediv__", "__setattr__", "__setformat__", "__sizeof__", "__str__", "__sub__", "__subclasshook__", "__truediv__", "__trunc__", "as_integer_ratio", "conjugate", "fromhex", "hex", "imag", "is_integer", "real"};
559.77 - String[] COMPLEX_ATTRS = new String[] {"__abs__", "__add__", "__class__", "__coerce__", "__delattr__", "__div__", "__divmod__", "__doc__", "__eq__", "__float__", "__floordiv__", "__format__", "__ge__", "__getattribute__", "__getnewargs__", "__gt__", "__hash__", "__init__", "__int__", "__le__", "__long__", "__lt__", "__mod__", "__mul__", "__ne__", "__neg__", "__new__", "__nonzero__", "__pos__", "__pow__", "__radd__", "__rdiv__", "__rdivmod__", "__reduce__", "__reduce_ex__", "__repr__", "__rfloordiv__", "__rmod__", "__rmul__", "__rpow__", "__rsub__", "__rtruediv__", "__setattr__", "__sizeof__", "__str__", "__sub__", "__subclasshook__", "__truediv__", "conjugate", "imag", "real"};
559.78 - String[] BOOL_ATTRS = new String[] {"__abs__", "__add__", "__and__", "__class__", "__cmp__", "__coerce__", "__delattr__", "__div__", "__divmod__", "__doc__", "__float__", "__floordiv__", "__format__", "__getattribute__", "__getnewargs__", "__hash__", "__hex__", "__index__", "__init__", "__int__", "__invert__", "__long__", "__lshift__", "__mod__", "__mul__", "__neg__", "__new__", "__nonzero__", "__oct__", "__or__", "__pos__", "__pow__", "__radd__", "__rand__", "__rdiv__", "__rdivmod__", "__reduce__", "__reduce_ex__", "__repr__", "__rfloordiv__", "__rlshift__", "__rmod__", "__rmul__", "__ror__", "__rpow__", "__rrshift__", "__rshift__", "__rsub__", "__rtruediv__", "__rxor__", "__setattr__", "__sizeof__", "__str__", "__sub__", "__subclasshook__", "__truediv__", "__trunc__", "__xor__", "conjugate", "denominator", "imag", "numerator", "real"};
559.79 - String[] STR_ATTRS = new String[] {"__add__", "__class__", "__contains__", "__delattr__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__getitem__", "__getnewargs__", "__getslice__", "__gt__", "__hash__", "__init__", "__le__", "__len__", "__lt__", "__mod__", "__mul__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__rmod__", "__rmul__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "_formatter_field_name_split", "_formatter_parser", "capitalize", "center", "count", "decode", "encode", "endswith", "expandtabs", "find", "format", "index", "isalnum", "isalpha", "isdigit", "islower", "isspace", "istitle", "isupper", "join", "ljust", "lower", "lstrip", "partition", "replace", "rfind", "rindex", "rjust", "rpartition", "rsplit", "rstrip", "split", "splitlines", "startswith", "strip", "swapcase", "title", "translate", "upper", "zfill"};
559.80 - String[] LIST_ATTRS = new String[] {"__add__", "__class__", "__contains__", "__delattr__", "__delitem__", "__delslice__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__getitem__", "__getslice__", "__gt__", "__hash__", "__iadd__", "__imul__", "__init__", "__iter__", "__le__", "__len__", "__lt__", "__mul__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__reversed__", "__rmul__", "__setattr__", "__setitem__", "__setslice__", "__sizeof__", "__str__", "__subclasshook__", "append", "count", "extend", "index", "insert", "pop", "remove", "reverse", "sort"};
559.81 - String[] DICT_ATTRS = new String[] {"__class__", "__cmp__", "__contains__", "__delattr__", "__delitem__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__getitem__", "__gt__", "__hash__", "__init__", "__iter__", "__le__", "__len__", "__lt__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__setitem__", "__sizeof__", "__str__", "__subclasshook__", "clear", "copy", "fromkeys", "get", "has_key", "items", "iteritems", "iterkeys", "itervalues", "keys", "pop", "popitem", "setdefault", "update", "values"};
559.82 - String[] TUPLE_ATTRS = new String[] {"__add__", "__class__", "__contains__", "__delattr__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__getitem__", "__getnewargs__", "__getslice__", "__gt__", "__hash__", "__init__", "__iter__", "__le__", "__len__", "__lt__", "__mul__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__rmul__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "count", "index"};
559.83 - String[] LONG_ATTRS = new String[] {"__abs__", "__add__", "__and__", "__class__", "__cmp__", "__coerce__", "__delattr__", "__div__", "__divmod__", "__doc__", "__float__", "__floordiv__", "__format__", "__getattribute__", "__getnewargs__", "__hash__", "__hex__", "__index__", "__init__", "__int__", "__invert__", "__long__", "__lshift__", "__mod__", "__mul__", "__neg__", "__new__", "__nonzero__", "__oct__", "__or__", "__pos__", "__pow__", "__radd__", "__rand__", "__rdiv__", "__rdivmod__", "__reduce__", "__reduce_ex__", "__repr__", "__rfloordiv__", "__rlshift__", "__rmod__", "__rmul__", "__ror__", "__rpow__", "__rrshift__", "__rshift__", "__rsub__", "__rtruediv__", "__rxor__", "__setattr__", "__sizeof__", "__str__", "__sub__", "__subclasshook__", "__truediv__", "__trunc__", "__xor__", "conjugate", "denominator", "imag", "numerator", "real"};
559.84 - String[] UNICODE_ATTRS = new String[] {"__add__", "__class__", "__contains__", "__delattr__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__getitem__", "__getnewargs__", "__getslice__", "__gt__", "__hash__", "__init__", "__le__", "__len__", "__lt__", "__mod__", "__mul__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__rmod__", "__rmul__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "_formatter_field_name_split", "_formatter_parser", "capitalize", "center", "count", "decode", "encode", "endswith", "expandtabs", "find", "format", "index", "isalnum", "isalpha", "isdecimal", "isdigit", "islower", "isnumeric", "isspace", "istitle", "isupper", "join", "ljust", "lower", "lstrip", "partition", "replace", "rfind", "rindex", "rjust", "rpartition", "rsplit", "rstrip", "split", "splitlines", "startswith", "strip", "swapcase", "title", "translate", "upper", "zfill"};
559.85 -
559.86 - private static void appendList(StringBuilder sb, List<String> list) {
559.87 - sb.append("{ ");
559.88 - boolean first = true;
559.89 - for (String m : list) {
559.90 - if (first) {
559.91 - first = false;
559.92 - } else {
559.93 - sb.append(", ");
559.94 - }
559.95 - sb.append('"');
559.96 - sb.append(m);
559.97 - sb.append('"');
559.98 - }
559.99 - sb.append(" }; ");
559.100 - }
559.101 -
559.102 - public void checkFile(String clz, String[] attrs, String... relFilePaths) throws Exception {
559.103 - Set<String> defined = new HashSet<String>(100);
559.104 - boolean foundClass = false;
559.105 -
559.106 - for (String relFilePath : relFilePaths) {
559.107 - List<IndexDocument> result = indexFile(relFilePath);
559.108 -
559.109 - IndexDocumentImpl clzDoc = null;
559.110 - for (IndexDocument doc : result) {
559.111 - assertTrue(doc instanceof IndexDocumentImpl);
559.112 - IndexDocumentImpl idoc = (IndexDocumentImpl)doc;
559.113 - for (int i = 0; i < idoc.indexedKeys.size(); i++) {
559.114 - if (PythonIndexer.FIELD_CLASS_NAME.equals(idoc.indexedKeys.get(i))) {
559.115 - if (clz.equals(idoc.indexedValues.get(i))) {
559.116 - clzDoc = idoc;
559.117 - break;
559.118 - }
559.119 - }
559.120 - if (clzDoc != null) {
559.121 - break;
559.122 - }
559.123 - }
559.124 - }
559.125 -
559.126 - if (clzDoc == null) {
559.127 - continue;
559.128 - }
559.129 - foundClass = true;
559.130 -
559.131 - for (int i = 0; i < clzDoc.indexedKeys.size(); i++) {
559.132 - String key = clzDoc.indexedKeys.get(i);
559.133 - if (PythonIndexer.FIELD_MEMBER.equals(key)) {
559.134 - String value = clzDoc.indexedValues.get(i);
559.135 - int semi = value.indexOf(';');
559.136 - if (semi != -1) {
559.137 - value = value.substring(0, semi);
559.138 - }
559.139 - defined.add(value);
559.140 - }
559.141 - }
559.142 - }
559.143 -
559.144 - if (!foundClass) {
559.145 - StringBuilder sb = new StringBuilder();
559.146 - sb.append("No class definition whatsoever for ");
559.147 - sb.append(clz);
559.148 - sb.append(" : ");
559.149 - appendList(sb, Arrays.asList(attrs));
559.150 -
559.151 - fail(sb.toString());
559.152 - }
559.153 -
559.154 - // Now check that all attributes are accounted for (and produce a complete list)
559.155 - List<String> missing = new ArrayList<String>();
559.156 - for (String attribute : attrs) {
559.157 - // Current exceptions - not yet handled
559.158 - if ("__reduce__".equals(attribute) ||
559.159 - "__reduce_ex__".equals(attribute)) {
559.160 - continue;
559.161 - }
559.162 -
559.163 -
559.164 - if (!defined.contains(attribute)) {
559.165 - missing.add(attribute);
559.166 - }
559.167 - }
559.168 -
559.169 - if (missing.size() > 0) {
559.170 - StringBuilder sb = new StringBuilder();
559.171 - sb.append("Class ");
559.172 - sb.append(clz);
559.173 - sb.append(" is missing definitions for: ");
559.174 - appendList(sb, missing);
559.175 -
559.176 - fail(sb.toString());
559.177 - }
559.178 -
559.179 - Set<String> extra = new HashSet<String>(defined);
559.180 - for (String attribute : attrs) {
559.181 - extra.remove(attribute);
559.182 - }
559.183 -
559.184 - if (extra.size() > 0) {
559.185 - StringBuilder sb = new StringBuilder();
559.186 - sb.append("Class ");
559.187 - sb.append(clz);
559.188 - sb.append(" is defining extra names that should not be present: ");
559.189 - List<String> extraList = new ArrayList<String>(extra);
559.190 - Collections.sort(extraList);
559.191 - appendList(sb, extraList);
559.192 -
559.193 - fail(sb.toString());
559.194 - }
559.195 - }
559.196 -
559.197 - public void testFloat() throws Exception {
559.198 - checkFile("float", FLOAT_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
559.199 - }
559.200 -
559.201 - public void testInt() throws Exception {
559.202 - checkFile("int", INT_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
559.203 - }
559.204 -
559.205 - public void testComplex() throws Exception {
559.206 - checkFile("complex", COMPLEX_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
559.207 - }
559.208 -
559.209 - public void testBool() throws Exception {
559.210 - checkFile("bool", BOOL_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
559.211 - }
559.212 -
559.213 - public void testStr() throws Exception {
559.214 - checkFile("str", STR_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
559.215 - }
559.216 -
559.217 - public void testList() throws Exception {
559.218 - checkFile("list", LIST_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
559.219 - }
559.220 -
559.221 - public void testDict() throws Exception {
559.222 - checkFile("dict", DICT_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
559.223 - }
559.224 -
559.225 - public void testTuple() throws Exception {
559.226 - checkFile("tuple", TUPLE_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
559.227 - }
559.228 -
559.229 - public void testLong() throws Exception {
559.230 - checkFile("long", LONG_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
559.231 - }
559.232 -
559.233 - public void testUnicode() throws Exception {
559.234 - checkFile("unicode", UNICODE_ATTRS, "testfiles/rst/stdtypes.rst", "testfiles/rst/operator.rst", "testfiles/rst/stub_missing.rst");
559.235 - }
559.236 -
559.237 -// Generate a list of documented APIs
559.238 -// public void testGenerateDocumentedNames() throws Exception {
559.239 -// FileObject fo = getClusterHome().getFileObject("pythonstubs/pythonstubs-2_6_1.egg");
559.240 -// assertNotNull(fo);
559.241 -// GsfTestCompilationInfo info = getInfo(fo);
559.242 -// ParserResult rpr = info.getEmbeddedResult(info.getPreferredMimeType(), 0);
559.243 -// assertNotNull(rpr);
559.244 -//
559.245 -// PythonIndexer indexer = new PythonIndexer();
559.246 -// IndexDocumentFactory factory = new IndexDocumentFactoryImpl(/*info.getIndex(info.getPreferredMimeType())*/);
559.247 -// List<IndexDocument> result = indexer.index(rpr, factory);
559.248 -// assertNotNull(result);
559.249 -//
559.250 -// String[] RELEVANT = { "int", "float", "long", "complex", "list", "dict", "tuple", "str", "unicode" };
559.251 -//
559.252 -// // Generate a name document for Python inclusion into the extract_rst file
559.253 -// // This lists all the names for each class that we've defined
559.254 -// Map<String,Set<String>> classes = new HashMap<String,Set<String>>();
559.255 -//
559.256 -// for (IndexDocument idoc : result) {
559.257 -// IndexDocumentImpl doc = (IndexDocumentImpl)idoc;
559.258 -//
559.259 -// if (doc.overrideUrl.indexOf("stub_missing") != -1) {
559.260 -// continue;
559.261 -// }
559.262 -//
559.263 -// List<String> members = new ArrayList<String>();
559.264 -// String cls = null;
559.265 -// for (int i = 0, n = doc.indexedKeys.size(); i < n; i++) {
559.266 -// String key = doc.indexedKeys.get(i);
559.267 -// if (PythonIndexer.FIELD_MEMBER.equals(key)) {
559.268 -// String member = doc.indexedValues.get(i);
559.269 -// int idx = member.indexOf(';');
559.270 -// if (idx != -1) {
559.271 -// member = member.substring(0, idx);
559.272 -// }
559.273 -// members.add(member);
559.274 -// } else if (PythonIndexer.FIELD_CLASS_NAME.equals(key)) {
559.275 -// cls = doc.indexedValues.get(i);
559.276 -// }
559.277 -// }
559.278 -// if (members.size() > 0) {
559.279 -// assertNotNull(cls);
559.280 -// boolean found = false;
559.281 -// for (String s : RELEVANT) {
559.282 -// if (s.equals(cls)) {
559.283 -// found = true;
559.284 -// break;
559.285 -// }
559.286 -// }
559.287 -// if (!found) {
559.288 -// continue;
559.289 -// }
559.290 -// Set<String> memberSet = classes.get(cls);
559.291 -// if (memberSet == null) {
559.292 -// memberSet = new HashSet<String>();
559.293 -// classes.put(cls, memberSet);
559.294 -// }
559.295 -// //memberSet.addAll(members);
559.296 -// for (String member : members) {
559.297 -// if (memberSet.contains(member)) {
559.298 -// System.err.println("WARNING: Class " + cls + " already contains " + member);
559.299 -// }
559.300 -// memberSet.add(member);
559.301 -// }
559.302 -// }
559.303 -// }
559.304 -//
559.305 -// List<String> classNames = new ArrayList<String>(classes.keySet());
559.306 -// Collections.sort(classNames);
559.307 -// StringBuilder sb = new StringBuilder();
559.308 -// for (String cls : classNames) {
559.309 -// Set<String> memberSet = classes.get(cls);
559.310 -// assertNotNull(memberSet);
559.311 -//
559.312 -// List<String> members = new ArrayList<String>(memberSet);
559.313 -// Collections.sort(members);
559.314 -// sb.append("'");
559.315 -// sb.append(cls);
559.316 -// sb.append("': [");
559.317 -// boolean first = true;
559.318 -// for (String member : members) {
559.319 -// if (first) {
559.320 -// first = false;
559.321 -// } else {
559.322 -// sb.append(", ");
559.323 -// }
559.324 -// sb.append("'");
559.325 -// sb.append(member);
559.326 -// sb.append("'");
559.327 -// }
559.328 -// sb.append("],\n");
559.329 -// }
559.330 -//
559.331 -// System.out.println(sb.toString());
559.332 -// }
559.333 -
559.334 -}
560.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/InstalledFileLocatorImpl.java Sun Jan 04 13:11:53 2015 -0600
560.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
560.3 @@ -1,92 +0,0 @@
560.4 -/*
560.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
560.6 - *
560.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
560.8 - *
560.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
560.10 - * Other names may be trademarks of their respective owners.
560.11 - *
560.12 - * The contents of this file are subject to the terms of either the GNU
560.13 - * General Public License Version 2 only ("GPL") or the Common
560.14 - * Development and Distribution License("CDDL") (collectively, the
560.15 - * "License"). You may not use this file except in compliance with the
560.16 - * License. You can obtain a copy of the License at
560.17 - * http://www.netbeans.org/cddl-gplv2.html
560.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
560.19 - * specific language governing permissions and limitations under the
560.20 - * License. When distributing the software, include this License Header
560.21 - * Notice in each file and include the License file at
560.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
560.23 - * particular file as subject to the "Classpath" exception as provided
560.24 - * by Oracle in the GPL Version 2 section of the License file that
560.25 - * accompanied this code. If applicable, add the following below the
560.26 - * License Header, with the fields enclosed by brackets [] replaced by
560.27 - * your own identifying information:
560.28 - * "Portions Copyrighted [year] [name of copyright owner]"
560.29 - *
560.30 - * The Original Software is NetBeans. The Initial Developer of the Original
560.31 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun
560.32 - * Microsystems, Inc. All Rights Reserved.
560.33 - *
560.34 - * If you wish your version of this file to be governed by only the CDDL
560.35 - * or only the GPL Version 2, indicate your decision by adding
560.36 - * "[Contributor] elects to include this software in this distribution
560.37 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
560.38 - * single choice of license, a recipient has the option to distribute
560.39 - * your version of this file under either the CDDL, the GPL Version 2 or
560.40 - * to extend the choice of license to its licensees as provided above.
560.41 - * However, if you add GPL Version 2 code and therefore, elected the GPL
560.42 - * Version 2 license, then the option applies only if the new code is
560.43 - * made subject to such option by the copyright holder.
560.44 - */
560.45 -package org.netbeans.modules.python.editor;
560.46 -
560.47 -import java.io.File;
560.48 -import java.io.IOException;
560.49 -import org.openide.modules.InstalledFileLocator;
560.50 -import org.openide.util.Exceptions;
560.51 -
560.52 -public final class InstalledFileLocatorImpl extends InstalledFileLocator {
560.53 -
560.54 - public InstalledFileLocatorImpl() {
560.55 - }
560.56 -
560.57 - public
560.58 - @Override
560.59 - File locate(String relativePath, String codeNameBase, boolean localized) {
560.60 - if (relativePath.equals("jython-2.5.1")) {
560.61 - return PythonTestBase.getXTestPythonHome();
560.62 - } else if (relativePath.startsWith("jython-2.5.1" + File.separator)) {
560.63 - return new File(PythonTestBase.getXTestPythonHome(), relativePath.substring("jython-2.5.1".length() + 1));
560.64 - } else if (relativePath.equals("platform_info.py")) {
560.65 - String script = System.getProperty("xtest.platform_info.py");
560.66 - if (script == null) {
560.67 - throw new RuntimeException("xtest.platform_info.rb property has to be set when running within binary distribution");
560.68 - }
560.69 - return new File(script);
560.70 - } else if ("coverage/coverage.py".equals(relativePath) || "coverage/coverage_wrapper.py".equals(relativePath)) {
560.71 - try {
560.72 - return new File(PythonTestBase.getXTestPythonHome().getParentFile(), relativePath.replace("/", File.separator)).getCanonicalFile();
560.73 - } catch (IOException ex) {
560.74 - Exceptions.printStackTrace(ex);
560.75 - throw new RuntimeException("Couldn't find coverage files");
560.76 - }
560.77 - } else if (relativePath.equals("modules/org-netbeans-modules-python-editor.jar")) {
560.78 - // During test?
560.79 - // HACK - TODO use mock
560.80 - String jsDir = System.getProperty("xtest.python.home"); // NOI18N
560.81 - if (jsDir == null) {
560.82 - throw new RuntimeException("xtest.python.home property has to be set when running within binary distribution");
560.83 - }
560.84 - File jsStubs = new File(jsDir + File.separator + ".." + File.separator + "modules" + File.separator + "org-netbeans-modules-python-editor.jar"); // NOI18N
560.85 - if (jsStubs.exists()) {
560.86 - try {
560.87 - return jsStubs.getCanonicalFile();
560.88 - } catch (IOException ex) {
560.89 - Exceptions.printStackTrace(ex);
560.90 - }
560.91 - }
560.92 - }
560.93 - return null;
560.94 - }
560.95 -}
561.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonAstOffsetsTest.java Sun Jan 04 13:11:53 2015 -0600
561.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
561.3 @@ -1,101 +0,0 @@
561.4 -/*
561.5 - * To change this template, choose Tools | Templates
561.6 - * and open the template in the editor.
561.7 - */
561.8 -
561.9 -package org.netbeans.modules.python.editor;
561.10 -
561.11 -import java.util.List;
561.12 -import java.util.Map;
561.13 -import org.netbeans.modules.gsf.api.CompilationInfo;
561.14 -import org.netbeans.modules.gsf.api.OffsetRange;
561.15 -import org.netbeans.modules.gsf.api.ParserResult;
561.16 -import org.python.antlr.PythonTree;
561.17 -import org.python.antlr.Visitor;
561.18 -
561.19 -/**
561.20 - * Test offsets in the python parse trees
561.21 - *
561.22 - * @author Tor Norbye
561.23 - */
561.24 -public class PythonAstOffsetsTest extends PythonTestBase {
561.25 - public PythonAstOffsetsTest(String testName) {
561.26 - super(testName);
561.27 - }
561.28 -
561.29 - @Override
561.30 - protected String describeNode(CompilationInfo info, Object obj, boolean includePath) throws Exception {
561.31 - return obj.toString();
561.32 - }
561.33 -
561.34 - @Override
561.35 - protected void initializeNodes(CompilationInfo info, ParserResult result, List<Object> validNodes,
561.36 - Map<Object,OffsetRange> positions, List<Object> invalidNodes) throws Exception {
561.37 - PythonTree root = PythonAstUtils.getRoot(info);
561.38 - assertNotNull(root);
561.39 -
561.40 - new TreeVisitor(validNodes, invalidNodes, positions, info).visit(root);
561.41 - }
561.42 -
561.43 - public void testOffsets1() throws Exception {
561.44 - checkOffsets("testfiles/empty.py");
561.45 - }
561.46 -
561.47 - public void testOffsets2() throws Exception {
561.48 - checkOffsets("testfiles/ConfigParser.py");
561.49 - }
561.50 -
561.51 - public void testOffsets3() throws Exception {
561.52 - checkOffsets("testfiles/datetime.py");
561.53 - }
561.54 -
561.55 - public void testOffsets4() throws Exception {
561.56 - checkOffsets("testfiles/getopt.py");
561.57 - }
561.58 -
561.59 - public void testOffsets5() throws Exception {
561.60 - checkOffsets("testfiles/test_scope.py");
561.61 - }
561.62 -
561.63 - public void testAttributes() throws Exception {
561.64 - checkOffsets("testfiles/attribute.py");
561.65 - }
561.66 -
561.67 - public void testDecorators() throws Exception {
561.68 - checkOffsets("testfiles/staticmethods.py");
561.69 - }
561.70 -
561.71 - public void test149618() throws Exception {
561.72 - checkOffsets("testfiles/issue149618.py");
561.73 - }
561.74 -
561.75 - private static class TreeVisitor extends Visitor {
561.76 - private List<Object> validNodes;
561.77 - private List<Object> invalidNodes;
561.78 - private Map<Object, OffsetRange> positions;
561.79 -
561.80 - TreeVisitor(List<Object> validNodes, List<Object> invalidNodes, Map<Object,
561.81 - OffsetRange> positions, CompilationInfo info) {
561.82 - this.validNodes = validNodes;
561.83 - this.invalidNodes = invalidNodes;
561.84 - this.positions = positions;
561.85 - }
561.86 -
561.87 - @Override
561.88 - public void traverse(PythonTree node) throws Exception {
561.89 - assertTrue(node.getCharStartIndex() <= node.getCharStopIndex());
561.90 -
561.91 - OffsetRange range = new OffsetRange(node.getCharStartIndex(), node.getCharStopIndex());
561.92 - if (range.getStart() != 0 || range.getEnd() != 0) { // Don't include 0-0 PythonTrees, these are errors
561.93 - validNodes.add(node);
561.94 - positions.put(node, range);
561.95 - } else {
561.96 - invalidNodes.add(node);
561.97 - }
561.98 -
561.99 - super.traverse(node);
561.100 - }
561.101 -
561.102 - }
561.103 -
561.104 -}
562.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonAstUtilsTest.java Sun Jan 04 13:11:53 2015 -0600
562.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
562.3 @@ -1,185 +0,0 @@
562.4 -/*
562.5 - * To change this template, choose Tools | Templates
562.6 - * and open the template in the editor.
562.7 - */
562.8 -
562.9 -package org.netbeans.modules.python.editor;
562.10 -
562.11 -import java.util.ArrayList;
562.12 -import java.util.List;
562.13 -import org.netbeans.modules.gsf.GsfTestCompilationInfo;
562.14 -import org.netbeans.modules.gsf.api.CompilationInfo;
562.15 -import org.openide.filesystems.FileObject;
562.16 -import org.openide.filesystems.FileUtil;
562.17 -import org.python.antlr.PythonTree;
562.18 -import org.python.antlr.Visitor;
562.19 -import org.python.antlr.ast.Call;
562.20 -import org.python.antlr.ast.FunctionDef;
562.21 -import org.python.antlr.base.expr;
562.22 -
562.23 -/**
562.24 - *
562.25 - * @author Tor Norbye
562.26 - */
562.27 -public class PythonAstUtilsTest extends PythonTestBase {
562.28 -
562.29 - public PythonAstUtilsTest(String testName) {
562.30 - super(testName);
562.31 - }
562.32 -
562.33 - public void testScope() throws Exception {
562.34 - String relFilePath = "testfiles/ConfigParser.py";
562.35 - String caretLine = "Error.__init__(se^lf, \"Section %r already exists\" % section)";
562.36 -
562.37 - CompilationInfo info = getInfo(relFilePath);
562.38 - PythonTree root = PythonAstUtils.getRoot(info);
562.39 - int lineOffset = caretLine.indexOf('^');
562.40 - assertTrue(lineOffset != -1);
562.41 - caretLine = caretLine.substring(0, lineOffset) + caretLine.substring(lineOffset+1);
562.42 - int offset = info.getText().indexOf(caretLine)+lineOffset;
562.43 -
562.44 - AstPath path = AstPath.get(root, offset);
562.45 -
562.46 -// assertEquals("ClassDef", PythonAstUtils.getClassDef(path).toString());
562.47 - assertEquals("ClassDef", PythonAstUtils.getClassScope(path).toString());
562.48 - assertEquals("FunctionDef", PythonAstUtils.getLocalScope(path).toString());
562.49 - }
562.50 -
562.51 - public void testGetParamters() throws Exception {
562.52 - String relFilePath = "testfiles/ConfigParser.py";
562.53 - String caretLine = "Error.__init__(se^lf, \"Section %r already exists\" % section)";
562.54 -
562.55 - CompilationInfo info = getInfo(relFilePath);
562.56 - PythonTree root = PythonAstUtils.getRoot(info);
562.57 - int lineOffset = caretLine.indexOf('^');
562.58 - assertTrue(lineOffset != -1);
562.59 - caretLine = caretLine.substring(0, lineOffset) + caretLine.substring(lineOffset+1);
562.60 - int offset = info.getText().indexOf(caretLine)+lineOffset;
562.61 -
562.62 - AstPath path = AstPath.get(root, offset);
562.63 -
562.64 - FunctionDef def = (FunctionDef)PythonAstUtils.getLocalScope(path);
562.65 - assertEquals("[self, section]", PythonAstUtils.getParameters(def).toString());
562.66 - }
562.67 -
562.68 - public void testDecorators() throws Exception {
562.69 - String relFilePath = "testfiles/staticmethods.py";
562.70 -
562.71 - CompilationInfo info = getInfo(relFilePath);
562.72 - PythonTree root = PythonAstUtils.getRoot(info);
562.73 - List<PythonTree> nodes = getAllNodes(root);
562.74 - int count = 0;
562.75 - for (PythonTree node : nodes) {
562.76 - if (node instanceof FunctionDef) {
562.77 - boolean result=PythonAstUtils.isStaticMethod(node);
562.78 - /** Three function in the relFilePath [False, True, True]**/
562.79 - if (count==0)
562.80 - assertEquals(result, false);
562.81 - if (count>1)
562.82 - assertEquals(result, true);
562.83 - count += 1;
562.84 - }
562.85 - }
562.86 - }
562.87 -
562.88 - public void testStress() throws Exception {
562.89 - List<FileObject> files = findJythonFiles();
562.90 -
562.91 - int MAX_FILES = Integer.MAX_VALUE;
562.92 -
562.93 - for (int i = 0; i < files.size() && i < MAX_FILES; i++) {
562.94 - FileObject fo = files.get(i);
562.95 - GsfTestCompilationInfo info = getInfo(fo);
562.96 - PythonTree root = PythonAstUtils.getRoot(info);
562.97 - assertNotNull(FileUtil.getFileDisplayName(fo), root);
562.98 - List<PythonTree> nodes = getAllNodes(root);
562.99 - for (PythonTree node : nodes) {
562.100 - if (node instanceof Call) {
562.101 - PythonAstUtils.getCallName((Call)node);
562.102 - PythonAstUtils.isGetter((Call)node, false);
562.103 - }
562.104 - PythonAstUtils.getDocumentation(node);
562.105 - PythonAstUtils.getDocumentationNode(node);
562.106 - if (node instanceof expr) {
562.107 - PythonAstUtils.getExprName((expr)node);
562.108 - }
562.109 - PythonAstUtils.getName(node);
562.110 - PythonAstUtils.isNameNode(node);
562.111 - PythonAstUtils.getRange(node);
562.112 - PythonAstUtils.getNameRange(info, node);
562.113 - if (node instanceof FunctionDef) {
562.114 - PythonAstUtils.getParameters((FunctionDef)node);
562.115 - }
562.116 -
562.117 - //Document doc = info.getDocument();
562.118 - //for (int offset = 0; offset < doc.getLength(); offset++) {
562.119 - // assertNull("Handling " + FileUtil.getFileDisplayName(fo) + " at offset " + offset, PythonOccurrencesMarker.error);
562.120 - //}
562.121 -
562.122 - }
562.123 -
562.124 - final List<PythonTree> defs = new ArrayList<PythonTree>();
562.125 - PythonAstUtils.addNodesByType(root, new Class[] { PythonTree.class }, defs);
562.126 - new NodeFinder(new AstPathChecker() {
562.127 - public void check(AstPath path) {
562.128 - PythonAstUtils.getClassDef(path);
562.129 - PythonAstUtils.getClassScope(path);
562.130 - PythonAstUtils.getFuncDef(path);
562.131 - PythonAstUtils.getLocalScope(path);
562.132 - PythonAstUtils.getParentClassFromNode(path, null, "");
562.133 - PythonAstUtils.getParentClassFromNode(path, path.leaf(), "");
562.134 - for (PythonTree def : defs) {
562.135 - PythonAstUtils.isClassMethod(path, (FunctionDef)def);
562.136 - }
562.137 - }
562.138 - }).visit(root);
562.139 - }
562.140 - }
562.141 -
562.142 - interface AstPathChecker {
562.143 - void check(AstPath path);
562.144 - }
562.145 -
562.146 - private static class NodeFinder extends Visitor {
562.147 - private ArrayList<PythonTree> path = new ArrayList<PythonTree>();
562.148 - private AstPathChecker checker;
562.149 -
562.150 - private NodeFinder(AstPathChecker checker) {
562.151 - this.checker = checker;
562.152 - }
562.153 -
562.154 - @Override
562.155 - public void traverse(PythonTree node) throws Exception {
562.156 - path.add(node);
562.157 -
562.158 - checker.check(new AstPath(path));
562.159 -
562.160 - super.traverse(node);
562.161 - path.remove(path.size()-1);
562.162 - }
562.163 - }
562.164 -
562.165 -// public void testFindSpecialNodeTypes() throws Exception {
562.166 -// List<FileObject> files = findJythonFiles();
562.167 -//
562.168 -// int MAX_FILES = Integer.MAX_VALUE;
562.169 -//
562.170 -// for (int i = 0; i < files.size() && i < MAX_FILES; i++) {
562.171 -// final FileObject fo = files.get(i);
562.172 -// GsfTestCompilationInfo info = getInfo(fo);
562.173 -// PythonTree root = PythonAstUtils.getRoot(info);
562.174 -// new Visitor() {
562.175 -//
562.176 -// @Override
562.177 -// public Object visitGlobal(Global node) throws Exception {
562.178 -// String s = fo.getNameExt();
562.179 -// fail(s);
562.180 -// return super.visitGlobal(node);
562.181 -// }
562.182 -//
562.183 -// }.visit(root);
562.184 -// }
562.185 -// }
562.186 -
562.187 -
562.188 -}
563.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonCodeCompleterTest.java Sun Jan 04 13:11:53 2015 -0600
563.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
563.3 @@ -1,292 +0,0 @@
563.4 -/*
563.5 - * To change this template, choose Tools | Templates
563.6 - * and open the template in the editor.
563.7 - */
563.8 -package org.netbeans.modules.python.editor;
563.9 -
563.10 -import java.net.URL;
563.11 -import java.util.List;
563.12 -
563.13 -/**
563.14 - *
563.15 - * @author Tor Norbye
563.16 - */
563.17 -public class PythonCodeCompleterTest extends PythonTestBase {
563.18 - public PythonCodeCompleterTest(String testName) {
563.19 - super(testName);
563.20 - }
563.21 - private boolean skipJython = false;
563.22 -
563.23 - @Override
563.24 - protected boolean skipRhs() {
563.25 - return true;
563.26 - }
563.27 -
563.28 - @Override
563.29 - protected List<URL> getExtraCpUrls() {
563.30 - // I'm overriding various Jython classes here for tests which causes
563.31 - // confusion when it's trying to locate classes and finds it in multiple places
563.32 - if (!skipJython) {
563.33 - return super.getExtraCpUrls();
563.34 - }
563.35 -
563.36 - return null;
563.37 - }
563.38 -
563.39 - public void testLocals1() throws Exception {
563.40 - checkCompletion("testfiles/ConfigParser.py", "s^elf.section = section", true);
563.41 - }
563.42 -
563.43 - public void testClasses2() throws Exception {
563.44 - checkCompletion("testfiles/ConfigParser.py", "raise D^uplicateSectionError(section)", true);
563.45 - }
563.46 -
563.47 - public void testStringCompletion() throws Exception {
563.48 - checkCompletion("testfiles/ConfigParser.py", "in \"^rR\"", true);
563.49 - }
563.50 -
563.51 - public void testNoStringCompletion() throws Exception {
563.52 - checkCompletion("testfiles/test_scope.py", "r\"i^mport", true);
563.53 - }
563.54 -
563.55 - public void testImports2() throws Exception {
563.56 - checkCompletion("testfiles/ConfigParser.py", "import r^e", true);
563.57 - }
563.58 -
563.59 - public void testImports7() throws Exception {
563.60 - checkCompletion("testfiles/imports7.py", "import ^", true);
563.61 - }
563.62 -
563.63 - public void testImports8() throws Exception {
563.64 - checkCompletion("testfiles/imports8.py", "import distutils.com^mand", true);
563.65 - }
563.66 -
563.67 - public void testImports9() throws Exception {
563.68 - checkCompletion("testfiles/imports9.py", "from difflib import ^c", true);
563.69 - }
563.70 -
563.71 - public void testFromImports() throws Exception {
563.72 - checkCompletion("testfiles/fromimports.py", "core.^g", true);
563.73 - }
563.74 -
563.75 - public void testDoc1() throws Exception {
563.76 - try {
563.77 - skipJython = true;
563.78 - checkCompletionDocumentation("testfiles/SocketServer.py", "class TCPServer(BaseSer^ver):", true, "BaseServer");
563.79 - } finally {
563.80 - skipJython = false;
563.81 - }
563.82 - }
563.83 -
563.84 - public void testDoc2() throws Exception {
563.85 - try {
563.86 - skipJython = true;
563.87 - checkCompletionDocumentation("testfiles/SocketServer.py", "class BaseRequestHandler^:", true, "BaseRequestHandler");
563.88 - } finally {
563.89 - skipJython = false;
563.90 - }
563.91 - }
563.92 -
563.93 - public void testDoc3() throws Exception {
563.94 - try {
563.95 - skipJython = true;
563.96 - checkCompletionDocumentation("testfiles/pickle.py", "import ^re", true, "pickle");
563.97 - } finally {
563.98 - skipJython = false;
563.99 - }
563.100 - }
563.101 -
563.102 - public void testDoc5() throws Exception {
563.103 - try {
563.104 - skipJython = true;
563.105 - // Treat r"""raw strings""" specially - as preformatted content perhaps?
563.106 - checkCompletionDocumentation("testfiles/pickle.py", "decode_lo^ng", true, "decode_long");
563.107 - } finally {
563.108 - skipJython = false;
563.109 - }
563.110 - }
563.111 -
563.112 - public void testFutureImport1() throws Exception {
563.113 - try {
563.114 - skipJython = true;
563.115 - checkCompletion("testfiles/futureimport.py", "import ^", true);
563.116 - } finally {
563.117 - skipJython = false;
563.118 - }
563.119 - }
563.120 -
563.121 - public void testDoc6() throws Exception {
563.122 - // Find documentation for a method that doesn't actually have a def - it's an alias
563.123 - checkCompletionDocumentation("testfiles/compl5.py", "self.assertA^lmostEquals(1,2)", true, "assertAlmostEquals");
563.124 - }
563.125 -
563.126 - public void testObjMethodCompletion2() throws Exception {
563.127 - checkCompletion("testfiles/compl.py", "self.^my", true);
563.128 - }
563.129 -
563.130 - public void testObjMethodCompletion3() throws Exception {
563.131 - // Test that imports of symbols in a
563.132 - checkCompletion("testfiles/compl2.py", "print w^hatever.r", true);
563.133 - }
563.134 -
563.135 - public void testObjMethodCompletion5() throws Exception {
563.136 - checkCompletion("testfiles/compl2.py", "print whatever.r^", true);
563.137 - }
563.138 -
563.139 - public void testObjMethodCompletion9() throws Exception {
563.140 - checkCompletion("testfiles/compl4.py", "faen.e^", true);
563.141 - }
563.142 -
563.143 - public void testObjMethodCompletion10() throws Exception {
563.144 - checkCompletion("testfiles/compl5.py", "unittest.T^", true);
563.145 - }
563.146 -
563.147 - public void testObjMethodCompletion11() throws Exception {
563.148 - checkCompletion("testfiles/compl5.py", "x.^r", true);
563.149 - }
563.150 -
563.151 - public void testObjMethodConstructors1() throws Exception {
563.152 - checkCompletion("testfiles/compl2.py", "myvar.^close()", true);
563.153 - }
563.154 -
563.155 - public void testObjMethodConstructors2() throws Exception {
563.156 - checkCompletion("testfiles/compl2.py", "myothervar.^", true);
563.157 - }
563.158 -
563.159 - public void testObjMethodConstructors3() throws Exception {
563.160 - // Not a calling a recognized type - all-completion
563.161 - checkCompletion("testfiles/compl2.py", "unknown.fai^", true);
563.162 - }
563.163 -
563.164 - public void testOverride1() throws Exception {
563.165 - // Not a calling a recognized type - all-completion
563.166 - checkCompletion("testfiles/compl5.py", "MyTest(unittest.TestCase):\n ^", true);
563.167 - }
563.168 -
563.169 - public void testOverride2() throws Exception {
563.170 - // Not a calling a recognized type - all-completion
563.171 - checkCompletion("testfiles/compl5.py", "def ^f(self)", true);
563.172 - }
563.173 -
563.174 - public void testLocals3() throws Exception {
563.175 - checkCompletion("testfiles/occurrences2.py", "tople^velvar = 1", true);
563.176 - }
563.177 -
563.178 - public void testLocals7() throws Exception {
563.179 - checkCompletion("testfiles/occurrences2.py", "print t^oplevelvar2", true);
563.180 - }
563.181 -
563.182 - public void testKeywordFrom() throws Exception {
563.183 - // See http://www.netbeans.org/issues/show_bug.cgi?id=154131
563.184 - checkCompletion("testfiles/org.py", "from or^", true);
563.185 - }
563.186 -
563.187 - public void testProperties() throws Exception {
563.188 - checkCompletion("testfiles/properties.py", "x.ba^", true);
563.189 - }
563.190 -
563.191 - public void testParameters1() throws Exception {
563.192 - checkCompletion("testfiles/complete-calls.py", "functionfoo(foo^, bar)", true);
563.193 - }
563.194 -
563.195 - public void testParameters2() throws Exception {
563.196 - checkCompletion("testfiles/complete-calls.py", "functionfoo(foo, bar^)", true);
563.197 - }
563.198 -
563.199 - public void testParameters3() throws Exception {
563.200 - checkCompletion("testfiles/complete-calls.py", "y.foo(x^yz)", true);
563.201 - }
563.202 -
563.203 - public void testParameters4() throws Exception {
563.204 - checkCompletion("testfiles/complete-calls.py", "y.foo(xyz, b^az)", true);
563.205 - }
563.206 -
563.207 - public void testParameters5() throws Exception {
563.208 - checkCompletion("testfiles/complete-calls.py", "functionfoo(\"foo\", \"bar\", inval^id)", true);
563.209 - }
563.210 -
563.211 - public void testDecorators1() throws Exception {
563.212 - checkCompletion("testfiles/emptydecorators.py", "@^", true);
563.213 - }
563.214 -
563.215 - public void testDecorators2() throws Exception {
563.216 - checkCompletion("testfiles/decorators.py", "@c^", true);
563.217 - }
563.218 -
563.219 - public void testTypedVars1() throws Exception {
563.220 - checkCompletion("testfiles/compl5.py", "os2.^", true);
563.221 - }
563.222 -
563.223 - public void testTypedVars2() throws Exception {
563.224 - checkCompletion("testfiles/compl5.py", "os3.^", true);
563.225 - }
563.226 -
563.227 - public void testTypedVars3() throws Exception {
563.228 - checkCompletion("testfiles/compl5.py", "os4.^", true);
563.229 - }
563.230 -
563.231 - public void testTypedVars4() throws Exception {
563.232 - // No type specified
563.233 - checkCompletion("testfiles/compl5.py", "os5.xhd^", true);
563.234 - }
563.235 - // -------------------------
563.236 - // Unstable tests:
563.237 - // -------------------------
563.238 - //
563.239 - //public void testObjMethodCompletion4() throws Exception {
563.240 - // checkCompletion("testfiles/compl2.py", "print whatever.^r", true);
563.241 - //}
563.242 - //public void testObjMethodCompletion6() throws Exception {
563.243 - // checkCompletion("testfiles/compl2.py", "print sys.getfile^systeme", true);
563.244 - //}
563.245 - //public void testObjMethodCompletion7() throws Exception {
563.246 - // checkCompletion("testfiles/compl2.py", "print os.^", true);
563.247 - //}
563.248 - //public void testObjMethodCompletion8() throws Exception {
563.249 - // checkCompletion("testfiles/compl3.py", "server=SocketServer.^TCPServer", true);
563.250 - //}
563.251 - //public void testLocals4() throws Exception {
563.252 - // checkCompletion("testfiles/occurrences2.py", "print ^toplevelvar2", true);
563.253 - //}
563.254 - //public void testLocals5() throws Exception {
563.255 - // checkCompletion("testfiles/occurrences2.py", "x = ^myfunc", true);
563.256 - //}
563.257 - //public void testDoc4() throws Exception {
563.258 - // try {
563.259 - // skipJython = true;
563.260 - // checkCompletionDocumentation("testfiles/SocketServer.py", "def serve_fore^ver(self):", true, "serve_forever");
563.261 - // } finally {
563.262 - // skipJython = false;
563.263 - // }
563.264 - //}
563.265 - //public void testObjMethodCompletion1() throws Exception {
563.266 - // checkCompletion("testfiles/compl.py", "^self.my", true);
563.267 - //}
563.268 - //public void testImports3() throws Exception {
563.269 - // checkCompletion("testfiles/imports3.py", "import ^", true);
563.270 - //}
563.271 - //public void testImports4() throws Exception {
563.272 - // checkCompletion("testfiles/imports4.py", "import ^", true);
563.273 - //}
563.274 - //public void testImports5() throws Exception {
563.275 - // checkCompletion("testfiles/imports5.py", "import i^", true);
563.276 - //}
563.277 - //public void testImports6() throws Exception {
563.278 - // checkCompletion("testfiles/imports6.py", "from ^i", true);
563.279 - //}
563.280 - //public void testImports6b() throws Exception {
563.281 - // checkCompletion("testfiles/imports6.py", "from i^", true);
563.282 - //}
563.283 - //public void testKeywords() throws Exception {
563.284 - // checkCompletion("testfiles/empty.py", "^print", true);
563.285 - //}
563.286 - //public void testLocals2() throws Exception {
563.287 - // checkCompletion("testfiles/datetime.py", "^dnum = _days_before_month(y, m) + d", true);
563.288 - //}
563.289 - //public void testClasses() throws Exception {
563.290 - // checkCompletion("testfiles/ConfigParser.py", "^self.section = section", true);
563.291 - //}
563.292 - //public void testImports1() throws Exception {
563.293 - // checkCompletion("testfiles/ConfigParser.py", "import ^re", true);
563.294 - //}
563.295 -}
564.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonDeclarationFinderTest.java Sun Jan 04 13:11:53 2015 -0600
564.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
564.3 @@ -1,281 +0,0 @@
564.4 -/*
564.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
564.6 - *
564.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
564.8 - *
564.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
564.10 - * Other names may be trademarks of their respective owners.
564.11 - *
564.12 - * The contents of this file are subject to the terms of either the GNU
564.13 - * General Public License Version 2 only ("GPL") or the Common
564.14 - * Development and Distribution License("CDDL") (collectively, the
564.15 - * "License"). You may not use this file except in compliance with the
564.16 - * License. You can obtain a copy of the License at
564.17 - * http://www.netbeans.org/cddl-gplv2.html
564.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
564.19 - * specific language governing permissions and limitations under the
564.20 - * License. When distributing the software, include this License Header
564.21 - * Notice in each file and include the License file at
564.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
564.23 - * particular file as subject to the "Classpath" exception as provided
564.24 - * by Oracle in the GPL Version 2 section of the License file that
564.25 - * accompanied this code. If applicable, add the following below the
564.26 - * License Header, with the fields enclosed by brackets [] replaced by
564.27 - * your own identifying information:
564.28 - * "Portions Copyrighted [year] [name of copyright owner]"
564.29 - *
564.30 - * If you wish your version of this file to be governed by only the CDDL
564.31 - * or only the GPL Version 2, indicate your decision by adding
564.32 - * "[Contributor] elects to include this software in this distribution
564.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
564.34 - * single choice of license, a recipient has the option to distribute
564.35 - * your version of this file under either the CDDL, the GPL Version 2 or
564.36 - * to extend the choice of license to its licensees as provided above.
564.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
564.38 - * Version 2 license, then the option applies only if the new code is
564.39 - * made subject to such option by the copyright holder.
564.40 - *
564.41 - * Contributor(s):
564.42 - *
564.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
564.44 - */
564.45 -package org.netbeans.modules.python.editor;
564.46 -
564.47 -import java.net.URL;
564.48 -import java.util.Collections;
564.49 -import java.util.Comparator;
564.50 -import java.util.List;
564.51 -import javax.swing.text.BadLocationException;
564.52 -import org.netbeans.editor.BaseDocument;
564.53 -import org.netbeans.modules.gsf.GsfHtmlFormatter;
564.54 -import org.netbeans.modules.gsf.api.CompilationInfo;
564.55 -import org.netbeans.modules.gsf.api.DeclarationFinder.AlternativeLocation;
564.56 -import org.netbeans.modules.gsf.api.DeclarationFinder.DeclarationLocation;
564.57 -import org.netbeans.modules.gsf.api.ElementKind;
564.58 -import org.netbeans.modules.gsf.api.HtmlFormatter;
564.59 -import org.netbeans.modules.gsf.spi.GsfUtilities;
564.60 -import org.openide.filesystems.FileObject;
564.61 -
564.62 -/**
564.63 - *
564.64 - * @author Tor Norbye
564.65 - */
564.66 -public class PythonDeclarationFinderTest extends PythonTestBase {
564.67 -
564.68 - public PythonDeclarationFinderTest(String testName) {
564.69 - super(testName);
564.70 - }
564.71 -
564.72 - private boolean skipJython = true;
564.73 -
564.74 - @Override
564.75 - protected List<URL> getExtraCpUrls() {
564.76 - // I'm overriding various Jython classes here for tests which causes
564.77 - // confusion when it's trying to locate classes and finds it in multiple places
564.78 - if (!skipJython) {
564.79 - return super.getExtraCpUrls();
564.80 - }
564.81 -
564.82 - return null;
564.83 - }
564.84 -
564.85 - // Not yet provided by GSF so manual testing here
564.86 - protected void checkOverrides(String relFilePath, String caretLine) throws Exception {
564.87 -
564.88 - CompilationInfo info = getInfo(relFilePath);
564.89 -
564.90 - String text = info.getText();
564.91 -
564.92 - int caretDelta = caretLine.indexOf('^');
564.93 - assertTrue(caretDelta != -1);
564.94 - caretLine = caretLine.substring(0, caretDelta) + caretLine.substring(caretDelta + 1);
564.95 - int lineOffset = text.indexOf(caretLine);
564.96 - assertTrue(lineOffset != -1);
564.97 - int caretOffset = lineOffset + caretDelta;
564.98 -
564.99 - PythonDeclarationFinder finder = new PythonDeclarationFinder();
564.100 - DeclarationLocation location = finder.getSuperImplementations(info, caretOffset);
564.101 - String annotate = annotateFullDeclarationLocation(location);
564.102 - assertDescriptionMatches(relFilePath, annotate, true, ".declarations");
564.103 - }
564.104 -
564.105 - private String annotateFileLocation(DeclarationLocation location) throws BadLocationException {
564.106 - StringBuilder sb = new StringBuilder();
564.107 - FileObject fo = location.getFileObject();
564.108 - sb.append(fo.getNameExt());
564.109 - sb.append(":");
564.110 - int offset = location.getOffset();
564.111 - sb.append(offset);
564.112 - sb.append(":");
564.113 - BaseDocument document = GsfUtilities.getDocument(fo, true);
564.114 - if (document != null) {
564.115 - String text = document.getText(0, document.getLength());
564.116 - sb.append(getSourceWindow(text, offset));
564.117 - }
564.118 - sb.append("\n");
564.119 - return sb.toString();
564.120 - }
564.121 -
564.122 - private String annotateFullDeclarationLocation(DeclarationLocation location) throws BadLocationException {
564.123 - StringBuilder sb = new StringBuilder();
564.124 -
564.125 - if (location == DeclarationLocation.NONE) {
564.126 - sb.append("NONE\n");
564.127 - } else {
564.128 - if (location.getInvalidMessage() != null) {
564.129 - sb.append(location.getInvalidMessage());
564.130 - sb.append("\n");
564.131 - }
564.132 - if (location.getUrl() != null) {
564.133 - sb.append("URL: " + location.getUrl());
564.134 - sb.append("\n");
564.135 - } else {
564.136 - sb.append(annotateFileLocation(location));
564.137 - sb.append("\n\n");
564.138 - sb.append("Alternative Locations:\n");
564.139 - if (location.getAlternativeLocations() != null) {
564.140 - List<AlternativeLocation> locations = location.getAlternativeLocations();
564.141 - Collections.sort(locations, new Comparator<AlternativeLocation>() {
564.142 -
564.143 - public int compare(AlternativeLocation l1, AlternativeLocation l2) {
564.144 - String d1 = l1.getDisplayHtml(new PlainHtmlFormatter());
564.145 - String d2 = l1.getDisplayHtml(new PlainHtmlFormatter());
564.146 - int ret = d1.compareTo(d2);
564.147 - if (ret != 0) {
564.148 - return ret;
564.149 - }
564.150 - DeclarationLocation loc1 = l1.getLocation();
564.151 - DeclarationLocation loc2 = l2.getLocation();
564.152 - return loc1.toString().compareTo(loc2.toString());
564.153 - }
564.154 -
564.155 - });
564.156 - for (AlternativeLocation alt : locations) {
564.157 - sb.append(alt.getDisplayHtml(new PlainHtmlFormatter()));
564.158 - sb.append("\n");
564.159 - DeclarationLocation loc = alt.getLocation();
564.160 - sb.append(annotateFileLocation(loc));
564.161 - sb.append("\n\n");
564.162 - }
564.163 - }
564.164 - }
564.165 - }
564.166 -
564.167 - return sb.toString();
564.168 - }
564.169 -
564.170 - private class PlainHtmlFormatter extends HtmlFormatter {
564.171 - private StringBuilder sb = new StringBuilder();
564.172 -
564.173 - @Override
564.174 - public void reset() {
564.175 - sb.setLength(0);
564.176 - }
564.177 -
564.178 - @Override
564.179 - public void appendHtml(String html) {
564.180 - sb.append(html);
564.181 - }
564.182 -
564.183 - @Override
564.184 - public void appendText(String text, int fromInclusive, int toExclusive) {
564.185 - sb.append(text, fromInclusive, toExclusive);
564.186 - }
564.187 -
564.188 - @Override
564.189 - public void name(ElementKind kind, boolean start) {
564.190 - }
564.191 -
564.192 - @Override
564.193 - public void active(boolean start) {
564.194 - }
564.195 -
564.196 - @Override
564.197 - public void parameters(boolean start) {
564.198 - }
564.199 -
564.200 - @Override
564.201 - public void type(boolean start) {
564.202 - }
564.203 -
564.204 - @Override
564.205 - public void deprecated(boolean start) {
564.206 - }
564.207 -
564.208 - @Override
564.209 - public String getText() {
564.210 - return sb.toString();
564.211 - }
564.212 -
564.213 - @Override
564.214 - public void emphasis(boolean start) {
564.215 - }
564.216 - }
564.217 -
564.218 - public void testDeclaration1() throws Exception {
564.219 - checkDeclaration("testfiles/ConfigParser.py", "% (line^no, line)", "def append(self, ^lineno, line)");
564.220 - }
564.221 -
564.222 - public void testDeclaration2() throws Exception {
564.223 - checkDeclaration("testfiles/rawstringdoc.py", "import rawstr^ingdoc", "rawstringdoc.py", 0);
564.224 - }
564.225 -
564.226 - public void testDeclaration3() throws Exception {
564.227 - checkDeclaration("testfiles/ConfigParser.py", "raise Interpola^tionSyntaxError(option, section,", "class ^InterpolationSyntaxError(InterpolationError):");
564.228 - }
564.229 -
564.230 - public void testDeclaration4() throws Exception {
564.231 - checkDeclaration("testfiles/ConfigParser.py", "opt = self.optio^nxform(option)", "def ^optionxform(self, optionstr):");
564.232 - }
564.233 -
564.234 - public void testDeclaration5() throws Exception {
564.235 - checkDeclaration("testfiles/gotolocal.py", "print na^me;", "def ggg(^name)");
564.236 - }
564.237 -
564.238 - public void testDeclaration6() throws Exception {
564.239 - checkDeclaration("testfiles/datetime.py", "http://we^bexhibits.org/daylightsaving/", new URL("http://webexhibits.org/daylightsaving/"));
564.240 - }
564.241 -
564.242 - public void testDeclaration7() throws Exception {
564.243 - checkDeclaration("testfiles/datetime.py", "converter = _ti^me.localtime", "^import time as _time");
564.244 - }
564.245 -
564.246 - public void testDeclaration8() throws Exception {
564.247 - checkOverrides("testfiles/overrides.py", "def ov^erridden_method1(self, a, b): # Final");
564.248 - }
564.249 -
564.250 - public void testDeclaration9() throws Exception {
564.251 - checkOverrides("testfiles/overrides.py", "ov^erridden_method2(self, c, d): # Final");
564.252 - }
564.253 -
564.254 -// Not yet working
564.255 -// public void testDeclaration8() throws Exception {
564.256 -// checkDeclaration("testfiles/datetime.py", "_time.loc^altime", "time.rst", 0);
564.257 -// }
564.258 -
564.259 -// public void testDeclaration9() throws Exception {
564.260 -// // Broken because of Jython ast offset bug -- see PythonAstOffsetsTest.testAttributes
564.261 -// checkDeclaration("testfiles/datetime.py", "dayfrac, days = _ma^th.modf(days)", "^import math as _math");
564.262 -// }
564.263 -
564.264 -
564.265 -// Works for me but not on the build machine
564.266 -// public void testDeclaration10() throws Exception {
564.267 -// DeclarationLocation location = findDeclaration("testfiles/datetime.py", "assert ab^s(daysecondsfrac) <= 1.0");
564.268 -// assertNotNull(location);
564.269 -// assertTrue(location != DeclarationLocation.NONE);
564.270 -//
564.271 -// String message = NbBundle.getMessage(PythonDeclarationFinder.class, "BuiltinPython", "abs");
564.272 -// assertEquals(message, location.getInvalidMessage());
564.273 -// }
564.274 -
564.275 -// For some reason, the fnmatch module isn't found from the test infrastructure
564.276 -// public void testDeclaration11() throws Exception {
564.277 -// checkDeclaration("testfiles/declarations.py", "fnmatchca^se", "fnmatch.py", 0);
564.278 -// }
564.279 -
564.280 -// No such package found in the index, make custom test file
564.281 -// public void testDeclaration12() throws Exception {
564.282 -// checkDeclaration("testfiles/minicompat.py", "import xml.d^om", "xml.py", 0);
564.283 -// }
564.284 -}
565.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonFormatterTest.java Sun Jan 04 13:11:53 2015 -0600
565.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
565.3 @@ -1,145 +0,0 @@
565.4 -/*
565.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
565.6 - *
565.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
565.8 - *
565.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
565.10 - * Other names may be trademarks of their respective owners.
565.11 - *
565.12 - * The contents of this file are subject to the terms of either the GNU
565.13 - * General Public License Version 2 only ("GPL") or the Common
565.14 - * Development and Distribution License("CDDL") (collectively, the
565.15 - * "License"). You may not use this file except in compliance with the
565.16 - * License. You can obtain a copy of the License at
565.17 - * http://www.netbeans.org/cddl-gplv2.html
565.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
565.19 - * specific language governing permissions and limitations under the
565.20 - * License. When distributing the software, include this License Header
565.21 - * Notice in each file and include the License file at
565.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
565.23 - * particular file as subject to the "Classpath" exception as provided
565.24 - * by Oracle in the GPL Version 2 section of the License file that
565.25 - * accompanied this code. If applicable, add the following below the
565.26 - * License Header, with the fields enclosed by brackets [] replaced by
565.27 - * your own identifying information:
565.28 - * "Portions Copyrighted [year] [name of copyright owner]"
565.29 - *
565.30 - * If you wish your version of this file to be governed by only the CDDL
565.31 - * or only the GPL Version 2, indicate your decision by adding
565.32 - * "[Contributor] elects to include this software in this distribution
565.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
565.34 - * single choice of license, a recipient has the option to distribute
565.35 - * your version of this file under either the CDDL, the GPL Version 2 or
565.36 - * to extend the choice of license to its licensees as provided above.
565.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
565.38 - * Version 2 license, then the option applies only if the new code is
565.39 - * made subject to such option by the copyright holder.
565.40 - *
565.41 - * Contributor(s):
565.42 - *
565.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
565.44 - */
565.45 -
565.46 -package org.netbeans.modules.python.editor;
565.47 -
565.48 -/**
565.49 - *
565.50 - * @author Tor Norbye
565.51 - */
565.52 -public class PythonFormatterTest extends PythonTestBase {
565.53 -
565.54 - public PythonFormatterTest(String testName) {
565.55 - super(testName);
565.56 - }
565.57 -
565.58 - public void testFormatFile1() throws Exception {
565.59 - reformatFileContents("testfiles/ConfigParser.py", new IndentPrefs(4,4));
565.60 - }
565.61 -
565.62 - public void testFormatFile2() throws Exception {
565.63 - reformatFileContents("testfiles/imports/organize1.py", new IndentPrefs(4,4));
565.64 - }
565.65 -
565.66 - public void testFormatFile3() throws Exception {
565.67 - reformatFileContents("testfiles/datetime.py", new IndentPrefs(4,4));
565.68 - }
565.69 -
565.70 - public void testFormatFile4() throws Exception {
565.71 - reformatFileContents("testfiles/formatting.py", new IndentPrefs(4,4));
565.72 - }
565.73 -
565.74 - public void testFormatFile5() throws Exception {
565.75 - reformatFileContents("testfiles/hanging_indent.py", new IndentPrefs(2,2));
565.76 - }
565.77 -
565.78 - public void testFormatFile6() throws Exception {
565.79 - reformatFileContents("testfiles/hanging_indent2.py", new IndentPrefs(2,2));
565.80 - }
565.81 -
565.82 - public void testStarArg() throws Exception {
565.83 - reformatFileContents("testfiles/star_arg.py", new IndentPrefs(4,4));
565.84 - }
565.85 -
565.86 - public void testSimple1() throws Exception {
565.87 - format("if true\n foo\nelse\n bar\n",
565.88 - "if true\n foo\nelse\n bar\n", null);
565.89 - }
565.90 -
565.91 - public void testSimple2() throws Exception {
565.92 - format(" if true\n foo\n else\n bar\n",
565.93 - " if true\n foo\n else\n bar\n", null);
565.94 - }
565.95 -
565.96 - public void testSimple3() throws Exception {
565.97 - format("if true\n foo\nelse\n bar\n",
565.98 - "if true\n foo\nelse\n bar\n", null);
565.99 - }
565.100 -
565.101 - public void testSimple4() throws Exception {
565.102 - format("if true\n %<%foo\nelse\n bar\n%>%",
565.103 - "if true\n foo\nelse\n bar\n", null);
565.104 - }
565.105 -
565.106 - public void testSimple5() throws Exception {
565.107 - format("if \"%\" in v:\n self._interpolate_some(option, accum, v,\n section, map, depth + 1)\nelse:\n accum.append(v)\n",
565.108 - "if \"%\" in v:\n self._interpolate_some(option, accum, v,\n section, map, depth + 1)\nelse:\n accum.append(v)\n",
565.109 - null);
565.110 - }
565.111 -
565.112 - public void testSimple6() throws Exception {
565.113 - format("class Foo\n def bar\n baz\nclass Bar\n",
565.114 - "class Foo\n def bar\n baz\nclass Bar\n", null);
565.115 - }
565.116 -
565.117 - public void testInconsistent() throws Exception {
565.118 - format("if true\n bar\n if false\n hello\nif false\n baz",
565.119 - "if true\n bar\n if false\n hello\nif false\n baz",
565.120 - null);
565.121 - }
565.122 -
565.123 - public void testInconsistent2() throws Exception {
565.124 - format("if true\n bar\n %<%if false\n hello\nif false\n baz%>%",
565.125 - "if true\n bar\n if false\n hello\nif false\n baz",
565.126 - null);
565.127 - }
565.128 -
565.129 - public void testSimple7() throws Exception {
565.130 - format("if true\n if bar\n baz\nhello",
565.131 - "if true\n if bar\n baz\nhello", null);
565.132 - }
565.133 -
565.134 - public void testSimple8() throws Exception {
565.135 - format(
565.136 - "'''This is my string\n which\n should\n not be changed'''",
565.137 - "'''This is my string\n which\n should\n not be changed'''", null);
565.138 - }
565.139 -
565.140 - public void testSimple9() throws Exception {
565.141 - format(
565.142 - "'''This is my string\n which\n should\n not be changed'''\nhello\nworld\n",
565.143 - "'''This is my string\n which\n should\n not be changed'''\nhello\nworld\n", null);
565.144 - }
565.145 -
565.146 - // Test: Try removing all WHITESPACE in the document (except for line prefixes) and then reformat and compare with master!
565.147 - // Also try doubling all space!
565.148 -}
566.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonIndexTest.java Sun Jan 04 13:11:53 2015 -0600
566.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
566.3 @@ -1,69 +0,0 @@
566.4 -/*
566.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
566.6 - *
566.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
566.8 - *
566.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
566.10 - * Other names may be trademarks of their respective owners.
566.11 - *
566.12 - * The contents of this file are subject to the terms of either the GNU
566.13 - * General Public License Version 2 only ("GPL") or the Common
566.14 - * Development and Distribution License("CDDL") (collectively, the
566.15 - * "License"). You may not use this file except in compliance with the
566.16 - * License. You can obtain a copy of the License at
566.17 - * http://www.netbeans.org/cddl-gplv2.html
566.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
566.19 - * specific language governing permissions and limitations under the
566.20 - * License. When distributing the software, include this License Header
566.21 - * Notice in each file and include the License file at
566.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
566.23 - * particular file as subject to the "Classpath" exception as provided
566.24 - * by Oracle in the GPL Version 2 section of the License file that
566.25 - * accompanied this code. If applicable, add the following below the
566.26 - * License Header, with the fields enclosed by brackets [] replaced by
566.27 - * your own identifying information:
566.28 - * "Portions Copyrighted [year] [name of copyright owner]"
566.29 - *
566.30 - * If you wish your version of this file to be governed by only the CDDL
566.31 - * or only the GPL Version 2, indicate your decision by adding
566.32 - * "[Contributor] elects to include this software in this distribution
566.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
566.34 - * single choice of license, a recipient has the option to distribute
566.35 - * your version of this file under either the CDDL, the GPL Version 2 or
566.36 - * to extend the choice of license to its licensees as provided above.
566.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
566.38 - * Version 2 license, then the option applies only if the new code is
566.39 - * made subject to such option by the copyright holder.
566.40 - *
566.41 - * Contributor(s):
566.42 - *
566.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
566.44 - */
566.45 -
566.46 -package org.netbeans.modules.python.editor;
566.47 -
566.48 -import org.openide.filesystems.FileObject;
566.49 -
566.50 -/**
566.51 - *
566.52 - * @author Tor Norbye
566.53 - */
566.54 -public class PythonIndexTest extends PythonTestBase {
566.55 -
566.56 - public PythonIndexTest(String name) {
566.57 - super(name);
566.58 - }
566.59 -
566.60 - // Unstable
566.61 -// public void testGetFileObject1() throws Exception {
566.62 -// FileObject fo = PythonIndex.getFileObject("python:Lib/zipfile.py");
566.63 -// assertNotNull(fo);
566.64 -// assertEquals("zipfile.py", fo.getNameExt());
566.65 -// }
566.66 -
566.67 - public void testGetFileObject2() throws Exception {
566.68 - FileObject fo = PythonIndex.getFileObject("cluster:pythonstubs/pythonstubs-2_6_1.egg");
566.69 - assertNotNull(fo);
566.70 - assertEquals("pythonstubs-2_6_1.egg", fo.getNameExt());
566.71 - }
566.72 -}
567.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonIndexerTest.java Sun Jan 04 13:11:53 2015 -0600
567.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
567.3 @@ -1,190 +0,0 @@
567.4 -/*
567.5 - * To change this template, choose Tools | Templates
567.6 - * and open the template in the editor.
567.7 - */
567.8 -
567.9 -package org.netbeans.modules.python.editor;
567.10 -
567.11 -import org.netbeans.modules.python.editor.elements.IndexedElement;
567.12 -
567.13 -/**
567.14 - *
567.15 - * @author Tor Norbye
567.16 - */
567.17 -public class PythonIndexerTest extends PythonTestBase {
567.18 -
567.19 - public PythonIndexerTest(String testName) {
567.20 - super(testName);
567.21 - }
567.22 -
567.23 - @Override
567.24 - public String prettyPrintValue(String key, String value) {
567.25 - if (value == null) {
567.26 - return value;
567.27 - }
567.28 - int index = -1;
567.29 - if (PythonIndexer.FIELD_MEMBER.equals(key) ||PythonIndexer.FIELD_ITEM.equals(key)) {
567.30 - index = IndexedElement.FLAG_INDEX;
567.31 - } else if (PythonIndexer.FIELD_CLASS_ATTR_NAME.equals(key)) {
567.32 - index = 0;
567.33 - value = ";" + value + ";";
567.34 - }
567.35 - if (index != -1) {
567.36 - // Decode the attributes
567.37 - int attributeIndex = 0;
567.38 - for (int i = 0; i < index; i++) {
567.39 - attributeIndex = value.indexOf(';', attributeIndex+1);
567.40 - }
567.41 - int flags = IndexedElement.decode(value, attributeIndex+1, 0);
567.42 - String desc = IndexedElement.decodeFlags(flags);
567.43 - value = value.substring(0, attributeIndex) + ";" + desc + value.substring(value.indexOf(';', attributeIndex+1));
567.44 - }
567.45 -
567.46 - return value;
567.47 - }
567.48 -
567.49 -
567.50 - public void testIsIndexable1() throws Exception {
567.51 - checkIsIndexable("testfiles/javascript.js", false);
567.52 - }
567.53 -
567.54 - public void testIsIndexable2() throws Exception {
567.55 - checkIsIndexable("testfiles/compiled.pyc", false);
567.56 - }
567.57 -
567.58 - public void testIsIndexable3() throws Exception {
567.59 - checkIsIndexable("testfiles/ConfigParser.py", true);
567.60 - }
567.61 -
567.62 - public void testIsIndexable4() throws Exception {
567.63 - checkIsIndexable("testfiles/datetime.py", true);
567.64 - }
567.65 -
567.66 - public void testIsIndexable5() throws Exception {
567.67 - checkIsIndexable("testfiles/antlr_python_runtime-3.1.1-py2.5.egg", true);
567.68 - }
567.69 -
567.70 - public void testIndex1() throws Exception {
567.71 - checkIndexer("testfiles/ConfigParser.py");
567.72 - }
567.73 -
567.74 - public void testIndex2() throws Exception {
567.75 - checkIndexer("testfiles/datetime.py");
567.76 - }
567.77 -
567.78 - public void testIndex3() throws Exception {
567.79 - checkIndexer("testfiles/doc.py");
567.80 - }
567.81 -
567.82 - public void testIndex4() throws Exception {
567.83 - checkIndexer("testfiles/md5.py");
567.84 - }
567.85 -
567.86 - public void testIndex5() throws Exception {
567.87 - checkIndexer("testfiles/scope.py");
567.88 - }
567.89 -
567.90 - public void testIndex6() throws Exception {
567.91 - checkIndexer("testfiles/httplib.py");
567.92 - }
567.93 -
567.94 - public void testIndex7() throws Exception {
567.95 - checkIndexer("testfiles/minicompat.py");
567.96 - }
567.97 -
567.98 - public void testIndex8() throws Exception {
567.99 - checkIndexer("testfiles/socket.py");
567.100 - }
567.101 -
567.102 - public void testIndex9() throws Exception {
567.103 - checkIndexer("testfiles/jreload.py");
567.104 - }
567.105 -
567.106 - public void testIndex10() throws Exception {
567.107 - checkIndexer("testfiles/doctest.py");
567.108 - }
567.109 -
567.110 - public void testIndex11() throws Exception {
567.111 - checkIndexer("testfiles/zipfile.py");
567.112 - }
567.113 -
567.114 - public void testIndex12() throws Exception {
567.115 - checkIndexer("testfiles/os.py");
567.116 - }
567.117 -
567.118 - public void testIndex13() throws Exception {
567.119 - checkIndexer("testfiles/unittest.py");
567.120 - }
567.121 -
567.122 - public void testIndex14() throws Exception {
567.123 - checkIndexer("testfiles/properties.py");
567.124 - }
567.125 -
567.126 - public void testIndex15() throws Exception {
567.127 - checkIndexer("testfiles/tarfile.py");
567.128 - }
567.129 -
567.130 - public void testIndex16() throws Exception {
567.131 - checkIndexer("testfiles/rst/pickle.rst");
567.132 - }
567.133 -
567.134 - public void testRstIndex1() throws Exception {
567.135 - checkIndexer("testfiles/rst/zipfile.rst");
567.136 - }
567.137 -
567.138 - public void testRstIndex2() throws Exception {
567.139 - checkIndexer("testfiles/rst/stdtypes.rst");
567.140 - }
567.141 -
567.142 - public void testRstIndex3() throws Exception {
567.143 - checkIndexer("testfiles/rst/platform.rst");
567.144 - }
567.145 -
567.146 - public void testRstIndex4() throws Exception {
567.147 - checkIndexer("testfiles/rst/smtpd.rst");
567.148 - }
567.149 -
567.150 - public void testRstIndex5() throws Exception {
567.151 - checkIndexer("testfiles/rst/exceptions.rst");
567.152 - }
567.153 -
567.154 - public void testRstIndex6() throws Exception {
567.155 - checkIndexer("testfiles/rst/logging.rst");
567.156 - }
567.157 -
567.158 - public void testRstIndex7() throws Exception {
567.159 - checkIndexer("testfiles/rst/string.rst");
567.160 - }
567.161 -
567.162 - public void testRstIndex8() throws Exception {
567.163 - checkIndexer("testfiles/rst/bz2.rst");
567.164 - }
567.165 -
567.166 - public void testRstIndex9() throws Exception {
567.167 - checkIndexer("testfiles/rst/constants.rst");
567.168 - }
567.169 -
567.170 - public void testRstIndex10() throws Exception {
567.171 - checkIndexer("testfiles/rst/operator.rst");
567.172 - }
567.173 -
567.174 - public void testRstIndex11() throws Exception {
567.175 - checkIndexer("testfiles/rst/collections.rst");
567.176 - }
567.177 -
567.178 - public void testRstIndex12() throws Exception {
567.179 - checkIndexer("testfiles/rst/ctypes.rst");
567.180 - }
567.181 -
567.182 - public void testRstIndex13() throws Exception {
567.183 - checkIndexer("testfiles/rst/stub_missing.rst");
567.184 - }
567.185 -
567.186 - public void testIndexEgg() throws Exception {
567.187 - checkIndexer("testfiles/antlr_python_runtime-3.1.1-py2.5.egg");
567.188 - }
567.189 -
567.190 -// public void testIndexEgg2() throws Exception {
567.191 -// checkIndexer("testfiles/pythonstubs-2_6_1.egg");
567.192 -// }
567.193 -}
568.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonInstantRenameTest.java Sun Jan 04 13:11:53 2015 -0600
568.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
568.3 @@ -1,62 +0,0 @@
568.4 -/*
568.5 - * To change this template, choose Tools | Templates
568.6 - * and open the template in the editor.
568.7 - */
568.8 -
568.9 -package org.netbeans.modules.python.editor;
568.10 -
568.11 -/**
568.12 - *
568.13 - * @author Tor Norbye
568.14 - */
568.15 -public class PythonInstantRenameTest extends PythonTestBase {
568.16 -
568.17 - public PythonInstantRenameTest(String testName) {
568.18 - super(testName);
568.19 - }
568.20 -
568.21 - public void testRename1() throws Exception {
568.22 - String caretLine = "def __init__(self, m^sg=''):";
568.23 - checkRenameSections("testfiles/ConfigParser.py", caretLine);
568.24 - }
568.25 -
568.26 - public void testRename2() throws Exception {
568.27 - String caretLine = "for (ke^y, value) in self._sections[section].items():";
568.28 - checkRenameSections("testfiles/ConfigParser.py", caretLine);
568.29 - }
568.30 -
568.31 - public void testRename3() throws Exception {
568.32 - String caretLine = "raise Interpola^tionSyntaxError(option, section,";
568.33 - checkRenameSections("testfiles/ConfigParser.py", caretLine);
568.34 - }
568.35 -
568.36 - public void testRename4() throws Exception {
568.37 - String caretLine = "print toplevelv^ar4";
568.38 - checkRenameSections("testfiles/occurrences2.py", caretLine);
568.39 - }
568.40 -
568.41 - public void testRename5() throws Exception {
568.42 - String caretLine = "x = myf^unc";
568.43 - checkRenameSections("testfiles/occurrences2.py", caretLine);
568.44 - }
568.45 -
568.46 - public void testRename6() throws Exception {
568.47 - String caretLine = "print toplevel^var2";
568.48 - checkRenameSections("testfiles/occurrences2.py", caretLine);
568.49 - }
568.50 -
568.51 - public void testRename7() throws Exception {
568.52 - String caretLine = "# @type ^xy str";
568.53 - checkRenameSections("testfiles/typevars.py", caretLine);
568.54 - }
568.55 -
568.56 - public void testRename8() throws Exception {
568.57 - String caretLine = "x^y.s1";
568.58 - checkRenameSections("testfiles/typevars.py", caretLine);
568.59 - }
568.60 -
568.61 - public void testRename9() throws Exception {
568.62 - String caretLine = "print self.not^okay";
568.63 - checkRenameSections("testfiles/attributes.py", caretLine);
568.64 - }
568.65 -}
569.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonKeystrokeHandlerTest.java Sun Jan 04 13:11:53 2015 -0600
569.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
569.3 @@ -1,699 +0,0 @@
569.4 -/*
569.5 - * To change this template, choose Tools | Templates
569.6 - * and open the template in the editor.
569.7 - */
569.8 -
569.9 -package org.netbeans.modules.python.editor;
569.10 -
569.11 -import javax.swing.text.BadLocationException;
569.12 -import org.netbeans.modules.gsf.api.Formatter;
569.13 -
569.14 -/**
569.15 - *
569.16 - * @author Tor Norbye
569.17 - */
569.18 -public class PythonKeystrokeHandlerTest extends PythonTestBase {
569.19 - static {
569.20 - System.setProperty("python.fromimport", "true");
569.21 - }
569.22 -
569.23 - public PythonKeystrokeHandlerTest(String testName) {
569.24 - super(testName);
569.25 - }
569.26 -
569.27 - private void match(String original) throws BadLocationException {
569.28 - super.assertMatches(original);
569.29 - }
569.30 -
569.31 - private void insertChar(String original, char insertText, String expected) throws Exception {
569.32 - insertChar(original, insertText, expected, null);
569.33 - }
569.34 -
569.35 - private void insertChar(String original, char insertText, String expected, String selection) throws Exception {
569.36 - insertChar(original, insertText, expected, selection, false);
569.37 - }
569.38 -
569.39 - @Override
569.40 - public void deleteWord(String original, String expected) throws Exception {
569.41 - // Try deleting the word not just using the testcase but also surrounded by strings
569.42 - // to make sure there's no problem with lexer token directions
569.43 - super.deleteWord(original, expected);
569.44 - super.deleteWord(original+"foo", expected+"foo");
569.45 - super.deleteWord("foo"+original, "foo"+expected);
569.46 - super.deleteWord(original+"::", expected+"::");
569.47 - super.deleteWord(original+"::", expected+"::");
569.48 - }
569.49 -
569.50 - @Override
569.51 - protected Formatter getFormatter(IndentPrefs preferences) {
569.52 - //return new PythonFormatter();
569.53 - return null;
569.54 - }
569.55 -
569.56 - public void testReturn() throws Exception {
569.57 - insertBreak(" def foo():\n return^", " def foo():\n return\n ^");
569.58 - }
569.59 -
569.60 - public void testReturn2() throws Exception {
569.61 - insertBreak(" def foo():\n return^\n", " def foo():\n return\n ^\n");
569.62 - }
569.63 -
569.64 - public void testReturn3() throws Exception {
569.65 - insertBreak(" def foo():\n return true^\n", " def foo():\n return true\n ^\n");
569.66 - }
569.67 -
569.68 - public void testRaise1() throws Exception {
569.69 - insertBreak(" def foo():\n raise RuntimeError^\n", " def foo():\n raise RuntimeError\n ^\n");
569.70 - }
569.71 -
569.72 - public void testDefParenSkip1() throws Exception {
569.73 - insertBreak("def foo(^):\n", "def foo():\n ^\n");
569.74 - }
569.75 -
569.76 - public void testDefParenSkip2() throws Exception {
569.77 - insertBreak("class Foo(^):\n", "class Foo():\n ^\n");
569.78 - }
569.79 -
569.80 - public void testDefParenSkip3() throws Exception {
569.81 - insertBreak("def foo(self^):\n", "def foo(self):\n ^\n");
569.82 - }
569.83 -
569.84 - public void testDefParenSkip4() throws Exception {
569.85 - insertBreak("def foo(self,^):\n", "def foo(self,\n^):\n");
569.86 - }
569.87 -
569.88 - public void testDefParenSkip5() throws Exception {
569.89 - insertBreak("def foo(self^):", "def foo(self):\n ^");
569.90 - }
569.91 -
569.92 - public void testContinued() throws Exception {
569.93 - insertBreak(" def foo():\n raise RuntimeError \\^\n", " def foo():\n raise RuntimeError \\\n ^\n");
569.94 - }
569.95 -
569.96 - public void testContinued2() throws Exception {
569.97 - insertBreak("foo\\^", "foo\\\n ^");
569.98 - }
569.99 -
569.100 - public void testContinued3() throws Exception {
569.101 - insertBreak("foo\\^\n", "foo\\\n ^\n");
569.102 - }
569.103 -
569.104 - public void testNotContinued1() throws Exception {
569.105 - insertBreak("fo^o\\\n", "fo\n^o\\\n");
569.106 - }
569.107 -
569.108 - public void testPassDedent() throws Exception {
569.109 - insertBreak(" if (true):\n pass^\n", " if (true):\n pass\n ^\n");
569.110 - }
569.111 -
569.112 - public void testPassDedent2() throws Exception {
569.113 - insertBreak(" if (true):\n pass^", " if (true):\n pass\n ^");
569.114 - }
569.115 -
569.116 - public void testReindentElse() throws Exception {
569.117 - insertChar(" if (true):\n pass\n else^", ':', " if (true):\n pass\n else:^");
569.118 - }
569.119 -
569.120 - public void testReindentElse2() throws Exception {
569.121 - insertChar(" if (true):\n pass\n else^\n", ':', " if (true):\n pass\n else:^\n");
569.122 - }
569.123 -
569.124 - public void testReindentElif() throws Exception {
569.125 - insertChar(" if (true):\n pass\n elif^", ':', " if (true):\n pass\n elif:^");
569.126 - }
569.127 -
569.128 - public void testReindentElif2() throws Exception {
569.129 - insertChar(" if (true):\n pass\n elif^\n", ':', " if (true):\n pass\n elif:^\n");
569.130 - }
569.131 -
569.132 - public void testReindentExcept() throws Exception {
569.133 - insertChar(" try:\n pass\n except Foo^", ':', " try:\n pass\n except Foo:^");
569.134 - }
569.135 -
569.136 - public void testReindentExcept2() throws Exception {
569.137 - insertChar(" try:\n pass\n except Foo^\n", ':', " try:\n pass\n except Foo:^\n");
569.138 - }
569.139 -
569.140 - public void testReindentExcept3() throws Exception {
569.141 - insertChar(" try:\n pass\n finally^\n", ':', " try:\n pass\n finally:^\n");
569.142 - }
569.143 -
569.144 - public void testMultilineString() throws Exception {
569.145 - insertBreak("\"\"\"^\n", "\"\"\"\n^\n\"\"\"\n");
569.146 - }
569.147 -
569.148 - public void testMultilineString2() throws Exception {
569.149 - insertBreak(" \"\"\"^\n", " \"\"\"\n ^\n \"\"\"\n");
569.150 - }
569.151 -
569.152 - public void testMultilineString3() throws Exception {
569.153 - insertBreak("\"\"\"^", "\"\"\"\n^\n\"\"\"");
569.154 - }
569.155 -
569.156 - public void testNoMultilineString() throws Exception {
569.157 - insertBreak("# \"\"\"^\n", "# \"\"\"\n^\n");
569.158 - }
569.159 -
569.160 - public void testNoMultilineString2() throws Exception {
569.161 - insertBreak("\"\"\"^\n\n\"\"\"\n", "\"\"\"\n^\n\n\"\"\"\n");
569.162 - }
569.163 -
569.164 -// Not yet implemented
569.165 -// public void testSinglineString1() throws Exception {
569.166 -// // Not yet passing - should implement this
569.167 -// insertBreak("\"\"\"foo^\n\"\"\"", "\"\"\"foo\n\"\"\"\n^");
569.168 -// }
569.169 -//
569.170 -// public void testSinglineString2() throws Exception {
569.171 -// insertBreak("\"\"\"foo^\n\"\"\"\n", "\"\"\"foo\n\"\"\"\n^\n");
569.172 -// }
569.173 -//
569.174 -// public void testSinglineString3() throws Exception {
569.175 -// insertBreak(" \"\"\"foo^\n\"\"\"\n", " \"\"\"foo\n\"\"\"\n ^\n");
569.176 -// }
569.177 -
569.178 - public void testInsertColon1() throws Exception {
569.179 - insertChar("def foo^", '(', "def foo(^):");
569.180 - }
569.181 -
569.182 - public void testInsertColon2() throws Exception {
569.183 - insertChar("def foo^\n", '(', "def foo(^):\n");
569.184 - }
569.185 -
569.186 - public void testInsertColon3() throws Exception {
569.187 - insertChar("class A\n def foo^", '(', "class A\n def foo(self^):");
569.188 - }
569.189 -
569.190 - public void testInsertColon4() throws Exception {
569.191 - insertChar("class Abc^\n", '(', "class Abc(^):\n");
569.192 - }
569.193 -
569.194 - public void testInsertColon5() throws Exception {
569.195 - insertChar("class A\n def foo()\n bar\n\n \n def bar^\n", '(', "class A\n def foo()\n bar\n\n \n def bar(self^):\n");
569.196 - }
569.197 -
569.198 - public void testTypethroughComma1() throws Exception {
569.199 - insertChar("class Abc(^):\n", 'a', "class Abc(a^):\n");
569.200 - }
569.201 -
569.202 - public void testTypethroughComma2() throws Exception {
569.203 - insertChar("class Abc(a^):\n", ')', "class Abc(a)^:\n");
569.204 - }
569.205 -
569.206 - public void testTypethroughComma4() throws Exception {
569.207 - insertChar("class Abc(a)^:\n", ':', "class Abc(a):^\n");
569.208 - }
569.209 -
569.210 - public void testTypethroughComma5() throws Exception {
569.211 - insertChar("def foo(^):\n", ')', "def foo()^:\n");
569.212 - }
569.213 -
569.214 - public void testTypethroughComma6() throws Exception {
569.215 - insertChar("def foo()^:\n", ':', "def foo():^\n");
569.216 - }
569.217 -
569.218 - public void testNoTypethroughComma1() throws Exception {
569.219 - insertChar("ashex = _binascii.hexlify(data[:^-1])", ':', "ashex = _binascii.hexlify(data[::^-1])");
569.220 - }
569.221 -
569.222 - public void testNoTypethroughComma2() throws Exception {
569.223 - insertChar("ashex = _binascii.hexlify(data[^:-1])", ':', "ashex = _binascii.hexlify(data[:^:-1])");
569.224 - }
569.225 -
569.226 - public void testNoTypethroughComma3() throws Exception {
569.227 - insertChar("# def foo()^:\n", ':', "# def foo():^:\n");
569.228 - }
569.229 -
569.230 - public void testFromImport() throws Exception {
569.231 - insertChar("from sys^", ' ', "from sys import ^");
569.232 - }
569.233 -
569.234 - public void testFromImport2() throws Exception {
569.235 - insertChar("from sys^\n", ' ', "from sys import ^\n");
569.236 - }
569.237 -
569.238 - public void testNoFromImport() throws Exception {
569.239 - insertChar("from sys^\n", 's', "from syss^\n");
569.240 - }
569.241 -
569.242 - public void testNoFromImport2() throws Exception {
569.243 - insertChar("from sys^ import *\n", ' ', "from sys ^ import *\n");
569.244 - }
569.245 -
569.246 - public void testBreak1() throws Exception {
569.247 - insertBreak("test1:^", "test1:\n ^");
569.248 - }
569.249 -
569.250 - public void testBreak2() throws Exception {
569.251 - insertBreak("test1:^\n", "test1:\n ^\n");
569.252 - }
569.253 -
569.254 - public void testBreak3() throws Exception {
569.255 - insertBreak("test1:\n foo^", "test1:\n foo\n ^");
569.256 - }
569.257 -
569.258 - public void testTripleQuotes1() throws Exception {
569.259 - insertChar("\"\"^", '"', "\"\"\"^");
569.260 - insertChar("\"\"^\n", '"', "\"\"\"^\n");
569.261 - }
569.262 -
569.263 - public void testTripleQuotes2() throws Exception {
569.264 - insertChar("class A:\n def foo():\n \"\"^\n",
569.265 - '"',
569.266 - "class A:\n def foo():\n \"\"\"^\n");
569.267 - }
569.268 -
569.269 - public void testTripleQuotes3() throws Exception {
569.270 - insertChar("''^", '\'', "'''^");
569.271 - insertChar("''^\n", '\'', "'''^\n");
569.272 - }
569.273 -
569.274 - public void testTripleQuotes4() throws Exception {
569.275 - insertBreak(" '''^", " '''\n ^\n '''");
569.276 - }
569.277 -
569.278 - public void testTripleQuotes5() throws Exception {
569.279 - insertBreak(" '''^\n", " '''\n ^\n '''\n");
569.280 - }
569.281 -
569.282 - public void testTripleQuotes6() throws Exception {
569.283 - insertBreak(" \"\"\"^\n", " \"\"\"\n ^\n \"\"\"\n");
569.284 - }
569.285 -
569.286 - public void testTripleQuotes7() throws Exception {
569.287 - insertBreak(" '''foo^\n", " '''foo'''\n ^\n");
569.288 - }
569.289 -
569.290 - public void testTripleQuotes8() throws Exception {
569.291 - insertBreak(" '''foo^", " '''foo'''\n ^");
569.292 - }
569.293 -
569.294 - public void testTripleQuotes9() throws Exception {
569.295 - insertBreak(" '''foo^bar\n", " '''foo\n ^bar\n");
569.296 - }
569.297 -
569.298 - public void testTripleQuotes10() throws Exception {
569.299 - insertBreak(" '''foo^'''\n", " '''foo\n ^'''\n");
569.300 - }
569.301 -
569.302 - public void testTripleQuotes11() throws Exception {
569.303 - insertBreak(" '''\n foo^", " '''\n foo'''\n ^");
569.304 - }
569.305 -
569.306 - public void testTripleQuotes12() throws Exception {
569.307 - insertBreak(" '''\n foo^\n", " '''\n foo'''\n ^\n");
569.308 - }
569.309 -
569.310 - public void testTripleQuotes13() throws Exception {
569.311 - insertBreak(" r'''\n foo^\n", " r'''\n foo'''\n ^\n");
569.312 - }
569.313 -
569.314 - public void testTripleQuotes14() throws Exception {
569.315 - insertBreak(" r'''foo^'''\n", " r'''foo\n ^'''\n");
569.316 - }
569.317 -
569.318 - public void testBreak4() throws Exception {
569.319 - insertBreak("test1:\n foo^\n", "test1:\n foo\n ^\n");
569.320 - }
569.321 -
569.322 - public void testBreak5() throws Exception {
569.323 - insertBreak(" test1: ^ foo", " test1: \n ^foo");
569.324 - }
569.325 -
569.326 - public void testBreak6() throws Exception {
569.327 - insertBreak("test1: ^", "test1: \n ^");
569.328 - insertBreak("test1: ^\n", "test1: \n ^\n");
569.329 - }
569.330 -
569.331 - public void testBreak7() throws Exception {
569.332 - insertBreak(" test1: ^", " test1: \n ^");
569.333 - insertBreak(" test1: ^\n", " test1: \n ^\n");
569.334 - }
569.335 -
569.336 - public void testBak1() throws Exception {
569.337 - // Ensure that a backspace with indent 4 will delete 3 more characters to
569.338 - // outdent one level
569.339 - deleteChar(" ^", " ^");
569.340 - }
569.341 -
569.342 - public void testBak2() throws Exception {
569.343 - deleteChar(" ^test", " ^test");
569.344 - }
569.345 -
569.346 - public void testBak3() throws Exception {
569.347 - // Make sure normal deletion works
569.348 - deleteChar("foo^", "fo^");
569.349 - }
569.350 -
569.351 - public void testBak4() throws Exception {
569.352 - // Don't delete blocks when we're not in a prefix!
569.353 - deleteChar(" # type(ff) ^int", " # type(ff)^int");
569.354 - }
569.355 -
569.356 - public void testLogicalRange1() throws Exception {
569.357 - String code = "print \"He^llo World!\"\n";
569.358 - String next = "print %<%\"He^llo World!\"%>%\n";
569.359 - assertLogicalRange(code, true, next);
569.360 - assertLogicalRange(next, false, code);
569.361 - }
569.362 -
569.363 - public void testLogicalRange2() throws Exception {
569.364 - String code = "print %<%\"He^llo World!\"%>%\n";
569.365 - String next = "%<%print \"He^llo World!\"%>%\n";
569.366 - assertLogicalRange(code, true, next);
569.367 - assertLogicalRange(next, false, code);
569.368 - }
569.369 -
569.370 - public void testLogicalRange3() throws Exception {
569.371 - String code = "class A:\n def foo():\n self.filename = file^name\n";
569.372 - String next = "class A:\n def foo():\n self.filename = %<%file^name%>%\n";
569.373 - assertLogicalRange(code, true, next);
569.374 - assertLogicalRange(next, false, code);
569.375 - }
569.376 -
569.377 - public void testLogicalRange4() throws Exception {
569.378 - String code = "class A:\n def foo():\n self.filename = %<%file^name%>%\n";
569.379 - String next = "class A:\n def foo():\n %<%self.filename = file^name%>%\n";
569.380 - assertLogicalRange(code, true, next);
569.381 - assertLogicalRange(next, false, code);
569.382 - }
569.383 -
569.384 - public void testLogicalRange5() throws Exception {
569.385 - String code = "class A:\n def foo():\n %<%self.filename = file^name%>%\n";
569.386 - String next = "class A:\n %<%def foo():\n self.filename = file^name%>%\n";
569.387 - assertLogicalRange(code, true, next);
569.388 - assertLogicalRange(next, false, code);
569.389 - }
569.390 -
569.391 - public void testLogicalRange6() throws Exception {
569.392 - String code = "class A:\n %<%def foo():\n self.filename = file^name%>%\n";
569.393 - String next = "%<%class A:\n def foo():\n self.filename = file^name%>%\n";
569.394 - assertLogicalRange(code, true, next);
569.395 - assertLogicalRange(next, false, code);
569.396 - }
569.397 -
569.398 - public void testInsertX() throws Exception {
569.399 - insertChar("c^ass", 'l', "cl^ass");
569.400 - }
569.401 -
569.402 - public void testInsertX2() throws Exception {
569.403 - insertChar("clas^", 's', "class^");
569.404 - }
569.405 -
569.406 - public void testNoMatchInComments() throws Exception {
569.407 - // End
569.408 - insertChar("# Hello^", '\'', "# Hello'^");
569.409 - insertChar("# Hello^", '"', "# Hello\"^");
569.410 - insertChar("# Hello^", '[', "# Hello[^");
569.411 - insertChar("# Hello^", '(', "# Hello(^");
569.412 -
569.413 - // Middle
569.414 - insertChar("# Hello^o", '\'', "# Hello'^o");
569.415 - insertChar("# Hello^o", '"', "# Hello\"^o");
569.416 - insertChar("# Hello^o", '[', "# Hello[^o");
569.417 - insertChar("# Hello^o", '(', "# Hello(^o");
569.418 -
569.419 - // Before newline
569.420 - insertChar("# Hello^\n", '\'', "# Hello'^\n");
569.421 - insertChar("# Hello^\n", '"', "# Hello\"^\n");
569.422 - insertChar("# Hello^\n", '[', "# Hello[^\n");
569.423 - insertChar("# Hello^\n", '(', "# Hello(^\n");
569.424 - }
569.425 -
569.426 - public void testNoMatchInStrings() throws Exception {
569.427 - insertChar("x = \"^\"", '\'', "x = \"'^\"");
569.428 - insertChar("x = \"^\"", '[', "x = \"[^\"");
569.429 - insertChar("x = \"^\"", '(', "x = \"(^\"");
569.430 - insertChar("x = \"^)\"", ')', "x = \")^)\"");
569.431 - insertChar("x = '^'", '"', "x = '\"^'");
569.432 - }
569.433 -
569.434 - public void testSingleQuotes1() throws Exception {
569.435 - insertChar("x = ^", '\'', "x = '^'");
569.436 - }
569.437 -
569.438 - public void testSingleQuotes2() throws Exception {
569.439 - insertChar("x = '^'", '\'', "x = ''^");
569.440 - }
569.441 -
569.442 - public void testSingleQuotes3() throws Exception {
569.443 - insertChar("x = '^'", 'a', "x = 'a^'");
569.444 - }
569.445 -
569.446 - public void testSingleQuotes4() throws Exception {
569.447 - insertChar("x = '\\^'", '\'', "x = '\\'^'");
569.448 - }
569.449 -
569.450 - public void testInsertBrokenQuote() throws Exception {
569.451 - insertChar("System.out.prinlnt(\"pavel^)", '"',
569.452 - "System.out.prinlnt(\"pavel\"^)");
569.453 - }
569.454 -
569.455 - public void testInsertBrokenQuote2() throws Exception {
569.456 - insertChar("System.out.prinlnt(\"pavel^\n", '"',
569.457 - "System.out.prinlnt(\"pavel\"^\n");
569.458 - }
569.459 -
569.460 - public void testInsertBrokenQuote3() throws Exception {
569.461 - insertChar("System.out.prinlnt(\"^\n", '"',
569.462 - "System.out.prinlnt(\"\"^\n");
569.463 - }
569.464 -
569.465 - public void testInsertBrokenQuote4() throws Exception {
569.466 - insertChar("System.out.prinlnt(\"pavel^", '"',
569.467 - "System.out.prinlnt(\"pavel\"^");
569.468 - }
569.469 -
569.470 - public void testDoubleQuotes1() throws Exception {
569.471 - insertChar("x = ^", '"', "x = \"^\"");
569.472 - }
569.473 -
569.474 - public void testDoubleQuotes2() throws Exception {
569.475 - insertChar("x = \"^\"", '"', "x = \"\"^");
569.476 - }
569.477 -
569.478 - public void testDoubleQuotes3() throws Exception {
569.479 - insertChar("x = \"^\"", 'a', "x = \"a^\"");
569.480 - }
569.481 -
569.482 - public void testDobuleQuotes4() throws Exception {
569.483 - insertChar("x = \"\\^\"", '"', "x = \"\\\"^\"");
569.484 - }
569.485 -
569.486 -// public void testInsertBrace1() throws Exception {
569.487 -// insertBreak("foobar({^});", "foobar({\n ^\n});");
569.488 -// }
569.489 -//
569.490 -// public void testInsertBrace2() throws Exception {
569.491 -// insertBreak("foobar([^]);", "foobar([\n ^\n]);");
569.492 -// }
569.493 -//
569.494 -// public void testInsertBrace3() throws Exception {
569.495 -// insertBreak("x = {^}", "x = {\n ^\n}");
569.496 -// }
569.497 -
569.498 - public void testInsertEnd1() throws Exception {
569.499 - insertBreak("x^", "x\n^");
569.500 - }
569.501 -
569.502 -// public void testSplitStrings1() throws Exception {
569.503 -// insertBreak(" x = 'te^st'", " x = 'te\\n\\\n^st'");
569.504 -// }
569.505 -//
569.506 -// public void testSplitStrings1b() throws Exception {
569.507 -// insertBreak(" x = '^test'", " x = '\\\n^test'");
569.508 -// }
569.509 -//
569.510 -// public void testSplitStrings2() throws Exception {
569.511 -// insertBreak(" x = 'test^'", " x = 'test\\n\\\n^'");
569.512 -// }
569.513 -//
569.514 -// public void testSplitStrings3() throws Exception {
569.515 -// insertBreak(" x = \"te^st\"", " x = \"te\\n\\\n^st\"");
569.516 -// }
569.517 -//
569.518 -
569.519 - public void testBrackets1() throws Exception {
569.520 - insertChar("x = ^", '[', "x = [^]");
569.521 - }
569.522 -
569.523 - public void testBrackets2() throws Exception {
569.524 - insertChar("x = [^]", ']', "x = []^");
569.525 - }
569.526 -
569.527 - public void testBrackets3() throws Exception {
569.528 - insertChar("x = [^]", 'a', "x = [a^]");
569.529 - }
569.530 -
569.531 - public void testBrackets4() throws Exception {
569.532 - insertChar("x = [^]", '[', "x = [[^]]");
569.533 - }
569.534 -
569.535 - public void testBrackets5() throws Exception {
569.536 - insertChar("x = [[^]]", ']', "x = [[]^]");
569.537 - }
569.538 -
569.539 - public void testBrackets6() throws Exception {
569.540 - insertChar("x = [[]^]", ']', "x = [[]]^");
569.541 - }
569.542 -
569.543 - public void testParens1() throws Exception {
569.544 - insertChar("x = ^", '(', "x = (^)");
569.545 - }
569.546 -
569.547 - public void testParens2() throws Exception {
569.548 - insertChar("x = (^)", ')', "x = ()^");
569.549 - }
569.550 -
569.551 - public void testParens3() throws Exception {
569.552 - insertChar("x = (^)", 'a', "x = (a^)");
569.553 - }
569.554 -
569.555 - public void testParens4() throws Exception {
569.556 - insertChar("x = (^)", '(', "x = ((^))");
569.557 - }
569.558 -
569.559 - public void testParens5() throws Exception {
569.560 - insertChar("x = ((^))", ')', "x = (()^)");
569.561 - }
569.562 -
569.563 - public void testParens6() throws Exception {
569.564 - insertChar("x = (()^)", ')', "x = (())^");
569.565 - }
569.566 -//
569.567 -//
569.568 -// public void testFindMatching1() throws Exception {
569.569 -// match("if (true) ^{\n^}");
569.570 -// }
569.571 -//
569.572 -// public void testFindMatching2() throws Exception {
569.573 -// match("x=^(true^)\ny=5");
569.574 -// }
569.575 -//
569.576 -// public void testFindMatching3() throws Exception {
569.577 -// match("x=^(true || (false)^)\ny=5");
569.578 -// }
569.579 -//
569.580 -// public void testFindMatching4() throws Exception {
569.581 -// match("function foo() ^{\nif (true) {\n}\n^}\n}");
569.582 -// }
569.583 -//
569.584 - public void testBackspace1() throws Exception {
569.585 - deleteChar("x^", "^");
569.586 - }
569.587 -
569.588 - public void testBackspace2() throws Exception {
569.589 - deleteChar("x^y", "^y");
569.590 - }
569.591 -
569.592 - public void testBackspace3() throws Exception {
569.593 - deleteChar("xy^z", "x^z");
569.594 - }
569.595 -
569.596 - public void testBackspace4() throws Exception {
569.597 - deleteChar("xy^z", "x^z");
569.598 - }
569.599 -
569.600 - public void testBackspace5() throws Exception {
569.601 - deleteChar("x=\"^\"", "x=^");
569.602 - }
569.603 -
569.604 - public void testBackspace6() throws Exception {
569.605 - deleteChar("x='^'", "x=^");
569.606 - }
569.607 -
569.608 - public void testBackspace7() throws Exception {
569.609 - deleteChar("x=(^)", "x=^");
569.610 - }
569.611 -
569.612 - public void testBackspace7b() throws Exception {
569.613 - deleteChar("x=[^]", "x=^");
569.614 - }
569.615 -
569.616 - public void testBackspace8() throws Exception {
569.617 - // See bug 111534
569.618 - deleteChar("x={^}", "x=^");
569.619 - }
569.620 -
569.621 - public void testBackspace9() throws Exception {
569.622 - deleteChar("def foo(^):\n", "def foo^\n");
569.623 - }
569.624 -
569.625 - public void testBackspaceComment() throws Exception {
569.626 - deleteChar("# x=[^]", "# x=^]");
569.627 - }
569.628 -
569.629 - public void testReplaceSelection1() throws Exception {
569.630 - insertChar("x = foo^", 'y', "x = y^", "foo");
569.631 - }
569.632 -
569.633 - public void testReplaceSelection2() throws Exception {
569.634 - insertChar("x = foo^", '"', "x = \"foo\"^", "foo");
569.635 - }
569.636 -
569.637 - public void testReplaceSelection4() throws Exception {
569.638 - insertChar("x = 'foo^bar'", '#', "x = '#^bar'", "foo");
569.639 - }
569.640 -
569.641 - public void testReplaceSelection5() throws Exception {
569.642 - insertChar("'(^position:absolute;'", '{', "'{^position:absolute;'", "(");
569.643 - }
569.644 -
569.645 - public void testReplaceSelection6() throws Exception {
569.646 - insertChar("'position^:absolute;'", '{', "'pos{^:absolute;'", "ition");
569.647 - }
569.648 -
569.649 - public void testReplaceSelectionChangeType1() throws Exception {
569.650 - insertChar("x = \"foo\"^", '\'', "x = 'foo'^", "\"foo\"");
569.651 - }
569.652 -
569.653 - public void testReplaceSelectionChangeType2() throws Exception {
569.654 - insertChar("x = \"foo\"^", '{', "x = {foo}^", "\"foo\"");
569.655 - }
569.656 -
569.657 - public void testReplaceSelectionNotInTemplateMode1() throws Exception {
569.658 - insertChar("x = foo^", '"', "x = \"^\"", "foo", true);
569.659 - }
569.660 -
569.661 - public void testdeleteWord() throws Exception {
569.662 - deleteWord("foo_bar_baz^", "foo_bar_^");
569.663 - }
569.664 -
569.665 - public void testdeleteWord111303() throws Exception {
569.666 - deleteWord("foo::bar^", "foo::^");
569.667 - deleteWord("Foo::Bar^", "Foo::^");
569.668 - deleteWord("Foo::Bar_Baz^", "Foo::Bar_^");
569.669 - }
569.670 - public void testdeleteWordx111305() throws Exception {
569.671 - deleteWord("foo_bar^", "foo_^");
569.672 - deleteWord("x.foo_bar^.y", "x.foo_^.y");
569.673 - }
569.674 -
569.675 - public void testdeleteWord2() throws Exception {
569.676 - deleteWord("foo_bar_baz ^", "foo_bar_baz^");
569.677 - deleteWord("foo_bar_^", "foo_^");
569.678 - }
569.679 -
569.680 - public void testdeleteWord3() throws Exception {
569.681 - deleteWord("FooBarBaz^", "FooBar^");
569.682 - }
569.683 -
569.684 - public void testDeleteWord4_110998() throws Exception {
569.685 - deleteWord("Blah::Set^Foo", "Blah::^Foo");
569.686 - }
569.687 -
569.688 - public void testdeleteWord5() throws Exception {
569.689 - deleteWord("foo_bar_^", "foo_^");
569.690 - }
569.691 -
569.692 - public void testdeleteWords() throws Exception {
569.693 - deleteWord("foo bar^", "foo ^");
569.694 - }
569.695 -
569.696 -
569.697 - public void testDeleteWord4_110998c() throws Exception {
569.698 - String before = " snark^\n";
569.699 - String after = " ^\n";
569.700 - deleteWord(before, after);
569.701 - }
569.702 -}
570.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonNameRangeTest.java Sun Jan 04 13:11:53 2015 -0600
570.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
570.3 @@ -1,95 +0,0 @@
570.4 -/*
570.5 - * To change this template, choose Tools | Templates
570.6 - * and open the template in the editor.
570.7 - */
570.8 -
570.9 -package org.netbeans.modules.python.editor;
570.10 -
570.11 -import java.util.List;
570.12 -import java.util.Map;
570.13 -import org.netbeans.modules.gsf.api.CompilationInfo;
570.14 -import org.netbeans.modules.gsf.api.OffsetRange;
570.15 -import org.netbeans.modules.gsf.api.ParserResult;
570.16 -import org.python.antlr.PythonTree;
570.17 -import org.python.antlr.Visitor;
570.18 -
570.19 -/**
570.20 - * Test the name range
570.21 - *
570.22 - * @author Tor Norbye
570.23 - */
570.24 -public class PythonNameRangeTest extends PythonTestBase {
570.25 - public PythonNameRangeTest(String testName) {
570.26 - super(testName);
570.27 - }
570.28 -
570.29 - @Override
570.30 - protected String describeNode(CompilationInfo info, Object obj, boolean includePath) throws Exception {
570.31 - return obj.toString();
570.32 - }
570.33 -
570.34 - @Override
570.35 - protected String getOffsetTestGoldenSuffix() {
570.36 - return ".nameoffsets";
570.37 - }
570.38 -
570.39 - @Override
570.40 - protected void initializeNodes(CompilationInfo info, ParserResult result, List<Object> validNodes,
570.41 - Map<Object,OffsetRange> positions, List<Object> invalidNodes) throws Exception {
570.42 - PythonTree root = PythonAstUtils.getRoot(info);
570.43 - assertNotNull(root);
570.44 -
570.45 - new TreeVisitor(validNodes, invalidNodes, positions, info).visit(root);
570.46 - }
570.47 -
570.48 - public void testOffsets1() throws Exception {
570.49 - checkOffsets("testfiles/empty.py");
570.50 - }
570.51 -
570.52 - public void testOffsets2() throws Exception {
570.53 - checkOffsets("testfiles/ConfigParser.py");
570.54 - }
570.55 -
570.56 - public void testOffsets3() throws Exception {
570.57 - checkOffsets("testfiles/datetime.py");
570.58 - }
570.59 -
570.60 - public void testOffsets4() throws Exception {
570.61 - checkOffsets("testfiles/getopt.py");
570.62 - }
570.63 -
570.64 - public void testOffsets5() throws Exception {
570.65 - checkOffsets("testfiles/test_scope.py");
570.66 - }
570.67 -
570.68 - private static class TreeVisitor extends Visitor {
570.69 - private List<Object> validNodes;
570.70 - private List<Object> invalidNodes;
570.71 - private Map<Object, OffsetRange> positions;
570.72 - private CompilationInfo info;
570.73 -
570.74 - TreeVisitor(List<Object> validNodes, List<Object> invalidNodes, Map<Object,
570.75 - OffsetRange> positions, CompilationInfo info) {
570.76 - this.validNodes = validNodes;
570.77 - this.invalidNodes = invalidNodes;
570.78 - this.positions = positions;
570.79 - this.info = info;
570.80 - }
570.81 -
570.82 - @Override
570.83 - public void traverse(PythonTree node) throws Exception {
570.84 - assertTrue(node.getCharStartIndex() <= node.getCharStopIndex());
570.85 -
570.86 - OffsetRange range = PythonAstUtils.getRange(node);
570.87 - OffsetRange nameRange = PythonAstUtils.getNameRange(info, node);
570.88 - if (!range.equals(nameRange) || PythonAstUtils.isNameNode(node)) {
570.89 - validNodes.add(node);
570.90 - positions.put(node, nameRange);
570.91 - }
570.92 -
570.93 - super.traverse(node);
570.94 - }
570.95 -
570.96 - }
570.97 -
570.98 -}
571.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonOccurrencesMarkerTest.java Sun Jan 04 13:11:53 2015 -0600
571.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
571.3 @@ -1,133 +0,0 @@
571.4 -/*
571.5 - * To change this template, choose Tools | Templates
571.6 - * and open the template in the editor.
571.7 - */
571.8 -
571.9 -package org.netbeans.modules.python.editor;
571.10 -
571.11 -import java.util.List;
571.12 -import javax.swing.text.Document;
571.13 -import org.netbeans.modules.gsf.GsfTestCompilationInfo;
571.14 -import org.openide.filesystems.FileObject;
571.15 -import org.openide.filesystems.FileUtil;
571.16 -
571.17 -/**
571.18 - *
571.19 - * @author Tor Norbye
571.20 - */
571.21 -public class PythonOccurrencesMarkerTest extends PythonTestBase {
571.22 -
571.23 - public PythonOccurrencesMarkerTest(String testName) {
571.24 - super(testName);
571.25 - }
571.26 -
571.27 - public void testMarks1() throws Exception {
571.28 - // TODO - these tests SHOULD pass symmetric but don't yet
571.29 - boolean symmetric = false;
571.30 -
571.31 - String caretLine = "def __init__(self, m^sg=''):";
571.32 - checkOccurrences("testfiles/ConfigParser.py", caretLine, symmetric);
571.33 - }
571.34 -
571.35 - public void testMarks2() throws Exception {
571.36 - // TODO - these tests SHOULD pass symmetric but don't yet
571.37 - boolean symmetric = false;
571.38 -
571.39 - String caretLine = "for (ke^y, value) in self._sections[section].items():";
571.40 - checkOccurrences("testfiles/ConfigParser.py", caretLine, symmetric);
571.41 - }
571.42 -
571.43 - public void test150581() throws Exception {
571.44 - FileObject testFile = getXTestPythonHomeFo().getFileObject("Lib/repr.py");
571.45 - assertNotNull(testFile);
571.46 - GsfTestCompilationInfo info = getInfo(testFile);
571.47 - PythonOccurrencesMarker marker = new PythonOccurrencesMarker();
571.48 - marker.setCaretPosition(786);
571.49 - marker.run(info);
571.50 - marker.getOccurrences();
571.51 - assertNull(PythonOccurrencesMarker.error);
571.52 - }
571.53 -
571.54 - // I think this test is wrong...
571.55 - //public void test150581b() throws Exception {
571.56 - // // TODO - these tests SHOULD pass symmetric but don't yet
571.57 - // boolean symmetric = false;
571.58 - //
571.59 - // String caretLine = "__builtin__.re^pr(x)";
571.60 - // checkOccurrences("testfiles/occurrences1.py", caretLine, symmetric);
571.61 - //}
571.62 -
571.63 - public void testMarks3() throws Exception {
571.64 - boolean symmetric = true;
571.65 - String caretLine = "new^format.append(zreplace)";
571.66 - checkOccurrences("testfiles/datetime.py", caretLine, symmetric);
571.67 - }
571.68 -
571.69 - public void testMarks4() throws Exception {
571.70 - boolean symmetric = true;
571.71 - String caretLine = "x = myf^unc";
571.72 - checkOccurrences("testfiles/occurrences2.py", caretLine, symmetric);
571.73 - }
571.74 -
571.75 - public void testMarks5() throws Exception {
571.76 - boolean symmetric = true;
571.77 - String caretLine = "import m^odule1";
571.78 - checkOccurrences("testfiles/occurrences2.py", caretLine, symmetric);
571.79 - }
571.80 -
571.81 - public void testMarks6() throws Exception {
571.82 - boolean symmetric = true;
571.83 - String caretLine = "import module3 as modu^le4";
571.84 - checkOccurrences("testfiles/occurrences2.py", caretLine, symmetric);
571.85 - }
571.86 -
571.87 - public void testMarks7() throws Exception {
571.88 - boolean symmetric = true;
571.89 - String caretLine = "toplevelv^ar2 =";
571.90 - checkOccurrences("testfiles/occurrences2.py", caretLine, symmetric);
571.91 - }
571.92 -
571.93 - public void testMarks8() throws Exception {
571.94 - boolean symmetric = true;
571.95 - String caretLine = "def mymethod(self,param1,pa^ram2):";
571.96 - checkOccurrences("testfiles/occurrences2.py", caretLine, symmetric);
571.97 - }
571.98 -
571.99 - public void testMarks9() throws Exception {
571.100 - boolean symmetric = true;
571.101 - String caretLine = "def _bu^ild_struct_time(";
571.102 - checkOccurrences("testfiles/datetime.py", caretLine, symmetric);
571.103 - }
571.104 -
571.105 - public void testMarks10() throws Exception {
571.106 - boolean symmetric = true;
571.107 - String caretLine = "sel^f.year, self.month, self.day = year, month, day";
571.108 - checkOccurrences("testfiles/datetime.py", caretLine, symmetric);
571.109 - }
571.110 -
571.111 - public void testMarks11() throws Exception {
571.112 - boolean symmetric = true;
571.113 - String caretLine = "# @type ^xy str";
571.114 - checkOccurrences("testfiles/typevars.py", caretLine, symmetric);
571.115 - }
571.116 -
571.117 - public void testStress() throws Exception {
571.118 - List<FileObject> files = findJythonFiles();
571.119 -
571.120 - //int MAX_FILES = Integer.MAX_VALUE;
571.121 - int MAX_FILES = 100;
571.122 -
571.123 - for (int i = 0; i < files.size() && i < MAX_FILES; i++) {
571.124 - FileObject fo = files.get(i);
571.125 - GsfTestCompilationInfo info = getInfo(fo);
571.126 - Document doc = info.getDocument();
571.127 - for (int offset = 0; offset < doc.getLength(); offset++) {
571.128 - PythonOccurrencesMarker marker = new PythonOccurrencesMarker();
571.129 - marker.setCaretPosition(offset);
571.130 - marker.run(info);
571.131 - marker.getOccurrences();
571.132 - assertNull("Handling " + FileUtil.getFileDisplayName(fo) + " at offset " + offset, PythonOccurrencesMarker.error);
571.133 - }
571.134 - }
571.135 - }
571.136 -}
572.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonParserTest.java Sun Jan 04 13:11:53 2015 -0600
572.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
572.3 @@ -1,178 +0,0 @@
572.4 -/*
572.5 - * To change this template, choose Tools | Templates
572.6 - * and open the template in the editor.
572.7 - */
572.8 -
572.9 -package org.netbeans.modules.python.editor;
572.10 -
572.11 -import java.util.List;
572.12 -import org.netbeans.modules.gsf.GsfTestCompilationInfo;
572.13 -import org.netbeans.modules.gsf.api.CompilationInfo;
572.14 -import org.python.antlr.PythonTree;
572.15 -import org.python.antlr.Visitor;
572.16 -import org.netbeans.modules.gsf.api.ParserResult;
572.17 -import org.netbeans.modules.gsf.api.Error;
572.18 -
572.19 -/**
572.20 - *
572.21 - * @author Tor Norbye
572.22 - */
572.23 -public class PythonParserTest extends PythonTestBase {
572.24 -
572.25 - public PythonParserTest(String testName) {
572.26 - super(testName);
572.27 - }
572.28 -
572.29 -// private void checkParseTree(String file, String caretLine, String nodeType) throws Exception {
572.30 -// PythonParser.runtimeException = null;
572.31 -// CompilationInfo info = getInfo(file);
572.32 -//
572.33 -// String text = info.getText();
572.34 -//
572.35 -// int caretOffset = -1;
572.36 -// if (caretLine != null) {
572.37 -// int caretDelta = caretLine.indexOf("^");
572.38 -// assertTrue(caretDelta != -1);
572.39 -// caretLine = caretLine.substring(0, caretDelta) + caretLine.substring(caretDelta + 1);
572.40 -// int lineOffset = text.indexOf(caretLine);
572.41 -// assertTrue(lineOffset != -1);
572.42 -//
572.43 -// caretOffset = lineOffset + caretDelta;
572.44 -// ((GsfTestCompilationInfo)info).setCaretOffset(caretOffset);
572.45 -// }
572.46 -//
572.47 -// PythonTree root = PythonAstUtils.getRoot(info);
572.48 -// assertNotNull("Parsing broken input failed for " + file, root);
572.49 -//
572.50 -// // Ensure that we find the node we're looking for
572.51 -// if (nodeType != null) {
572.52 -// PythonParserResult rpr = PythonAstUtils.getParseResult(info);
572.53 -// OffsetRange range = rpr.getSanitizedRange();
572.54 -// if (range.containsInclusive(caretOffset)) {
572.55 -// caretOffset = range.getStart();
572.56 -// }
572.57 -// AstPath path = AstPath.get(root, caretOffset);
572.58 -// PythonTree closest = path.leaf();
572.59 -// assertNotNull(closest);
572.60 -// String leafName = closest.getClass().getName();
572.61 -// leafName = leafName.substring(leafName.lastIndexOf('.')+1);
572.62 -// assertEquals(nodeType, closest.toString());
572.63 -// }
572.64 -// assertNull(PythonParser.runtimeException);
572.65 -// }
572.66 -
572.67 - private void checkNoParseAbort(String file) throws Exception {
572.68 - checkNoParseAbort(file, null);
572.69 - }
572.70 - private void checkNoParseAbort(String file, String caretLine) throws Exception {
572.71 - PythonParser.runtimeException = null;
572.72 - CompilationInfo info = getInfo(file);
572.73 - PythonTree root = PythonAstUtils.getRoot(info);
572.74 - assertNull(PythonParser.runtimeException != null ? PythonParser.runtimeException.toString() : "OK", PythonParser.runtimeException);
572.75 - // Check that a walk works too
572.76 - if (root != null) {
572.77 - new Visitor() {
572.78 - @Override
572.79 - public void traverse(PythonTree node) throws Exception {
572.80 - super.traverse(node);
572.81 - }
572.82 -
572.83 - }.visit(root);
572.84 - }
572.85 - }
572.86 -
572.87 - protected void checkErrors(String relFilePath, String caretLine) throws Exception {
572.88 - GsfTestCompilationInfo info = getInfo(relFilePath);
572.89 -
572.90 - if (caretLine != null) {
572.91 - int caretDelta = caretLine.indexOf("^");
572.92 - assertTrue(caretDelta != -1);
572.93 - caretLine = caretLine.substring(0, caretDelta) + caretLine.substring(caretDelta + 1);
572.94 - int lineOffset = info.getText().indexOf(caretLine);
572.95 - assertTrue("NOT FOUND: " + info.getFileObject().getName() + ":" + caretLine, lineOffset != -1);
572.96 -
572.97 - int caretOffset = lineOffset + caretDelta;
572.98 - info.setCaretOffset(caretOffset);
572.99 - }
572.100 -
572.101 - String text = info.getText();
572.102 - assertNotNull(text);
572.103 -
572.104 - ParserResult pr = info.getEmbeddedResult(info.getPreferredMimeType(), 0);
572.105 - assertNotNull(pr);
572.106 -
572.107 - List<Error> diagnostics = pr.getDiagnostics();
572.108 - String annotatedSource = annotateErrors(text, diagnostics);
572.109 - assertDescriptionMatches(relFilePath, annotatedSource, false, ".errors");
572.110 - }
572.111 -
572.112 - public void testPartial11() throws Exception {
572.113 - checkNoParseAbort("testfiles/errors1.py");
572.114 - checkErrors("testfiles/errors1.py");
572.115 - }
572.116 -
572.117 - public void testCastAbort1() throws Exception {
572.118 - checkNoParseAbort("testfiles/errors2.py");
572.119 - checkErrors("testfiles/errors2.py");
572.120 - }
572.121 -
572.122 - public void testInfiniteLoop1() throws Exception {
572.123 - checkNoParseAbort("testfiles/errors3.py");
572.124 - checkErrors("testfiles/errors3.py");
572.125 - }
572.126 -
572.127 - public void testInfiniteLoop2() throws Exception {
572.128 - checkNoParseAbort("testfiles/errors4.py");
572.129 - checkErrors("testfiles/errors4.py");
572.130 - }
572.131 -
572.132 - public void testPositions() throws Exception {
572.133 - checkNoParseAbort("testfiles/errors5.py");
572.134 - }
572.135 -
572.136 - // Not yet passing
572.137 - public void testAsKeyword() throws Exception {
572.138 - // See 150921
572.139 - checkNoParseAbort("testfiles/lib-old/Para.py");
572.140 - }
572.141 -
572.142 - public void testNpe() throws Exception {
572.143 - // See 150921
572.144 - checkNoParseAbort("testfiles/errors6.py");
572.145 - }
572.146 -
572.147 - public void testNpe2() throws Exception {
572.148 - // See 155904
572.149 - checkNoParseAbort("testfiles/errors7.py");
572.150 - }
572.151 -
572.152 - public void testCastException1() throws Exception {
572.153 - checkNoParseAbort("testfiles/errors8.py");
572.154 - }
572.155 -
572.156 - public void testCastException2() throws Exception {
572.157 - checkNoParseAbort("testfiles/errors9.py");
572.158 - }
572.159 -
572.160 - public void testPython26Syntax() throws Exception {
572.161 - checkNoParseAbort("testfiles/exceptas.py");
572.162 - }
572.163 -
572.164 - public void testMissingColons1() throws Exception {
572.165 - checkNoParseAbort("testfiles/errors10.py");
572.166 - checkErrors("testfiles/errors10.py");
572.167 - }
572.168 -
572.169 - public void testMissingColons2() throws Exception {
572.170 - checkNoParseAbort("testfiles/errors11.py");
572.171 - checkErrors("testfiles/errors11.py");
572.172 - }
572.173 -
572.174 - // https://netbeans.org/bugzilla/show_bug.cgi?id=178442
572.175 - public void testIncremental1() throws Exception {
572.176 - checkErrors("testfiles/errors12.py", "ABC,^DEF");
572.177 - }
572.178 - public void testIncremental2() throws Exception {
572.179 - checkErrors("testfiles/errors13.py", "newparam,^");
572.180 - }
572.181 -}
573.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonSemanticHighlighterTest.java Sun Jan 04 13:11:53 2015 -0600
573.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
573.3 @@ -1,45 +0,0 @@
573.4 -/*
573.5 - * To change this template, choose Tools | Templates
573.6 - * and open the template in the editor.
573.7 - */
573.8 -
573.9 -package org.netbeans.modules.python.editor;
573.10 -
573.11 -/**
573.12 - *
573.13 - * @author Tor Norbye
573.14 - */
573.15 -public class PythonSemanticHighlighterTest extends PythonTestBase {
573.16 -
573.17 - public PythonSemanticHighlighterTest(String testName) {
573.18 - super(testName);
573.19 - }
573.20 -
573.21 - public void testSemantic1() throws Exception {
573.22 - checkSemantic("testfiles/empty.py");
573.23 - }
573.24 -
573.25 - public void testSemantic2() throws Exception {
573.26 - checkSemantic("testfiles/ConfigParser.py");
573.27 - }
573.28 -
573.29 - public void testSemantic3() throws Exception {
573.30 - checkSemantic("testfiles/datetime.py");
573.31 - }
573.32 -
573.33 - public void testSemantic4() throws Exception {
573.34 - checkSemantic("testfiles/getopt.py");
573.35 - }
573.36 -
573.37 - public void testSemantic5() throws Exception {
573.38 - checkSemantic("testfiles/test_scope.py");
573.39 - }
573.40 -
573.41 - public void testDecorators() throws Exception {
573.42 - checkSemantic("testfiles/staticmethods.py");
573.43 - }
573.44 -
573.45 - public void testDecorators2() throws Exception {
573.46 - checkSemantic("testfiles/decorators.py");
573.47 - }
573.48 -}
574.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonStructureScannerTest.java Sun Jan 04 13:11:53 2015 -0600
574.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
574.3 @@ -1,61 +0,0 @@
574.4 -/*
574.5 - * To change this template, choose Tools | Templates
574.6 - * and open the template in the editor.
574.7 - */
574.8 -
574.9 -package org.netbeans.modules.python.editor;
574.10 -
574.11 -/**
574.12 - *
574.13 - * @author Tor Norbye
574.14 - */
574.15 -public class PythonStructureScannerTest extends PythonTestBase {
574.16 -
574.17 - public PythonStructureScannerTest(String testName) {
574.18 - super(testName);
574.19 - }
574.20 -
574.21 - public void testStructure1() throws Exception {
574.22 - checkStructure("testfiles/empty.py");
574.23 - }
574.24 -
574.25 - public void testStructure2() throws Exception {
574.26 - checkStructure("testfiles/ConfigParser.py");
574.27 - }
574.28 -
574.29 - public void testStructure3() throws Exception {
574.30 - checkStructure("testfiles/datetime.py");
574.31 - }
574.32 -
574.33 - public void testStructure4() throws Exception {
574.34 - checkStructure("testfiles/getopt.py");
574.35 - }
574.36 -
574.37 - public void testStructure5() throws Exception {
574.38 - checkStructure("testfiles/test_scope.py");
574.39 - }
574.40 -
574.41 - public void testFolds1() throws Exception {
574.42 - checkFolds("testfiles/empty.py");
574.43 - }
574.44 -
574.45 - public void testFolds2() throws Exception {
574.46 - checkFolds("testfiles/ConfigParser.py");
574.47 - }
574.48 -
574.49 - public void testFolds3() throws Exception {
574.50 - checkFolds("testfiles/datetime.py");
574.51 - }
574.52 -
574.53 - public void testFolds4() throws Exception {
574.54 - checkFolds("testfiles/getopt.py");
574.55 - }
574.56 -
574.57 - public void testFolds5() throws Exception {
574.58 - checkFolds("testfiles/test_scope.py");
574.59 - }
574.60 -
574.61 - public void testModifiers() throws Exception {
574.62 - checkStructure("testfiles/modifiers.py");
574.63 - }
574.64 -}
575.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonTestBase.java Sun Jan 04 13:11:53 2015 -0600
575.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
575.3 @@ -1,199 +0,0 @@
575.4 -/*
575.5 - * To change this template, choose Tools | Templates
575.6 - * and open the template in the editor.
575.7 - */
575.8 -
575.9 -package org.netbeans.modules.python.editor;
575.10 -
575.11 -import java.io.File;
575.12 -import java.net.MalformedURLException;
575.13 -import java.net.URL;
575.14 -import java.util.ArrayList;
575.15 -import java.util.Collections;
575.16 -import java.util.List;
575.17 -import java.util.Map;
575.18 -import java.util.Set;
575.19 -import org.netbeans.modules.python.editor.hints.PythonAstRule;
575.20 -import org.netbeans.modules.python.editor.hints.PythonSelectionRule;
575.21 -import org.netbeans.modules.python.editor.lexer.PythonTokenId;
575.22 -import org.netbeans.editor.BaseDocument;
575.23 -import org.netbeans.modules.gsf.GsfTestBase;
575.24 -import org.netbeans.modules.gsf.Language;
575.25 -import org.netbeans.modules.gsf.LanguageRegistry;
575.26 -import org.netbeans.modules.gsf.spi.DefaultLanguageConfig;
575.27 -import org.netbeans.modules.gsfret.hints.infrastructure.GsfHintsManager;
575.28 -import org.openide.filesystems.FileObject;
575.29 -import org.openide.filesystems.FileStateInvalidException;
575.30 -import org.openide.filesystems.FileUtil;
575.31 -import org.openide.util.Exceptions;
575.32 -import org.python.antlr.PythonTree;
575.33 -import org.python.antlr.Visitor;
575.34 -
575.35 -/**
575.36 - * @author Tor Norbye
575.37 - */
575.38 -public abstract class PythonTestBase extends GsfTestBase {
575.39 - static {
575.40 - PythonIndex.setClusterUrl(getClusterUrl().toExternalForm());
575.41 - }
575.42 -
575.43 - public PythonTestBase(String testName) {
575.44 - super(testName);
575.45 - }
575.46 -
575.47 - @Override
575.48 - protected boolean runInEQ() {
575.49 - // Must run in AWT thread (BaseKit.install() checks for that)
575.50 - return true;
575.51 - }
575.52 -
575.53 - @Override
575.54 - protected DefaultLanguageConfig getPreferredLanguage() {
575.55 - return new PythonLanguage();
575.56 - }
575.57 -
575.58 - @Override
575.59 - protected String getPreferredMimeType() {
575.60 - return PythonTokenId.PYTHON_MIME_TYPE;
575.61 - }
575.62 -
575.63 - @Override
575.64 - protected void initializeClassPaths() {
575.65 - System.setProperty("netbeans.user", getWorkDirPath());
575.66 - org.netbeans.modules.gsfret.source.usages.Index.addPreindexRoot(getClusterHome());
575.67 - org.netbeans.modules.gsfret.source.usages.Index.addPreindexRoot(getXTestPythonHomeFo().getFileObject("Lib"));
575.68 - initializeRegistry();
575.69 - super.initializeClassPaths();
575.70 - }
575.71 -
575.72 - @Override
575.73 - protected List<URL> getExtraCpUrls() {
575.74 - try {
575.75 - return Collections.singletonList(getXTestPythonHomeFo().getFileObject("Lib").getURL());
575.76 - } catch (FileStateInvalidException ex) {
575.77 - Exceptions.printStackTrace(ex);
575.78 - return null;
575.79 - }
575.80 - }
575.81 -
575.82 - @SuppressWarnings("unchecked")
575.83 - public void ensureRegistered(PythonAstRule hint) throws Exception {
575.84 - Language language = LanguageRegistry.getInstance().getLanguageByMimeType(getPreferredMimeType());
575.85 - assertNotNull(language.getHintsProvider());
575.86 - GsfHintsManager hintsManager = language.getHintsManager();
575.87 - Map<Integer, List<PythonAstRule>> hints = (Map)hintsManager.getHints();
575.88 - Set<Class> kinds = hint.getKinds();
575.89 - for (Class nodeType : kinds) {
575.90 - List<PythonAstRule> rules = hints.get(nodeType);
575.91 - assertNotNull(rules);
575.92 - boolean found = false;
575.93 - for (PythonAstRule rule : rules) {
575.94 - if (rule.getClass() == hint.getClass()) {
575.95 - found = true;
575.96 - break;
575.97 - }
575.98 - }
575.99 -
575.100 - assertTrue(found);
575.101 - }
575.102 - }
575.103 -
575.104 - @SuppressWarnings("unchecked")
575.105 - public void ensureRegistered(PythonSelectionRule hint) throws Exception {
575.106 - Language language = LanguageRegistry.getInstance().getLanguageByMimeType(getPreferredMimeType());
575.107 - assertNotNull(language.getHintsProvider());
575.108 - GsfHintsManager hintsManager = language.getHintsManager();
575.109 - List<PythonSelectionRule> hints = (List<PythonSelectionRule>) hintsManager.getSelectionHints();
575.110 - boolean found = false;
575.111 - for (PythonSelectionRule rule : hints) {
575.112 - if (rule.getClass() == hint.getClass()) {
575.113 - found = true;
575.114 - break;
575.115 - }
575.116 - }
575.117 -
575.118 - assertTrue(found);
575.119 - }
575.120 -
575.121 - // Called via reflection from GsfUtilities. This is necessary because
575.122 - // during tests, going from a FileObject to a BaseDocument only works
575.123 - // if all the correct data loaders are installed and working - and that
575.124 - // hasn't been the case; we end up with PlainDocuments instead of BaseDocuments.
575.125 - // If anyone can figure this out, please let me know and simplify the
575.126 - // test infrastructure.
575.127 - public static BaseDocument getDocumentFor(FileObject fo) {
575.128 - BaseDocument doc = GsfTestBase.createDocument(read(fo));
575.129 - doc.putProperty(org.netbeans.api.lexer.Language.class, PythonTokenId.language());
575.130 - doc.putProperty("mimeType", PythonTokenId.PYTHON_MIME_TYPE);
575.131 -
575.132 - return doc;
575.133 - }
575.134 -
575.135 - // Locate as many Python files from the JPython distribution as possible: libs, gems, etc.
575.136 - protected List<FileObject> findJythonFiles() {
575.137 - List<FileObject> l = new ArrayList<FileObject>();
575.138 - addPythonFiles(l, getXTestPythonHomeFo());
575.139 -
575.140 - return l;
575.141 - }
575.142 -
575.143 - private void addPythonFiles(List<FileObject> list, FileObject parent) {
575.144 - for (FileObject child : parent.getChildren()) {
575.145 - if (child.isFolder()) {
575.146 - if (child.getName().equals("test")) {
575.147 - // Skip test stuff
575.148 - continue;
575.149 - }
575.150 - addPythonFiles(list, child);
575.151 - } else if (child.getMIMEType().equals(PythonTokenId.PYTHON_MIME_TYPE)) {
575.152 - list.add(child);
575.153 - }
575.154 - }
575.155 - }
575.156 -
575.157 - public static File getXTestPythonHome() {
575.158 - String destDir = System.getProperty("xtest.python.home");
575.159 - if (destDir == null) {
575.160 - throw new RuntimeException("xtest.Python.home property has to be set when running within binary distribution");
575.161 - }
575.162 - return new File(destDir);
575.163 - }
575.164 -
575.165 - public static String getXTestPythonHomePath() {
575.166 - return getXTestPythonHome().getAbsolutePath();
575.167 - }
575.168 -
575.169 - public static FileObject getXTestPythonHomeFo() {
575.170 - return FileUtil.toFileObject(getXTestPythonHome());
575.171 - }
575.172 -
575.173 - public static FileObject getClusterHome() {
575.174 - return FileUtil.toFileObject(getXTestPythonHome().getParentFile());
575.175 - }
575.176 -
575.177 - public static URL getClusterUrl() {
575.178 - try {
575.179 - return getXTestPythonHome().getParentFile().toURI().toURL();
575.180 - } catch (MalformedURLException ex) {
575.181 - Exceptions.printStackTrace(ex);
575.182 - fail(ex.toString());
575.183 - return null;
575.184 - }
575.185 - }
575.186 -
575.187 - protected List<PythonTree> getAllNodes(PythonTree root) throws Exception {
575.188 - final List<PythonTree> nodes = new ArrayList<PythonTree>();
575.189 -
575.190 - Visitor visitor = new Visitor() {
575.191 -
575.192 - @Override
575.193 - public void traverse(PythonTree node) throws Exception {
575.194 - nodes.add(node);
575.195 - super.traverse(node);
575.196 - }
575.197 -
575.198 - };
575.199 - visitor.visit(root);
575.200 - return nodes;
575.201 - }
575.202 -}
576.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonTypeAnalyzerTest.java Sun Jan 04 13:11:53 2015 -0600
576.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
576.3 @@ -1,115 +0,0 @@
576.4 -/*
576.5 - * To change this template, choose Tools | Templates
576.6 - * and open the template in the editor.
576.7 - */
576.8 -
576.9 -package org.netbeans.modules.python.editor;
576.10 -
576.11 -import org.netbeans.modules.python.editor.lexer.PythonTokenId;
576.12 -import org.netbeans.modules.gsf.GsfTestCompilationInfo;
576.13 -import org.openide.filesystems.FileObject;
576.14 -import org.python.antlr.PythonTree;
576.15 -
576.16 -/**
576.17 - * Test for the Python type analyzer.
576.18 - *
576.19 - * @author Tor Norbye
576.20 - */
576.21 -public class PythonTypeAnalyzerTest extends PythonTestBase {
576.22 -
576.23 - public PythonTypeAnalyzerTest(String testName) {
576.24 - super(testName);
576.25 - }
576.26 -
576.27 - private PythonTypeAnalyzer getAnalyzer(String file, String caretLine, boolean findMethod) throws Exception {
576.28 - FileObject fo = getTestFile(file);
576.29 - GsfTestCompilationInfo info = getInfo(fo);
576.30 - PythonTree root = PythonAstUtils.getRoot(info);
576.31 - initializeRegistry();
576.32 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE));
576.33 -
576.34 - int caretOffset = -1;
576.35 - if (caretLine != null) {
576.36 - int caretDelta = caretLine.indexOf("^");
576.37 - assertTrue(caretDelta != -1);
576.38 - caretLine = caretLine.substring(0, caretDelta) + caretLine.substring(caretDelta + 1);
576.39 - int lineOffset = info.getText().indexOf(caretLine);
576.40 - assertTrue(lineOffset != -1);
576.41 - caretOffset = lineOffset + caretDelta;
576.42 - }
576.43 -
576.44 - AstPath path = AstPath.get(root, caretOffset);
576.45 - PythonTree node = path.leaf();
576.46 -
576.47 - if (findMethod) {
576.48 - PythonTree method = PythonAstUtils.getLocalScope(path);
576.49 - assertNotNull(method);
576.50 -
576.51 - root = method;
576.52 - }
576.53 -
576.54 - PythonTypeAnalyzer instance = new PythonTypeAnalyzer(info, index, root, node, caretOffset, caretOffset, fo);
576.55 -
576.56 - return instance;
576.57 - }
576.58 -
576.59 - public void testGetType1() throws Exception {
576.60 - PythonTypeAnalyzer instance = getAnalyzer("testfiles/types.py", "#^FIRST_CARET_POS", true);
576.61 -
576.62 - assertEquals("SomeOtherClass", instance.getType("x"));
576.63 - assertEquals("SomeOtherClass", instance.getType("y"));
576.64 - assertEquals("SomeOtherClass", instance.getType("z"));
576.65 - assertEquals("str", instance.getType("yz"));
576.66 - assertEquals("int", instance.getType("w"));
576.67 - assertEquals(null, instance.getType("unknown"));
576.68 - }
576.69 -
576.70 - public void testGetType2() throws Exception {
576.71 - PythonTypeAnalyzer instance = getAnalyzer("testfiles/types.py", "#^SECOND_CARET_POS", true);
576.72 -
576.73 - assertEquals("Other", instance.getType("x"));
576.74 - assertEquals("int", instance.getType("y"));
576.75 - assertEquals("str", instance.getType("z"));
576.76 - assertEquals("str", instance.getType("yz"));
576.77 - assertEquals("int", instance.getType("w"));
576.78 - assertEquals(null, instance.getType("unknown"));
576.79 - }
576.80 -
576.81 - public void testGetType3() throws Exception {
576.82 - PythonTypeAnalyzer instance = getAnalyzer("testfiles/compl2.py", "unknown^", true);
576.83 -
576.84 - assertEquals("ZipFile", instance.getType("myothervar"));
576.85 - assertEquals("file", instance.getType("myvar"));
576.86 - assertEquals(null, instance.getType("unknown"));
576.87 - }
576.88 -
576.89 - public void testTypeAssertions1() throws Exception {
576.90 - PythonTypeAnalyzer instance = getAnalyzer("testfiles/types.py", "#^FIRST_CARET_POS", true);
576.91 -
576.92 - assertEquals("int", instance.getType("defined1"));
576.93 - }
576.94 -
576.95 - public void testTypeAssertions2() throws Exception {
576.96 - PythonTypeAnalyzer instance = getAnalyzer("testfiles/types.py", "#^SECOND_CARET_POS", true);
576.97 -
576.98 - assertEquals("str", instance.getType("defined1"));
576.99 - }
576.100 -
576.101 - public void testTypeAssertions3() throws Exception {
576.102 - PythonTypeAnalyzer instance = getAnalyzer("testfiles/types.py", "#^SECOND_CARET_POS", true);
576.103 -
576.104 - assertEquals("str", instance.getType("s"));
576.105 - }
576.106 -
576.107 - public void testTypeExceptionVars1() throws Exception {
576.108 - PythonTypeAnalyzer instance = getAnalyzer("testfiles/exceptas.py", "% ex.^e", true);
576.109 -
576.110 - assertEquals("MyError", instance.getType("ex"));
576.111 - }
576.112 -
576.113 - public void testTypeExceptionVars2() throws Exception {
576.114 - PythonTypeAnalyzer instance = getAnalyzer("testfiles/exceptas.py", "% ex2.^e", true);
576.115 -
576.116 - assertEquals("MyError", instance.getType("ex2"));
576.117 - }
576.118 -}
577.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/PythonUtilsTest.java Sun Jan 04 13:11:53 2015 -0600
577.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
577.3 @@ -1,138 +0,0 @@
577.4 -/*
577.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
577.6 - *
577.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
577.8 - *
577.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
577.10 - * Other names may be trademarks of their respective owners.
577.11 - *
577.12 - * The contents of this file are subject to the terms of either the GNU
577.13 - * General Public License Version 2 only ("GPL") or the Common
577.14 - * Development and Distribution License("CDDL") (collectively, the
577.15 - * "License"). You may not use this file except in compliance with the
577.16 - * License. You can obtain a copy of the License at
577.17 - * http://www.netbeans.org/cddl-gplv2.html
577.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
577.19 - * specific language governing permissions and limitations under the
577.20 - * License. When distributing the software, include this License Header
577.21 - * Notice in each file and include the License file at
577.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
577.23 - * particular file as subject to the "Classpath" exception as provided
577.24 - * by Oracle in the GPL Version 2 section of the License file that
577.25 - * accompanied this code. If applicable, add the following below the
577.26 - * License Header, with the fields enclosed by brackets [] replaced by
577.27 - * your own identifying information:
577.28 - * "Portions Copyrighted [year] [name of copyright owner]"
577.29 - *
577.30 - * If you wish your version of this file to be governed by only the CDDL
577.31 - * or only the GPL Version 2, indicate your decision by adding
577.32 - * "[Contributor] elects to include this software in this distribution
577.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
577.34 - * single choice of license, a recipient has the option to distribute
577.35 - * your version of this file under either the CDDL, the GPL Version 2 or
577.36 - * to extend the choice of license to its licensees as provided above.
577.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
577.38 - * Version 2 license, then the option applies only if the new code is
577.39 - * made subject to such option by the copyright holder.
577.40 - *
577.41 - * Contributor(s):
577.42 - *
577.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
577.44 - */
577.45 -package org.netbeans.modules.python.editor;
577.46 -
577.47 -import java.util.ArrayList;
577.48 -import java.util.Arrays;
577.49 -import java.util.Collections;
577.50 -import java.util.List;
577.51 -import org.netbeans.modules.python.api.Util;
577.52 -import org.openide.filesystems.FileObject;
577.53 -import org.openide.filesystems.FileUtil;
577.54 -
577.55 -/**
577.56 - *
577.57 - * @author Tor Norbye
577.58 - */
577.59 -public class PythonUtilsTest extends PythonTestBase {
577.60 -
577.61 - public PythonUtilsTest(String name) {
577.62 - super(name);
577.63 - }
577.64 -
577.65 - public void testGetOffsetByLineCol() throws Exception {
577.66 - assertEquals(5, PythonUtils.getOffsetByLineCol("fooooooooo\nHello\n", 0, 5));
577.67 - }
577.68 -
577.69 - public void testGetOffsetByLineCol2() throws Exception {
577.70 - assertEquals(5, PythonUtils.getOffsetByLineCol("fooooooooo", 0, 5));
577.71 - }
577.72 -
577.73 - public void testGetOffsetByLineCol3() throws Exception {
577.74 - assertEquals(2, PythonUtils.getOffsetByLineCol("o\nHello\n", 1, 0));
577.75 - }
577.76 -
577.77 - public void testGetOffsetByLineCol4() throws Exception {
577.78 - assertEquals(4, PythonUtils.getOffsetByLineCol("o\nHello\n", 1, 2));
577.79 - }
577.80 -
577.81 - public void testGetOffsetByLineCol5() throws Exception {
577.82 - assertEquals(8, PythonUtils.getOffsetByLineCol("o\nHello\n", 2, 0));
577.83 - }
577.84 -
577.85 - public void testGetOffsetByLineCol6() throws Exception {
577.86 - assertEquals(8, PythonUtils.getOffsetByLineCol("o\nHello\n", 50, 0));
577.87 - }
577.88 -
577.89 - public void testGetOffsetByLineCol7() throws Exception {
577.90 - assertEquals(2, PythonUtils.getOffsetByLineCol("o\nHello\n", 1, -1));
577.91 - }
577.92 - public void checkRoots(FileObject[] expected, FileObject[] path) throws Exception {
577.93 - List<FileObject> pythonPath = Arrays.asList(path);
577.94 -
577.95 - List<FileObject> roots = Util.findUniqueRoots(pythonPath);
577.96 - List<String> list = new ArrayList<String>();
577.97 - for (FileObject root : roots) {
577.98 - list.add(FileUtil.getFileDisplayName(root));
577.99 - }
577.100 - Collections.sort(list);
577.101 - List<FileObject> expectedList = Arrays.asList(expected);
577.102 - Collections.sort(list);
577.103 -
577.104 - List<String> elist = new ArrayList<String>();
577.105 - for (FileObject root : expectedList) {
577.106 - elist.add(FileUtil.getFileDisplayName(root));
577.107 - }
577.108 - Collections.sort(elist);
577.109 -
577.110 - assertEquals(elist.toString(), list.toString());
577.111 - }
577.112 -
577.113 - public void testFindUniqueRoots() throws Exception {
577.114 - FileObject path1 = getTestFile("testfiles/package/subpackage1");
577.115 - FileObject path2 = getTestFile("testfiles/package/subpackage2");
577.116 - FileObject path3 = getTestFile("testfiles/toppkg");
577.117 - FileObject path4 = getTestFile("testfiles/package");
577.118 - FileObject path5 = getTestFile("testfiles/");
577.119 - FileObject path6 = getTestFile("testfiles/toppkg/medpkg/lowpkg");
577.120 -
577.121 - checkRoots(
577.122 - new FileObject[]{path5},
577.123 - new FileObject[]{path1, path2, path3, path4, path5, path6});
577.124 -
577.125 - checkRoots(
577.126 - new FileObject[]{path4, path3},
577.127 - new FileObject[]{path6, path3, path4});
577.128 -
577.129 - checkRoots(
577.130 - new FileObject[]{path1, path2},
577.131 - new FileObject[]{path1, path2});
577.132 -
577.133 - checkRoots(
577.134 - new FileObject[]{path6},
577.135 - new FileObject[]{path6});
577.136 -
577.137 - checkRoots(
577.138 - new FileObject[]{path1, path3},
577.139 - new FileObject[]{path1, path3, path6});
577.140 - }
577.141 -}
578.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/RstFormatterTest.java Sun Jan 04 13:11:53 2015 -0600
578.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
578.3 @@ -1,263 +0,0 @@
578.4 -/*
578.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
578.6 - *
578.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
578.8 - *
578.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
578.10 - * Other names may be trademarks of their respective owners.
578.11 - *
578.12 - * The contents of this file are subject to the terms of either the GNU
578.13 - * General Public License Version 2 only ("GPL") or the Common
578.14 - * Development and Distribution License("CDDL") (collectively, the
578.15 - * "License"). You may not use this file except in compliance with the
578.16 - * License. You can obtain a copy of the License at
578.17 - * http://www.netbeans.org/cddl-gplv2.html
578.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
578.19 - * specific language governing permissions and limitations under the
578.20 - * License. When distributing the software, include this License Header
578.21 - * Notice in each file and include the License file at
578.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
578.23 - * particular file as subject to the "Classpath" exception as provided
578.24 - * by Oracle in the GPL Version 2 section of the License file that
578.25 - * accompanied this code. If applicable, add the following below the
578.26 - * License Header, with the fields enclosed by brackets [] replaced by
578.27 - * your own identifying information:
578.28 - * "Portions Copyrighted [year] [name of copyright owner]"
578.29 - *
578.30 - * If you wish your version of this file to be governed by only the CDDL
578.31 - * or only the GPL Version 2, indicate your decision by adding
578.32 - * "[Contributor] elects to include this software in this distribution
578.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
578.34 - * single choice of license, a recipient has the option to distribute
578.35 - * your version of this file under either the CDDL, the GPL Version 2 or
578.36 - * to extend the choice of license to its licensees as provided above.
578.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
578.38 - * Version 2 license, then the option applies only if the new code is
578.39 - * made subject to such option by the copyright holder.
578.40 - *
578.41 - * Contributor(s):
578.42 - *
578.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
578.44 - */
578.45 -
578.46 -package org.netbeans.modules.python.editor;
578.47 -
578.48 -import java.util.ArrayList;
578.49 -import java.util.List;
578.50 -import org.netbeans.editor.BaseDocument;
578.51 -import org.netbeans.modules.gsf.api.CompilationInfo;
578.52 -import org.netbeans.modules.gsf.api.ElementKind;
578.53 -import org.netbeans.modules.python.editor.elements.IndexedElement;
578.54 -import org.netbeans.modules.python.editor.elements.IndexedMethod;
578.55 -import org.openide.filesystems.FileObject;
578.56 -import org.openide.filesystems.FileUtil;
578.57 -import org.python.antlr.PythonTree;
578.58 -import org.python.antlr.ast.ClassDef;
578.59 -import org.python.antlr.ast.FunctionDef;
578.60 -import org.python.antlr.ast.Module;
578.61 -
578.62 -/**
578.63 - *
578.64 - * @author Tor Norbye
578.65 - */
578.66 -public class RstFormatterTest extends PythonTestBase {
578.67 -
578.68 - public RstFormatterTest(String name) {
578.69 - super(name);
578.70 - }
578.71 -
578.72 - private IndexedElement getFakeElement(String name, ElementKind kind, String url, String rhs, List<String> parameters) {
578.73 - IndexedElement fakeElement;
578.74 - if (parameters != null) {
578.75 - assert kind == ElementKind.METHOD;
578.76 - String clz = "Unknown";
578.77 - StringBuilder sb2 = new StringBuilder();
578.78 - sb2.append(name);
578.79 -
578.80 - sb2.append(";F;0;"); // NOI18N
578.81 -
578.82 - boolean first = true;
578.83 - for (String s : parameters) {
578.84 - if (first) {
578.85 - first = false;
578.86 - } else {
578.87 - sb2.append(',');
578.88 - }
578.89 - sb2.append(s);
578.90 - }
578.91 - sb2.append(';');
578.92 - String signature = sb2.toString();
578.93 - fakeElement = new IndexedMethod(name, kind, url, rhs, clz, signature);
578.94 - } else {
578.95 - String clz = null;
578.96 - String signature = null;
578.97 - fakeElement = new IndexedElement(name, kind, url, rhs, clz, signature);
578.98 - }
578.99 -
578.100 - return fakeElement;
578.101 - }
578.102 -
578.103 - private void checkDocumentation(String testFile, String name, ElementKind kind) throws Exception {
578.104 - FileObject fo = getTestFile(testFile);
578.105 - String url = FileUtil.toFile(fo).toURI().toURL().toExternalForm();
578.106 - String rhs = null;
578.107 -
578.108 - IndexedElement fakeElement = getFakeElement(name, kind, url, rhs, null);
578.109 - String html = RstFormatter.getDocumentation(fakeElement);
578.110 -
578.111 - assertDescriptionMatches(testFile, "<html><body>" + html + "</body></html>", true, ".html");
578.112 - }
578.113 -
578.114 - public void formatFile(String file) throws Exception {
578.115 - if (file.endsWith(".rst")) {
578.116 - StringBuilder sb = new StringBuilder();
578.117 - sb.append("<html><body>\n"); // NOI18N
578.118 - String rst = readFile(getTestFile(file));
578.119 - sb.append(RstFormatter.document(rst));
578.120 - sb.append("</body></html>\n");
578.121 -
578.122 - assertDescriptionMatches(file, sb.toString(), false, ".html");
578.123 -
578.124 - return;
578.125 - }
578.126 -
578.127 - CompilationInfo info = getInfo(file);
578.128 -
578.129 - List<PythonTree> result = new ArrayList<PythonTree>();
578.130 - PythonTree root = PythonAstUtils.getRoot(info);
578.131 - PythonAstUtils.addNodesByType(root, new Class[] { Module.class, FunctionDef.class, ClassDef.class }, result);
578.132 -
578.133 - StringBuilder sb = new StringBuilder();
578.134 - sb.append("<html><body>\n"); // NOI18N
578.135 -
578.136 - for (PythonTree node : result) {
578.137 - PythonTree docNode = PythonAstUtils.getDocumentationNode(node);
578.138 - if (docNode != null) {
578.139 - String name = "";
578.140 - ElementKind kind = ElementKind.OTHER;
578.141 - List<String> parameters = null;
578.142 - if (node instanceof FunctionDef) {
578.143 - kind = ElementKind.METHOD;
578.144 - FunctionDef func = (FunctionDef)node;
578.145 - name = func.getInternalName();
578.146 - parameters = PythonAstUtils.getParameters(func);
578.147 - } else if (node instanceof Module) {
578.148 - name = info.getFileObject().getNameExt();
578.149 - kind = ElementKind.MODULE;
578.150 - } else if (node instanceof ClassDef) {
578.151 - kind = ElementKind.CLASS;
578.152 - name = ((ClassDef)node).getInternalName();
578.153 - }
578.154 - String url = FileUtil.toFile(info.getFileObject()).toURI().toURL().toExternalForm();
578.155 - String rhs = null;
578.156 -
578.157 - IndexedElement fakeElement = getFakeElement(name, kind, url, rhs, parameters);
578.158 -
578.159 - String s = RstFormatter.document(info, node, fakeElement);
578.160 - if (s != null && s.length() > 0) {
578.161 - sb.append("<h2 style=\"color: green\">Next Comment</h2>\n"); // NOI18N
578.162 - sb.append(s);
578.163 - }
578.164 - }
578.165 - }
578.166 - sb.append("</body></html>\n");
578.167 -
578.168 - assertDescriptionMatches(file, sb.toString(), false, ".html");
578.169 - }
578.170 -
578.171 - public void testExtract1() throws Exception {
578.172 - RstFormatter formatter = new RstFormatter();
578.173 - BaseDocument doc = getDocument(getTestFile("testfiles/rst/stdtypes.rst"));
578.174 - String rst = formatter.extractRst("dict", null, ElementKind.CLASS, doc, null);
578.175 - assertTrue(rst, rst.trim().startsWith("Return a new dictionary initialized from "));
578.176 - }
578.177 -
578.178 - public void testExtract2() throws Exception {
578.179 - RstFormatter formatter = new RstFormatter();
578.180 - BaseDocument doc = getDocument(getTestFile("testfiles/rst/stdtypes.rst"));
578.181 - String rst = formatter.extractRst("hex", null, ElementKind.METHOD, doc, null);
578.182 - assertTrue(rst, rst.trim().startsWith("Return a representation of a floating-point number as a hexadecimal"));
578.183 - }
578.184 -
578.185 - public void testExtract3() throws Exception {
578.186 - RstFormatter formatter = new RstFormatter();
578.187 - BaseDocument doc = getDocument(getTestFile("testfiles/rst/stdtypes.rst"));
578.188 - String rst = formatter.extractRst("encoding", null, ElementKind.ATTRIBUTE, doc, null);
578.189 - assertTrue(rst, rst.trim().startsWith("The encoding that this file uses. When Unicode strings are written to a file,"));
578.190 - }
578.191 -
578.192 - public void testExtract4() throws Exception {
578.193 - RstFormatter formatter = new RstFormatter();
578.194 - BaseDocument doc = getDocument(getTestFile("testfiles/rst/platform.rst"));
578.195 - String[] signatureHolder = new String[1];
578.196 - String rst = formatter.extractRst("machine", null, ElementKind.METHOD, doc, signatureHolder);
578.197 - assertTrue(rst, rst.trim().startsWith("Returns the machine type, e.g"));
578.198 - assertEquals("machine()", signatureHolder[0]);
578.199 - }
578.200 -
578.201 - public void testExtract5() throws Exception {
578.202 - RstFormatter formatter = new RstFormatter();
578.203 - BaseDocument doc = getDocument(getTestFile("testfiles/rst/zipfile.rst"));
578.204 - String rst = formatter.extractRst("ZIP_STORED", null, ElementKind.ATTRIBUTE, doc, null);
578.205 - assertTrue(rst, rst.trim().startsWith("The numeric constant for an uncompressed archive membe"));
578.206 - }
578.207 -
578.208 - public void testExtract6() throws Exception {
578.209 - RstFormatter formatter = new RstFormatter();
578.210 - BaseDocument doc = getDocument(getTestFile("testfiles/rst/zipfile.rst"));
578.211 - String rst = formatter.extractRst("zipfile", null, ElementKind.MODULE, doc, null);
578.212 - assertTrue(rst, rst.trim().startsWith(":synopsis: Read and write ZIP-format archive files"));
578.213 - }
578.214 -
578.215 - public void testFormatBig1() throws Exception {
578.216 - formatFile("testfiles/ConfigParser.py");
578.217 - }
578.218 -
578.219 - public void testRawStringDoc() throws Exception {
578.220 - formatFile("testfiles/rawstringdoc.py");
578.221 - }
578.222 -
578.223 - public void testGetDoc1() throws Exception {
578.224 - checkDocumentation("testfiles/rst/zipfile.rst", "ZIP_STORED", ElementKind.ATTRIBUTE);
578.225 - }
578.226 -
578.227 - public void testGetDoc2() throws Exception {
578.228 - checkDocumentation("testfiles/rst/stdtypes.rst", "dict", ElementKind.CLASS);
578.229 - }
578.230 -
578.231 - public void testGetDoc3() throws Exception {
578.232 - checkDocumentation("testfiles/rst/zipfile.rst", "write", ElementKind.METHOD);
578.233 - }
578.234 -
578.235 - public void testGetDoc4() throws Exception {
578.236 - checkDocumentation("testfiles/rst/stdtypes.rst", "close", ElementKind.METHOD);
578.237 - }
578.238 -
578.239 - public void testGetDoc5() throws Exception {
578.240 - checkDocumentation("testfiles/rst/operator.rst", "__delitem__", ElementKind.METHOD);
578.241 - }
578.242 -
578.243 - public void testFormatAll1() throws Exception {
578.244 - formatFile("testfiles/rst/string.rst");
578.245 - }
578.246 -
578.247 - public void testFormatAll2() throws Exception {
578.248 - formatFile("testfiles/rst/stdtypes.rst");
578.249 - }
578.250 -
578.251 - public void testFormatAll3() throws Exception {
578.252 - formatFile("testfiles/rst/zipfile.rst");
578.253 - }
578.254 -
578.255 - public void testFormatAll4() throws Exception {
578.256 - formatFile("testfiles/rst/platform.rst");
578.257 - }
578.258 -
578.259 - public void testFormatAll5() throws Exception {
578.260 - formatFile("testfiles/rst/smtpd.rst");
578.261 - }
578.262 -
578.263 - public void testFormatAll6() throws Exception {
578.264 - formatFile("testfiles/rst/stub_missing.rst");
578.265 - }
578.266 -}
579.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/codecoverage/CodeCoverageTestHelper.java Sun Jan 04 13:11:53 2015 -0600
579.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
579.3 @@ -1,89 +0,0 @@
579.4 -package org.netbeans.modules.python.editor.codecoverage;
579.5 -
579.6 -import org.netbeans.api.project.Project;
579.7 -import org.netbeans.api.project.ProjectManager;
579.8 -import org.netbeans.editor.BaseDocument;
579.9 -import org.netbeans.editor.Utilities;
579.10 -import org.netbeans.modules.gsf.GsfTestBase;
579.11 -import org.netbeans.modules.gsf.codecoverage.api.CoverageProvider;
579.12 -import org.netbeans.modules.gsf.codecoverage.api.CoverageType;
579.13 -import org.netbeans.modules.gsf.codecoverage.api.FileCoverageDetails;
579.14 -import org.openide.filesystems.FileObject;
579.15 -import org.openide.xml.XMLUtil;
579.16 -
579.17 -public class CodeCoverageTestHelper {
579.18 - public static String annotateCoverage(CoverageProvider provider, FileObject fo, FileCoverageDetails details, BaseDocument doc) throws Exception {
579.19 - StringBuilder sb = new StringBuilder();
579.20 -
579.21 - sb.append("<html>\n");
579.22 - sb.append("<head>\n");
579.23 - sb.append("<style>\n");
579.24 - sb.append("div { white-space: pre; font-family: monospace; margin: 0px; padding: 0px }\n");
579.25 - sb.append(".covered { background-color: CCFFCC }\n");
579.26 - sb.append(".partial { background-color: FFFFCC }\n");
579.27 - sb.append(".not_covered { background-color: FFCCCC }\n");
579.28 - sb.append(".inferred { background-color: E0FFE0 }\n");
579.29 - sb.append(".unknown { background-color: EEEEEE }\n");
579.30 - sb.append("</style>\n");
579.31 - sb.append("</head>\n");
579.32 - sb.append("<body>\n<h1>File Coverage for ");
579.33 - sb.append(fo.getNameExt());
579.34 - sb.append("</h1>\n");
579.35 - int offset = 0;
579.36 - int lineno = 0;
579.37 - int maxLines = details.getLineCount();
579.38 - while (offset < doc.getLength() && lineno < maxLines) {
579.39 - CoverageType type = details.getType(lineno);
579.40 - String line = doc.getText(offset, Utilities.getRowEnd(doc, offset) - offset);
579.41 - sb.append("<div class=\"");
579.42 - switch (type) {
579.43 - case COVERED:
579.44 - sb.append("covered");
579.45 - break;
579.46 - case UNKNOWN:
579.47 - sb.append("unknown");
579.48 - break;
579.49 - case INFERRED:
579.50 - sb.append("inferred");
579.51 - break;
579.52 - case PARTIAL:
579.53 - sb.append("partial");
579.54 - break;
579.55 - case NOT_COVERED:
579.56 - sb.append("not_covered");
579.57 - break;
579.58 - }
579.59 - sb.append("\">");
579.60 - sb.append(XMLUtil.toElementContent(line));
579.61 - sb.append("</div>\n");
579.62 -
579.63 - offset = Utilities.getRowEnd(doc, offset) + 1;
579.64 - lineno++;
579.65 - }
579.66 -
579.67 - sb.append("\n</body></html>\n");
579.68 -
579.69 - return sb.toString();
579.70 - }
579.71 -
579.72 - public static void checkCoverage(GsfTestBase test, String projectPath, String exeFile) throws Exception {
579.73 - FileObject projectDir = test.getTestFile(projectPath);
579.74 - GsfTestBase.assertNotNull(projectDir);
579.75 - String relFilePath = projectPath + "/" + exeFile; // NOI18N
579.76 - FileObject fo = test.getTestFile(relFilePath);
579.77 - GsfTestBase.assertNotNull(fo);
579.78 - BaseDocument doc = test.getDocument(fo);
579.79 - GsfTestBase.assertNotNull(doc);
579.80 -
579.81 - Project project = ProjectManager.getDefault().findProject(projectDir);
579.82 - GsfTestBase.assertNotNull(project);
579.83 - CoverageProvider provider = project.getLookup().lookup(CoverageProvider.class);
579.84 - GsfTestBase.assertNotNull(provider);
579.85 - GsfTestBase.assertTrue(provider.isEnabled());
579.86 - FileCoverageDetails details = provider.getDetails(fo, doc);
579.87 -
579.88 - String annotatedSource = annotateCoverage(provider, fo, details, doc);
579.89 - test.assertDescriptionMatches(relFilePath, annotatedSource, false, ".coverage.html");
579.90 - }
579.91 -}
579.92 -
580.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/codecoverage/PythonCoverageProviderTest.java Sun Jan 04 13:11:53 2015 -0600
580.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
580.3 @@ -1,134 +0,0 @@
580.4 -/*
580.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
580.6 - *
580.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
580.8 - *
580.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
580.10 - * Other names may be trademarks of their respective owners.
580.11 - *
580.12 - * The contents of this file are subject to the terms of either the GNU
580.13 - * General Public License Version 2 only ("GPL") or the Common
580.14 - * Development and Distribution License("CDDL") (collectively, the
580.15 - * "License"). You may not use this file except in compliance with the
580.16 - * License. You can obtain a copy of the License at
580.17 - * http://www.netbeans.org/cddl-gplv2.html
580.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
580.19 - * specific language governing permissions and limitations under the
580.20 - * License. When distributing the software, include this License Header
580.21 - * Notice in each file and include the License file at
580.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
580.23 - * particular file as subject to the "Classpath" exception as provided
580.24 - * by Oracle in the GPL Version 2 section of the License file that
580.25 - * accompanied this code. If applicable, add the following below the
580.26 - * License Header, with the fields enclosed by brackets [] replaced by
580.27 - * your own identifying information:
580.28 - * "Portions Copyrighted [year] [name of copyright owner]"
580.29 - *
580.30 - * If you wish your version of this file to be governed by only the CDDL
580.31 - * or only the GPL Version 2, indicate your decision by adding
580.32 - * "[Contributor] elects to include this software in this distribution
580.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
580.34 - * single choice of license, a recipient has the option to distribute
580.35 - * your version of this file under either the CDDL, the GPL Version 2 or
580.36 - * to extend the choice of license to its licensees as provided above.
580.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
580.38 - * Version 2 license, then the option applies only if the new code is
580.39 - * made subject to such option by the copyright holder.
580.40 - *
580.41 - * Contributor(s):
580.42 - *
580.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
580.44 - */
580.45 -package org.netbeans.modules.python.editor.codecoverage;
580.46 -
580.47 -import java.util.concurrent.Future;
580.48 -import org.netbeans.api.project.Project;
580.49 -import org.netbeans.editor.BaseDocument;
580.50 -import org.netbeans.modules.python.api.PythonExecution;
580.51 -import org.netbeans.modules.python.api.PythonPlatform;
580.52 -import org.netbeans.modules.python.api.PythonPlatformManager;
580.53 -import org.netbeans.modules.python.editor.PythonTestBase;
580.54 -import org.openide.filesystems.FileObject;
580.55 -import org.openide.filesystems.FileUtil;
580.56 -
580.57 -/**
580.58 - *
580.59 - * @author Tor Norbye
580.60 - */
580.61 -public class PythonCoverageProviderTest extends PythonTestBase {
580.62 - public PythonCoverageProviderTest(String name) {
580.63 - super(name);
580.64 - }
580.65 -
580.66 - private void recordCoverage(String projectPath, String exeFile) throws Exception {
580.67 - Project project = getTestProject(projectPath);
580.68 - assertNotNull(project);
580.69 - PythonCoverageProvider provider = PythonCoverageProvider.get(project);
580.70 - assertNotNull(provider);
580.71 -
580.72 - provider.setEnabled(true);
580.73 -
580.74 - String relFilePath = projectPath + "/" + exeFile; // NOI18N
580.75 - FileObject fo = getTestFile(relFilePath);
580.76 - assertNotNull(fo);
580.77 - BaseDocument doc = getDocument(fo);
580.78 - assertNotNull(doc);
580.79 -
580.80 - String script = FileUtil.toFile(fo).getAbsolutePath();
580.81 - PythonExecution pyexec = new PythonExecution();
580.82 - pyexec.setDisplayName(fo.getName());
580.83 - String path = FileUtil.toFile(project.getProjectDirectory()).getAbsolutePath();
580.84 - pyexec.setWorkingDirectory(path);
580.85 - PythonPlatformManager manager = PythonPlatformManager.getInstance();
580.86 - PythonPlatform platform = manager.getPlatform(manager.getDefaultPlatform());
580.87 - pyexec.setCommand(platform.getInterpreterCommand());
580.88 - pyexec.setScript(script);
580.89 - pyexec.setCommandArgs(platform.getInterpreterArgs());
580.90 - pyexec.setShowControls(false);
580.91 - pyexec.setShowInput(false);
580.92 - pyexec.setShowWindow(false);
580.93 - pyexec.addStandardRecognizers();
580.94 -
580.95 - pyexec = provider.wrapWithCoverage(pyexec);
580.96 - Future<Integer> run = pyexec.run();
580.97 - run.get();
580.98 - }
580.99 -
580.100 - private void checkCoverage(String projectPath, String exeFile) throws Exception {
580.101 - checkCoverage(projectPath, exeFile, exeFile);
580.102 - }
580.103 -
580.104 - private void checkCoverage(String projectPath, String exeFile, String checkFile) throws Exception {
580.105 - recordCoverage(projectPath, exeFile);
580.106 - // TODO - assert that we have coverage data run at this point... might be delayed..
580.107 - // Perhaps add a little delay
580.108 - try {
580.109 - Thread.sleep(1000);
580.110 - } catch (InterruptedException ire) {
580.111 - fail();
580.112 - }
580.113 -
580.114 - CodeCoverageTestHelper.checkCoverage(this, projectPath, checkFile);
580.115 - }
580.116 -
580.117 - public void testCoverage1() throws Exception {
580.118 - checkCoverage("testfiles/codecoverage/CoveragePrj", "src/coverageprj.py");
580.119 - }
580.120 -
580.121 - public void testCoverage2() throws Exception {
580.122 - checkCoverage("testfiles/codecoverage/CoveragePrj", "src/md5driver.py");
580.123 - }
580.124 -
580.125 - public void testCoverage3() throws Exception {
580.126 - checkCoverage("testfiles/codecoverage/CoveragePrj", "src/coverageprj2.py");
580.127 - }
580.128 -
580.129 - public void testCoverage4() throws Exception {
580.130 - checkCoverage("testfiles/codecoverage/CoveragePrj", "src/coverageprj3.py");
580.131 - }
580.132 -
580.133 - public void testCoverage5() throws Exception {
580.134 - checkCoverage("testfiles/codecoverage/CoveragePrj2", "src/romantest9.py", "src/roman9.py");
580.135 - }
580.136 -
580.137 -}
581.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/elements/IndexedElementTest.java Sun Jan 04 13:11:53 2015 -0600
581.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
581.3 @@ -1,473 +0,0 @@
581.4 -/*
581.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
581.6 - *
581.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
581.8 - *
581.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
581.10 - * Other names may be trademarks of their respective owners.
581.11 - *
581.12 - * The contents of this file are subject to the terms of either the GNU
581.13 - * General Public License Version 2 only ("GPL") or the Common
581.14 - * Development and Distribution License("CDDL") (collectively, the
581.15 - * "License"). You may not use this file except in compliance with the
581.16 - * License. You can obtain a copy of the License at
581.17 - * http://www.netbeans.org/cddl-gplv2.html
581.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
581.19 - * specific language governing permissions and limitations under the
581.20 - * License. When distributing the software, include this License Header
581.21 - * Notice in each file and include the License file at
581.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
581.23 - * particular file as subject to the "Classpath" exception as provided
581.24 - * by Oracle in the GPL Version 2 section of the License file that
581.25 - * accompanied this code. If applicable, add the following below the
581.26 - * License Header, with the fields enclosed by brackets [] replaced by
581.27 - * your own identifying information:
581.28 - * "Portions Copyrighted [year] [name of copyright owner]"
581.29 - *
581.30 - * If you wish your version of this file to be governed by only the CDDL
581.31 - * or only the GPL Version 2, indicate your decision by adding
581.32 - * "[Contributor] elects to include this software in this distribution
581.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
581.34 - * single choice of license, a recipient has the option to distribute
581.35 - * your version of this file under either the CDDL, the GPL Version 2 or
581.36 - * to extend the choice of license to its licensees as provided above.
581.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
581.38 - * Version 2 license, then the option applies only if the new code is
581.39 - * made subject to such option by the copyright holder.
581.40 - *
581.41 - * Contributor(s):
581.42 - *
581.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
581.44 - */
581.45 -
581.46 -package org.netbeans.modules.python.editor.elements;
581.47 -
581.48 -import java.net.URL;
581.49 -import java.util.List;
581.50 -import org.netbeans.modules.gsf.api.CompilationInfo;
581.51 -import org.netbeans.modules.gsf.api.Index.SearchResult;
581.52 -import org.netbeans.modules.python.editor.PythonAstUtils;
581.53 -import org.netbeans.modules.python.editor.PythonIndexer;
581.54 -import org.netbeans.modules.python.editor.PythonTestBase;
581.55 -import org.netbeans.modules.python.editor.RstFormatter;
581.56 -import org.python.antlr.PythonTree;
581.57 -
581.58 -/**
581.59 - *
581.60 - * @author Tor Norbye
581.61 - */
581.62 -public class IndexedElementTest extends PythonTestBase {
581.63 -
581.64 - public IndexedElementTest(String name) {
581.65 - super(name);
581.66 - }
581.67 -
581.68 - @Override
581.69 - protected List<URL> getExtraCpUrls() {
581.70 - // I'm overriding various Jython classes here for tests which causes
581.71 - // confusion when it's trying to locate classes and finds it in multiple places
581.72 -// if (!skipJython) {
581.73 -// return super.getExtraCpUrls();
581.74 -// }
581.75 -
581.76 - return null;
581.77 - }
581.78 -
581.79 - public void checkCreate(String testFile) throws Exception {
581.80 - List<SearchResult> maps;
581.81 - if (testFile.endsWith(".indexed")) {
581.82 - maps = createTestMapsFromIndexFile(getTestFile(testFile));
581.83 - } else {
581.84 - maps = createTestMaps(getTestFile(testFile));
581.85 - }
581.86 -
581.87 -// PythonIndex pythonIndex = PythonIndex.get(null, null);
581.88 -
581.89 - int mapNo = -1;
581.90 - for (SearchResult map : maps) {
581.91 - mapNo++;
581.92 -
581.93 - //if (mapNo < 1853) {
581.94 - // continue;
581.95 - //}
581.96 -
581.97 - String url = map.getPersistentUrl();
581.98 - assertNotNull(url);
581.99 -
581.100 -// String clz = map.getValue("class");
581.101 -// if (clz != null) {
581.102 -// String fqn = map.getValue("fqn");
581.103 -// String attrs = map.getValue("clzattrs");
581.104 -//
581.105 -// String originalAttrs = attrs;
581.106 -// if (attrs != null) {
581.107 -// int flags = IndexedElement.stringToFlags(attrs);
581.108 -// if (flags != 0) {
581.109 -// int begin = attrs.indexOf("|");
581.110 -// assertTrue(begin != -1);
581.111 -// int end = attrs.indexOf(';', begin);
581.112 -// if (end == -1) {
581.113 -// end = attrs.length();
581.114 -// }
581.115 -// attrs = attrs.substring(0, begin) + IndexedElement.encode(flags) + attrs.substring(end);
581.116 -// ((TestSearchResult)map).setValue("attrs", attrs);
581.117 -//
581.118 -// }
581.119 -// }
581.120 -//
581.121 -// IndexedClass cm = rubyIndex.createClass(fqn, clz, map);
581.122 -//
581.123 -// if (originalAttrs != null) {
581.124 -// if (originalAttrs.indexOf("|STATIC") != -1) {
581.125 -// assertTrue(fqn+";"+originalAttrs, cm.isStatic());
581.126 -// }
581.127 -// if (originalAttrs.indexOf("|NODOC") != -1) {
581.128 -// assertTrue(fqn+";"+originalAttrs, cm.isNoDoc());
581.129 -// }
581.130 -// if (originalAttrs.indexOf("|TOP_LEVEL") != -1) {
581.131 -// assertTrue(fqn+";"+originalAttrs, cm.isTopLevel());
581.132 -// }
581.133 -// if (originalAttrs.indexOf("|DOCUMENTED") != -1) {
581.134 -// assertTrue(fqn+";"+originalAttrs, cm.isDocumented());
581.135 -// }
581.136 -// if (originalAttrs.indexOf("|PRIVATE") != -1) {
581.137 -// assertTrue(fqn+";"+originalAttrs, cm.isPrivate());
581.138 -// }
581.139 -// if (originalAttrs.indexOf("|PROTECTED") != -1) {
581.140 -// assertTrue(fqn+";"+originalAttrs, cm.isProtected());
581.141 -// }
581.142 -// }
581.143 -//
581.144 -// boolean skip = false;
581.145 -// // Skip known problems
581.146 -// skip = !Character.isUpperCase(cm.getName().charAt(0));
581.147 -// if (url.endsWith("/action_controller.rb") || url.endsWith("/active_record.rb") || url.endsWith("/action_mailer.rb") || url.endsWith("/action_view.rb")) {
581.148 -// // These classes are faked up by RubyIndexer
581.149 -// skip = true;
581.150 -// }
581.151 -// if (fqn.equals("Object")) {
581.152 -// // Top level methods may not specify Object
581.153 -// skip = true;
581.154 -// }
581.155 -//
581.156 -// if (!skip) {
581.157 -// assertEquals(url, cm.getFileUrl());
581.158 -// assertNotNull(cm.getFileUrl(), cm.getFileObject());
581.159 -// CompilationInfo[] compilationInfoHolder = new CompilationInfo[1];
581.160 -// PythonTree node = AstUtilities.getForeignNode(cm, compilationInfoHolder);
581.161 -// assertNotNull("Map " + mapNo + ", url=" + url + ":" + fqn, node);
581.162 -// } // else: Lots of problems with lowerclass class names - comes from anonymous classes assigned to variables
581.163 -// }
581.164 -
581.165 - String[] methods = map.getValues("member");
581.166 - if (methods != null) {
581.167 - //System.err.println("Checking url " + url + ", " + methods.length + " methods");
581.168 - int methodCount = -1;
581.169 - for (String signature : methods) {
581.170 - methodCount++;
581.171 - //String methodName = signature.substring(0, signature.indexOf('('));
581.172 - String originalSignature = signature;
581.173 - int flags = IndexedMethod.stringToFlags(signature);
581.174 - if (flags != 0) {
581.175 - int begin = signature.indexOf("|",1); //1: "|" is a valid method name
581.176 - assertTrue(begin != -1);
581.177 - int end = signature.indexOf(';', begin);
581.178 - if (end == -1) {
581.179 - end = signature.length();
581.180 - }
581.181 - signature = signature.substring(0, begin) + IndexedElement.encode(flags) + signature.substring(end);
581.182 - }
581.183 -
581.184 - String clz = map.getValue(PythonIndexer.FIELD_CLASS_NAME);
581.185 - String module = map.getValue(PythonIndexer.FIELD_IN);
581.186 - IndexedElement method = IndexedElement.create(signature, module, url, clz);
581.187 -
581.188 - assertEquals(url, method.getFilenameUrl());
581.189 -
581.190 - if (originalSignature.indexOf("|STATIC") != -1) {
581.191 - assertTrue(originalSignature, method.isStatic());
581.192 - }
581.193 - if (originalSignature.indexOf("|DEPRECATED") != -1) {
581.194 - assertTrue(originalSignature, method.isDeprecated());
581.195 - }
581.196 - if (originalSignature.indexOf("|NODOC") != -1) {
581.197 - assertTrue(originalSignature, method.isNoDoc());
581.198 - }
581.199 -// if (originalSignature.indexOf("|BLOCK_OPTIONAL") != -1) {
581.200 -// assertTrue(originalSignature, method.isBlockOptional());
581.201 -// }
581.202 -// if (originalSignature.indexOf("|TOP_LEVEL") != -1) {
581.203 -// assertTrue(originalSignature, method.isTopLevel());
581.204 -// }
581.205 - if (originalSignature.indexOf("|DOCUMENTED") != -1) {
581.206 - assertTrue(originalSignature, method.isDocumented());
581.207 - }
581.208 - if (originalSignature.indexOf("|PRIVATE") != -1) {
581.209 - assertTrue(originalSignature, method.isPrivate());
581.210 - }
581.211 -// if (originalSignature.indexOf("|PROTECTED") != -1) {
581.212 -// assertTrue(originalSignature, method.isProtected());
581.213 -// }
581.214 -
581.215 -// // Known exceptions
581.216 -// if (url.endsWith("/schema_definitions.rb")) {
581.217 -// // These are generated dynamically, no actual AST node
581.218 -// continue;
581.219 -// }
581.220 -// // The bug here is that there is a sessions_key local variable we store
581.221 -// // a class on -- but this isn't a class named session_key!!
581.222 -// // Too late to mess with that now
581.223 -// if (url.endsWith("/scenario_runner.rb")) {
581.224 -// continue;
581.225 -// }
581.226 -// if (url.endsWith("/drb_server.rb")) {
581.227 -// continue;
581.228 -// }
581.229 -// if (url.endsWith("/set.rb")) {
581.230 -// // Another innerclass
581.231 -// continue;
581.232 -// }
581.233 -// if (url.endsWith("/testrunner.rb")) {
581.234 -// // Another innerclass
581.235 -// continue;
581.236 -// }
581.237 -// if (signature.indexOf("hyphenate_to") != -1) {
581.238 -// continue;
581.239 -// }
581.240 -
581.241 - assertNotNull(method.getFilenameUrl(), method.getFileObject());
581.242 - if (method.isDocumented()) {
581.243 - String doc = RstFormatter.getDocumentation(method);
581.244 - //CompilationInfo[] compilationInfoHolder = new CompilationInfo[1];
581.245 - //PythonTree node = PythonAstUtils.getForeignNode(method, compilationInfoHolder);
581.246 - //assertNotNull("Map " + mapNo + ":" + methodCount + ", url=" + url + ":" + signature + "; " + method.getSignature(), node);
581.247 - assertTrue(method.attributes, doc != null && doc.length() > 0);
581.248 - }
581.249 - if (method.isDocOnly()) {
581.250 - assertTrue(method.getFilenameUrl().indexOf(".rst") != -1);
581.251 - }
581.252 - if (!method.getFilenameUrl().endsWith(".rst")) {
581.253 - CompilationInfo[] compilationInfoHolder = new CompilationInfo[1];
581.254 - PythonTree node = PythonAstUtils.getForeignNode(method, compilationInfoHolder);
581.255 - assertNotNull("Map " + mapNo + ":" + methodCount + ", url=" + url + ":" + signature + "; " + method.getSignature(), node);
581.256 - }
581.257 - }
581.258 - }
581.259 -
581.260 - String[] items = map.getValues("items");
581.261 - if (items != null) {
581.262 - //System.err.println("Checking url " + url + ", " + items.length + " methods");
581.263 - int methodCount = -1;
581.264 - for (String signature : items) {
581.265 - methodCount++;
581.266 - String originalSignature = signature;
581.267 - int flags = IndexedMethod.stringToFlags(signature);
581.268 - if (flags != 0) {
581.269 - int begin = signature.indexOf("|",1); //1: "|" is a valid method name
581.270 - assertTrue(begin != -1);
581.271 - int end = signature.indexOf(';', begin);
581.272 - if (end == -1) {
581.273 - end = signature.length();
581.274 - }
581.275 - signature = signature.substring(0, begin) + IndexedElement.encode(flags) + signature.substring(end);
581.276 - }
581.277 -
581.278 - String module = map.getValue(PythonIndexer.FIELD_MODULE_NAME);
581.279 - IndexedElement method = IndexedElement.create(signature, module, url, null);
581.280 -
581.281 - assertEquals(url, method.getFilenameUrl());
581.282 -
581.283 - if (originalSignature.indexOf("|STATIC") != -1) {
581.284 - assertTrue(originalSignature, method.isStatic());
581.285 - }
581.286 - if (originalSignature.indexOf("|DEPRECATED") != -1) {
581.287 - assertTrue(originalSignature, method.isDeprecated());
581.288 - }
581.289 - if (originalSignature.indexOf("|NODOC") != -1) {
581.290 - assertTrue(originalSignature, method.isNoDoc());
581.291 - }
581.292 -// if (originalSignature.indexOf("|BLOCK_OPTIONAL") != -1) {
581.293 -// assertTrue(originalSignature, method.isBlockOptional());
581.294 -// }
581.295 -// if (originalSignature.indexOf("|TOP_LEVEL") != -1) {
581.296 -// assertTrue(originalSignature, method.isTopLevel());
581.297 -// }
581.298 - if (originalSignature.indexOf("|DOCUMENTED") != -1) {
581.299 - assertTrue(originalSignature, method.isDocumented());
581.300 - }
581.301 - if (originalSignature.indexOf("|PRIVATE") != -1) {
581.302 - assertTrue(originalSignature, method.isPrivate());
581.303 - }
581.304 -// if (originalSignature.indexOf("|PROTECTED") != -1) {
581.305 -// assertTrue(originalSignature, method.isProtected());
581.306 -// }
581.307 -
581.308 -// // Known exceptions
581.309 -// if (url.endsWith("/schema_definitions.rb")) {
581.310 -// // These are generated dynamically, no actual AST node
581.311 -// continue;
581.312 -// }
581.313 -// // The bug here is that there is a sessions_key local variable we store
581.314 -// // a class on -- but this isn't a class named session_key!!
581.315 -// // Too late to mess with that now
581.316 -// if (url.endsWith("/scenario_runner.rb")) {
581.317 -// continue;
581.318 -// }
581.319 -// if (url.endsWith("/drb_server.rb")) {
581.320 -// continue;
581.321 -// }
581.322 -// if (url.endsWith("/set.rb")) {
581.323 -// // Another innerclass
581.324 -// continue;
581.325 -// }
581.326 -// if (url.endsWith("/testrunner.rb")) {
581.327 -// // Another innerclass
581.328 -// continue;
581.329 -// }
581.330 -// if (signature.indexOf("hyphenate_to") != -1) {
581.331 -// continue;
581.332 -// }
581.333 -
581.334 - assertNotNull(method.getFilenameUrl(), method.getFileObject());
581.335 - if (method.isDocumented()) {
581.336 - String doc = RstFormatter.getDocumentation(method);
581.337 - assertTrue(doc != null && doc.length() > 0);
581.338 - }
581.339 - if (method.isDocOnly()) {
581.340 - assertTrue(method.getFilenameUrl().indexOf(".rst") != -1);
581.341 - }
581.342 -
581.343 - if (!method.getFilenameUrl().endsWith(".rst")) {
581.344 - CompilationInfo[] compilationInfoHolder = new CompilationInfo[1];
581.345 - PythonTree node = PythonAstUtils.getForeignNode(method, compilationInfoHolder);
581.346 - assertNotNull("Map " + mapNo + ":" + methodCount + ", url=" + url + ":" + signature + "; " + method.getSignature(), node);
581.347 - }
581.348 - }
581.349 - }
581.350 -
581.351 - }
581.352 - }
581.353 -
581.354 - public void testIndex1() throws Exception {
581.355 - checkCreate("testfiles/ConfigParser.py.indexed");
581.356 - }
581.357 -
581.358 - public void testIndex2() throws Exception {
581.359 - checkCreate("testfiles/datetime.py.indexed");
581.360 - }
581.361 -
581.362 - public void testIndex3() throws Exception {
581.363 - checkCreate("testfiles/doc.py.indexed");
581.364 - }
581.365 -
581.366 - public void testIndex4() throws Exception {
581.367 - checkCreate("testfiles/md5.py.indexed");
581.368 - }
581.369 -
581.370 - public void testIndex5() throws Exception {
581.371 - checkCreate("testfiles/scope.py.indexed");
581.372 - }
581.373 -
581.374 - public void testIndex6() throws Exception {
581.375 - checkCreate("testfiles/httplib.py.indexed");
581.376 - }
581.377 -
581.378 - public void testIndex7() throws Exception {
581.379 - checkCreate("testfiles/minicompat.py.indexed");
581.380 - }
581.381 -
581.382 - public void testIndex8() throws Exception {
581.383 - checkCreate("testfiles/socket.py.indexed");
581.384 - }
581.385 -
581.386 - public void testIndex9() throws Exception {
581.387 - checkCreate("testfiles/jreload.py.indexed");
581.388 - }
581.389 -
581.390 - public void testIndex10() throws Exception {
581.391 - checkCreate("testfiles/doctest.py.indexed");
581.392 - }
581.393 -
581.394 - public void testIndex11() throws Exception {
581.395 - checkCreate("testfiles/zipfile.py");
581.396 - }
581.397 -
581.398 - public void testIndex12() throws Exception {
581.399 - checkCreate("testfiles/os.py");
581.400 - }
581.401 -
581.402 - public void testIndex13() throws Exception {
581.403 - checkCreate("testfiles/unittest.py");
581.404 - }
581.405 -
581.406 - public void testIndex14() throws Exception {
581.407 - checkCreate("testfiles/properties.py");
581.408 - }
581.409 -
581.410 - public void testIndex15() throws Exception {
581.411 - checkCreate("testfiles/tarfile.py");
581.412 - }
581.413 -
581.414 - public void testIndex16() throws Exception {
581.415 - checkCreate("testfiles/rst/pickle.rst");
581.416 - }
581.417 -
581.418 - public void testRstIndex1() throws Exception {
581.419 - checkCreate("testfiles/rst/zipfile.rst.indexed");
581.420 - }
581.421 -
581.422 - // Known fail -- I'm not properly indexing the set < other and set > other stuff
581.423 - // in the stdtypes.rst file!
581.424 - //public void testRstIndex2() throws Exception {
581.425 - // checkCreate("testfiles/rst/stdtypes.rst.indexed");
581.426 - //}
581.427 -
581.428 - public void testRstIndex3() throws Exception {
581.429 - checkCreate("testfiles/rst/platform.rst.indexed");
581.430 - }
581.431 -
581.432 - public void testRstIndex4() throws Exception {
581.433 - checkCreate("testfiles/rst/smtpd.rst.indexed");
581.434 - }
581.435 -
581.436 - public void testRstIndex5() throws Exception {
581.437 - checkCreate("testfiles/rst/exceptions.rst.indexed");
581.438 - }
581.439 -
581.440 - public void testRstIndex6() throws Exception {
581.441 - checkCreate("testfiles/rst/logging.rst.indexed");
581.442 - }
581.443 -
581.444 - public void testRstIndex7() throws Exception {
581.445 - checkCreate("testfiles/rst/string.rst");
581.446 - }
581.447 -
581.448 - public void testRstIndex8() throws Exception {
581.449 - checkCreate("testfiles/rst/bz2.rst");
581.450 - }
581.451 -
581.452 - public void testRstIndex9() throws Exception {
581.453 - checkCreate("testfiles/rst/constants.rst");
581.454 - }
581.455 -
581.456 - public void testRstIndex10() throws Exception {
581.457 - checkCreate("testfiles/rst/operator.rst");
581.458 - }
581.459 -
581.460 - public void testRstIndex11() throws Exception {
581.461 - checkCreate("testfiles/rst/collections.rst");
581.462 - }
581.463 -
581.464 - public void testRstIndex12() throws Exception {
581.465 - checkCreate("testfiles/rst/ctypes.rst");
581.466 - }
581.467 -
581.468 - public void testRstIndex13() throws Exception {
581.469 - checkCreate("testfiles/rst/stub_missing.rst");
581.470 - }
581.471 -
581.472 -// public void testIndexEgg() throws Exception {
581.473 -// checkCreate("testfiles/antlr_python_runtime-3.1.1-py2.5.egg");
581.474 -// }
581.475 -
581.476 -}
582.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/AccessToProtectedTest.java Sun Jan 04 13:11:53 2015 -0600
582.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
582.3 @@ -1,64 +0,0 @@
582.4 -/*
582.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
582.6 - *
582.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
582.8 - *
582.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
582.10 - * Other names may be trademarks of their respective owners.
582.11 - *
582.12 - * The contents of this file are subject to the terms of either the GNU
582.13 - * General Public License Version 2 only ("GPL") or the Common
582.14 - * Development and Distribution License("CDDL") (collectively, the
582.15 - * "License"). You may not use this file except in compliance with the
582.16 - * License. You can obtain a copy of the License at
582.17 - * http://www.netbeans.org/cddl-gplv2.html
582.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
582.19 - * specific language governing permissions and limitations under the
582.20 - * License. When distributing the software, include this License Header
582.21 - * Notice in each file and include the License file at
582.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
582.23 - * particular file as subject to the "Classpath" exception as provided
582.24 - * by Oracle in the GPL Version 2 section of the License file that
582.25 - * accompanied this code. If applicable, add the following below the
582.26 - * License Header, with the fields enclosed by brackets [] replaced by
582.27 - * your own identifying information:
582.28 - * "Portions Copyrighted [year] [name of copyright owner]"
582.29 - *
582.30 - * If you wish your version of this file to be governed by only the CDDL
582.31 - * or only the GPL Version 2, indicate your decision by adding
582.32 - * "[Contributor] elects to include this software in this distribution
582.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
582.34 - * single choice of license, a recipient has the option to distribute
582.35 - * your version of this file under either the CDDL, the GPL Version 2 or
582.36 - * to extend the choice of license to its licensees as provided above.
582.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
582.38 - * Version 2 license, then the option applies only if the new code is
582.39 - * made subject to such option by the copyright holder.
582.40 - *
582.41 - * Contributor(s):
582.42 - *
582.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
582.44 - */
582.45 -
582.46 -package org.netbeans.modules.python.editor.hints;
582.47 -
582.48 -import org.netbeans.modules.python.editor.PythonTestBase;
582.49 -
582.50 -public class AccessToProtectedTest extends PythonTestBase {
582.51 -
582.52 - public AccessToProtectedTest(String testName) {
582.53 - super(testName);
582.54 - }
582.55 -
582.56 - private PythonAstRule createRule() {
582.57 - return new AccessToProtected();
582.58 - }
582.59 -
582.60 - public void testRegistered() throws Exception {
582.61 - ensureRegistered(createRule());
582.62 - }
582.63 -
582.64 - public void testAccessToProtected() throws Exception {
582.65 - findHints(this, createRule(), "testfiles/attributes.py", null, null);
582.66 - }
582.67 -}
583.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/AllAssignExistsTest.java Sun Jan 04 13:11:53 2015 -0600
583.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
583.3 @@ -1,72 +0,0 @@
583.4 -/*
583.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
583.6 - *
583.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
583.8 - *
583.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
583.10 - * Other names may be trademarks of their respective owners.
583.11 - *
583.12 - * The contents of this file are subject to the terms of either the GNU
583.13 - * General Public License Version 2 only ("GPL") or the Common
583.14 - * Development and Distribution License("CDDL") (collectively, the
583.15 - * "License"). You may not use this file except in compliance with the
583.16 - * License. You can obtain a copy of the License at
583.17 - * http://www.netbeans.org/cddl-gplv2.html
583.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
583.19 - * specific language governing permissions and limitations under the
583.20 - * License. When distributing the software, include this License Header
583.21 - * Notice in each file and include the License file at
583.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
583.23 - * particular file as subject to the "Classpath" exception as provided
583.24 - * by Oracle in the GPL Version 2 section of the License file that
583.25 - * accompanied this code. If applicable, add the following below the
583.26 - * License Header, with the fields enclosed by brackets [] replaced by
583.27 - * your own identifying information:
583.28 - * "Portions Copyrighted [year] [name of copyright owner]"
583.29 - *
583.30 - * If you wish your version of this file to be governed by only the CDDL
583.31 - * or only the GPL Version 2, indicate your decision by adding
583.32 - * "[Contributor] elects to include this software in this distribution
583.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
583.34 - * single choice of license, a recipient has the option to distribute
583.35 - * your version of this file under either the CDDL, the GPL Version 2 or
583.36 - * to extend the choice of license to its licensees as provided above.
583.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
583.38 - * Version 2 license, then the option applies only if the new code is
583.39 - * made subject to such option by the copyright holder.
583.40 - *
583.41 - * Contributor(s):
583.42 - *
583.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
583.44 - */
583.45 -
583.46 -package org.netbeans.modules.python.editor.hints;
583.47 -
583.48 -import org.netbeans.modules.python.editor.PythonTestBase;
583.49 -
583.50 -/**
583.51 - *
583.52 - * @author Tor Norbye
583.53 - */
583.54 -public class AllAssignExistsTest extends PythonTestBase {
583.55 -
583.56 - public AllAssignExistsTest(String testName) {
583.57 - super(testName);
583.58 - }
583.59 -
583.60 - private PythonAstRule createRule() {
583.61 - return new AllAssignExists();
583.62 - }
583.63 -
583.64 - public void testRegistered() throws Exception {
583.65 - ensureRegistered(createRule());
583.66 - }
583.67 -
583.68 - public void testAssign1() throws Exception {
583.69 - findHints(this, createRule(), "testfiles/all.py", null, null);
583.70 - }
583.71 -
583.72 - public void testAssign2() throws Exception {
583.73 - findHints(this, createRule(), "testfiles/all2.py", null, null);
583.74 - }
583.75 -}
584.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/AssignToVariableTest.java Sun Jan 04 13:11:53 2015 -0600
584.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
584.3 @@ -1,98 +0,0 @@
584.4 -/*
584.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
584.6 - *
584.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
584.8 - *
584.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
584.10 - * Other names may be trademarks of their respective owners.
584.11 - *
584.12 - * The contents of this file are subject to the terms of either the GNU
584.13 - * General Public License Version 2 only ("GPL") or the Common
584.14 - * Development and Distribution License("CDDL") (collectively, the
584.15 - * "License"). You may not use this file except in compliance with the
584.16 - * License. You can obtain a copy of the License at
584.17 - * http://www.netbeans.org/cddl-gplv2.html
584.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
584.19 - * specific language governing permissions and limitations under the
584.20 - * License. When distributing the software, include this License Header
584.21 - * Notice in each file and include the License file at
584.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
584.23 - * particular file as subject to the "Classpath" exception as provided
584.24 - * by Oracle in the GPL Version 2 section of the License file that
584.25 - * accompanied this code. If applicable, add the following below the
584.26 - * License Header, with the fields enclosed by brackets [] replaced by
584.27 - * your own identifying information:
584.28 - * "Portions Copyrighted [year] [name of copyright owner]"
584.29 - *
584.30 - * If you wish your version of this file to be governed by only the CDDL
584.31 - * or only the GPL Version 2, indicate your decision by adding
584.32 - * "[Contributor] elects to include this software in this distribution
584.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
584.34 - * single choice of license, a recipient has the option to distribute
584.35 - * your version of this file under either the CDDL, the GPL Version 2 or
584.36 - * to extend the choice of license to its licensees as provided above.
584.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
584.38 - * Version 2 license, then the option applies only if the new code is
584.39 - * made subject to such option by the copyright holder.
584.40 - *
584.41 - * Contributor(s):
584.42 - *
584.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
584.44 - */
584.45 -
584.46 -package org.netbeans.modules.python.editor.hints;
584.47 -
584.48 -import org.netbeans.modules.python.editor.PythonTestBase;
584.49 -
584.50 -/**
584.51 - *
584.52 - * @author Tor Norbye
584.53 - */
584.54 -public class AssignToVariableTest extends PythonTestBase {
584.55 -
584.56 - public AssignToVariableTest(String testName) {
584.57 - super(testName);
584.58 - }
584.59 -
584.60 - private PythonAstRule createRule() {
584.61 - return new AssignToVariable();
584.62 - }
584.63 -
584.64 - public void testRegistered() throws Exception {
584.65 - ensureRegistered(createRule());
584.66 - }
584.67 -
584.68 - public void testAssign1() throws Exception {
584.69 - findHints(this, createRule(), "testfiles/assign.py", null, "^\"foo\"");
584.70 - }
584.71 -
584.72 - public void testAssign2() throws Exception {
584.73 - findHints(this, createRule(), "testfiles/assign.py", null, "3+1^");
584.74 - }
584.75 -
584.76 - public void testAssign3() throws Exception {
584.77 - findHints(this, createRule(), "testfiles/assign.py", null, "^get_preprocess2");
584.78 - }
584.79 -
584.80 - public void testNoHint() throws Exception {
584.81 - findHints(this, createRule(), "testfiles/ConfigParser.py", null, "d = s^elf._defaults.copy()");
584.82 - }
584.83 -
584.84 - public void testNoHint2() throws Exception {
584.85 - findHints(this, createRule(), "testfiles/ConfigParser.py", null, "\"\"\"Raised when^ a section is multiply-created.");
584.86 - }
584.87 -
584.88 - public void testNoHint3() throws Exception {
584.89 - // Contains call that is not a getter
584.90 - findHints(this, createRule(), "testfiles/assign.py", null, "^preprocess1");
584.91 - }
584.92 -
584.93 - public void testNoHint4() throws Exception {
584.94 - // Don't assign docstrings
584.95 - findHints(this, createRule(), "testfiles/assign2.py", null, "^\"year -> 1");
584.96 - }
584.97 -
584.98 - public void testFixAssign() throws Exception {
584.99 - applyHint(this, createRule(), "testfiles/assign.py", "^3+1", "Assign");
584.100 - }
584.101 -}
585.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/AttributeDefinedOutsideInitTest.java Sun Jan 04 13:11:53 2015 -0600
585.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
585.3 @@ -1,64 +0,0 @@
585.4 -/*
585.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
585.6 - *
585.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
585.8 - *
585.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
585.10 - * Other names may be trademarks of their respective owners.
585.11 - *
585.12 - * The contents of this file are subject to the terms of either the GNU
585.13 - * General Public License Version 2 only ("GPL") or the Common
585.14 - * Development and Distribution License("CDDL") (collectively, the
585.15 - * "License"). You may not use this file except in compliance with the
585.16 - * License. You can obtain a copy of the License at
585.17 - * http://www.netbeans.org/cddl-gplv2.html
585.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
585.19 - * specific language governing permissions and limitations under the
585.20 - * License. When distributing the software, include this License Header
585.21 - * Notice in each file and include the License file at
585.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
585.23 - * particular file as subject to the "Classpath" exception as provided
585.24 - * by Oracle in the GPL Version 2 section of the License file that
585.25 - * accompanied this code. If applicable, add the following below the
585.26 - * License Header, with the fields enclosed by brackets [] replaced by
585.27 - * your own identifying information:
585.28 - * "Portions Copyrighted [year] [name of copyright owner]"
585.29 - *
585.30 - * If you wish your version of this file to be governed by only the CDDL
585.31 - * or only the GPL Version 2, indicate your decision by adding
585.32 - * "[Contributor] elects to include this software in this distribution
585.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
585.34 - * single choice of license, a recipient has the option to distribute
585.35 - * your version of this file under either the CDDL, the GPL Version 2 or
585.36 - * to extend the choice of license to its licensees as provided above.
585.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
585.38 - * Version 2 license, then the option applies only if the new code is
585.39 - * made subject to such option by the copyright holder.
585.40 - *
585.41 - * Contributor(s):
585.42 - *
585.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
585.44 - */
585.45 -
585.46 -package org.netbeans.modules.python.editor.hints;
585.47 -
585.48 -import org.netbeans.modules.python.editor.PythonTestBase;
585.49 -
585.50 -public class AttributeDefinedOutsideInitTest extends PythonTestBase {
585.51 -
585.52 - public AttributeDefinedOutsideInitTest(String testName) {
585.53 - super(testName);
585.54 - }
585.55 -
585.56 - private PythonAstRule createRule() {
585.57 - return new AttributeDefinedOutsideInit();
585.58 - }
585.59 -
585.60 - public void testRegistered() throws Exception {
585.61 - ensureRegistered(createRule());
585.62 - }
585.63 -
585.64 - public void testAttributeDefinedOutsideInit() throws Exception {
585.65 - findHints(this, createRule(), "testfiles/attributes.py", null, null);
585.66 - }
585.67 -}
586.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/ClassCircularRedundancyTest.java Sun Jan 04 13:11:53 2015 -0600
586.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
586.3 @@ -1,64 +0,0 @@
586.4 -/*
586.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
586.6 - *
586.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
586.8 - *
586.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
586.10 - * Other names may be trademarks of their respective owners.
586.11 - *
586.12 - * The contents of this file are subject to the terms of either the GNU
586.13 - * General Public License Version 2 only ("GPL") or the Common
586.14 - * Development and Distribution License("CDDL") (collectively, the
586.15 - * "License"). You may not use this file except in compliance with the
586.16 - * License. You can obtain a copy of the License at
586.17 - * http://www.netbeans.org/cddl-gplv2.html
586.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
586.19 - * specific language governing permissions and limitations under the
586.20 - * License. When distributing the software, include this License Header
586.21 - * Notice in each file and include the License file at
586.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
586.23 - * particular file as subject to the "Classpath" exception as provided
586.24 - * by Oracle in the GPL Version 2 section of the License file that
586.25 - * accompanied this code. If applicable, add the following below the
586.26 - * License Header, with the fields enclosed by brackets [] replaced by
586.27 - * your own identifying information:
586.28 - * "Portions Copyrighted [year] [name of copyright owner]"
586.29 - *
586.30 - * If you wish your version of this file to be governed by only the CDDL
586.31 - * or only the GPL Version 2, indicate your decision by adding
586.32 - * "[Contributor] elects to include this software in this distribution
586.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
586.34 - * single choice of license, a recipient has the option to distribute
586.35 - * your version of this file under either the CDDL, the GPL Version 2 or
586.36 - * to extend the choice of license to its licensees as provided above.
586.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
586.38 - * Version 2 license, then the option applies only if the new code is
586.39 - * made subject to such option by the copyright holder.
586.40 - *
586.41 - * Contributor(s):
586.42 - *
586.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
586.44 - */
586.45 -
586.46 -package org.netbeans.modules.python.editor.hints;
586.47 -
586.48 -import org.netbeans.modules.python.editor.PythonTestBase;
586.49 -
586.50 -public class ClassCircularRedundancyTest extends PythonTestBase {
586.51 -
586.52 - public ClassCircularRedundancyTest(String testName) {
586.53 - super(testName);
586.54 - }
586.55 -
586.56 - private PythonAstRule createRule() {
586.57 - return new ClassCircularRedundancy();
586.58 - }
586.59 -
586.60 - public void testRegistered() throws Exception {
586.61 - ensureRegistered(createRule());
586.62 - }
586.63 -
586.64 - public void testCircularRedundancy() throws Exception {
586.65 - findHints(this, createRule(), "testfiles/circularredundancy.py", null, null);
586.66 - }
586.67 -}
587.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/CreateDocStringTest.java Sun Jan 04 13:11:53 2015 -0600
587.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
587.3 @@ -1,68 +0,0 @@
587.4 -/*
587.5 - * To change this template, choose Tools | Templates
587.6 - * and open the template in the editor.
587.7 - */
587.8 -
587.9 -package org.netbeans.modules.python.editor.hints;
587.10 -
587.11 -import org.netbeans.modules.python.editor.PythonTestBase;
587.12 -
587.13 -/**
587.14 - *
587.15 - * @author Tor Norbye
587.16 - */
587.17 -public class CreateDocStringTest extends PythonTestBase {
587.18 -
587.19 - public CreateDocStringTest(String testName) {
587.20 - super(testName);
587.21 - }
587.22 -
587.23 - private PythonAstRule createRule() {
587.24 - return new CreateDocString();
587.25 - }
587.26 -
587.27 - public void testRegistered() throws Exception {
587.28 - ensureRegistered(createRule());
587.29 - }
587.30 -
587.31 - public void testHint1() throws Exception {
587.32 - findHints(this, createRule(), "testfiles/create_docstring.py", null, "def set^up");
587.33 - }
587.34 -
587.35 - public void testHint2() throws Exception {
587.36 - // There should be no matches here!
587.37 - findHints(this, createRule(), "testfiles/create_docstring.py", null, "a^lready");
587.38 - }
587.39 -
587.40 - public void testHint3() throws Exception {
587.41 - findHints(this, createRule(), "testfiles/create_docstring.py", null, "Datagram^RequestHandler");
587.42 - }
587.43 -
587.44 - public void testFix1() throws Exception {
587.45 - applyHint(this, createRule(), "testfiles/create_docstring.py", "def set^up", "one");
587.46 - }
587.47 -
587.48 - public void testFix2() throws Exception {
587.49 - applyHint(this, createRule(), "testfiles/create_docstring.py", "def set^up", "multi");
587.50 - }
587.51 -
587.52 - public void testFix3() throws Exception {
587.53 - applyHint(this, createRule(), "testfiles/create_docstring.py", "Datagram^RequestHandler", "one");
587.54 - }
587.55 -
587.56 - public void testFix4() throws Exception {
587.57 - applyHint(this, createRule(), "testfiles/create_docstring.py", "Datagram^RequestHandler", "multi");
587.58 - }
587.59 -
587.60 - public void testFix5() throws Exception {
587.61 - applyHint(this, createRule(), "testfiles/create_docstring2.py", "def fa^", "one");
587.62 - }
587.63 -
587.64 - public void testFix6() throws Exception {
587.65 - applyHint(this, createRule(), "testfiles/create_docstring3.py", "def fa^", "one");
587.66 - }
587.67 -
587.68 - public void testFix7() throws Exception {
587.69 - applyHint(this, createRule(), "testfiles/create_docstring4.py", "def sec^", "one");
587.70 - }
587.71 -}
588.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/DeprecationsTest.java Sun Jan 04 13:11:53 2015 -0600
588.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
588.3 @@ -1,35 +0,0 @@
588.4 -/*
588.5 - * To change this template, choose Tools | Templates
588.6 - * and open the template in the editor.
588.7 - */
588.8 -
588.9 -package org.netbeans.modules.python.editor.hints;
588.10 -
588.11 -import org.netbeans.modules.python.editor.PythonTestBase;
588.12 -
588.13 -/**
588.14 - *
588.15 - * @author Tor Norbye
588.16 - */
588.17 -public class DeprecationsTest extends PythonTestBase {
588.18 -
588.19 - public DeprecationsTest(String testName) {
588.20 - super(testName);
588.21 - }
588.22 -
588.23 - private PythonAstRule createRule() {
588.24 - return new Deprecations();
588.25 - }
588.26 -
588.27 - public void testRegistered() throws Exception {
588.28 - ensureRegistered(createRule());
588.29 - }
588.30 -
588.31 - public void testNoHints() throws Exception {
588.32 - findHints(this, createRule(), "testfiles/test_scope.py", null, null);
588.33 - }
588.34 -
588.35 - public void testDeprecations() throws Exception {
588.36 - findHints(this, createRule(), "testfiles/deprecated-imports.py", null, null);
588.37 - }
588.38 -}
589.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/ExtractCodeTest.java Sun Jan 04 13:11:53 2015 -0600
589.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
589.3 @@ -1,104 +0,0 @@
589.4 -/*
589.5 - * To change this template, choose Tools | Templates
589.6 - * and open the template in the editor.
589.7 - */
589.8 -
589.9 -package org.netbeans.modules.python.editor.hints;
589.10 -
589.11 -import org.netbeans.modules.python.editor.PythonTestBase;
589.12 -
589.13 -/**
589.14 - *
589.15 - * @author Tor Norbye
589.16 - */
589.17 -public class ExtractCodeTest extends PythonTestBase {
589.18 -
589.19 - public ExtractCodeTest(String testName) {
589.20 - super(testName);
589.21 - }
589.22 -
589.23 - private PythonSelectionRule createRule() {
589.24 - return new ExtractCode();
589.25 - }
589.26 -
589.27 - public void testRegistered() throws Exception {
589.28 - ensureRegistered(createRule());
589.29 - }
589.30 -
589.31 - public void testHint1() throws Exception {
589.32 - checkHints(createRule(), "testfiles/extract1.py",
589.33 - "^# Beginning of extraction segment",
589.34 - "# End of extraction segment^");
589.35 - }
589.36 -
589.37 - public void testFix1() throws Exception {
589.38 - applyHint(this, createRule(), "testfiles/extract1.py",
589.39 - "^# Beginning of extraction segment",
589.40 - "# End of extraction segment^",
589.41 - "Extract Method", true);
589.42 - }
589.43 -
589.44 - public void testFix1b() throws Exception {
589.45 - applyHint(this, createRule(), "testfiles/extract1.py",
589.46 - "^ # Beginning of extraction segment",
589.47 - "# End of extraction segment^",
589.48 - "Extract Method", true);
589.49 - }
589.50 -
589.51 - public void testFix2() throws Exception {
589.52 - applyHint(this, createRule(), "testfiles/extract2.py",
589.53 - "^simple_code = 1",
589.54 - "simple_code = simple_code+1^",
589.55 - "Extract Method", true);
589.56 - }
589.57 -
589.58 - public void testFix3() throws Exception {
589.59 - applyHint(this, createRule(), "testfiles/extract2.py",
589.60 - "^not_used = 1",
589.61 - "print simple_code + not_used^",
589.62 - "Extract Method", true);
589.63 - }
589.64 -
589.65 - public void testFix4() throws Exception {
589.66 - applyHint(this, createRule(), "testfiles/datetime.py",
589.67 - "^assert 1 <= month <= 12, month",
589.68 - "assert 1 <= month <= 12, month^",
589.69 - "Extract Method", true);
589.70 - }
589.71 -
589.72 - public void testFix5() throws Exception {
589.73 - // 150932: Quickfix extract method does not change all instances of the chosen name
589.74 - applyHint(this, createRule(), "testfiles/extract4.py",
589.75 - "^if _a >a:",
589.76 - "c = b^",
589.77 - "Extract Method", true);
589.78 - }
589.79 -
589.80 - public void testFix6() throws Exception {
589.81 - applyHint(this, createRule(), "testfiles/extract5.py",
589.82 - "^if _a >a:",
589.83 - "c = b^",
589.84 - "Extract Method", true);
589.85 - }
589.86 -
589.87 - public void testFix7() throws Exception {
589.88 - applyHint(this, createRule(), "testfiles/extract1.py",
589.89 - "^not_used_in_block = 1",
589.90 - "read_after_block_only = 4\n^",
589.91 - "Extract Method", true);
589.92 - }
589.93 -
589.94 - //public void testFix4() throws Exception {
589.95 - // applyHint(this, createRule(), "testfiles/extract2.py",
589.96 - // "^preprocess(foo, source, output_file, macros, include_dirs, extra_preargs, extra_postargs);",
589.97 - // "get_preprocess(self, source, output_file, macros, include_dirs, extra_preargs, extra_postargs)^",
589.98 - // "Extract Method");
589.99 - //}
589.100 -
589.101 - public void testFix8() throws Exception {
589.102 - applyHint(this, createRule(), "testfiles/ConfigParser.py",
589.103 - "^try:",
589.104 - "raise NoSectionError(section)^",
589.105 - "Extract Method", true);
589.106 - }
589.107 -}
590.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/InputOutputFinderTest.java Sun Jan 04 13:11:53 2015 -0600
590.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
590.3 @@ -1,173 +0,0 @@
590.4 -/*
590.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
590.6 - *
590.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
590.8 - *
590.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
590.10 - * Other names may be trademarks of their respective owners.
590.11 - *
590.12 - * The contents of this file are subject to the terms of either the GNU
590.13 - * General Public License Version 2 only ("GPL") or the Common
590.14 - * Development and Distribution License("CDDL") (collectively, the
590.15 - * "License"). You may not use this file except in compliance with the
590.16 - * License. You can obtain a copy of the License at
590.17 - * http://www.netbeans.org/cddl-gplv2.html
590.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
590.19 - * specific language governing permissions and limitations under the
590.20 - * License. When distributing the software, include this License Header
590.21 - * Notice in each file and include the License file at
590.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
590.23 - * particular file as subject to the "Classpath" exception as provided
590.24 - * by Oracle in the GPL Version 2 section of the License file that
590.25 - * accompanied this code. If applicable, add the following below the
590.26 - * License Header, with the fields enclosed by brackets [] replaced by
590.27 - * your own identifying information:
590.28 - * "Portions Copyrighted [year] [name of copyright owner]"
590.29 - *
590.30 - * If you wish your version of this file to be governed by only the CDDL
590.31 - * or only the GPL Version 2, indicate your decision by adding
590.32 - * "[Contributor] elects to include this software in this distribution
590.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
590.34 - * single choice of license, a recipient has the option to distribute
590.35 - * your version of this file under either the CDDL, the GPL Version 2 or
590.36 - * to extend the choice of license to its licensees as provided above.
590.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
590.38 - * Version 2 license, then the option applies only if the new code is
590.39 - * made subject to such option by the copyright holder.
590.40 - *
590.41 - * Contributor(s):
590.42 - *
590.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
590.44 - */
590.45 -
590.46 -package org.netbeans.modules.python.editor.hints;
590.47 -
590.48 -import java.util.Collections;
590.49 -import java.util.HashSet;
590.50 -import java.util.List;
590.51 -import java.util.Set;
590.52 -import org.netbeans.modules.gsf.GsfTestCompilationInfo;
590.53 -import org.netbeans.modules.python.editor.AstPath;
590.54 -import org.netbeans.modules.python.editor.PythonAstUtils;
590.55 -import org.netbeans.modules.python.editor.PythonTestBase;
590.56 -import org.python.antlr.PythonTree;
590.57 -
590.58 -/**
590.59 - *
590.60 - * @author Tor Norbye
590.61 - */
590.62 -public class InputOutputFinderTest extends PythonTestBase {
590.63 -
590.64 - public InputOutputFinderTest(String name) {
590.65 - super(name);
590.66 - }
590.67 -
590.68 - InputOutputFinder getFinder(String source) throws Exception {
590.69 - String BEGIN = "%<%"; // NOI18N
590.70 - String END = "%>%"; // NOI18N
590.71 - int sourceStartPos = source.indexOf(BEGIN);
590.72 - if (sourceStartPos != -1) {
590.73 - source = source.substring(0, sourceStartPos) + source.substring(sourceStartPos+BEGIN.length());
590.74 - }
590.75 -
590.76 - int caretPos = source.indexOf('^');
590.77 - if (caretPos != -1) {
590.78 - source = source.substring(0, caretPos) + source.substring(caretPos+1);
590.79 - }
590.80 -
590.81 - int sourceEndPos = source.indexOf(END);
590.82 - if (sourceEndPos != -1) {
590.83 - source = source.substring(0, sourceEndPos) + source.substring(sourceEndPos+END.length());
590.84 - }
590.85 -
590.86 - GsfTestCompilationInfo info = getInfoForText(source, "temp.py");
590.87 - assertNotNull(info);
590.88 -
590.89 - if (caretPos != -1) {
590.90 - info.setCaretOffset(caretPos);
590.91 - }
590.92 -
590.93 - PythonTree root = PythonAstUtils.getRoot(info);
590.94 - assertNotNull(root);
590.95 -
590.96 - PythonTree startNode = AstPath.get(root, sourceStartPos).leaf();
590.97 - PythonTree endNode = AstPath.get(root, sourceEndPos).leaf();
590.98 -
590.99 - List<PythonTree> applicableBlocks = Collections.emptyList();
590.100 - InputOutputFinder finder = new InputOutputFinder(startNode, endNode, applicableBlocks);
590.101 -
590.102 - PythonTree scope = PythonAstUtils.getLocalScope(AstPath.get(root, sourceStartPos));
590.103 - assertNotNull(scope);
590.104 - finder.visit(scope);
590.105 -
590.106 - return finder;
590.107 - }
590.108 -
590.109 - public void testCall() throws Exception {
590.110 - InputOutputFinder finder = getFinder("foo = 1;\n%<%foo()%>%\nprint foo\n");
590.111 - Set<String> inputVars = finder.getInputVars();
590.112 - assertEquals(Collections.emptySet(), inputVars);
590.113 -
590.114 - Set<String> outputVars = finder.getOutputVars();
590.115 - assertEquals(Collections.emptySet(), outputVars);
590.116 - }
590.117 -
590.118 - public void testVariableRead() throws Exception {
590.119 - InputOutputFinder finder = getFinder("x = 1\ny = 2\n%<%print x+y%>%");
590.120 - Set<String> inputVars = finder.getInputVars();
590.121 - Set<String> expected = new HashSet<String>() {{
590.122 - add("x");
590.123 - add("y");
590.124 - }};
590.125 - assertEquals(expected, inputVars);
590.126 -
590.127 - Set<String> outputVars = finder.getOutputVars();
590.128 - assertEquals(Collections.emptySet(), outputVars);
590.129 - }
590.130 -
590.131 - public void testVariableWrite() throws Exception {
590.132 - InputOutputFinder finder = getFinder("%<%y = 1%>%\nprint y\n");
590.133 - Set<String> inputVars = finder.getInputVars();
590.134 - assertEquals(Collections.emptySet(), inputVars);
590.135 -
590.136 - Set<String> outputVars = finder.getOutputVars();
590.137 - Set<String> expected = new HashSet<String>() {{
590.138 - add("y");
590.139 - }};
590.140 - assertEquals(expected, outputVars);
590.141 - }
590.142 -
590.143 - public void testIncrement() throws Exception {
590.144 - InputOutputFinder finder = getFinder("%<%x = x + 1%>%\nprint x");
590.145 - Set<String> inputVars = finder.getInputVars();
590.146 - Set<String> expected = new HashSet<String>() {{
590.147 - add("x");
590.148 - }};
590.149 - assertEquals(expected, inputVars);
590.150 -
590.151 - Set<String> outputVars = finder.getOutputVars();
590.152 - expected = new HashSet<String>() {{
590.153 - add("x");
590.154 - }};
590.155 - assertEquals(expected, outputVars);
590.156 - }
590.157 -
590.158 -
590.159 - public void testAssignment() throws Exception {
590.160 - InputOutputFinder finder = getFinder(
590.161 - "x = 5\n" +
590.162 - "%<%y = x + 1%>%\n" +
590.163 - "print y");
590.164 - Set<String> inputVars = finder.getInputVars();
590.165 - Set<String> expected = new HashSet<String>() {{
590.166 - add("x");
590.167 - }};
590.168 - assertEquals(expected, inputVars);
590.169 -
590.170 - Set<String> outputVars = finder.getOutputVars();
590.171 - expected = new HashSet<String>() {{
590.172 - add("y");
590.173 - }};
590.174 - assertEquals(expected, outputVars);
590.175 - }
590.176 -}
591.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/NameRuleTest.java Sun Jan 04 13:11:53 2015 -0600
591.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
591.3 @@ -1,67 +0,0 @@
591.4 -/*
591.5 - * To change this template, choose Tools | Templates
591.6 - * and open the template in the editor.
591.7 - */
591.8 -package org.netbeans.modules.python.editor.hints;
591.9 -
591.10 -import org.netbeans.modules.python.editor.PythonTestBase;
591.11 -
591.12 -/**
591.13 - *
591.14 - * @author Tor Norbye
591.15 - */
591.16 -public class NameRuleTest extends PythonTestBase {
591.17 - public NameRuleTest(String testName) {
591.18 - super(testName);
591.19 - }
591.20 -
591.21 - private PythonAstRule createRule() {
591.22 - return new NameRule();
591.23 - }
591.24 -
591.25 - public void testRegistered() throws Exception {
591.26 - ensureRegistered(createRule());
591.27 - }
591.28 -
591.29 - public void testHint1() throws Exception {
591.30 - findHints(this, createRule(), "testfiles/ConfigParser.py", null, null);
591.31 - }
591.32 -
591.33 - public void testHint2() throws Exception {
591.34 - findHints(this, createRule(), "testfiles/names.py", null, null);
591.35 - }
591.36 -
591.37 - public void testHint3() throws Exception {
591.38 - findHints(this, createRule(), "testfiles/names2.py", null, null);
591.39 - }
591.40 -
591.41 - public void testHint4() throws Exception {
591.42 - findHints(this, createRule(), "testfiles/getopt.py", null, null);
591.43 - }
591.44 -
591.45 - public void testHint5() throws Exception {
591.46 - findHints(this, createRule(), "testfiles/datetime.py", null, null);
591.47 - }
591.48 -
591.49 - public void testHint6() throws Exception {
591.50 - findHints(this, createRule(), "testfiles/test_scope.py", null, null);
591.51 - }
591.52 -
591.53 - public void testHint7() throws Exception {
591.54 - findHints(this, createRule(), "testfiles/staticmethods.py", null, null);
591.55 - }
591.56 -
591.57 - public void testFix1() throws Exception {
591.58 - applyHint(this, createRule(), "testfiles/names2.py",
591.59 - "^def noargs()",
591.60 - "def noargs()^",
591.61 - "Insert a new first param");
591.62 - }
591.63 -
591.64 - public void testFix2() throws Exception {
591.65 - applyHint(this, createRule(), "testfiles/names2.py",
591.66 - "^def bad2(filename)",
591.67 - "bad2(filename)^",
591.68 - "Rename");
591.69 - }
591.70 -}
592.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/NameStyleTest.java Sun Jan 04 13:11:53 2015 -0600
592.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
592.3 @@ -1,99 +0,0 @@
592.4 -/*
592.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
592.6 - *
592.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
592.8 - *
592.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
592.10 - * Other names may be trademarks of their respective owners.
592.11 - *
592.12 - * The contents of this file are subject to the terms of either the GNU
592.13 - * General Public License Version 2 only ("GPL") or the Common
592.14 - * Development and Distribution License("CDDL") (collectively, the
592.15 - * "License"). You may not use this file except in compliance with the
592.16 - * License. You can obtain a copy of the License at
592.17 - * http://www.netbeans.org/cddl-gplv2.html
592.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
592.19 - * specific language governing permissions and limitations under the
592.20 - * License. When distributing the software, include this License Header
592.21 - * Notice in each file and include the License file at
592.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
592.23 - * particular file as subject to the "Classpath" exception as provided
592.24 - * by Oracle in the GPL Version 2 section of the License file that
592.25 - * accompanied this code. If applicable, add the following below the
592.26 - * License Header, with the fields enclosed by brackets [] replaced by
592.27 - * your own identifying information:
592.28 - * "Portions Copyrighted [year] [name of copyright owner]"
592.29 - *
592.30 - * If you wish your version of this file to be governed by only the CDDL
592.31 - * or only the GPL Version 2, indicate your decision by adding
592.32 - * "[Contributor] elects to include this software in this distribution
592.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
592.34 - * single choice of license, a recipient has the option to distribute
592.35 - * your version of this file under either the CDDL, the GPL Version 2 or
592.36 - * to extend the choice of license to its licensees as provided above.
592.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
592.38 - * Version 2 license, then the option applies only if the new code is
592.39 - * made subject to such option by the copyright holder.
592.40 - *
592.41 - * Contributor(s):
592.42 - *
592.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
592.44 - */
592.45 -package org.netbeans.modules.python.editor.hints;
592.46 -
592.47 -import org.netbeans.junit.NbTestCase;
592.48 -
592.49 -/**
592.50 - *
592.51 - * @author Tor Norbye
592.52 - */
592.53 -public class NameStyleTest extends NbTestCase {
592.54 - public NameStyleTest(String name) {
592.55 - super(name);
592.56 - }
592.57 -
592.58 - public void testComplies() {
592.59 - assertTrue(NameStyle.NO_PREFERENCE.complies("foo"));
592.60 - assertTrue(NameStyle.NO_PREFERENCE.complies("s_43"));
592.61 - assertTrue(NameStyle.NO_PREFERENCE.complies("Ffoo"));
592.62 -
592.63 - assertTrue(NameStyle.CAPITALIZED_WITH_UNDERSCORES.complies("FOO"));
592.64 - assertTrue(NameStyle.CAPITALIZED_WITH_UNDERSCORES.complies("FOO_BAR"));
592.65 - assertTrue(NameStyle.CAPITALIZED_WITH_UNDERSCORES.complies("_FOO_BAR"));
592.66 - assertTrue(NameStyle.CAPITALIZED_WITH_UNDERSCORES.complies("__FOO_BAR__"));
592.67 - assertTrue(NameStyle.CAPITALIZED_WITH_UNDERSCORES.complies("FOO1"));
592.68 - assertTrue(!NameStyle.CAPITALIZED_WITH_UNDERSCORES.complies("foo"));
592.69 -
592.70 - assertTrue(NameStyle.CAPITALIZED_WORDS.complies("FooF"));
592.71 - assertTrue(NameStyle.CAPITALIZED_WORDS.complies("FooBar"));
592.72 - assertTrue(!NameStyle.CAPITALIZED_WORDS.complies("fooBar"));
592.73 - assertTrue(!NameStyle.CAPITALIZED_WORDS.complies("foobar"));
592.74 -
592.75 - assertTrue(NameStyle.LOWERCASE.complies("foobar"));
592.76 - assertTrue(NameStyle.LOWERCASE.complies("__foobar"));
592.77 - assertTrue(!NameStyle.LOWERCASE.complies("__Foobar"));
592.78 - assertTrue(!NameStyle.LOWERCASE.complies("__fooBar"));
592.79 -
592.80 - assertTrue(NameStyle.LOWERCASE_WITH_UNDERSCORES.complies("foo"));
592.81 - assertTrue(NameStyle.LOWERCASE_WITH_UNDERSCORES.complies("foo_bar"));
592.82 - assertTrue(!NameStyle.LOWERCASE_WITH_UNDERSCORES.complies("foo_Bar"));
592.83 -
592.84 - assertTrue(NameStyle.MIXED_CASE.complies("foobar"));
592.85 - assertTrue(NameStyle.MIXED_CASE.complies("fooBar"));
592.86 - assertTrue(!NameStyle.MIXED_CASE.complies("FooBar"));
592.87 - assertTrue(!NameStyle.MIXED_CASE.complies("foo_bar"));
592.88 - assertTrue(!NameStyle.MIXED_CASE.complies("Foobar"));
592.89 -
592.90 - assertTrue(NameStyle.UPPERCASE.complies("FOOBAR"));
592.91 - assertTrue(NameStyle.UPPERCASE.complies("F"));
592.92 - assertTrue(NameStyle.UPPERCASE.complies("__FOOBAR__"));
592.93 - assertTrue(NameStyle.UPPERCASE.complies("_FOOBAR"));
592.94 - assertTrue(!NameStyle.UPPERCASE.complies("FOO_BAR"));
592.95 - assertTrue(!NameStyle.UPPERCASE.complies("FooBar"));
592.96 -
592.97 - assertTrue(NameStyle.UPPERCASE_WITH_UNDERSCORES.complies("FOOBAR"));
592.98 - assertTrue(NameStyle.UPPERCASE_WITH_UNDERSCORES.complies("FOO_BAR"));
592.99 - assertTrue(NameStyle.UPPERCASE_WITH_UNDERSCORES.complies("__FOO_BAR__"));
592.100 - assertTrue(!NameStyle.UPPERCASE_WITH_UNDERSCORES.complies("FooBar"));
592.101 - }
592.102 -}
593.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/RelativeImportsTest.java Sun Jan 04 13:11:53 2015 -0600
593.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
593.3 @@ -1,59 +0,0 @@
593.4 -/*
593.5 - * To change this template, choose Tools | Templates
593.6 - * and open the template in the editor.
593.7 - */
593.8 -
593.9 -package org.netbeans.modules.python.editor.hints;
593.10 -
593.11 -import org.netbeans.modules.python.editor.PythonTestBase;
593.12 -
593.13 -/**
593.14 - *
593.15 - * @author Tor Norbye
593.16 - */
593.17 -public class RelativeImportsTest extends PythonTestBase {
593.18 -
593.19 - public RelativeImportsTest(String testName) {
593.20 - super(testName);
593.21 - }
593.22 -
593.23 - private PythonAstRule createRule() {
593.24 - return new RelativeImports();
593.25 - }
593.26 -
593.27 - public void testRegistered() throws Exception {
593.28 - ensureRegistered(createRule());
593.29 - }
593.30 -
593.31 - public void testNoHints() throws Exception {
593.32 - findHints(this, createRule(), "testfiles/pickle.py", null, null);
593.33 - }
593.34 -
593.35 - public void testHint1() throws Exception {
593.36 - findHints(this, createRule(), "testfiles/toppkg/medpkg/lowpkg/imports.py", null, null);
593.37 - }
593.38 -
593.39 - public void testHint2() throws Exception {
593.40 - findHints(this, createRule(), "testfiles/package/subpackage1/moduleX.py", null, null);
593.41 - }
593.42 -
593.43 - public void testFix1() throws Exception {
593.44 - applyHint(this, createRule(), "testfiles/toppkg/medpkg/lowpkg/imports.py", "from .m^oduleY import spam", "Replace");
593.45 - }
593.46 -
593.47 - public void testFix2() throws Exception {
593.48 - applyHint(this, createRule(), "testfiles/toppkg/medpkg/lowpkg/imports.py", "fr^om ..subpackage1 import moduleY", "Replace");
593.49 - }
593.50 -
593.51 - public void testFix3() throws Exception {
593.52 - applyHint(this, createRule(), "testfiles/toppkg/medpkg/lowpkg/imports.py", "fr^om ...package import bar", "Replace");
593.53 - }
593.54 -
593.55 - public void testFix4() throws Exception {
593.56 - applyHint(this, createRule(), "testfiles/package/subpackage1/moduleX.py", "f^rom . import moduleY", "Replace");
593.57 - }
593.58 -
593.59 - public void testFix5() throws Exception {
593.60 - applyHint(this, createRule(), "testfiles/package/subpackage1/moduleX.py", "from .m^oduleY import spam", "Replace");
593.61 - }
593.62 -}
594.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/SplitImportsTest.java Sun Jan 04 13:11:53 2015 -0600
594.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
594.3 @@ -1,39 +0,0 @@
594.4 -/*
594.5 - * To change this template, choose Tools | Templates
594.6 - * and open the template in the editor.
594.7 - */
594.8 -
594.9 -package org.netbeans.modules.python.editor.hints;
594.10 -
594.11 -import org.netbeans.modules.python.editor.PythonTestBase;
594.12 -
594.13 -/**
594.14 - *
594.15 - * @author Tor Norbye
594.16 - */
594.17 -public class SplitImportsTest extends PythonTestBase {
594.18 -
594.19 - public SplitImportsTest(String testName) {
594.20 - super(testName);
594.21 - }
594.22 -
594.23 - private PythonAstRule createRule() {
594.24 - return new SplitImports();
594.25 - }
594.26 -
594.27 - public void testRegistered() throws Exception {
594.28 - ensureRegistered(createRule());
594.29 - }
594.30 -
594.31 - public void testHint1() throws Exception {
594.32 - findHints(this, createRule(), "testfiles/split_imports.py", null, null);
594.33 - }
594.34 -
594.35 - public void testFix1() throws Exception {
594.36 - applyHint(this, createRule(), "testfiles/split_imports.py", "^import sys, os, foobar", "Split");
594.37 - }
594.38 -
594.39 - public void testFix2() throws Exception {
594.40 - applyHint(this, createRule(), "testfiles/split_imports.py", "^import sys as whatever, os as bar", "Split");
594.41 - }
594.42 -}
595.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/SurroundWithTest.java Sun Jan 04 13:11:53 2015 -0600
595.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
595.3 @@ -1,110 +0,0 @@
595.4 -/*
595.5 - * To change this template, choose Tools | Templates
595.6 - * and open the template in the editor.
595.7 - */
595.8 -
595.9 -package org.netbeans.modules.python.editor.hints;
595.10 -
595.11 -import org.netbeans.modules.python.editor.PythonTestBase;
595.12 -
595.13 -/**
595.14 - *
595.15 - * @author Tor Norbye
595.16 - */
595.17 -public class SurroundWithTest extends PythonTestBase {
595.18 -
595.19 - public SurroundWithTest(String testName) {
595.20 - super(testName);
595.21 - }
595.22 -
595.23 - private PythonSelectionRule createRule() {
595.24 - return new SurroundWith();
595.25 - }
595.26 -
595.27 - public void testRegistered() throws Exception {
595.28 - ensureRegistered(createRule());
595.29 - }
595.30 -
595.31 - public void testHint1() throws Exception {
595.32 - checkHints(createRule(), "testfiles/datetime.py",
595.33 - "^for dim in _DAYS_IN_MONTH[1:]:",
595.34 - "del dbm, dim^");
595.35 - }
595.36 -
595.37 - public void testHint2() throws Exception {
595.38 - checkHints(createRule(), "testfiles/datetime.py",
595.39 - "^\"year -> number of days in year (366 if a leap year, else 365).\"",
595.40 - "\"year -> number of days in year (366 if a leap year, else 365).\"^");
595.41 - }
595.42 -
595.43 - public void testHint3() throws Exception {
595.44 - checkHints(createRule(), "testfiles/datetime.py",
595.45 - "^# Now compute how many 4-year cycles precede it.",
595.46 - "^ # And now how many single years.");
595.47 - }
595.48 -
595.49 - public void testHint4() throws Exception {
595.50 - checkHints(createRule(), "testfiles/simple.py",
595.51 - "^x = 1",
595.52 - "y = 2^");
595.53 - }
595.54 -
595.55 - public void testNoHint1() throws Exception {
595.56 - checkHints(createRule(), "testfiles/datetime.py",
595.57 - "f^or dim in _DAYS_IN_MONTH[1:]:",
595.58 - "del dbm, dim^");
595.59 - }
595.60 -
595.61 - public void testNoHint2() throws Exception {
595.62 - checkHints(createRule(), "testfiles/datetime.py",
595.63 - "^for dim in _DAYS_IN_MONTH[1:]:",
595.64 - "del dbm, di^m");
595.65 - }
595.66 -
595.67 - public void testNoHint3() throws Exception {
595.68 - checkHints(createRule(), "testfiles/datetime.py",
595.69 - "^def _is_leap(year):",
595.70 - " return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)^");
595.71 - }
595.72 -
595.73 - public void testNoHint4() throws Exception {
595.74 - checkHints(createRule(), "testfiles/datetime.py",
595.75 - "def ^_days_before_year(year):",
595.76 - "def _days_before_year^(year):");
595.77 - }
595.78 -
595.79 - public void testFix1() throws Exception {
595.80 - applyHint(this, createRule(), "testfiles/datetime.py",
595.81 - "^assert 1 <= month <= 12, month",
595.82 - "return 29^",
595.83 - "Surround With Try/Except\n");
595.84 - }
595.85 -
595.86 - public void testFix2() throws Exception {
595.87 - applyHint(this, createRule(), "testfiles/datetime.py",
595.88 - "^assert 1 <= month <= 12, month",
595.89 - "return 29^",
595.90 - "Surround With Try/Except/Finally");
595.91 - }
595.92 -
595.93 - public void testFix3() throws Exception {
595.94 - applyHint(this, createRule(), "testfiles/datetime.py",
595.95 - "^assert 1 <= month <= 12, month",
595.96 - "return 29^",
595.97 - "Surround With Try/Finally");
595.98 - }
595.99 -
595.100 - public void testFix4() throws Exception {
595.101 - applyHint(this, createRule(), "testfiles/surround.py",
595.102 - "^ print \"second\"",
595.103 - "^ print \"third\"",
595.104 - "Surround With Try/Finally");
595.105 - }
595.106 -
595.107 - public void testFix5() throws Exception {
595.108 - applyHint(this, createRule(), "testfiles/datetime.py",
595.109 - "^_DI400Y = _days_before_year(401)",
595.110 - "^_DI4Y = _days_before_year(5)",
595.111 - "Surround With Try/Finally");
595.112 - }
595.113 -}
596.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/UnresolvedClassComponentsTest.java Sun Jan 04 13:11:53 2015 -0600
596.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
596.3 @@ -1,77 +0,0 @@
596.4 -/*
596.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
596.6 - *
596.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
596.8 - *
596.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
596.10 - * Other names may be trademarks of their respective owners.
596.11 - *
596.12 - * The contents of this file are subject to the terms of either the GNU
596.13 - * General Public License Version 2 only ("GPL") or the Common
596.14 - * Development and Distribution License("CDDL") (collectively, the
596.15 - * "License"). You may not use this file except in compliance with the
596.16 - * License. You can obtain a copy of the License at
596.17 - * http://www.netbeans.org/cddl-gplv2.html
596.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
596.19 - * specific language governing permissions and limitations under the
596.20 - * License. When distributing the software, include this License Header
596.21 - * Notice in each file and include the License file at
596.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
596.23 - * particular file as subject to the "Classpath" exception as provided
596.24 - * by Oracle in the GPL Version 2 section of the License file that
596.25 - * accompanied this code. If applicable, add the following below the
596.26 - * License Header, with the fields enclosed by brackets [] replaced by
596.27 - * your own identifying information:
596.28 - * "Portions Copyrighted [year] [name of copyright owner]"
596.29 - *
596.30 - * If you wish your version of this file to be governed by only the CDDL
596.31 - * or only the GPL Version 2, indicate your decision by adding
596.32 - * "[Contributor] elects to include this software in this distribution
596.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
596.34 - * single choice of license, a recipient has the option to distribute
596.35 - * your version of this file under either the CDDL, the GPL Version 2 or
596.36 - * to extend the choice of license to its licensees as provided above.
596.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
596.38 - * Version 2 license, then the option applies only if the new code is
596.39 - * made subject to such option by the copyright holder.
596.40 - *
596.41 - * Contributor(s):
596.42 - *
596.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
596.44 - */
596.45 -
596.46 -package org.netbeans.modules.python.editor.hints;
596.47 -
596.48 -import org.netbeans.modules.python.editor.PythonTestBase;
596.49 -
596.50 -/**
596.51 - *
596.52 - * @author Tor Norbye
596.53 - */
596.54 -public class UnresolvedClassComponentsTest extends PythonTestBase {
596.55 -
596.56 - public UnresolvedClassComponentsTest(String name) {
596.57 - super(name);
596.58 - }
596.59 -
596.60 - private PythonAstRule createRule() {
596.61 - return new UnresolvedClassComponents();
596.62 - }
596.63 -
596.64 - public void testRegistered() throws Exception {
596.65 - ensureRegistered(createRule());
596.66 - }
596.67 -
596.68 - public void testUnresolvedAttribute() throws Exception {
596.69 - findHints(this, createRule(), "testfiles/unresolvedattributes.py", null, null);
596.70 - }
596.71 -
596.72 - public void testUnresolvedParent() throws Exception {
596.73 - // Make sure wildcard imports work
596.74 - findHints(this, createRule(), "testfiles/unresolvedparents.py", null, null);
596.75 - }
596.76 -
596.77 - public void testUnresolvedCleanCase() throws Exception {
596.78 - findHints(this, createRule(), "testfiles/httplib.py", null, null);
596.79 - }
596.80 -}
597.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/UnresolvedDetectorTest.java Sun Jan 04 13:11:53 2015 -0600
597.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
597.3 @@ -1,95 +0,0 @@
597.4 -/*
597.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
597.6 - *
597.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
597.8 - *
597.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
597.10 - * Other names may be trademarks of their respective owners.
597.11 - *
597.12 - * The contents of this file are subject to the terms of either the GNU
597.13 - * General Public License Version 2 only ("GPL") or the Common
597.14 - * Development and Distribution License("CDDL") (collectively, the
597.15 - * "License"). You may not use this file except in compliance with the
597.16 - * License. You can obtain a copy of the License at
597.17 - * http://www.netbeans.org/cddl-gplv2.html
597.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
597.19 - * specific language governing permissions and limitations under the
597.20 - * License. When distributing the software, include this License Header
597.21 - * Notice in each file and include the License file at
597.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
597.23 - * particular file as subject to the "Classpath" exception as provided
597.24 - * by Oracle in the GPL Version 2 section of the License file that
597.25 - * accompanied this code. If applicable, add the following below the
597.26 - * License Header, with the fields enclosed by brackets [] replaced by
597.27 - * your own identifying information:
597.28 - * "Portions Copyrighted [year] [name of copyright owner]"
597.29 - *
597.30 - * If you wish your version of this file to be governed by only the CDDL
597.31 - * or only the GPL Version 2, indicate your decision by adding
597.32 - * "[Contributor] elects to include this software in this distribution
597.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
597.34 - * single choice of license, a recipient has the option to distribute
597.35 - * your version of this file under either the CDDL, the GPL Version 2 or
597.36 - * to extend the choice of license to its licensees as provided above.
597.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
597.38 - * Version 2 license, then the option applies only if the new code is
597.39 - * made subject to such option by the copyright holder.
597.40 - *
597.41 - * Contributor(s):
597.42 - *
597.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
597.44 - */
597.45 -
597.46 -package org.netbeans.modules.python.editor.hints;
597.47 -
597.48 -import org.netbeans.modules.python.editor.PythonTestBase;
597.49 -
597.50 -/**
597.51 - *
597.52 - * @author Tor Norbye
597.53 - */
597.54 -public class UnresolvedDetectorTest extends PythonTestBase {
597.55 -
597.56 - public UnresolvedDetectorTest(String name) {
597.57 - super(name);
597.58 - }
597.59 -
597.60 - private PythonAstRule createRule() {
597.61 - return new UnresolvedDetector();
597.62 - }
597.63 -
597.64 - public void testRegistered() throws Exception {
597.65 - ensureRegistered(createRule());
597.66 - }
597.67 -
597.68 - public void testUnresolvedHints() throws Exception {
597.69 - findHints(this, createRule(), "testfiles/unresolved.py", null, null);
597.70 - }
597.71 -
597.72 - public void testUnresolvedHints2() throws Exception {
597.73 - // Make sure wildcard imports work
597.74 - findHints(this, createRule(), "testfiles/unresolved2.py", null, null);
597.75 - }
597.76 -
597.77 - public void testUnresolvedHints3() throws Exception {
597.78 - // Make sure wildcard imports work
597.79 - findHints(this, createRule(), "testfiles/unresolved3.py", null, null);
597.80 - }
597.81 -
597.82 - public void testUnresolvedHints4() throws Exception {
597.83 - findHints(this, createRule(), "testfiles/unresolved4.py", null, null);
597.84 - }
597.85 -
597.86 - public void testUnresolvedHints5() throws Exception {
597.87 - findHints(this, createRule(), "testfiles/unresolved5.py", null, null);
597.88 - }
597.89 -
597.90 - public void testUnresolvedHints6() throws Exception {
597.91 - // Test free variables in function/method
597.92 - findHints(this, createRule(), "testfiles/unresolved6.py", null, null);
597.93 - }
597.94 -
597.95 - public void testUnresolvedHints7() throws Exception {
597.96 - findHints(this, createRule(), "testfiles/datetime.py", null, null);
597.97 - }
597.98 -}
598.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/UnusedDetectorTest.java Sun Jan 04 13:11:53 2015 -0600
598.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
598.3 @@ -1,114 +0,0 @@
598.4 -/*
598.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
598.6 - *
598.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
598.8 - *
598.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
598.10 - * Other names may be trademarks of their respective owners.
598.11 - *
598.12 - * The contents of this file are subject to the terms of either the GNU
598.13 - * General Public License Version 2 only ("GPL") or the Common
598.14 - * Development and Distribution License("CDDL") (collectively, the
598.15 - * "License"). You may not use this file except in compliance with the
598.16 - * License. You can obtain a copy of the License at
598.17 - * http://www.netbeans.org/cddl-gplv2.html
598.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
598.19 - * specific language governing permissions and limitations under the
598.20 - * License. When distributing the software, include this License Header
598.21 - * Notice in each file and include the License file at
598.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
598.23 - * particular file as subject to the "Classpath" exception as provided
598.24 - * by Oracle in the GPL Version 2 section of the License file that
598.25 - * accompanied this code. If applicable, add the following below the
598.26 - * License Header, with the fields enclosed by brackets [] replaced by
598.27 - * your own identifying information:
598.28 - * "Portions Copyrighted [year] [name of copyright owner]"
598.29 - *
598.30 - * If you wish your version of this file to be governed by only the CDDL
598.31 - * or only the GPL Version 2, indicate your decision by adding
598.32 - * "[Contributor] elects to include this software in this distribution
598.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
598.34 - * single choice of license, a recipient has the option to distribute
598.35 - * your version of this file under either the CDDL, the GPL Version 2 or
598.36 - * to extend the choice of license to its licensees as provided above.
598.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
598.38 - * Version 2 license, then the option applies only if the new code is
598.39 - * made subject to such option by the copyright holder.
598.40 - *
598.41 - * Contributor(s):
598.42 - *
598.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
598.44 - */
598.45 -package org.netbeans.modules.python.editor.hints;
598.46 -
598.47 -import java.util.prefs.Preferences;
598.48 -import org.netbeans.modules.gsf.LanguageRegistry;
598.49 -import org.netbeans.modules.gsfret.hints.infrastructure.GsfHintsManager;
598.50 -import org.netbeans.modules.python.editor.PythonTestBase;
598.51 -
598.52 -/**
598.53 - *
598.54 - * @author Tor Norbye
598.55 - */
598.56 -public class UnusedDetectorTest extends PythonTestBase {
598.57 - public UnusedDetectorTest(String name) {
598.58 - super(name);
598.59 - }
598.60 -
598.61 - private void setHintOptions(boolean skipParams, boolean skipTupleAssigns, String ignoreNames) {
598.62 - org.netbeans.modules.gsf.Language language = LanguageRegistry.getInstance().getLanguageByMimeType(getPreferredMimeType());
598.63 - GsfHintsManager hintsManager = getHintsManager(language);
598.64 - Preferences prefs = hintsManager.getPreferences(createRule());
598.65 - UnusedDetector.setSkipParameters(prefs, skipParams);
598.66 - UnusedDetector.setSkipTupleAssignments(prefs, skipTupleAssigns);
598.67 - UnusedDetector.setIgnoreNames(prefs, ignoreNames);
598.68 - }
598.69 -
598.70 - private PythonAstRule createRule() {
598.71 - return new UnusedDetector();
598.72 - }
598.73 -
598.74 - public void testRegistered() throws Exception {
598.75 - ensureRegistered(createRule());
598.76 - }
598.77 -
598.78 - public void testUnusedHints() throws Exception {
598.79 - setHintOptions(false, false, "");
598.80 - findHints(this, createRule(), "testfiles/datetime.py", null, null);
598.81 - }
598.82 -
598.83 - public void testUnusedHints2() throws Exception {
598.84 - setHintOptions(false, false, "");
598.85 - findHints(this, createRule(), "testfiles/ConfigParser.py", null, null);
598.86 - }
598.87 -
598.88 - public void testUnusedHints3() throws Exception {
598.89 - setHintOptions(true, false, "");
598.90 - findHints(this, createRule(), "testfiles/datetime.py", null, null);
598.91 - }
598.92 -
598.93 - public void testUnusedHints4() throws Exception {
598.94 - setHintOptions(true, false, "");
598.95 - findHints(this, createRule(), "testfiles/datetime.py", null, null);
598.96 - }
598.97 -
598.98 - public void testUnusedHints5() throws Exception {
598.99 - setHintOptions(false, false, " jday, mm ");
598.100 - findHints(this, createRule(), "testfiles/datetime.py", null, null);
598.101 - }
598.102 -
598.103 - public void testUnusedHints6() throws Exception {
598.104 - setHintOptions(false, false, "");
598.105 - findHints(this, createRule(), "testfiles/delete.py", null, null);
598.106 - }
598.107 -
598.108 - public void testUnusedHints7() throws Exception {
598.109 - setHintOptions(false, false, "");
598.110 - findHints(this, createRule(), "testfiles/tuples.py", null, null);
598.111 - }
598.112 -
598.113 - public void testUnusedHints8() throws Exception {
598.114 - setHintOptions(true, true, "");
598.115 - findHints(this, createRule(), "testfiles/tuples.py", null, null);
598.116 - }
598.117 -}
599.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/hints/UnusedImportsTest.java Sun Jan 04 13:11:53 2015 -0600
599.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
599.3 @@ -1,109 +0,0 @@
599.4 -/*
599.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
599.6 - *
599.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
599.8 - *
599.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
599.10 - * Other names may be trademarks of their respective owners.
599.11 - *
599.12 - * The contents of this file are subject to the terms of either the GNU
599.13 - * General Public License Version 2 only ("GPL") or the Common
599.14 - * Development and Distribution License("CDDL") (collectively, the
599.15 - * "License"). You may not use this file except in compliance with the
599.16 - * License. You can obtain a copy of the License at
599.17 - * http://www.netbeans.org/cddl-gplv2.html
599.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
599.19 - * specific language governing permissions and limitations under the
599.20 - * License. When distributing the software, include this License Header
599.21 - * Notice in each file and include the License file at
599.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
599.23 - * particular file as subject to the "Classpath" exception as provided
599.24 - * by Oracle in the GPL Version 2 section of the License file that
599.25 - * accompanied this code. If applicable, add the following below the
599.26 - * License Header, with the fields enclosed by brackets [] replaced by
599.27 - * your own identifying information:
599.28 - * "Portions Copyrighted [year] [name of copyright owner]"
599.29 - *
599.30 - * If you wish your version of this file to be governed by only the CDDL
599.31 - * or only the GPL Version 2, indicate your decision by adding
599.32 - * "[Contributor] elects to include this software in this distribution
599.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
599.34 - * single choice of license, a recipient has the option to distribute
599.35 - * your version of this file under either the CDDL, the GPL Version 2 or
599.36 - * to extend the choice of license to its licensees as provided above.
599.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
599.38 - * Version 2 license, then the option applies only if the new code is
599.39 - * made subject to such option by the copyright holder.
599.40 - *
599.41 - * Contributor(s):
599.42 - *
599.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
599.44 - */
599.45 -
599.46 -package org.netbeans.modules.python.editor.hints;
599.47 -
599.48 -import org.netbeans.modules.python.editor.PythonTestBase;
599.49 -
599.50 -/**
599.51 - *
599.52 - * @author Tor Norbye
599.53 - */
599.54 -public class UnusedImportsTest extends PythonTestBase {
599.55 -
599.56 - public UnusedImportsTest(String name) {
599.57 - super(name);
599.58 - }
599.59 -
599.60 - private PythonAstRule createRule() {
599.61 - return new UnusedImports();
599.62 - }
599.63 -
599.64 - public void testRegistered() throws Exception {
599.65 - ensureRegistered(createRule());
599.66 - }
599.67 -
599.68 - public void testHints() throws Exception {
599.69 - findHints(this, createRule(), "testfiles/unusedimports1.py", null, null);
599.70 - }
599.71 -
599.72 - public void testNoHints2() throws Exception {
599.73 - // The operator import isn't unused - it's responsible for importing abs() even though
599.74 - // abs() would otherwise have been imported by the builtin functions module.
599.75 - findHints(this, createRule(), "testfiles/unusedimports3.py", null, null);
599.76 - }
599.77 -
599.78 - public void testNoHints3() throws Exception {
599.79 - findHints(this, createRule(), "testfiles/futureimport.py", null, null);
599.80 - }
599.81 -
599.82 - public void testNoHints4() throws Exception {
599.83 - // No unused import detection in __init__.py files!
599.84 - findHints(this, createRule(), "testfiles/package/subpackage1/__init__.py", null, null);
599.85 - }
599.86 -
599.87 - public void testNoHints5() throws Exception {
599.88 - // No unused import detection in __init__.py files!
599.89 - findHints(this, createRule(), "testfiles/imports/__init__.py", null, null);
599.90 - }
599.91 -
599.92 - public void testFix1() throws Exception {
599.93 - applyHint(this, createRule(), "testfiles/unusedimports1.py", "import ur^import", "Remove Unused");
599.94 - }
599.95 -
599.96 - public void testFix2() throws Exception {
599.97 - applyHint(this, createRule(), "testfiles/unusedimports1.py", "import ur^import", "Remove All");
599.98 - }
599.99 -
599.100 - public void testFix3() throws Exception {
599.101 - applyHint(this, createRule(), "testfiles/unusedimports1.py", "import ur^import", "Organize");
599.102 - }
599.103 -
599.104 - public void testFix4() throws Exception {
599.105 - applyHint(this, createRule(), "testfiles/unusedimports1.py", "from foo import Sy^m1, Sym2", "Sym1");
599.106 - }
599.107 -
599.108 - public void testFix5() throws Exception {
599.109 - // BUGGY -- there should be no comma at the end of sys! TODO FIXME
599.110 - applyHint(this, createRule(), "testfiles/unusedimports2.py", "import sys, os, f^our", "four");
599.111 - }
599.112 -}
600.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/imports/ImportManagerTest.java Sun Jan 04 13:11:53 2015 -0600
600.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
600.3 @@ -1,377 +0,0 @@
600.4 -/*
600.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
600.6 - *
600.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
600.8 - *
600.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
600.10 - * Other names may be trademarks of their respective owners.
600.11 - *
600.12 - * The contents of this file are subject to the terms of either the GNU
600.13 - * General Public License Version 2 only ("GPL") or the Common
600.14 - * Development and Distribution License("CDDL") (collectively, the
600.15 - * "License"). You may not use this file except in compliance with the
600.16 - * License. You can obtain a copy of the License at
600.17 - * http://www.netbeans.org/cddl-gplv2.html
600.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
600.19 - * specific language governing permissions and limitations under the
600.20 - * License. When distributing the software, include this License Header
600.21 - * Notice in each file and include the License file at
600.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
600.23 - * particular file as subject to the "Classpath" exception as provided
600.24 - * by Oracle in the GPL Version 2 section of the License file that
600.25 - * accompanied this code. If applicable, add the following below the
600.26 - * License Header, with the fields enclosed by brackets [] replaced by
600.27 - * your own identifying information:
600.28 - * "Portions Copyrighted [year] [name of copyright owner]"
600.29 - *
600.30 - * If you wish your version of this file to be governed by only the CDDL
600.31 - * or only the GPL Version 2, indicate your decision by adding
600.32 - * "[Contributor] elects to include this software in this distribution
600.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
600.34 - * single choice of license, a recipient has the option to distribute
600.35 - * your version of this file under either the CDDL, the GPL Version 2 or
600.36 - * to extend the choice of license to its licensees as provided above.
600.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
600.38 - * Version 2 license, then the option applies only if the new code is
600.39 - * made subject to such option by the copyright holder.
600.40 - *
600.41 - * Contributor(s):
600.42 - *
600.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
600.44 - */
600.45 -
600.46 -package org.netbeans.modules.python.editor.imports;
600.47 -
600.48 -import java.util.ArrayList;
600.49 -import java.util.Collections;
600.50 -import java.util.HashMap;
600.51 -import java.util.HashSet;
600.52 -import java.util.List;
600.53 -import java.util.Map;
600.54 -import java.util.Set;
600.55 -import java.util.prefs.Preferences;
600.56 -import javax.swing.JEditorPane;
600.57 -import javax.swing.text.Document;
600.58 -import org.netbeans.editor.BaseDocument;
600.59 -import org.netbeans.modules.editor.indent.spi.CodeStylePreferences;
600.60 -import org.netbeans.modules.gsf.GsfTestCompilationInfo;
600.61 -import org.netbeans.modules.gsf.api.EditList;
600.62 -import org.netbeans.modules.gsf.api.NameKind;
600.63 -import org.netbeans.modules.python.editor.PythonAstUtils;
600.64 -import org.netbeans.modules.python.editor.PythonIndex;
600.65 -import org.netbeans.modules.python.editor.PythonTestBase;
600.66 -import org.netbeans.modules.python.editor.elements.IndexedElement;
600.67 -import org.netbeans.modules.python.editor.lexer.PythonTokenId;
600.68 -import org.netbeans.modules.python.editor.options.CodeStyle.ImportCleanupStyle;
600.69 -import org.netbeans.modules.python.editor.options.FmtOptions;
600.70 -import org.openide.filesystems.FileObject;
600.71 -import org.openide.loaders.DataObject;
600.72 -
600.73 -/**
600.74 - *
600.75 - * @author Tor Norbye
600.76 - */
600.77 -public class ImportManagerTest extends PythonTestBase {
600.78 -
600.79 - public ImportManagerTest(String name) {
600.80 - super(name);
600.81 - }
600.82 -
600.83 - @Override
600.84 - protected void setUp() throws Exception {
600.85 - super.setUp();
600.86 -
600.87 - // Make sure the test file is indexed
600.88 - FileObject fo = getTestFile("testfiles/imports/definitions.py");
600.89 - GsfTestCompilationInfo info = getInfo(fo);
600.90 - assertNotNull(PythonAstUtils.getRoot(info));
600.91 - info.getIndex(PythonTokenId.PYTHON_MIME_TYPE);
600.92 - // Force init of the index for both files that we care about
600.93 - PythonIndex index = PythonIndex.get(info.getIndex(PythonTokenId.PYTHON_MIME_TYPE), info.getFileObject());
600.94 - Set<IndexedElement> classes = index.getClasses("DecimalException", NameKind.EXACT_NAME, PythonIndex.ALL_SCOPE, null, false);
600.95 - assertTrue(classes.size() > 0);
600.96 - }
600.97 -
600.98 - private void applyImports(String testFile, boolean commentOut) throws Exception {
600.99 - GsfTestCompilationInfo info = getInfo(getTestFile(testFile));
600.100 - info.getDocument();
600.101 - JEditorPane target = getPane(info.getText());
600.102 - Document doc = target.getDocument();
600.103 -
600.104 - DataObject dobj = DataObject.find(info.getFileObject());
600.105 - assertNotNull(dobj);
600.106 - doc.putProperty(Document.StreamDescriptionProperty, dobj);
600.107 -
600.108 - Preferences prefs = CodeStylePreferences.get(doc).getPreferences();
600.109 - if (commentOut) {
600.110 - prefs.put(FmtOptions.cleanupUnusedImports, ImportCleanupStyle.COMMENT_OUT.name());
600.111 - } else {
600.112 - prefs.put(FmtOptions.cleanupUnusedImports, ImportCleanupStyle.DELETE.name());
600.113 - }
600.114 -
600.115 - new FixImportsAction().actionPerformed(null, target);
600.116 -
600.117 - String text = doc.getText(0, doc.getLength());
600.118 - assertDescriptionMatches(testFile, text, true, ".imported");
600.119 - }
600.120 -
600.121 - private void checkImports(String testFile) throws Exception {
600.122 - GsfTestCompilationInfo info = getInfo(getTestFile(testFile));
600.123 - Document doc = info.getDocument();
600.124 - DataObject dobj = DataObject.find(info.getFileObject());
600.125 - assertNotNull(dobj);
600.126 - doc.putProperty(Document.StreamDescriptionProperty, dobj);
600.127 -
600.128 - List<String> ambiguousSymbols = new ArrayList<String>();
600.129 - Set<ImportEntry> unused = new HashSet<ImportEntry>();
600.130 - Set<ImportEntry> duplicates = new HashSet<ImportEntry>();
600.131 - Map<String, String> defaultLists = new HashMap<String, String>();
600.132 - Map<String, List<String>> alternatives = new HashMap<String, List<String>>();
600.133 -
600.134 - ImportManager manager = new ImportManager(info, (BaseDocument)doc);
600.135 - boolean ambiguous = manager.computeImports(ambiguousSymbols, defaultLists, alternatives, unused, duplicates);
600.136 -
600.137 - StringBuilder sb = new StringBuilder();
600.138 - sb.append("Requires user interaction: ");
600.139 - if (ambiguous) {
600.140 - sb.append("Yes");
600.141 - } else {
600.142 - sb.append("No");
600.143 - }
600.144 - sb.append("\n");
600.145 - if (unused.size() > 0) {
600.146 - sb.append("Unused imports:\n");
600.147 - List<ImportEntry> unusedList = new ArrayList<ImportEntry>(unused);
600.148 - Collections.sort(unusedList);
600.149 - for (ImportEntry entry : unusedList) {
600.150 - sb.append(" ");
600.151 - sb.append(entry.module);
600.152 - if (entry.symbol != null) {
600.153 - sb.append(" ");
600.154 - sb.append(entry.symbol);
600.155 - }
600.156 - if (entry.asName != null) {
600.157 - sb.append(" ");
600.158 - sb.append(entry.asName);
600.159 - }
600.160 - sb.append("\n");
600.161 - }
600.162 - }
600.163 - if (duplicates.size() > 0) {
600.164 - sb.append("Duplicate imports:\n");
600.165 - List<ImportEntry> duplicatesList = new ArrayList<ImportEntry>(duplicates);
600.166 - Collections.sort(duplicatesList);
600.167 - for (ImportEntry entry : duplicatesList) {
600.168 - sb.append(" ");
600.169 - sb.append(entry.module);
600.170 - if (entry.symbol != null) {
600.171 - sb.append(" ");
600.172 - sb.append(entry.symbol);
600.173 - }
600.174 - if (entry.asName != null) {
600.175 - sb.append(" ");
600.176 - sb.append(entry.asName);
600.177 - }
600.178 - sb.append("\n");
600.179 - }
600.180 - }
600.181 - if (ambiguousSymbols.size() > 0) {
600.182 - sb.append("Unresolved Symbols:\n");
600.183 - for (int i = 0; i < ambiguousSymbols.size(); i ++) {
600.184 - String symbol = ambiguousSymbols.get(i);
600.185 - sb.append(" ");
600.186 - sb.append(symbol);
600.187 - sb.append("\n");
600.188 - String deflt = defaultLists.get(symbol);
600.189 - List<String> choices = alternatives.get(symbol);
600.190 - for (String choice : choices) {
600.191 - sb.append(" ");
600.192 - if (choice.equals(deflt)) {
600.193 - sb.append("*");
600.194 - }
600.195 - if (choice.startsWith("<html>")) {
600.196 - sb.append("<cannot resolve>");
600.197 - } else {
600.198 - sb.append(choice);
600.199 - }
600.200 - sb.append("\n");
600.201 - }
600.202 - }
600.203 - }
600.204 -
600.205 - assertDescriptionMatches(testFile, sb.toString(), false, ".imports");
600.206 - }
600.207 -
600.208 - private void checkOrganize(String testFile, boolean systemLibsFirst, boolean splitImports, boolean commentOut, boolean sort, boolean separateFrom) throws Exception {
600.209 - GsfTestCompilationInfo info = getInfo(getTestFile(testFile));
600.210 - Document doc = info.getDocument();
600.211 - DataObject dobj = DataObject.find(info.getFileObject());
600.212 - assertNotNull(dobj);
600.213 - doc.putProperty(Document.StreamDescriptionProperty, dobj);
600.214 -
600.215 - EditList edits = new EditList((BaseDocument)doc);
600.216 - Preferences prefs = CodeStylePreferences.get(doc).getPreferences();
600.217 - if (commentOut) {
600.218 - prefs.put(FmtOptions.cleanupUnusedImports, ImportCleanupStyle.COMMENT_OUT.name());
600.219 - } else {
600.220 - prefs.put(FmtOptions.cleanupUnusedImports, ImportCleanupStyle.DELETE.name());
600.221 - }
600.222 - prefs.putBoolean(FmtOptions.oneImportPerLine, splitImports);
600.223 - prefs.putBoolean(FmtOptions.systemLibsFirst, systemLibsFirst);
600.224 - prefs.putBoolean(FmtOptions.sortImports, sort);
600.225 - prefs.putBoolean(FmtOptions.separateFromImps, separateFrom);
600.226 -
600.227 - ImportManager manager = new ImportManager(info, (BaseDocument)doc);
600.228 - manager.rewriteMainImports(edits, Collections.<ImportEntry>emptyList(), Collections.<ImportEntry>emptySet());
600.229 - edits.apply();
600.230 -
600.231 - String text = doc.getText(0, doc.getLength());
600.232 - assertDescriptionMatches(testFile, text, true, ".imported");
600.233 - }
600.234 -
600.235 - public void testIsImported1() throws Exception {
600.236 - GsfTestCompilationInfo info = getInfo(getTestFile("testfiles/imports/imports1.py"));
600.237 -
600.238 - /*
600.239 - import foo
600.240 - import bar as BAR
600.241 - import module1, module2, module3
600.242 - from module4 import Class1
600.243 - from module5 import Class2 as Class3
600.244 - */
600.245 - assertFalse(new ImportManager(info).isImported("foo", "Whatever"));
600.246 - assertTrue(new ImportManager(info).isImported("foo", null));
600.247 - assertTrue(new ImportManager(info).isImported("bar", "BAR"));
600.248 - assertFalse(new ImportManager(info).isImported("bar", "FOO"));
600.249 - assertTrue(new ImportManager(info).isImported("module1", null));
600.250 - assertFalse(new ImportManager(info).isImported("module1", "Whatever"));
600.251 - assertFalse(new ImportManager(info).isImported("module2", "Whatever"));
600.252 - assertTrue(new ImportManager(info).isImported("module4", "Class1"));
600.253 - assertFalse(new ImportManager(info).isImported("module4", "Class2"));
600.254 - assertFalse(new ImportManager(info).isImported("module5", "Class2"));
600.255 - assertTrue(new ImportManager(info).isImported("module5", "Class3"));
600.256 - }
600.257 -
600.258 -// public void testFixImports1() throws Exception {
600.259 -// applyImports("testfiles/imports/imports1.py", false);
600.260 -// }
600.261 -//
600.262 -// public void testFixImports2() throws Exception {
600.263 -// applyImports("testfiles/imports/imports1.py", true);
600.264 -// }
600.265 -//
600.266 -// public void testFixImports3() throws Exception {
600.267 -// applyImports("testfiles/imports/imports2.py", true);
600.268 -// }
600.269 -//
600.270 -// public void testFixImports4() throws Exception {
600.271 -// applyImports("testfiles/imports/imports3.py", true);
600.272 -// }
600.273 -//
600.274 -// public void testFixImports5() throws Exception {
600.275 -// checkImports("testfiles/imports/imports1.py");
600.276 -// }
600.277 -//
600.278 -// public void testFixImports6() throws Exception {
600.279 -// checkImports("testfiles/imports/imports2.py");
600.280 -// }
600.281 -//
600.282 -// public void testFixImports7() throws Exception {
600.283 -// checkImports("testfiles/imports/imports3.py");
600.284 -// }
600.285 -//
600.286 -// public void testFixDuplicates1() throws Exception {
600.287 -// checkImports("testfiles/imports/duplicates1.py");
600.288 -// }
600.289 -//
600.290 -// public void testFixDuplicates2() throws Exception {
600.291 -// checkImports("testfiles/imports/duplicates2.py");
600.292 -// }
600.293 -//
600.294 -// public void testFixDuplicates2b() throws Exception {
600.295 -// applyImports("testfiles/imports/duplicates2.py", true);
600.296 -// }
600.297 -//
600.298 -// public void testFixDuplicates3() throws Exception {
600.299 -// checkImports("testfiles/imports/duplicates3.py");
600.300 -// }
600.301 -//
600.302 -// public void testFixDuplicates3b() throws Exception {
600.303 -// applyImports("testfiles/imports/duplicates3.py", true);
600.304 -// }
600.305 -//
600.306 -// public void testFixDuplicates4() throws Exception {
600.307 -// checkImports("testfiles/imports/duplicates4.py");
600.308 -// }
600.309 -//
600.310 -// public void testFixDuplicates4b() throws Exception {
600.311 -// applyImports("testfiles/imports/duplicates4.py", true);
600.312 -// }
600.313 -//
600.314 -// public void testFixDuplicates5() throws Exception {
600.315 -// checkImports("testfiles/imports/duplicates5.py");
600.316 -// }
600.317 -//
600.318 -// public void testFixDuplicates5b() throws Exception {
600.319 -// applyImports("testfiles/imports/duplicates5.py", true);
600.320 -// }
600.321 -//
600.322 -// public void testFixDuplicates6() throws Exception {
600.323 -// checkImports("testfiles/imports/duplicates6.py");
600.324 -// }
600.325 -//
600.326 -// public void testFixDuplicates6b() throws Exception {
600.327 -// applyImports("testfiles/imports/duplicates6.py", true);
600.328 -// }
600.329 -//
600.330 -// public void testFixDuplicates7() throws Exception {
600.331 -// applyImports("testfiles/imports/duplicates7.py", true);
600.332 -// }
600.333 -
600.334 - public void testFixOrganize1() throws Exception {
600.335 - checkOrganize("testfiles/imports/organize1.py", true, true, false, true, false);
600.336 - }
600.337 -
600.338 - public void testFixOrganize2() throws Exception {
600.339 - checkOrganize("testfiles/imports/organize1.py", true, false, false, true, false);
600.340 - }
600.341 -
600.342 - public void testFixOrganize3() throws Exception {
600.343 - checkOrganize("testfiles/imports/organize1.py", true, true, false, true, false);
600.344 - }
600.345 -
600.346 - public void testFixOrganize4() throws Exception {
600.347 - checkOrganize("testfiles/imports/organize1.py", false, true, true, true, false);
600.348 - }
600.349 -
600.350 - public void testFixOrganize5() throws Exception {
600.351 - checkOrganize("testfiles/imports/organize1.py", true, false, false, true, false);
600.352 - }
600.353 -
600.354 - public void testFixOrganize6() throws Exception {
600.355 - checkOrganize("testfiles/imports/imports1.py", true, true, false, true, false);
600.356 - }
600.357 -
600.358 - public void testFixOrganize7() throws Exception {
600.359 - checkOrganize("testfiles/imports/organize1.py", true, true, false, false, false);
600.360 - }
600.361 -
600.362 - public void testFixOrganize8() throws Exception {
600.363 - checkOrganize("testfiles/imports/organize2.py", true, true, false, true, false);
600.364 - }
600.365 -
600.366 - public void testSortFutureImports() throws Exception {
600.367 - // 156442: Python __future__ imports not sorted properly
600.368 - checkOrganize("testfiles/imports/futures.py", false, true, false, true, true);
600.369 - }
600.370 -
600.371 - public void testFixInit() throws Exception {
600.372 - checkOrganize("testfiles/package/subpackage1/__init__.py", true, true, false, true, false);
600.373 - }
600.374 -
600.375 - public void testFixInit2() throws Exception {
600.376 - checkOrganize("testfiles/imports/__init__.py", true, true, false, true, false);
600.377 - }
600.378 -
600.379 - // TODO - try manually importing zlib - doesn't go to the right place (and check for system libs)
600.380 -}
601.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/lexer/CallTest.java Sun Jan 04 13:11:53 2015 -0600
601.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
601.3 @@ -1,255 +0,0 @@
601.4 -/*
601.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
601.6 - *
601.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
601.8 - *
601.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
601.10 - * Other names may be trademarks of their respective owners.
601.11 - *
601.12 - * The contents of this file are subject to the terms of either the GNU
601.13 - * General Public License Version 2 only ("GPL") or the Common
601.14 - * Development and Distribution License("CDDL") (collectively, the
601.15 - * "License"). You may not use this file except in compliance with the
601.16 - * License. You can obtain a copy of the License at
601.17 - * http://www.netbeans.org/cddl-gplv2.html
601.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
601.19 - * specific language governing permissions and limitations under the
601.20 - * License. When distributing the software, include this License Header
601.21 - * Notice in each file and include the License file at
601.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
601.23 - * particular file as subject to the "Classpath" exception as provided
601.24 - * by Oracle in the GPL Version 2 section of the License file that
601.25 - * accompanied this code. If applicable, add the following below the
601.26 - * License Header, with the fields enclosed by brackets [] replaced by
601.27 - * your own identifying information:
601.28 - * "Portions Copyrighted [year] [name of copyright owner]"
601.29 - *
601.30 - * Contributor(s):
601.31 - *
601.32 - * The Original Software is NetBeans. The Initial Developer of the Original
601.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
601.34 - * Microsystems, Inc. All Rights Reserved.
601.35 - *
601.36 - * If you wish your version of this file to be governed by only the CDDL
601.37 - * or only the GPL Version 2, indicate your decision by adding
601.38 - * "[Contributor] elects to include this software in this distribution
601.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
601.40 - * single choice of license, a recipient has the option to distribute
601.41 - * your version of this file under either the CDDL, the GPL Version 2 or
601.42 - * to extend the choice of license to its licensees as provided above.
601.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
601.44 - * Version 2 license, then the option applies only if the new code is
601.45 - * made subject to such option by the copyright holder.
601.46 - */
601.47 -
601.48 -package org.netbeans.modules.python.editor.lexer;
601.49 -
601.50 -import javax.swing.text.Document;
601.51 -import org.netbeans.api.lexer.TokenHierarchy;
601.52 -import org.netbeans.editor.BaseDocument;
601.53 -import org.netbeans.modules.python.editor.PythonTestBase;
601.54 -
601.55 -/**
601.56 - *
601.57 - * @author Tor Norbye
601.58 - */
601.59 -public class CallTest extends PythonTestBase {
601.60 -
601.61 - public CallTest(String testName) {
601.62 - super(testName);
601.63 - }
601.64 -
601.65 - private Call getCall(String source) {
601.66 - int caretPos = source.indexOf('^');
601.67 -
601.68 - source = source.substring(0, caretPos) + source.substring(caretPos + 1);
601.69 -
601.70 - BaseDocument doc = getDocument(source);
601.71 -
601.72 - TokenHierarchy<Document> th = TokenHierarchy.get((Document) doc);
601.73 - Call call = Call.getCallType(doc, th, caretPos);
601.74 -
601.75 - return call;
601.76 - }
601.77 -
601.78 - public void testCall1() throws Exception {
601.79 - Call call = getCall("File.ex^");
601.80 - assertEquals("File", call.getLhs());
601.81 - assertEquals("File", call.getType());
601.82 - assertTrue(call.isSimpleIdentifier());
601.83 - assertTrue(call.isStatic());
601.84 - }
601.85 -
601.86 - public void testCall1c() throws Exception {
601.87 - Call call = getCall("File.ex^ ");
601.88 - assertEquals("File", call.getLhs());
601.89 - assertEquals("File", call.getType());
601.90 - assertTrue(call.isSimpleIdentifier());
601.91 - assertTrue(call.isStatic());
601.92 - }
601.93 -
601.94 - public void testCall2() throws Exception {
601.95 - Call call = getCall("xy.ex^");
601.96 - assertEquals("xy", call.getLhs());
601.97 - assertEquals(null, call.getType());
601.98 - }
601.99 -
601.100 - public void testCall2b() throws Exception {
601.101 - Call call = getCall("xy.^");
601.102 - assertEquals("xy", call.getLhs());
601.103 - assertEquals(null, call.getType());
601.104 - }
601.105 -
601.106 - public void testCall2c() throws Exception {
601.107 - Call call = getCall("xy.ex^ ");
601.108 - assertEquals("xy", call.getLhs());
601.109 - assertEquals(null, call.getType());
601.110 - }
601.111 -
601.112 - public void testCall2d() throws Exception {
601.113 - Call call = getCall("xy.^ ");
601.114 - assertEquals("xy", call.getLhs());
601.115 - assertEquals(null, call.getType());
601.116 - }
601.117 -
601.118 - public void testCall3() throws Exception {
601.119 - Call call = getCall("\"foo\".gsu^");
601.120 - assertEquals("StringType", call.getType());
601.121 - assertFalse(call.isSimpleIdentifier());
601.122 - assertFalse(call.isStatic());
601.123 - }
601.124 -
601.125 - public void testCall3b() throws Exception {
601.126 - Call call = getCall("\"foo\".^");
601.127 - assertEquals("StringType", call.getType());
601.128 - assertFalse(call.isSimpleIdentifier());
601.129 - assertFalse(call.isStatic());
601.130 - }
601.131 -
601.132 - public void testCall5() throws Exception {
601.133 - Call call = getCall("[1,2,3].each^");
601.134 - assertEquals("ListType", call.getType());
601.135 - assertFalse(call.isSimpleIdentifier());
601.136 - assertFalse(call.isStatic());
601.137 - }
601.138 -
601.139 - public void testCall5b() throws Exception {
601.140 - Call call = getCall("[1,2,3].^");
601.141 - assertEquals("ListType", call.getType());
601.142 - assertFalse(call.isSimpleIdentifier());
601.143 - assertFalse(call.isStatic());
601.144 - }
601.145 -
601.146 - public void testCall6() throws Exception {
601.147 - Call call = getCall("{:x=>:y}.foo^");
601.148 - assertEquals("DictType", call.getType());
601.149 - assertFalse(call.isSimpleIdentifier());
601.150 - assertFalse(call.isStatic());
601.151 - }
601.152 -
601.153 - public void testCall6b() throws Exception {
601.154 - Call call = getCall("{:x=>:y}.^");
601.155 - assertEquals("DictType", call.getType());
601.156 - assertFalse(call.isSimpleIdentifier());
601.157 - assertFalse(call.isStatic());
601.158 - }
601.159 -
601.160 - public void testCalll2() throws Exception {
601.161 - Call call = getCall("True.foo^");
601.162 - assertEquals("BooleanType", call.getType());
601.163 - assertFalse(call.isSimpleIdentifier());
601.164 - assertFalse(call.isStatic());
601.165 - }
601.166 -
601.167 - public void testCalll2b() throws Exception {
601.168 - Call call = getCall("True.^");
601.169 - assertEquals("BooleanType", call.getType());
601.170 - assertFalse(call.isSimpleIdentifier());
601.171 - assertFalse(call.isStatic());
601.172 - }
601.173 -
601.174 - public void testCalll3() throws Exception {
601.175 - Call call = getCall("False.foo^");
601.176 - assertEquals("BooleanType", call.getType());
601.177 - assertFalse(call.isSimpleIdentifier());
601.178 - assertFalse(call.isStatic());
601.179 - }
601.180 -
601.181 - public void testCalll3b() throws Exception {
601.182 - Call call = getCall("False.^");
601.183 - assertEquals("BooleanType", call.getType());
601.184 - assertFalse(call.isSimpleIdentifier());
601.185 - assertFalse(call.isStatic());
601.186 - }
601.187 -
601.188 - public void testCall14() throws Exception {
601.189 - Call call = getCall("self.foo^");
601.190 - assertEquals("self", call.getType());
601.191 - assertEquals("self", call.getLhs());
601.192 - }
601.193 -
601.194 - public void testCall14b() throws Exception {
601.195 - Call call = getCall("self.^");
601.196 - assertEquals("self", call.getType());
601.197 - assertEquals("self", call.getLhs());
601.198 - }
601.199 -
601.200 - public void testCalll5() throws Exception {
601.201 - Call call = getCall("super.foo^");
601.202 - assertEquals("super", call.getType());
601.203 - assertEquals("super", call.getLhs());
601.204 - }
601.205 -
601.206 - public void testCalll5b() throws Exception {
601.207 - Call call = getCall("super.^");
601.208 - assertEquals("super", call.getType());
601.209 - assertEquals("super", call.getLhs());
601.210 - }
601.211 -
601.212 - public void testCall20() throws Exception {
601.213 - Call call = getCall("foo.bar.ex^");
601.214 - assertEquals("foo.bar", call.getLhs());
601.215 - assertEquals(null, call.getType());
601.216 - }
601.217 -
601.218 - public void testCallUnknown() throws Exception {
601.219 - Call call = getCall("getFoo().x^");
601.220 - assertSame(Call.UNKNOWN, call);
601.221 - }
601.222 -
601.223 - public void testCallLocal() throws Exception {
601.224 - Call call = getCall("foo^");
601.225 - assertSame(Call.LOCAL, call);
601.226 - }
601.227 -
601.228 - public void testCallOperator1() throws Exception {
601.229 - Call call = getCall("=foo^");
601.230 - assertSame(Call.LOCAL, call);
601.231 - }
601.232 -
601.233 - public void testCallOperator2() throws Exception {
601.234 - Call call = getCall("+foo^");
601.235 - assertSame(Call.LOCAL, call);
601.236 - }
601.237 -
601.238 - public void testCallOperator3() throws Exception {
601.239 - Call call = getCall("=SocketServer.^");
601.240 - assertEquals("SocketServer", call.getLhs());
601.241 - assertEquals("SocketServer", call.getType());
601.242 - }
601.243 -
601.244 - public void testParen() throws Exception {
601.245 - Call call = getCall("(SocketServer.^");
601.246 - assertEquals("SocketServer", call.getLhs());
601.247 - assertEquals("SocketServer", call.getType());
601.248 - }
601.249 -
601.250 - public void testParen2() throws Exception {
601.251 - Call call = getCall("[SocketServer.^");
601.252 - assertEquals("SocketServer", call.getLhs());
601.253 - assertEquals("SocketServer", call.getType());
601.254 - }
601.255 -
601.256 - // TODO - test complex numbers and tuples, lists and dicts,
601.257 - // etc. See http://www.python.org/doc/2.5.2/lib/module-types.html
601.258 -}
602.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/lexer/PythonCommentLexerTest.java Sun Jan 04 13:11:53 2015 -0600
602.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
602.3 @@ -1,202 +0,0 @@
602.4 -/*
602.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
602.6 - *
602.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
602.8 - *
602.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
602.10 - * Other names may be trademarks of their respective owners.
602.11 - *
602.12 - * The contents of this file are subject to the terms of either the GNU
602.13 - * General Public License Version 2 only ("GPL") or the Common
602.14 - * Development and Distribution License("CDDL") (collectively, the
602.15 - * "License"). You may not use this file except in compliance with the
602.16 - * License. You can obtain a copy of the License at
602.17 - * http://www.netbeans.org/cddl-gplv2.html
602.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
602.19 - * specific language governing permissions and limitations under the
602.20 - * License. When distributing the software, include this License Header
602.21 - * Notice in each file and include the License file at
602.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
602.23 - * particular file as subject to the "Classpath" exception as provided
602.24 - * by Oracle in the GPL Version 2 section of the License file that
602.25 - * accompanied this code. If applicable, add the following below the
602.26 - * License Header, with the fields enclosed by brackets [] replaced by
602.27 - * your own identifying information:
602.28 - * "Portions Copyrighted [year] [name of copyright owner]"
602.29 - *
602.30 - * If you wish your version of this file to be governed by only the CDDL
602.31 - * or only the GPL Version 2, indicate your decision by adding
602.32 - * "[Contributor] elects to include this software in this distribution
602.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
602.34 - * single choice of license, a recipient has the option to distribute
602.35 - * your version of this file under either the CDDL, the GPL Version 2 or
602.36 - * to extend the choice of license to its licensees as provided above.
602.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
602.38 - * Version 2 license, then the option applies only if the new code is
602.39 - * made subject to such option by the copyright holder.
602.40 - *
602.41 - * Contributor(s):
602.42 - *
602.43 - * Portions Copyrighted 2009 Sun Microsystems, Inc.
602.44 - */
602.45 -
602.46 -package org.netbeans.modules.python.editor.lexer;
602.47 -
602.48 -import java.util.logging.Level;
602.49 -import java.util.logging.Logger;
602.50 -import org.netbeans.api.lexer.TokenHierarchy;
602.51 -import org.netbeans.api.lexer.TokenSequence;
602.52 -import org.netbeans.junit.NbTestCase;
602.53 -import org.netbeans.lib.lexer.test.LexerTestUtilities;
602.54 -
602.55 -/**
602.56 - *
602.57 - * @author tor
602.58 - */
602.59 -public class PythonCommentLexerTest extends NbTestCase{
602.60 -
602.61 - public PythonCommentLexerTest(String testName) {
602.62 - super(testName);
602.63 - }
602.64 -
602.65 - @Override
602.66 - protected void setUp() throws java.lang.Exception {
602.67 - Logger.getLogger(PythonLexer.class.getName()).setLevel(Level.FINEST);
602.68 - }
602.69 -
602.70 - @Override
602.71 - protected void tearDown() throws java.lang.Exception {
602.72 - }
602.73 -
602.74 - @Override
602.75 - protected Level logLevel() {
602.76 - // enabling logging
602.77 - return Level.INFO; // uncomment this to have logging from PyhonLexer
602.78 - // we are only interested in a single logger, so we set its level in setUp(),
602.79 - // as returning Level.FINEST here would log from all loggers
602.80 - }
602.81 -
602.82 - public void testTypeVars() {
602.83 - String text = "Whatever @type foo int bye";
602.84 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
602.85 - TokenSequence ts = hi.tokenSequence();
602.86 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
602.87 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPEKEY, "@type");
602.88 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
602.89 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.VARNAME, "foo");
602.90 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
602.91 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPE, "int");
602.92 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, " bye");
602.93 - assertFalse(ts.moveNext());
602.94 - }
602.95 -
602.96 - public void testTypeVarsWithColon() {
602.97 - String text = "Whatever @type foo: int bye";
602.98 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
602.99 - TokenSequence ts = hi.tokenSequence();
602.100 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
602.101 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPEKEY, "@type");
602.102 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
602.103 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.VARNAME, "foo");
602.104 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, ": ");
602.105 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPE, "int");
602.106 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, " bye");
602.107 - assertFalse(ts.moveNext());
602.108 - }
602.109 -
602.110 - public void testTodo() {
602.111 - String text = "Whatever TODO this TODOS SANTOS TODO";
602.112 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
602.113 - TokenSequence ts = hi.tokenSequence();
602.114 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
602.115 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TODO, "TODO");
602.116 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, " this TODOS SANTOS ");
602.117 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TODO, "TODO");
602.118 - assertFalse(ts.moveNext());
602.119 - }
602.120 -
602.121 - public void testTodo2() {
602.122 - String text = "STODO"; // Not a TODO
602.123 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
602.124 - TokenSequence ts = hi.tokenSequence();
602.125 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "STODO");
602.126 - assertFalse(ts.moveNext());
602.127 - }
602.128 -
602.129 - public void testEof1() {
602.130 - String text = "Whatever @type foo int ";
602.131 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
602.132 - TokenSequence ts = hi.tokenSequence();
602.133 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
602.134 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPEKEY, "@type");
602.135 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
602.136 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.VARNAME, "foo");
602.137 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
602.138 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPE, "int");
602.139 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, " ");
602.140 - assertFalse(ts.moveNext());
602.141 - }
602.142 -
602.143 - public void testEof2() {
602.144 - String text = "Whatever @type foo int";
602.145 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
602.146 - TokenSequence ts = hi.tokenSequence();
602.147 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
602.148 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPEKEY, "@type");
602.149 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
602.150 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.VARNAME, "foo");
602.151 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
602.152 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPE, "int");
602.153 - assertFalse(ts.moveNext());
602.154 - }
602.155 -
602.156 - public void testEof3() {
602.157 - String text = "Whatever @type foo ";
602.158 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
602.159 - TokenSequence ts = hi.tokenSequence();
602.160 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
602.161 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPEKEY, "@type");
602.162 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
602.163 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.VARNAME, "foo");
602.164 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
602.165 - assertFalse(ts.moveNext());
602.166 - }
602.167 -
602.168 - public void testEof4() {
602.169 - String text = "Whatever @type foo";
602.170 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
602.171 - TokenSequence ts = hi.tokenSequence();
602.172 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
602.173 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPEKEY, "@type");
602.174 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
602.175 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.VARNAME, "foo");
602.176 - assertFalse(ts.moveNext());
602.177 - }
602.178 -
602.179 - public void testEof5() {
602.180 - String text = "Whatever @type ";
602.181 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
602.182 - TokenSequence ts = hi.tokenSequence();
602.183 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
602.184 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPEKEY, "@type");
602.185 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.SEPARATOR, " ");
602.186 - assertFalse(ts.moveNext());
602.187 - }
602.188 -
602.189 - public void testEof6() {
602.190 - String text = "Whatever @type";
602.191 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
602.192 - TokenSequence ts = hi.tokenSequence();
602.193 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
602.194 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TYPEKEY, "@type");
602.195 - assertFalse(ts.moveNext());
602.196 - }
602.197 -
602.198 - public void testEof7() {
602.199 - String text = "Whatever ";
602.200 - TokenHierarchy hi = TokenHierarchy.create(text, PythonCommentTokenId.language());
602.201 - TokenSequence ts = hi.tokenSequence();
602.202 - LexerTestUtilities.assertNextTokenEquals(ts, PythonCommentTokenId.TEXT, "Whatever ");
602.203 - assertFalse(ts.moveNext());
602.204 - }
602.205 -}
603.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/lexer/PythonIncrementalLexingTest.java Sun Jan 04 13:11:53 2015 -0600
603.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
603.3 @@ -1,124 +0,0 @@
603.4 -/*
603.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
603.6 - *
603.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
603.8 - *
603.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
603.10 - * Other names may be trademarks of their respective owners.
603.11 - *
603.12 - * The contents of this file are subject to the terms of either the GNU
603.13 - * General Public License Version 2 only ("GPL") or the Common
603.14 - * Development and Distribution License("CDDL") (collectively, the
603.15 - * "License"). You may not use this file except in compliance with the
603.16 - * License. You can obtain a copy of the License at
603.17 - * http://www.netbeans.org/cddl-gplv2.html
603.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
603.19 - * specific language governing permissions and limitations under the
603.20 - * License. When distributing the software, include this License Header
603.21 - * Notice in each file and include the License file at
603.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
603.23 - * particular file as subject to the "Classpath" exception as provided
603.24 - * by Oracle in the GPL Version 2 section of the License file that
603.25 - * accompanied this code. If applicable, add the following below the
603.26 - * License Header, with the fields enclosed by brackets [] replaced by
603.27 - * your own identifying information:
603.28 - * "Portions Copyrighted [year] [name of copyright owner]"
603.29 - *
603.30 - * Contributor(s):
603.31 - *
603.32 - * The Original Software is NetBeans. The Initial Developer of the Original
603.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
603.34 - * Microsystems, Inc. All Rights Reserved.
603.35 - *
603.36 - * If you wish your version of this file to be governed by only the CDDL
603.37 - * or only the GPL Version 2, indicate your decision by adding
603.38 - * "[Contributor] elects to include this software in this distribution
603.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
603.40 - * single choice of license, a recipient has the option to distribute
603.41 - * your version of this file under either the CDDL, the GPL Version 2 or
603.42 - * to extend the choice of license to its licensees as provided above.
603.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
603.44 - * Version 2 license, then the option applies only if the new code is
603.45 - * made subject to such option by the copyright holder.
603.46 - */
603.47 -
603.48 -package org.netbeans.modules.python.editor.lexer;
603.49 -
603.50 -import junit.framework.TestCase;
603.51 -// Grr, this doesn't work outside the NB build tree!!! GRRRR
603.52 -import org.netbeans.lib.lexer.test.FixedTextDescriptor;
603.53 -import org.netbeans.lib.lexer.test.RandomCharDescriptor;
603.54 -import org.netbeans.lib.lexer.test.RandomModifyDescriptor;
603.55 -import org.netbeans.lib.lexer.test.RandomTextProvider;
603.56 -import org.netbeans.lib.lexer.test.TestRandomModify;
603.57 -
603.58 -/**
603.59 - * Randomly edit the document and test the incremental operation
603.60 - *
603.61 - */
603.62 -public class PythonIncrementalLexingTest extends TestCase {
603.63 -
603.64 - public PythonIncrementalLexingTest(String testName) {
603.65 - super(testName);
603.66 - }
603.67 -
603.68 - @Override
603.69 - protected void setUp() throws java.lang.Exception {
603.70 - // Set-up testing environment
603.71 - System.setProperty("netbeans.debug.lexer.test", "true");
603.72 - }
603.73 -
603.74 - public void testRandom() throws Exception {
603.75 - test(0);
603.76 - }
603.77 -
603.78 - private void test(long seed) throws Exception {
603.79 - TestRandomModify randomModify = new TestRandomModify(seed);
603.80 - randomModify.setLanguage(PythonTokenId.language());
603.81 -
603.82 - //randomModify.setDebugOperation(true);
603.83 - //randomModify.setDebugDocumentText(true);
603.84 - //randomModify.setDebugHierarchy(true);
603.85 -
603.86 - FixedTextDescriptor[] fixedTexts = new FixedTextDescriptor[] {
603.87 - FixedTextDescriptor.create("'''", 0.2),
603.88 - FixedTextDescriptor.create("<=", 0.2),
603.89 - };
603.90 -
603.91 - RandomCharDescriptor[] regularChars = new RandomCharDescriptor[] {
603.92 - RandomCharDescriptor.letter(0.3),
603.93 - RandomCharDescriptor.space(0.3),
603.94 - RandomCharDescriptor.lf(0.3),
603.95 - RandomCharDescriptor.chars(new char[] { '+', '-', '*', '/', ':'}, 0.3),
603.96 - };
603.97 -
603.98 - RandomCharDescriptor[] anyChar = new RandomCharDescriptor[] {
603.99 - RandomCharDescriptor.anyChar(1.0),
603.100 - };
603.101 -
603.102 - RandomTextProvider regularTextProvider = new RandomTextProvider(regularChars, fixedTexts);
603.103 - RandomTextProvider anyCharTextProvider = new RandomTextProvider(anyChar, fixedTexts);
603.104 -
603.105 - randomModify.test(
603.106 - new RandomModifyDescriptor[] {
603.107 - new RandomModifyDescriptor(1000, regularTextProvider,
603.108 - 0.2, 0.2, 0.1,
603.109 - 0.2, 0.2,
603.110 - 0.0, 0.0),
603.111 - }
603.112 - );
603.113 -
603.114 - randomModify.test(
603.115 - new RandomModifyDescriptor[] {
603.116 - new RandomModifyDescriptor(1000, anyCharTextProvider,
603.117 - 0.4, 0.2, 0.2,
603.118 - 0.1, 0.1,
603.119 - 0.0, 0.0),
603.120 - new RandomModifyDescriptor(1000, anyCharTextProvider,
603.121 - 0.2, 0.2, 0.1,
603.122 - 0.4, 0.3,
603.123 - 0.0, 0.0),
603.124 - }
603.125 - );
603.126 - }
603.127 -}
604.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/lexer/PythonLexerTest.java Sun Jan 04 13:11:53 2015 -0600
604.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
604.3 @@ -1,421 +0,0 @@
604.4 -/*
604.5 - * To change this template, choose Tools | Templates
604.6 - * and open the template in the editor.
604.7 - */
604.8 -
604.9 -package org.netbeans.modules.python.editor.lexer;
604.10 -
604.11 -
604.12 -import java.util.ConcurrentModificationException;
604.13 -import javax.swing.text.BadLocationException;
604.14 -import java.util.logging.Level;
604.15 -import java.util.logging.Logger;
604.16 -import javax.swing.text.Document;
604.17 -import org.netbeans.api.lexer.Language;
604.18 -import org.netbeans.api.lexer.TokenHierarchy;
604.19 -import org.netbeans.api.lexer.TokenSequence;
604.20 -import org.netbeans.junit.NbTestCase;
604.21 -import org.netbeans.lib.lexer.test.LexerTestUtilities;
604.22 -import org.netbeans.lib.lexer.test.ModificationTextDocument;
604.23 -
604.24 -/**
604.25 - *
604.26 - * @author Tor Norbye
604.27 - */
604.28 -public class PythonLexerTest extends NbTestCase {
604.29 -
604.30 - public PythonLexerTest(String testName) {
604.31 - super(testName);
604.32 - }
604.33 -
604.34 - @Override
604.35 - protected void setUp() throws java.lang.Exception {
604.36 - Logger.getLogger(PythonLexer.class.getName()).setLevel(Level.FINEST);
604.37 - }
604.38 -
604.39 - @Override
604.40 - protected void tearDown() throws java.lang.Exception {
604.41 - }
604.42 -
604.43 - @Override
604.44 - protected Level logLevel() {
604.45 - // enabling logging
604.46 - return Level.INFO; // uncomment this to have logging from PyhonLexer
604.47 - // we are only interested in a single logger, so we set its level in setUp(),
604.48 - // as returning Level.FINEST here would log from all loggers
604.49 - }
604.50 -
604.51 - public void test1() {
604.52 - String text =
604.53 - "# this is the first comment\n" +
604.54 - "SPAM = 1 # and this is the second comment\n" +
604.55 - " # ... and now a third!\n" +
604.56 - "STRING = \"# This is not a comment.\"";
604.57 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.58 - TokenSequence ts = hi.tokenSequence();
604.59 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COMMENT, "# this is the first comment");
604.60 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
604.61 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "SPAM");
604.62 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
604.63 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_OPERATOR, "=");
604.64 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
604.65 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.INT_LITERAL, "1");
604.66 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
604.67 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COMMENT, "# and this is the second comment");
604.68 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
604.69 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
604.70 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COMMENT, "# ... and now a third!");
604.71 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
604.72 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "STRING");
604.73 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
604.74 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_OPERATOR, "=");
604.75 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
604.76 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
604.77 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_LITERAL, "# This is not a comment.");
604.78 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"");
604.79 - }
604.80 -
604.81 - public void test2() {
604.82 - String text =
604.83 - "#! /usr/bin/python\n" +
604.84 - "print \"Hello World!\"\t\n";
604.85 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.86 - TokenSequence ts = hi.tokenSequence();
604.87 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COMMENT, "#! /usr/bin/python");
604.88 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
604.89 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_KEYWORD, "print");
604.90 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
604.91 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
604.92 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_LITERAL, "Hello World!");
604.93 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"");
604.94 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, "\t");
604.95 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
604.96 - assertFalse(ts.moveNext());
604.97 - }
604.98 -
604.99 - public void test3() {
604.100 - String text =
604.101 - "#! /usr/bin/python\n" +
604.102 - "print \"Hello World!\"\t";
604.103 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.104 - TokenSequence ts = hi.tokenSequence();
604.105 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COMMENT, "#! /usr/bin/python");
604.106 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
604.107 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_KEYWORD, "print");
604.108 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
604.109 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
604.110 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_LITERAL, "Hello World!");
604.111 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"");
604.112 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, "\t");
604.113 - assertFalse(ts.moveNext());
604.114 - }
604.115 -
604.116 - public void test4() throws BadLocationException {
604.117 - Document doc = new ModificationTextDocument();
604.118 - // Assign a language to the document
604.119 - doc.putProperty(Language.class, PythonTokenId.language());
604.120 - TokenHierarchy<?> hi = TokenHierarchy.get(doc);
604.121 - assertNotNull("Null token hierarchy for document", hi);
604.122 - TokenSequence<?> ts = hi.tokenSequence();
604.123 -
604.124 - // Newline in empty doc: this started happening around June 1st 2009
604.125 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
604.126 -
604.127 - assertFalse(ts.moveNext());
604.128 -
604.129 - // Insert text into document
604.130 - String text =
604.131 - "#! /usr/bin/python\n" +
604.132 - "print \"Hello World!\"";
604.133 - doc.insertString(0, text, null);
604.134 -
604.135 - // Last token sequence should throw exception - new must be obtained
604.136 - try {
604.137 - ts.moveNext();
604.138 - fail("TokenSequence.moveNext() did not throw exception as expected.");
604.139 - } catch (ConcurrentModificationException e) {
604.140 - // Expected exception
604.141 - }
604.142 -
604.143 - ts = hi.tokenSequence();
604.144 -
604.145 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COMMENT, "#! /usr/bin/python");
604.146 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
604.147 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_KEYWORD, "print");
604.148 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
604.149 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
604.150 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_LITERAL, "Hello World!");
604.151 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"");
604.152 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
604.153 -
604.154 - assertFalse(ts.moveNext());
604.155 -
604.156 - LexerTestUtilities.incCheck(doc, false);
604.157 -
604.158 - int offset = text.length() - 1;
604.159 -
604.160 - doc.remove(offset, 1);
604.161 -
604.162 - ts = hi.tokenSequence();
604.163 -
604.164 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COMMENT, "#! /usr/bin/python");
604.165 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
604.166 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_KEYWORD, "print");
604.167 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
604.168 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
604.169 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ERROR, "Hello World!\n");
604.170 -
604.171 - assertFalse(ts.moveNext());
604.172 -
604.173 - LexerTestUtilities.incCheck(doc, false);
604.174 - }
604.175 -
604.176 - public void testSpecialChars() {
604.177 - String text =
604.178 - "x(3,2.0)\n" +
604.179 - "if (foo.bar[0]):\n";
604.180 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.181 - TokenSequence ts = hi.tokenSequence();
604.182 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "x");
604.183 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.LPAREN, "(");
604.184 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.INT_LITERAL, "3");
604.185 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COMMA, ",");
604.186 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.FLOAT_LITERAL, "2.0");
604.187 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.RPAREN, ")");
604.188 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
604.189 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IF, "if");
604.190 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
604.191 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.LPAREN, "(");
604.192 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "foo");
604.193 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.DOT, ".");
604.194 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "bar");
604.195 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.LBRACKET, "[");
604.196 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.INT_LITERAL, "0");
604.197 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.RBRACKET, "]");
604.198 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.RPAREN, ")");
604.199 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COLON, ":");
604.200 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
604.201 - assertFalse(ts.moveNext());
604.202 - }
604.203 -
604.204 - public void testStrings1() {
604.205 - String text =
604.206 - "x=UR'''this is\na\nstring\\nwith\\n\\nescapes\n '''";
604.207 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.208 - TokenSequence ts = hi.tokenSequence();
604.209 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "x");
604.210 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_OPERATOR, "=");
604.211 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "UR'''");
604.212 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_LITERAL, "this is\na\nstring\\nwith\\n\\nescapes\n ");
604.213 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "'''");
604.214 - assertFalse(ts.moveNext());
604.215 - }
604.216 -
604.217 - public void testStrings2() {
604.218 - String text =
604.219 - "x=UR'''this is\na\nstring\\nwith\\n\\nescapes\n ";
604.220 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.221 - TokenSequence ts = hi.tokenSequence();
604.222 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "x");
604.223 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_OPERATOR, "=");
604.224 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "UR'''");
604.225 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ERROR, "this is\na\nstring\\nwith\\n\\nescapes\n ");
604.226 - assertFalse(ts.moveNext());
604.227 - }
604.228 -
604.229 - public void testStrings3() {
604.230 - String text =
604.231 - "x=UR\"\"\"this is\na\nstring\\nwith\\n\\nescapes\n \"\"\"";
604.232 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.233 - TokenSequence ts = hi.tokenSequence();
604.234 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "x");
604.235 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_OPERATOR, "=");
604.236 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "UR\"\"\"");
604.237 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_LITERAL, "this is\na\nstring\\nwith\\n\\nescapes\n ");
604.238 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"\"\"");
604.239 - assertFalse(ts.moveNext());
604.240 - }
604.241 -
604.242 - public void testStrings4() {
604.243 - String text =
604.244 - "x=R\"\"\"this is\na\nstring\\nwith\\n\\nescapes\n \"\"\"";
604.245 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.246 - TokenSequence ts = hi.tokenSequence();
604.247 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "x");
604.248 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_OPERATOR, "=");
604.249 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "R\"\"\"");
604.250 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_LITERAL, "this is\na\nstring\\nwith\\n\\nescapes\n ");
604.251 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"\"\"");
604.252 - assertFalse(ts.moveNext());
604.253 - }
604.254 -
604.255 - public void testStrings5() {
604.256 - String text =
604.257 - "x=u\"\"\"this is\na\nstring\\nwith\\n\\nescapes\n \"\"\"";
604.258 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.259 - TokenSequence ts = hi.tokenSequence();
604.260 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "x");
604.261 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_OPERATOR, "=");
604.262 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "u\"\"\"");
604.263 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_LITERAL, "this is\na\nstring\\nwith\\n\\nescapes\n ");
604.264 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"\"\"");
604.265 - assertFalse(ts.moveNext());
604.266 - }
604.267 -
604.268 - public void testDotPrefix() {
604.269 - String text =
604.270 - ".5";
604.271 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.272 - TokenSequence ts = hi.tokenSequence();
604.273 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.FLOAT_LITERAL, ".5");
604.274 - assertFalse(ts.moveNext());
604.275 -
604.276 - text = "x.y";
604.277 - hi = TokenHierarchy.create(text, PythonTokenId.language());
604.278 - ts = hi.tokenSequence();
604.279 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "x");
604.280 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.DOT, ".");
604.281 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "y");
604.282 - assertFalse(ts.moveNext());
604.283 - }
604.284 -
604.285 - public void testExponential() {
604.286 - String text =
604.287 - "1e100";
604.288 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.289 - TokenSequence ts = hi.tokenSequence();
604.290 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.FLOAT_LITERAL, "1e100");
604.291 - assertFalse(ts.moveNext());
604.292 - }
604.293 -
604.294 - public void testExponential2() {
604.295 - String text =
604.296 - "3.14e-10";
604.297 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.298 - TokenSequence ts = hi.tokenSequence();
604.299 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.FLOAT_LITERAL, "3.14e-10");
604.300 - assertFalse(ts.moveNext());
604.301 - }
604.302 -
604.303 - public void testImaginary() {
604.304 - String text =
604.305 - "3.14e-10j";
604.306 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.307 - TokenSequence ts = hi.tokenSequence();
604.308 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.FLOAT_LITERAL, "3.14e-10j");
604.309 - assertFalse(ts.moveNext());
604.310 - }
604.311 -
604.312 - public void testChars1() {
604.313 - String text =
604.314 - "x = \"\"";
604.315 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.316 - TokenSequence ts = hi.tokenSequence();
604.317 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "x");
604.318 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
604.319 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_OPERATOR, "=");
604.320 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
604.321 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
604.322 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"");
604.323 - assertFalse(ts.moveNext());
604.324 - }
604.325 -
604.326 - public void testChars2() {
604.327 - String text =
604.328 - "x = \"'\"";
604.329 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.330 - TokenSequence ts = hi.tokenSequence();
604.331 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "x");
604.332 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
604.333 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ANY_OPERATOR, "=");
604.334 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
604.335 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
604.336 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_LITERAL, "'");
604.337 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"");
604.338 - assertFalse(ts.moveNext());
604.339 - }
604.340 -
604.341 - public void testCornerCases() {
604.342 - String text =
604.343 - "\"";
604.344 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.345 - TokenSequence ts = hi.tokenSequence();
604.346 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
604.347 - assertFalse(ts.moveNext());
604.348 - }
604.349 -
604.350 - public void testCornerCases2() {
604.351 - String text =
604.352 - "\"foo";
604.353 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.354 - TokenSequence ts = hi.tokenSequence();
604.355 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
604.356 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.ERROR, "foo");
604.357 - assertFalse(ts.moveNext());
604.358 - }
604.359 -
604.360 - public void testEmptyString1() {
604.361 - String text =
604.362 - "\"\"\"\"\"\"";
604.363 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.364 - TokenSequence ts = hi.tokenSequence();
604.365 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"\"\"");
604.366 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"\"\"");
604.367 - assertFalse(ts.moveNext());
604.368 - }
604.369 -
604.370 - public void testEmptyString2() {
604.371 - String text =
604.372 - "''''''";
604.373 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.374 - TokenSequence ts = hi.tokenSequence();
604.375 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "'''");
604.376 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "'''");
604.377 - assertFalse(ts.moveNext());
604.378 - }
604.379 -
604.380 - public void testEmptyString3() {
604.381 - String text =
604.382 - "''";
604.383 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.384 - TokenSequence ts = hi.tokenSequence();
604.385 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "'");
604.386 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "'");
604.387 - assertFalse(ts.moveNext());
604.388 - }
604.389 -
604.390 - public void testEmptyString4() {
604.391 - String text =
604.392 - "\"\"";
604.393 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.394 - TokenSequence ts = hi.tokenSequence();
604.395 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_BEGIN, "\"");
604.396 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.STRING_END, "\"");
604.397 - assertFalse(ts.moveNext());
604.398 - }
604.399 -
604.400 - public void testDecorators1() {
604.401 - String text =
604.402 - "@foo\ndef bar:\n";
604.403 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.404 - TokenSequence ts = hi.tokenSequence();
604.405 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.DECORATOR, "@foo");
604.406 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
604.407 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.DEF, "def");
604.408 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.WHITESPACE, " ");
604.409 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.IDENTIFIER, "bar");
604.410 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COLON, ":");
604.411 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.NEWLINE, "\n");
604.412 - assertFalse(ts.moveNext());
604.413 - }
604.414 -
604.415 - public void testDecorators2() {
604.416 - String text =
604.417 - "@,";
604.418 - TokenHierarchy hi = TokenHierarchy.create(text, PythonTokenId.language());
604.419 - TokenSequence ts = hi.tokenSequence();
604.420 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.DECORATOR, "@");
604.421 - LexerTestUtilities.assertNextTokenEquals(ts, PythonTokenId.COMMA, ",");
604.422 - assertFalse(ts.moveNext());
604.423 - }
604.424 -}
605.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/lexer/PythonLexerUtilsTest.java Sun Jan 04 13:11:53 2015 -0600
605.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
605.3 @@ -1,225 +0,0 @@
605.4 -/*
605.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
605.6 - *
605.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
605.8 - *
605.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
605.10 - * Other names may be trademarks of their respective owners.
605.11 - *
605.12 - * The contents of this file are subject to the terms of either the GNU
605.13 - * General Public License Version 2 only ("GPL") or the Common
605.14 - * Development and Distribution License("CDDL") (collectively, the
605.15 - * "License"). You may not use this file except in compliance with the
605.16 - * License. You can obtain a copy of the License at
605.17 - * http://www.netbeans.org/cddl-gplv2.html
605.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
605.19 - * specific language governing permissions and limitations under the
605.20 - * License. When distributing the software, include this License Header
605.21 - * Notice in each file and include the License file at
605.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
605.23 - * particular file as subject to the "Classpath" exception as provided
605.24 - * by Oracle in the GPL Version 2 section of the License file that
605.25 - * accompanied this code. If applicable, add the following below the
605.26 - * License Header, with the fields enclosed by brackets [] replaced by
605.27 - * your own identifying information:
605.28 - * "Portions Copyrighted [year] [name of copyright owner]"
605.29 - *
605.30 - * If you wish your version of this file to be governed by only the CDDL
605.31 - * or only the GPL Version 2, indicate your decision by adding
605.32 - * "[Contributor] elects to include this software in this distribution
605.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
605.34 - * single choice of license, a recipient has the option to distribute
605.35 - * your version of this file under either the CDDL, the GPL Version 2 or
605.36 - * to extend the choice of license to its licensees as provided above.
605.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
605.38 - * Version 2 license, then the option applies only if the new code is
605.39 - * made subject to such option by the copyright holder.
605.40 - *
605.41 - * Contributor(s):
605.42 - *
605.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
605.44 - */
605.45 -
605.46 -package org.netbeans.modules.python.editor.lexer;
605.47 -
605.48 -import org.netbeans.editor.BaseDocument;
605.49 -import org.netbeans.modules.gsf.api.OffsetRange;
605.50 -import org.netbeans.modules.python.editor.PythonTestBase;
605.51 -
605.52 -/**
605.53 - *
605.54 - * @author Tor Norbye
605.55 - */
605.56 -public class PythonLexerUtilsTest extends PythonTestBase {
605.57 -
605.58 - public PythonLexerUtilsTest(String name) {
605.59 - super(name);
605.60 - }
605.61 -
605.62 - public void testNarrow() throws Exception {
605.63 - BaseDocument doc = getDocument(getTestFile("testfiles/extract1.py"));
605.64 - String s = doc.getText(0, doc.getLength());
605.65 -
605.66 - int start = getCaretOffset(s, "^# Beginning of extraction segment");
605.67 - int end = getCaretOffset(s, "# End of extraction segment^");
605.68 - OffsetRange range = new OffsetRange(start, end);
605.69 -
605.70 - OffsetRange result = PythonLexerUtils.narrow(doc, range, true);
605.71 -
605.72 - OffsetRange expected = new OffsetRange(
605.73 - getCaretOffset(s, "^read_after_block = 5"),
605.74 - getCaretOffset(s, "print param_read_in_block^")
605.75 - );
605.76 -
605.77 - assertEquals(expected, result);
605.78 - }
605.79 -
605.80 - public void testNarrow2() throws Exception {
605.81 - BaseDocument doc = getDocument(getTestFile("testfiles/extract1.py"));
605.82 - String s = doc.getText(0, doc.getLength());
605.83 -
605.84 - int start = getCaretOffset(s, "^read_after_block = 5");
605.85 - int end = getCaretOffset(s, "read_after_block = 5^");
605.86 - OffsetRange range = new OffsetRange(start, end);
605.87 -
605.88 - OffsetRange result = PythonLexerUtils.narrow(doc, range, true);
605.89 -
605.90 - assertEquals(range, result);
605.91 - }
605.92 -
605.93 - public void testNarrow3() throws Exception {
605.94 - BaseDocument doc = getDocument(getTestFile("testfiles/extract1.py"));
605.95 - String s = doc.getText(0, doc.getLength());
605.96 -
605.97 - int start = getCaretOffset(s, "^ read_after_block = 5");
605.98 - int end = getCaretOffset(s, "read_after_block = 5^");
605.99 - OffsetRange range = new OffsetRange(start, end);
605.100 -
605.101 - OffsetRange result = PythonLexerUtils.narrow(doc, range, true);
605.102 -
605.103 - OffsetRange expected = new OffsetRange(
605.104 - getCaretOffset(s, "^read_after_block = 5"),
605.105 - getCaretOffset(s, "read_after_block = 5^")
605.106 - );
605.107 -
605.108 - assertEquals(expected, result);
605.109 - }
605.110 -
605.111 -
605.112 - public void testNarrow4() throws Exception {
605.113 - BaseDocument doc = getDocument(getTestFile("testfiles/extract1.py"));
605.114 - String s = doc.getText(0, doc.getLength());
605.115 -
605.116 - int start = getCaretOffset(s, "= 4\n^");
605.117 - int end = getCaretOffset(s, "^ print local1");
605.118 - OffsetRange range = new OffsetRange(start, end);
605.119 -
605.120 - OffsetRange result = PythonLexerUtils.narrow(doc, range, false);
605.121 -
605.122 - OffsetRange expected = new OffsetRange(
605.123 - getCaretOffset(s, "^# Beginning of extraction segment"),
605.124 - getCaretOffset(s, "# End of extraction segment^")
605.125 - );
605.126 -
605.127 - assertEquals(expected, result);
605.128 - }
605.129 -
605.130 - public void testNarrow5() throws Exception {
605.131 - BaseDocument doc = getDocument(getTestFile("testfiles/extract1.py"));
605.132 - String s = doc.getText(0, doc.getLength());
605.133 -
605.134 - int start = getCaretOffset(s, "r^ead_after_block = 5");
605.135 - int end = getCaretOffset(s, "# End of extraction segment^");
605.136 - OffsetRange range = new OffsetRange(start, end);
605.137 -
605.138 - OffsetRange result = PythonLexerUtils.narrow(doc, range, true);
605.139 - assertEquals(OffsetRange.NONE, result);
605.140 - }
605.141 -
605.142 - public void testNarrow6() throws Exception {
605.143 - BaseDocument doc = getDocument(getTestFile("testfiles/extract1.py"));
605.144 - String s = doc.getText(0, doc.getLength());
605.145 -
605.146 - int start = getCaretOffset(s, "^# Beginning of extraction segment");
605.147 - int end = getCaretOffset(s, "print param_read_in_bloc^k");
605.148 - OffsetRange range = new OffsetRange(start, end);
605.149 -
605.150 - OffsetRange result = PythonLexerUtils.narrow(doc, range, true);
605.151 - assertEquals(OffsetRange.NONE, result);
605.152 - }
605.153 -
605.154 - public void testFindSpaceBegin() {
605.155 - // Spaces in strings don't count
605.156 - String s = "x = 'f oo'";
605.157 - BaseDocument doc = getDocument(s);
605.158 - assertEquals(0, PythonLexerUtils.findSpaceBegin(doc, 0));
605.159 - assertEquals(1, PythonLexerUtils.findSpaceBegin(doc, 1));
605.160 - assertEquals(1, PythonLexerUtils.findSpaceBegin(doc, 2));
605.161 - assertEquals(3, PythonLexerUtils.findSpaceBegin(doc, 3));
605.162 - assertEquals(3, PythonLexerUtils.findSpaceBegin(doc, 4));
605.163 - assertEquals(3, PythonLexerUtils.findSpaceBegin(doc, 5));
605.164 - assertEquals(6, PythonLexerUtils.findSpaceBegin(doc, 6));
605.165 - assertEquals(7, PythonLexerUtils.findSpaceBegin(doc, 7));
605.166 - assertEquals(8, PythonLexerUtils.findSpaceBegin(doc, 8));
605.167 - assertEquals(9, PythonLexerUtils.findSpaceBegin(doc, 9));
605.168 - assertEquals(10, PythonLexerUtils.findSpaceBegin(doc, 10));
605.169 - }
605.170 -
605.171 - public void testFindSpaceBeginNoNewlines() {
605.172 - // Spaces in strings don't count
605.173 - String s = "x = \n 'f oo'";
605.174 - BaseDocument doc = getDocument(s);
605.175 - assertEquals(0, PythonLexerUtils.findSpaceBegin(doc, 0));
605.176 - assertEquals(1, PythonLexerUtils.findSpaceBegin(doc, 1));
605.177 - assertEquals(1, PythonLexerUtils.findSpaceBegin(doc, 2));
605.178 - assertEquals(3, PythonLexerUtils.findSpaceBegin(doc, 3));
605.179 - assertEquals(3, PythonLexerUtils.findSpaceBegin(doc, 4));
605.180 - assertEquals(5, PythonLexerUtils.findSpaceBegin(doc, 5));
605.181 - assertEquals(6, PythonLexerUtils.findSpaceBegin(doc, 6));
605.182 - assertEquals(7, PythonLexerUtils.findSpaceBegin(doc, 7));
605.183 - assertEquals(8, PythonLexerUtils.findSpaceBegin(doc, 8));
605.184 - assertEquals(9, PythonLexerUtils.findSpaceBegin(doc, 9));
605.185 - assertEquals(10, PythonLexerUtils.findSpaceBegin(doc, 10));
605.186 - }
605.187 -
605.188 - public void testFindSpaceBeginNoNewlinesBlank() {
605.189 - String s = "x = \n ";
605.190 - BaseDocument doc = getDocument(s);
605.191 - assertEquals(0, PythonLexerUtils.findSpaceBegin(doc, 0));
605.192 - assertEquals(1, PythonLexerUtils.findSpaceBegin(doc, 1));
605.193 - assertEquals(1, PythonLexerUtils.findSpaceBegin(doc, 2));
605.194 - assertEquals(3, PythonLexerUtils.findSpaceBegin(doc, 3));
605.195 - assertEquals(3, PythonLexerUtils.findSpaceBegin(doc, 4));
605.196 - assertEquals(5, PythonLexerUtils.findSpaceBegin(doc, 5));
605.197 - assertEquals(6, PythonLexerUtils.findSpaceBegin(doc, 6));
605.198 - assertEquals(7, PythonLexerUtils.findSpaceBegin(doc, 7));
605.199 - assertEquals(8, PythonLexerUtils.findSpaceBegin(doc, 8));
605.200 - }
605.201 -
605.202 - public void testFindSpaceBeginLineContinuation() {
605.203 - String s = "foo(a, \n f";
605.204 - BaseDocument doc = getDocument(s);
605.205 - assertEquals(0, PythonLexerUtils.findSpaceBegin(doc, 0));
605.206 - assertEquals(1, PythonLexerUtils.findSpaceBegin(doc, 1));
605.207 - assertEquals(2, PythonLexerUtils.findSpaceBegin(doc, 2));
605.208 - assertEquals(3, PythonLexerUtils.findSpaceBegin(doc, 3));
605.209 - assertEquals(4, PythonLexerUtils.findSpaceBegin(doc, 4));
605.210 - assertEquals(5, PythonLexerUtils.findSpaceBegin(doc, 5));
605.211 - assertEquals(6, PythonLexerUtils.findSpaceBegin(doc, 6));
605.212 - assertEquals(6, PythonLexerUtils.findSpaceBegin(doc, 7));
605.213 - assertEquals(6, PythonLexerUtils.findSpaceBegin(doc, 8));
605.214 - assertEquals(6, PythonLexerUtils.findSpaceBegin(doc, 9));
605.215 - assertEquals(6, PythonLexerUtils.findSpaceBegin(doc, 10));
605.216 - assertEquals(6, PythonLexerUtils.findSpaceBegin(doc, 11));
605.217 - assertEquals(12, PythonLexerUtils.findSpaceBegin(doc, 12));
605.218 - }
605.219 - public void testFindSpaceBeginBlanks() {
605.220 - String s = " \n ";
605.221 - BaseDocument doc = getDocument(s);
605.222 - assertEquals(0, PythonLexerUtils.findSpaceBegin(doc, 0));
605.223 - assertEquals(1, PythonLexerUtils.findSpaceBegin(doc, 1));
605.224 - assertEquals(2, PythonLexerUtils.findSpaceBegin(doc, 2));
605.225 - assertEquals(3, PythonLexerUtils.findSpaceBegin(doc, 3));
605.226 - assertEquals(4, PythonLexerUtils.findSpaceBegin(doc, 4));
605.227 - }
605.228 -}
606.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/lexer/PythonStringLexerTest.java Sun Jan 04 13:11:53 2015 -0600
606.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
606.3 @@ -1,121 +0,0 @@
606.4 -/*
606.5 - * To change this template, choose Tools | Templates
606.6 - * and open the template in the editor.
606.7 - */
606.8 -
606.9 -package org.netbeans.modules.python.editor.lexer;
606.10 -
606.11 -import java.util.logging.Level;
606.12 -import java.util.logging.Logger;
606.13 -import org.netbeans.api.lexer.TokenHierarchy;
606.14 -import org.netbeans.api.lexer.TokenSequence;
606.15 -import org.netbeans.junit.NbTestCase;
606.16 -import org.netbeans.lib.lexer.test.LexerTestUtilities;
606.17 -
606.18 -/**
606.19 - *
606.20 - * @author Tor Norbye
606.21 - */
606.22 -public class PythonStringLexerTest extends NbTestCase {
606.23 -
606.24 - public PythonStringLexerTest(String testName) {
606.25 - super(testName);
606.26 - }
606.27 -
606.28 - @Override
606.29 - protected void setUp() throws java.lang.Exception {
606.30 - Logger.getLogger(PythonStringLexer.class.getName()).setLevel(Level.FINEST);
606.31 - }
606.32 -
606.33 - @Override
606.34 - protected void tearDown() throws java.lang.Exception {
606.35 - }
606.36 -
606.37 - @Override
606.38 - protected Level logLevel() {
606.39 - // enabling logging
606.40 - return Level.INFO; // uncomment this to have logging from PyhonLexer
606.41 - // we are only interested in a single logger, so we set its level in setUp(),
606.42 - // as returning Level.FINEST here would log from all loggers
606.43 - }
606.44 -
606.45 - public void test1() {
606.46 - String text =
606.47 - "\nThis is the \"example\" module.\n\nThe example module supplies one function, factorial(). For example,\n\n>>> factorial(5)120\n";
606.48 - TokenHierarchy hi = TokenHierarchy.create(text, PythonStringTokenId.language);
606.49 - TokenSequence ts = hi.tokenSequence();
606.50 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, "\nThis is the \"example\" module.\n\nThe example module supplies one function, factorial(). For example,\n\n");
606.51 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.EMBEDDED_PYTHON, ">>> factorial(5)120");
606.52 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, "\n");
606.53 - assertFalse(ts.moveNext());
606.54 - }
606.55 -
606.56 - public void test2() {
606.57 - String text =
606.58 - "\n>>\n";
606.59 - TokenHierarchy hi = TokenHierarchy.create(text, PythonStringTokenId.language);
606.60 - TokenSequence ts = hi.tokenSequence();
606.61 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, "\n>>\n");
606.62 - assertFalse(ts.moveNext());
606.63 - }
606.64 -
606.65 - public void test3() {
606.66 - String text =
606.67 - "\n>>>\n";
606.68 - TokenHierarchy hi = TokenHierarchy.create(text, PythonStringTokenId.language);
606.69 - TokenSequence ts = hi.tokenSequence();
606.70 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, "\n");
606.71 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, ">>>\n");
606.72 - assertFalse(ts.moveNext());
606.73 - }
606.74 -
606.75 - public void test4() {
606.76 - String text =
606.77 - "\n>>> \n";
606.78 - TokenHierarchy hi = TokenHierarchy.create(text, PythonStringTokenId.language);
606.79 - TokenSequence ts = hi.tokenSequence();
606.80 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, "\n");
606.81 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, ">>> \n");
606.82 - assertFalse(ts.moveNext());
606.83 - }
606.84 -
606.85 - public void test5() {
606.86 - String text =
606.87 - "\n>>>";
606.88 - TokenHierarchy hi = TokenHierarchy.create(text, PythonStringTokenId.language);
606.89 - TokenSequence ts = hi.tokenSequence();
606.90 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, "\n");
606.91 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, ">>>");
606.92 - assertFalse(ts.moveNext());
606.93 - }
606.94 -
606.95 - public void test6() {
606.96 - String text =
606.97 - "\n>>>>";
606.98 - TokenHierarchy hi = TokenHierarchy.create(text, PythonStringTokenId.language);
606.99 - TokenSequence ts = hi.tokenSequence();
606.100 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, "\n");
606.101 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, ">>>>");
606.102 - assertFalse(ts.moveNext());
606.103 - }
606.104 -
606.105 - public void test8() {
606.106 - String text =
606.107 - "\\";
606.108 - TokenHierarchy hi = TokenHierarchy.create(text, PythonStringTokenId.language);
606.109 - TokenSequence ts = hi.tokenSequence();
606.110 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_INVALID, "\\");
606.111 - assertFalse(ts.moveNext());
606.112 - }
606.113 -
606.114 - public void test9() {
606.115 - String text =
606.116 - "a\\nb";
606.117 - TokenHierarchy hi = TokenHierarchy.create(text, PythonStringTokenId.language);
606.118 - TokenSequence ts = hi.tokenSequence();
606.119 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, "a");
606.120 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_ESCAPE, "\\n");
606.121 - LexerTestUtilities.assertNextTokenEquals(ts, PythonStringTokenId.STRING_TEXT, "b");
606.122 - assertFalse(ts.moveNext());
606.123 - }
606.124 -}
607.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/lexer/PythonStringTokenDumpTest.java Sun Jan 04 13:11:53 2015 -0600
607.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
607.3 @@ -1,69 +0,0 @@
607.4 -/*
607.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
607.6 - *
607.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
607.8 - *
607.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
607.10 - * Other names may be trademarks of their respective owners.
607.11 - *
607.12 - * The contents of this file are subject to the terms of either the GNU
607.13 - * General Public License Version 2 only ("GPL") or the Common
607.14 - * Development and Distribution License("CDDL") (collectively, the
607.15 - * "License"). You may not use this file except in compliance with the
607.16 - * License. You can obtain a copy of the License at
607.17 - * http://www.netbeans.org/cddl-gplv2.html
607.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
607.19 - * specific language governing permissions and limitations under the
607.20 - * License. When distributing the software, include this License Header
607.21 - * Notice in each file and include the License file at
607.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
607.23 - * particular file as subject to the "Classpath" exception as provided
607.24 - * by Oracle in the GPL Version 2 section of the License file that
607.25 - * accompanied this code. If applicable, add the following below the
607.26 - * License Header, with the fields enclosed by brackets [] replaced by
607.27 - * your own identifying information:
607.28 - * "Portions Copyrighted [year] [name of copyright owner]"
607.29 - *
607.30 - * Contributor(s):
607.31 - *
607.32 - * The Original Software is NetBeans. The Initial Developer of the Original
607.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
607.34 - * Microsystems, Inc. All Rights Reserved.
607.35 - *
607.36 - * If you wish your version of this file to be governed by only the CDDL
607.37 - * or only the GPL Version 2, indicate your decision by adding
607.38 - * "[Contributor] elects to include this software in this distribution
607.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
607.40 - * single choice of license, a recipient has the option to distribute
607.41 - * your version of this file under either the CDDL, the GPL Version 2 or
607.42 - * to extend the choice of license to its licensees as provided above.
607.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
607.44 - * Version 2 license, then the option applies only if the new code is
607.45 - * made subject to such option by the copyright holder.
607.46 - */
607.47 -
607.48 -package org.netbeans.modules.python.editor.lexer;
607.49 -
607.50 -import org.netbeans.junit.NbTestCase;
607.51 -import org.netbeans.lib.lexer.test.LexerTestUtilities;
607.52 -
607.53 -/**
607.54 - * Test tokens dump of Python -string- code input.
607.55 - */
607.56 -public class PythonStringTokenDumpTest extends NbTestCase {
607.57 -
607.58 - public PythonStringTokenDumpTest(String testName) {
607.59 - super(testName);
607.60 - }
607.61 -
607.62 - @Override
607.63 - protected void setUp() throws java.lang.Exception {
607.64 - // Set-up testing environment
607.65 - LexerTestUtilities.setTesting(true);
607.66 - }
607.67 -
607.68 - public void testInput() throws Exception {
607.69 - LexerTestUtilities.checkTokenDump(this, "testfiles/syntax-string.py.txt",
607.70 - PythonStringTokenId.language);
607.71 - }
607.72 -}
608.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/lexer/PythonTokenDumpTest.java Sun Jan 04 13:11:53 2015 -0600
608.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
608.3 @@ -1,69 +0,0 @@
608.4 -/*
608.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
608.6 - *
608.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
608.8 - *
608.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
608.10 - * Other names may be trademarks of their respective owners.
608.11 - *
608.12 - * The contents of this file are subject to the terms of either the GNU
608.13 - * General Public License Version 2 only ("GPL") or the Common
608.14 - * Development and Distribution License("CDDL") (collectively, the
608.15 - * "License"). You may not use this file except in compliance with the
608.16 - * License. You can obtain a copy of the License at
608.17 - * http://www.netbeans.org/cddl-gplv2.html
608.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
608.19 - * specific language governing permissions and limitations under the
608.20 - * License. When distributing the software, include this License Header
608.21 - * Notice in each file and include the License file at
608.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
608.23 - * particular file as subject to the "Classpath" exception as provided
608.24 - * by Oracle in the GPL Version 2 section of the License file that
608.25 - * accompanied this code. If applicable, add the following below the
608.26 - * License Header, with the fields enclosed by brackets [] replaced by
608.27 - * your own identifying information:
608.28 - * "Portions Copyrighted [year] [name of copyright owner]"
608.29 - *
608.30 - * Contributor(s):
608.31 - *
608.32 - * The Original Software is NetBeans. The Initial Developer of the Original
608.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
608.34 - * Microsystems, Inc. All Rights Reserved.
608.35 - *
608.36 - * If you wish your version of this file to be governed by only the CDDL
608.37 - * or only the GPL Version 2, indicate your decision by adding
608.38 - * "[Contributor] elects to include this software in this distribution
608.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
608.40 - * single choice of license, a recipient has the option to distribute
608.41 - * your version of this file under either the CDDL, the GPL Version 2 or
608.42 - * to extend the choice of license to its licensees as provided above.
608.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
608.44 - * Version 2 license, then the option applies only if the new code is
608.45 - * made subject to such option by the copyright holder.
608.46 - */
608.47 -
608.48 -package org.netbeans.modules.python.editor.lexer;
608.49 -
608.50 -import org.netbeans.junit.NbTestCase;
608.51 -import org.netbeans.lib.lexer.test.LexerTestUtilities;
608.52 -
608.53 -/**
608.54 - * Test tokens dump of Python code input. Based on Java one by Mila Metelka.
608.55 - */
608.56 -public class PythonTokenDumpTest extends NbTestCase {
608.57 -
608.58 - public PythonTokenDumpTest(String testName) {
608.59 - super(testName);
608.60 - }
608.61 -
608.62 - @Override
608.63 - protected void setUp() throws java.lang.Exception {
608.64 - // Set-up testing environment
608.65 - LexerTestUtilities.setTesting(true);
608.66 - }
608.67 -
608.68 - public void testInput() throws Exception {
608.69 - LexerTestUtilities.checkTokenDump(this, "testfiles/syntax.py.txt",
608.70 - PythonTokenId.language());
608.71 - }
608.72 -}
609.1 --- a/python.editor/test/unit/src/org/netbeans/modules/python/editor/scopes/SymbolTableTest.java Sun Jan 04 13:11:53 2015 -0600
609.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
609.3 @@ -1,265 +0,0 @@
609.4 -/*
609.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
609.6 - *
609.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
609.8 - *
609.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
609.10 - * Other names may be trademarks of their respective owners.
609.11 - *
609.12 - * The contents of this file are subject to the terms of either the GNU
609.13 - * General Public License Version 2 only ("GPL") or the Common
609.14 - * Development and Distribution License("CDDL") (collectively, the
609.15 - * "License"). You may not use this file except in compliance with the
609.16 - * License. You can obtain a copy of the License at
609.17 - * http://www.netbeans.org/cddl-gplv2.html
609.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
609.19 - * specific language governing permissions and limitations under the
609.20 - * License. When distributing the software, include this License Header
609.21 - * Notice in each file and include the License file at
609.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
609.23 - * particular file as subject to the "Classpath" exception as provided
609.24 - * by Oracle in the GPL Version 2 section of the License file that
609.25 - * accompanied this code. If applicable, add the following below the
609.26 - * License Header, with the fields enclosed by brackets [] replaced by
609.27 - * your own identifying information:
609.28 - * "Portions Copyrighted [year] [name of copyright owner]"
609.29 - *
609.30 - * If you wish your version of this file to be governed by only the CDDL
609.31 - * or only the GPL Version 2, indicate your decision by adding
609.32 - * "[Contributor] elects to include this software in this distribution
609.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
609.34 - * single choice of license, a recipient has the option to distribute
609.35 - * your version of this file under either the CDDL, the GPL Version 2 or
609.36 - * to extend the choice of license to its licensees as provided above.
609.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
609.38 - * Version 2 license, then the option applies only if the new code is
609.39 - * made subject to such option by the copyright holder.
609.40 - *
609.41 - * Contributor(s):
609.42 - *
609.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
609.44 - */
609.45 -package org.netbeans.modules.python.editor.scopes;
609.46 -
609.47 -import java.util.ArrayList;
609.48 -import java.util.Collections;
609.49 -import java.util.List;
609.50 -import java.util.Map;
609.51 -import org.netbeans.modules.gsf.GsfTestCompilationInfo;
609.52 -import org.netbeans.modules.gsf.api.NameKind;
609.53 -import org.netbeans.modules.python.editor.AstPath;
609.54 -import org.netbeans.modules.python.editor.PythonAstUtils;
609.55 -import org.netbeans.modules.python.editor.PythonParserResult;
609.56 -import org.netbeans.modules.python.editor.PythonTestBase;
609.57 -import org.netbeans.modules.python.editor.PythonUtils;
609.58 -import org.openide.filesystems.FileObject;
609.59 -import org.openide.filesystems.FileUtil;
609.60 -import org.python.antlr.PythonTree;
609.61 -import org.python.antlr.Visitor;
609.62 -
609.63 -/**
609.64 - *
609.65 - * @author Tor Norbye
609.66 - */
609.67 -public class SymbolTableTest extends PythonTestBase {
609.68 -
609.69 - public SymbolTableTest(String name) {
609.70 - super(name);
609.71 - }
609.72 -
609.73 - @SuppressWarnings("unchecked")
609.74 - public void checkScopes(String relFilePath) throws Exception {
609.75 - GsfTestCompilationInfo info = getInfo(getTestFile(relFilePath));
609.76 - PythonTree root = PythonAstUtils.getRoot(info);
609.77 - assertNotNull(root);
609.78 - PythonParserResult parseResult = PythonAstUtils.getParseResult(info);
609.79 - SymbolTable scopeManager = parseResult.getSymbolTable();
609.80 - Map<PythonTree, ScopeInfo> scopes = scopeManager.getScopes();
609.81 -
609.82 - StringBuilder sb = new StringBuilder();
609.83 - List<PythonTree> nodes = new ArrayList<PythonTree>(scopes.keySet());
609.84 - Collections.sort(nodes, PythonUtils.NODE_POS_COMPARATOR);
609.85 -
609.86 - for (PythonTree node : nodes) {
609.87 - ScopeInfo scope = scopes.get(node);
609.88 - String dump = scope.dump();
609.89 - sb.append(dump);
609.90 - sb.append("\n");
609.91 - }
609.92 -
609.93 - assertDescriptionMatches(relFilePath, sb.toString(), false, ".scopes");
609.94 - }
609.95 -
609.96 - public void testScopes1() throws Exception {
609.97 - checkScopes("testfiles/datetime.py");
609.98 - }
609.99 -
609.100 - public void testScopes2() throws Exception {
609.101 - checkScopes("testfiles/unusedimports1.py");
609.102 - }
609.103 -
609.104 - public void testScopes3() throws Exception {
609.105 - checkScopes("testfiles/compl.py");
609.106 - }
609.107 -
609.108 - public void testScopes4() throws Exception {
609.109 - checkScopes("testfiles/scope.py");
609.110 - }
609.111 -
609.112 - public void testScopes5() throws Exception {
609.113 - checkScopes("testfiles/mimetypes.py");
609.114 - }
609.115 -
609.116 - public void testScopes6() throws Exception {
609.117 - checkScopes("testfiles/scope2.py");
609.118 - }
609.119 -
609.120 - public void testScopes7() throws Exception {
609.121 - checkScopes("testfiles/unresolved.py");
609.122 - }
609.123 -
609.124 - public void testScopes8() throws Exception {
609.125 - checkScopes("testfiles/ConfigParser.py");
609.126 - }
609.127 -
609.128 - public void testScopes9() throws Exception {
609.129 - checkScopes("testfiles/old-decorators1.py");
609.130 - }
609.131 -
609.132 - public void testScopes10() throws Exception {
609.133 - checkScopes("testfiles/old-decorators2.py");
609.134 - }
609.135 -
609.136 - public void testScopes11() throws Exception {
609.137 - // Generates duplicate arg warning!
609.138 - checkScopes("testfiles/formatting.py");
609.139 - }
609.140 -
609.141 - public void testScopes12() throws Exception {
609.142 - // Make sure we handle __all__ generators
609.143 - checkScopes("testfiles/tokenize.py");
609.144 - }
609.145 -
609.146 - public void testScopes13() throws Exception {
609.147 - // Make sure we invalidate the __all__ list if we're messing with it
609.148 - checkScopes("testfiles/os.py");
609.149 - }
609.150 -
609.151 - public void testScopes14() throws Exception {
609.152 - checkScopes("testfiles/zipfile.py");
609.153 - }
609.154 -
609.155 - public void testScopes15() throws Exception {
609.156 - checkScopes("testfiles/scope3.py");
609.157 - }
609.158 -
609.159 - public void testScopes16() throws Exception {
609.160 - checkScopes("testfiles/unittest.py");
609.161 - }
609.162 -
609.163 - public void testScopes17() throws Exception {
609.164 - checkScopes("testfiles/delete2.py");
609.165 - }
609.166 -
609.167 - // Unstable
609.168 - //public void testScopes17() throws Exception {
609.169 - // checkScopes("testfiles/attributes.py");
609.170 - //}
609.171 - //
609.172 - // Unstable
609.173 - //public void testScopes18() throws Exception {
609.174 - // checkScopes("testfiles/decorators.py");
609.175 - //}
609.176 -
609.177 - public void testStress() throws Exception {
609.178 - initializeClassPaths();
609.179 -
609.180 - List<FileObject> files = findJythonFiles();
609.181 -
609.182 - int MAX_FILES = Integer.MAX_VALUE;
609.183 -
609.184 - for (int i = 0; i < files.size() && i < MAX_FILES; i++) {
609.185 - // Don't take too long for regular test runs -- just check 20 files
609.186 - // Comment out occasionally for a full run
609.187 - if (i == 20) {
609.188 - break;
609.189 - }
609.190 - final FileObject fo = files.get(i);
609.191 - final GsfTestCompilationInfo info = getInfo(fo);
609.192 - final PythonParserResult parseResult = PythonAstUtils.getParseResult(info);
609.193 - final SymbolTable scopeManager = parseResult.getSymbolTable();
609.194 -
609.195 - System.err.println("Scanning " + FileUtil.getFileDisplayName(fo));
609.196 -
609.197 - scopeManager.getErrors();
609.198 - scopeManager.getFilename();
609.199 - scopeManager.getImports();
609.200 - scopeManager.getImportsFrom();
609.201 - scopeManager.getMainImports();
609.202 - scopeManager.getPublicSymbols();
609.203 - scopeManager.getUnresolved(info);
609.204 - scopeManager.getUnresolvedNames(info);
609.205 - scopeManager.getUnused(false, false);
609.206 - scopeManager.getUnused(false, true);
609.207 - scopeManager.getUnused(true, false);
609.208 - scopeManager.getUnused(true, true);
609.209 - scopeManager.getUnusedImports();
609.210 -
609.211 - PythonTree root = PythonAstUtils.getRoot(info);
609.212 - assertNotNull(FileUtil.getFileDisplayName(fo), root);
609.213 - List<PythonTree> nodes = getAllNodes(root);
609.214 - final List<PythonTree> defs = new ArrayList<PythonTree>();
609.215 - PythonAstUtils.addNodesByType(root, new Class[] { PythonTree.class }, defs);
609.216 - new NodeFinder(new AstPathChecker() {
609.217 - public void check(AstPath path) {
609.218 - PythonTree scope = PythonAstUtils.getLocalScope(path);
609.219 - PythonTree node = path.leaf();
609.220 -
609.221 - PythonAstUtils.isNameNode(node);
609.222 - String name = PythonAstUtils.getName(node);
609.223 - if (name != null) {
609.224 - scopeManager.findDeclaration(scope, name, false);
609.225 - scopeManager.findDeclaration(scope, name, true);
609.226 - scopeManager.getOccurrences(scope, name, false);
609.227 - scopeManager.getOccurrences(scope, name, true);
609.228 - scopeManager.isPrivate(node, name);
609.229 - }
609.230 - if (scope != null) {
609.231 - scopeManager.getDefinedElements(info, scope, "", NameKind.PREFIX);
609.232 - }
609.233 - }
609.234 - }).visit(root);
609.235 -
609.236 - for (PythonTree node : nodes) {
609.237 - scopeManager.isTopLevel(node);
609.238 - scopeManager.error("testerror", true, node);
609.239 - }
609.240 - }
609.241 - }
609.242 -
609.243 - interface AstPathChecker {
609.244 - void check(AstPath path);
609.245 - }
609.246 -
609.247 - private static class NodeFinder extends Visitor {
609.248 - private ArrayList<PythonTree> path = new ArrayList<PythonTree>();
609.249 - private AstPathChecker checker;
609.250 -
609.251 - private NodeFinder(AstPathChecker checker) {
609.252 - this.checker = checker;
609.253 - }
609.254 -
609.255 - @Override
609.256 - public void traverse(PythonTree node) throws Exception {
609.257 - path.add(node);
609.258 -
609.259 - checker.check(new AstPath(path));
609.260 -
609.261 - super.traverse(node);
609.262 - path.remove(path.size()-1);
609.263 - }
609.264 - }
609.265 -
609.266 - // TODO - test the various other functions -- unused, unresolved, etc!
609.267 -
609.268 -}
610.1 --- a/python.platform/src/org/netbeans/modules/python/platform/panels/PythonPlatformPanel.java Sun Jan 04 13:11:53 2015 -0600
610.2 +++ b/python.platform/src/org/netbeans/modules/python/platform/panels/PythonPlatformPanel.java Sun Feb 01 15:02:07 2015 -0800
610.3 @@ -460,7 +460,7 @@
610.4 //Exceptions.printStackTrace(ex);
610.5 }catch(Exception ex){
610.6 NotifyDescriptor message = new Message(
610.7 - "Invalid Python Type", NotifyDescriptor.ERROR_MESSAGE); // was Invlaid and platform_info.py is NOT where expected
610.8 + "Invlaid Python Type", NotifyDescriptor.ERROR_MESSAGE);
610.9 DialogDisplayer.getDefault().notify(message);
610.10 }
610.11 }
611.1 --- a/python.project/nbproject/project.properties Sun Jan 04 13:11:53 2015 -0600
611.2 +++ b/python.project/nbproject/project.properties Sun Feb 01 15:02:07 2015 -0800
611.3 @@ -8,7 +8,7 @@
611.4 auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.blankLinesAfterClassHeader=0
611.5 auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.indentCasesFromSwitch=false
611.6 auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.spaceAfterTypeCast=false
611.7 -javac.source=1.6
611.8 +javac.source=1.7
611.9 javac.compilerargs=-Xlint -Xlint:-serial
611.10
611.11 test-unit-sys-prop.xtest.python.home=${netbeans.dest.dir}/python/jython-2.5.1
612.1 --- a/python.project/nbproject/project.xml Sun Jan 04 13:11:53 2015 -0600
612.2 +++ b/python.project/nbproject/project.xml Sun Feb 01 15:02:07 2015 -0800
612.3 @@ -6,6 +6,24 @@
612.4 <code-name-base>org.netbeans.modules.python.project</code-name-base>
612.5 <module-dependencies>
612.6 <dependency>
612.7 + <code-name-base>org.netbeans.api.annotations.common</code-name-base>
612.8 + <build-prerequisite/>
612.9 + <compile-dependency/>
612.10 + <run-dependency>
612.11 + <release-version>1</release-version>
612.12 + <specification-version>1.25</specification-version>
612.13 + </run-dependency>
612.14 + </dependency>
612.15 + <dependency>
612.16 + <code-name-base>org.netbeans.api.java.classpath</code-name-base>
612.17 + <build-prerequisite/>
612.18 + <compile-dependency/>
612.19 + <run-dependency>
612.20 + <release-version>1</release-version>
612.21 + <specification-version>1.48</specification-version>
612.22 + </run-dependency>
612.23 + </dependency>
612.24 + <dependency>
612.25 <code-name-base>org.netbeans.api.progress</code-name-base>
612.26 <build-prerequisite/>
612.27 <compile-dependency/>
612.28 @@ -109,6 +127,14 @@
612.29 </run-dependency>
612.30 </dependency>
612.31 <dependency>
612.32 + <code-name-base>org.netbeans.modules.python.source</code-name-base>
612.33 + <build-prerequisite/>
612.34 + <compile-dependency/>
612.35 + <run-dependency>
612.36 + <specification-version>1.0</specification-version>
612.37 + </run-dependency>
612.38 + </dependency>
612.39 + <dependency>
612.40 <code-name-base>org.netbeans.modules.queries</code-name-base>
612.41 <build-prerequisite/>
612.42 <compile-dependency/>
612.43 @@ -174,14 +200,6 @@
612.44 </run-dependency>
612.45 </dependency>
612.46 <dependency>
612.47 - <code-name-base>org.openide.util.ui</code-name-base>
612.48 - <build-prerequisite/>
612.49 - <compile-dependency/>
612.50 - <run-dependency>
612.51 - <specification-version>9.3</specification-version>
612.52 - </run-dependency>
612.53 - </dependency>
612.54 - <dependency>
612.55 <code-name-base>org.openide.util</code-name-base>
612.56 <build-prerequisite/>
612.57 <compile-dependency/>
612.58 @@ -198,6 +216,14 @@
612.59 </run-dependency>
612.60 </dependency>
612.61 <dependency>
612.62 + <code-name-base>org.openide.util.ui</code-name-base>
612.63 + <build-prerequisite/>
612.64 + <compile-dependency/>
612.65 + <run-dependency>
612.66 + <specification-version>9.3</specification-version>
612.67 + </run-dependency>
612.68 + </dependency>
612.69 + <dependency>
612.70 <code-name-base>org.openide.windows</code-name-base>
612.71 <build-prerequisite/>
612.72 <compile-dependency/>
612.73 @@ -215,66 +241,6 @@
612.74 </run-dependency>
612.75 </dependency>
612.76 </module-dependencies>
612.77 - <test-dependencies>
612.78 - <test-type>
612.79 - <name>unit</name>
612.80 - <test-dependency>
612.81 - <code-name-base>org.netbeans.libs.junit4</code-name-base>
612.82 - <compile-dependency/>
612.83 - </test-dependency>
612.84 - <test-dependency>
612.85 - <code-name-base>org.netbeans.modules.editor.lib</code-name-base>
612.86 - <compile-dependency/>
612.87 - </test-dependency>
612.88 - <test-dependency>
612.89 - <code-name-base>org.netbeans.modules.editor.mimelookup</code-name-base>
612.90 - <recursive/>
612.91 - <compile-dependency/>
612.92 - <test/>
612.93 - </test-dependency>
612.94 - <test-dependency>
612.95 - <code-name-base>org.netbeans.modules.editor.mimelookup.impl</code-name-base>
612.96 - </test-dependency>
612.97 - <test-dependency>
612.98 - <code-name-base>org.netbeans.modules.editor.util</code-name-base>
612.99 - <recursive/>
612.100 - <compile-dependency/>
612.101 - </test-dependency>
612.102 - <test-dependency>
612.103 - <code-name-base>org.netbeans.modules.gsf</code-name-base>
612.104 - <recursive/>
612.105 - <compile-dependency/>
612.106 - <test/>
612.107 - </test-dependency>
612.108 - <test-dependency>
612.109 - <code-name-base>org.netbeans.modules.lexer</code-name-base>
612.110 - <compile-dependency/>
612.111 - <test/>
612.112 - </test-dependency>
612.113 - <test-dependency>
612.114 - <code-name-base>org.netbeans.modules.masterfs</code-name-base>
612.115 - </test-dependency>
612.116 - <test-dependency>
612.117 - <code-name-base>org.netbeans.modules.nbjunit</code-name-base>
612.118 - <recursive/>
612.119 - <compile-dependency/>
612.120 - </test-dependency>
612.121 - <test-dependency>
612.122 - <code-name-base>org.netbeans.modules.python.editor</code-name-base>
612.123 - <recursive/>
612.124 - <compile-dependency/>
612.125 - <test/>
612.126 - </test-dependency>
612.127 - <test-dependency>
612.128 - <code-name-base>org.netbeans.modules.python.project</code-name-base>
612.129 - <recursive/>
612.130 - <compile-dependency/>
612.131 - </test-dependency>
612.132 - <test-dependency>
612.133 - <code-name-base>org.openide.util</code-name-base>
612.134 - </test-dependency>
612.135 - </test-type>
612.136 - </test-dependencies>
612.137 <public-packages>
612.138 <package>org.netbeans.modules.python.project.spi</package>
612.139 <package>org.netbeans.modules.python.project</package>
613.1 --- a/python.project/src/org/netbeans/modules/python/project/PythonBaseProject.java Sun Jan 04 13:11:53 2015 -0600
613.2 +++ b/python.project/src/org/netbeans/modules/python/project/PythonBaseProject.java Sun Feb 01 15:02:07 2015 -0800
613.3 @@ -16,8 +16,8 @@
613.4 import org.netbeans.api.project.Project;
613.5 import org.netbeans.api.project.ProjectInformation;
613.6 import org.netbeans.api.project.ProjectManager;
613.7 -import org.netbeans.modules.gsfpath.api.classpath.ClassPath;
613.8 -import org.netbeans.modules.gsfpath.api.classpath.GlobalPathRegistry;
613.9 +//import org.netbeans.modules.gsfpath.api.classpath.ClassPath;
613.10 +//import org.netbeans.modules.gsfpath.api.classpath.GlobalPathRegistry;
613.11 import org.netbeans.modules.python.editor.codecoverage.PythonCoverageProvider;
613.12 import org.netbeans.spi.project.AuxiliaryConfiguration;
613.13 import org.netbeans.spi.project.support.ant.AntProjectHelper;
614.1 --- a/python.project/src/org/netbeans/modules/python/project/PythonProject.java Sun Jan 04 13:11:53 2015 -0600
614.2 +++ b/python.project/src/org/netbeans/modules/python/project/PythonProject.java Sun Feb 01 15:02:07 2015 -0800
614.3 @@ -2,7 +2,6 @@
614.4 * To change this template, choose Tools | Templates
614.5 * and open the template in the editor.
614.6 */
614.7 -
614.8 package org.netbeans.modules.python.project;
614.9
614.10 import java.beans.PropertyChangeListener;
614.11 @@ -10,15 +9,16 @@
614.12 import java.io.IOException;
614.13 import javax.swing.Icon;
614.14 import javax.swing.ImageIcon;
614.15 +import org.netbeans.api.java.classpath.ClassPath;
614.16 +import org.netbeans.api.java.classpath.GlobalPathRegistry;
614.17 import org.netbeans.modules.python.api.PythonPlatformProvider;
614.18 import org.netbeans.modules.python.project.gsf.ClassPathProviderImpl;
614.19 import org.netbeans.modules.python.project.ui.customizer.PythonCustomizerProvider;
614.20 import org.netbeans.api.project.Project;
614.21 import org.netbeans.api.project.ProjectInformation;
614.22 import org.netbeans.api.project.ProjectManager;
614.23 -import org.netbeans.modules.gsfpath.api.classpath.ClassPath;
614.24 -import org.netbeans.modules.gsfpath.api.classpath.GlobalPathRegistry;
614.25 import org.netbeans.modules.python.editor.codecoverage.PythonCoverageProvider;
614.26 +import org.netbeans.modules.python.source.queries.SourceLevelQueryImplementation;
614.27 import org.netbeans.spi.project.AuxiliaryConfiguration;
614.28 import org.netbeans.spi.project.support.ant.AntProjectHelper;
614.29 import org.netbeans.spi.project.support.ant.ProjectXmlSavedHook;
614.30 @@ -47,82 +47,86 @@
614.31 * @author Tomas Zezula
614.32 */
614.33 public class PythonProject implements Project {
614.34 -
614.35 +
614.36 private static final ImageIcon PROJECT_ICON = ImageUtilities.loadImageIcon("org/netbeans/modules/python/project/resources/py_25_16.png", false);
614.37 -
614.38 +
614.39 protected AntProjectHelper helper;
614.40 - protected UpdateHelper updateHelper;
614.41 - protected LogicalViewProvider logicalView = new PythonLogicalView(this);
614.42 - protected SourceRoots sourceRoots;
614.43 - protected SourceRoots testRoots;
614.44 - protected Lookup lkp;
614.45 - protected PropertyEvaluator evaluator;
614.46 - protected ReferenceHelper refHelper;
614.47 - protected AuxiliaryConfiguration aux;
614.48 -
614.49 + protected UpdateHelper updateHelper;
614.50 + protected LogicalViewProvider logicalView = new PythonLogicalView(this);
614.51 + protected SourceRoots sourceRoots;
614.52 + protected SourceRoots testRoots;
614.53 + protected Lookup lkp;
614.54 + protected PropertyEvaluator evaluator;
614.55 + protected ReferenceHelper refHelper;
614.56 + protected AuxiliaryConfiguration aux;
614.57 +
614.58 public PythonProject(final AntProjectHelper helper) {
614.59 assert helper != null;
614.60 this.helper = helper;
614.61 - this.updateHelper = new UpdateHelper(UpdateImplementation.NULL,helper);
614.62 + this.updateHelper = new UpdateHelper(UpdateImplementation.NULL, helper);
614.63 this.evaluator = createEvaluator();
614.64 - this.aux = helper.createAuxiliaryConfiguration();
614.65 + this.aux = helper.createAuxiliaryConfiguration();
614.66 refHelper = new ReferenceHelper(helper, aux, evaluator);
614.67 this.sourceRoots = SourceRoots.create(updateHelper, evaluator, refHelper, false);
614.68 this.testRoots = SourceRoots.create(updateHelper, evaluator, refHelper, true);
614.69 this.lkp = createLookup();
614.70 }
614.71 -public PythonProject()
614.72 -{
614.73 -
614.74 -}
614.75 +
614.76 + public PythonProject() {
614.77 +
614.78 + }
614.79 +
614.80 + @Override
614.81 public FileObject getProjectDirectory() {
614.82 return helper.getProjectDirectory();
614.83 }
614.84 -
614.85 - public PropertyEvaluator createEvaluator() {
614.86 +
614.87 + public PropertyEvaluator createEvaluator() {
614.88 PropertyEvaluator privateProps = PropertyUtils.sequentialPropertyEvaluator(
614.89 helper.getStockPropertyPreprovider(),
614.90 helper.getPropertyProvider(AntProjectHelper.PRIVATE_PROPERTIES_PATH));
614.91 return PropertyUtils.sequentialPropertyEvaluator(
614.92 - helper.getStockPropertyPreprovider(),
614.93 + helper.getStockPropertyPreprovider(),
614.94 helper.getPropertyProvider(AntProjectHelper.PRIVATE_PROPERTIES_PATH),
614.95 PropertyUtils.userPropertiesProvider(privateProps,
614.96 - "user.properties.file", FileUtil.toFile(getProjectDirectory())), // NOI18N
614.97 + "user.properties.file", FileUtil.toFile(getProjectDirectory())), // NOI18N
614.98 helper.getPropertyProvider(AntProjectHelper.PROJECT_PROPERTIES_PATH));
614.99 }
614.100 -
614.101 - private Lookup createLookup () {
614.102 +
614.103 + private Lookup createLookup() {
614.104 return Lookups.fixed(new Object[]{
614.105 - this, //project spec requires a project be in it's own lookup
614.106 - aux, //Auxiliary configuartion to store bookmarks and so on
614.107 - new PythonActionProvider(this), //Provides Standard like build and cleen
614.108 - new ClassPathProviderImpl(this),
614.109 - new Info(), // Project information Implementation
614.110 - logicalView, // Logical view if project implementation
614.111 - new PythonOpenedHook(), //Called by project framework when project is opened (closed)
614.112 - new PythonProjectXmlSavedHook(), //Called when project.xml changes
614.113 - new PythonSources(this, helper,evaluator,sourceRoots,testRoots), //Python source grops - used by package view, factories, refactoring, ...
614.114 - new PythonProjectOperations(this), //move, rename, copy of project
614.115 - new RecommendedTemplatesImpl(this.updateHelper), // Recommended Templates
614.116 - new PythonCustomizerProvider(this), //Project custmoizer
614.117 - new PythonProjectFileEncodingQuery(getEvaluator()), //Provides encoding of the project - used by editor, runtime
614.118 - new PythonSharabilityQuery(helper, getEvaluator(), getSourceRoots(), getTestRoots()), //Sharabilit info - used by VCS
614.119 - helper.createCacheDirectoryProvider(), //Cache provider
614.120 - helper.createAuxiliaryProperties(), // AuxiliaryConfiguraion provider - used by bookmarks, project Preferences, etc
614.121 - new PythonPlatformProvider(getEvaluator()),
614.122 - new PythonCoverageProvider(this)
614.123 - });
614.124 + this, //project spec requires a project be in it's own lookup
614.125 + aux, //Auxiliary configuartion to store bookmarks and so on
614.126 + new PythonActionProvider(this), //Provides Standard like build and cleen
614.127 + new ClassPathProviderImpl(this),
614.128 + new Info(), // Project information Implementation
614.129 + logicalView, // Logical view if project implementation
614.130 + new PythonOpenedHook(), //Called by project framework when project is opened (closed)
614.131 + new PythonProjectXmlSavedHook(), //Called when project.xml changes
614.132 + new PythonSources(this, helper, evaluator, sourceRoots, testRoots), //Python source grops - used by package view, factories, refactoring, ...
614.133 + new PythonProjectOperations(this), //move, rename, copy of project
614.134 + new RecommendedTemplatesImpl(this.updateHelper), // Recommended Templates
614.135 + new PythonCustomizerProvider(this), //Project custmoizer
614.136 + new PythonProjectFileEncodingQuery(getEvaluator()), //Provides encoding of the project - used by editor, runtime
614.137 + new PythonSharabilityQuery(helper, getEvaluator(), getSourceRoots(), getTestRoots()), //Sharabilit info - used by VCS
614.138 + helper.createCacheDirectoryProvider(), //Cache provider
614.139 + helper.createAuxiliaryProperties(), // AuxiliaryConfiguraion provider - used by bookmarks, project Preferences, etc
614.140 + new PythonPlatformProvider(getEvaluator()),
614.141 + new PythonCoverageProvider(this),
614.142 + new PythonProjectSourceLevelQuery(evaluator, "")
614.143 + });
614.144 }
614.145 -
614.146 - public Lookup getLookup() {
614.147 +
614.148 + @Override
614.149 + public Lookup getLookup() {
614.150 return lkp;
614.151 }
614.152 -
614.153 - public SourceRoots getSourceRoots () {
614.154 +
614.155 + public SourceRoots getSourceRoots() {
614.156 return this.sourceRoots;
614.157 }
614.158 -
614.159 - public SourceRoots getTestRoots () {
614.160 +
614.161 + public SourceRoots getTestRoots() {
614.162 return this.testRoots;
614.163 }
614.164
614.165 @@ -134,20 +138,21 @@
614.166 return getTestRoots().getRoots();
614.167 }
614.168
614.169 - public PropertyEvaluator getEvaluator () {
614.170 + public PropertyEvaluator getEvaluator() {
614.171 return evaluator;
614.172 }
614.173 -
614.174 - AntProjectHelper getHelper () {
614.175 +
614.176 + AntProjectHelper getHelper() {
614.177 return this.helper;
614.178 }
614.179 -
614.180 +
614.181 public FileObject getSrcFolder() {
614.182 return getProjectDirectory();
614.183 - }
614.184 -
614.185 - public String getName () {
614.186 + }
614.187 +
614.188 + public String getName() {
614.189 return ProjectManager.mutex().readAccess(new Mutex.Action<String>() {
614.190 + @Override
614.191 public String run() {
614.192 Element data = getHelper().getPrimaryConfigurationData(true);
614.193 NodeList nl = data.getElementsByTagNameNS(PythonProjectType.PROJECT_CONFIGURATION_NAMESPACE, "name"); // NOI18N
614.194 @@ -162,9 +167,10 @@
614.195 }
614.196 });
614.197 }
614.198 -
614.199 +
614.200 void setName(final String name) {
614.201 ProjectManager.mutex().writeAccess(new Runnable() {
614.202 + @Override
614.203 public void run() {
614.204 Element data = getHelper().getPrimaryConfigurationData(true);
614.205 NodeList nl = data.getElementsByTagNameNS(PythonProjectType.PROJECT_CONFIGURATION_NAMESPACE, "name"); // NOI18N
614.206 @@ -178,48 +184,56 @@
614.207 } else {
614.208 nameEl = data.getOwnerDocument().createElementNS(
614.209 PythonProjectType.PROJECT_CONFIGURATION_NAMESPACE, "name"); // NOI18N
614.210 - data.insertBefore(nameEl, /* OK if null */data.getChildNodes().item(0));
614.211 + data.insertBefore(nameEl, /* OK if null */ data.getChildNodes().item(0));
614.212 }
614.213 nameEl.appendChild(data.getOwnerDocument().createTextNode(name));
614.214 getHelper().putPrimaryConfigurationData(data, true);
614.215 }
614.216 });
614.217 }
614.218 -
614.219 - private final class Info implements ProjectInformation{
614.220 -
614.221 +
614.222 + private final class Info implements ProjectInformation {
614.223 +
614.224 private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
614.225 -
614.226 - public void addPropertyChangeListener(PropertyChangeListener listener) {
614.227 +
614.228 + @Override
614.229 + public void addPropertyChangeListener(PropertyChangeListener listener) {
614.230 propertyChangeSupport.addPropertyChangeListener(listener);
614.231 }
614.232 -
614.233 +
614.234 + @Override
614.235 public void removePropertyChangeListener(PropertyChangeListener listener) {
614.236 propertyChangeSupport.removePropertyChangeListener(listener);
614.237 }
614.238
614.239 + @Override
614.240 public String getDisplayName() {
614.241 return getName();
614.242 }
614.243
614.244 + @Override
614.245 public Icon getIcon() {
614.246 return PROJECT_ICON;
614.247 }
614.248
614.249 + @Override
614.250 public String getName() {
614.251 return PythonProject.this.getName();
614.252 }
614.253
614.254 + @Override
614.255 public Project getProject() {
614.256 return PythonProject.this;
614.257 }
614.258 -
614.259 +
614.260 void firePropertyChange(String prop) {
614.261 - propertyChangeSupport.firePropertyChange(prop , null, null);
614.262 + propertyChangeSupport.firePropertyChange(prop, null, null);
614.263 }
614.264 }
614.265 -
614.266 +
614.267 public final class PythonOpenedHook extends ProjectOpenedHook {
614.268 +
614.269 + @Override
614.270 protected void projectOpened() {
614.271 // register project's classpaths to GlobalPathRegistry
614.272 final ClassPathProviderImpl cpProvider = getLookup().lookup(ClassPathProviderImpl.class);
614.273 @@ -234,7 +248,8 @@
614.274 }
614.275 }
614.276
614.277 - protected void projectClosed() {
614.278 + @Override
614.279 + protected void projectClosed() {
614.280 // unregister project's classpaths to GlobalPathRegistry
614.281 final ClassPathProviderImpl cpProvider = getLookup().lookup(ClassPathProviderImpl.class);
614.282 assert cpProvider != null;
614.283 @@ -247,49 +262,53 @@
614.284 }
614.285 }
614.286 }
614.287 -
614.288 +
614.289 public final class PythonProjectXmlSavedHook extends ProjectXmlSavedHook {
614.290 -
614.291 - public PythonProjectXmlSavedHook() {}
614.292 -
614.293 +
614.294 + public PythonProjectXmlSavedHook() {
614.295 + }
614.296 +
614.297 + @Override
614.298 protected void projectXmlSaved() throws IOException {
614.299 Info info = getLookup().lookup(Info.class);
614.300 assert info != null;
614.301 info.firePropertyChange(ProjectInformation.PROP_NAME);
614.302 info.firePropertyChange(ProjectInformation.PROP_DISPLAY_NAME);
614.303 - }
614.304 + }
614.305 }
614.306 +
614.307 private static final class RecommendedTemplatesImpl implements RecommendedTemplates, PrivilegedTemplates {
614.308 -
614.309 - RecommendedTemplatesImpl (UpdateHelper helper) {
614.310 +
614.311 + RecommendedTemplatesImpl(UpdateHelper helper) {
614.312 this.helper = helper;
614.313 }
614.314 -
614.315 +
614.316 private final UpdateHelper helper;
614.317 -
614.318 +
614.319 // List of primarily supported templates
614.320 -
614.321 - private static final String[] APPLICATION_TYPES = new String[] {
614.322 - "python", // NOI18N
614.323 - "XML", // NOI18N
614.324 - "simple-files" // NOI18N
614.325 + private static final String[] APPLICATION_TYPES = new String[]{
614.326 + "python", // NOI18N
614.327 + "XML", // NOI18N
614.328 + "simple-files" // NOI18N
614.329 };
614.330 -
614.331 - private static final String[] PRIVILEGED_NAMES = new String[] {
614.332 +
614.333 + private static final String[] PRIVILEGED_NAMES = new String[]{
614.334 "Templates/Python/_package", // NOI18N
614.335 "Templates/Python/_module.py", //NOI18N
614.336 "Templates/Python/_main.py", // NOI18N
614.337 "Templates/Python/_empty_module.py", // NOI18N
614.338 "Templates/Python/_test.py", // NOI18N
614.339 };
614.340 -
614.341 +
614.342 + @Override
614.343 public String[] getRecommendedTypes() {
614.344 return APPLICATION_TYPES;
614.345 }
614.346 -
614.347 +
614.348 + @Override
614.349 public String[] getPrivilegedTemplates() {
614.350 return PRIVILEGED_NAMES;
614.351 }
614.352 -
614.353 +
614.354 }
614.355 }
615.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
615.2 +++ b/python.project/src/org/netbeans/modules/python/project/PythonProjectSourceLevelQuery.java Sun Feb 01 15:02:07 2015 -0800
615.3 @@ -0,0 +1,98 @@
615.4 +/*
615.5 + * To change this license header, choose License Headers in Project Properties.
615.6 + * To change this template file, choose Tools | Templates
615.7 + * and open the template in the editor.
615.8 + */
615.9 +package org.netbeans.modules.python.project;
615.10 +
615.11 +import java.beans.PropertyChangeEvent;
615.12 +import java.beans.PropertyChangeListener;
615.13 +import javax.swing.event.ChangeListener;
615.14 +import org.netbeans.api.annotations.common.CheckForNull;
615.15 +import org.netbeans.api.annotations.common.NonNull;
615.16 +import org.netbeans.modules.python.source.queries.SourceLevelQueryImplementation;
615.17 +import org.netbeans.spi.project.support.ant.PropertyEvaluator;
615.18 +import org.openide.filesystems.FileObject;
615.19 +import org.openide.util.ChangeSupport;
615.20 +import org.openide.util.WeakListeners;
615.21 +
615.22 +/**
615.23 + *
615.24 + * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
615.25 + */
615.26 +class PythonProjectSourceLevelQuery implements SourceLevelQueryImplementation {
615.27 +
615.28 + private static final String PLATFORM_ACTIVE = "platform.active"; //NOI18N
615.29 +
615.30 + private final PropertyEvaluator eval;
615.31 + private final Result result;
615.32 +
615.33 + PythonProjectSourceLevelQuery(
615.34 + @NonNull final PropertyEvaluator eval,
615.35 + @NonNull final String platformType) {
615.36 + assert eval != null;
615.37 + assert platformType != null;
615.38 + this.eval = eval;
615.39 + this.result = new R();
615.40 + }
615.41 +
615.42 + @Override
615.43 + public Result getSourceLevel(FileObject javaFile) {
615.44 + return this.result;
615.45 + }
615.46 +
615.47 + @CheckForNull
615.48 + static String findSourceLevel (
615.49 + @NonNull final PropertyEvaluator eval) {
615.50 + return findValue(eval);
615.51 + }
615.52 +
615.53 + @CheckForNull
615.54 + private static String findValue(
615.55 + @NonNull final PropertyEvaluator eval) {
615.56 + final String activePlatform = eval.getProperty(PLATFORM_ACTIVE);
615.57 + return activePlatform;
615.58 + }
615.59 +
615.60 + private class R implements Result, PropertyChangeListener {
615.61 +
615.62 + private final ChangeSupport cs = new ChangeSupport(this);
615.63 +
615.64 + @SuppressWarnings("LeakingThisInConstructor")
615.65 + private R() {
615.66 + eval.addPropertyChangeListener(WeakListeners.propertyChange(this, eval));
615.67 + }
615.68 +
615.69 + @Override
615.70 + public String getSourceLevel() {
615.71 + return findSourceLevel(eval);
615.72 + }
615.73 +
615.74 + @Override
615.75 + public void addChangeListener(ChangeListener listener) {
615.76 + this.cs.addChangeListener(listener);
615.77 + }
615.78 +
615.79 + @Override
615.80 + public void removeChangeListener(ChangeListener listener) {
615.81 + this.cs.removeChangeListener(listener);
615.82 + }
615.83 +
615.84 + @Override
615.85 + public void propertyChange(PropertyChangeEvent evt) {
615.86 + final String name = evt.getPropertyName();
615.87 + if (name == null ||
615.88 + PLATFORM_ACTIVE.equals(name)) {
615.89 + this.cs.fireChange();
615.90 + }
615.91 + }
615.92 +
615.93 + @Override
615.94 + public String toString() {
615.95 + final String sl = getSourceLevel();
615.96 + return sl == null ? "" : sl; //NOI18M
615.97 + }
615.98 +
615.99 + }
615.100 +
615.101 +}
616.1 --- a/python.project/src/org/netbeans/modules/python/project/actions/Bundle.properties Sun Jan 04 13:11:53 2015 -0600
616.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
616.3 @@ -1,1 +0,0 @@
616.4 -CTL_OptionPythonConsole=Python Console
617.1 --- a/python.project/src/org/netbeans/modules/python/project/gsf/BootClassPathImplementation.java Sun Jan 04 13:11:53 2015 -0600
617.2 +++ b/python.project/src/org/netbeans/modules/python/project/gsf/BootClassPathImplementation.java Sun Feb 01 15:02:07 2015 -0800
617.3 @@ -44,9 +44,6 @@
617.4 package org.netbeans.modules.python.project.gsf;
617.5
617.6 import java.beans.PropertyChangeEvent;
617.7 -import org.netbeans.modules.gsfpath.spi.classpath.ClassPathImplementation;
617.8 -import org.netbeans.modules.gsfpath.spi.classpath.PathResourceImplementation;
617.9 -import org.netbeans.modules.gsfpath.spi.classpath.support.ClassPathSupport;
617.10 import java.beans.PropertyChangeListener;
617.11 import java.beans.PropertyChangeSupport;
617.12 import java.net.URL;
617.13 @@ -58,6 +55,9 @@
617.14 import org.netbeans.modules.python.project.PythonProject;
617.15 import org.netbeans.modules.python.project.PythonProjectUtil;
617.16 import org.netbeans.modules.python.project.ui.customizer.PythonProjectProperties;
617.17 +import org.netbeans.spi.java.classpath.ClassPathImplementation;
617.18 +import org.netbeans.spi.java.classpath.PathResourceImplementation;
617.19 +import org.netbeans.spi.java.classpath.support.ClassPathSupport;
617.20 import org.netbeans.spi.project.support.ant.PropertyEvaluator;
617.21 import org.openide.util.Parameters;
617.22 import org.openide.util.RequestProcessor;
618.1 --- a/python.project/src/org/netbeans/modules/python/project/gsf/ClassPathProviderImpl.java Sun Jan 04 13:11:53 2015 -0600
618.2 +++ b/python.project/src/org/netbeans/modules/python/project/gsf/ClassPathProviderImpl.java Sun Feb 01 15:02:07 2015 -0800
618.3 @@ -45,14 +45,19 @@
618.4
618.5 import java.util.HashMap;
618.6 import java.util.Map;
618.7 +import org.netbeans.api.java.classpath.ClassPath;
618.8 import org.netbeans.modules.python.project.PythonProject;
618.9 import org.netbeans.modules.python.project.SourceRoots;
618.10 import org.netbeans.modules.python.project.util.Pair;
618.11 -import org.netbeans.modules.gsfpath.api.classpath.ClassPath;
618.12 -import org.netbeans.modules.gsfpath.spi.classpath.ClassPathFactory;
618.13 -import org.netbeans.modules.gsfpath.spi.classpath.ClassPathImplementation;
618.14 -import org.netbeans.modules.gsfpath.spi.classpath.ClassPathProvider;
618.15 -import org.netbeans.modules.gsfpath.spi.classpath.support.ClassPathSupport;
618.16 +import org.netbeans.spi.java.classpath.ClassPathFactory;
618.17 +import org.netbeans.spi.java.classpath.ClassPathImplementation;
618.18 +import org.netbeans.spi.java.classpath.ClassPathProvider;
618.19 +import org.netbeans.spi.java.classpath.support.ClassPathSupport;
618.20 +//import org.netbeans.modules.gsfpath.api.classpath.ClassPath;
618.21 +//import org.netbeans.modules.gsfpath.spi.classpath.ClassPathFactory;
618.22 +//import org.netbeans.modules.gsfpath.spi.classpath.ClassPathImplementation;
618.23 +//import org.netbeans.modules.gsfpath.spi.classpath.ClassPathProvider;
618.24 +//import org.netbeans.modules.gsfpath.spi.classpath.support.ClassPathSupport;
618.25 import org.openide.filesystems.FileObject;
618.26 import org.openide.filesystems.FileUtil;
618.27
619.1 --- a/python.project/src/org/netbeans/modules/python/project/gsf/CompilePathImplementation.java Sun Jan 04 13:11:53 2015 -0600
619.2 +++ b/python.project/src/org/netbeans/modules/python/project/gsf/CompilePathImplementation.java Sun Feb 01 15:02:07 2015 -0800
619.3 @@ -54,11 +54,14 @@
619.4 import java.util.concurrent.atomic.AtomicBoolean;
619.5 import java.util.logging.Logger;
619.6 import org.netbeans.api.project.ProjectManager;
619.7 -import org.netbeans.modules.gsfpath.spi.classpath.ClassPathImplementation;
619.8 -import org.netbeans.modules.gsfpath.spi.classpath.PathResourceImplementation;
619.9 -import org.netbeans.modules.gsfpath.spi.classpath.support.ClassPathSupport;
619.10 +//import org.netbeans.modules.gsfpath.spi.classpath.ClassPathImplementation;
619.11 +//import org.netbeans.modules.gsfpath.spi.classpath.PathResourceImplementation;
619.12 +//import org.netbeans.modules.gsfpath.spi.classpath.support.ClassPathSupport;
619.13 import org.netbeans.modules.python.project.PythonProject;
619.14 import org.netbeans.modules.python.project.ui.customizer.PythonProjectProperties;
619.15 +import org.netbeans.spi.java.classpath.ClassPathImplementation;
619.16 +import org.netbeans.spi.java.classpath.PathResourceImplementation;
619.17 +import org.netbeans.spi.java.classpath.support.ClassPathSupport;
619.18 import org.netbeans.spi.project.support.ant.PropertyEvaluator;
619.19 import org.netbeans.spi.project.support.ant.PropertyUtils;
619.20 import org.openide.filesystems.FileObject;
620.1 --- a/python.project/src/org/netbeans/modules/python/project/gsf/SourcePathImplementation.java Sun Jan 04 13:11:53 2015 -0600
620.2 +++ b/python.project/src/org/netbeans/modules/python/project/gsf/SourcePathImplementation.java Sun Feb 01 15:02:07 2015 -0800
620.3 @@ -51,9 +51,12 @@
620.4 import java.beans.PropertyChangeSupport;
620.5 import java.net.URL;
620.6 import org.netbeans.modules.python.project.SourceRoots;
620.7 -import org.netbeans.modules.gsfpath.spi.classpath.ClassPathImplementation;
620.8 -import org.netbeans.modules.gsfpath.spi.classpath.PathResourceImplementation;
620.9 -import org.netbeans.modules.gsfpath.spi.classpath.support.ClassPathSupport;
620.10 +import org.netbeans.spi.java.classpath.ClassPathImplementation;
620.11 +import org.netbeans.spi.java.classpath.PathResourceImplementation;
620.12 +import org.netbeans.spi.java.classpath.support.ClassPathSupport;
620.13 +//import org.netbeans.modules.gsfpath.spi.classpath.ClassPathImplementation;
620.14 +//import org.netbeans.modules.gsfpath.spi.classpath.PathResourceImplementation;
620.15 +//import org.netbeans.modules.gsfpath.spi.classpath.support.ClassPathSupport;
620.16 import org.openide.util.WeakListeners;
620.17
620.18 /**
621.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
621.2 +++ b/python.project/src/org/netbeans/modules/python/project/queries/PythonProjectSourceLevelQuery.java Sun Feb 01 15:02:07 2015 -0800
621.3 @@ -0,0 +1,29 @@
621.4 +/*
621.5 + * To change this license header, choose License Headers in Project Properties.
621.6 + * To change this template file, choose Tools | Templates
621.7 + * and open the template in the editor.
621.8 + */
621.9 +package org.netbeans.modules.python.project.queries;
621.10 +
621.11 +import org.netbeans.modules.python.source.queries.SourceLevelQueryImplementation;
621.12 +import org.netbeans.api.project.FileOwnerQuery;
621.13 +import org.netbeans.api.project.Project;
621.14 +import org.openide.filesystems.FileObject;
621.15 +import org.openide.util.lookup.ServiceProvider;
621.16 +
621.17 +@ServiceProvider(service = SourceLevelQueryImplementation.class)
621.18 +public class PythonProjectSourceLevelQuery implements SourceLevelQueryImplementation {
621.19 +
621.20 + @Override
621.21 + public Result getSourceLevel(FileObject pythonFile) {
621.22 + final Project project = FileOwnerQuery.getOwner(pythonFile);
621.23 + if (project != null) {
621.24 + SourceLevelQueryImplementation impl = project.getLookup().lookup(SourceLevelQueryImplementation.class);
621.25 + if (impl != null) {
621.26 + return impl.getSourceLevel(pythonFile);
621.27 + }
621.28 + }
621.29 + return null;
621.30 + }
621.31 +
621.32 +}
622.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
622.2 +++ b/python.project/src/org/netbeans/modules/python/project/queries/PythonShebangSourceLevelQuery.java Sun Feb 01 15:02:07 2015 -0800
622.3 @@ -0,0 +1,125 @@
622.4 +/*
622.5 + * To change this license header, choose License Headers in Project Properties.
622.6 + * To change this template file, choose Tools | Templates
622.7 + * and open the template in the editor.
622.8 + */
622.9 +package org.netbeans.modules.python.project.queries;
622.10 +
622.11 +import org.netbeans.modules.python.source.queries.SourceLevelQueryImplementation;
622.12 +import java.io.FileNotFoundException;
622.13 +import java.io.IOException;
622.14 +import java.util.HashSet;
622.15 +import java.util.Scanner;
622.16 +import java.util.Set;
622.17 +import javax.swing.event.ChangeEvent;
622.18 +import javax.swing.event.ChangeListener;
622.19 +import org.openide.filesystems.FileAttributeEvent;
622.20 +import org.openide.filesystems.FileChangeListener;
622.21 +import org.openide.filesystems.FileEvent;
622.22 +import org.openide.filesystems.FileObject;
622.23 +import org.openide.filesystems.FileRenameEvent;
622.24 +import org.openide.util.ChangeSupport;
622.25 +import org.openide.util.Exceptions;
622.26 +import org.openide.util.lookup.ServiceProvider;
622.27 +
622.28 +/**
622.29 + *
622.30 + * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
622.31 + */
622.32 +@ServiceProvider(service = SourceLevelQueryImplementation.class)
622.33 +public class PythonShebangSourceLevelQuery implements SourceLevelQueryImplementation {
622.34 +
622.35 + @Override
622.36 + public Result getSourceLevel(FileObject pythonFile) {
622.37 + return new ResultImpl(pythonFile);
622.38 + }
622.39 +
622.40 + private final static class ResultImpl implements Result, FileChangeListener {
622.41 + private final ChangeSupport cs = new ChangeSupport(this);
622.42 +
622.43 + private final FileObject pythonFile;
622.44 + private String sourceLevel = "";
622.45 +
622.46 + @SuppressWarnings("LeakingThisInConstructor")
622.47 + private ResultImpl(FileObject pythonFile) {
622.48 + this.pythonFile = pythonFile;
622.49 + this.pythonFile.addFileChangeListener(this);
622.50 + this.fileChanged(null);
622.51 + }
622.52 +
622.53 + @Override
622.54 + public void addChangeListener(ChangeListener listener) {
622.55 + this.cs.addChangeListener(listener);
622.56 + }
622.57 +
622.58 + @Override
622.59 + public void fileAttributeChanged(FileAttributeEvent fe) {
622.60 + }
622.61 +
622.62 + @Override
622.63 + public void fileChanged(FileEvent fe) {
622.64 + if (pythonFile.isValid()) {
622.65 + String shebang = null;
622.66 + try (Scanner sc = new Scanner(pythonFile.getInputStream())) {
622.67 + if (sc.hasNextLine()) {
622.68 + shebang = sc.nextLine();
622.69 + }
622.70 + } catch (FileNotFoundException ex) {
622.71 + Exceptions.printStackTrace(ex);
622.72 + }
622.73 + processShebang(shebang);
622.74 + }
622.75 + }
622.76 +
622.77 + @Override
622.78 + public void fileDataCreated(FileEvent fe) {
622.79 + }
622.80 +
622.81 + @Override
622.82 + public void fileDeleted(FileEvent fe) {
622.83 + }
622.84 +
622.85 + @Override
622.86 + public void fileFolderCreated(FileEvent fe) {
622.87 + }
622.88 +
622.89 + @Override
622.90 + public void fileRenamed(FileRenameEvent fe) {
622.91 + }
622.92 +
622.93 + @Override
622.94 + public String getSourceLevel() {
622.95 + return this.sourceLevel;
622.96 + }
622.97 +
622.98 + @Override
622.99 + public void removeChangeListener(ChangeListener listener) {
622.100 + this.cs.removeChangeListener(listener);
622.101 + }
622.102 +
622.103 + private void setSourceLevel(String sourceLevel) {
622.104 + this.sourceLevel = sourceLevel;
622.105 + cs.fireChange();
622.106 + }
622.107 +
622.108 + private void processShebang(String shebang) {
622.109 + if (shebang != null && shebang.startsWith("#!")) {
622.110 + try {
622.111 + Process proc = Runtime.getRuntime().exec(shebang.substring(2) + " --version");
622.112 + String version = null;
622.113 + try(Scanner sc = new Scanner(proc.getInputStream())) {
622.114 + if(sc.hasNextLine()) {
622.115 + version = sc.nextLine();
622.116 + }
622.117 + }
622.118 + proc.destroy();
622.119 + if(version != null && !version.isEmpty() && !version.equals(this.sourceLevel)) {
622.120 + setSourceLevel(version);
622.121 + }
622.122 + } catch(IOException ex) {
622.123 + Exceptions.printStackTrace(ex);
622.124 + }
622.125 + }
622.126 + }
622.127 + }
622.128 +}
623.1 --- a/python.project/src/org/netbeans/modules/python/project/templates/NewPythonProjectWizardIterator.java Sun Jan 04 13:11:53 2015 -0600
623.2 +++ b/python.project/src/org/netbeans/modules/python/project/templates/NewPythonProjectWizardIterator.java Sun Feb 01 15:02:07 2015 -0800
623.3 @@ -38,7 +38,6 @@
623.4
623.5 public class NewPythonProjectWizardIterator implements WizardDescriptor.ProgressInstantiatingIterator {
623.6
623.7 - static final String SET_AS_MAIN = "setAsMain"; //NOI18N
623.8 static final String MAIN_FILE ="mainFile"; //NOI18N
623.9 static final String PROP_PROJECT_NAME = "projectName"; //NOI18N
623.10 static final String PROP_PROJECT_LOCATION = "pojectLocation"; //NOI18N
624.1 --- a/python.project/src/org/netbeans/modules/python/project/templates/PanelOptionsVisual.form Sun Jan 04 13:11:53 2015 -0600
624.2 +++ b/python.project/src/org/netbeans/modules/python/project/templates/PanelOptionsVisual.form Sun Feb 01 15:02:07 2015 -0800
624.3 @@ -25,10 +25,6 @@
624.4 <DimensionLayout dim="0">
624.5 <Group type="103" groupAlignment="0" attributes="0">
624.6 <Group type="102" alignment="0" attributes="0">
624.7 - <Component id="setAsMainCheckBox" min="-2" max="-2" attributes="0"/>
624.8 - <EmptySpace pref="353" max="32767" attributes="0"/>
624.9 - </Group>
624.10 - <Group type="102" alignment="0" attributes="0">
624.11 <Group type="103" groupAlignment="0" attributes="0">
624.12 <Component id="createMainCheckBox" alignment="0" min="-2" max="-2" attributes="0"/>
624.13 <Component id="jLabel1" alignment="0" min="-2" max="-2" attributes="0"/>
624.14 @@ -41,7 +37,7 @@
624.15 <Component id="manage" min="-2" max="-2" attributes="0"/>
624.16 <EmptySpace min="-2" pref="4" max="-2" attributes="0"/>
624.17 </Group>
624.18 - <Component id="mainFileTextField" alignment="0" pref="353" max="32767" attributes="0"/>
624.19 + <Component id="mainFileTextField" alignment="0" max="32767" attributes="0"/>
624.20 </Group>
624.21 </Group>
624.22 </Group>
624.23 @@ -49,8 +45,7 @@
624.24 <DimensionLayout dim="1">
624.25 <Group type="103" groupAlignment="0" attributes="0">
624.26 <Group type="102" attributes="0">
624.27 - <Component id="setAsMainCheckBox" min="-2" max="-2" attributes="0"/>
624.28 - <EmptySpace min="-2" pref="5" max="-2" attributes="0"/>
624.29 + <EmptySpace max="-2" attributes="0"/>
624.30 <Group type="103" groupAlignment="3" attributes="0">
624.31 <Component id="createMainCheckBox" alignment="3" min="-2" max="-2" attributes="0"/>
624.32 <Component id="mainFileTextField" alignment="3" min="-2" max="-2" attributes="0"/>
624.33 @@ -63,7 +58,7 @@
624.34 </Group>
624.35 <Component id="manage" alignment="0" min="-2" max="-2" attributes="0"/>
624.36 </Group>
624.37 - <EmptySpace pref="50" max="32767" attributes="0"/>
624.38 + <EmptySpace max="32767" attributes="0"/>
624.39 </Group>
624.40 </Group>
624.41 </DimensionLayout>
624.42 @@ -101,25 +96,6 @@
624.43 </Property>
624.44 </AccessibilityProperties>
624.45 </Component>
624.46 - <Component class="javax.swing.JCheckBox" name="setAsMainCheckBox">
624.47 - <Properties>
624.48 - <Property name="selected" type="boolean" value="true"/>
624.49 - <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
624.50 - <ResourceString bundle="org/netbeans/modules/python/project/templates/Bundle.properties" key="LBL_setAsMainCheckBox" replaceFormat="org.openide.util.NbBundle.getBundle({sourceFileName}.class).getString("{key}")"/>
624.51 - </Property>
624.52 - </Properties>
624.53 - <AccessibilityProperties>
624.54 - <Property name="AccessibleContext.accessibleName" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
624.55 - <ResourceString bundle="org/netbeans/modules/python/project/templates/Bundle.properties" key="ACSN_setAsMainCheckBox" replaceFormat="org.openide.util.NbBundle.getBundle({sourceFileName}.class).getString("{key}")"/>
624.56 - </Property>
624.57 - <Property name="AccessibleContext.accessibleDescription" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
624.58 - <ResourceString bundle="org/netbeans/modules/python/project/templates/Bundle.properties" key="ACSD_setAsMainCheckBox" replaceFormat="org.openide.util.NbBundle.getBundle({sourceFileName}.class).getString("{key}")"/>
624.59 - </Property>
624.60 - </AccessibilityProperties>
624.61 - <AuxValues>
624.62 - <AuxValue name="generateMnemonicsCode" type="java.lang.Boolean" value="true"/>
624.63 - </AuxValues>
624.64 - </Component>
624.65 <Component class="javax.swing.JLabel" name="jLabel1">
624.66 <Properties>
624.67 <Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
625.1 --- a/python.project/src/org/netbeans/modules/python/project/templates/PanelOptionsVisual.java Sun Jan 04 13:11:53 2015 -0600
625.2 +++ b/python.project/src/org/netbeans/modules/python/project/templates/PanelOptionsVisual.java Sun Feb 01 15:02:07 2015 -0800
625.3 @@ -99,7 +99,6 @@
625.4 mainFileTextField.setEnabled( lastMainClassCheck );
625.5 break;
625.6 case EXISTING:
625.7 - setAsMainCheckBox.setVisible( true );
625.8 createMainCheckBox.setVisible( false );
625.9 mainFileTextField.setVisible( false );
625.10 break;
625.11 @@ -154,7 +153,6 @@
625.12
625.13 createMainCheckBox = new javax.swing.JCheckBox();
625.14 mainFileTextField = new javax.swing.JTextField();
625.15 - setAsMainCheckBox = new javax.swing.JCheckBox();
625.16 jLabel1 = new javax.swing.JLabel();
625.17 platforms = org.netbeans.modules.python.api.PlatformComponentFactory.getPythonPlatformsComboxBox();
625.18 manage = new javax.swing.JButton();
625.19 @@ -164,9 +162,6 @@
625.20
625.21 mainFileTextField.setText("main");
625.22
625.23 - setAsMainCheckBox.setSelected(true);
625.24 - org.openide.awt.Mnemonics.setLocalizedText(setAsMainCheckBox, org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("LBL_setAsMainCheckBox")); // NOI18N
625.25 -
625.26 jLabel1.setLabelFor(platforms);
625.27 org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(PanelOptionsVisual.class, "TXT_PythonPlatform")); // NOI18N
625.28
625.29 @@ -182,9 +177,6 @@
625.30 layout.setHorizontalGroup(
625.31 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
625.32 .addGroup(layout.createSequentialGroup()
625.33 - .addComponent(setAsMainCheckBox)
625.34 - .addContainerGap(353, Short.MAX_VALUE))
625.35 - .addGroup(layout.createSequentialGroup()
625.36 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
625.37 .addComponent(createMainCheckBox)
625.38 .addComponent(jLabel1))
625.39 @@ -195,13 +187,12 @@
625.40 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
625.41 .addComponent(manage)
625.42 .addGap(4, 4, 4))
625.43 - .addComponent(mainFileTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)))
625.44 + .addComponent(mainFileTextField)))
625.45 );
625.46 layout.setVerticalGroup(
625.47 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
625.48 .addGroup(layout.createSequentialGroup()
625.49 - .addComponent(setAsMainCheckBox)
625.50 - .addGap(5, 5, 5)
625.51 + .addContainerGap()
625.52 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
625.53 .addComponent(createMainCheckBox)
625.54 .addComponent(mainFileTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
625.55 @@ -211,15 +202,13 @@
625.56 .addComponent(jLabel1)
625.57 .addComponent(platforms, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
625.58 .addComponent(manage))
625.59 - .addContainerGap(50, Short.MAX_VALUE))
625.60 + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
625.61 );
625.62
625.63 createMainCheckBox.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("ACSN_createMainCheckBox")); // NOI18N
625.64 createMainCheckBox.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("ACSD_createMainCheckBox")); // NOI18N
625.65 mainFileTextField.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("ASCN_mainClassTextFiled")); // NOI18N
625.66 mainFileTextField.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("ASCD_mainClassTextFiled")); // NOI18N
625.67 - setAsMainCheckBox.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("ACSN_setAsMainCheckBox")); // NOI18N
625.68 - setAsMainCheckBox.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(PanelOptionsVisual.class).getString("ACSD_setAsMainCheckBox")); // NOI18N
625.69
625.70 getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(PanelOptionsVisual.class, "ACSN_PanelOptionsVisual")); // NOI18N
625.71 getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(PanelOptionsVisual.class, "ACSD_PanelOptionsVisual")); // NOI18N
625.72 @@ -286,7 +275,6 @@
625.73 }
625.74
625.75 void store( WizardDescriptor d ) {
625.76 - d.putProperty(NewPythonProjectWizardIterator.SET_AS_MAIN, setAsMainCheckBox.isSelected() && setAsMainCheckBox.isVisible() ? Boolean.TRUE : Boolean.FALSE ); // NOI18N
625.77 d.putProperty(NewPythonProjectWizardIterator.MAIN_FILE, createMainCheckBox.isSelected() && createMainCheckBox.isVisible() ? mainFileTextField.getText() : null ); // NOI18N
625.78 PythonPlatform platform = PlatformComponentFactory.getPlatform(platforms);
625.79 if (platform != null) {
625.80 @@ -300,7 +288,6 @@
625.81 private javax.swing.JTextField mainFileTextField;
625.82 private javax.swing.JButton manage;
625.83 private javax.swing.JComboBox platforms;
625.84 - private javax.swing.JCheckBox setAsMainCheckBox;
625.85 // End of variables declaration//GEN-END:variables
625.86
625.87 private void mainFileChanged () {
626.1 --- a/python.project/src/org/netbeans/modules/python/project/ui/PackageRootNode.java Sun Jan 04 13:11:53 2015 -0600
626.2 +++ b/python.project/src/org/netbeans/modules/python/project/ui/PackageRootNode.java Sun Feb 01 15:02:07 2015 -0800
626.3 @@ -155,7 +155,7 @@
626.4 public @Override String getDisplayName() {
626.5 String s = super.getDisplayName ();
626.6
626.7 - try {
626.8 + try {
626.9 s = file.getFileSystem ().getDecorator ().annotateName (s, files);
626.10 } catch (FileStateInvalidException e) {
626.11 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
627.1 --- a/python.project/src/org/netbeans/modules/python/project/ui/PackageViewChildren.java Sun Jan 04 13:11:53 2015 -0600
627.2 +++ b/python.project/src/org/netbeans/modules/python/project/ui/PackageViewChildren.java Sun Feb 01 15:02:07 2015 -0800
627.3 @@ -87,8 +87,8 @@
627.4 import org.openide.filesystems.FileRenameEvent;
627.5 import org.openide.filesystems.FileStateInvalidException;
627.6 import org.openide.filesystems.FileSystem;
627.7 +import org.openide.filesystems.FileUIUtils;
627.8 import org.openide.filesystems.FileUtil;
627.9 -import org.openide.filesystems.FileUIUtils;
627.10 import org.openide.filesystems.StatusDecorator;
627.11 import org.openide.loaders.ChangeableDataFilter;
627.12 import org.openide.loaders.DataFilter;
628.1 --- a/python.project/test/unit/data/testfiles/compl2.py Sun Jan 04 13:11:53 2015 -0600
628.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
628.3 @@ -1,1 +0,0 @@
628.4 -#Test for compl2
628.5 \ No newline at end of file
629.1 --- a/python.project/test/unit/data/testfiles/tests/compl2_test.py Sun Jan 04 13:11:53 2015 -0600
629.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
629.3 @@ -1,15 +0,0 @@
629.4 -import sys as whatever
629.5 -import os
629.6 -
629.7 -print whatever.r
629.8 -print os.r
629.9 -print sys.getfilesysteme
629.10 -
629.11 -myvar = file()
629.12 -myvar.close()
629.13 -
629.14 -myothervar = ZipFile()
629.15 -myothervar.x
629.16 -
629.17 -unknown.fai
629.18 -
630.1 --- a/python.project/test/unit/src/org/netbeans/modules/python/project/GotoTestTest.java Sun Jan 04 13:11:53 2015 -0600
630.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
630.3 @@ -1,122 +0,0 @@
630.4 -/*
630.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
630.6 - *
630.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
630.8 - *
630.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
630.10 - * Other names may be trademarks of their respective owners.
630.11 - *
630.12 - * The contents of this file are subject to the terms of either the GNU
630.13 - * General Public License Version 2 only ("GPL") or the Common
630.14 - * Development and Distribution License("CDDL") (collectively, the
630.15 - * "License"). You may not use this file except in compliance with the
630.16 - * License. You can obtain a copy of the License at
630.17 - * http://www.netbeans.org/cddl-gplv2.html
630.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
630.19 - * specific language governing permissions and limitations under the
630.20 - * License. When distributing the software, include this License Header
630.21 - * Notice in each file and include the License file at
630.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
630.23 - * particular file as subject to the "Classpath" exception as provided
630.24 - * by Oracle in the GPL Version 2 section of the License file that
630.25 - * accompanied this code. If applicable, add the following below the
630.26 - * License Header, with the fields enclosed by brackets [] replaced by
630.27 - * your own identifying information:
630.28 - * "Portions Copyrighted [year] [name of copyright owner]"
630.29 - *
630.30 - * Contributor(s):
630.31 - *
630.32 - * The Original Software is NetBeans. The Initial Developer of the Original
630.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun
630.34 - * Microsystems, Inc. All Rights Reserved.
630.35 - *
630.36 - * If you wish your version of this file to be governed by only the CDDL
630.37 - * or only the GPL Version 2, indicate your decision by adding
630.38 - * "[Contributor] elects to include this software in this distribution
630.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
630.40 - * single choice of license, a recipient has the option to distribute
630.41 - * your version of this file under either the CDDL, the GPL Version 2 or
630.42 - * to extend the choice of license to its licensees as provided above.
630.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
630.44 - * Version 2 license, then the option applies only if the new code is
630.45 - * made subject to such option by the copyright holder.
630.46 - */
630.47 -package org.netbeans.modules.python.project;
630.48 -
630.49 -import org.netbeans.modules.python.editor.PythonTestBase;
630.50 -import org.netbeans.spi.gototest.TestLocator.LocationResult;
630.51 -
630.52 -/**
630.53 - * @author Tor Norbye
630.54 - */
630.55 -public class GotoTestTest extends PythonTestBase {
630.56 -
630.57 - private GotoTest gotoTest;
630.58 -
630.59 - public GotoTestTest(String testName) {
630.60 - super(testName);
630.61 - }
630.62 - private static LocationResult NONE = null;
630.63 -
630.64 - @Override
630.65 - protected void setUp() throws Exception {
630.66 - super.setUp();
630.67 -
630.68 - gotoTest = new GotoTest();
630.69 - }
630.70 -
630.71 - public void testGotoTestUnit() {
630.72 - LocationResult loc = gotoTest.findTest(getTestFile("testfiles/compl2.py"), -1);
630.73 - assertNotSame(NONE, loc);
630.74 - assertEquals(getTestFile("testfiles/tests/compl2_test.py"), loc.getFileObject());
630.75 - }
630.76 -
630.77 - public void testGotoTestUnit2() {
630.78 - LocationResult loc = gotoTest.findTested(getTestFile("testfiles/tests/compl2_test.py"), -1);
630.79 - assertNotSame(NONE, loc);
630.80 - assertEquals(getTestFile("testfiles/compl2.py"), loc.getFileObject());
630.81 - }
630.82 -
630.83 - public void testGotoTestUnit3() {
630.84 - LocationResult loc = gotoTest.findTest(getTestFile("testfiles/foo.py"), -1);
630.85 - assertNotSame(NONE, loc);
630.86 - assertEquals(getTestFile("testfiles/foo_test.py"), loc.getFileObject());
630.87 - }
630.88 -
630.89 - public void testGotoTestUnit4() {
630.90 - LocationResult loc = gotoTest.findTested(getTestFile("testfiles/foo_test.py"), -1);
630.91 - assertNotSame(NONE, loc);
630.92 - assertEquals(getTestFile("testfiles/foo.py"), loc.getFileObject());
630.93 - }
630.94 -
630.95 - public void testGotoTestUnit5() {
630.96 - LocationResult loc = gotoTest.findTest(getTestFile("testfiles/bar.py"), -1);
630.97 - assertNotSame(NONE, loc);
630.98 - assertEquals(getTestFile("testfiles/test_bar.py"), loc.getFileObject());
630.99 - }
630.100 -
630.101 - public void testGotoTestUnit6() {
630.102 - LocationResult loc = gotoTest.findTested(getTestFile("testfiles/test_bar.py"), -1);
630.103 - assertNotSame(NONE, loc);
630.104 - assertEquals(getTestFile("testfiles/bar.py"), loc.getFileObject());
630.105 - }
630.106 -
630.107 - public void testGotoTestUnit7() {
630.108 - LocationResult loc = gotoTest.findTest(getTestFile("testfiles/dir/baz.py"), -1);
630.109 - assertNotSame(NONE, loc);
630.110 - assertEquals(getTestFile("testfiles/tests/test_baz.py"), loc.getFileObject());
630.111 - }
630.112 -
630.113 - public void testGotoTestUnit8() {
630.114 - LocationResult loc = gotoTest.findTest(getTestFile("testfiles/whatever.py"), -1);
630.115 - assertNotSame(NONE, loc);
630.116 - assertEquals(getTestFile("testfiles/testwhatever.py"), loc.getFileObject());
630.117 - }
630.118 -
630.119 - // Not yet working
630.120 - //public void testGotoTestUnit8() {
630.121 - // LocationResult loc = gotoTest.findTested(getTestFile("testfiles/tests/test_baz.py"), -1);
630.122 - // assertNotSame(NONE, loc);
630.123 - // assertEquals(getTestFile("testfiles/dir/baz.py"), loc.getFileObject());
630.124 - //}
630.125 -}
631.1 --- a/python.qshell/nbproject/project.xml Sun Jan 04 13:11:53 2015 -0600
631.2 +++ b/python.qshell/nbproject/project.xml Sun Feb 01 15:02:07 2015 -0800
631.3 @@ -48,6 +48,14 @@
631.4 </run-dependency>
631.5 </dependency>
631.6 <dependency>
631.7 + <code-name-base>org.openide.util</code-name-base>
631.8 + <build-prerequisite/>
631.9 + <compile-dependency/>
631.10 + <run-dependency>
631.11 + <specification-version>9.3</specification-version>
631.12 + </run-dependency>
631.13 + </dependency>
631.14 + <dependency>
631.15 <code-name-base>org.openide.util.ui</code-name-base>
631.16 <build-prerequisite/>
631.17 <compile-dependency/>
632.1 --- a/python.qshell/src/org/netbeans/modules/python/qshell/TermExecutor.java Sun Jan 04 13:11:53 2015 -0600
632.2 +++ b/python.qshell/src/org/netbeans/modules/python/qshell/TermExecutor.java Sun Feb 01 15:02:07 2015 -0800
632.3 @@ -101,6 +101,16 @@
632.4 pixels.height, pixels.width);
632.5 }
632.6 }
632.7 +
632.8 + @Override
632.9 + public void titleChanged(String string) {
632.10 + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
632.11 + }
632.12 +
632.13 + @Override
632.14 + public void cwdChanged(String cwd) {
632.15 + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
632.16 + }
632.17 }
632.18
632.19 private static void error(String fmt, Object...args) {
633.1 --- a/python.qshell/src/org/netbeans/modules/python/qshell/richexecution/PtyLibrary.java Sun Jan 04 13:11:53 2015 -0600
633.2 +++ b/python.qshell/src/org/netbeans/modules/python/qshell/richexecution/PtyLibrary.java Sun Feb 01 15:02:07 2015 -0800
633.3 @@ -47,6 +47,7 @@
633.4 import com.sun.jna.Library;
633.5 import com.sun.jna.Native;
633.6 import com.sun.jna.Structure;
633.7 +import java.util.List;
633.8
633.9 public interface PtyLibrary extends Library {
633.10
633.11 @@ -64,6 +65,11 @@
633.12 this.ws_xpixel = (short) width;
633.13 this.ws_ypixel = (short) height;
633.14 }
633.15 +
633.16 + @Override
633.17 + protected List getFieldOrder() {
633.18 + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
633.19 + }
633.20 }
633.21
633.22 // struct termios
633.23 @@ -80,6 +86,11 @@
633.24 public Termios() {
633.25 c_cc = new byte[NCCS];
633.26 }
633.27 +
633.28 + @Override
633.29 + protected List getFieldOrder() {
633.30 + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
633.31 + }
633.32 }
633.33
633.34 public PtyLibrary INSTANCE = (PtyLibrary) Native.loadLibrary("c", PtyLibrary.class);
634.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
634.2 +++ b/python.source/build.xml Sun Feb 01 15:02:07 2015 -0800
634.3 @@ -0,0 +1,8 @@
634.4 +<?xml version="1.0" encoding="UTF-8"?>
634.5 +<!-- You may freely edit this file. See harness/README in the NetBeans platform -->
634.6 +<!-- for some information on what you could do (e.g. targets to override). -->
634.7 +<!-- If you delete this file and reopen the project it will be recreated. -->
634.8 +<project name="contrib/python.source" default="netbeans" basedir=".">
634.9 + <description>Builds, tests, and runs the project org.netbeans.modules.python.source.</description>
634.10 + <import file="../../nbbuild/templates/projectized.xml"/>
634.11 +</project>
635.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
635.2 +++ b/python.source/manifest.mf Sun Feb 01 15:02:07 2015 -0800
635.3 @@ -0,0 +1,5 @@
635.4 +Manifest-Version: 1.0
635.5 +OpenIDE-Module: org.netbeans.modules.python.source
635.6 +OpenIDE-Module-Localizing-Bundle: org/netbeans/modules/python/source/Bundle.properties
635.7 +OpenIDE-Module-Specification-Version: 1.0
635.8 +AutoUpdate-Show-In-Client: false
636.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
636.2 +++ b/python.source/nbproject/project.properties Sun Feb 01 15:02:07 2015 -0800
636.3 @@ -0,0 +1,2 @@
636.4 +javac.source=1.6
636.5 +javac.compilerargs=-Xlint -Xlint:-serial
637.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
637.2 +++ b/python.source/nbproject/project.xml Sun Feb 01 15:02:07 2015 -0800
637.3 @@ -0,0 +1,48 @@
637.4 +<?xml version="1.0" encoding="UTF-8"?>
637.5 +<project xmlns="http://www.netbeans.org/ns/project/1">
637.6 + <type>org.netbeans.modules.apisupport.project</type>
637.7 + <configuration>
637.8 + <data xmlns="http://www.netbeans.org/ns/nb-module-project/3">
637.9 + <code-name-base>org.netbeans.modules.python.source</code-name-base>
637.10 + <!--<suite-component/>-->
637.11 + <module-dependencies>
637.12 + <dependency>
637.13 + <code-name-base>org.netbeans.api.annotations.common</code-name-base>
637.14 + <build-prerequisite/>
637.15 + <compile-dependency/>
637.16 + <run-dependency>
637.17 + <release-version>1</release-version>
637.18 + <specification-version>1.24.1</specification-version>
637.19 + </run-dependency>
637.20 + </dependency>
637.21 + <dependency>
637.22 + <code-name-base>org.openide.filesystems</code-name-base>
637.23 + <build-prerequisite/>
637.24 + <compile-dependency/>
637.25 + <run-dependency>
637.26 + <specification-version>8.12.1</specification-version>
637.27 + </run-dependency>
637.28 + </dependency>
637.29 + <dependency>
637.30 + <code-name-base>org.openide.util</code-name-base>
637.31 + <build-prerequisite/>
637.32 + <compile-dependency/>
637.33 + <run-dependency>
637.34 + <specification-version>8.39.1</specification-version>
637.35 + </run-dependency>
637.36 + </dependency>
637.37 + <dependency>
637.38 + <code-name-base>org.openide.util.lookup</code-name-base>
637.39 + <build-prerequisite/>
637.40 + <compile-dependency/>
637.41 + <run-dependency>
637.42 + <specification-version>8.25.1</specification-version>
637.43 + </run-dependency>
637.44 + </dependency>
637.45 + </module-dependencies>
637.46 + <public-packages>
637.47 + <package>org.netbeans.modules.python.source.queries</package>
637.48 + </public-packages>
637.49 + </data>
637.50 + </configuration>
637.51 +</project>
638.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
638.2 +++ b/python.source/src/org/netbeans/modules/python/source/Bundle.properties Sun Feb 01 15:02:07 2015 -0800
638.3 @@ -0,0 +1,1 @@
638.4 +OpenIDE-Module-Name=Python Source
639.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
639.2 +++ b/python.source/src/org/netbeans/modules/python/source/queries/SourceLevelQuery.java Sun Feb 01 15:02:07 2015 -0800
639.3 @@ -0,0 +1,240 @@
639.4 +/*
639.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
639.6 + *
639.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
639.8 + *
639.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
639.10 + * Other names may be trademarks of their respective owners.
639.11 + *
639.12 + * The contents of this file are subject to the terms of either the GNU
639.13 + * General Public License Version 2 only ("GPL") or the Common
639.14 + * Development and Distribution License("CDDL") (collectively, the
639.15 + * "License"). You may not use this file except in compliance with the
639.16 + * License. You can obtain a copy of the License at
639.17 + * http://www.netbeans.org/cddl-gplv2.html
639.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
639.19 + * specific language governing permissions and limitations under the
639.20 + * License. When distributing the software, include this License Header
639.21 + * Notice in each file and include the License file at
639.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
639.23 + * particular file as subject to the "Classpath" exception as provided
639.24 + * by Oracle in the GPL Version 2 section of the License file that
639.25 + * accompanied this code. If applicable, add the following below the
639.26 + * License Header, with the fields enclosed by brackets [] replaced by
639.27 + * your own identifying information:
639.28 + * "Portions Copyrighted [year] [name of copyright owner]"
639.29 + *
639.30 + * Contributor(s):
639.31 + *
639.32 + * The Original Software is NetBeans. The Initial Developer of the Original
639.33 + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
639.34 + * Microsystems, Inc. All Rights Reserved.
639.35 + *
639.36 + * If you wish your version of this file to be governed by only the CDDL
639.37 + * or only the GPL Version 2, indicate your decision by adding
639.38 + * "[Contributor] elects to include this software in this distribution
639.39 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
639.40 + * single choice of license, a recipient has the option to distribute
639.41 + * your version of this file under either the CDDL, the GPL Version 2 or
639.42 + * to extend the choice of license to its licensees as provided above.
639.43 + * However, if you add GPL Version 2 code and therefore, elected the GPL
639.44 + * Version 2 license, then the option applies only if the new code is
639.45 + * made subject to such option by the copyright holder.
639.46 + */
639.47 +
639.48 +package org.netbeans.modules.python.source.queries;
639.49 +
639.50 +import java.text.MessageFormat;
639.51 +import java.util.logging.Level;
639.52 +import java.util.logging.Logger;
639.53 +import java.util.regex.Matcher;
639.54 +import java.util.regex.Pattern;
639.55 +import javax.swing.event.ChangeEvent;
639.56 +import javax.swing.event.ChangeListener;
639.57 +import org.netbeans.api.annotations.common.CheckForNull;
639.58 +import org.netbeans.api.annotations.common.NonNull;
639.59 +import org.netbeans.api.annotations.common.NullAllowed;
639.60 +import org.openide.filesystems.FileObject;
639.61 +import org.openide.util.ChangeSupport;
639.62 +import org.openide.util.Lookup;
639.63 +import org.openide.util.Parameters;
639.64 +import org.openide.util.Union2;
639.65 +import org.openide.util.WeakListeners;
639.66 +
639.67 +/**
639.68 + * Returns source level of the given Python file if it is known.
639.69 + * @author David Konecny
639.70 + * @author Tomas Zezula
639.71 + * @author Ralph Benjamin Ruijs
639.72 + */
639.73 +public final class SourceLevelQuery {
639.74 +
639.75 + private static final Logger LOGGER = Logger.getLogger(SourceLevelQuery.class.getName());
639.76 +
639.77 + private static final Pattern SOURCE_LEVEL = Pattern.compile("Python.(\\d+\\.\\d+)\\.\\d+"); //NOI18N
639.78 + private static final Pattern SYNONYM = Pattern.compile("\\d+");//NOI18N
639.79 +
639.80 + private static final Lookup.Result<? extends SourceLevelQueryImplementation> impls =
639.81 + Lookup.getDefault().lookupResult (SourceLevelQueryImplementation.class);
639.82 +
639.83 + private SourceLevelQuery() {
639.84 + }
639.85 +
639.86 + /**
639.87 + * Returns a source level of the given Python file, Python package or source folder.
639.88 + * @param pythonFile Python source file, Python package or source folder in question
639.89 + * @return a {@link Result} object encapsulating the source level of the Python file. Results created for source
639.90 + * levels provided by the {@link SourceLevelQueryImplementation} do not support listening. Use {@link Result#supportsChanges()}
639.91 + * to check if the result supports listening.
639.92 + */
639.93 + @SuppressWarnings("deprecation")
639.94 + public static @NonNull Result getSourceLevelResult(final @NonNull FileObject pythonFile) {
639.95 + for (SourceLevelQueryImplementation sqi : impls.allInstances()) {
639.96 + final SourceLevelQueryImplementation.Result result = sqi.getSourceLevel(pythonFile);
639.97 + if (result != null) {
639.98 + if (LOGGER.isLoggable(Level.FINE)) {
639.99 + LOGGER.log(Level.FINE, "Found source level {0} for {1} from {2}", new Object[] {result, pythonFile, sqi}); //NOI18N
639.100 + }
639.101 + return new Result(result);
639.102 + }
639.103 + }
639.104 + LOGGER.log(Level.FINE, "No source level found for {0}", pythonFile);
639.105 + return new Result(pythonFile);
639.106 + }
639.107 +
639.108 + public static String getSourceLevel(FileObject javaFile) {
639.109 + for (SourceLevelQueryImplementation sqi : impls.allInstances()) {
639.110 + final SourceLevelQueryImplementation.Result result = sqi.getSourceLevel(javaFile);
639.111 + if (result != null) {
639.112 + final String s = normalize(result.getSourceLevel());
639.113 + if (s != null) {
639.114 + Matcher matcher = SOURCE_LEVEL.matcher(s);
639.115 + if (!matcher.matches()) {
639.116 + LOGGER.log(Level.WARNING, "#83994: Ignoring bogus source level {0} for {1} from {2}", new Object[] {s, javaFile, sqi}); //NOI18N
639.117 + continue;
639.118 + }
639.119 + if (LOGGER.isLoggable(Level.FINE)) {
639.120 + LOGGER.log(Level.FINE, "Found source level {0} for {1} from {2}", new Object[] {s, javaFile, sqi}); //NOI18N
639.121 + }
639.122 + return matcher.group(1);
639.123 + }
639.124 + }
639.125 + }
639.126 + LOGGER.log(Level.FINE, "No source level found for {0}", javaFile);
639.127 + return null;
639.128 + }
639.129 +
639.130 + /**
639.131 + * Result of finding source level, encapsulating the answer as well as the
639.132 + * ability to listen to it.
639.133 + */
639.134 + public static final class Result {
639.135 +
639.136 + private final @NonNull Union2<SourceLevelQueryImplementation.Result,FileObject> delegate;
639.137 + private final ChangeSupport cs = new ChangeSupport(this);
639.138 + private /**@GuardedBy("this")*/ ChangeListener spiListener;
639.139 +
639.140 + private Result(@NonNull final SourceLevelQueryImplementation.Result delegate) {
639.141 + Parameters.notNull("delegate", delegate); //NOI18N
639.142 + this.delegate = Union2.<SourceLevelQueryImplementation.Result,FileObject>createFirst(delegate);
639.143 + }
639.144 +
639.145 + private Result(@NonNull final FileObject javaFile) {
639.146 + Parameters.notNull("sourceLevel", javaFile);
639.147 + this.delegate = Union2.<SourceLevelQueryImplementation.Result,FileObject>createSecond(javaFile);
639.148 + }
639.149 +
639.150 + /**
639.151 + * Get the source level.
639.152 + * @return a source level of the Python file, e.g. "2.7", "3.0", "3.1"
639.153 + * or null if the source level is unknown. Even it is allowed for a SPI implementation to return
639.154 + * a source level synonym e.g. "3" for "3.0+" the returned value is always normalized.
639.155 + */
639.156 + public @CheckForNull String getSourceLevel() {
639.157 + if (delegate.hasFirst()) {
639.158 + String sourceLevel = normalize(delegate.first().getSourceLevel());
639.159 + Matcher matcher = SOURCE_LEVEL.matcher(sourceLevel);
639.160 + if (sourceLevel != null && !matcher.matches()) {
639.161 + LOGGER.log(
639.162 + Level.WARNING,
639.163 + "#83994: Ignoring bogus source level {0} from {2}", //NOI18N
639.164 + new Object[] {
639.165 + sourceLevel,
639.166 + delegate.first()
639.167 + });
639.168 + sourceLevel = null;
639.169 + }
639.170 + return matcher.group(1);
639.171 + } else {
639.172 + return SourceLevelQuery.getSourceLevel(delegate.second());
639.173 + }
639.174 + }
639.175 +
639.176 +
639.177 + /**
639.178 + * Add a listener to changes of source level.
639.179 + * If {@link #supportsChanges} is false, the listener will never be notified
639.180 + * although {@link #getSourceLevel} may change from call to call.
639.181 + * @param listener a listener to add
639.182 + */
639.183 + public void addChangeListener(@NonNull ChangeListener listener) {
639.184 + Parameters.notNull("listener", listener); //NOI18N
639.185 + final SourceLevelQueryImplementation.Result _delegate = getDelegate();
639.186 + if (_delegate == null) {
639.187 + return;
639.188 + }
639.189 + cs.addChangeListener(listener);
639.190 + synchronized (this) {
639.191 + if (spiListener == null) {
639.192 + spiListener = new ChangeListener() {
639.193 + @Override
639.194 + public void stateChanged(ChangeEvent e) {
639.195 + cs.fireChange();
639.196 + }
639.197 + };
639.198 + _delegate.addChangeListener(WeakListeners.change(spiListener, _delegate));
639.199 + }
639.200 + }
639.201 +
639.202 + }
639.203 +
639.204 + /**
639.205 + * Remove a listener to changes of source level.
639.206 + * @param listener a listener to add
639.207 + */
639.208 + public void removeChangeListener(@NonNull ChangeListener listener) {
639.209 + Parameters.notNull("listener", listener); //NOI18N
639.210 + final SourceLevelQueryImplementation.Result _delegate = getDelegate();
639.211 + if (_delegate == null) {
639.212 + return;
639.213 + }
639.214 + cs.removeChangeListener(listener);
639.215 + }
639.216 +
639.217 + /**
639.218 + * Returns true if the result support updates and client may
639.219 + * listen on it. If false client should always ask again to
639.220 + * obtain current value. The results created for values returned
639.221 + * by the {@link SourceLevelQueryImplementation} do not support
639.222 + * listening.
639.223 + * @return true if the result supports changes and listening
639.224 + */
639.225 + public boolean supportsChanges() {
639.226 + return getDelegate() != null;
639.227 + }
639.228 +
639.229 + private SourceLevelQueryImplementation.Result getDelegate() {
639.230 + return delegate.hasFirst() ? delegate.first() : null;
639.231 + }
639.232 + }
639.233 +
639.234 + @CheckForNull
639.235 + private static String normalize(@NullAllowed String sourceLevel) {
639.236 + if (sourceLevel != null && SYNONYM.matcher(sourceLevel).matches()) {
639.237 + sourceLevel = MessageFormat.format("1.{0}", sourceLevel); //NOI18N
639.238 + }
639.239 + return sourceLevel;
639.240 + }
639.241 +
639.242 +}
639.243 +
640.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
640.2 +++ b/python.source/src/org/netbeans/modules/python/source/queries/SourceLevelQueryImplementation.java Sun Feb 01 15:02:07 2015 -0800
640.3 @@ -0,0 +1,103 @@
640.4 +/*
640.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
640.6 + *
640.7 + * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
640.8 + *
640.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
640.10 + * Other names may be trademarks of their respective owners.
640.11 + *
640.12 + * The contents of this file are subject to the terms of either the GNU
640.13 + * General Public License Version 2 only ("GPL") or the Common
640.14 + * Development and Distribution License("CDDL") (collectively, the
640.15 + * "License"). You may not use this file except in compliance with the
640.16 + * License. You can obtain a copy of the License at
640.17 + * http://www.netbeans.org/cddl-gplv2.html
640.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
640.19 + * specific language governing permissions and limitations under the
640.20 + * License. When distributing the software, include this License Header
640.21 + * Notice in each file and include the License file at
640.22 + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
640.23 + * particular file as subject to the "Classpath" exception as provided
640.24 + * by Oracle in the GPL Version 2 section of the License file that
640.25 + * accompanied this code. If applicable, add the following below the
640.26 + * License Header, with the fields enclosed by brackets [] replaced by
640.27 + * your own identifying information:
640.28 + * "Portions Copyrighted [year] [name of copyright owner]"
640.29 + *
640.30 + * If you wish your version of this file to be governed by only the CDDL
640.31 + * or only the GPL Version 2, indicate your decision by adding
640.32 + * "[Contributor] elects to include this software in this distribution
640.33 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
640.34 + * single choice of license, a recipient has the option to distribute
640.35 + * your version of this file under either the CDDL, the GPL Version 2 or
640.36 + * to extend the choice of license to its licensees as provided above.
640.37 + * However, if you add GPL Version 2 code and therefore, elected the GPL
640.38 + * Version 2 license, then the option applies only if the new code is
640.39 + * made subject to such option by the copyright holder.
640.40 + *
640.41 + * Contributor(s):
640.42 + *
640.43 + * Portions Copyrighted 2010 Sun Microsystems, Inc.
640.44 + */
640.45 +
640.46 +package org.netbeans.modules.python.source.queries;
640.47 +
640.48 +import javax.swing.event.ChangeListener;
640.49 +import org.netbeans.api.annotations.common.CheckForNull;
640.50 +import org.netbeans.api.annotations.common.NonNull;
640.51 +import org.openide.filesystems.FileObject;
640.52 +
640.53 +/**
640.54 + *
640.55 + * Permits providers to return specification source level of Java source file.
640.56 + * <p>
640.57 + * A default implementation is registered by the
640.58 + * <code>org.netbeans.modules.python.project</code> module which looks up the
640.59 + * project corresponding to the file (if any) and checks whether that
640.60 + * project has an implementation of this interface in its lookup. If so, it
640.61 + * delegates to that implementation. Therefore it is not generally necessary
640.62 + * for a project type provider to register its own global implementation of
640.63 + * this query, if it depends on the Python Project module and uses this style.
640.64 + * </p>
640.65 + * @see org.netbeans.modules.python.source.queries.SourceLevelQuery
640.66 + * @author Tomas Zezula
640.67 + * @author Ralph Benjamin Ruijs
640.68 + */
640.69 +public interface SourceLevelQueryImplementation {
640.70 +
640.71 + /**
640.72 + * Returns source level of the given Python file.
640.73 + * @param pythonFile Python source file in question
640.74 + * @return source level of the Python file encapsulated as {@link Result}, or
640.75 + * null if the file is not handled by this provider.
640.76 + */
640.77 + Result getSourceLevel(FileObject pythonFile);
640.78 +
640.79 + /**
640.80 + * Result of finding source level, encapsulating the answer as well as the
640.81 + * ability to listen to it.
640.82 + */
640.83 + interface Result {
640.84 +
640.85 + /**
640.86 + * Get the source level.
640.87 + * @return a source level of the Python file, e.g. "2.6", "3.0", "3.1"
640.88 + * or null if the source level is unknown. It is allowed to return source level synonyms
640.89 + * e.g. "3" for "Python 3". These synonyms are always normalized by
640.90 + * {@link SourceLevelQuery#getSourceLevel}.
640.91 + */
640.92 + @CheckForNull String getSourceLevel();
640.93 +
640.94 + /**
640.95 + * Add a listener to changes of source level.
640.96 + * @param listener a listener to add
640.97 + */
640.98 + void addChangeListener(@NonNull ChangeListener listener);
640.99 +
640.100 + /**
640.101 + * Remove a listener to changes of source level.
640.102 + * @param listener a listener to add
640.103 + */
640.104 + void removeChangeListener(@NonNull ChangeListener listener);
640.105 + }
640.106 +}
641.1 --- a/python.testrunner/nbproject/project.xml Sun Jan 04 13:11:53 2015 -0600
641.2 +++ b/python.testrunner/nbproject/project.xml Sun Feb 01 15:02:07 2015 -0800
641.3 @@ -236,20 +236,6 @@
641.4 </run-dependency>
641.5 </dependency>
641.6 </module-dependencies>
641.7 - <test-dependencies>
641.8 - <test-type>
641.9 - <name>unit</name>
641.10 - <test-dependency>
641.11 - <code-name-base>org.netbeans.libs.junit4</code-name-base>
641.12 - <compile-dependency/>
641.13 - </test-dependency>
641.14 - <test-dependency>
641.15 - <code-name-base>org.netbeans.modules.nbjunit</code-name-base>
641.16 - <recursive/>
641.17 - <compile-dependency/>
641.18 - </test-dependency>
641.19 - </test-type>
641.20 - </test-dependencies>
641.21 <public-packages/>
641.22 </data>
641.23 </configuration>
642.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/Bundle.properties Sun Jan 04 13:11:53 2015 -0600
642.2 +++ b/python.testrunner/src/org/netbeans/modules/python/testrunner/Bundle.properties Sun Feb 01 15:02:07 2015 -0800
642.3 @@ -1,14 +1,1 @@
642.4 -OpenIDE-Module-Name=Python Test Runner
642.5 -OpenIDE-Module-Display-Category=Python
642.6 -OpenIDE-Module-Short-Description=Python Test Runner
642.7 -OpenIDE-Module-Long-Description=\
642.8 - Provides support for running and displaying Test/Unit and RSpec tests.
642.9 -
642.10 -# {0} - project name
642.11 -AutoTest=AutoTest ({0})
642.12 -MSG_SpecOptsWarning = [Using {0}; create {1} to set options used under the IDE. \
642.13 - Suppress this warning message by adding \
642.14 - -J-D{2}=false to the flags in etc/netbeans.conf]
642.15 -
642.16 -# RspecRunner
642.17 -MSG_SpecNotFound = Could not find the 'spec' executable. Make sure it is on the path.
642.18 +OpenIDE-Module-Name=PythonTestrunner
643.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/PyUnitRunner.java Sun Jan 04 13:11:53 2015 -0600
643.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
643.3 @@ -1,341 +0,0 @@
643.4 -/*
643.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
643.6 - *
643.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
643.8 - *
643.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
643.10 - * Other names may be trademarks of their respective owners.
643.11 - *
643.12 - * The contents of this file are subject to the terms of either the GNU
643.13 - * General Public License Version 2 only ("GPL") or the Common
643.14 - * Development and Distribution License("CDDL") (collectively, the
643.15 - * "License"). You may not use this file except in compliance with the
643.16 - * License. You can obtain a copy of the License at
643.17 - * http://www.netbeans.org/cddl-gplv2.html
643.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
643.19 - * specific language governing permissions and limitations under the
643.20 - * License. When distributing the software, include this License Header
643.21 - * Notice in each file and include the License file at
643.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
643.23 - * particular file as subject to the "Classpath" exception as provided
643.24 - * by Oracle in the GPL Version 2 section of the License file that
643.25 - * accompanied this code. If applicable, add the following below the
643.26 - * License Header, with the fields enclosed by brackets [] replaced by
643.27 - * your own identifying information:
643.28 - * "Portions Copyrighted [year] [name of copyright owner]"
643.29 - *
643.30 - * If you wish your version of this file to be governed by only the CDDL
643.31 - * or only the GPL Version 2, indicate your decision by adding
643.32 - * "[Contributor] elects to include this software in this distribution
643.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
643.34 - * single choice of license, a recipient has the option to distribute
643.35 - * your version of this file under either the CDDL, the GPL Version 2 or
643.36 - * to extend the choice of license to its licensees as provided above.
643.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
643.38 - * Version 2 license, then the option applies only if the new code is
643.39 - * made subject to such option by the copyright holder.
643.40 - *
643.41 - * Contributor(s):
643.42 - *
643.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
643.44 - */
643.45 -package org.netbeans.modules.python.testrunner;
643.46 -
643.47 -import java.io.File;
643.48 -import java.util.ArrayList;
643.49 -import java.util.List;
643.50 -import java.util.Map;
643.51 -import java.util.logging.Level;
643.52 -import java.util.logging.Logger;
643.53 -import org.netbeans.api.project.FileOwnerQuery;
643.54 -import org.netbeans.api.project.Project;
643.55 -import org.netbeans.api.project.ProjectUtils;
643.56 -import org.netbeans.modules.gsf.testrunner.api.TestSession;
643.57 -import org.netbeans.modules.gsf.testrunner.api.TestSession.SessionType;
643.58 -import org.netbeans.modules.gsf.testrunner.ui.api.Manager;
643.59 -import org.netbeans.modules.python.api.PythonExecution;
643.60 -import org.netbeans.modules.python.api.PythonPlatform;
643.61 -import org.netbeans.modules.python.editor.codecoverage.PythonCoverageProvider;
643.62 -import org.netbeans.modules.python.project.PythonProject;
643.63 -import org.netbeans.modules.python.project.spi.TestRunner;
643.64 -import org.netbeans.modules.python.project.ui.customizer.PythonProjectProperties;
643.65 -import org.netbeans.modules.python.testrunner.ui.PyUnitHandlerFactory;
643.66 -import org.openide.filesystems.FileObject;
643.67 -import org.openide.filesystems.FileUtil;
643.68 -import org.openide.modules.InstalledFileLocator;
643.69 -import org.openide.util.BaseUtilities;
643.70 -
643.71 -/**
643.72 - * Test runner implmentation for running PyUnit tests
643.73 - *
643.74 - * @author Erno Mononen
643.75 - */
643.76 -@org.openide.util.lookup.ServiceProviders({/*@org.openide.util.lookup.ServiceProvider(service=org.netbeans.modules.python.pythonproject.spi.RakeTaskCustomizer.class), */@org.openide.util.lookup.ServiceProvider(service=org.netbeans.modules.python.project.spi.TestRunner.class)})
643.77 -public final class PyUnitRunner implements TestRunner/*, RakeTaskCustomizer*/ {
643.78 -
643.79 - private static final Logger LOGGER = Logger.getLogger(PyUnitRunner.class.getName());
643.80 - private static final String NB_TEST_RUNNER = "NB_TEST_RUNNER"; //NOI18N
643.81 - //public static final String MEDIATOR_SCRIPT_NAME = "nb_test_mediator.py"; //NOI18N
643.82 - public static final String RUNNER_SCRIPT_NAME = "nb_test_runner.py"; //NOI18N
643.83 - private static final TestRunner INSTANCE = new PyUnitRunner();
643.84 -
643.85 - static {
643.86 - // this env variable is referenced from nb_test_runner.py, where it
643.87 - // gets appended to the rake require path
643.88 - System.setProperty(NB_TEST_RUNNER, getScript(RUNNER_SCRIPT_NAME).getAbsolutePath());
643.89 - }
643.90 -
643.91 - public TestRunner getInstance() {
643.92 - return INSTANCE;
643.93 - }
643.94 -
643.95 - public void runSingleTest(FileObject testFile, String className, String testMethod, boolean debug) {
643.96 - List<String> additionalArgs = getTestFileArgs(testFile);
643.97 - additionalArgs.add("-m"); // NOI18N
643.98 - String methodRef;
643.99 - String file = additionalArgs.get(1);
643.100 - if (className.startsWith(file+".")) { // NOI18N
643.101 - className = className.substring(file.length()+1);
643.102 - }
643.103 - methodRef = className + "." + testMethod; // NOI18N
643.104 - additionalArgs.add(methodRef);
643.105 - run(FileOwnerQuery.getOwner(testFile), additionalArgs, testMethod, debug);
643.106 - }
643.107 -
643.108 - public void runTest(FileObject testFile, boolean debug) {
643.109 - Project project = FileOwnerQuery.getOwner(testFile);
643.110 - if (!testFile.isFolder()) {
643.111 - run(project, getTestFileArgs(testFile), testFile.getName(), debug);
643.112 - } else {
643.113 - List<String> additionalArgs = new ArrayList<String>();
643.114 - additionalArgs.add("-d"); //NOI18N
643.115 - additionalArgs.add(FileUtil.toFile(testFile).getAbsolutePath());
643.116 - String name = ProjectUtils.getInformation(project).getDisplayName();
643.117 - run(project, additionalArgs, name, debug);
643.118 - }
643.119 - }
643.120 -
643.121 - private List<String> getTestFileArgs(FileObject testFile) {
643.122 - Project project = FileOwnerQuery.getOwner(testFile);
643.123 - String testFilePath = FileUtil.toFile(testFile).getAbsolutePath();
643.124 - if (project instanceof PythonProject) {
643.125 - PythonProject pythonPrj = (PythonProject)project;
643.126 - FileObject root = null;
643.127 - for (FileObject r : pythonPrj.getSourceRootFiles()) {
643.128 - if (FileUtil.isParentOf(r, testFile)) {
643.129 - root = r;
643.130 - break;
643.131 - }
643.132 - }
643.133 - if (root == null) {
643.134 - for (FileObject r : pythonPrj.getTestSourceRootFiles()) {
643.135 - if (FileUtil.isParentOf(r, testFile)) {
643.136 - root = r;
643.137 - break;
643.138 - }
643.139 - }
643.140 - }
643.141 -
643.142 - if (root != null) {
643.143 - String rootPath = FileUtil.toFile(root).getAbsolutePath();
643.144 - if (testFilePath.startsWith(rootPath)) {
643.145 - testFilePath = testFilePath.substring(rootPath.length());
643.146 - if (testFilePath.startsWith("/") || testFilePath.startsWith("\\")) { // NOI18N
643.147 - testFilePath = testFilePath.substring(1);
643.148 - }
643.149 -
643.150 - testFilePath = testFilePath.replace("\\", ".");
643.151 - testFilePath = testFilePath.replace("/", ".");
643.152 -
643.153 - if (testFilePath.endsWith(".py")) {
643.154 - testFilePath = testFilePath.substring(0, testFilePath.length()-3);
643.155 - }
643.156 - }
643.157 - }
643.158 - }
643.159 - List<String> additionalArgs = new ArrayList<String>();
643.160 - additionalArgs.add("-f"); //NOI18N
643.161 - additionalArgs.add(testFilePath);
643.162 - return additionalArgs;
643.163 - }
643.164 -
643.165 - private static File getScript(String name) {
643.166 - File script = InstalledFileLocator.getDefault().locate(
643.167 - name, "org.netbeans.modules.python.testrunner", false); // NOI18N
643.168 -
643.169 - if (script == null) {
643.170 - throw new IllegalStateException("Could not locate " + name); // NOI18N
643.171 -
643.172 - }
643.173 - return script;
643.174 -
643.175 - }
643.176 -
643.177 - static void addPyUnitRunnerToEnv(Map<String, String> env) {
643.178 - env.put(NB_TEST_RUNNER, getScript(RUNNER_SCRIPT_NAME).getAbsolutePath());
643.179 - }
643.180 -
643.181 - public void runAllTests(Project project, boolean debug) {
643.182 - List<String> additionalArgs = new ArrayList<String>();
643.183 - PythonProject baseProject = project.getLookup().lookup(PythonProject.class);
643.184 - boolean haveTestFolders = false;
643.185 - for (FileObject testDir : baseProject.getTestSourceRootFiles()) {
643.186 - additionalArgs.add("-d"); //NOI18N
643.187 - additionalArgs.add(FileUtil.toFile(testDir).getAbsolutePath());
643.188 - haveTestFolders = true;
643.189 - }
643.190 - if (!haveTestFolders) {
643.191 - for (FileObject testDir : baseProject.getSourceRootFiles()) {
643.192 - additionalArgs.add("-d"); //NOI18N
643.193 - additionalArgs.add(FileUtil.toFile(testDir).getAbsolutePath());
643.194 - }
643.195 - }
643.196 -
643.197 - String name = ProjectUtils.getInformation(project).getDisplayName();
643.198 -
643.199 - run(project, additionalArgs, name, debug);
643.200 - }
643.201 -
643.202 - protected ArrayList<String> buildPythonPath( PythonPlatform platform , PythonProject project ) {
643.203 - final ArrayList<String> pythonPath = new ArrayList<String>() ;
643.204 - // start with platform
643.205 - pythonPath.addAll(platform.getPythonPath());
643.206 - for (FileObject fo : project.getSourceRoots().getRoots()) {
643.207 - File f = FileUtil.toFile(fo);
643.208 - pythonPath.add(f.getAbsolutePath());
643.209 - }
643.210 - for (FileObject fo : project.getTestRoots().getRoots()) {
643.211 - File f = FileUtil.toFile(fo);
643.212 - pythonPath.add(f.getAbsolutePath());
643.213 - }
643.214 - PythonProjectProperties properties = new PythonProjectProperties(project);
643.215 - pythonPath.addAll(properties.getPythonPath());
643.216 - return pythonPath ;
643.217 - }
643.218 -
643.219 - /**
643.220 - *
643.221 - * provide a reasonable common Build of JAVAPATH for Run or Debug Jython commands
643.222 - * @param platform current platform
643.223 - * @param project current project
643.224 - * @return JavaPath fileList for jython CLASSPATH command
643.225 - */
643.226 - protected ArrayList<String> buildJavaPath( PythonPlatform platform , PythonProject project ) {
643.227 - final ArrayList<String> javaPath = new ArrayList<String>() ;
643.228 - // start with platform
643.229 - javaPath.addAll(platform.getJavaPath());
643.230 - PythonProjectProperties properties = new PythonProjectProperties(project);
643.231 - javaPath.addAll(properties.getJavaPath());
643.232 - return javaPath ;
643.233 - }
643.234 -
643.235 - private void run(Project project, List<String> additionalArgs, String name, boolean debug) {
643.236 - PythonPlatform platform = PythonPlatform.platformFor(project);
643.237 -
643.238 - //String targetPath = getScript(MEDIATOR_SCRIPT_NAME).getAbsolutePath();
643.239 - PythonExecution desc = null;
643.240 - desc = new PythonExecution();
643.241 -
643.242 - // TODO: Handle debugging...
643.243 - // Requires some coordination between the test infrastructure (which wants to own it through
643.244 - // its TestExecutionManager.start call) and debugging (which wants to own it through its
643.245 - // DebugPythonSource.startDebugging call
643.246 -
643.247 - // TODO - handle passing arguments to the script.
643.248 - // The PythonExecution descriptor needs work.
643.249 -
643.250 - //String charsetName = null;
643.251 - //FileLocator locator = project.getLookup().lookup(FileLocator.class);
643.252 -// desc.additionalArgs(additionalArgs.toArray(new String[additionalArgs.size()]));
643.253 -// desc.initialArgs(PythonProjectUtil.getLoadPath(project)); //NOI18N
643.254 -//
643.255 -// desc.debug(debug);
643.256 -// desc.allowInput();
643.257 -// desc.fileLocator(locator);
643.258 -
643.259 - File pwd = FileUtil.toFile(project.getProjectDirectory());
643.260 -
643.261 - desc.setDisplayName(name);
643.262 - desc.setScriptArgs(BaseUtilities.escapeParameters(additionalArgs.toArray(new String[additionalArgs.size()])));
643.263 - desc.setWorkingDirectory(pwd.getAbsolutePath());
643.264 - desc.setCommand(platform.getInterpreterCommand());
643.265 - desc.setScript(getScript(RUNNER_SCRIPT_NAME).getAbsolutePath());
643.266 - desc.setCommandArgs(platform.getInterpreterArgs());
643.267 - if (project instanceof PythonProject) {
643.268 - PythonProject pythonProject = (PythonProject)project;
643.269 - desc.setPath(PythonPlatform.buildPath(buildPythonPath(platform, pythonProject)));
643.270 - desc.setJavaPath(PythonPlatform.buildPath(buildJavaPath(platform, pythonProject)));
643.271 - }
643.272 - desc.setShowControls(true);
643.273 - desc.setShowInput(true);
643.274 - desc.setShowWindow(true);
643.275 - desc.addStandardRecognizers();
643.276 -
643.277 - PythonCoverageProvider coverageProvider = PythonCoverageProvider.get(project);
643.278 - if (coverageProvider != null && coverageProvider.isEnabled()) {
643.279 - desc = coverageProvider.wrapWithCoverage(desc);
643.280 - }
643.281 -
643.282 - if (LOGGER.isLoggable(Level.INFO)) {
643.283 - LOGGER.log(Level.INFO, "Running Python Unit Test with the following descriptor: command={0} " +
643.284 - "commandArgs={1} displayName={2} javaPath={3} path={4} script={5} scriptArgs={6}" +
643.285 - " workingDirectory={7}", new Object[]{desc.getCommand(), desc.getCommandArgs(),
643.286 - desc.getDisplayName(), desc.getJavaPath(), desc.getPath(), desc.getScript(),
643.287 - desc.getScriptArgs(), desc.getWorkingDirectory()});
643.288 - }
643.289 - Manager.getInstance().setNodeFactory(new PythonTestRunnerNodeFactory());
643.290 - final TestSession session = new TestSession(name,
643.291 - project,
643.292 - debug ? SessionType.DEBUG : SessionType.TEST);
643.293 -
643.294 - TestExecutionManager.getInstance().start(desc, new PyUnitHandlerFactory(), session);
643.295 - }
643.296 -
643.297 - public boolean supports(TestType type) {
643.298 - return type == TestType.PY_UNIT;
643.299 - }
643.300 -
643.301 -// public void customize(Project project, RakeTask task, final PythonExecution taskDescriptor, boolean debug) {
643.302 -// boolean useRunner = TestRunnerUtilities.useTestRunner(project, SharedPythonProjectProperties.TEST_TASKS, task, new DefaultTaskEvaluator() {
643.303 -//
643.304 -// public boolean isDefault(RakeTask task) {
643.305 -// return "test".equals(task.getTask()) || task.getTask().startsWith("test:"); //NOI18N
643.306 -// }
643.307 -// });
643.308 -//
643.309 -// if (!useRunner) {
643.310 -// return;
643.311 -// }
643.312 -//
643.313 -// TestExecutionManager.getInstance().reset();
643.314 -// // this takes care of loading our custom TestTask, which in turn passes
643.315 -// // the custom test runner as an option for the task. This is needed since
643.316 -// // the test run is forked to a different process (by Rake::TestTask) than rake itself
643.317 -// task.addRakeParameters("-r \"" + getScript(RUNNER_SCRIPT_NAME).getAbsolutePath() + "\""); //NOI18N
643.318 -// TestSession session = new TestSession(task.getDisplayName(),
643.319 -// project,
643.320 -// debug ? SessionType.DEBUG : SessionType.TEST,
643.321 -// new PythonTestRunnerNodeFactory());
643.322 -//
643.323 -// Map<String, String> env = new HashMap<String, String>(1);
643.324 -// addPyUnitRunnerToEnv(env);
643.325 -// taskDescriptor.addAdditionalEnv(env);
643.326 -// Manager manager = Manager.getInstance();
643.327 -// final TestRunnerLineConvertor testConvertor = new TestRunnerLineConvertor(manager, session, new PyUnitHandlerFactory());
643.328 -// taskDescriptor.addStandardRecognizers();
643.329 -// taskDescriptor.addOutConvertor(testConvertor);
643.330 -// taskDescriptor.addErrConvertor(testConvertor);
643.331 -// taskDescriptor.lineBased(true);
643.332 -// taskDescriptor.setOutProcessorFactory(new TestRunnerInputProcessorFactory(manager, session, true));
643.333 -// taskDescriptor.setErrProcessorFactory(new TestRunnerInputProcessorFactory(manager, session, false));
643.334 -// taskDescriptor.postBuild(new Runnable() {
643.335 -//
643.336 -// public void run() {
643.337 -// TestExecutionManager.getInstance().finish();
643.338 -// testConvertor.refreshSession();
643.339 -// }
643.340 -// });
643.341 -// TestExecutionManager.getInstance().init(taskDescriptor);
643.342 -// }
643.343 -
643.344 -}
644.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/PythonTestRunnerNodeFactory.java Sun Jan 04 13:11:53 2015 -0600
644.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
644.3 @@ -1,75 +0,0 @@
644.4 -/*
644.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
644.6 - *
644.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
644.8 - *
644.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
644.10 - * Other names may be trademarks of their respective owners.
644.11 - *
644.12 - * The contents of this file are subject to the terms of either the GNU
644.13 - * General Public License Version 2 only ("GPL") or the Common
644.14 - * Development and Distribution License("CDDL") (collectively, the
644.15 - * "License"). You may not use this file except in compliance with the
644.16 - * License. You can obtain a copy of the License at
644.17 - * http://www.netbeans.org/cddl-gplv2.html
644.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
644.19 - * specific language governing permissions and limitations under the
644.20 - * License. When distributing the software, include this License Header
644.21 - * Notice in each file and include the License file at
644.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
644.23 - * particular file as subject to the "Classpath" exception as provided
644.24 - * by Oracle in the GPL Version 2 section of the License file that
644.25 - * accompanied this code. If applicable, add the following below the
644.26 - * License Header, with the fields enclosed by brackets [] replaced by
644.27 - * your own identifying information:
644.28 - * "Portions Copyrighted [year] [name of copyright owner]"
644.29 - *
644.30 - * If you wish your version of this file to be governed by only the CDDL
644.31 - * or only the GPL Version 2, indicate your decision by adding
644.32 - * "[Contributor] elects to include this software in this distribution
644.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
644.34 - * single choice of license, a recipient has the option to distribute
644.35 - * your version of this file under either the CDDL, the GPL Version 2 or
644.36 - * to extend the choice of license to its licensees as provided above.
644.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
644.38 - * Version 2 license, then the option applies only if the new code is
644.39 - * made subject to such option by the copyright holder.
644.40 - *
644.41 - * Contributor(s):
644.42 - *
644.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
644.44 - */
644.45 -
644.46 -package org.netbeans.modules.python.testrunner;
644.47 -
644.48 -import org.netbeans.api.project.Project;
644.49 -import org.netbeans.modules.gsf.testrunner.ui.api.TestRunnerNodeFactory;
644.50 -import org.netbeans.modules.gsf.testrunner.api.Testcase;
644.51 -import org.netbeans.modules.gsf.testrunner.ui.api.TestsuiteNode;
644.52 -import org.netbeans.modules.python.testrunner.ui.PythonCallstackFrameNode;
644.53 -import org.netbeans.modules.python.testrunner.ui.PythonTestMethodNode;
644.54 -import org.netbeans.modules.python.testrunner.ui.PythonTestsuiteNode;
644.55 -import org.openide.nodes.Node;
644.56 -
644.57 -/**
644.58 - *
644.59 - * @author Erno Mononen
644.60 - */
644.61 -public class PythonTestRunnerNodeFactory extends TestRunnerNodeFactory {
644.62 -
644.63 - @Override
644.64 - public Node createTestMethodNode(Testcase testcase, Project project) {
644.65 - return new PythonTestMethodNode(testcase, project);
644.66 - }
644.67 -
644.68 - @Override
644.69 - public Node createCallstackFrameNode(String frameInfo, String dispayName) {
644.70 - return new PythonCallstackFrameNode(frameInfo, dispayName);
644.71 - }
644.72 -
644.73 - @Override
644.74 - public TestsuiteNode createTestSuiteNode(String suiteName, boolean filtered) {
644.75 - return new PythonTestsuiteNode(suiteName, filtered);
644.76 - }
644.77 -
644.78 -}
645.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/TestExecutionManager.java Sun Jan 04 13:11:53 2015 -0600
645.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
645.3 @@ -1,243 +0,0 @@
645.4 -/*
645.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
645.6 - *
645.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
645.8 - *
645.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
645.10 - * Other names may be trademarks of their respective owners.
645.11 - *
645.12 - * The contents of this file are subject to the terms of either the GNU
645.13 - * General Public License Version 2 only ("GPL") or the Common
645.14 - * Development and Distribution License("CDDL") (collectively, the
645.15 - * "License"). You may not use this file except in compliance with the
645.16 - * License. You can obtain a copy of the License at
645.17 - * http://www.netbeans.org/cddl-gplv2.html
645.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
645.19 - * specific language governing permissions and limitations under the
645.20 - * License. When distributing the software, include this License Header
645.21 - * Notice in each file and include the License file at
645.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
645.23 - * particular file as subject to the "Classpath" exception as provided
645.24 - * by Oracle in the GPL Version 2 section of the License file that
645.25 - * accompanied this code. If applicable, add the following below the
645.26 - * License Header, with the fields enclosed by brackets [] replaced by
645.27 - * your own identifying information:
645.28 - * "Portions Copyrighted [year] [name of copyright owner]"
645.29 - *
645.30 - * If you wish your version of this file to be governed by only the CDDL
645.31 - * or only the GPL Version 2, indicate your decision by adding
645.32 - * "[Contributor] elects to include this software in this distribution
645.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
645.34 - * single choice of license, a recipient has the option to distribute
645.35 - * your version of this file under either the CDDL, the GPL Version 2 or
645.36 - * to extend the choice of license to its licensees as provided above.
645.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
645.38 - * Version 2 license, then the option applies only if the new code is
645.39 - * made subject to such option by the copyright holder.
645.40 - *
645.41 - * Contributor(s):
645.42 - *
645.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
645.44 - */
645.45 -
645.46 -package org.netbeans.modules.python.testrunner;
645.47 -
645.48 -import java.io.IOException;
645.49 -import java.util.Set;
645.50 -import java.util.concurrent.Callable;
645.51 -import java.util.concurrent.CancellationException;
645.52 -import java.util.concurrent.ExecutionException;
645.53 -import java.util.concurrent.Future;
645.54 -import java.util.logging.Level;
645.55 -import java.util.logging.Logger;
645.56 -import javax.swing.event.ChangeListener;
645.57 -import org.netbeans.api.extexecution.ExecutionDescriptor;
645.58 -import org.netbeans.api.extexecution.ExecutionService;
645.59 -import org.netbeans.modules.gsf.testrunner.ui.api.Manager;
645.60 -import org.netbeans.modules.gsf.testrunner.api.RerunHandler;
645.61 -import org.netbeans.modules.gsf.testrunner.api.RerunType;
645.62 -import org.netbeans.modules.gsf.testrunner.api.TestSession;
645.63 -//import org.netbeans.modules.python.testrunner.ui.Manager;
645.64 -import org.netbeans.modules.gsf.testrunner.api.Testcase;
645.65 -import org.netbeans.modules.python.api.PythonExecution;
645.66 -import org.netbeans.modules.python.testrunner.ui.TestHandlerFactory;
645.67 -import org.netbeans.modules.python.testrunner.ui.TestRunnerInputProcessorFactory;
645.68 -import org.netbeans.modules.python.testrunner.ui.TestRunnerLineConvertor;
645.69 -//import org.netbeans.modules.python.testrunner.ui.TestSession;
645.70 -import org.openide.LifecycleManager;
645.71 -import org.openide.util.ChangeSupport;
645.72 -import org.openide.util.Exceptions;
645.73 -import org.openide.util.RequestProcessor;
645.74 -
645.75 -/**
645.76 - * Handles running and re-running of test executions.
645.77 - *
645.78 - * <i>This class will probably not be needed after migrating to the new Execution API</i>
645.79 - *
645.80 - * @author Erno Mononen
645.81 - */
645.82 -public final class TestExecutionManager implements RerunHandler {
645.83 -
645.84 - private final static Logger LOGGER = Logger.getLogger(TestExecutionManager.class.getName());
645.85 -
645.86 - /**
645.87 - * The current execution.
645.88 - */
645.89 - private ExecutionService execution;
645.90 - private Future<Integer> result;
645.91 - /**
645.92 - * Indicates whether the current execution has finished.
645.93 - */
645.94 - private boolean finished;
645.95 - private TestRunnerLineConvertor outConvertor;
645.96 - private TestRunnerLineConvertor errConvertor;
645.97 - private final ChangeSupport changeSupport = new ChangeSupport(this);
645.98 - private final RequestProcessor testExecutionProcessor = new RequestProcessor("Python Test Execution Processor"); //NOI18N
645.99 -
645.100 - private static final TestExecutionManager INSTANCE = new TestExecutionManager();
645.101 -
645.102 - private TestExecutionManager() {
645.103 - }
645.104 -
645.105 - public static TestExecutionManager getInstance() {
645.106 - return INSTANCE;
645.107 - }
645.108 -
645.109 - synchronized void finish() {
645.110 - setFinished(true);
645.111 - }
645.112 -
645.113 - synchronized void reset() {
645.114 - this.finished = false;
645.115 - }
645.116 - /**
645.117 - * Inits our TestExecutionManager with the given PythonExecution. Does not
645.118 - * run the execution.
645.119 - *
645.120 - * @param pythonDescriptor
645.121 - */
645.122 - synchronized void init(PythonExecution pythonDescriptor) {
645.123 - try {
645.124 - Callable<Process> rpc = pythonDescriptor.buildProcess();
645.125 -//
645.126 - ExecutionDescriptor descriptor = pythonDescriptor.toExecutionDescriptor();
645.127 - execution = ExecutionService.newService(rpc, descriptor, pythonDescriptor.getDisplayName());
645.128 - } catch (IOException ex) {
645.129 - Exceptions.printStackTrace(ex);
645.130 - }
645.131 - }
645.132 - /**
645.133 - * Starts a PythonExecution with the given executionDescriptor and testRecognizer.
645.134 - *
645.135 - * @param executionDescriptor
645.136 - * @param testRecognizer
645.137 - */
645.138 - synchronized void start(PythonExecution pythonDescriptor,
645.139 - TestHandlerFactory handlerFactory, TestSession session) {
645.140 -
645.141 - setFinished(false);
645.142 - session.setRerunHandler(this);
645.143 - final Manager manager = Manager.getInstance();
645.144 - outConvertor = new TestRunnerLineConvertor(manager, session, handlerFactory);
645.145 - errConvertor = new TestRunnerLineConvertor(manager, session, handlerFactory);
645.146 - pythonDescriptor.addOutConvertor(outConvertor);
645.147 - pythonDescriptor.addErrConvertor(errConvertor);
645.148 - pythonDescriptor.setOutProcessorFactory(new TestRunnerInputProcessorFactory(manager, session, handlerFactory.printSummary()));
645.149 - pythonDescriptor.setErrProcessorFactory(new TestRunnerInputProcessorFactory(manager, session, false));
645.150 - pythonDescriptor.lineBased(true);
645.151 -
645.152 -
645.153 - try {
645.154 - Callable<Process> rpc = pythonDescriptor.buildProcess();
645.155 -
645.156 - final Runnable oldPostExecutionHook = pythonDescriptor.getPostExecutionHook();
645.157 - ExecutionDescriptor descriptor = pythonDescriptor.toExecutionDescriptor()
645.158 - .postExecution(new Runnable() {
645.159 -
645.160 - public void run() {
645.161 - refresh();
645.162 - if (oldPostExecutionHook != null) {
645.163 - oldPostExecutionHook.run();
645.164 - }
645.165 - }
645.166 - });
645.167 - execution = ExecutionService.newService(rpc, descriptor, pythonDescriptor.getDisplayName());
645.168 - runExecution();
645.169 - } catch (IOException ex) {
645.170 - Exceptions.printStackTrace(ex);
645.171 - }
645.172 - }
645.173 -
645.174 - private void runExecution() {
645.175 - result = execution.run();
645.176 - testExecutionProcessor.post(new Runnable() {
645.177 - public void run() {
645.178 - try {
645.179 - result.get();
645.180 - } catch (InterruptedException ex) {
645.181 - Exceptions.printStackTrace(ex);
645.182 - } catch (ExecutionException ex) {
645.183 - Exceptions.printStackTrace(ex);
645.184 - } catch (CancellationException ex) {
645.185 - // ignore
645.186 - }
645.187 - setFinished(result.isDone());
645.188 - }
645.189 - });
645.190 - }
645.191 -
645.192 - /**
645.193 - * Checks whether the current execution is finished.
645.194 - *
645.195 - * @return true if the current execution has finished,
645.196 - * false otherwise.
645.197 - */
645.198 - @Override
645.199 - public boolean enabled(RerunType type) {
645.200 - return RerunType.ALL.equals(type) && (finished || (result != null && result.isDone()));
645.201 - }
645.202 -
645.203 - private void setFinished(boolean finished) {
645.204 - this.finished = finished;
645.205 - changeSupport.fireChange();
645.206 - }
645.207 - /**
645.208 - * Re-runs the last run test execution.
645.209 - */
645.210 - public synchronized void rerun() {
645.211 - assert enabled(RerunType.ALL);
645.212 - if (LOGGER.isLoggable(Level.FINE)) {
645.213 - LOGGER.log(Level.FINE, "Re-running: " + execution);
645.214 - }
645.215 - refresh();
645.216 - setFinished(false);
645.217 - LifecycleManager.getDefault().saveAll();
645.218 - runExecution();
645.219 - }
645.220 -
645.221 - @Override
645.222 - public void rerun(Set<Testcase> tests) {
645.223 - //not implemented yet
645.224 - }
645.225 -
645.226 - public void addChangeListener(ChangeListener listener) {
645.227 - changeSupport.addChangeListener(listener);
645.228 - }
645.229 -
645.230 - public void removeChangeListener(ChangeListener listener) {
645.231 - changeSupport.removeChangeListener(listener);
645.232 - }
645.233 -
645.234 - /**
645.235 - * Refreshes the current session, i.e. clears all currently
645.236 - * computed test statuses.
645.237 - */
645.238 - public synchronized void refresh() {
645.239 - if (outConvertor != null) {
645.240 - outConvertor.refreshSession();
645.241 - }
645.242 - if (errConvertor != null) {
645.243 - errConvertor.refreshSession();
645.244 - }
645.245 - }
645.246 -}
646.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/TestRunnerUtilities.java Sun Jan 04 13:11:53 2015 -0600
646.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
646.3 @@ -1,93 +0,0 @@
646.4 -/*
646.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
646.6 - *
646.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
646.8 - *
646.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
646.10 - * Other names may be trademarks of their respective owners.
646.11 - *
646.12 - * The contents of this file are subject to the terms of either the GNU
646.13 - * General Public License Version 2 only ("GPL") or the Common
646.14 - * Development and Distribution License("CDDL") (collectively, the
646.15 - * "License"). You may not use this file except in compliance with the
646.16 - * License. You can obtain a copy of the License at
646.17 - * http://www.netbeans.org/cddl-gplv2.html
646.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
646.19 - * specific language governing permissions and limitations under the
646.20 - * License. When distributing the software, include this License Header
646.21 - * Notice in each file and include the License file at
646.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
646.23 - * particular file as subject to the "Classpath" exception as provided
646.24 - * by Oracle in the GPL Version 2 section of the License file that
646.25 - * accompanied this code. If applicable, add the following below the
646.26 - * License Header, with the fields enclosed by brackets [] replaced by
646.27 - * your own identifying information:
646.28 - * "Portions Copyrighted [year] [name of copyright owner]"
646.29 - *
646.30 - * If you wish your version of this file to be governed by only the CDDL
646.31 - * or only the GPL Version 2, indicate your decision by adding
646.32 - * "[Contributor] elects to include this software in this distribution
646.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
646.34 - * single choice of license, a recipient has the option to distribute
646.35 - * your version of this file under either the CDDL, the GPL Version 2 or
646.36 - * to extend the choice of license to its licensees as provided above.
646.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
646.38 - * Version 2 license, then the option applies only if the new code is
646.39 - * made subject to such option by the copyright holder.
646.40 - *
646.41 - * Contributor(s):
646.42 - *
646.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
646.44 - */
646.45 -
646.46 -package org.netbeans.modules.python.testrunner;
646.47 -
646.48 -import org.netbeans.api.project.Project;
646.49 -import org.netbeans.spi.project.support.ant.PropertyEvaluator;
646.50 -
646.51 -/**
646.52 - * Utility methods for <code>TestRunner</code> implementations.
646.53 - *
646.54 - * @author Erno Mononen
646.55 - */
646.56 -final class TestRunnerUtilities {
646.57 -
646.58 - private TestRunnerUtilities() {
646.59 - }
646.60 -
646.61 - /**
646.62 - * Checks whether the given task should be run using the UI test runner.
646.63 - *
646.64 - * @param project
646.65 - * @param property
646.66 - * @param task
646.67 - * @param taskEvaluator
646.68 - * @return true if the given task should be run using the UI test runner;
646.69 - * false otherwise.
646.70 - */
646.71 - static boolean useTestRunner(Project project, String property, /*RakeTask task,*/ DefaultTaskEvaluator taskEvaluator) {
646.72 -throw new RuntimeException("useTestRunner -- not sure what to do here");
646.73 -// PropertyEvaluator evaluator = project.getLookup().lookup(PropertyEvaluator.class);
646.74 -// if (evaluator == null || evaluator.getProperty(property) == null) {
646.75 -// return taskEvaluator.isDefault(task);
646.76 -// }
646.77 -// String definedTasks = evaluator.getProperty(property);
646.78 -// if ("".equals(definedTasks.trim())) {
646.79 -// return false;
646.80 -// }
646.81 -// for (String each : definedTasks.split(",")) { //NOI18N
646.82 -// if (task.getTask().equals(each.trim())) {
646.83 -// return true;
646.84 -// }
646.85 -// }
646.86 -// return false;
646.87 -// return true;
646.88 - }
646.89 -
646.90 -
646.91 - interface DefaultTaskEvaluator {
646.92 -
646.93 - boolean isDefault(Object task/*RakeTask task*/);
646.94 - }
646.95 -
646.96 -}
647.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/BaseTestMethodNodeAction.java Sun Jan 04 13:11:53 2015 -0600
647.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
647.3 @@ -1,103 +0,0 @@
647.4 -/*
647.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
647.6 - *
647.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
647.8 - *
647.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
647.10 - * Other names may be trademarks of their respective owners.
647.11 - *
647.12 - * The contents of this file are subject to the terms of either the GNU
647.13 - * General Public License Version 2 only ("GPL") or the Common
647.14 - * Development and Distribution License("CDDL") (collectively, the
647.15 - * "License"). You may not use this file except in compliance with the
647.16 - * License. You can obtain a copy of the License at
647.17 - * http://www.netbeans.org/cddl-gplv2.html
647.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
647.19 - * specific language governing permissions and limitations under the
647.20 - * License. When distributing the software, include this License Header
647.21 - * Notice in each file and include the License file at
647.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
647.23 - * particular file as subject to the "Classpath" exception as provided
647.24 - * by Oracle in the GPL Version 2 section of the License file that
647.25 - * accompanied this code. If applicable, add the following below the
647.26 - * License Header, with the fields enclosed by brackets [] replaced by
647.27 - * your own identifying information:
647.28 - * "Portions Copyrighted [year] [name of copyright owner]"
647.29 - *
647.30 - * If you wish your version of this file to be governed by only the CDDL
647.31 - * or only the GPL Version 2, indicate your decision by adding
647.32 - * "[Contributor] elects to include this software in this distribution
647.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
647.34 - * single choice of license, a recipient has the option to distribute
647.35 - * your version of this file under either the CDDL, the GPL Version 2 or
647.36 - * to extend the choice of license to its licensees as provided above.
647.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
647.38 - * Version 2 license, then the option applies only if the new code is
647.39 - * made subject to such option by the copyright holder.
647.40 - *
647.41 - * Contributor(s):
647.42 - *
647.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
647.44 - */
647.45 -
647.46 -package org.netbeans.modules.python.testrunner.ui;
647.47 -
647.48 -import java.util.Collection;
647.49 -import java.util.logging.Logger;
647.50 -import org.netbeans.api.project.Project;
647.51 -import org.netbeans.modules.gsf.testrunner.ui.api.TestNodeAction;
647.52 -import org.netbeans.modules.gsf.testrunner.api.Testcase;
647.53 -import org.netbeans.modules.python.project.PythonProject;
647.54 -import org.netbeans.modules.python.project.spi.TestRunner;
647.55 -import org.openide.filesystems.FileObject;
647.56 -import org.openide.util.Lookup;
647.57 -
647.58 -/**
647.59 - * Base class for actions associated with a test method node.
647.60 - *
647.61 - * @author Erno Mononen
647.62 - */
647.63 -abstract class BaseTestMethodNodeAction extends TestNodeAction {
647.64 -
647.65 - private static final Logger LOGGER = Logger.getLogger(BaseTestMethodNodeAction.class.getName());
647.66 -
647.67 - protected final Testcase testcase;
647.68 - protected final Project project;
647.69 - protected final String name;
647.70 -
647.71 - public BaseTestMethodNodeAction(Testcase testcase, Project project, String name) {
647.72 - this.testcase = testcase;
647.73 - this.project = project;
647.74 - this.name = name;
647.75 - }
647.76 -
647.77 - @Override
647.78 - public Object getValue(String key) {
647.79 - if (NAME.equals(key)) {
647.80 - return name;
647.81 - }
647.82 - return super.getValue(key);
647.83 - }
647.84 -
647.85 - protected String getTestMethod() {
647.86 - return testcase.getClassName() + "/" + testcase.getName(); //NOI18N
647.87 - }
647.88 -
647.89 - protected FileObject getTestSourceRoot() {
647.90 - PythonProject baseProject = project.getLookup().lookup(PythonProject.class);
647.91 - // need to use test source roots, not source roots -- see the comments in #135680
647.92 - FileObject[] testRoots = baseProject.getTestSourceRootFiles();
647.93 - // if there are not test roots, return the project root -- works in rails projects
647.94 - return 0 == testRoots.length ? project.getProjectDirectory() : testRoots[0];
647.95 - }
647.96 -
647.97 - protected TestRunner getTestRunner(TestRunner.TestType testType) {
647.98 - Collection<? extends TestRunner> testRunners = Lookup.getDefault().lookupAll(TestRunner.class);
647.99 - for (TestRunner each : testRunners) {
647.100 - if (each.supports(testType)) {
647.101 - return each;
647.102 - }
647.103 - }
647.104 - return null;
647.105 - }
647.106 -}
648.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/Bundle.properties Sun Jan 04 13:11:53 2015 -0600
648.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
648.3 @@ -1,141 +0,0 @@
648.4 -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
648.5 -#
648.6 -# Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
648.7 -#
648.8 -# Oracle and Java are registered trademarks of Oracle and/or its affiliates.
648.9 -# Other names may be trademarks of their respective owners.
648.10 -#
648.11 -# The contents of this file are subject to the terms of either the GNU
648.12 -# General Public License Version 2 only ("GPL") or the Common
648.13 -# Development and Distribution License("CDDL") (collectively, the
648.14 -# "License"). You may not use this file except in compliance with the
648.15 -# License. You can obtain a copy of the License at
648.16 -# http://www.netbeans.org/cddl-gplv2.html
648.17 -# or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
648.18 -# specific language governing permissions and limitations under the
648.19 -# License. When distributing the software, include this License Header
648.20 -# Notice in each file and include the License file at
648.21 -# nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
648.22 -# particular file as subject to the "Classpath" exception as provided
648.23 -# by Oracle in the GPL Version 2 section of the License file that
648.24 -# accompanied this code. If applicable, add the following below the
648.25 -# License Header, with the fields enclosed by brackets [] replaced by
648.26 -# your own identifying information:
648.27 -# "Portions Copyrighted [year] [name of copyright owner]"
648.28 -#
648.29 -# Contributor(s):
648.30 -#
648.31 -# The Original Software is NetBeans. The Initial Developer of the Original
648.32 -# Software is Sun Microsystems, Inc. Portions Copyright 2006-2008 Sun
648.33 -# Microsystems, Inc. All Rights Reserved.
648.34 -#
648.35 -# If you wish your version of this file to be governed by only the CDDL
648.36 -# or only the GPL Version 2, indicate your decision by adding
648.37 -# "[Contributor] elects to include this software in this distribution
648.38 -# under the [CDDL or GPL Version 2] license." If you do not indicate a
648.39 -# single choice of license, a recipient has the option to distribute
648.40 -# your version of this file under either the CDDL, the GPL Version 2 or
648.41 -# to extend the choice of license to its licensees as provided above.
648.42 -# However, if you add GPL Version 2 code and therefore, elected the GPL
648.43 -# Version 2 license, then the option applies only if the new code is
648.44 -# made subject to such option by the copyright holder.
648.45 -
648.46 -TITLE_TEST_RESULTS=Python Test Results
648.47 -ResultWindowOpenAction.MenuName=Python &Test Results
648.48 -ACSN_TestResults=Python Test Results
648.49 -ACSD_TestResults=Displays information about passed and failed tests and output generated by them
648.50 -ACSN_FilterButton=Filter On/Off
648.51 -ACSN_RerunButton = Rerun
648.52 -ACSN_ResultPanelTree=Information about passed and failed tests
648.53 -ACSD_ResultPanelTree=Displays in a tree structure information about passed, failed and erroneous tests
648.54 -ACSN_HorizontalScrollbar=Horizontal scrollbar of the results panel
648.55 -ACSN_OutputTextPane=Test Output
648.56 -ACSD_OutputTextPane=Displays output and error output generated by executed test methods
648.57 -
648.58 -MSG_PassedTestsInfo={0,choice,0#No test|1#1 test|1<{0,number,integer} tests} passed
648.59 -MSG_FailedTestsInfo={0,choice,1#1 test|1<{0,number,integer} tests} failed
648.60 -MSG_PendingTestsInfo={0,choice,1#1 test|1<{0,number,integer} tests} pending
648.61 -MSG_ErrorTestsInfo={0,choice,1#1 test|1<{0,number,integer} tests} caused an error
648.62 -
648.63 -MSG_TestsInfoNoTests=No tests executed.
648.64 -
648.65 -# "All 58 tests passed."
648.66 -MSG_TestsInfoAllOK={0,choice,1#The test|2#Both tests|2<All {0,number,integer} tests} passed.
648.67 -
648.68 -# The result summary can be a combination of passed, pending, failed and error
648.69 -# causing tests. The keys below are for all combinations of these, the preferred
648.70 -# order is passed, pending, failed, error.
648.71 -MSG_TestResultSummary1 = {0}, {1}.
648.72 -MSG_TestResultSummary2 = {0}, {1}, {2}.
648.73 -MSG_TestResultSummary3 = {0}, {1}, {2}, {3}.
648.74 -
648.75 -# {0} .. name of the test class
648.76 -MSG_TestsuiteNoname=Test suite
648.77 -MSG_TestsuiteRunning={0} - running...
648.78 -MSG_TestsuiteRunningNoname=Test suite running...
648.79 -MSG_TestsuiteFailed={0} - FAILED
648.80 -MSG_TestsuitePending={0} - PENDING
648.81 -MSG_TestsuiteRunning_HTML=running...
648.82 -MSG_TestsuitePassed_HTML=passed
648.83 -MSG_TestsuiteFailed_HTML=FAILED
648.84 -MSG_TestsuitePending_HTML=PENDING
648.85 -
648.86 -# {0} .. name of the test method
648.87 -MSG_TestMethodFailed={0} - FAILED
648.88 -MSG_TestMethodPending={0} - PENDING
648.89 -MSG_TestMethodError={0} - caused an ERROR
648.90 -MSG_TestMethodPassed_HTML=passed
648.91 -MSG_TestMethodFailed_HTML=FAILED
648.92 -MSG_TestMethodPending_HTML=PENDING
648.93 -MSG_TestMethodError_HTML=caused an ERROR
648.94 -
648.95 -# {0} .. name of the test method, {1} .. elapsed time in seconds
648.96 -MSG_TestMethodPassed_time={0} ({1,number,0.0##} s)
648.97 -MSG_TestMethodFailed_time={0} - FAILED ({1,number,0.0##} s)
648.98 -MSG_TestMethodPending_time={0} - PENDING ({1,number,0.0##} s)
648.99 -MSG_TestMethodError_time={0} - caused an ERROR ({1,number,0.0##} s)
648.100 -MSG_TestMethodPassed_HTML_time=passed ({0,number,0.0##} s)
648.101 -MSG_TestMethodFailed_HTML_time=FAILED ({0,number,0.0##} s)
648.102 -MSG_TestMethodPending_HTML_time=PENDING ({0,number,0.0##} s)
648.103 -MSG_TestMethodError_HTML_time=caused an ERROR ({0,number,0.0##} s)
648.104 -
648.105 -MSG_TestMethodPassed_HTML_cause=passed
648.106 -MSG_TestMethodFailed_HTML_cause=FAILED ({0})
648.107 -MSG_TestMethodPending_HTML_cause=PENDING ({0})
648.108 -MSG_TestMethodError_HTML_cause=caused an ERROR ({0})
648.109 -
648.110 -# Elapsed time for a test suite
648.111 -MSG_TestSuiteElapsedTime= ({0,number,0.0##} s)
648.112 -
648.113 -#
648.114 -MSG_PassedNotDisplayed=Information about passed tests is not displayed.
648.115 -MSG_SomePassedNotDisplayed=Information about some passed tests is not displayed.
648.116 -
648.117 -MSG_StdOutput=Standard Output:
648.118 -MSG_ErrOutput=Error Output:
648.119 -
648.120 -#
648.121 -MultiviewPanel.btnFilter.showAll.tooltip=Show All Results
648.122 -MultiviewPanel.btnFilter.showFailures.tooltip=Show Failures Only
648.123 -
648.124 -MultiviewPanel.rerunButton.tooltip=Rerun
648.125 -
648.126 -LBL_RunningTests=Running...
648.127 -
648.128 -MSG_Error = {0}) Error:
648.129 -MSG_Failure = {0}) Failure:
648.130 -
648.131 -MSG_NextFailure = Next Failure - Ctrl+Period
648.132 -MSG_PreviousFailure = Previous Failure - Ctrl+Comma
648.133 -# test results summary
648.134 -MSG_TestSessionStarting = Running {0}...
648.135 -MSG_TestSessionFinished = Finished in {0,number,0.0##} seconds.
648.136 -MSG_TestSessionFinishedSummary = {0} tests, {1} failures, {2} errors
648.137 -
648.138 -# actions for a test method node
648.139 -LBL_RerunTest= &Run Again
648.140 -LBL_DebugTest= &Debug
648.141 -LBL_GoToSource = &Go to Source
648.142 -
648.143 -# displayed in tooltip of a test case / suite when there is no output for it
648.144 -MSG_NoOutput = No output.
649.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/DisplayOutputForNodeAction.java Sun Jan 04 13:11:53 2015 -0600
649.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
649.3 @@ -1,79 +0,0 @@
649.4 -/*
649.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
649.6 - *
649.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
649.8 - *
649.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
649.10 - * Other names may be trademarks of their respective owners.
649.11 - *
649.12 - * The contents of this file are subject to the terms of either the GNU
649.13 - * General Public License Version 2 only ("GPL") or the Common
649.14 - * Development and Distribution License("CDDL") (collectively, the
649.15 - * "License"). You may not use this file except in compliance with the
649.16 - * License. You can obtain a copy of the License at
649.17 - * http://www.netbeans.org/cddl-gplv2.html
649.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
649.19 - * specific language governing permissions and limitations under the
649.20 - * License. When distributing the software, include this License Header
649.21 - * Notice in each file and include the License file at
649.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
649.23 - * particular file as subject to the "Classpath" exception as provided
649.24 - * by Oracle in the GPL Version 2 section of the License file that
649.25 - * accompanied this code. If applicable, add the following below the
649.26 - * License Header, with the fields enclosed by brackets [] replaced by
649.27 - * your own identifying information:
649.28 - * "Portions Copyrighted [year] [name of copyright owner]"
649.29 - *
649.30 - * If you wish your version of this file to be governed by only the CDDL
649.31 - * or only the GPL Version 2, indicate your decision by adding
649.32 - * "[Contributor] elects to include this software in this distribution
649.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
649.34 - * single choice of license, a recipient has the option to distribute
649.35 - * your version of this file under either the CDDL, the GPL Version 2 or
649.36 - * to extend the choice of license to its licensees as provided above.
649.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
649.38 - * Version 2 license, then the option applies only if the new code is
649.39 - * made subject to such option by the copyright holder.
649.40 - *
649.41 - * Contributor(s):
649.42 - *
649.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
649.44 - */
649.45 -package org.netbeans.modules.python.testrunner.ui;
649.46 -
649.47 -//import java.awt.event.ActionEvent;
649.48 -//import java.util.List;
649.49 -//import javax.swing.AbstractAction;
649.50 -//import org.netbeans.modules.gsf.testrunner.Manager;
649.51 -//import org.netbeans.modules.gsf.testrunner.TestSession;
649.52 -////import org.netbeans.modules.gsf.testrunner.output.OutputLine;
649.53 -//
649.54 -///**
649.55 -// *
649.56 -// * @author Erno Mononen
649.57 -// */
649.58 -//final class DisplayOutputForNodeAction extends AbstractAction {
649.59 -//
649.60 -// private final List<OutputLine> output;
649.61 -// private final TestSession session;
649.62 -//
649.63 -// public DisplayOutputForNodeAction(List<OutputLine> output, TestSession session) {
649.64 -// this.output = output;
649.65 -// this.session = session;
649.66 -// }
649.67 -//
649.68 -//
649.69 -// public Object getValue(String key) {
649.70 -// if (NAME.equals(key)) {
649.71 -// return "display";
649.72 -// }
649.73 -// return super.getValue(key);
649.74 -// }
649.75 -//
649.76 -// public void actionPerformed(ActionEvent e) {
649.77 -// Manager manager = Manager.getInstance();
649.78 -// for (OutputLine ol : output) {
649.79 -// manager.displayOutput(session, ol.getLine(), ol.isError());
649.80 -// }
649.81 -// }
649.82 -//}
650.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/JumpToCallStackAction.java Sun Jan 04 13:11:53 2015 -0600
650.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
650.3 @@ -1,105 +0,0 @@
650.4 -/*
650.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
650.6 - *
650.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
650.8 - *
650.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
650.10 - * Other names may be trademarks of their respective owners.
650.11 - *
650.12 - * The contents of this file are subject to the terms of either the GNU
650.13 - * General Public License Version 2 only ("GPL") or the Common
650.14 - * Development and Distribution License("CDDL") (collectively, the
650.15 - * "License"). You may not use this file except in compliance with the
650.16 - * License. You can obtain a copy of the License at
650.17 - * http://www.netbeans.org/cddl-gplv2.html
650.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
650.19 - * specific language governing permissions and limitations under the
650.20 - * License. When distributing the software, include this License Header
650.21 - * Notice in each file and include the License file at
650.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
650.23 - * particular file as subject to the "Classpath" exception as provided
650.24 - * by Oracle in the GPL Version 2 section of the License file that
650.25 - * accompanied this code. If applicable, add the following below the
650.26 - * License Header, with the fields enclosed by brackets [] replaced by
650.27 - * your own identifying information:
650.28 - * "Portions Copyrighted [year] [name of copyright owner]"
650.29 - *
650.30 - * Contributor(s):
650.31 - *
650.32 - * The Original Software is NetBeans. The Initial Developer of the Original
650.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
650.34 - * Microsystems, Inc. All Rights Reserved.
650.35 - *
650.36 - * If you wish your version of this file to be governed by only the CDDL
650.37 - * or only the GPL Version 2, indicate your decision by adding
650.38 - * "[Contributor] elects to include this software in this distribution
650.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
650.40 - * single choice of license, a recipient has the option to distribute
650.41 - * your version of this file under either the CDDL, the GPL Version 2 or
650.42 - * to extend the choice of license to its licensees as provided above.
650.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
650.44 - * Version 2 license, then the option applies only if the new code is
650.45 - * made subject to such option by the copyright holder.
650.46 - */
650.47 -
650.48 -package org.netbeans.modules.python.testrunner.ui;
650.49 -
650.50 -import java.awt.event.ActionEvent;
650.51 -import javax.swing.AbstractAction;
650.52 -import org.openide.nodes.Node;
650.53 -import org.openide.util.NbBundle;
650.54 -
650.55 -/**
650.56 - * Jump to action for call stack lines.
650.57 - *
650.58 - * @author Marian Petras, Erno Mononen
650.59 - */
650.60 -final class JumpToCallStackAction extends AbstractAction {
650.61 -
650.62 - /** */
650.63 - private final Node node;
650.64 - /** */
650.65 - private final String callstackFrameInfo;
650.66 -
650.67 - private int line;
650.68 -
650.69 - /** Creates a new instance of JumpAction */
650.70 - JumpToCallStackAction(Node node, String callstackFrameInfo) {
650.71 - this(node, callstackFrameInfo, -1);
650.72 - }
650.73 -
650.74 - /**
650.75 - * @param node
650.76 - * @param callstackFrameInfo a line in call stack representing the location
650.77 - * to jump
650.78 - * @param line the line where to jump, if <code>line == -1</code>, then
650.79 - * the line will be computed from the given <code>callstackFrameInfo</code>.
650.80 - */
650.81 - JumpToCallStackAction(Node node, String callstackFrameInfo, int line) {
650.82 - this.node = node;
650.83 - this.callstackFrameInfo = callstackFrameInfo;
650.84 - this.line = line;
650.85 - }
650.86 -
650.87 -
650.88 - @Override
650.89 - public Object getValue(String key) {
650.90 - if (NAME.equals(key)) {
650.91 - return NbBundle.getMessage(JumpToCallStackAction.class, "LBL_GoToSource");
650.92 - }
650.93 - return super.getValue(key);
650.94 - }
650.95 -
650.96 - /**
650.97 - * If the <code>callstackFrameInfo</code> is not <code>null</code>,
650.98 - * tries to jump to the callstack frame source code. Otherwise does nothing.
650.99 - */
650.100 - public void actionPerformed(ActionEvent e) {
650.101 - if (callstackFrameInfo == null) {
650.102 - return;
650.103 - }
650.104 -
650.105 - OutputUtils.openCallstackFrame(node, callstackFrameInfo, line);
650.106 - }
650.107 -
650.108 -}
651.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/JumpToTestAction.java Sun Jan 04 13:11:53 2015 -0600
651.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
651.3 @@ -1,73 +0,0 @@
651.4 -/*
651.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
651.6 - *
651.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
651.8 - *
651.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
651.10 - * Other names may be trademarks of their respective owners.
651.11 - *
651.12 - * The contents of this file are subject to the terms of either the GNU
651.13 - * General Public License Version 2 only ("GPL") or the Common
651.14 - * Development and Distribution License("CDDL") (collectively, the
651.15 - * "License"). You may not use this file except in compliance with the
651.16 - * License. You can obtain a copy of the License at
651.17 - * http://www.netbeans.org/cddl-gplv2.html
651.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
651.19 - * specific language governing permissions and limitations under the
651.20 - * License. When distributing the software, include this License Header
651.21 - * Notice in each file and include the License file at
651.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
651.23 - * particular file as subject to the "Classpath" exception as provided
651.24 - * by Oracle in the GPL Version 2 section of the License file that
651.25 - * accompanied this code. If applicable, add the following below the
651.26 - * License Header, with the fields enclosed by brackets [] replaced by
651.27 - * your own identifying information:
651.28 - * "Portions Copyrighted [year] [name of copyright owner]"
651.29 - *
651.30 - * If you wish your version of this file to be governed by only the CDDL
651.31 - * or only the GPL Version 2, indicate your decision by adding
651.32 - * "[Contributor] elects to include this software in this distribution
651.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
651.34 - * single choice of license, a recipient has the option to distribute
651.35 - * your version of this file under either the CDDL, the GPL Version 2 or
651.36 - * to extend the choice of license to its licensees as provided above.
651.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
651.38 - * Version 2 license, then the option applies only if the new code is
651.39 - * made subject to such option by the copyright holder.
651.40 - *
651.41 - * Contributor(s):
651.42 - *
651.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
651.44 - */
651.45 -
651.46 -package org.netbeans.modules.python.testrunner.ui;
651.47 -
651.48 -import java.awt.event.ActionEvent;
651.49 -import org.netbeans.api.project.Project;
651.50 -import org.netbeans.modules.gsf.api.DeclarationFinder.DeclarationLocation;
651.51 -import org.netbeans.modules.gsf.spi.GsfUtilities;
651.52 -import org.netbeans.modules.gsf.testrunner.api.Testcase;
651.53 -import org.netbeans.modules.python.editor.PythonDeclarationFinder;
651.54 -
651.55 -/**
651.56 - * Jump to action for test methods.
651.57 - *
651.58 - * @author Erno Mononen
651.59 - */
651.60 -final class JumpToTestAction extends BaseTestMethodNodeAction {
651.61 -
651.62 - private final boolean jumpToClass;
651.63 -
651.64 - JumpToTestAction(Testcase testcase, Project project, String name, boolean clazz) {
651.65 - super(testcase, project, name);
651.66 - this.jumpToClass = clazz;
651.67 - }
651.68 -
651.69 - protected void doActionPerformed(ActionEvent e) {
651.70 - DeclarationLocation location = PythonDeclarationFinder.getTestDeclaration(getTestSourceRoot(), getTestMethod(), jumpToClass);
651.71 - if (!(DeclarationLocation.NONE == location)) {
651.72 - GsfUtilities.open(location.getFileObject(), location.getOffset(), null);
651.73 - }
651.74 - }
651.75 -
651.76 -}
652.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/OutputUtils.java Sun Jan 04 13:11:53 2015 -0600
652.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
652.3 @@ -1,145 +0,0 @@
652.4 -/*
652.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
652.6 - *
652.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
652.8 - *
652.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
652.10 - * Other names may be trademarks of their respective owners.
652.11 - *
652.12 - * The contents of this file are subject to the terms of either the GNU
652.13 - * General Public License Version 2 only ("GPL") or the Common
652.14 - * Development and Distribution License("CDDL") (collectively, the
652.15 - * "License"). You may not use this file except in compliance with the
652.16 - * License. You can obtain a copy of the License at
652.17 - * http://www.netbeans.org/cddl-gplv2.html
652.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
652.19 - * specific language governing permissions and limitations under the
652.20 - * License. When distributing the software, include this License Header
652.21 - * Notice in each file and include the License file at
652.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
652.23 - * particular file as subject to the "Classpath" exception as provided
652.24 - * by Oracle in the GPL Version 2 section of the License file that
652.25 - * accompanied this code. If applicable, add the following below the
652.26 - * License Header, with the fields enclosed by brackets [] replaced by
652.27 - * your own identifying information:
652.28 - * "Portions Copyrighted [year] [name of copyright owner]"
652.29 - *
652.30 - * Contributor(s):
652.31 - *
652.32 - * The Original Software is NetBeans. The Initial Developer of the Original
652.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
652.34 - * Microsystems, Inc. All Rights Reserved.
652.35 - *
652.36 - * If you wish your version of this file to be governed by only the CDDL
652.37 - * or only the GPL Version 2, indicate your decision by adding
652.38 - * "[Contributor] elects to include this software in this distribution
652.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
652.40 - * single choice of license, a recipient has the option to distribute
652.41 - * your version of this file under either the CDDL, the GPL Version 2 or
652.42 - * to extend the choice of license to its licensees as provided above.
652.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
652.44 - * Version 2 license, then the option applies only if the new code is
652.45 - * made subject to such option by the copyright holder.
652.46 - */
652.47 -package org.netbeans.modules.python.testrunner.ui;
652.48 -
652.49 -import java.io.File;
652.50 -import java.util.logging.Logger;
652.51 -import java.util.regex.Matcher;
652.52 -import java.util.regex.Pattern;
652.53 -import javax.swing.text.BadLocationException;
652.54 -import org.netbeans.api.extexecution.print.LineConvertors.FileLocator;
652.55 -import org.netbeans.editor.BaseDocument;
652.56 -import org.netbeans.modules.gsf.spi.GsfUtilities;
652.57 -import org.netbeans.modules.gsf.testrunner.api.Report;
652.58 -import org.netbeans.modules.gsf.testrunner.ui.api.TestsuiteNode;
652.59 -import org.netbeans.modules.python.api.FileLocation;
652.60 -import org.openide.filesystems.FileObject;
652.61 -import org.openide.filesystems.FileUtil;
652.62 -import org.openide.nodes.Node;
652.63 -import org.openide.util.Exceptions;
652.64 -
652.65 -/**
652.66 - *
652.67 - * @author Marian Petras, Erno Mononen
652.68 - */
652.69 -final class OutputUtils {
652.70 -
652.71 - private static final Logger LOGGER = Logger.getLogger(OutputUtils.class.getName());
652.72 -
652.73 - private OutputUtils() {
652.74 - }
652.75 -
652.76 - /**
652.77 - */
652.78 - static void openCallstackFrame(Node node, String frameInfo, int line) {
652.79 - Report report = getTestsuiteNode(node).getReport();
652.80 -
652.81 - FileLocation location = null;
652.82 - // The stacktrace format is defined in nb_test_runner.py
652.83 - Pattern STACK_FRAME = Pattern.compile("\\S+ in (\\S+):(\\d+)"); // NOI18N
652.84 - Matcher matcher = STACK_FRAME.matcher(frameInfo);
652.85 - if (matcher.matches()) {
652.86 - String file = matcher.group(1);
652.87 - String lineStr = matcher.group(2);
652.88 - int lineNo = Integer.parseInt(lineStr);
652.89 - location = new FileLocation(file, lineNo);
652.90 - }
652.91 -
652.92 - if (location == null) {
652.93 - location = FileLocation.getLocation(frameInfo);
652.94 - }
652.95 -
652.96 - if (location != null) {
652.97 - FileObject fo = findFile(location.file, report.getFileLocator());
652.98 - if (fo != null) {
652.99 - if (line == -1) {
652.100 - line = location.line;
652.101 - }
652.102 -
652.103 - BaseDocument doc = GsfUtilities.getDocument(fo, true);
652.104 - if (doc != null) {
652.105 - int offset = org.netbeans.editor.Utilities.getRowStartFromLineOffset(doc, line-1);
652.106 - if (offset == -1) {
652.107 - // Invalid line number - just go to the end of the file
652.108 - offset = doc.getLength();
652.109 - }
652.110 - GsfUtilities.open(fo, offset, null);
652.111 - }
652.112 -
652.113 - return;
652.114 - }
652.115 - }
652.116 -
652.117 - LOGGER.info("Could not open a file for " + frameInfo) ;
652.118 - }
652.119 -
652.120 - static TestsuiteNode getTestsuiteNode(Node node) {
652.121 - while (!(node instanceof TestsuiteNode)) {
652.122 - node = node.getParentNode();
652.123 - }
652.124 - return (TestsuiteNode) node;
652.125 - }
652.126 -
652.127 - // TODO: copied from OutputUtils, should introduce this as a utility method
652.128 - // in python.platform
652.129 - static FileObject findFile(final String path, FileLocator fileLocator) {
652.130 - if (fileLocator != null) {
652.131 - FileObject fo = fileLocator.find(path);
652.132 - if (fo != null) {
652.133 - return fo;
652.134 - }
652.135 - }
652.136 -
652.137 - // Perhaps it's an absolute path of some sort... try to resolve those
652.138 - // Absolute path? Happens for stack traces in Jython libraries and such
652.139 - File file = new File(path);
652.140 - if (file.isFile()) {
652.141 - return FileUtil.toFileObject(FileUtil.normalizeFile(file));
652.142 - } else {
652.143 - LOGGER.warning("Cannot resolve file for \"" + path + "\" path.");
652.144 - return null;
652.145 - }
652.146 - }
652.147 -
652.148 -}
653.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/PyUnitHandlerFactory.java Sun Jan 04 13:11:53 2015 -0600
653.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
653.3 @@ -1,380 +0,0 @@
653.4 -/*
653.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
653.6 - *
653.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
653.8 - *
653.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
653.10 - * Other names may be trademarks of their respective owners.
653.11 - *
653.12 - * The contents of this file are subject to the terms of either the GNU
653.13 - * General Public License Version 2 only ("GPL") or the Common
653.14 - * Development and Distribution License("CDDL") (collectively, the
653.15 - * "License"). You may not use this file except in compliance with the
653.16 - * License. You can obtain a copy of the License at
653.17 - * http://www.netbeans.org/cddl-gplv2.html
653.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
653.19 - * specific language governing permissions and limitations under the
653.20 - * License. When distributing the software, include this License Header
653.21 - * Notice in each file and include the License file at
653.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
653.23 - * particular file as subject to the "Classpath" exception as provided
653.24 - * by Oracle in the GPL Version 2 section of the License file that
653.25 - * accompanied this code. If applicable, add the following below the
653.26 - * License Header, with the fields enclosed by brackets [] replaced by
653.27 - * your own identifying information:
653.28 - * "Portions Copyrighted [year] [name of copyright owner]"
653.29 - *
653.30 - * If you wish your version of this file to be governed by only the CDDL
653.31 - * or only the GPL Version 2, indicate your decision by adding
653.32 - * "[Contributor] elects to include this software in this distribution
653.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
653.34 - * single choice of license, a recipient has the option to distribute
653.35 - * your version of this file under either the CDDL, the GPL Version 2 or
653.36 - * to extend the choice of license to its licensees as provided above.
653.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
653.38 - * Version 2 license, then the option applies only if the new code is
653.39 - * made subject to such option by the copyright holder.
653.40 - *
653.41 - * Contributor(s):
653.42 - *
653.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
653.44 - */
653.45 -package org.netbeans.modules.python.testrunner.ui;
653.46 -
653.47 -import java.util.ArrayList;
653.48 -import java.util.Arrays;
653.49 -import java.util.Collections;
653.50 -import java.util.List;
653.51 -import java.util.logging.Level;
653.52 -import java.util.logging.Logger;
653.53 -import java.util.regex.Matcher;
653.54 -import java.util.regex.Pattern;
653.55 -import org.netbeans.modules.gsf.testrunner.ui.api.Manager;
653.56 -import org.netbeans.modules.gsf.testrunner.api.TestSession;
653.57 -import org.netbeans.modules.gsf.testrunner.api.TestSuite;
653.58 -import org.netbeans.modules.gsf.testrunner.api.Testcase;
653.59 -import org.netbeans.modules.gsf.testrunner.api.Trouble;
653.60 -import org.netbeans.modules.python.editor.lexer.PythonTokenId;
653.61 -import org.netbeans.modules.python.project.spi.TestRunner.TestType;
653.62 -import org.netbeans.modules.python.testrunner.PyUnitRunner;
653.63 -import org.openide.util.NbBundle;
653.64 -
653.65 -/**
653.66 - * An output recognizer for parsing output of the PyUnit test runner
653.67 - * script, <code>nb_test_runner.py</code>. Updates the test result UI.
653.68 - *
653.69 - * Closely based on the TestUnitHandlerFactory for Ruby by Erno.
653.70 - *
653.71 - * @author Erno Mononen
653.72 - * @author Tor Norbye
653.73 - */
653.74 -public class PyUnitHandlerFactory implements TestHandlerFactory {
653.75 -
653.76 - private static final Logger LOGGER = Logger.getLogger(PyUnitHandlerFactory.class.getName());
653.77 -
653.78 - public boolean printSummary() {
653.79 - return true;
653.80 - }
653.81 -
653.82 - public List<TestRecognizerHandler> createHandlers() {
653.83 - List<TestRecognizerHandler> result = new ArrayList<TestRecognizerHandler>();
653.84 - result.add(new SuiteStartingHandler());
653.85 - result.add(new SuiteStartedHandler());
653.86 - result.add(new SuiteFinishedHandler());
653.87 - result.add(new SuiteErrorOutputHandler());
653.88 - result.add(new TestStartedHandler());
653.89 - result.add(new TestFailedHandler());
653.90 - result.add(new TestErrorHandler());
653.91 - result.add(new TestFinishedHandler());
653.92 - result.add(new TestLoggerHandler());
653.93 - result.add(new TestMiscHandler());
653.94 - result.add(new SuiteMiscHandler());
653.95 - return result;
653.96 - }
653.97 -
653.98 - private static String errorMsg(long failureCount) {
653.99 - return NbBundle.getMessage(PyUnitHandlerFactory.class, "MSG_Error", failureCount);
653.100 - }
653.101 -
653.102 - private static String failureMsg(long failureCount) {
653.103 - return NbBundle.getMessage(PyUnitHandlerFactory.class, "MSG_Failure", failureCount);
653.104 - }
653.105 -
653.106 - static String[] getStackTrace(String message, String stackTrace) {
653.107 - List<String> stackTraceList = new ArrayList<String>();
653.108 - stackTraceList.add(message);
653.109 - for (String location : stackTrace.split("%BR%")) { //NOI18N
653.110 - if (/*!location.contains(PyUnitRunner.MEDIATOR_SCRIPT_NAME) &&*/ !location.contains(PyUnitRunner.RUNNER_SCRIPT_NAME)) { //NOI18N
653.111 - stackTraceList.add(location);
653.112 - }
653.113 - }
653.114 - return stackTraceList.toArray(new String[stackTraceList.size()]);
653.115 - }
653.116 -
653.117 - // Doctest message defined in nb_test_runner.py, the other one is from unittest
653.118 - private static final Pattern STRING_COMPARISON = Pattern.compile("(Expected (.+) but got (.+))|((.+) != (.+))", Pattern.DOTALL); // NOI18N
653.119 -
653.120 - // Package private for tests
653.121 - static Trouble.ComparisonFailure getComparisonFailure(String msg) {
653.122 - Matcher comparisonMatcher = STRING_COMPARISON.matcher(msg);
653.123 - if (!comparisonMatcher.matches()) {
653.124 - return null;
653.125 - }
653.126 - String expected;
653.127 - String actual;
653.128 -
653.129 - boolean isDocTest = false;
653.130 - expected = comparisonMatcher.group(2);
653.131 - if (expected == null) {
653.132 - expected = comparisonMatcher.group(5);
653.133 - actual = comparisonMatcher.group(6);
653.134 - } else {
653.135 - isDocTest = true;
653.136 - actual = comparisonMatcher.group(3);
653.137 - }
653.138 -
653.139 - // Convert back to multiline strings, if applicable
653.140 - expected = expected.replace("\\n", "\n"); // NOI18N
653.141 - actual = actual.replace("\\n", "\n"); // NOI18N
653.142 -
653.143 - if (isDocTest) {
653.144 - // We know the doc test output is in python console format which generally
653.145 - // can be highlighted by the python lexer (for string literals, etc.)
653.146 - return new Trouble.ComparisonFailure(expected, actual, PythonTokenId.PYTHON_MIME_TYPE);
653.147 - } else {
653.148 - return new Trouble.ComparisonFailure(expected, actual);
653.149 - }
653.150 - }
653.151 -
653.152 -
653.153 - static class TestFailedHandler extends TestRecognizerHandler {
653.154 - private List<String> output;
653.155 -
653.156 - public TestFailedHandler(String regex) {
653.157 - super(regex);
653.158 - }
653.159 -
653.160 - public TestFailedHandler() {
653.161 - super("%TEST_FAILED%\\stime=(.+)\\stestname=(.+) \\((.+)\\)\\smessage=(.*)\\slocation=(.*)"); //NOI18N
653.162 - }
653.163 -
653.164 - @Override
653.165 - void updateUI( Manager manager, TestSession session) {
653.166 - Testcase testcase = new Testcase(matcher.group(2), TestType.PY_UNIT.name(), session);
653.167 - testcase.setTimeMillis(toMillis(matcher.group(1)));
653.168 - testcase.setClassName(matcher.group(3));
653.169 - testcase.setTrouble(new Trouble(false));
653.170 - String message = matcher.group(4).replace("%BR%", "\n");
653.171 - String location = matcher.group(5);
653.172 - testcase.getTrouble().setStackTrace(getStackTrace(message, location));
653.173 - testcase.getTrouble().setComparisonFailure(getComparisonFailure(message));
653.174 -
653.175 - session.addTestCase(testcase);
653.176 -
653.177 - String failureMsg = failureMsg(session.incrementFailuresCount());
653.178 - String testCase = testcase.getName() + "(" + testcase.getClassName() + "):";
653.179 - output = new ArrayList<String>();
653.180 - output.add("");
653.181 - output.add(failureMsg);
653.182 - output.add(testCase);
653.183 - output.addAll(Arrays.asList(testcase.getTrouble().getStackTrace()));
653.184 - output.add("");
653.185 -
653.186 - manager.displayOutput(session, "", false);
653.187 - manager.displayOutput(session, failureMsg, false);
653.188 - manager.displayOutput(session, testCase, false); //NOI18N
653.189 - for (String line : testcase.getTrouble().getStackTrace()) {
653.190 - manager.displayOutput(session, line, false);
653.191 - }
653.192 - manager.displayOutput(session, "", false);
653.193 - testcase.addOutputLines(output);
653.194 - }
653.195 -
653.196 - @Override
653.197 - List<String> getRecognizedOutput() {
653.198 - return new ArrayList<String>(output);
653.199 - }
653.200 - }
653.201 -
653.202 - static class TestErrorHandler extends TestRecognizerHandler {
653.203 -
653.204 - private List<String> output;
653.205 -
653.206 - public TestErrorHandler() {
653.207 - super("%TEST_ERROR%\\stime=(.+)\\stestname=(.+) \\((.+)\\)\\smessage=(.*)\\slocation=(.*)"); //NOI18N
653.208 - }
653.209 -
653.210 - @Override
653.211 - void updateUI( Manager manager, TestSession session) {
653.212 - Testcase testcase = new Testcase(matcher.group(2), TestType.PY_UNIT.name(), session);
653.213 - testcase.setTimeMillis(toMillis(matcher.group(1)));
653.214 - testcase.setClassName(matcher.group(3));
653.215 - testcase.setTrouble(new Trouble(true));
653.216 - testcase.getTrouble().setStackTrace(getStackTrace(matcher.group(4).replace("%BR%", "\n"), matcher.group(5)));
653.217 - session.addTestCase(testcase);
653.218 -
653.219 - String errorMsg = errorMsg(session.incrementFailuresCount());
653.220 - String testCase = testcase.getName() + "(" + testcase.getClassName() + "):";
653.221 - output = new ArrayList<String>();
653.222 - output.add("");
653.223 - output.add(errorMsg);
653.224 - output.add(testCase);
653.225 - output.addAll(Arrays.asList(testcase.getTrouble().getStackTrace()));
653.226 - output.add("");
653.227 -
653.228 - manager.displayOutput(session, "", false);
653.229 - manager.displayOutput(session, errorMsg, false);
653.230 - manager.displayOutput(session, testCase, false); //NOI18N
653.231 - for (String line : testcase.getTrouble().getStackTrace()) {
653.232 - manager.displayOutput(session, line, true);
653.233 - }
653.234 - manager.displayOutput(session, "", false);
653.235 - testcase.addOutputLines(output);
653.236 - }
653.237 -
653.238 - @Override
653.239 - List<String> getRecognizedOutput() {
653.240 - return new ArrayList<String>(output);
653.241 - }
653.242 - }
653.243 -
653.244 - static class TestStartedHandler extends TestRecognizerHandler {
653.245 -
653.246 - public TestStartedHandler() {
653.247 - super("%TEST_STARTED%\\s*(.+) \\((.+)\\)"); //NOI18N
653.248 - }
653.249 -
653.250 - @Override
653.251 - void updateUI( Manager manager, TestSession session) {
653.252 - }
653.253 - }
653.254 -
653.255 - static class TestFinishedHandler extends TestRecognizerHandler {
653.256 -
653.257 - public TestFinishedHandler(String regex) {
653.258 - super(regex);
653.259 - }
653.260 -
653.261 - public TestFinishedHandler() {
653.262 - super("%TEST_FINISHED%\\stime=(.+)\\s+(.+) \\((.+)\\)"); //NOI18N
653.263 - }
653.264 -
653.265 - @Override
653.266 - void updateUI( Manager manager, TestSession session) {
653.267 - Testcase testcase = new Testcase(matcher.group(2), TestType.PY_UNIT.name(), session);
653.268 - testcase.setTimeMillis(toMillis(matcher.group(1)));
653.269 - testcase.setClassName(matcher.group(3));
653.270 - session.addTestCase(testcase);
653.271 - }
653.272 - }
653.273 -
653.274 - /**
653.275 - * Captures the rest of %TEST_* patterns that are not handled
653.276 - * otherwise (yet).
653.277 - */
653.278 - static class TestMiscHandler extends TestRecognizerHandler {
653.279 -
653.280 - public TestMiscHandler() {
653.281 - super("%TEST_.*"); //NOI18N
653.282 - }
653.283 -
653.284 - @Override
653.285 - void updateUI( Manager manager, TestSession session) {
653.286 - }
653.287 - }
653.288 -
653.289 - static class SuiteFinishedHandler extends TestRecognizerHandler {
653.290 -
653.291 - public SuiteFinishedHandler() {
653.292 - super("%SUITE_FINISHED%\\s+time=(.+)"); //NOI18N
653.293 - }
653.294 -
653.295 - @Override
653.296 - void updateUI( Manager manager, TestSession session) {
653.297 - manager.displayReport(session, session.getReport(toMillis(matcher.group(1))));
653.298 - }
653.299 - }
653.300 -
653.301 - static class SuiteStartedHandler extends TestRecognizerHandler {
653.302 -
653.303 - public SuiteStartedHandler() {
653.304 - super("%SUITE_STARTED%\\s.*"); //NOI18N
653.305 - }
653.306 -
653.307 - @Override
653.308 - void updateUI( Manager manager, TestSession session) {
653.309 - }
653.310 - }
653.311 -
653.312 - static class SuiteErrorOutputHandler extends TestRecognizerHandler {
653.313 -
653.314 - public SuiteErrorOutputHandler() {
653.315 - super("%SUITE_ERROR_OUTPUT%\\serror=(.*)"); //NOI18N
653.316 - }
653.317 -
653.318 - @Override
653.319 - void updateUI( Manager manager, TestSession session) {
653.320 - manager.displayOutput(session, matcher.group(1), true);
653.321 - manager.displayOutput(session, "", false);
653.322 - }
653.323 -
653.324 - @Override
653.325 - List<String> getRecognizedOutput() {
653.326 - return Collections.<String>singletonList(matcher.group(1));
653.327 - }
653.328 -
653.329 - }
653.330 -
653.331 - static class SuiteStartingHandler extends TestRecognizerHandler {
653.332 -
653.333 - private boolean firstSuite = true;
653.334 -
653.335 - public SuiteStartingHandler() {
653.336 - super("%SUITE_STARTING%\\s+(.+)"); //NOI18N
653.337 - }
653.338 -
653.339 - @Override
653.340 - void updateUI( Manager manager, TestSession session) {
653.341 - if (firstSuite) {
653.342 - firstSuite = false;
653.343 - manager.testStarted(session);
653.344 - }
653.345 - String suiteName = matcher.group(1);
653.346 - session.addSuite(new TestSuite(suiteName));
653.347 - manager.displaySuiteRunning(session, suiteName);
653.348 - }
653.349 - }
653.350 -
653.351 - /**
653.352 - * Captures the rest of %SUITE_* patterns that are not handled
653.353 - * otherwise (yet).
653.354 - */
653.355 - static class SuiteMiscHandler extends TestRecognizerHandler {
653.356 -
653.357 - public SuiteMiscHandler() {
653.358 - super("%SUITE_.*"); //NOI18N
653.359 - }
653.360 -
653.361 - @Override
653.362 - void updateUI( Manager manager, TestSession session) {
653.363 - }
653.364 - }
653.365 -
653.366 - /**
653.367 - * Captures output meant for logging.
653.368 - */
653.369 - static class TestLoggerHandler extends TestRecognizerHandler {
653.370 -
653.371 - public TestLoggerHandler() {
653.372 - super("%TEST_LOGGER%\\slevel=(.+)\\smsg=(.*)"); //NOI18N
653.373 - }
653.374 -
653.375 - @Override
653.376 - void updateUI( Manager manager, TestSession session) {
653.377 - Level level = Level.parse(matcher.group(1));
653.378 - if (LOGGER.isLoggable(level))
653.379 - LOGGER.log(level, matcher.group(2));
653.380 - }
653.381 - }
653.382 -}
653.383 -
654.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/PythonCallstackFrameNode.java Sun Jan 04 13:11:53 2015 -0600
654.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
654.3 @@ -1,84 +0,0 @@
654.4 -/*
654.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
654.6 - *
654.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
654.8 - *
654.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
654.10 - * Other names may be trademarks of their respective owners.
654.11 - *
654.12 - * The contents of this file are subject to the terms of either the GNU
654.13 - * General Public License Version 2 only ("GPL") or the Common
654.14 - * Development and Distribution License("CDDL") (collectively, the
654.15 - * "License"). You may not use this file except in compliance with the
654.16 - * License. You can obtain a copy of the License at
654.17 - * http://www.netbeans.org/cddl-gplv2.html
654.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
654.19 - * specific language governing permissions and limitations under the
654.20 - * License. When distributing the software, include this License Header
654.21 - * Notice in each file and include the License file at
654.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
654.23 - * particular file as subject to the "Classpath" exception as provided
654.24 - * by Oracle in the GPL Version 2 section of the License file that
654.25 - * accompanied this code. If applicable, add the following below the
654.26 - * License Header, with the fields enclosed by brackets [] replaced by
654.27 - * your own identifying information:
654.28 - * "Portions Copyrighted [year] [name of copyright owner]"
654.29 - *
654.30 - * Contributor(s):
654.31 - *
654.32 - * The Original Software is NetBeans. The Initial Developer of the Original
654.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
654.34 - * Microsystems, Inc. All Rights Reserved.
654.35 - *
654.36 - * If you wish your version of this file to be governed by only the CDDL
654.37 - * or only the GPL Version 2, indicate your decision by adding
654.38 - * "[Contributor] elects to include this software in this distribution
654.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
654.40 - * single choice of license, a recipient has the option to distribute
654.41 - * your version of this file under either the CDDL, the GPL Version 2 or
654.42 - * to extend the choice of license to its licensees as provided above.
654.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
654.44 - * Version 2 license, then the option applies only if the new code is
654.45 - * made subject to such option by the copyright holder.
654.46 - */
654.47 -
654.48 -package org.netbeans.modules.python.testrunner.ui;
654.49 -import javax.swing.Action;
654.50 -import org.netbeans.modules.gsf.testrunner.ui.api.CallstackFrameNode;
654.51 -import org.netbeans.modules.gsf.testrunner.ui.api.DiffViewAction;
654.52 -import org.netbeans.modules.gsf.testrunner.api.Trouble.ComparisonFailure;
654.53 -import org.openide.util.actions.SystemAction;
654.54 -
654.55 -/**
654.56 - *
654.57 - * @author Marian Petras
654.58 - */
654.59 -public final class PythonCallstackFrameNode extends CallstackFrameNode {
654.60 - private final String displayName;
654.61 -
654.62 - public PythonCallstackFrameNode(String frameInfo, String displayName) {
654.63 - super(frameInfo, displayName);
654.64 - // Keep our own copy since the parent will assign frameInfo to displayName
654.65 - // if none is provided
654.66 - this.displayName = displayName;
654.67 - }
654.68 -
654.69 - /**
654.70 - */
654.71 - @Override
654.72 - public Action getPreferredAction() {
654.73 - // If it's a diff failure line, the default action is to diff it!
654.74 - if (displayName != null) {
654.75 - ComparisonFailure failure = PyUnitHandlerFactory.getComparisonFailure(displayName);
654.76 - if (failure != null) {
654.77 - return new DiffViewAction(failure);
654.78 - }
654.79 - }
654.80 -
654.81 - return new JumpToCallStackAction(this, frameInfo);
654.82 - }
654.83 -
654.84 - public SystemAction[] getActions(boolean context) {
654.85 - return new SystemAction[0];
654.86 - }
654.87 -}
655.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/PythonTestMethodNode.java Sun Jan 04 13:11:53 2015 -0600
655.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
655.3 @@ -1,160 +0,0 @@
655.4 -/*
655.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
655.6 - *
655.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
655.8 - *
655.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
655.10 - * Other names may be trademarks of their respective owners.
655.11 - *
655.12 - * The contents of this file are subject to the terms of either the GNU
655.13 - * General Public License Version 2 only ("GPL") or the Common
655.14 - * Development and Distribution License("CDDL") (collectively, the
655.15 - * "License"). You may not use this file except in compliance with the
655.16 - * License. You can obtain a copy of the License at
655.17 - * http://www.netbeans.org/cddl-gplv2.html
655.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
655.19 - * specific language governing permissions and limitations under the
655.20 - * License. When distributing the software, include this License Header
655.21 - * Notice in each file and include the License file at
655.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
655.23 - * particular file as subject to the "Classpath" exception as provided
655.24 - * by Oracle in the GPL Version 2 section of the License file that
655.25 - * accompanied this code. If applicable, add the following below the
655.26 - * License Header, with the fields enclosed by brackets [] replaced by
655.27 - * your own identifying information:
655.28 - * "Portions Copyrighted [year] [name of copyright owner]"
655.29 - *
655.30 - * Contributor(s):
655.31 - *
655.32 - * The Original Software is NetBeans. The Initial Developer of the Original
655.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
655.34 - * Microsystems, Inc. All Rights Reserved.
655.35 - *
655.36 - * If you wish your version of this file to be governed by only the CDDL
655.37 - * or only the GPL Version 2, indicate your decision by adding
655.38 - * "[Contributor] elects to include this software in this distribution
655.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
655.40 - * single choice of license, a recipient has the option to distribute
655.41 - * your version of this file under either the CDDL, the GPL Version 2 or
655.42 - * to extend the choice of license to its licensees as provided above.
655.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
655.44 - * Version 2 license, then the option applies only if the new code is
655.45 - * made subject to such option by the copyright holder.
655.46 - */
655.47 -
655.48 -package org.netbeans.modules.python.testrunner.ui;
655.49 -
655.50 -import java.util.ArrayList;
655.51 -import java.util.List;
655.52 -import javax.swing.Action;
655.53 -import org.netbeans.api.project.Project;
655.54 -import org.netbeans.modules.gsf.testrunner.ui.api.DiffViewAction;
655.55 -import org.netbeans.modules.gsf.testrunner.ui.api.Locator;
655.56 -import org.netbeans.modules.gsf.testrunner.api.Testcase;
655.57 -import org.netbeans.modules.gsf.testrunner.ui.api.TestMethodNode;
655.58 -import org.openide.nodes.Node;
655.59 -import org.openide.util.NbBundle;
655.60 -import org.openide.util.lookup.Lookups;
655.61 -
655.62 -/**
655.63 - *
655.64 - * @author Marian Petras, Erno Mononen
655.65 - */
655.66 -public final class PythonTestMethodNode extends TestMethodNode {
655.67 -
655.68 - public PythonTestMethodNode(Testcase testcase, Project project) {
655.69 - super(testcase, project, Lookups.singleton(new Locator() {
655.70 -
655.71 - public void jumpToSource(Node node) {
655.72 - node.getPreferredAction().actionPerformed(null);
655.73 - }
655.74 - }));
655.75 - }
655.76 -
655.77 - /**
655.78 - */
655.79 - @Override
655.80 - public Action getPreferredAction() {
655.81 - // the location to jump from the node
655.82 - String testLocation = getTestLocation(testcase, getProject());
655.83 - String stackTrace = getTestCaseLineFromStackTrace(testcase);
655.84 - String jumpToLocation = stackTrace != null
655.85 - ? stackTrace
655.86 - : testLocation;
655.87 -
655.88 - return jumpToLocation == null
655.89 - ? new JumpToTestAction(testcase, getProject(), NbBundle.getMessage(PythonTestMethodNode.class, "LBL_GoToSource"), false)
655.90 - : new JumpToCallStackAction(this, jumpToLocation);
655.91 - }
655.92 -
655.93 - static String getTestLocation(Testcase testcase, Project project) {
655.94 - if (testcase.getLocation() == null) {
655.95 - return null;
655.96 - }
655.97 -// PythonPlatform platform = PythonPlatform.platformFor(project);
655.98 -// if (platform != null && platform.isJython()) {
655.99 -// // XXX: return no location for Jython -- ExampleMethods#implementation_backtrace
655.100 -// // behaves differently for MRI and Jython, on Jython the test file itself is not present
655.101 -// return null;
655.102 -// }
655.103 - return testcase.getLocation();
655.104 - }
655.105 -
655.106 - /**
655.107 - * Gets the line from the stack trace representing the last line in the test class.
655.108 - * If that can't be resolved
655.109 - * then returns the second line of the stack trace (the
655.110 - * first line represents the error message) or <code>null</code> if there
655.111 - * was no (usable) stack trace attached.
655.112 - *
655.113 - * @return
655.114 - */
655.115 - private static String getTestCaseLineFromStackTrace(Testcase testcase) {
655.116 - if (testcase.getTrouble() == null) {
655.117 - return null;
655.118 - }
655.119 - String[] stacktrace = testcase.getTrouble().getStackTrace();
655.120 - if (stacktrace == null || stacktrace.length <= 1) {
655.121 - return null;
655.122 - }
655.123 -
655.124 - // Skip unittest.py stuff
655.125 - int j = 1;
655.126 - for (; j < stacktrace.length; j++) {
655.127 - if (!stacktrace[j].contains("unittest.py")) {
655.128 - break;
655.129 - }
655.130 - }
655.131 -
655.132 - // Rails specific - maybe this doesn't apply to Python/Django?
655.133 -// if (stacktrace.length > 2) {
655.134 -// String underscoreName = PythonUtils.camelToUnderlinedName(testcase.getClassName());
655.135 -// for (int i = 0; i < stacktrace.length; i++) {
655.136 -// if (stacktrace[i].contains(underscoreName) && stacktrace[i].contains(testcase.getName())) {
655.137 -// return stacktrace[i];
655.138 -// }
655.139 -// }
655.140 -// }
655.141 -
655.142 - if (j == stacktrace.length) {
655.143 - j = stacktrace.length-1;
655.144 - }
655.145 -
655.146 - return stacktrace[j];
655.147 - }
655.148 -
655.149 -
655.150 - @Override
655.151 - public Action[] getActions(boolean context) {
655.152 - if (context) {
655.153 - return new Action[0];
655.154 - }
655.155 - List<Action> actions = new ArrayList<Action>();
655.156 - actions.add(getPreferredAction());
655.157 - actions.add(new DiffViewAction(testcase));
655.158 - actions.add(new RunTestMethodAction(testcase, getProject(), NbBundle.getMessage(PythonTestMethodNode.class, "LBL_RerunTest"), false));
655.159 - actions.add(new RunTestMethodAction(testcase, getProject(), NbBundle.getMessage(PythonTestMethodNode.class, "LBL_DebugTest"), true));
655.160 -// actions.add(new DisplayOutputForNodeAction(testcase.getOutput(), testcase.getSession()));
655.161 - return actions.toArray(new Action[actions.size()]);
655.162 - }
655.163 -}
656.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/PythonTestsuiteNode.java Sun Jan 04 13:11:53 2015 -0600
656.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
656.3 @@ -1,116 +0,0 @@
656.4 -/*
656.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
656.6 - *
656.7 - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
656.8 - *
656.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
656.10 - * Other names may be trademarks of their respective owners.
656.11 - *
656.12 - * The contents of this file are subject to the terms of either the GNU
656.13 - * General Public License Version 2 only ("GPL") or the Common
656.14 - * Development and Distribution License("CDDL") (collectively, the
656.15 - * "License"). You may not use this file except in compliance with the
656.16 - * License. You can obtain a copy of the License at
656.17 - * http://www.netbeans.org/cddl-gplv2.html
656.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
656.19 - * specific language governing permissions and limitations under the
656.20 - * License. When distributing the software, include this License Header
656.21 - * Notice in each file and include the License file at
656.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
656.23 - * particular file as subject to the "Classpath" exception as provided
656.24 - * by Oracle in the GPL Version 2 section of the License file that
656.25 - * accompanied this code. If applicable, add the following below the
656.26 - * License Header, with the fields enclosed by brackets [] replaced by
656.27 - * your own identifying information:
656.28 - * "Portions Copyrighted [year] [name of copyright owner]"
656.29 - *
656.30 - * Contributor(s):
656.31 - *
656.32 - * The Original Software is NetBeans. The Initial Developer of the Original
656.33 - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
656.34 - * Microsystems, Inc. All Rights Reserved.
656.35 - *
656.36 - * If you wish your version of this file to be governed by only the CDDL
656.37 - * or only the GPL Version 2, indicate your decision by adding
656.38 - * "[Contributor] elects to include this software in this distribution
656.39 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
656.40 - * single choice of license, a recipient has the option to distribute
656.41 - * your version of this file under either the CDDL, the GPL Version 2 or
656.42 - * to extend the choice of license to its licensees as provided above.
656.43 - * However, if you add GPL Version 2 code and therefore, elected the GPL
656.44 - * Version 2 license, then the option applies only if the new code is
656.45 - * made subject to such option by the copyright holder.
656.46 - */
656.47 -
656.48 -package org.netbeans.modules.python.testrunner.ui;
656.49 -
656.50 -import java.util.ArrayList;
656.51 -import java.util.List;
656.52 -import javax.swing.Action;
656.53 -import org.netbeans.modules.gsf.testrunner.ui.api.Locator;
656.54 -import org.netbeans.modules.gsf.testrunner.api.Testcase;
656.55 -import org.netbeans.modules.gsf.testrunner.ui.api.TestsuiteNode;
656.56 -import org.netbeans.modules.python.project.spi.TestRunner.TestType;
656.57 -import org.openide.nodes.Node;
656.58 -import org.openide.util.NbBundle;
656.59 -import org.openide.util.lookup.Lookups;
656.60 -
656.61 -/**
656.62 - *
656.63 - * @author Marian Petras, Erno Mononen
656.64 - */
656.65 -public final class PythonTestsuiteNode extends TestsuiteNode {
656.66 -
656.67 - public PythonTestsuiteNode(String suiteName, boolean filtered) {
656.68 - super(null, suiteName, filtered, Lookups.singleton(new Locator() {
656.69 -
656.70 - public void jumpToSource(Node node) {
656.71 - Action jumpTo = node.getPreferredAction();
656.72 - if (jumpTo != null) {
656.73 - jumpTo.actionPerformed(null);
656.74 - }
656.75 - }
656.76 - }));
656.77 - }
656.78 -
656.79 - private Testcase getFirstTestCase() {
656.80 - return report.getTests().isEmpty() ? null : report.getTests().iterator().next();
656.81 - }
656.82 -
656.83 - @Override
656.84 - public Action getPreferredAction() {
656.85 - Testcase testcase = getFirstTestCase();
656.86 - if (testcase == null) {
656.87 - // need to have at least one test case to locate the test file
656.88 - return null;
656.89 - }
656.90 - TestType type = TestType.valueOf(testcase.getType());
656.91 - //if (TestType.RSPEC == type) {
656.92 - // //XXX: not the exact location of the class
656.93 - // return new JumpToCallStackAction(this, PythonTestMethodNode.getTestLocation(testcase, report.getProject()), 1);
656.94 - //}
656.95 - return new JumpToTestAction(getFirstTestCase(), report.getProject(), NbBundle.getMessage(PythonTestsuiteNode.class, "LBL_GoToSource"), true);
656.96 - }
656.97 -
656.98 - @Override
656.99 - public Action[] getActions(boolean context) {
656.100 - if (context) {
656.101 - return new Action[0];
656.102 - }
656.103 - List<Action> actions = new ArrayList<Action>(3);
656.104 - Action preferred = getPreferredAction();
656.105 - if (preferred != null) {
656.106 - actions.add(preferred);
656.107 - }
656.108 - Testcase testcase = getFirstTestCase();
656.109 - // these actions are enable only if the suite had at least one test (otherwise
656.110 - // we can't reliably locate the test file)
656.111 - if (testcase != null) {
656.112 - actions.add(new RunTestSuiteAction(testcase, report.getProject(), NbBundle.getMessage(PythonTestMethodNode.class, "LBL_RerunTest"), false));
656.113 - actions.add(new RunTestSuiteAction(testcase, report.getProject(), NbBundle.getMessage(PythonTestMethodNode.class, "LBL_DebugTest"), true));
656.114 -// actions.add(new DisplayOutputForNodeAction(getOutput(), testcase.getSession()));
656.115 - }
656.116 - return actions.toArray(new Action[actions.size()]);
656.117 - }
656.118 -
656.119 -}
657.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/RunTestMethodAction.java Sun Jan 04 13:11:53 2015 -0600
657.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
657.3 @@ -1,78 +0,0 @@
657.4 -/*
657.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
657.6 - *
657.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
657.8 - *
657.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
657.10 - * Other names may be trademarks of their respective owners.
657.11 - *
657.12 - * The contents of this file are subject to the terms of either the GNU
657.13 - * General Public License Version 2 only ("GPL") or the Common
657.14 - * Development and Distribution License("CDDL") (collectively, the
657.15 - * "License"). You may not use this file except in compliance with the
657.16 - * License. You can obtain a copy of the License at
657.17 - * http://www.netbeans.org/cddl-gplv2.html
657.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
657.19 - * specific language governing permissions and limitations under the
657.20 - * License. When distributing the software, include this License Header
657.21 - * Notice in each file and include the License file at
657.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
657.23 - * particular file as subject to the "Classpath" exception as provided
657.24 - * by Oracle in the GPL Version 2 section of the License file that
657.25 - * accompanied this code. If applicable, add the following below the
657.26 - * License Header, with the fields enclosed by brackets [] replaced by
657.27 - * your own identifying information:
657.28 - * "Portions Copyrighted [year] [name of copyright owner]"
657.29 - *
657.30 - * If you wish your version of this file to be governed by only the CDDL
657.31 - * or only the GPL Version 2, indicate your decision by adding
657.32 - * "[Contributor] elects to include this software in this distribution
657.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
657.34 - * single choice of license, a recipient has the option to distribute
657.35 - * your version of this file under either the CDDL, the GPL Version 2 or
657.36 - * to extend the choice of license to its licensees as provided above.
657.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
657.38 - * Version 2 license, then the option applies only if the new code is
657.39 - * made subject to such option by the copyright holder.
657.40 - *
657.41 - * Contributor(s):
657.42 - *
657.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
657.44 - */
657.45 -package org.netbeans.modules.python.testrunner.ui;
657.46 -
657.47 -import java.awt.event.ActionEvent;
657.48 -import java.util.logging.Logger;
657.49 -import org.netbeans.api.project.Project;
657.50 -import org.netbeans.modules.gsf.api.DeclarationFinder.DeclarationLocation;
657.51 -import org.netbeans.modules.gsf.testrunner.api.Testcase;
657.52 -import org.netbeans.modules.python.editor.PythonDeclarationFinder;
657.53 -import org.netbeans.modules.python.project.spi.TestRunner;
657.54 -
657.55 -/**
657.56 - * An action for running/debugging a singe test method.
657.57 - *
657.58 - * @author Erno Mononen
657.59 - */
657.60 -class RunTestMethodAction extends BaseTestMethodNodeAction {
657.61 -
657.62 - private static final Logger LOGGER = Logger.getLogger(RunTestMethodAction.class.getName());
657.63 - private final boolean debug;
657.64 -
657.65 - public RunTestMethodAction(Testcase testcase, Project project, String name, boolean debug) {
657.66 - super(testcase, project, name);
657.67 - this.debug = debug;
657.68 - }
657.69 -
657.70 - protected void doActionPerformed(ActionEvent e) {
657.71 - TestRunner.TestType type = TestRunner.TestType.valueOf(testcase.getType());
657.72 - //if (TestRunner.TestType.RSPEC == type) {
657.73 - // runRspec();
657.74 - // return;
657.75 - //}
657.76 - DeclarationLocation location = PythonDeclarationFinder.getTestDeclaration(getTestSourceRoot(), getTestMethod(), false);
657.77 - if (!(DeclarationLocation.NONE == location)) {
657.78 - getTestRunner(type).runSingleTest(location.getFileObject(),testcase.getClassName(), testcase.getName(), debug);
657.79 - }
657.80 - }
657.81 -}
658.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/RunTestSuiteAction.java Sun Jan 04 13:11:53 2015 -0600
658.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
658.3 @@ -1,77 +0,0 @@
658.4 -/*
658.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
658.6 - *
658.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
658.8 - *
658.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
658.10 - * Other names may be trademarks of their respective owners.
658.11 - *
658.12 - * The contents of this file are subject to the terms of either the GNU
658.13 - * General Public License Version 2 only ("GPL") or the Common
658.14 - * Development and Distribution License("CDDL") (collectively, the
658.15 - * "License"). You may not use this file except in compliance with the
658.16 - * License. You can obtain a copy of the License at
658.17 - * http://www.netbeans.org/cddl-gplv2.html
658.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
658.19 - * specific language governing permissions and limitations under the
658.20 - * License. When distributing the software, include this License Header
658.21 - * Notice in each file and include the License file at
658.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
658.23 - * particular file as subject to the "Classpath" exception as provided
658.24 - * by Oracle in the GPL Version 2 section of the License file that
658.25 - * accompanied this code. If applicable, add the following below the
658.26 - * License Header, with the fields enclosed by brackets [] replaced by
658.27 - * your own identifying information:
658.28 - * "Portions Copyrighted [year] [name of copyright owner]"
658.29 - *
658.30 - * If you wish your version of this file to be governed by only the CDDL
658.31 - * or only the GPL Version 2, indicate your decision by adding
658.32 - * "[Contributor] elects to include this software in this distribution
658.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
658.34 - * single choice of license, a recipient has the option to distribute
658.35 - * your version of this file under either the CDDL, the GPL Version 2 or
658.36 - * to extend the choice of license to its licensees as provided above.
658.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
658.38 - * Version 2 license, then the option applies only if the new code is
658.39 - * made subject to such option by the copyright holder.
658.40 - *
658.41 - * Contributor(s):
658.42 - *
658.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
658.44 - */
658.45 -package org.netbeans.modules.python.testrunner.ui;
658.46 -
658.47 -import java.awt.event.ActionEvent;
658.48 -import org.netbeans.api.project.Project;
658.49 -import org.netbeans.modules.gsf.api.DeclarationFinder.DeclarationLocation;
658.50 -import org.netbeans.modules.gsf.testrunner.api.Testcase;
658.51 -import org.netbeans.modules.python.editor.PythonDeclarationFinder;
658.52 -import org.netbeans.modules.python.project.spi.TestRunner;
658.53 -
658.54 -/**
658.55 - * Action for running all tests in a file.
658.56 - *
658.57 - * @author Erno Mononen
658.58 - */
658.59 -final class RunTestSuiteAction extends BaseTestMethodNodeAction {
658.60 -
658.61 - private final boolean debug;
658.62 -
658.63 - public RunTestSuiteAction(Testcase testcase, Project project, String name, boolean debug) {
658.64 - super(testcase, project, name);
658.65 - this.debug = debug;
658.66 - }
658.67 -
658.68 - protected void doActionPerformed(ActionEvent e) {
658.69 - TestRunner.TestType type = TestRunner.TestType.valueOf(testcase.getType());
658.70 - //if (TestRunner.TestType.RSPEC == type) {
658.71 - // runRspec();
658.72 - // return;
658.73 - //}
658.74 - DeclarationLocation location = PythonDeclarationFinder.getTestDeclaration(getTestSourceRoot(), getTestMethod(), true);
658.75 - if (!(DeclarationLocation.NONE == location)) {
658.76 - getTestRunner(type).runTest(location.getFileObject(), debug);
658.77 - }
658.78 -
658.79 - }
658.80 -}
659.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/TestHandlerFactory.java Sun Jan 04 13:11:53 2015 -0600
659.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
659.3 @@ -1,57 +0,0 @@
659.4 -/*
659.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
659.6 - *
659.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
659.8 - *
659.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
659.10 - * Other names may be trademarks of their respective owners.
659.11 - *
659.12 - * The contents of this file are subject to the terms of either the GNU
659.13 - * General Public License Version 2 only ("GPL") or the Common
659.14 - * Development and Distribution License("CDDL") (collectively, the
659.15 - * "License"). You may not use this file except in compliance with the
659.16 - * License. You can obtain a copy of the License at
659.17 - * http://www.netbeans.org/cddl-gplv2.html
659.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
659.19 - * specific language governing permissions and limitations under the
659.20 - * License. When distributing the software, include this License Header
659.21 - * Notice in each file and include the License file at
659.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
659.23 - * particular file as subject to the "Classpath" exception as provided
659.24 - * by Oracle in the GPL Version 2 section of the License file that
659.25 - * accompanied this code. If applicable, add the following below the
659.26 - * License Header, with the fields enclosed by brackets [] replaced by
659.27 - * your own identifying information:
659.28 - * "Portions Copyrighted [year] [name of copyright owner]"
659.29 - *
659.30 - * If you wish your version of this file to be governed by only the CDDL
659.31 - * or only the GPL Version 2, indicate your decision by adding
659.32 - * "[Contributor] elects to include this software in this distribution
659.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
659.34 - * single choice of license, a recipient has the option to distribute
659.35 - * your version of this file under either the CDDL, the GPL Version 2 or
659.36 - * to extend the choice of license to its licensees as provided above.
659.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
659.38 - * Version 2 license, then the option applies only if the new code is
659.39 - * made subject to such option by the copyright holder.
659.40 - *
659.41 - * Contributor(s):
659.42 - *
659.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
659.44 - */
659.45 -
659.46 -package org.netbeans.modules.python.testrunner.ui;
659.47 -
659.48 -import java.util.List;
659.49 -
659.50 -/**
659.51 - *
659.52 - * @author Erno Mononen
659.53 - */
659.54 -public interface TestHandlerFactory {
659.55 -
659.56 - List<TestRecognizerHandler> createHandlers();
659.57 -
659.58 - boolean printSummary();
659.59 -
659.60 -}
660.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/TestRecognizerHandler.java Sun Jan 04 13:11:53 2015 -0600
660.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
660.3 @@ -1,113 +0,0 @@
660.4 -/*
660.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
660.6 - *
660.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
660.8 - *
660.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
660.10 - * Other names may be trademarks of their respective owners.
660.11 - *
660.12 - * The contents of this file are subject to the terms of either the GNU
660.13 - * General Public License Version 2 only ("GPL") or the Common
660.14 - * Development and Distribution License("CDDL") (collectively, the
660.15 - * "License"). You may not use this file except in compliance with the
660.16 - * License. You can obtain a copy of the License at
660.17 - * http://www.netbeans.org/cddl-gplv2.html
660.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
660.19 - * specific language governing permissions and limitations under the
660.20 - * License. When distributing the software, include this License Header
660.21 - * Notice in each file and include the License file at
660.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
660.23 - * particular file as subject to the "Classpath" exception as provided
660.24 - * by Oracle in the GPL Version 2 section of the License file that
660.25 - * accompanied this code. If applicable, add the following below the
660.26 - * License Header, with the fields enclosed by brackets [] replaced by
660.27 - * your own identifying information:
660.28 - * "Portions Copyrighted [year] [name of copyright owner]"
660.29 - *
660.30 - * If you wish your version of this file to be governed by only the CDDL
660.31 - * or only the GPL Version 2, indicate your decision by adding
660.32 - * "[Contributor] elects to include this software in this distribution
660.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
660.34 - * single choice of license, a recipient has the option to distribute
660.35 - * your version of this file under either the CDDL, the GPL Version 2 or
660.36 - * to extend the choice of license to its licensees as provided above.
660.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
660.38 - * Version 2 license, then the option applies only if the new code is
660.39 - * made subject to such option by the copyright holder.
660.40 - *
660.41 - * Contributor(s):
660.42 - *
660.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
660.44 - */
660.45 -package org.netbeans.modules.python.testrunner.ui;
660.46 -
660.47 -import java.util.Collections;
660.48 -import java.util.List;
660.49 -import java.util.logging.Level;
660.50 -import java.util.logging.Logger;
660.51 -import java.util.regex.Matcher;
660.52 -import java.util.regex.Pattern;
660.53 -import org.netbeans.modules.gsf.testrunner.ui.api.Manager;
660.54 -import org.netbeans.modules.gsf.testrunner.api.TestSession;
660.55 -
660.56 -/**
660.57 - * Base class for test recognizer handlers.
660.58 - *
660.59 - * @author Erno Mononen
660.60 - */
660.61 -abstract class TestRecognizerHandler {
660.62 -
660.63 - private static final Logger LOGGER = Logger.getLogger(TestRecognizerHandler.class.getName());
660.64 -
660.65 - protected final Pattern pattern;
660.66 - protected Matcher matcher;
660.67 -
660.68 - TestRecognizerHandler(String regex) {
660.69 - // handle newline chars at the end -- see #143508
660.70 - if (!regex.endsWith(".*")) { //NOI18N
660.71 - regex += ".*"; //NOI18N
660.72 - }
660.73 - // see #151725
660.74 - if (!regex.startsWith(".*")) { //NOI18N
660.75 - regex = ".*" + regex; //NOI18N
660.76 - }
660.77 - this.pattern = Pattern.compile(regex, Pattern.DOTALL);
660.78 - }
660.79 -
660.80 - final boolean matches(String line) {
660.81 - return match(line).matches();
660.82 - }
660.83 -
660.84 - /**
660.85 - * <i>Package private for unit tests, otherwise don't use directly</i>.
660.86 - */
660.87 - final Matcher match(String line) {
660.88 - this.matcher = pattern.matcher(line);
660.89 - return matcher;
660.90 - }
660.91 -
660.92 - abstract void updateUI(Manager manager, TestSession session);
660.93 -
660.94 - /**
660.95 - * Gets the RecognizedOutput for output that should be passed on
660.96 - * for printing to Output. Override in subclasses as needed, the default
660.97 - * implementation supresses all output (i.e. nothing is passed on
660.98 - * for printing).
660.99 - *
660.100 - * @return the RecognizedOutput for output that should be passed on
660.101 - * for printing to Output.
660.102 - */
660.103 - List<String> getRecognizedOutput() {
660.104 - return Collections.<String>emptyList();
660.105 - }
660.106 -
660.107 - protected static int toMillis(String timeInSeconds) {
660.108 - try {
660.109 - Double elapsedTimeMillis = Double.parseDouble(timeInSeconds) * 1000;
660.110 - return elapsedTimeMillis.intValue();
660.111 - } catch (NumberFormatException nfe) {
660.112 - LOGGER.log(Level.WARNING, "Could not parse time, returning 0", nfe);
660.113 - }
660.114 - return 0;
660.115 - }
660.116 -}
661.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/TestRunnerInputProcessorFactory.java Sun Jan 04 13:11:53 2015 -0600
661.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
661.3 @@ -1,143 +0,0 @@
661.4 -/*
661.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
661.6 - *
661.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
661.8 - *
661.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
661.10 - * Other names may be trademarks of their respective owners.
661.11 - *
661.12 - * The contents of this file are subject to the terms of either the GNU
661.13 - * General Public License Version 2 only ("GPL") or the Common
661.14 - * Development and Distribution License("CDDL") (collectively, the
661.15 - * "License"). You may not use this file except in compliance with the
661.16 - * License. You can obtain a copy of the License at
661.17 - * http://www.netbeans.org/cddl-gplv2.html
661.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
661.19 - * specific language governing permissions and limitations under the
661.20 - * License. When distributing the software, include this License Header
661.21 - * Notice in each file and include the License file at
661.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
661.23 - * particular file as subject to the "Classpath" exception as provided
661.24 - * by Oracle in the GPL Version 2 section of the License file that
661.25 - * accompanied this code. If applicable, add the following below the
661.26 - * License Header, with the fields enclosed by brackets [] replaced by
661.27 - * your own identifying information:
661.28 - * "Portions Copyrighted [year] [name of copyright owner]"
661.29 - *
661.30 - * If you wish your version of this file to be governed by only the CDDL
661.31 - * or only the GPL Version 2, indicate your decision by adding
661.32 - * "[Contributor] elects to include this software in this distribution
661.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
661.34 - * single choice of license, a recipient has the option to distribute
661.35 - * your version of this file under either the CDDL, the GPL Version 2 or
661.36 - * to extend the choice of license to its licensees as provided above.
661.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
661.38 - * Version 2 license, then the option applies only if the new code is
661.39 - * made subject to such option by the copyright holder.
661.40 - *
661.41 - * Contributor(s):
661.42 - *
661.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
661.44 - */
661.45 -package org.netbeans.modules.python.testrunner.ui;
661.46 -
661.47 -import java.io.IOException;
661.48 -import java.util.ArrayList;
661.49 -import java.util.List;
661.50 -import java.util.logging.Level;
661.51 -import java.util.logging.Logger;
661.52 -import org.netbeans.api.extexecution.ExecutionDescriptor;
661.53 -import org.netbeans.api.extexecution.input.InputProcessor;
661.54 -import org.netbeans.modules.gsf.testrunner.ui.api.Manager;
661.55 -import org.netbeans.modules.gsf.testrunner.api.TestSession;
661.56 -import org.openide.util.Exceptions;
661.57 -import org.openide.util.NbBundle;
661.58 -
661.59 -/**
661.60 - *
661.61 - * @author Erno Mononen
661.62 - */
661.63 -public final class TestRunnerInputProcessorFactory implements ExecutionDescriptor.InputProcessorFactory {
661.64 -
661.65 - private static final Logger LOGGER = Logger.getLogger(TestRunnerInputProcessorFactory.class.getName());
661.66 -
661.67 - private final Data data;
661.68 -
661.69 - public TestRunnerInputProcessorFactory(Manager manager, TestSession session, boolean printSummary) {
661.70 - this.data = new Data(manager, session, printSummary);
661.71 - }
661.72 -
661.73 - public InputProcessor newInputProcessor(InputProcessor defaultProcessor) {
661.74 - return new TestRunnerInputProcessor(defaultProcessor, data);
661.75 - }
661.76 -
661.77 - // just a helper for holding conf data
661.78 - private static class Data {
661.79 - private final Manager manager;
661.80 - private final TestSession session;
661.81 - private final boolean printSummary;
661.82 -
661.83 - public Data(Manager manager, TestSession session, boolean printSummary) {
661.84 - this.manager = manager;
661.85 - this.session = session;
661.86 - this.printSummary = printSummary;
661.87 - }
661.88 - }
661.89 -
661.90 - private static class TestRunnerInputProcessor implements InputProcessor {
661.91 -
661.92 - private final InputProcessor delegate;
661.93 - private final Data data;
661.94 -
661.95 - public TestRunnerInputProcessor(InputProcessor delegate, Data data) {
661.96 - this.delegate = delegate;
661.97 - this.data = data;
661.98 - }
661.99 -
661.100 - public void processInput(char[] chars) throws IOException {
661.101 - delegate.processInput(chars);
661.102 - }
661.103 -
661.104 - public void reset() throws IOException {
661.105 - delegate.reset();
661.106 - }
661.107 -
661.108 - public void close() throws IOException {
661.109 - finish();
661.110 - delegate.close();
661.111 - }
661.112 -
661.113 - private synchronized void finish() {
661.114 -
661.115 - printSummary();
661.116 -
661.117 - if (LOGGER.isLoggable(Level.FINE)) {
661.118 - LOGGER.log(Level.FINE, "Session finished: " + data.session);
661.119 - }
661.120 - data.manager.sessionFinished(data.session);
661.121 - }
661.122 -
661.123 - private void printSummary() {
661.124 - if (!data.printSummary) {
661.125 - return;
661.126 - }
661.127 - List<String> output = new ArrayList<String>(2);
661.128 - output.add(""); //NOI18N
661.129 - output.add(NbBundle.getMessage(TestRunnerInputProcessorFactory.class,
661.130 - "MSG_TestSessionFinished", new Double(data.session.getSessionResult().getElapsedTime() / 1000d)));
661.131 - output.add(NbBundle.getMessage(TestRunnerInputProcessorFactory.class,
661.132 - "MSG_TestSessionFinishedSummary",
661.133 - data.session.getSessionResult().getTotal(),
661.134 - data.session.getSessionResult().getFailed(),
661.135 - data.session.getSessionResult().getErrors()));
661.136 -
661.137 - try {
661.138 - for (String line : output) {
661.139 - delegate.processInput((line + "\n").toCharArray()); //NOI18N
661.140 - }
661.141 - } catch (IOException ex) {
661.142 - Exceptions.printStackTrace(ex);
661.143 - }
661.144 - }
661.145 - }
661.146 -}
662.1 --- a/python.testrunner/src/org/netbeans/modules/python/testrunner/ui/TestRunnerLineConvertor.java Sun Jan 04 13:11:53 2015 -0600
662.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
662.3 @@ -1,127 +0,0 @@
662.4 -/*
662.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
662.6 - *
662.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
662.8 - *
662.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
662.10 - * Other names may be trademarks of their respective owners.
662.11 - *
662.12 - * The contents of this file are subject to the terms of either the GNU
662.13 - * General Public License Version 2 only ("GPL") or the Common
662.14 - * Development and Distribution License("CDDL") (collectively, the
662.15 - * "License"). You may not use this file except in compliance with the
662.16 - * License. You can obtain a copy of the License at
662.17 - * http://www.netbeans.org/cddl-gplv2.html
662.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
662.19 - * specific language governing permissions and limitations under the
662.20 - * License. When distributing the software, include this License Header
662.21 - * Notice in each file and include the License file at
662.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
662.23 - * particular file as subject to the "Classpath" exception as provided
662.24 - * by Oracle in the GPL Version 2 section of the License file that
662.25 - * accompanied this code. If applicable, add the following below the
662.26 - * License Header, with the fields enclosed by brackets [] replaced by
662.27 - * your own identifying information:
662.28 - * "Portions Copyrighted [year] [name of copyright owner]"
662.29 - *
662.30 - * If you wish your version of this file to be governed by only the CDDL
662.31 - * or only the GPL Version 2, indicate your decision by adding
662.32 - * "[Contributor] elects to include this software in this distribution
662.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
662.34 - * single choice of license, a recipient has the option to distribute
662.35 - * your version of this file under either the CDDL, the GPL Version 2 or
662.36 - * to extend the choice of license to its licensees as provided above.
662.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
662.38 - * Version 2 license, then the option applies only if the new code is
662.39 - * made subject to such option by the copyright holder.
662.40 - *
662.41 - * Contributor(s):
662.42 - *
662.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
662.44 - */
662.45 -package org.netbeans.modules.python.testrunner.ui;
662.46 -
662.47 -import java.util.ArrayList;
662.48 -import java.util.List;
662.49 -import java.util.logging.Level;
662.50 -import java.util.logging.Logger;
662.51 -import org.netbeans.api.extexecution.print.ConvertedLine;
662.52 -import org.netbeans.api.extexecution.print.LineConvertor;
662.53 -import org.netbeans.modules.gsf.testrunner.ui.api.Manager;
662.54 -import org.netbeans.modules.gsf.testrunner.api.RerunHandler;
662.55 -import org.netbeans.modules.gsf.testrunner.api.TestSession;
662.56 -import org.netbeans.modules.python.api.PythonLineConvertorFactory;
662.57 -import org.netbeans.modules.python.testrunner.PythonTestRunnerNodeFactory;
662.58 -
662.59 -/**
662.60 - *
662.61 - * @author Erno Mononen
662.62 - */
662.63 -public final class TestRunnerLineConvertor implements LineConvertor {
662.64 -
662.65 - private static final Logger LOGGER = Logger.getLogger(TestRunnerLineConvertor.class.getName());
662.66 - private final Manager manager;
662.67 - private TestSession session;
662.68 - private final List<TestRecognizerHandler> handlers;
662.69 -
662.70 - public TestRunnerLineConvertor(Manager manager, TestSession session, TestHandlerFactory handlerFactory) {
662.71 - this.manager = manager;
662.72 - this.session = session;
662.73 - this.handlers = handlerFactory.createHandlers();
662.74 - }
662.75 -
662.76 - public synchronized void refreshSession() {
662.77 - RerunHandler handler = this.session.getRerunHandler();
662.78 - Manager.getInstance().setNodeFactory(new PythonTestRunnerNodeFactory());
662.79 - this.session = new TestSession(session.getName(), session.getProject(), session.getSessionType());
662.80 - session.setRerunHandler(handler);
662.81 - }
662.82 -
662.83 - public synchronized List<ConvertedLine> convert(String line) {
662.84 -
662.85 - for (TestRecognizerHandler handler : handlers) {
662.86 - if (handler.matches(line)) {
662.87 - if (LOGGER.isLoggable(Level.FINE)) {
662.88 - LOGGER.log(Level.FINE, "Handler [" + handler + "] matched line: " + line);
662.89 - }
662.90 - try {
662.91 - handler.updateUI(manager, session);
662.92 - return asConvertedLines(handler.getRecognizedOutput());
662.93 - } catch (IllegalStateException ise) {
662.94 - // ISE is thrown when mathing a group fails, should be enough to log a warning
662.95 - LOGGER.log(Level.WARNING, "Failed to process line: " + line + " with handler: " + handler, ise);
662.96 - } catch (IndexOutOfBoundsException ioobe) {
662.97 - // IOOBE is thrown when there is no group with the expected index.
662.98 - LOGGER.log(Level.WARNING, "Failed to process line: " + line + " with handler: " + handler, ioobe);
662.99 - }
662.100 - }
662.101 - }
662.102 -
662.103 - if (LOGGER.isLoggable(Level.FINE)) {
662.104 - LOGGER.log(Level.FINE, "No handler for line: " + line);
662.105 - }
662.106 - session.addOutput(line);
662.107 - manager.displayOutput(session, line, false);
662.108 - return null;
662.109 - }
662.110 -
662.111 - private List<ConvertedLine> asConvertedLines(List<String> lines) {
662.112 - List<ConvertedLine> result = new ArrayList<ConvertedLine>(lines.size());
662.113 -
662.114 - boolean handled = false;
662.115 - for (String line : lines) {
662.116 - for (LineConvertor convertor : PythonLineConvertorFactory.getStandardConvertors(session.getFileLocator())) {
662.117 - List<ConvertedLine> converted = convertor.convert(line);
662.118 - if (converted != null) {
662.119 - result.addAll(converted);
662.120 - handled = true;
662.121 - break;
662.122 - }
662.123 - }
662.124 - if (!handled) {
662.125 - result.add(ConvertedLine.forText(line, null));
662.126 - }
662.127 - }
662.128 - return result;
662.129 - }
662.130 -}
663.1 --- a/python.testrunner/test/unit/src/org/netbeans/modules/python/testrunner/ui/PyUnitRecognizerTest.java Sun Jan 04 13:11:53 2015 -0600
663.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
663.3 @@ -1,268 +0,0 @@
663.4 -/*
663.5 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
663.6 - *
663.7 - * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
663.8 - *
663.9 - * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
663.10 - * Other names may be trademarks of their respective owners.
663.11 - *
663.12 - * The contents of this file are subject to the terms of either the GNU
663.13 - * General Public License Version 2 only ("GPL") or the Common
663.14 - * Development and Distribution License("CDDL") (collectively, the
663.15 - * "License"). You may not use this file except in compliance with the
663.16 - * License. You can obtain a copy of the License at
663.17 - * http://www.netbeans.org/cddl-gplv2.html
663.18 - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
663.19 - * specific language governing permissions and limitations under the
663.20 - * License. When distributing the software, include this License Header
663.21 - * Notice in each file and include the License file at
663.22 - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
663.23 - * particular file as subject to the "Classpath" exception as provided
663.24 - * by Oracle in the GPL Version 2 section of the License file that
663.25 - * accompanied this code. If applicable, add the following below the
663.26 - * License Header, with the fields enclosed by brackets [] replaced by
663.27 - * your own identifying information:
663.28 - * "Portions Copyrighted [year] [name of copyright owner]"
663.29 - *
663.30 - * If you wish your version of this file to be governed by only the CDDL
663.31 - * or only the GPL Version 2, indicate your decision by adding
663.32 - * "[Contributor] elects to include this software in this distribution
663.33 - * under the [CDDL or GPL Version 2] license." If you do not indicate a
663.34 - * single choice of license, a recipient has the option to distribute
663.35 - * your version of this file under either the CDDL, the GPL Version 2 or
663.36 - * to extend the choice of license to its licensees as provided above.
663.37 - * However, if you add GPL Version 2 code and therefore, elected the GPL
663.38 - * Version 2 license, then the option applies only if the new code is
663.39 - * made subject to such option by the copyright holder.
663.40 - *
663.41 - * Contributor(s):
663.42 - *
663.43 - * Portions Copyrighted 2008 Sun Microsystems, Inc.
663.44 - */
663.45 -package org.netbeans.modules.python.testrunner.ui;
663.46 -
663.47 -import java.util.regex.Matcher;
663.48 -import junit.framework.TestCase;
663.49 -import org.netbeans.modules.gsf.testrunner.api.Trouble.ComparisonFailure;
663.50 -
663.51 -/**
663.52 - * Unit test for the PyUnitHandler - adapted from the Test::Unit testcases by
663.53 - * Erno.
663.54 - *
663.55 - * @author Erno Mononen
663.56 - * @author Tor Norbye
663.57 - */
663.58 -public class PyUnitRecognizerTest extends TestCase {
663.59 - public void testTestStarted() {
663.60 - TestRecognizerHandler handler = new PyUnitHandlerFactory.TestStartedHandler();
663.61 - String output = "%TEST_STARTED% test_foo (TestFooBar)";
663.62 - Matcher matcher = handler.match(output);
663.63 - assertTrue(matcher.matches());
663.64 - assertEquals(2, matcher.groupCount());
663.65 - assertEquals("test_foo", matcher.group(1));
663.66 - assertEquals("TestFooBar", matcher.group(2));
663.67 -
663.68 - output = "%TEST_STARTED% test_foo (Foo::Bar::TestFooBar)";
663.69 - matcher = handler.match(output);
663.70 - assertTrue(matcher.matches());
663.71 - assertEquals(2, matcher.groupCount());
663.72 - assertEquals("test_foo", matcher.group(1));
663.73 - assertEquals("Foo::Bar::TestFooBar", matcher.group(2));
663.74 - }
663.75 -
663.76 - public void testTestFinished() {
663.77 - TestRecognizerHandler handler = new PyUnitHandlerFactory.TestFinishedHandler();
663.78 - String output = "%TEST_FINISHED% time=0.008765 test_foo (TestFooBar)";
663.79 - Matcher matcher = handler.match(output);
663.80 - assertTrue(matcher.matches());
663.81 - assertEquals(3, matcher.groupCount());
663.82 - assertEquals("0.008765", matcher.group(1));
663.83 - assertEquals("test_foo", matcher.group(2));
663.84 - assertEquals("TestFooBar", matcher.group(3));
663.85 -
663.86 - output = "%TEST_FINISHED% time=0.008765 test_foo (FooModule::TestFooBar)";
663.87 - matcher = handler.match(output);
663.88 - assertTrue(matcher.matches());
663.89 - assertEquals(3, matcher.groupCount());
663.90 - assertEquals("0.008765", matcher.group(1));
663.91 - assertEquals("test_foo", matcher.group(2));
663.92 - assertEquals("FooModule::TestFooBar", matcher.group(3));
663.93 - }
663.94 -
663.95 - public void testTestFinished2() {
663.96 - TestRecognizerHandler handler = new PyUnitHandlerFactory.TestFinishedHandler();
663.97 - String output = "%TEST_FINISHED% time=8.4e-05 test_foo (TestFooBar)";
663.98 - Matcher matcher = handler.match(output);
663.99 - assertTrue(matcher.matches());
663.100 - assertEquals(3, matcher.groupCount());
663.101 - assertEquals("8.4e-05", matcher.group(1));
663.102 - assertEquals("test_foo", matcher.group(2));
663.103 - assertEquals("TestFooBar", matcher.group(3));
663.104 - }
663.105 -
663.106 - public void testTestFailed() {
663.107 - TestRecognizerHandler handler = new PyUnitHandlerFactory.TestFailedHandler();
663.108 - String output = "%TEST_FAILED% time=0.007233 testname=test_positive_price (ProductTest) message=<false> is not true. location=./test/unit/product_test.rb:69:in `test_positive_price'";
663.109 - Matcher matcher = handler.match(output);
663.110 - assertTrue(matcher.matches());
663.111 -
663.112 - assertEquals(5, matcher.groupCount());
663.113 - assertEquals("0.007233", matcher.group(1));
663.114 - assertEquals("test_positive_price", matcher.group(2));
663.115 - assertEquals("ProductTest", matcher.group(3));
663.116 - assertEquals("<false> is not true.", matcher.group(4));
663.117 - assertEquals("./test/unit/product_test.rb:69:in `test_positive_price'", matcher.group(5));
663.118 -
663.119 - String outputScientificNotation = "%TEST_FAILED% time=9.8e-07 testname=test_positive_price (ProductTest) message=<false> is not true. location=./test/unit/product_test.rb:69:in `test_positive_price'";
663.120 - matcher = handler.match(outputScientificNotation);
663.121 - assertTrue(matcher.matches());
663.122 - assertEquals("9.8e-07", matcher.group(1));
663.123 -
663.124 - // nested class name
663.125 - String outputNestedClass = "%TEST_FAILED% time=0.0060 testname=test_foo (TestSomething::TestNotExecuted) message=this test is not executed. location=/a/path/to/somewhere/test/test_something.rb:21:in `test_foo'";
663.126 - matcher = handler.match(outputNestedClass);
663.127 - assertTrue(matcher.matches());
663.128 -
663.129 - assertEquals(5, matcher.groupCount());
663.130 - assertEquals("0.0060", matcher.group(1));
663.131 - assertEquals("test_foo", matcher.group(2));
663.132 - assertEquals("TestSomething::TestNotExecuted", matcher.group(3));
663.133 - assertEquals("this test is not executed.", matcher.group(4));
663.134 - assertEquals("/a/path/to/somewhere/test/test_something.rb:21:in `test_foo'", matcher.group(5));
663.135 - }
663.136 -
663.137 -
663.138 - /*
663.139 - FAen ta meg!
663.140 - %SUITE_STARTING% Other_TestCase
663.141 - Joda!
663.142 - %TEST_STARTED% test_probably_errs (other_test.Other_TestCase)
663.143 - %TEST_ERROR% time=0.000024 testname=test_probably_errs (other_test.Other_TestCase) message=integer division or modulo by zero location=run() in /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/unittest.py:267%BR%test_probably_errs() in /Users/tor/NetBeansProjects/NewPythonProject44/src/other_test.py:27%BR%
663.144 - %TEST_STARTED% test_probably_fails (other_test.Other_TestCase)
663.145 - %TEST_FAILED% time=0.000028 testname=test_probably_fails (other_test.Other_TestCase) message=TODO: Write test location=run() in /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/unittest.py:263%BR%test_probably_fails() in /Users/tor/NetBeansProjects/NewPythonProject44/src/other_test.py:24%BR%fail() in /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/unittest.py:301%BR%
663.146 - %TEST_STARTED% test_should_succeed (other_test.Other_TestCase)
663.147 - %TEST_FINISHED% time=0.000013 test_should_succeed (other_test.Other_TestCase)
663.148 - %SUITE_FAILURES% 1
663.149 - %SUITE_ERRORS% 1
663.150 - %SUITE_FINISHED% time=0.0005
663.151 -
663.152 -
663.153 - */
663.154 - public void testTestError() {
663.155 - PyUnitHandlerFactory.TestErrorHandler handler = new PyUnitHandlerFactory.TestErrorHandler();
663.156 -
663.157 -
663.158 - String output = "%TEST_ERROR% time=0.000024 testname=test_probably_errs (other_test.Other_TestCase) message=integer division or modulo by zero location=run() in /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/unittest.py:267%BR%test_probably_errs() in /Users/tor/NetBeansProjects/NewPythonProject44/src/other_test.py:27%BR%";
663.159 -
663.160 - Matcher matcher = handler.match(output);
663.161 - assertTrue(matcher.matches());
663.162 -
663.163 - assertEquals(5, matcher.groupCount());
663.164 - assertEquals("0.000024", matcher.group(1));
663.165 - assertEquals("test_probably_errs", matcher.group(2));
663.166 - assertEquals("other_test.Other_TestCase", matcher.group(3));
663.167 - assertEquals("integer division or modulo by zero", matcher.group(4));
663.168 -
663.169 - String[] stackTrace = PyUnitHandlerFactory.getStackTrace(matcher.group(4), matcher.group(5));
663.170 - assertEquals(3, stackTrace.length);
663.171 - assertEquals("integer division or modulo by zero", stackTrace[0]);
663.172 - assertEquals("test_probably_errs() in /Users/tor/NetBeansProjects/NewPythonProject44/src/other_test.py:27", stackTrace[2]);
663.173 - assertEquals("run() in /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/unittest.py:267", stackTrace[1]);
663.174 - }
663.175 -
663.176 - public void testSuiteFinished() {
663.177 - TestRecognizerHandler handler = new PyUnitHandlerFactory.SuiteFinishedHandler();
663.178 - String output = "%SUITE_FINISHED% time=0.124";
663.179 - Matcher matcher = handler.match(output);
663.180 - assertTrue(matcher.matches());
663.181 -
663.182 - assertEquals(1, matcher.groupCount());
663.183 - assertEquals("0.124", matcher.group(1));
663.184 - }
663.185 -
663.186 - public void testSuiteFinished2() {
663.187 - TestRecognizerHandler handler = new PyUnitHandlerFactory.SuiteFinishedHandler();
663.188 - String output = "%SUITE_FINISHED% time=8.4e-05";
663.189 - Matcher matcher = handler.match(output);
663.190 - assertTrue(matcher.matches());
663.191 -
663.192 - assertEquals(1, matcher.groupCount());
663.193 - assertEquals("8.4e-05", matcher.group(1));
663.194 - }
663.195 -
663.196 - public void testSuiteStarted() {
663.197 - TestRecognizerHandler handler = new PyUnitHandlerFactory.SuiteStartedHandler();
663.198 - String output = "%SUITE_STARTED% 0 tests, 0 assertions, 0 failures, 0 errors";
663.199 - Matcher matcher = handler.match(output);
663.200 - assertTrue(matcher.matches());
663.201 - }
663.202 -
663.203 - public void testSuiteStarting() throws InterruptedException {
663.204 - TestRecognizerHandler handler = new PyUnitHandlerFactory.SuiteStartingHandler();
663.205 - String output = "%SUITE_STARTING% TestMe";
663.206 - Matcher matcher = handler.match(output);
663.207 - assertTrue(matcher.matches());
663.208 - assertEquals(1, matcher.groupCount());
663.209 - assertEquals("TestMe", matcher.group(1));
663.210 -
663.211 - output = "%SUITE_STARTING% MyModule::TestMe";
663.212 - matcher = handler.match(output);
663.213 - assertTrue(matcher.matches());
663.214 - assertEquals(1, matcher.groupCount());
663.215 - assertEquals("MyModule::TestMe", matcher.group(1));
663.216 - }
663.217 -
663.218 - public void testSuiteErrorOutput() throws InterruptedException {
663.219 - TestRecognizerHandler handler = new PyUnitHandlerFactory.SuiteErrorOutputHandler();
663.220 - String output = "%SUITE_ERROR_OUTPUT% error=undefined method `size' for UserHelperTest:Class";
663.221 - Matcher matcher = handler.match(output);
663.222 - assertTrue(matcher.matches());
663.223 - assertEquals(1, matcher.groupCount());
663.224 - assertEquals("undefined method `size' for UserHelperTest:Class", matcher.group(1));
663.225 - }
663.226 -
663.227 - public void testTestLogger() throws InterruptedException {
663.228 - TestRecognizerHandler handler = new PyUnitHandlerFactory.TestLoggerHandler();
663.229 - String output = "%TEST_LOGGER% level=FINE msg=Loading 3 files took 12.345";
663.230 - Matcher matcher = handler.match(output);
663.231 - assertTrue(matcher.matches());
663.232 - assertEquals(2, matcher.groupCount());
663.233 - assertEquals("FINE", matcher.group(1));
663.234 - assertEquals("Loading 3 files took 12.345", matcher.group(2));
663.235 - }
663.236 -
663.237 - public void testIssue143508TestStarted() {
663.238 - TestRecognizerHandler handler = new PyUnitHandlerFactory.TestStartedHandler();
663.239 - String output = "%TEST_STARTED% test_foo (FooTest)\\n";
663.240 - Matcher matcher = handler.match(output);
663.241 - assertTrue(matcher.matches());
663.242 - assertEquals(2, matcher.groupCount());
663.243 - assertEquals("test_foo", matcher.group(1));
663.244 - assertEquals("FooTest", matcher.group(2));
663.245 - }
663.246 -
663.247 - public void testIssue143508TestFinished() {
663.248 - TestRecognizerHandler handler = new PyUnitHandlerFactory.TestFinishedHandler();
663.249 - String output = "%TEST_FINISHED% time=0.203 test_foo (FooTest)\\n";
663.250 - Matcher matcher = handler.match(output);
663.251 - assertTrue(matcher.matches());
663.252 - assertEquals(3, matcher.groupCount());
663.253 - assertEquals("0.203", matcher.group(1));
663.254 - assertEquals("test_foo", matcher.group(2));
663.255 - assertEquals("FooTest", matcher.group(3));
663.256 - }
663.257 -
663.258 - public void testExtractDiff1() {
663.259 - ComparisonFailure failure = PyUnitHandlerFactory.getComparisonFailure("'foo\nbar\nbaz' != 'foo\nbr\nbazz'");
663.260 - assertNotNull(failure);
663.261 - assertEquals("'foo\nbar\nbaz'", failure.getExpected());
663.262 - assertEquals("'foo\nbr\nbazz'", failure.getActual());
663.263 - }
663.264 -
663.265 - public void testExtractDiff2() {
663.266 - ComparisonFailure failure = PyUnitHandlerFactory.getComparisonFailure("Expected 265252859812191058636308480000000L but got 132626429906095529318154240000000L");
663.267 - assertNotNull(failure);
663.268 - assertEquals("265252859812191058636308480000000L", failure.getExpected());
663.269 - assertEquals("132626429906095529318154240000000L", failure.getActual());
663.270 - }
663.271 -}